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.

Fop.java 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. /*
  2. * $Id$
  3. * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
  4. * For details on use and redistribution please refer to the
  5. * LICENSE file included with these sources.
  6. */
  7. package org.apache.fop.tools.anttasks;
  8. // Ant
  9. import org.apache.tools.ant.*;
  10. import org.apache.tools.ant.types.FileSet;
  11. // SAX
  12. import org.xml.sax.XMLReader;
  13. import org.xml.sax.InputSource;
  14. import org.xml.sax.SAXException;
  15. import org.xml.sax.SAXParseException;
  16. // Java
  17. import java.io.*;
  18. import java.util.*;
  19. // FOP
  20. import org.apache.fop.apps.Starter;
  21. import org.apache.fop.apps.InputHandler;
  22. import org.apache.fop.apps.FOInputHandler;
  23. import org.apache.fop.apps.Driver;
  24. import org.apache.fop.apps.FOPException;
  25. import org.apache.fop.fo.FOUserAgent;
  26. // Avalon
  27. import org.apache.avalon.framework.logger.ConsoleLogger;
  28. import org.apache.avalon.framework.logger.Logger;
  29. /**
  30. * Wrapper for Fop which allows it to be accessed from within an Ant task.
  31. * Accepts the inputs:
  32. * <ul>
  33. * <li>fofile -> formatting objects file to be transformed</li>
  34. * <li>format -> MIME type of the format to generate ex. "application/pdf"</li>
  35. * <li>outfile -> output filename</li>
  36. * <li>baseDir -> directory to work from</li>
  37. * <li>userconfig -> file with user configuration (same as the "-c" command line option)</li>
  38. * <li>messagelevel -> (info | verbose | debug) level to output non-error messages</li>
  39. * </ul>
  40. */
  41. public class Fop extends Task {
  42. File foFile;
  43. ArrayList filesets = new ArrayList();
  44. File outFile;
  45. File outDir;
  46. String format; //MIME type
  47. File baseDir;
  48. File userConfig;
  49. int messageType = Project.MSG_VERBOSE;
  50. /**
  51. * Sets the input file
  52. * @param File to input from
  53. */
  54. public void setUserconfig (File userConfig) {
  55. this.userConfig = userConfig;
  56. }
  57. /**
  58. * Sets the input file
  59. * @param File to input from
  60. */
  61. public void setFofile(File foFile) {
  62. this.foFile = foFile;
  63. }
  64. /**
  65. * Gets the input file
  66. */
  67. public File getFofile() {
  68. return foFile;
  69. }
  70. /**
  71. * Adds a set of fo files (nested fileset attribute).
  72. */
  73. public void addFileset(FileSet set) {
  74. filesets.add(set);
  75. }
  76. /**
  77. * Sets the output file
  78. * @param File to output to
  79. */
  80. public void setOutfile(File outFile) {
  81. this.outFile = outFile;
  82. }
  83. /**
  84. * Gets the output file
  85. */
  86. public File getOutfile() {
  87. return this.outFile;
  88. }
  89. /**
  90. * Sets the output directory
  91. * @param Directory to output to
  92. */
  93. public void setOutdir(File outDir) {
  94. this.outDir = outDir;
  95. }
  96. /**
  97. * Gets the output directory
  98. */
  99. public File getOutdir() {
  100. return this.outDir;
  101. }
  102. /**
  103. * Sets output format (MIME type)
  104. */
  105. public void setFormat(String format) {
  106. this.format = format;
  107. }
  108. /**
  109. * Gets the output format (MIME type)
  110. */
  111. public String getFormat() {
  112. return this.format;
  113. }
  114. /**
  115. * Sets the message level to be used while processing.
  116. * @param String (info | verbose | debug)
  117. */
  118. public void setMessagelevel(String messageLevel) {
  119. if (messageLevel.equalsIgnoreCase("info")) {
  120. messageType = Project.MSG_INFO;
  121. } else if (messageLevel.equalsIgnoreCase("verbose")) {
  122. messageType = Project.MSG_VERBOSE;
  123. } else if (messageLevel.equalsIgnoreCase("debug")) {
  124. messageType = Project.MSG_DEBUG;
  125. } else {
  126. log("messagelevel set to unknown value \"" + messageLevel +
  127. "\"", Project.MSG_ERR);
  128. throw new BuildException("unknown messagelevel");
  129. }
  130. }
  131. /**
  132. * Returns the message type corresponding to Property.MSG_(INFO | VERBOSE | DEBUG)
  133. * representing the current message level.
  134. */
  135. public int getMessageType() {
  136. return messageType;
  137. }
  138. /**
  139. * Sets the base directory; currently ignored
  140. * @param File to use as a working directory
  141. */
  142. public void setBasedir(File baseDir) {
  143. this.baseDir = baseDir;
  144. }
  145. /**
  146. * Gets the base directory
  147. */
  148. public File getBasedir() {
  149. return (baseDir != null) ? baseDir : project.resolveFile(".");
  150. }
  151. /**
  152. * Starts execution of this task
  153. */
  154. public void execute() throws BuildException {
  155. try {
  156. Starter starter = new FOPTaskStarter(this);
  157. starter.enableLogging(new ConsoleLogger(ConsoleLogger.LEVEL_INFO));
  158. starter.run();
  159. } catch (FOPException ex) {
  160. throw new BuildException(ex);
  161. }
  162. }
  163. }
  164. class FOPTaskStarter extends Starter {
  165. Fop task;
  166. String baseURL = null;
  167. FOPTaskStarter(Fop task) throws FOPException {
  168. this.task = task;
  169. }
  170. private int determineRenderer(String format) {
  171. if ((format == null) ||
  172. format.equalsIgnoreCase("application/pdf") ||
  173. format.equalsIgnoreCase("pdf")) {
  174. return Driver.RENDER_PDF;
  175. } else if (format.equalsIgnoreCase("application/postscript") ||
  176. format.equalsIgnoreCase("ps")) {
  177. return Driver.RENDER_PS;
  178. } else if (format.equalsIgnoreCase("application/vnd.mif") ||
  179. format.equalsIgnoreCase("mif")) {
  180. return Driver.RENDER_MIF;
  181. } else if (format.equalsIgnoreCase("application/vnd.hp-PCL") ||
  182. format.equalsIgnoreCase("pcl")) {
  183. return Driver.RENDER_PCL;
  184. } else if (format.equalsIgnoreCase("text/plain") ||
  185. format.equalsIgnoreCase("txt")) {
  186. return Driver.RENDER_TXT;
  187. } else if (format.equalsIgnoreCase("text/xml") ||
  188. format.equalsIgnoreCase("at") ||
  189. format.equalsIgnoreCase("xml")) {
  190. return Driver.RENDER_XML;
  191. } else {
  192. String err = "Couldn't determine renderer to use: "+format;
  193. getLogger().error(err);
  194. throw new BuildException(err);
  195. }
  196. }
  197. private String determineExtension(int renderer) {
  198. switch (renderer) {
  199. case Driver.RENDER_PDF:
  200. return ".pdf";
  201. case Driver.RENDER_PS:
  202. return ".ps";
  203. case Driver.RENDER_MIF:
  204. return ".mif";
  205. case Driver.RENDER_PCL:
  206. return ".pcl";
  207. case Driver.RENDER_TXT:
  208. return ".txt";
  209. case Driver.RENDER_XML:
  210. return ".xml";
  211. default:
  212. String err = "Unknown renderer: "+renderer;
  213. getLogger().error(err);
  214. throw new BuildException(err);
  215. }
  216. }
  217. private File replaceExtension(File file, String expectedExt,
  218. String newExt) {
  219. String name = file.getName();
  220. if (name.toLowerCase().endsWith(expectedExt)) {
  221. name = name.substring(0, name.length() - expectedExt.length());
  222. }
  223. name = name.concat(newExt);
  224. return new File(file.getParentFile(), name);
  225. }
  226. public void run() throws FOPException {
  227. if (task.userConfig != null) {
  228. }
  229. try {
  230. if (task.getFofile() != null) {
  231. baseURL = task.getFofile().getParentFile().toURL().
  232. toExternalForm();
  233. }
  234. } catch (Exception e) {
  235. getLogger().error("Error setting base directory", e);
  236. }
  237. task.log("Using base URL: " + baseURL, Project.MSG_DEBUG);
  238. int rint = determineRenderer(task.getFormat());
  239. String newExtension = determineExtension(rint);
  240. int actioncount = 0;
  241. // deal with single source file
  242. if (task.getFofile() != null) {
  243. if (task.getFofile().exists()) {
  244. File outf = task.getOutfile();
  245. if (outf == null) {
  246. throw new BuildException("outfile is required when fofile is used");
  247. }
  248. if (task.getOutdir() != null) {
  249. outf = new File(task.getOutdir(), outf.getName());
  250. }
  251. render(task.getFofile(), outf, rint);
  252. actioncount++;
  253. }
  254. }
  255. // deal with the filesets
  256. for (int i = 0; i < task.filesets.size(); i++) {
  257. FileSet fs = (FileSet) task.filesets.get(i);
  258. DirectoryScanner ds = fs.getDirectoryScanner(task.getProject());
  259. String[] files = ds.getIncludedFiles();
  260. for (int j = 0; j < files.length; j++) {
  261. File f = new File(fs.getDir(task.getProject()), files[j]);
  262. File outf = replaceExtension(f, ".fo", newExtension);
  263. if (task.getOutdir() != null) {
  264. outf = new File(task.getOutdir(), outf.getName());
  265. }
  266. try {
  267. baseURL = fs.getDir(task.getProject()).toURL().
  268. toExternalForm();
  269. } catch (Exception e) {
  270. task.log("Error setting base URL",
  271. Project.MSG_DEBUG);
  272. }
  273. render(f, outf, rint);
  274. actioncount++;
  275. }
  276. }
  277. if (actioncount == 0) {
  278. task.log(
  279. "No files processed. No files were selected by the filesets and no fofile was set." ,
  280. Project.MSG_WARN);
  281. }
  282. }
  283. private void render(File foFile, File outFile,
  284. int renderer) throws FOPException {
  285. InputHandler inputHandler = new FOInputHandler(foFile);
  286. XMLReader parser = inputHandler.getParser();
  287. setParserFeatures(parser);
  288. FileOutputStream out = null;
  289. try {
  290. out = new FileOutputStream(outFile);
  291. } catch (Exception ex) {
  292. getLogger().error("Failed to open " + outFile);
  293. throw new BuildException(ex);
  294. }
  295. task.log(foFile + " -> " + outFile, Project.MSG_INFO);
  296. try {
  297. Driver driver = new Driver();
  298. setupLogger(driver);
  299. driver.initialize();
  300. FOUserAgent userAgent = new FOUserAgent();
  301. userAgent.setBaseURL(baseURL);
  302. userAgent.enableLogging(getLogger());
  303. driver.setUserAgent(userAgent);
  304. driver.setRenderer(renderer);
  305. driver.setOutputStream(out);
  306. driver.render(parser, inputHandler.getInputSource());
  307. out.close();
  308. } catch (Exception ex) {
  309. getLogger().error("Couldn't render file: " + ex.getMessage());
  310. throw new BuildException(ex);
  311. }
  312. }
  313. }