KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > fop > visual > BatchDiffer


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
18 /* $Id: BatchDiffer.java 426576 2006-07-28 15:44:37Z jeremias $ */
19
20 package org.apache.fop.visual;
21
22 import java.awt.image.BufferedImage JavaDoc;
23 import java.io.File JavaDoc;
24 import java.io.FileOutputStream JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.io.OutputStream JavaDoc;
27 import java.util.Collection JavaDoc;
28 import java.util.Iterator JavaDoc;
29
30 import javax.xml.transform.TransformerConfigurationException JavaDoc;
31 import javax.xml.transform.stream.StreamSource JavaDoc;
32
33 import org.apache.avalon.framework.configuration.Configuration;
34 import org.apache.avalon.framework.configuration.ConfigurationException;
35 import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
36 import org.apache.avalon.framework.container.ContainerUtil;
37
38 import org.apache.batik.ext.awt.image.codec.PNGEncodeParam;
39 import org.apache.batik.ext.awt.image.codec.PNGImageEncoder;
40
41 import org.apache.commons.io.FileUtils;
42 import org.apache.commons.io.IOUtils;
43 import org.apache.commons.io.filefilter.IOFileFilter;
44 import org.apache.commons.io.filefilter.SuffixFileFilter;
45
46 import org.apache.commons.logging.Log;
47 import org.apache.commons.logging.LogFactory;
48
49 import org.apache.fop.layoutengine.LayoutEngineTestSuite;
50
51 import org.xml.sax.SAXException JavaDoc;
52
53 /**
54  * This class is used to visually diff bitmap images created through various sources.
55  * <p>
56  * Here's what the configuration format looks like:
57  * <p>
58  * <pre>
59  * <batch-diff>
60  * <source-directory>C:/Dev/FOP/trunk/test/layoutengine</source-directory>
61  * <filter-disabled>false</filter-disabled>
62  * <max-files>10</max-files>
63  * <target-directory>C:/Temp/diff-out</target-directory>
64  * <resolution>100</resolution>
65  * <stop-on-exception>false</stop-on-exception>
66  * <create-diffs>false</create-diffs>
67  * <stylesheet>C:/Dev/FOP/trunk/test/layoutengine/testcase2fo.xsl</stylesheet>
68  * <producers>
69  * <producer classname="org.apache.fop.visual.BitmapProducerJava2D">
70  * <delete-temp-files>false</delete-temp-files>
71  * </producer>
72  * <producer classname="org.apache.fop.visual.ReferenceBitmapLoader">
73  * <directory>C:/Temp/diff-bitmaps</directory>
74  * </producer>
75  * </producers>
76  * </batch-diff>
77  * </pre>
78  * <p>
79  * The optional "filter-disabled" element determines whether the source files should be filtered
80  * using the same "disabled-testcases.txt" file used for the layout engine tests. Default: true
81  * <p>
82  * The optional "max-files" element controls how many files at maximum should be processed.
83  * Default is to process all the files found.
84  * <p>
85  * The optional "resolution" element controls the requested bitmap resolution in dpi for the
86  * generated bitmaps. Defaults to 72dpi.
87  * <p>
88  * The optional "stop-on-exception" element controls whether the batch should be aborted when
89  * an exception is caught. Defaults to true.
90  * <p>
91  * The optional "create-diffs" element controls whether the diff images should be created.
92  * Defaults to true.
93  * <p>
94  * The optional "stylesheet" element allows you to supply an XSLT stylesheet to preprocess all
95  * source files with. Default: no stylesheet, identity transform.
96  * <p>
97  * The "producers" element contains a list of producer implementations with configuration.
98  * The "classname" attribute specifies the fully qualified class name for the implementation.
99  */

100 public class BatchDiffer {
101
102     /** Logger */
103     protected static Log log = LogFactory.getLog(BatchDiffer.class);
104
105     /**
106      * Prints the usage of this app to stdout.
107      */

108     public static void printUsage() {
109         System.out.println("Usage:");
110         System.out.println("java " + BatchDiffer.class.getName() + " <cfgfile>");
111         System.out.println();
112         System.out.println("<cfgfile>: Path to an XML file with the configuration"
113                 + " for the batch run.");
114     }
115
116     /**
117      * Saves a BufferedImage as a PNG file.
118      * @param bitmap the bitmap to encode
119      * @param outputFile the target file
120      * @throws IOException in case of an I/O problem
121      */

122     public static void saveAsPNG(BufferedImage JavaDoc bitmap, File JavaDoc outputFile) throws IOException JavaDoc {
123         OutputStream JavaDoc out = new FileOutputStream JavaDoc(outputFile);
124         try {
125             PNGImageEncoder encoder = new PNGImageEncoder(
126                     out,
127                     PNGEncodeParam.getDefaultEncodeParam(bitmap));
128             encoder.encode(bitmap);
129         } finally {
130             IOUtils.closeQuietly(out);
131         }
132     }
133     
134     /**
135      * Runs the batch.
136      * @param cfgFile configuration file to use
137      * @throws ConfigurationException In case of a problem with the configuration
138      * @throws SAXException In case of a problem during SAX processing
139      * @throws IOException In case of a I/O problem
140      */

141     public void runBatch(File JavaDoc cfgFile)
142                 throws ConfigurationException JavaDoc, SAXException JavaDoc, IOException JavaDoc {
143         DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder();
144         Configuration cfg = cfgBuilder.buildFromFile(cfgFile);
145         runBatch(cfg);
146     }
147
148     /**
149      * Runs the batch
150      * @param cfg Configuration for the batch
151      * @throws TransformerConfigurationException
152      */

153     public void runBatch(Configuration cfg) {
154         try {
155             ProducerContext context = new ProducerContext();
156             context.setTargetResolution(cfg.getChild("resolution").getValueAsInteger(72));
157             String JavaDoc xslt = cfg.getChild("stylesheet").getValue(null);
158             if (xslt != null) {
159                 try {
160                     context.setTemplates(context.getTransformerFactory().newTemplates(
161                             new StreamSource JavaDoc(xslt)));
162                 } catch (TransformerConfigurationException JavaDoc e) {
163                     log.error("Error setting up stylesheet", e);
164                     throw new RuntimeException JavaDoc("Error setting up stylesheet");
165                 }
166             }
167             BitmapProducer[] producers = getProducers(cfg.getChild("producers"));
168             
169             //Set up directories
170
File JavaDoc srcDir = new File JavaDoc(cfg.getChild("source-directory").getValue());
171             if (!srcDir.exists()) {
172                 throw new RuntimeException JavaDoc("source-directory does not exist: " + srcDir);
173             }
174             File JavaDoc targetDir = new File JavaDoc(cfg.getChild("target-directory").getValue());
175             targetDir.mkdirs();
176             if (!targetDir.exists()) {
177                 throw new RuntimeException JavaDoc("target-directory is invalid: " + targetDir);
178             }
179             context.setTargetDir(targetDir);
180             
181             boolean stopOnException = cfg.getChild("stop-on-exception").getValueAsBoolean(true);
182             boolean createDiffs = cfg.getChild("create-diffs").getValueAsBoolean(true);
183             
184             //RUN!
185
BufferedImage JavaDoc[] bitmaps = new BufferedImage JavaDoc[producers.length];
186             
187             IOFileFilter filter = new SuffixFileFilter(new String JavaDoc[] {".xml", ".fo"});
188             //Same filtering as in layout engine tests
189
if (cfg.getChild("filter-disabled").getValueAsBoolean(true)) {
190                 filter = LayoutEngineTestSuite.decorateWithDisabledList(filter);
191             }
192
193             int maxfiles = cfg.getChild("max-files").getValueAsInteger(-1);
194             Collection JavaDoc files = FileUtils.listFiles(srcDir, filter, null);
195             Iterator JavaDoc i = files.iterator();
196             while (i.hasNext()) {
197                 try {
198                     File JavaDoc f = (File JavaDoc)i.next();
199                     log.info("---=== " + f + " ===---");
200                     for (int j = 0; j < producers.length; j++) {
201                         bitmaps[j] = producers[j].produce(f, context);
202                     }
203                     //Create combined image
204
if (bitmaps[0] == null) {
205                         throw new RuntimeException JavaDoc("First producer didn't return a bitmap."
206                                 + " Cannot continue.");
207                     }
208                     BufferedImage JavaDoc combined = BitmapComparator.buildCompareImage(bitmaps);
209                     
210                     //Save combined bitmap as PNG file
211
File JavaDoc outputFile = new File JavaDoc(targetDir, f.getName() + "._combined.png");
212                     saveAsPNG(combined, outputFile);
213
214                     if (createDiffs) {
215                         for (int k = 1; k < bitmaps.length; k++) {
216                             BufferedImage JavaDoc diff = BitmapComparator.buildDiffImage(
217                                     bitmaps[0], bitmaps[k]);
218                             outputFile = new File JavaDoc(targetDir, f.getName() + "._diff" + k + ".png");
219                             saveAsPNG(diff, outputFile);
220                         }
221                     }
222                     //Release memory as soon as possible. These images are huge!
223
for (int k = 0; k < bitmaps.length; k++) {
224                         bitmaps[k] = null;
225                     }
226                 } catch (RuntimeException JavaDoc e) {
227                     System.out.println("Catching RE: " + e.getMessage());
228                     if (stopOnException) {
229                         System.out.println("rethrowing...");
230                         throw e;
231                     }
232                 }
233                 maxfiles = (maxfiles < 0 ? maxfiles : maxfiles - 1);
234                 if (maxfiles == 0) {
235                     break;
236                 }
237             }
238         } catch (IOException JavaDoc ioe) {
239             log.error("I/O problem while processing", ioe);
240             throw new RuntimeException JavaDoc("I/O problem: " + ioe.getMessage());
241         } catch (ConfigurationException JavaDoc e) {
242             log.error("Error while configuring BatchDiffer", e);
243             throw new RuntimeException JavaDoc("Error while configuring BatchDiffer: " + e.getMessage());
244         }
245     }
246     
247     private BitmapProducer[] getProducers(Configuration cfg) {
248         Configuration[] children = cfg.getChildren("producer");
249         BitmapProducer[] producers = new BitmapProducer[children.length];
250         for (int i = 0; i < children.length; i++) {
251             try {
252                 Class JavaDoc clazz = Class.forName(children[i].getAttribute("classname"));
253                 producers[i] = (BitmapProducer)clazz.newInstance();
254                 ContainerUtil.configure(producers[i], children[i]);
255             } catch (Exception JavaDoc e) {
256                 log.error("Error setting up producers", e);
257                 throw new RuntimeException JavaDoc("Error while setting up producers");
258             }
259         }
260         return producers;
261     }
262     
263     /**
264      * Main method.
265      * @param args command-line arguments
266      */

267     public static void main(String JavaDoc[] args) {
268         try {
269             if (args.length == 0) {
270                 System.err.println("Configuration file is missing!");
271                 printUsage();
272                 System.exit(-1);
273             }
274             File JavaDoc cfgFile = new File JavaDoc(args[0]);
275             if (!cfgFile.exists()) {
276                 System.err.println("Configuration file cannot be found: " + args[0]);
277                 printUsage();
278                 System.exit(-1);
279             }
280      
281             Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
282             BatchDiffer differ = new BatchDiffer();
283             differ.runBatch(cfgFile);
284             
285             System.out.println("Regular exit...");
286         } catch (Exception JavaDoc e) {
287             System.out.println("Exception caugth...");
288             e.printStackTrace();
289         }
290     }
291     
292 }
293
Popular Tags