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

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