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 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. * <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 "stylesheet" element allows you to supply an XSLT stylesheet to preprocess all
  75. * source files with. Default: no stylesheet, identity transform.
  76. * <p>
  77. * The "producers" element contains a list of producer implementations with configuration.
  78. * The "classname" attribute specifies the fully qualified class name for the implementation.
  79. */
  80. public class BatchDiffer {
  81. /** Logger */
  82. protected static Log log = LogFactory.getLog(BatchDiffer.class);
  83. /**
  84. * Prints the usage of this app to stdout.
  85. */
  86. public static void printUsage() {
  87. System.out.println("Usage:");
  88. System.out.println("java " + BatchDiffer.class.getName() + " <cfgfile>");
  89. System.out.println();
  90. System.out.println("<cfgfile>: Path to an XML file with the configuration"
  91. + " for the batch run.");
  92. }
  93. /**
  94. * Saves a BufferedImage as a PNG file.
  95. * @param bitmap the bitmap to encode
  96. * @param outputFile the target file
  97. * @throws IOException in case of an I/O problem
  98. */
  99. public static void saveAsPNG(BufferedImage bitmap, File outputFile) throws IOException {
  100. OutputStream out = new FileOutputStream(outputFile);
  101. try {
  102. PNGImageEncoder encoder = new PNGImageEncoder(
  103. out,
  104. PNGEncodeParam.getDefaultEncodeParam(bitmap));
  105. encoder.encode(bitmap);
  106. } finally {
  107. IOUtils.closeQuietly(out);
  108. }
  109. }
  110. /**
  111. * Runs the batch.
  112. * @param cfgFile configuration file to use
  113. * @throws ConfigurationException In case of a problem with the configuration
  114. * @throws SAXException In case of a problem during SAX processing
  115. * @throws IOException In case of a I/O problem
  116. */
  117. public void runBatch(File cfgFile)
  118. throws ConfigurationException, SAXException, IOException {
  119. DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder();
  120. Configuration cfg = cfgBuilder.buildFromFile(cfgFile);
  121. runBatch(cfg);
  122. }
  123. /**
  124. * Runs the batch
  125. * @param cfg Configuration for the batch
  126. * @throws TransformerConfigurationException
  127. */
  128. public void runBatch(Configuration cfg) {
  129. try {
  130. ProducerContext context = new ProducerContext();
  131. context.setResolution(cfg.getChild("resolution").getValueAsInteger(72));
  132. String xslt = cfg.getChild("stylesheet").getValue(null);
  133. if (xslt != null) {
  134. try {
  135. context.setTemplates(context.getTransformerFactory().newTemplates(
  136. new StreamSource(xslt)));
  137. } catch (TransformerConfigurationException e) {
  138. throw new RuntimeException("Error setting up stylesheet", e);
  139. }
  140. }
  141. BitmapProducer[] producers = getProducers(cfg.getChild("producers"));
  142. //Set up directories
  143. File srcDir = new File(cfg.getChild("source-directory").getValue());
  144. if (!srcDir.exists()) {
  145. throw new RuntimeException("source-directory does not exist: " + srcDir);
  146. }
  147. File targetDir = new File(cfg.getChild("target-directory").getValue());
  148. targetDir.mkdirs();
  149. if (!targetDir.exists()) {
  150. throw new RuntimeException("target-directory is invalid: " + targetDir);
  151. }
  152. context.setTargetDir(targetDir);
  153. //RUN!
  154. BufferedImage[] bitmaps = new BufferedImage[producers.length];
  155. IOFileFilter filter = new SuffixFileFilter(new String[] {".xml", ".fo"});
  156. //Same filtering as in layout engine tests
  157. if (cfg.getChild("filter-disabled").getValueAsBoolean(true)) {
  158. filter = LayoutEngineTestSuite.decorateWithDisabledList(filter);
  159. }
  160. int maxfiles = cfg.getChild("max-files").getValueAsInteger(-1);
  161. Collection files = FileUtils.listFiles(srcDir, filter, null);
  162. Iterator i = files.iterator();
  163. while (i.hasNext()) {
  164. File f = (File)i.next();
  165. log.info("---=== " + f + " ===---");
  166. for (int j = 0; j < producers.length; j++) {
  167. bitmaps[j] = producers[j].produce(f, context);
  168. }
  169. //Create combined image
  170. if (bitmaps[0] == null) {
  171. throw new RuntimeException("First producer didn't return a bitmap."
  172. + " Cannot continue.");
  173. }
  174. BufferedImage combined = BitmapComparator.buildCompareImage(bitmaps);
  175. //Save combined bitmap as PNG file
  176. File outputFile = new File(targetDir, f.getName() + "._combined.png");
  177. saveAsPNG(combined, outputFile);
  178. for (int k = 1; k < bitmaps.length; k++) {
  179. BufferedImage diff = BitmapComparator.buildDiffImage(bitmaps[0], bitmaps[k]);
  180. outputFile = new File(targetDir, f.getName() + "._diff" + k + ".png");
  181. saveAsPNG(diff, outputFile);
  182. }
  183. maxfiles = (maxfiles < 0 ? maxfiles : maxfiles - 1);
  184. if (maxfiles == 0) {
  185. break;
  186. }
  187. }
  188. } catch (IOException ioe) {
  189. log.error("I/O problem while processing", ioe);
  190. throw new RuntimeException("I/O problem: " + ioe.getMessage());
  191. } catch (ConfigurationException e) {
  192. log.error("Error while configuring BatchDiffer", e);
  193. throw new RuntimeException("Error while configuring BatchDiffer: " + e.getMessage());
  194. }
  195. }
  196. private BitmapProducer[] getProducers(Configuration cfg) {
  197. Configuration[] children = cfg.getChildren("producer");
  198. BitmapProducer[] producers = new BitmapProducer[children.length];
  199. for (int i = 0; i < children.length; i++) {
  200. try {
  201. Class clazz = Class.forName(children[i].getAttribute("classname"));
  202. producers[i] = (BitmapProducer)clazz.newInstance();
  203. ContainerUtil.configure(producers[i], children[i]);
  204. } catch (Exception e) {
  205. throw new RuntimeException("Error while setting up producers", e);
  206. }
  207. }
  208. return producers;
  209. }
  210. /**
  211. * Main method.
  212. * @param args command-line arguments
  213. */
  214. public static void main(String[] args) {
  215. try {
  216. if (args.length == 0) {
  217. System.err.println("Configuration file is missing!");
  218. printUsage();
  219. System.exit(-1);
  220. }
  221. File cfgFile = new File(args[0]);
  222. if (!cfgFile.exists()) {
  223. System.err.println("Configuration file cannot be found: " + args[0]);
  224. printUsage();
  225. System.exit(-1);
  226. }
  227. BatchDiffer differ = new BatchDiffer();
  228. differ.runBatch(cfgFile);
  229. } catch (Exception e) {
  230. e.printStackTrace();
  231. }
  232. }
  233. }