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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. /*
  2. ============================================================================
  3. The Apache Software License, Version 1.1
  4. ============================================================================
  5. Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
  6. Redistribution and use in source and binary forms, with or without modifica-
  7. tion, are permitted provided that the following conditions are met:
  8. 1. Redistributions of source code must retain the above copyright notice,
  9. this list of conditions and the following disclaimer.
  10. 2. Redistributions in binary form must reproduce the above copyright notice,
  11. this list of conditions and the following disclaimer in the documentation
  12. and/or other materials provided with the distribution.
  13. 3. The end-user documentation included with the redistribution, if any, must
  14. include the following acknowledgment: "This product includes software
  15. developed by the Apache Software Foundation (http://www.apache.org/)."
  16. Alternately, this acknowledgment may appear in the software itself, if
  17. and wherever such third-party acknowledgments normally appear.
  18. 4. The names "Fop" and "Apache Software Foundation" must not be used to
  19. endorse or promote products derived from this software without prior
  20. written permission. For written permission, please contact
  21. apache@apache.org.
  22. 5. Products derived from this software may not be called "Apache", nor may
  23. "Apache" appear in their name, without prior written permission of the
  24. Apache Software Foundation.
  25. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  26. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  27. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  28. APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  29. INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
  30. DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  31. OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  32. ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  33. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  34. THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  35. This software consists of voluntary contributions made by many individuals
  36. on behalf of the Apache Software Foundation and was originally created by
  37. James Tauber <jtauber@jtauber.com>. For more information on the Apache
  38. Software Foundation, please see <http://www.apache.org/>.
  39. */
  40. package org.apache.fop.tools.anttasks;
  41. // Ant
  42. import org.apache.tools.ant.*;
  43. // SAX
  44. import org.xml.sax.XMLReader;
  45. import org.xml.sax.InputSource;
  46. import org.xml.sax.SAXException;
  47. import org.xml.sax.SAXParseException;
  48. // Java
  49. import java.io.*;
  50. import java.util.*;
  51. // FOP
  52. import org.apache.fop.messaging.*;
  53. import org.apache.fop.apps.Starter;
  54. import org.apache.fop.apps.InputHandler;
  55. import org.apache.fop.apps.FOInputHandler;
  56. import org.apache.fop.apps.Driver;
  57. import org.apache.fop.apps.FOPException;
  58. import org.apache.fop.configuration.Configuration;
  59. /**
  60. * Wrapper for Fop which allows it to be accessed from within an Ant task.
  61. * Accepts the inputs:
  62. * <ul>
  63. * <li>fofile -> formatting objects file to be transformed</li>
  64. * <li>pdffile -> output filename</li>
  65. * <li>basedir -> directory to work from</li>
  66. * <li>messagelevel -> (info | verbose | debug) level to output non-error messages</li>
  67. * </ul>
  68. */
  69. public class Fop extends Task {
  70. File foFile;
  71. File pdfFile;
  72. File baseDir;
  73. int messageType = Project.MSG_VERBOSE;
  74. /**
  75. * Sets the input file
  76. * @param File to input from
  77. */
  78. public void setFofile(File foFile) {
  79. this.foFile = foFile;
  80. }
  81. /**
  82. * Gets the input file
  83. */
  84. public File getFofile() {
  85. if(foFile == null) {
  86. log("fofile attribute is not set", Project.MSG_ERR);
  87. throw new BuildException("fofile attribute is not set");
  88. }
  89. return foFile;
  90. }
  91. /**
  92. * Sets the output file
  93. * @param File to output to
  94. */
  95. public void setPdffile(File pdfFile) {
  96. this.pdfFile = pdfFile;
  97. }
  98. /**
  99. * Sets the output file
  100. */
  101. public File getPdffile() {
  102. if(pdfFile == null) {
  103. log("pdffile attribute is not set", Project.MSG_ERR);
  104. throw new BuildException("pdffile attribute is not set");
  105. }
  106. return pdfFile;
  107. }
  108. /**
  109. * Sets the message level to be used while processing.
  110. * @param String (info | verbose | debug)
  111. */
  112. public void setMessagelevel(String messageLevel) {
  113. if(messageLevel.equalsIgnoreCase("info")) {
  114. messageType = Project.MSG_INFO;
  115. } else if(messageLevel.equalsIgnoreCase("verbose")) {
  116. messageType = Project.MSG_VERBOSE;
  117. } else if(messageLevel.equalsIgnoreCase("debug")) {
  118. messageType = Project.MSG_DEBUG;
  119. } else {
  120. log("messagelevel set to unknown value \"" + messageLevel + "\"", Project.MSG_ERR);
  121. throw new BuildException("unknown messagelevel");
  122. }
  123. }
  124. /**
  125. * Returns the message type corresponding to Property.MSG_(INFO | VERBOSE | DEBUG)
  126. * representing the current message level.
  127. */
  128. public int getMessageType() {
  129. return messageType;
  130. }
  131. /**
  132. * Sets the base directory; currently ignored
  133. * @param File to use as a working directory
  134. */
  135. public void setBasedir(File baseDir) {
  136. this.baseDir = baseDir;
  137. }
  138. /**
  139. * Gets the base directory
  140. */
  141. public File getBasedir() {
  142. return (baseDir != null) ? baseDir : project.resolveFile(".");
  143. }
  144. /**
  145. * Starts execution of this task
  146. */
  147. public void execute () throws BuildException {
  148. try {
  149. Starter starter = new FOPTaskStarter(this);
  150. starter.run();
  151. }
  152. catch (FOPException ex) {
  153. throw new BuildException(ex);
  154. }
  155. }
  156. }
  157. class FOPTaskStarter extends Starter {
  158. Fop task;
  159. MessageLogger logger;
  160. FOPTaskStarter(Fop task)
  161. throws FOPException
  162. {
  163. this.task = task;
  164. MessageHandler.setOutputMethod(MessageHandler.EVENT);
  165. logger = new MessageLogger(new MessageHandler(), task);
  166. logger.setMessageLevel(task.getMessageType());
  167. }
  168. public void run ()
  169. throws FOPException
  170. {
  171. Configuration.put("basedir", task.getBasedir());
  172. InputHandler inputHandler = new FOInputHandler(task.getFofile());
  173. XMLReader parser = inputHandler.getParser();
  174. setParserFeatures(parser);
  175. FileOutputStream pdfOut = null;
  176. try {
  177. pdfOut = new FileOutputStream(task.getPdffile());
  178. }catch(Exception ex) {
  179. MessageHandler.errorln("Failed to open " + task.getPdffile());
  180. throw new BuildException(ex);
  181. }
  182. task.log("Using base directory: " + Configuration.getValue("basedir"), Project.MSG_DEBUG);
  183. task.log(task.getFofile().getName() + " -> " + task.getPdffile().getName(), Project.MSG_INFO);
  184. try {
  185. Driver driver = new Driver(inputHandler.getInputSource(), pdfOut);
  186. driver.setRenderer(Driver.RENDER_PDF);
  187. driver.setXMLReader(parser);
  188. driver.run();
  189. } catch (Exception ex) {
  190. MessageHandler.logln("Error: " + ex.getMessage());
  191. throw new BuildException(ex);
  192. }
  193. logger.die();
  194. }
  195. }
  196. class MessageLogger implements MessageListener {
  197. MessageHandler handler;
  198. Task task;
  199. int messageLevel = Project.MSG_VERBOSE;
  200. int lastMessageLevel = Integer.MIN_VALUE;
  201. StringBuffer cache = new StringBuffer();
  202. String breakChars = "\n";
  203. boolean performCaching = true;
  204. MessageLogger(MessageHandler handler, Task task) {
  205. this(handler, task, Project.MSG_VERBOSE);
  206. }
  207. MessageLogger(MessageHandler handler, Task task, int messageLevel) {
  208. this.handler = handler;
  209. this.task = task;
  210. setMessageLevel(messageLevel);
  211. handler.addListener(this);
  212. }
  213. public void setMessageLevel(int messageLevel) {
  214. this.messageLevel = messageLevel;
  215. }
  216. public int getMessageLevel() {
  217. return messageLevel;
  218. }
  219. public void processMessage(MessageEvent event) {
  220. task.log("Logger got message: \"" + event.getMessage() + "\"", Project.MSG_DEBUG);
  221. boolean flushed = false;
  222. if(!flushed) {
  223. int messageLevel;
  224. if(event.getMessageType() == MessageEvent.ERROR) {
  225. messageLevel = Project.MSG_ERR;
  226. } else {
  227. messageLevel = this.messageLevel;
  228. }
  229. if(messageLevel != lastMessageLevel) {
  230. flush();
  231. flushed = true;
  232. }
  233. lastMessageLevel = messageLevel;
  234. }
  235. cache.append(event.getMessage());
  236. if(!performCaching) {
  237. flush();
  238. flushed = true;
  239. }
  240. for(int i = 0; !flushed && i < breakChars.length(); i++) {
  241. if(event.getMessage().lastIndexOf(breakChars.charAt(i)) != -1) {
  242. flush();
  243. flushed = true;
  244. }
  245. }
  246. }
  247. public void flush() {
  248. StringTokenizer output = new StringTokenizer(cache.toString(), "\n", false);
  249. while(output.hasMoreElements()) {
  250. task.log(output.nextElement().toString(), lastMessageLevel);
  251. }
  252. cache.setLength(0);
  253. }
  254. public void die() {
  255. flush();
  256. // because MessageHandler is static this has to be done
  257. // or you can get duplicate messages if there are
  258. // multiple <fop> tags in a buildfile
  259. handler.removeListener(this);
  260. }
  261. }