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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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. /* $Id$ */
  18. package org.apache.fop.visual;
  19. import java.awt.image.BufferedImage;
  20. import java.awt.image.RenderedImage;
  21. import java.io.File;
  22. import java.io.FileOutputStream;
  23. import java.io.IOException;
  24. import java.io.OutputStream;
  25. import java.util.Collection;
  26. import java.util.Iterator;
  27. import javax.xml.transform.TransformerConfigurationException;
  28. import javax.xml.transform.stream.StreamSource;
  29. import org.apache.avalon.framework.configuration.Configuration;
  30. import org.apache.avalon.framework.configuration.ConfigurationException;
  31. import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
  32. import org.apache.avalon.framework.container.ContainerUtil;
  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.apache.xmlgraphics.image.writer.ImageWriter;
  41. import org.apache.xmlgraphics.image.writer.ImageWriterRegistry;
  42. import org.xml.sax.SAXException;
  43. /**
  44. * This class is used to visually diff bitmap images created through various sources.
  45. * <p>
  46. * Here's what the configuration format looks like:
  47. * <p>
  48. * <pre>
  49. * <batch-diff>
  50. * <source-directory>C:/Dev/FOP/trunk/test/layoutengine</source-directory>
  51. * <filter-disabled>false</filter-disabled>
  52. * <max-files>10</max-files>
  53. * <target-directory>C:/Temp/diff-out</target-directory>
  54. * <resolution>100</resolution>
  55. * <stop-on-exception>false</stop-on-exception>
  56. * <create-diffs>false</create-diffs>
  57. * <stylesheet>C:/Dev/FOP/trunk/test/layoutengine/testcase2fo.xsl</stylesheet>
  58. * <producers>
  59. * <producer classname="org.apache.fop.visual.BitmapProducerJava2D">
  60. * <delete-temp-files>false</delete-temp-files>
  61. * </producer>
  62. * <producer classname="org.apache.fop.visual.ReferenceBitmapLoader">
  63. * <directory>C:/Temp/diff-bitmaps</directory>
  64. * </producer>
  65. * </producers>
  66. * </batch-diff>
  67. * </pre>
  68. * <p>
  69. * The optional "filter-disabled" element determines whether the source files should be filtered
  70. * using the same "disabled-testcases.txt" file used for the layout engine tests. Default: true
  71. * <p>
  72. * The optional "max-files" element controls how many files at maximum should be processed.
  73. * Default is to process all the files found.
  74. * <p>
  75. * The optional "resolution" element controls the requested bitmap resolution in dpi for the
  76. * generated bitmaps. Defaults to 72dpi.
  77. * <p>
  78. * The optional "stop-on-exception" element controls whether the batch should be aborted when
  79. * an exception is caught. Defaults to true.
  80. * <p>
  81. * The optional "create-diffs" element controls whether the diff images should be created.
  82. * Defaults to true.
  83. * <p>
  84. * The optional "stylesheet" element allows you to supply an XSLT stylesheet to preprocess all
  85. * source files with. Default: no stylesheet, identity transform.
  86. * <p>
  87. * The "producers" element contains a list of producer implementations with configuration.
  88. * The "classname" attribute specifies the fully qualified class name for the implementation.
  89. */
  90. public class BatchDiffer {
  91. /** Logger */
  92. protected static Log log = LogFactory.getLog(BatchDiffer.class);
  93. /**
  94. * Prints the usage of this app to stdout.
  95. */
  96. public static void printUsage() {
  97. System.out.println("Usage:");
  98. System.out.println("java " + BatchDiffer.class.getName() + " <cfgfile>");
  99. System.out.println();
  100. System.out.println("<cfgfile>: Path to an XML file with the configuration"
  101. + " for the batch run.");
  102. }
  103. /**
  104. * Saves a BufferedImage as a PNG file.
  105. * @param bitmap the bitmap to encode
  106. * @param outputFile the target file
  107. * @throws IOException in case of an I/O problem
  108. */
  109. public static void saveAsPNG(RenderedImage bitmap, File outputFile) throws IOException {
  110. OutputStream out = new FileOutputStream(outputFile);
  111. try {
  112. ImageWriter writer = ImageWriterRegistry.getInstance().getWriterFor("image/png");
  113. writer.writeImage(bitmap, out);
  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. File f = (File)i.next();
  176. try {
  177. log.info("---=== " + f + " ===---");
  178. long[] times = new long[producers.length];
  179. for (int j = 0; j < producers.length; j++) {
  180. times[j] = System.currentTimeMillis();
  181. bitmaps[j] = producers[j].produce(f, context);
  182. times[j] = System.currentTimeMillis() - times[j];
  183. }
  184. if (log.isDebugEnabled()) {
  185. StringBuffer sb = new StringBuffer("Bitmap production times: ");
  186. for (int j = 0; j < producers.length; j++) {
  187. if (j > 0) {
  188. sb.append(", ");
  189. }
  190. sb.append(times[j]).append("ms");
  191. }
  192. log.debug(sb.toString());
  193. }
  194. //Create combined image
  195. if (bitmaps[0] == null) {
  196. throw new RuntimeException("First producer didn't return a bitmap for "
  197. + f + ". Cannot continue.");
  198. }
  199. BufferedImage combined = BitmapComparator.buildCompareImage(bitmaps);
  200. //Save combined bitmap as PNG file
  201. File outputFile = new File(targetDir, f.getName() + "._combined.png");
  202. saveAsPNG(combined, outputFile);
  203. if (createDiffs) {
  204. for (int k = 1; k < bitmaps.length; k++) {
  205. BufferedImage diff = BitmapComparator.buildDiffImage(
  206. bitmaps[0], bitmaps[k]);
  207. outputFile = new File(targetDir, f.getName() + "._diff" + k + ".png");
  208. saveAsPNG(diff, outputFile);
  209. }
  210. }
  211. //Release memory as soon as possible. These images are huge!
  212. for (int k = 0; k < bitmaps.length; k++) {
  213. bitmaps[k] = null;
  214. }
  215. } catch (RuntimeException e) {
  216. log.error("Catching RE on file " + f + ": " + e.getMessage());
  217. if (stopOnException) {
  218. log.error("rethrowing...");
  219. throw e;
  220. }
  221. }
  222. maxfiles = (maxfiles < 0 ? maxfiles : maxfiles - 1);
  223. if (maxfiles == 0) {
  224. break;
  225. }
  226. }
  227. } catch (IOException ioe) {
  228. log.error("I/O problem while processing", ioe);
  229. throw new RuntimeException("I/O problem: " + ioe.getMessage());
  230. } catch (ConfigurationException e) {
  231. log.error("Error while configuring BatchDiffer", e);
  232. throw new RuntimeException("Error while configuring BatchDiffer: " + e.getMessage());
  233. }
  234. }
  235. private BitmapProducer[] getProducers(Configuration cfg) {
  236. Configuration[] children = cfg.getChildren("producer");
  237. BitmapProducer[] producers = new BitmapProducer[children.length];
  238. for (int i = 0; i < children.length; i++) {
  239. try {
  240. Class clazz = Class.forName(children[i].getAttribute("classname"));
  241. producers[i] = (BitmapProducer)clazz.newInstance();
  242. ContainerUtil.configure(producers[i], children[i]);
  243. } catch (Exception e) {
  244. log.error("Error setting up producers", e);
  245. throw new RuntimeException("Error while setting up producers");
  246. }
  247. }
  248. return producers;
  249. }
  250. /**
  251. * Main method.
  252. * @param args command-line arguments
  253. */
  254. public static void main(String[] args) {
  255. try {
  256. if (args.length == 0) {
  257. System.err.println("Configuration file is missing!");
  258. printUsage();
  259. System.exit(-1);
  260. }
  261. File cfgFile = new File(args[0]);
  262. if (!cfgFile.exists()) {
  263. System.err.println("Configuration file cannot be found: " + args[0]);
  264. printUsage();
  265. System.exit(-1);
  266. }
  267. Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
  268. BatchDiffer differ = new BatchDiffer();
  269. differ.runBatch(cfgFile);
  270. System.out.println("Regular exit...");
  271. } catch (Exception e) {
  272. System.out.println("Exception caugth...");
  273. e.printStackTrace();
  274. }
  275. }
  276. }