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

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