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 java.io.File;
25 import java.io.FileWriter;
26 import java.io.IOException;
27 import java.io.Reader;
28 import java.io.StringReader;
29
30 import org.apache.maven.doxia.logging.Log;
31 import org.apache.maven.doxia.module.xdoc.XdocParser;
32 import org.apache.maven.doxia.parser.ParseException;
33 import org.apache.maven.doxia.sink.Sink;
34 import org.apache.maven.doxia.siterenderer.RenderingContext;
35 import org.apache.maven.project.MavenProject;
36 import org.codehaus.plexus.util.IOUtil;
37 import org.dom4j.Document;
38 import org.nuiton.util.FileUtil;
39
40
41
42
43
44
45
46 public abstract class AbstractJrstParser extends XdocParser {
47
48 public static final String JRST_PARSER_ID = "jrst";
49
50 public abstract JRSTToXmlStrategy getStrategy();
51
52 protected RenderingContext renderingContext;
53
54 protected MavenProject mavenProject;
55
56 protected boolean verbose;
57
58 @Override
59 public void parse(Reader source, Sink sink) throws ParseException {
60
61 try {
62
63 File sourceFile = prepareSourceFile(getLog(), source);
64
65
66
67 Document doc = getStrategy().generateRstToXml(sourceFile, JRST.UTF_8);
68
69
70 doc = JRST.generateXml(doc, JRST.TYPE_XDOC);
71
72
73 Reader reader = new StringReader(doc.asXML());
74 super.parse(reader, sink);
75 } catch (Exception e) {
76 throw new ParseException("Can't parse rst file", e);
77 } finally {
78
79 clear();
80 }
81 }
82
83 public void setRenderingContext(RenderingContext renderingContext) {
84 this.renderingContext = renderingContext;
85 }
86
87 public void setMavenProject(MavenProject mavenProject) {
88 this.mavenProject = mavenProject;
89 }
90
91 public void setVerbose(boolean verbose) {
92 this.verbose = verbose;
93 }
94
95 protected File prepareSourceFile(Log log, Reader source) throws IOException {
96
97 File sourceFile;
98
99 if (mavenProject == null) {
100 sourceFile = File.createTempFile("source", "rst");
101
102 } else {
103 File temporayDirectory = new File(
104 mavenProject.getBasedir(),
105 "target" + File.separator + "generated-jrst");
106
107 sourceFile = new File(temporayDirectory,
108 renderingContext.getInputName());
109
110 FileUtil.createDirectoryIfNecessary(sourceFile.getParentFile());
111 }
112
113 if (verbose) {
114 log.info("Transform rst file: " + sourceFile);
115 if (log.isDebugEnabled()) {
116 log.info("Copy " + renderingContext.getInputName() +
117 " to " + sourceFile);
118 }
119 }
120
121 FileWriter fileWriter = new FileWriter(sourceFile);
122 try {
123 IOUtil.copy(source, fileWriter);
124 } finally {
125 fileWriter.close();
126 }
127
128 return sourceFile;
129 }
130
131 public void clear() {
132 renderingContext = null;
133 mavenProject = null;
134 verbose = false;
135 }
136
137 }