KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > fop > tools > anttasks > Fop


1 /*
2  * $Id: Fop.java,v 1.14.2.8 2003/02/25 15:19:58 jeremias Exp $
3  * ============================================================================
4  * The Apache Software License, Version 1.1
5  * ============================================================================
6  *
7  * Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without modifica-
10  * tion, are permitted provided that the following conditions are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  *
19  * 3. The end-user documentation included with the redistribution, if any, must
20  * include the following acknowledgment: "This product includes software
21  * developed by the Apache Software Foundation (http://www.apache.org/)."
22  * Alternately, this acknowledgment may appear in the software itself, if
23  * and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. The names "FOP" and "Apache Software Foundation" must not be used to
26  * endorse or promote products derived from this software without prior
27  * written permission. For written permission, please contact
28  * apache@apache.org.
29  *
30  * 5. Products derived from this software may not be called "Apache", nor may
31  * "Apache" appear in their name, without prior written permission of the
32  * Apache Software Foundation.
33  *
34  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
35  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
36  * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
37  * APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
38  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
39  * DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
40  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
41  * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
42  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
43  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44  * ============================================================================
45  *
46  * This software consists of voluntary contributions made by many individuals
47  * on behalf of the Apache Software Foundation and was originally created by
48  * James Tauber <jtauber@jtauber.com>. For more information on the Apache
49  * Software Foundation, please see <http://www.apache.org/>.
50  */

51 package org.apache.fop.tools.anttasks;
52
53 // Ant
54
import org.apache.tools.ant.BuildException;
55 import org.apache.tools.ant.DirectoryScanner;
56 import org.apache.tools.ant.Project;
57 import org.apache.tools.ant.Task;
58 import org.apache.tools.ant.types.FileSet;
59
60 // SAX
61
import org.xml.sax.XMLReader JavaDoc;
62
63 // Java
64
import java.io.File JavaDoc;
65 import java.io.OutputStream JavaDoc;
66 import java.util.List JavaDoc;
67 import java.util.Map JavaDoc;
68
69 // FOP
70
import org.apache.fop.messaging.MessageHandler;
71 import org.apache.fop.apps.Options;
72 import org.apache.fop.apps.Starter;
73 import org.apache.fop.apps.InputHandler;
74 import org.apache.fop.apps.FOInputHandler;
75 import org.apache.fop.apps.Driver;
76 import org.apache.fop.apps.FOPException;
77 import org.apache.fop.configuration.Configuration;
78
79 // Avalon
80
import org.apache.avalon.framework.logger.ConsoleLogger;
81 import org.apache.avalon.framework.logger.Logger;
82 import org.apache.tools.ant.util.GlobPatternMapper;
83
84 /**
85  * Wrapper for Fop which allows it to be accessed from within an Ant task.
86  * Accepts the inputs:
87  * <ul>
88  * <li>fofile -> formatting objects file to be transformed</li>
89  * <li>format -> MIME type of the format to generate ex. "application/pdf"</li>
90  * <li>outfile -> output filename</li>
91  * <li>baseDir -> directory to work from</li>
92  * <li>userconfig -> file with user configuration (same as the "-c" command line option)</li>
93  * <li>messagelevel -> (error | warn | info | verbose | debug) level to output non-error messages</li>
94  * <li>logFiles -> Controls whether the names of the files that are processed are logged or not</li>
95  * </ul>
96  */

97 public class Fop extends Task {
98     
99     File JavaDoc foFile;
100     List JavaDoc filesets = new java.util.ArrayList JavaDoc();
101     File JavaDoc outFile;
102     File JavaDoc outDir;
103     String JavaDoc format; //MIME type
104
File JavaDoc baseDir;
105     File JavaDoc userConfig;
106     int messageType = Project.MSG_VERBOSE;
107     boolean logFiles = true;
108
109     /**
110      * Sets the input file
111      * @param File to input from
112      */

113     public void setUserconfig (File JavaDoc userConfig) {
114         this.userConfig = userConfig;
115     }
116
117     /**
118      * Sets the input file
119      * @param File to input from
120      */

121     public void setFofile(File JavaDoc foFile) {
122         this.foFile = foFile;
123     }
124
125     /**
126      * Gets the input file
127      */

128     public File JavaDoc getFofile() {
129         return foFile;
130     }
131
132     /**
133      * Adds a set of fo files (nested fileset attribute).
134      */

135     public void addFileset(FileSet set) {
136         filesets.add(set);
137     }
138
139     /**
140      * Sets the output file
141      * @param File to output to
142      */

143     public void setOutfile(File JavaDoc outFile) {
144         this.outFile = outFile;
145     }
146
147     /**
148      * Gets the output file
149      */

150     public File JavaDoc getOutfile() {
151         return this.outFile;
152     }
153
154     /**
155      * Sets the output directory
156      * @param Directory to output to
157      */

158     public void setOutdir(File JavaDoc outDir) {
159         this.outDir = outDir;
160     }
161
162     /**
163      * Gets the output directory
164      */

165     public File JavaDoc getOutdir() {
166         return this.outDir;
167     }
168
169     /**
170      * Sets output format (MIME type)
171      */

172     public void setFormat(String JavaDoc format) {
173         this.format = format;
174     }
175
176     /**
177      * Gets the output format (MIME type)
178      */

179     public String JavaDoc getFormat() {
180         return this.format;
181     }
182
183     /**
184      * Sets the message level to be used while processing.
185      * @param String (info | verbose | debug)
186      */

187     public void setMessagelevel(String JavaDoc messageLevel) {
188         if (messageLevel.equalsIgnoreCase("info")) {
189             messageType = Project.MSG_INFO;
190         } else if (messageLevel.equalsIgnoreCase("verbose")) {
191             messageType = Project.MSG_VERBOSE;
192         } else if (messageLevel.equalsIgnoreCase("debug")) {
193             messageType = Project.MSG_DEBUG;
194         } else if (messageLevel.equalsIgnoreCase("err") || messageLevel.equalsIgnoreCase("error")) {
195             messageType = Project.MSG_ERR;
196         } else if (messageLevel.equalsIgnoreCase("warn")) {
197             messageType = Project.MSG_WARN;
198         } else {
199             log("messagelevel set to unknown value \"" + messageLevel +
200                 "\"", Project.MSG_ERR);
201             throw new BuildException("unknown messagelevel");
202         }
203     }
204
205     /**
206      * Returns the message type corresponding to Property.MSG_(INFO | VERBOSE | DEBUG)
207      * representing the current message level.
208      */

209     public int getMessageType() {
210         return messageType;
211     }
212
213     /**
214      * Sets the base directory; currently ignored
215      * @param File to use as a working directory
216      */

217     public void setBasedir(File JavaDoc baseDir) {
218         this.baseDir = baseDir;
219     }
220
221     /**
222      * Gets the base directory
223      */

224     public File JavaDoc getBasedir() {
225         return (baseDir != null) ? baseDir : project.resolveFile(".");
226     }
227
228     /**
229      * Controls whether the filenames of the files that are processed are logged
230      * or not.
231      */

232     public void setLogFiles(boolean aBoolean) {
233         logFiles = aBoolean;
234     }
235
236     public boolean getLogFiles() {
237         return logFiles;
238     }
239
240     /**
241      * Starts execution of this task
242      */

243     public void execute() throws BuildException {
244         int logLevel = ConsoleLogger.LEVEL_INFO;
245         switch (getMessageType()) {
246             case Project.MSG_DEBUG : logLevel = ConsoleLogger.LEVEL_DEBUG; break;
247             case Project.MSG_INFO : logLevel = ConsoleLogger.LEVEL_INFO; break;
248             case Project.MSG_WARN : logLevel = ConsoleLogger.LEVEL_WARN; break;
249             case Project.MSG_ERR : logLevel = ConsoleLogger.LEVEL_ERROR; break;
250             case Project.MSG_VERBOSE: logLevel = ConsoleLogger.LEVEL_DEBUG; break;
251         }
252         Logger log = new ConsoleLogger(logLevel);
253         MessageHandler.setScreenLogger(log);
254         try {
255             Starter starter = new FOPTaskStarter(this, log, logFiles);
256             starter.run();
257         } catch (FOPException ex) {
258             throw new BuildException(ex);
259         }
260
261     }
262
263 }
264
265 class FOPTaskStarter extends Starter {
266     Fop task;
267     Logger log;
268     boolean logFiles;
269
270     FOPTaskStarter(Fop task, Logger aLogger, boolean aLogFiles) throws FOPException {
271         this.task = task;
272         log = aLogger;
273         logFiles = aLogFiles;
274     }
275
276     private int determineRenderer(String JavaDoc format) {
277         if ((format == null) ||
278                 format.equalsIgnoreCase("application/pdf") ||
279                 format.equalsIgnoreCase("pdf")) {
280             return Driver.RENDER_PDF;
281         } else if (format.equalsIgnoreCase("application/postscript") ||
282             format.equalsIgnoreCase("ps")) {
283             return Driver.RENDER_PS;
284         } else if (format.equalsIgnoreCase("application/vnd.mif") ||
285             format.equalsIgnoreCase("mif")) {
286             return Driver.RENDER_MIF;
287         } else if (format.equalsIgnoreCase("application/vnd.gp-PCL") ||
288             format.equalsIgnoreCase("pcl")) {
289             return Driver.RENDER_PCL;
290         } else if (format.equalsIgnoreCase("text/plain") ||
291             format.equalsIgnoreCase("txt")) {
292             return Driver.RENDER_TXT;
293         } else if (format.equalsIgnoreCase("text/xml") ||
294             format.equalsIgnoreCase("at") ||
295             format.equalsIgnoreCase("xml")) {
296             return Driver.RENDER_XML;
297         } else {
298             String JavaDoc err = "Couldn't determine renderer to use: "+format;
299             throw new BuildException(err);
300         }
301     }
302
303     private String JavaDoc determineExtension(int renderer) {
304         switch (renderer) {
305             case Driver.RENDER_PDF:
306                 return ".pdf";
307             case Driver.RENDER_PS:
308                 return ".ps";
309             case Driver.RENDER_MIF:
310                 return ".mif";
311             case Driver.RENDER_PCL:
312                 return ".pcl";
313             case Driver.RENDER_TXT:
314                 return ".txt";
315             case Driver.RENDER_XML:
316                 return ".xml";
317             default:
318                 String JavaDoc err = "Unknown renderer: "+renderer;
319                 throw new BuildException(err);
320         }
321     }
322
323     private File JavaDoc replaceExtension(File JavaDoc file, String JavaDoc expectedExt,
324                                   String JavaDoc newExt) {
325         String JavaDoc name = file.getName();
326         if (name.toLowerCase().endsWith(expectedExt)) {
327             name = name.substring(0, name.length() - expectedExt.length());
328         }
329         name = name.concat(newExt);
330         return new File JavaDoc(file.getParentFile(), name);
331     }
332
333     public void run() throws FOPException {
334         if (task.userConfig != null) {
335             new Options (task.userConfig);
336         }
337
338         try {
339             if (task.getFofile() != null) {
340                 if (task.getBasedir() != null) {
341                     Configuration.put("baseDir",
342                                       task.getBasedir().toURL().
343                                       toExternalForm());
344                 } else {
345                     Configuration.put("baseDir",
346                                       task.getFofile().getParentFile().toURL().
347                                       toExternalForm());
348                 }
349             }
350             task.log("Using base directory: " +
351                      Configuration.getValue("baseDir"), Project.MSG_DEBUG);
352         } catch (Exception JavaDoc e) {
353
354             task.log("Error setting base directory: " + e, Project.MSG_ERR);
355         }
356
357         int rint = determineRenderer(task.getFormat());
358         String JavaDoc newExtension = determineExtension(rint);
359
360         int actioncount = 0;
361
362         // deal with single source file
363
if (task.getFofile() != null) {
364             if (task.getFofile().exists()) {
365                 File JavaDoc outf = task.getOutfile();
366                 if (outf == null) {
367                     throw new BuildException("outfile is required when fofile is used");
368                 }
369                 if (task.getOutdir() != null) {
370                     outf = new File JavaDoc(task.getOutdir(), outf.getName());
371                 }
372                 render(task.getFofile(), outf, rint);
373                 actioncount++;
374             }
375         }
376
377         GlobPatternMapper mapper = new GlobPatternMapper();
378         mapper.setFrom("*.fo");
379         mapper.setTo("*" + newExtension);
380
381         // deal with the filesets
382
for (int i = 0; i < task.filesets.size(); i++) {
383             FileSet fs = (FileSet) task.filesets.get(i);
384             DirectoryScanner ds = fs.getDirectoryScanner(task.getProject());
385             String JavaDoc[] files = ds.getIncludedFiles();
386
387
388             for (int j = 0; j < files.length; j++) {
389                 File JavaDoc f = new File JavaDoc(fs.getDir(task.getProject()), files[j]);
390                 File JavaDoc outf = null;
391                 if (task.getOutdir() != null && files[j].endsWith(".fo")) {
392                   String JavaDoc[] sa = mapper.mapFileName(files[j]);
393                   outf = new File JavaDoc(task.getOutdir(), sa[0]);
394                 } else {
395                   outf = replaceExtension(f, ".fo", newExtension);
396                   if (task.getOutdir() != null) {
397                       outf = new File JavaDoc(task.getOutdir(), outf.getName());
398                   }
399                 }
400                 try {
401                     if (task.getBasedir() != null) {
402                         Configuration.put("baseDir",
403                                           task.getBasedir().toURL().
404                                           toExternalForm());
405                     } else {
406                         Configuration.put("baseDir",
407                                           fs.getDir(task.getProject()).toURL().
408                                           toExternalForm());
409                     }
410                     task.log("Using base directory: " +
411                              Configuration.getValue("baseDir"), Project.MSG_DEBUG);
412                 } catch (Exception JavaDoc e) {
413                     task.log("Error setting base directory: " + e, Project.MSG_ERR);
414                 }
415
416                 render(f, outf, rint);
417                 actioncount++;
418             }
419         }
420
421         if (actioncount == 0) {
422             task.log(
423               "No files processed. No files were selected by the filesets and no fofile was set." ,
424               Project.MSG_WARN);
425         }
426     }
427
428     private void render(File JavaDoc foFile, File JavaDoc outFile,
429                         int renderer) throws FOPException {
430         InputHandler inputHandler = new FOInputHandler(foFile);
431         XMLReader JavaDoc parser = inputHandler.getParser();
432
433         OutputStream JavaDoc out = null;
434         try {
435             File JavaDoc dir = outFile.getParentFile();
436             dir.mkdirs();
437             out = new java.io.FileOutputStream JavaDoc(outFile);
438         } catch (Exception JavaDoc ex) {
439             throw new BuildException(ex);
440         }
441
442         if (logFiles) task.log(foFile + " -> " + outFile, Project.MSG_INFO);
443
444         try {
445             Driver driver = new Driver(inputHandler.getInputSource(), out);
446             driver.setLogger(log);
447             driver.setRenderer(renderer);
448             if (renderer == Driver.RENDER_XML) {
449                 Map JavaDoc rendererOptions = new java.util.HashMap JavaDoc();
450                 rendererOptions.put("fineDetail", new Boolean JavaDoc(true));
451                 driver.getRenderer().setOptions(rendererOptions);
452             }
453             driver.setXMLReader(parser);
454             driver.run();
455             out.close();
456         } catch (Exception JavaDoc ex) {
457             throw new BuildException(ex);
458         }
459     }
460
461 }
462
463
Popular Tags