1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.nuiton.jrst;
23
24 import org.apache.commons.logging.Log;
25 import org.apache.commons.logging.LogFactory;
26 import org.codehaus.plexus.component.annotations.Component;
27 import org.dom4j.Document;
28 import org.dom4j.DocumentException;
29 import org.dom4j.DocumentHelper;
30 import org.nuiton.jrst.legacy.JRSTReader;
31 import org.python.util.PythonInterpreter;
32
33 import java.io.ByteArrayOutputStream;
34 import java.io.File;
35 import java.net.URL;
36
37
38
39
40
41
42
43 @Component(role = JRSTToXmlStrategy.class, hint = "docutils",
44 description = "Transform a RST model (using jython + docutils), " +
45 "to a xml format.")
46
47 public class JRSTToXmlStrategyDocutils implements JRSTToXmlStrategy {
48
49 private static final String DOCUTILS_LAUNCHER = "__run__.py";
50
51 private static final String IMPORT_SCRIPT = "import __run__";
52
53 private static final String WINDOWS_NAME = "win";
54
55 private static final String OS_NAME = "os.name";
56
57 private static final String BANG = "!";
58
59 private static final String FILE_URI_PREFIX = "file:";
60
61
62 private static final Log log =
63 LogFactory.getLog(JRSTToXmlStrategyDocutils.class);
64
65 @Override
66 public Document generateRstToXml(File in, String encoding) throws Exception {
67 ByteArrayOutputStream out = null;
68
69 try {
70
71 out = new ByteArrayOutputStream();
72
73
74
75
76
77
78 URL resource = JRST.class.getResource("/" + DOCUTILS_LAUNCHER);
79 String docutilsPath = resource.getPath()
80 .replaceAll(DOCUTILS_LAUNCHER, "");
81
82 docutilsPath = docutilsPath.replaceAll(BANG, "");
83 docutilsPath = docutilsPath.replaceAll(FILE_URI_PREFIX, "");
84
85
86 PythonInterpreter interp = new PythonInterpreter();
87 String commandImport = IMPORT_SCRIPT;
88 interp.exec(commandImport);
89
90
91 String filePath = in.getAbsolutePath();
92 String property = System.getProperty(OS_NAME).toLowerCase();
93 if (property.contains(WINDOWS_NAME)) {
94 filePath = filePath.replaceAll("\\\\", "\\\\\\\\");
95 }
96
97
98 interp.setOut(out);
99
100
101 String commandExec = String.format("__run__.exec_docutils('%s', '%s', '%s')",
102 docutilsPath, JRST.TYPE_XML, filePath);
103 interp.exec(commandExec);
104
105
106 interp.cleanup();
107
108
109 String xmlString = new String(out.toByteArray(), encoding);
110
111 Document doc = null;
112 try {
113 doc = DocumentHelper.parseText(xmlString);
114 } catch (DocumentException e) {
115 log.error("Error during the creation of the document", e);
116 }
117 out.close();
118
119 return doc;
120 } finally {
121 if (out != null) {
122 out.close();
123 }
124 }
125 }
126 }