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 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. /*
  2. * Copyright 1999-2005 The Apache Software Foundation.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. /* $Id$ */
  17. package org.apache.fop.tools.anttasks;
  18. // Ant
  19. import org.apache.tools.ant.BuildException;
  20. import org.apache.tools.ant.DirectoryScanner;
  21. import org.apache.tools.ant.Project;
  22. import org.apache.tools.ant.Task;
  23. import org.apache.tools.ant.types.FileSet;
  24. import org.apache.tools.ant.util.GlobPatternMapper;
  25. // Java
  26. import java.io.File;
  27. import java.io.IOException;
  28. import java.io.OutputStream;
  29. import java.net.MalformedURLException;
  30. import java.util.List;
  31. // FOP
  32. import org.apache.fop.apps.FOPException;
  33. import org.apache.fop.apps.FOUserAgent;
  34. import org.apache.fop.apps.MimeConstants;
  35. import org.apache.fop.cli.InputHandler;
  36. import org.apache.commons.logging.impl.SimpleLog;
  37. import org.apache.commons.logging.Log;
  38. /**
  39. * Wrapper for FOP which allows it to be accessed from within an Ant task.
  40. * Accepts the inputs:
  41. * <ul>
  42. * <li>fofile -> formatting objects file to be transformed</li>
  43. * <li>format -> MIME type of the format to generate ex. "application/pdf"</li>
  44. * <li>outfile -> output filename</li>
  45. * <li>baseDir -> directory to work from</li>
  46. * <li>relativebase -> (true | false) control whether to use each FO's
  47. * directory as base directory. false uses the baseDir parameter.</li>
  48. * <li>userconfig -> file with user configuration (same as the "-c" command
  49. * line option)</li>
  50. * <li>messagelevel -> (error | warn | info | verbose | debug) level to output
  51. * non-error messages</li>
  52. * <li>logFiles -> Controls whether the names of the files that are processed
  53. * are logged or not</li>
  54. * </ul>
  55. */
  56. public class Fop extends Task {
  57. private File foFile;
  58. private List filesets = new java.util.ArrayList();
  59. private File outFile;
  60. private File outDir;
  61. private String format; //MIME type
  62. private File baseDir;
  63. private File userConfig;
  64. private int messageType = Project.MSG_VERBOSE;
  65. private boolean logFiles = true;
  66. private boolean force = false;
  67. private boolean relativebase = false;
  68. /**
  69. * Sets the filename for the userconfig.xml.
  70. * @param userConfig Configuration to use
  71. */
  72. public void setUserconfig(File userConfig) {
  73. this.userConfig = userConfig;
  74. }
  75. /**
  76. * Returns the file for the userconfig.xml.
  77. * @return the userconfig.xml file
  78. */
  79. public File getUserconfig() {
  80. return this.userConfig;
  81. }
  82. /**
  83. * Sets the input XSL-FO file.
  84. * @param foFile input XSL-FO file
  85. */
  86. public void setFofile(File foFile) {
  87. this.foFile = foFile;
  88. }
  89. /**
  90. * Gets the input XSL-FO file.
  91. * @return input XSL-FO file
  92. */
  93. public File getFofile() {
  94. return foFile;
  95. }
  96. /**
  97. * Adds a set of XSL-FO files (nested fileset attribute).
  98. * @param set a fileset
  99. */
  100. public void addFileset(FileSet set) {
  101. filesets.add(set);
  102. }
  103. /**
  104. * Returns the current list of filesets.
  105. * @return the filesets
  106. */
  107. public List getFilesets() {
  108. return this.filesets;
  109. }
  110. /**
  111. * Set whether to include files (external-graphics, instream-foreign-object)
  112. * from a path relative to the .fo file (true) or the working directory (false, default)
  113. * only useful for filesets
  114. *
  115. * @param relbase true if paths are relative to file.
  116. */
  117. public void setRelativebase(boolean relbase) {
  118. this.relativebase = relbase;
  119. }
  120. /**
  121. * Gets the relative base attribute
  122. * @return the relative base attribute
  123. */
  124. public boolean getRelativebase() {
  125. return relativebase;
  126. }
  127. /**
  128. * Set whether to check dependencies, or to always generate;
  129. * optional, default is false.
  130. *
  131. * @param force true if always generate.
  132. */
  133. public void setForce(boolean force) {
  134. this.force = force;
  135. }
  136. /**
  137. * Gets the force attribute
  138. * @return the force attribute
  139. */
  140. public boolean getForce() {
  141. return force;
  142. }
  143. /**
  144. * Sets the output file.
  145. * @param outFile File to output to
  146. */
  147. public void setOutfile(File outFile) {
  148. this.outFile = outFile;
  149. }
  150. /**
  151. * Gets the output file.
  152. * @return the output file
  153. */
  154. public File getOutfile() {
  155. return this.outFile;
  156. }
  157. /**
  158. * Sets the output directory.
  159. * @param outDir Directory to output to
  160. */
  161. public void setOutdir(File outDir) {
  162. this.outDir = outDir;
  163. }
  164. /**
  165. * Gets the output directory.
  166. * @return the output directory
  167. */
  168. public File getOutdir() {
  169. return this.outDir;
  170. }
  171. /**
  172. * Sets output format (MIME type).
  173. * @param format the output format
  174. */
  175. public void setFormat(String format) {
  176. this.format = format;
  177. }
  178. /**
  179. * Gets the output format (MIME type).
  180. * @return the output format
  181. */
  182. public String getFormat() {
  183. return this.format;
  184. }
  185. /**
  186. * Sets the message level to be used while processing.
  187. * @param messageLevel (error | warn| info | verbose | debug)
  188. */
  189. public void setMessagelevel(String messageLevel) {
  190. if (messageLevel.equalsIgnoreCase("info")) {
  191. messageType = Project.MSG_INFO;
  192. } else if (messageLevel.equalsIgnoreCase("verbose")) {
  193. messageType = Project.MSG_VERBOSE;
  194. } else if (messageLevel.equalsIgnoreCase("debug")) {
  195. messageType = Project.MSG_DEBUG;
  196. } else if (messageLevel.equalsIgnoreCase("err")
  197. || messageLevel.equalsIgnoreCase("error")) {
  198. messageType = Project.MSG_ERR;
  199. } else if (messageLevel.equalsIgnoreCase("warn")) {
  200. messageType = Project.MSG_WARN;
  201. } else {
  202. log("messagelevel set to unknown value \"" + messageLevel
  203. + "\"", Project.MSG_ERR);
  204. throw new BuildException("unknown messagelevel");
  205. }
  206. }
  207. /**
  208. * Returns the message type corresponding to Project.MSG_*
  209. * representing the current message level.
  210. * @see org.apache.tools.ant.Project
  211. */
  212. public int getMessageType() {
  213. return messageType;
  214. }
  215. /**
  216. * Sets the base directory for single FO file (non-fileset) usage
  217. * @param baseDir File to use as a working directory
  218. */
  219. public void setBasedir(File baseDir) {
  220. this.baseDir = baseDir;
  221. }
  222. /**
  223. * Gets the base directory.
  224. * @return the base directory
  225. */
  226. public File getBasedir() {
  227. return (baseDir != null) ? baseDir : getProject().resolveFile(".");
  228. }
  229. /**
  230. * Controls whether the filenames of the files that are processed are logged
  231. * or not.
  232. * @param logFiles True if the feature should be enabled
  233. */
  234. public void setLogFiles(boolean logFiles) {
  235. this.logFiles = logFiles;
  236. }
  237. /**
  238. * Returns True if the filename of each file processed should be logged.
  239. * @return True if the filenames should be logged.
  240. */
  241. public boolean getLogFiles() {
  242. return this.logFiles;
  243. }
  244. /**
  245. * @see org.apache.tools.ant.Task#execute()
  246. */
  247. public void execute() throws BuildException {
  248. int logLevel = SimpleLog.LOG_LEVEL_INFO;
  249. switch (getMessageType()) {
  250. case Project.MSG_DEBUG : logLevel = SimpleLog.LOG_LEVEL_DEBUG; break;
  251. case Project.MSG_INFO : logLevel = SimpleLog.LOG_LEVEL_INFO; break;
  252. case Project.MSG_WARN : logLevel = SimpleLog.LOG_LEVEL_WARN; break;
  253. case Project.MSG_ERR : logLevel = SimpleLog.LOG_LEVEL_ERROR; break;
  254. case Project.MSG_VERBOSE: logLevel = SimpleLog.LOG_LEVEL_DEBUG; break;
  255. default: logLevel = SimpleLog.LOG_LEVEL_INFO;
  256. }
  257. SimpleLog logger = new SimpleLog("FOP/Anttask");
  258. logger.setLevel(logLevel);
  259. try {
  260. FOPTaskStarter starter = new FOPTaskStarter(this);
  261. starter.setLogger(logger);
  262. starter.run();
  263. } catch (FOPException ex) {
  264. throw new BuildException(ex);
  265. }
  266. }
  267. }
  268. class FOPTaskStarter {
  269. private Fop task;
  270. private String baseURL = null;
  271. /**
  272. * logging instance
  273. */
  274. protected Log logger = null;
  275. /**
  276. * Sets the Commons-Logging instance for this class
  277. * @param logger The Commons-Logging instance
  278. */
  279. public void setLogger(Log logger) {
  280. this.logger = logger;
  281. }
  282. /**
  283. * Returns the Commons-Logging instance for this class
  284. * @return The Commons-Logging instance
  285. */
  286. protected Log getLogger() {
  287. return logger;
  288. }
  289. FOPTaskStarter(Fop task) throws FOPException {
  290. this.task = task;
  291. }
  292. private static final String[][] SHORT_NAMES = {
  293. {"pdf", MimeConstants.MIME_PDF},
  294. {"ps", MimeConstants.MIME_POSTSCRIPT},
  295. {"mif", MimeConstants.MIME_MIF},
  296. {"rtf", MimeConstants.MIME_RTF},
  297. {"pcl", MimeConstants.MIME_PCL},
  298. {"txt", MimeConstants.MIME_PLAIN_TEXT},
  299. {"at", MimeConstants.MIME_FOP_AREA_TREE},
  300. {"xml", MimeConstants.MIME_FOP_AREA_TREE},
  301. {"tiff", MimeConstants.MIME_TIFF},
  302. {"tif", MimeConstants.MIME_TIFF},
  303. {"png", MimeConstants.MIME_PNG}
  304. };
  305. private String normalizeOutputFormat(String format) {
  306. for (int i = 0; i < SHORT_NAMES.length; i++) {
  307. if (SHORT_NAMES[i][0].equals(format)) {
  308. return SHORT_NAMES[i][1];
  309. }
  310. }
  311. return format; //no change
  312. }
  313. private static final String[][] EXTENSIONS = {
  314. {MimeConstants.MIME_FOP_AREA_TREE, ".at.xml"},
  315. {MimeConstants.MIME_FOP_AWT_PREVIEW, null},
  316. {MimeConstants.MIME_FOP_PRINT, null},
  317. {MimeConstants.MIME_PDF, ".pdf"},
  318. {MimeConstants.MIME_POSTSCRIPT, ".ps"},
  319. {MimeConstants.MIME_PCL, ".pcl"},
  320. {MimeConstants.MIME_PCL_ALT, ".pcl"},
  321. {MimeConstants.MIME_PLAIN_TEXT, ".txt"},
  322. {MimeConstants.MIME_RTF, ".rtf"},
  323. {MimeConstants.MIME_RTF_ALT1, ".rtf"},
  324. {MimeConstants.MIME_RTF_ALT2, ".rtf"},
  325. {MimeConstants.MIME_MIF, ".mif"},
  326. {MimeConstants.MIME_SVG, ".svg"},
  327. {MimeConstants.MIME_PNG, ".png"},
  328. {MimeConstants.MIME_JPEG, ".jpg"},
  329. {MimeConstants.MIME_TIFF, ".tif"},
  330. {MimeConstants.MIME_XSL_FO, ".fo"}
  331. };
  332. private String determineExtension(String outputFormat) {
  333. for (int i = 0; i < EXTENSIONS.length; i++) {
  334. if (EXTENSIONS[i][0].equals(outputFormat)) {
  335. String ext = EXTENSIONS[i][1];
  336. if (ext == null) {
  337. throw new RuntimeException("Output format '"
  338. + outputFormat + "' does not produce a file.");
  339. } else {
  340. return ext;
  341. }
  342. }
  343. }
  344. return ".unk"; //unknown
  345. }
  346. private File replaceExtension(File file, String expectedExt,
  347. String newExt) {
  348. String name = file.getName();
  349. if (name.toLowerCase().endsWith(expectedExt)) {
  350. name = name.substring(0, name.length() - expectedExt.length());
  351. }
  352. name = name.concat(newExt);
  353. return new File(file.getParentFile(), name);
  354. }
  355. /**
  356. * @see org.apache.fop.apps.Starter#run()
  357. */
  358. public void run() throws FOPException {
  359. //Setup configuration
  360. if (task.getUserconfig() != null) {
  361. /**@todo implement me */
  362. }
  363. //Set base directory
  364. if (task.getBasedir() != null) {
  365. try {
  366. this.baseURL = task.getBasedir().toURL().toExternalForm();
  367. } catch (MalformedURLException mfue) {
  368. logger.error("Error creating base URL from base directory", mfue);
  369. }
  370. } else {
  371. try {
  372. if (task.getFofile() != null) {
  373. this.baseURL = task.getFofile().getParentFile().toURL().
  374. toExternalForm();
  375. }
  376. } catch (MalformedURLException mfue) {
  377. logger.error("Error creating base URL from XSL-FO input file", mfue);
  378. }
  379. }
  380. task.log("Using base URL: " + baseURL, Project.MSG_DEBUG);
  381. String outputFormat = normalizeOutputFormat(task.getFormat());
  382. String newExtension = determineExtension(outputFormat);
  383. // actioncount = # of fofiles actually processed through FOP
  384. int actioncount = 0;
  385. // skippedcount = # of fofiles which haven't changed (force = "false")
  386. int skippedcount = 0;
  387. // deal with single source file
  388. if (task.getFofile() != null) {
  389. if (task.getFofile().exists()) {
  390. File outf = task.getOutfile();
  391. if (outf == null) {
  392. throw new BuildException("outfile is required when fofile is used");
  393. }
  394. if (task.getOutdir() != null) {
  395. outf = new File(task.getOutdir(), outf.getName());
  396. }
  397. // Render if "force" flag is set OR
  398. // OR output file doesn't exist OR
  399. // output file is older than input file
  400. if (task.getForce() || !outf.exists()
  401. || (task.getFofile().lastModified() > outf.lastModified() )) {
  402. render(task.getFofile(), outf, outputFormat);
  403. actioncount++;
  404. } else if (outf.exists()
  405. && (task.getFofile().lastModified() <= outf.lastModified() )) {
  406. skippedcount++;
  407. }
  408. }
  409. }
  410. GlobPatternMapper mapper = new GlobPatternMapper();
  411. mapper.setFrom("*.fo");
  412. mapper.setTo("*" + newExtension);
  413. // deal with the filesets
  414. for (int i = 0; i < task.getFilesets().size(); i++) {
  415. FileSet fs = (FileSet) task.getFilesets().get(i);
  416. DirectoryScanner ds = fs.getDirectoryScanner(task.getProject());
  417. String[] files = ds.getIncludedFiles();
  418. for (int j = 0; j < files.length; j++) {
  419. File f = new File(fs.getDir(task.getProject()), files[j]);
  420. File outf = null;
  421. if (task.getOutdir() != null && files[j].endsWith(".fo")) {
  422. String[] sa = mapper.mapFileName(files[j]);
  423. outf = new File(task.getOutdir(), sa[0]);
  424. } else {
  425. outf = replaceExtension(f, ".fo", newExtension);
  426. if (task.getOutdir() != null) {
  427. outf = new File(task.getOutdir(), outf.getName());
  428. }
  429. }
  430. try {
  431. if (task.getRelativebase()) {
  432. this.baseURL = f.getParentFile().toURL().
  433. toExternalForm();
  434. }
  435. if (this.baseURL == null) {
  436. this.baseURL = fs.getDir(task.getProject()).toURL().
  437. toExternalForm();
  438. }
  439. } catch (Exception e) {
  440. task.log("Error setting base URL", Project.MSG_DEBUG);
  441. }
  442. // Render if "force" flag is set OR
  443. // OR output file doesn't exist OR
  444. // output file is older than input file
  445. if (task.getForce() || !outf.exists()
  446. || (f.lastModified() > outf.lastModified() )) {
  447. render(f, outf, outputFormat);
  448. actioncount++;
  449. } else if (outf.exists() && (f.lastModified() <= outf.lastModified() )) {
  450. skippedcount++;
  451. }
  452. }
  453. }
  454. if (actioncount + skippedcount == 0) {
  455. task.log("No files processed. No files were selected by the filesets "
  456. + "and no fofile was set." , Project.MSG_WARN);
  457. } else if (skippedcount > 0) {
  458. task.log(skippedcount + " xslfo file(s) skipped (no change found"
  459. + " since last generation; set force=\"true\" to override)."
  460. , Project.MSG_INFO);
  461. }
  462. }
  463. private void render(File foFile, File outFile,
  464. String outputFormat) throws FOPException {
  465. InputHandler inputHandler = new InputHandler(foFile);
  466. OutputStream out = null;
  467. try {
  468. out = new java.io.FileOutputStream(outFile);
  469. } catch (Exception ex) {
  470. throw new BuildException("Failed to open " + outFile, ex);
  471. }
  472. if (task.getLogFiles()) {
  473. task.log(foFile + " -> " + outFile, Project.MSG_INFO);
  474. }
  475. try {
  476. FOUserAgent userAgent = new FOUserAgent();
  477. userAgent.setBaseURL(this.baseURL);
  478. org.apache.fop.apps.Fop fop = new org.apache.fop.apps.Fop(
  479. outputFormat, userAgent);
  480. fop.setOutputStream(out);
  481. inputHandler.render(fop);
  482. } catch (Exception ex) {
  483. throw new BuildException(ex);
  484. } finally {
  485. try {
  486. out.close();
  487. } catch (IOException ioe) {
  488. logger.error("Error closing output file", ioe);
  489. }
  490. }
  491. }
  492. }