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.

BatchDiffer.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. /*
  2. * Copyright 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.visual;
  18. import java.awt.image.BufferedImage;
  19. import java.io.File;
  20. import java.io.FileOutputStream;
  21. import java.io.IOException;
  22. import java.io.OutputStream;
  23. import java.util.Collection;
  24. import java.util.Iterator;
  25. import javax.xml.transform.TransformerConfigurationException;
  26. import javax.xml.transform.stream.StreamSource;
  27. import org.apache.avalon.framework.configuration.Configuration;
  28. import org.apache.avalon.framework.configuration.ConfigurationException;
  29. import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
  30. import org.apache.avalon.framework.container.ContainerUtil;
  31. import org.apache.batik.ext.awt.image.codec.PNGEncodeParam;
  32. import org.apache.batik.ext.awt.image.codec.PNGImageEncoder;
  33. import org.apache.commons.io.FileUtils;
  34. import org.apache.commons.io.IOUtils;
  35. import org.apache.commons.io.filefilter.IOFileFilter;
  36. import org.apache.commons.io.filefilter.SuffixFileFilter;
  37. import org.apache.commons.logging.Log;
  38. import org.apache.commons.logging.LogFactory;
  39. import org.apache.fop.layoutengine.LayoutEngineTestSuite;
  40. import org.xml.sax.SAXException;
  41. /**
  42. * This class is used to visually diff bitmap images created through various sources.
  43. * <p>
  44. * Here's what the configuration format looks like:
  45. * <p>
  46. * <pre>
  47. * <batch-diff>
  48. * <source-directory>C:/Dev/FOP/trunk/test/layoutengine</source-directory>
  49. * <filter-disabled>false</filter-disabled>
  50. * <max-files>10</max-files>
  51. * <target-directory>C:/Temp/diff-out</target-directory>
  52. * <resolution>100</resolution>
  53. * <stop-on-exception>false</stop-on-exception>
  54. * <create-diffs>false</create-diffs>
  55. * <stylesheet>C:/Dev/FOP/trunk/test/layoutengine/testcase2fo.xsl</stylesheet>
  56. * <producers>
  57. * <producer classname="org.apache.fop.visual.BitmapProducerJava2D">
  58. * <delete-temp-files>false</delete-temp-files>
  59. * </producer>
  60. * <producer classname="org.apache.fop.visual.ReferenceBitmapLoader">
  61. * <directory>C:/Temp/diff-bitmaps</directory>
  62. * </producer>
  63. * </producers>
  64. * </batch-diff>
  65. * </pre>
  66. * <p>
  67. * The optional "filter-disabled" element determines whether the source files should be filtered
  68. * using the same "disabled-testcases.txt" file used for the layout engine tests. Default: true
  69. * <p>
  70. * The optional "max-files" element controls how many files at maximum should be processed.
  71. * Default is to process all the files found.
  72. * <p>
  73. * The optional "resolution" element controls the requested bitmap resolution in dpi for the
  74. * generated bitmaps. Defaults to 72dpi.
  75. * <p>
  76. * The optional "stop-on-exception" element controls whether the batch should be aborted when
  77. * an exception is caught. Defaults to true.
  78. * <p>
  79. * The optional "create-diffs" element controls whether the diff images should be created.
  80. * Defaults to true.
  81. * <p>
  82. * The optional "stylesheet" element allows you to supply an XSLT stylesheet to preprocess all
  83. * source files with. Default: no stylesheet, identity transform.
  84. * <p>
  85. * The "producers" element contains a list of producer implementations with configuration.
  86. * The "classname" attribute specifies the fully qualified class name for the implementation.
  87. */
  88. public class BatchDiffer {
  89. /** Logger */
  90. protected static Log log = LogFactory.getLog(BatchDiffer.class);
  91. /**
  92. * Prints the usage of this app to stdout.
  93. */
  94. public static void printUsage() {
  95. System.out.println("Usage:");
  96. System.out.println("java " + BatchDiffer.class.getName() + " <cfgfile>");
  97. System.out.println();
  98. System.out.println("<cfgfile>: Path to an XML file with the configuration"
  99. + " for the batch run.");
  100. }
  101. /**
  102. * Saves a BufferedImage as a PNG file.
  103. * @param bitmap the bitmap to encode
  104. * @param outputFile the target file
  105. * @throws IOException in case of an I/O problem
  106. */
  107. public static void saveAsPNG(BufferedImage bitmap, File outputFile) throws IOException {
  108. OutputStream out = new FileOutputStream(outputFile);
  109. try {
  110. PNGImageEncoder encoder = new PNGImageEncoder(
  111. out,
  112. PNGEncodeParam.getDefaultEncodeParam(bitmap));
  113. encoder.encode(bitmap);
  114. } finally {
  115. IOUtils.closeQuietly(out);
  116. }
  117. }
  118. /**
  119. * Runs the batch.
  120. * @param cfgFile configuration file to use
  121. * @throws ConfigurationException In case of a problem with the configuration
  122. * @throws SAXException In case of a problem during SAX processing
  123. * @throws IOException In case of a I/O problem
  124. */
  125. public void runBatch(File cfgFile)
  126. throws ConfigurationException, SAXException, IOException {
  127. DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder();
  128. Configuration cfg = cfgBuilder.buildFromFile(cfgFile);
  129. runBatch(cfg);
  130. }
  131. /**
  132. * Runs the batch
  133. * @param cfg Configuration for the batch
  134. * @throws TransformerConfigurationException
  135. */
  136. public void runBatch(Configuration cfg) {
  137. try {
  138. ProducerContext context = new ProducerContext();
  139. context.setTargetResolution(cfg.getChild("resolution").getValueAsInteger(72));
  140. String xslt = cfg.getChild("stylesheet").getValue(null);
  141. if (xslt != null) {
  142. try {
  143. context.setTemplates(context.getTransformerFactory().newTemplates(
  144. new StreamSource(xslt)));
  145. } catch (TransformerConfigurationException e) {
  146. log.error("Error setting up stylesheet", e);
  147. throw new RuntimeException("Error setting up stylesheet");
  148. }
  149. }
  150. BitmapProducer[] producers = getProducers(cfg.getChild("producers"));
  151. //Set up directories
  152. File srcDir = new File(cfg.getChild("source-directory").getValue());
  153. if (!srcDir.exists()) {
  154. throw new RuntimeException("source-directory does not exist: " + srcDir);
  155. }
  156. File targetDir = new File(cfg.getChild("target-directory").getValue());
  157. targetDir.mkdirs();
  158. if (!targetDir.exists()) {
  159. throw new RuntimeException("target-directory is invalid: " + targetDir);
  160. }
  161. context.setTargetDir(targetDir);
  162. boolean stopOnException = cfg.getChild("stop-on-exception").getValueAsBoolean(true);
  163. boolean createDiffs = cfg.getChild("create-diffs").getValueAsBoolean(true);
  164. //RUN!
  165. BufferedImage[] bitmaps = new BufferedImage[producers.length];
  166. IOFileFilter filter = new SuffixFileFilter(new String[] {".xml", ".fo"});
  167. //Same filtering as in layout engine tests
  168. if (cfg.getChild("filter-disabled").getValueAsBoolean(true)) {
  169. filter = LayoutEngineTestSuite.decorateWithDisabledList(filter);
  170. }
  171. int maxfiles = cfg.getChild("max-files").getValueAsInteger(-1);
  172. Collection files = FileUtils.listFiles(srcDir, filter, null);
  173. Iterator i = files.iterator();
  174. while (i.hasNext()) {
  175. try {
  176. File f = (File)i.next();
  177. log.info("---=== " + f + " ===---");
  178. for (int j = 0; j < producers.length; j++) {
  179. bitmaps[j] = producers[j].produce(f, context);
  180. }
  181. //Create combined image
  182. if (bitmaps[0] == null) {
  183. throw new RuntimeException("First producer didn't return a bitmap."
  184. + " Cannot continue.");
  185. }
  186. BufferedImage combined = BitmapComparator.buildCompareImage(bitmaps);
  187. //Save combined bitmap as PNG file
  188. File outputFile = new File(targetDir, f.getName() + "._combined.png");
  189. saveAsPNG(combined, outputFile);
  190. if (createDiffs) {
  191. for (int k = 1; k < bitmaps.length; k++) {
  192. BufferedImage diff = BitmapComparator.buildDiffImage(
  193. bitmaps[0], bitmaps[k]);
  194. outputFile = new File(targetDir, f.getName() + "._diff" + k + ".png");
  195. saveAsPNG(diff, outputFile);
  196. }
  197. }
  198. //Release memory as soon as possible. These images are huge!
  199. for (int k = 0; k < bitmaps.length; k++) {
  200. bitmaps[k] = null;
  201. }
  202. } catch (RuntimeException e) {
  203. System.out.println("Catching RE: " + e.getMessage());
  204. if (stopOnException) {
  205. System.out.println("rethrowing...");
  206. throw e;
  207. }
  208. }
  209. maxfiles = (maxfiles < 0 ? maxfiles : maxfiles - 1);
  210. if (maxfiles == 0) {
  211. break;
  212. }
  213. }
  214. } catch (IOException ioe) {
  215. log.error("I/O problem while processing", ioe);
  216. throw new RuntimeException("I/O problem: " + ioe.getMessage());
  217. } catch (ConfigurationException e) {
  218. log.error("Error while configuring BatchDiffer", e);
  219. throw new RuntimeException("Error while configuring BatchDiffer: " + e.getMessage());
  220. }
  221. }
  222. private BitmapProducer[] getProducers(Configuration cfg) {
  223. Configuration[] children = cfg.getChildren("producer");
  224. BitmapProducer[] producers = new BitmapProducer[children.length];
  225. for (int i = 0; i < children.length; i++) {
  226. try {
  227. Class clazz = Class.forName(children[i].getAttribute("classname"));
  228. producers[i] = (BitmapProducer)clazz.newInstance();
  229. ContainerUtil.configure(producers[i], children[i]);
  230. } catch (Exception e) {
  231. log.error("Error setting up producers", e);
  232. throw new RuntimeException("Error while setting up producers");
  233. }
  234. }
  235. return producers;
  236. }
  237. /**
  238. * Main method.
  239. * @param args command-line arguments
  240. */
  241. public static void main(String[] args) {
  242. try {
  243. if (args.length == 0) {
  244. System.err.println("Configuration file is missing!");
  245. printUsage();
  246. System.exit(-1);
  247. }
  248. File cfgFile = new File(args[0]);
  249. if (!cfgFile.exists()) {
  250. System.err.println("Configuration file cannot be found: " + args[0]);
  251. printUsage();
  252. System.exit(-1);
  253. }
  254. Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
  255. BatchDiffer differ = new BatchDiffer();
  256. differ.runBatch(cfgFile);
  257. System.out.println("Regular exit...");
  258. } catch (Exception e) {
  259. System.out.println("Exception caugth...");
  260. e.printStackTrace();
  261. }
  262. }
  263. }