You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

EventProducerCollectorTask.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /* $Id$ */
  18. package org.apache.fop.tools;
  19. import java.io.File;
  20. import java.io.FileNotFoundException;
  21. import java.io.IOException;
  22. import java.io.OutputStream;
  23. import java.util.Iterator;
  24. import java.util.List;
  25. import javax.xml.transform.Result;
  26. import javax.xml.transform.Source;
  27. import javax.xml.transform.Transformer;
  28. import javax.xml.transform.TransformerException;
  29. import javax.xml.transform.URIResolver;
  30. import javax.xml.transform.dom.DOMResult;
  31. import javax.xml.transform.dom.DOMSource;
  32. import javax.xml.transform.sax.SAXTransformerFactory;
  33. import javax.xml.transform.stream.StreamResult;
  34. import javax.xml.transform.stream.StreamSource;
  35. import org.w3c.dom.Node;
  36. import org.apache.commons.io.IOUtils;
  37. import org.apache.tools.ant.BuildException;
  38. import org.apache.tools.ant.DirectoryScanner;
  39. import org.apache.tools.ant.Project;
  40. import org.apache.tools.ant.Task;
  41. import org.apache.tools.ant.types.FileSet;
  42. import org.apache.tools.ant.types.selectors.FilenameSelector;
  43. import org.apache.fop.events.model.EventModel;
  44. import org.apache.fop.events.model.EventProducerModel;
  45. /**
  46. * Ant task which inspects a file set for Java interfaces which extend the
  47. * {@link org.apache.fop.events.EventProducer} interface. For all such interfaces an event model
  48. * file and a translation file for the human-readable messages generated by the events is
  49. * created and/or updated.
  50. */
  51. public class EventProducerCollectorTask extends Task {
  52. private List filesets = new java.util.ArrayList();
  53. private File destDir;
  54. private File translationFile;
  55. /** {@inheritDoc} */
  56. public void execute() throws BuildException {
  57. try {
  58. EventProducerCollector collector = new EventProducerCollector();
  59. long lastModified = processFileSets(collector);
  60. for (Iterator iter = collector.getModels().iterator(); iter.hasNext();) {
  61. EventModel model = (EventModel) iter.next();
  62. File parentDir = getParentDir(model);
  63. if (!parentDir.exists() && !parentDir.mkdirs()) {
  64. throw new BuildException(
  65. "Could not create target directory for event model file: " + parentDir);
  66. }
  67. File modelFile = new File(parentDir, "event-model.xml");
  68. if (!modelFile.exists() || lastModified > modelFile.lastModified()) {
  69. model.saveToXML(modelFile);
  70. log("Event model written to " + modelFile);
  71. }
  72. if (getTranslationFile() != null) {
  73. if (!getTranslationFile().exists()
  74. || lastModified > getTranslationFile().lastModified()) {
  75. updateTranslationFile(modelFile);
  76. }
  77. }
  78. }
  79. } catch (ClassNotFoundException e) {
  80. throw new BuildException(e);
  81. } catch (EventConventionException ece) {
  82. throw new BuildException(ece);
  83. } catch (IOException ioe) {
  84. throw new BuildException(ioe);
  85. }
  86. }
  87. private static final String MODEL2TRANSLATION = "model2translation.xsl";
  88. private static final String MERGETRANSLATION = "merge-translation.xsl";
  89. private File getParentDir(EventModel model) {
  90. Iterator iter = model.getProducers();
  91. assert iter.hasNext();
  92. EventProducerModel producer = (EventProducerModel) iter.next();
  93. assert !iter.hasNext();
  94. String interfaceName = producer.getInterfaceName();
  95. int startLocalName = interfaceName.lastIndexOf(".");
  96. if (startLocalName < 0) {
  97. return destDir;
  98. } else {
  99. String dirname = interfaceName.substring(0, startLocalName);
  100. dirname = dirname.replace('.', File.separatorChar);
  101. return new File(destDir, dirname);
  102. }
  103. }
  104. /**
  105. * Updates the translation file with new entries for newly found event producer methods.
  106. * @throws IOException if an I/O error occurs
  107. */
  108. protected void updateTranslationFile(File modelFile) throws IOException {
  109. try {
  110. boolean resultExists = getTranslationFile().exists();
  111. SAXTransformerFactory tFactory
  112. = (SAXTransformerFactory)SAXTransformerFactory.newInstance();
  113. //Generate fresh generated translation file as template
  114. Source src = new StreamSource(modelFile.toURI().toURL().toExternalForm());
  115. StreamSource xslt1 = new StreamSource(
  116. getClass().getResourceAsStream(MODEL2TRANSLATION));
  117. if (xslt1.getInputStream() == null) {
  118. throw new FileNotFoundException(MODEL2TRANSLATION + " not found");
  119. }
  120. DOMResult domres = new DOMResult();
  121. Transformer transformer = tFactory.newTransformer(xslt1);
  122. transformer.transform(src, domres);
  123. final Node generated = domres.getNode();
  124. Node sourceDocument;
  125. if (resultExists) {
  126. //Load existing translation file into memory (because we overwrite it later)
  127. src = new StreamSource(getTranslationFile().toURI().toURL().toExternalForm());
  128. domres = new DOMResult();
  129. transformer = tFactory.newTransformer();
  130. transformer.transform(src, domres);
  131. sourceDocument = domres.getNode();
  132. } else {
  133. //Simply use generated as source document
  134. sourceDocument = generated;
  135. }
  136. //Generate translation file (with potentially new translations)
  137. src = new DOMSource(sourceDocument);
  138. //The following triggers a bug in older Xalan versions
  139. //Result res = new StreamResult(getTranslationFile());
  140. OutputStream out = new java.io.FileOutputStream(getTranslationFile());
  141. out = new java.io.BufferedOutputStream(out);
  142. Result res = new StreamResult(out);
  143. try {
  144. StreamSource xslt2 = new StreamSource(
  145. getClass().getResourceAsStream(MERGETRANSLATION));
  146. if (xslt2.getInputStream() == null) {
  147. throw new FileNotFoundException(MERGETRANSLATION + " not found");
  148. }
  149. transformer = tFactory.newTransformer(xslt2);
  150. transformer.setURIResolver(new URIResolver() {
  151. public Source resolve(String href, String base) throws TransformerException {
  152. if ("my:dom".equals(href)) {
  153. return new DOMSource(generated);
  154. }
  155. return null;
  156. }
  157. });
  158. if (resultExists) {
  159. transformer.setParameter("generated-url", "my:dom");
  160. }
  161. transformer.transform(src, res);
  162. if (resultExists) {
  163. log("Translation file updated: " + getTranslationFile());
  164. } else {
  165. log("Translation file generated: " + getTranslationFile());
  166. }
  167. } finally {
  168. IOUtils.closeQuietly(out);
  169. }
  170. } catch (TransformerException te) {
  171. throw new IOException(te.getMessage());
  172. }
  173. }
  174. /**
  175. * Processes the file sets defined for the task.
  176. * @param collector the collector to use for collecting the event producers
  177. * @return the time of the latest modification of any of the files inspected
  178. * @throws IOException if an I/O error occurs
  179. * @throws EventConventionException if the EventProducer conventions are violated
  180. * @throws ClassNotFoundException if a required class cannot be found
  181. */
  182. protected long processFileSets(EventProducerCollector collector)
  183. throws IOException, EventConventionException, ClassNotFoundException {
  184. long lastModified = 0;
  185. Iterator iter = filesets.iterator();
  186. while (iter.hasNext()) {
  187. FileSet fs = (FileSet)iter.next();
  188. DirectoryScanner ds = fs.getDirectoryScanner(getProject());
  189. String[] srcFiles = ds.getIncludedFiles();
  190. File directory = fs.getDir(getProject());
  191. for (int i = 0, c = srcFiles.length; i < c; i++) {
  192. String filename = srcFiles[i];
  193. File src = new File(directory, filename);
  194. boolean eventProducerFound = collector.scanFile(src);
  195. if (eventProducerFound) {
  196. lastModified = Math.max(lastModified, src.lastModified());
  197. }
  198. }
  199. }
  200. return lastModified;
  201. }
  202. /**
  203. * Adds a file set.
  204. * @param set the file set
  205. */
  206. public void addFileset(FileSet set) {
  207. filesets.add(set);
  208. }
  209. /**
  210. * Sets the destination directory for the event models.
  211. *
  212. * @param destDir the destination directory
  213. */
  214. public void setDestDir(File destDir) {
  215. if (!destDir.isDirectory()) {
  216. throw new IllegalArgumentException("destDir must be a directory");
  217. }
  218. this.destDir = destDir;
  219. }
  220. /**
  221. * Sets the translation file for the event producer methods.
  222. * @param f the translation file
  223. */
  224. public void setTranslationFile(File f) {
  225. this.translationFile = f;
  226. }
  227. /**
  228. * Returns the translation file for the event producer methods.
  229. * @return the translation file
  230. */
  231. public File getTranslationFile() {
  232. return this.translationFile;
  233. }
  234. /**
  235. * Command-line interface for testing purposes.
  236. * @param args the command-line arguments
  237. */
  238. public static void main(String[] args) {
  239. try {
  240. Project project = new Project();
  241. EventProducerCollectorTask generator = new EventProducerCollectorTask();
  242. generator.setProject(project);
  243. project.setName("Test");
  244. FileSet fileset = new FileSet();
  245. fileset.setDir(new File("test/java"));
  246. FilenameSelector selector = new FilenameSelector();
  247. selector.setName("**/*.java");
  248. fileset.add(selector);
  249. generator.addFileset(fileset);
  250. File targetDir = new File("build/codegen1");
  251. targetDir.mkdirs();
  252. generator.setTranslationFile(new File("D:/out1.xml"));
  253. generator.execute();
  254. } catch (Exception e) {
  255. e.printStackTrace();
  256. }
  257. }
  258. }