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

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