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.

LayoutEngineTester.java 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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.layoutengine;
  19. import java.io.File;
  20. import java.io.IOException;
  21. import java.lang.reflect.Constructor;
  22. import java.util.Iterator;
  23. import java.util.List;
  24. import java.util.Map;
  25. import javax.xml.parsers.DocumentBuilder;
  26. import javax.xml.parsers.DocumentBuilderFactory;
  27. import javax.xml.parsers.ParserConfigurationException;
  28. import javax.xml.transform.Result;
  29. import javax.xml.transform.Source;
  30. import javax.xml.transform.Templates;
  31. import javax.xml.transform.Transformer;
  32. import javax.xml.transform.TransformerConfigurationException;
  33. import javax.xml.transform.TransformerException;
  34. import javax.xml.transform.dom.DOMResult;
  35. import javax.xml.transform.dom.DOMSource;
  36. import javax.xml.transform.sax.SAXResult;
  37. import javax.xml.transform.sax.SAXTransformerFactory;
  38. import javax.xml.transform.sax.TransformerHandler;
  39. import javax.xml.transform.stream.StreamResult;
  40. import javax.xml.transform.stream.StreamSource;
  41. import org.w3c.dom.Document;
  42. import org.w3c.dom.Element;
  43. import org.w3c.dom.Node;
  44. import org.w3c.dom.NodeList;
  45. import org.xml.sax.SAXException;
  46. import org.apache.xpath.XPathAPI;
  47. import org.apache.xpath.objects.XObject;
  48. import org.apache.fop.apps.FOUserAgent;
  49. import org.apache.fop.apps.Fop;
  50. import org.apache.fop.apps.FopFactory;
  51. import org.apache.fop.apps.FormattingResults;
  52. import org.apache.fop.layoutmgr.ElementListObserver;
  53. import org.apache.fop.render.xml.XMLRenderer;
  54. import org.apache.fop.util.ConsoleEventListenerForTests;
  55. /**
  56. * Class for testing the FOP's layout engine using testcases specified in XML
  57. * files.
  58. */
  59. public class LayoutEngineTester {
  60. private static final Map CHECK_CLASSES = new java.util.HashMap();
  61. // configure fopFactory as desired
  62. private FopFactory fopFactory = FopFactory.newInstance();
  63. private FopFactory fopFactoryWithBase14Kerning = FopFactory.newInstance();
  64. private SAXTransformerFactory tfactory
  65. = (SAXTransformerFactory)SAXTransformerFactory.newInstance();
  66. private Templates testcase2fo;
  67. private Templates testcase2checks;
  68. private File areaTreeBackupDir;
  69. static {
  70. CHECK_CLASSES.put("true", TrueCheck.class);
  71. CHECK_CLASSES.put("eval", EvalCheck.class);
  72. CHECK_CLASSES.put("element-list", ElementListCheck.class);
  73. CHECK_CLASSES.put("result", ResultCheck.class);
  74. }
  75. /**
  76. * Constructs a new instance.
  77. * @param areaTreeBackupDir Optional directory that receives the generated
  78. * area tree XML files. May be null.
  79. */
  80. public LayoutEngineTester(File areaTreeBackupDir) {
  81. this.areaTreeBackupDir = areaTreeBackupDir;
  82. fopFactory.getFontManager().setBase14KerningEnabled(false);
  83. fopFactoryWithBase14Kerning.getFontManager().setBase14KerningEnabled(true);
  84. }
  85. private Templates getTestcase2FOStylesheet() throws TransformerConfigurationException {
  86. if (testcase2fo == null) {
  87. //Load and cache stylesheet
  88. Source src = new StreamSource(new File("test/layoutengine/testcase2fo.xsl"));
  89. testcase2fo = tfactory.newTemplates(src);
  90. }
  91. return testcase2fo;
  92. }
  93. private Templates getTestcase2ChecksStylesheet() throws TransformerConfigurationException {
  94. if (testcase2checks == null) {
  95. //Load and cache stylesheet
  96. Source src = new StreamSource(new File("test/layoutengine/testcase2checks.xsl"));
  97. testcase2checks = tfactory.newTemplates(src);
  98. }
  99. return testcase2checks;
  100. }
  101. /**
  102. * Runs a single layout engine test case.
  103. * @param testFile Test case to run
  104. * @throws TransformerException In case of an XSLT/JAXP problem
  105. * @throws IOException In case of an I/O problem
  106. * @throws SAXException In case of a problem during SAX processing
  107. * @throws ParserConfigurationException In case of a problem with the XML parser setup
  108. */
  109. public void runTest(File testFile)
  110. throws TransformerException, SAXException, IOException, ParserConfigurationException {
  111. DOMResult domres = new DOMResult();
  112. ElementListCollector elCollector = new ElementListCollector();
  113. ElementListObserver.addObserver(elCollector);
  114. Fop fop;
  115. try {
  116. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  117. dbf.setNamespaceAware(true);
  118. dbf.setValidating(false);
  119. DocumentBuilder builder = dbf.newDocumentBuilder();
  120. Document testDoc = builder.parse(testFile);
  121. XObject xo = XPathAPI.eval(testDoc, "/testcase/cfg/base14kerning");
  122. String s = xo.str();
  123. boolean base14kerning = ("true".equalsIgnoreCase(s));
  124. FopFactory effFactory = (base14kerning ? fopFactoryWithBase14Kerning : fopFactory);
  125. //Setup Transformer to convert the testcase XML to XSL-FO
  126. Transformer transformer = getTestcase2FOStylesheet().newTransformer();
  127. Source src = new DOMSource(testDoc);
  128. //Setup Transformer to convert the area tree to a DOM
  129. TransformerHandler athandler = tfactory.newTransformerHandler();
  130. athandler.setResult(domres);
  131. //Setup FOP for area tree rendering
  132. FOUserAgent ua = effFactory.newFOUserAgent();
  133. ua.setBaseURL(testFile.getParentFile().toURL().toString());
  134. ua.getEventBroadcaster().addEventListener(
  135. new ConsoleEventListenerForTests(testFile.getName()));
  136. XMLRenderer atrenderer = new XMLRenderer();
  137. atrenderer.setUserAgent(ua);
  138. atrenderer.setContentHandler(athandler);
  139. ua.setRendererOverride(atrenderer);
  140. fop = effFactory.newFop(ua);
  141. SAXResult fores = new SAXResult(fop.getDefaultHandler());
  142. transformer.transform(src, fores);
  143. } finally {
  144. ElementListObserver.removeObserver(elCollector);
  145. }
  146. Document doc = (Document)domres.getNode();
  147. if (this.areaTreeBackupDir != null) {
  148. saveAreaTreeXML(doc, new File(this.areaTreeBackupDir, testFile.getName() + ".at.xml"));
  149. }
  150. FormattingResults results = fop.getResults();
  151. LayoutResult result = new LayoutResult(doc, elCollector, results);
  152. checkAll(testFile, result);
  153. }
  154. /**
  155. * Factory method to create checks from DOM elements.
  156. * @param el DOM element to create the check from
  157. * @return The newly create check
  158. */
  159. protected LayoutEngineCheck createCheck(Element el) {
  160. String name = el.getTagName();
  161. Class clazz = (Class)CHECK_CLASSES.get(name);
  162. if (clazz != null) {
  163. try {
  164. Constructor c = clazz.getDeclaredConstructor(new Class[] {Node.class});
  165. LayoutEngineCheck instance = (LayoutEngineCheck)c.newInstance(new Object[] {el});
  166. return instance;
  167. } catch (Exception e) {
  168. throw new RuntimeException("Error while instantiating check '"
  169. + name + "': " + e.getMessage());
  170. }
  171. } else {
  172. throw new IllegalArgumentException("No check class found: " + name);
  173. }
  174. }
  175. /**
  176. * Perform all checks on the area tree.
  177. * @param testFile Test case XML file
  178. * @param result The layout results
  179. * @throws TransformerException if a problem occurs in XSLT/JAXP
  180. */
  181. protected void checkAll(File testFile, LayoutResult result) throws TransformerException {
  182. Transformer transformer = getTestcase2ChecksStylesheet().newTransformer();
  183. Source src = new StreamSource(testFile);
  184. DOMResult res = new DOMResult();
  185. transformer.transform(src, res);
  186. List checks = new java.util.ArrayList();
  187. Document doc = (Document)res.getNode();
  188. NodeList nodes = doc.getDocumentElement().getChildNodes();
  189. for (int i = 0; i < nodes.getLength(); i++) {
  190. Node node = nodes.item(i);
  191. if (node instanceof Element) {
  192. checks.add(createCheck((Element)node));
  193. }
  194. }
  195. if (checks.size() == 0) {
  196. throw new RuntimeException("No checks are available!");
  197. }
  198. Iterator i = checks.iterator();
  199. while (i.hasNext()) {
  200. LayoutEngineCheck check = (LayoutEngineCheck)i.next();
  201. check.check(result);
  202. }
  203. }
  204. /**
  205. * Save the area tree XML for later inspection.
  206. * @param doc area tree as a DOM document
  207. * @param target target file
  208. * @throws TransformerException if a problem occurs during serialization
  209. */
  210. protected void saveAreaTreeXML(Document doc, File target) throws TransformerException {
  211. Transformer transformer = tfactory.newTransformer();
  212. Source src = new DOMSource(doc);
  213. Result res = new StreamResult(target);
  214. transformer.transform(src, res);
  215. }
  216. }