KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > fop > layoutengine > LayoutEngineTester


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
18 /* $Id: LayoutEngineTester.java 426576 2006-07-28 15:44:37Z jeremias $ */
19
20 package org.apache.fop.layoutengine;
21
22 import java.io.File JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.lang.reflect.Constructor JavaDoc;
25 import java.util.Iterator JavaDoc;
26 import java.util.List JavaDoc;
27 import java.util.Map JavaDoc;
28
29 import javax.xml.parsers.DocumentBuilder JavaDoc;
30 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
31 import javax.xml.parsers.ParserConfigurationException JavaDoc;
32 import javax.xml.transform.Result JavaDoc;
33 import javax.xml.transform.Source JavaDoc;
34 import javax.xml.transform.Templates JavaDoc;
35 import javax.xml.transform.Transformer JavaDoc;
36 import javax.xml.transform.TransformerConfigurationException JavaDoc;
37 import javax.xml.transform.TransformerException JavaDoc;
38 import javax.xml.transform.dom.DOMResult JavaDoc;
39 import javax.xml.transform.dom.DOMSource JavaDoc;
40 import javax.xml.transform.sax.SAXResult JavaDoc;
41 import javax.xml.transform.sax.SAXTransformerFactory JavaDoc;
42 import javax.xml.transform.sax.TransformerHandler JavaDoc;
43 import javax.xml.transform.stream.StreamResult JavaDoc;
44 import javax.xml.transform.stream.StreamSource JavaDoc;
45
46 import org.apache.fop.apps.FOUserAgent;
47 import org.apache.fop.apps.Fop;
48 import org.apache.fop.apps.FopFactory;
49 import org.apache.fop.apps.FormattingResults;
50 import org.apache.fop.layoutmgr.ElementListObserver;
51 import org.apache.fop.render.xml.XMLRenderer;
52 import org.apache.xpath.XPathAPI;
53 import org.apache.xpath.objects.XObject;
54 import org.w3c.dom.Document JavaDoc;
55 import org.w3c.dom.Element JavaDoc;
56 import org.w3c.dom.Node JavaDoc;
57 import org.w3c.dom.NodeList JavaDoc;
58 import org.xml.sax.SAXException JavaDoc;
59
60 /**
61  * Class for testing the FOP's layout engine using testcases specified in XML
62  * files.
63  */

64 public class LayoutEngineTester {
65
66     private static final Map JavaDoc CHECK_CLASSES = new java.util.HashMap JavaDoc();
67     
68     // configure fopFactory as desired
69
private FopFactory fopFactory = FopFactory.newInstance();
70     private FopFactory fopFactoryWithBase14Kerning = FopFactory.newInstance();
71     
72     private SAXTransformerFactory JavaDoc tfactory
73             = (SAXTransformerFactory JavaDoc)SAXTransformerFactory.newInstance();
74
75     private Templates JavaDoc testcase2fo;
76     private Templates JavaDoc testcase2checks;
77     
78     private File JavaDoc areaTreeBackupDir;
79     
80     static {
81         CHECK_CLASSES.put("true", TrueCheck.class);
82         CHECK_CLASSES.put("eval", EvalCheck.class);
83         CHECK_CLASSES.put("element-list", ElementListCheck.class);
84         CHECK_CLASSES.put("result", ResultCheck.class);
85     }
86     
87     /**
88      * Constructs a new instance.
89      * @param areaTreeBackupDir Optional directory that receives the generated
90      * area tree XML files. May be null.
91      */

92     public LayoutEngineTester(File JavaDoc areaTreeBackupDir) {
93         this.areaTreeBackupDir = areaTreeBackupDir;
94         fopFactory.setBase14KerningEnabled(false);
95         fopFactoryWithBase14Kerning.setBase14KerningEnabled(true);
96     }
97     
98     private Templates JavaDoc getTestcase2FOStylesheet() throws TransformerConfigurationException JavaDoc {
99         if (testcase2fo == null) {
100             //Load and cache stylesheet
101
Source JavaDoc src = new StreamSource JavaDoc(new File JavaDoc("test/layoutengine/testcase2fo.xsl"));
102             testcase2fo = tfactory.newTemplates(src);
103         }
104         return testcase2fo;
105     }
106     
107     private Templates JavaDoc getTestcase2ChecksStylesheet() throws TransformerConfigurationException JavaDoc {
108         if (testcase2checks == null) {
109             //Load and cache stylesheet
110
Source JavaDoc src = new StreamSource JavaDoc(new File JavaDoc("test/layoutengine/testcase2checks.xsl"));
111             testcase2checks = tfactory.newTemplates(src);
112         }
113         return testcase2checks;
114     }
115     
116     /**
117      * Runs a single layout engine test case.
118      * @param testFile Test case to run
119      * @throws TransformerException In case of an XSLT/JAXP problem
120      * @throws IOException In case of an I/O problem
121      * @throws SAXException In case of a problem during SAX processing
122      * @throws ParserConfigurationException In case of a problem with the XML parser setup
123      */

124     public void runTest(File JavaDoc testFile)
125             throws TransformerException JavaDoc, SAXException JavaDoc, IOException JavaDoc, ParserConfigurationException JavaDoc {
126         
127         DOMResult JavaDoc domres = new DOMResult JavaDoc();
128
129         ElementListCollector elCollector = new ElementListCollector();
130         ElementListObserver.addObserver(elCollector);
131         
132         Fop fop;
133
134         try {
135             DocumentBuilderFactory JavaDoc dbf = DocumentBuilderFactory.newInstance();
136             dbf.setNamespaceAware(true);
137             dbf.setValidating(false);
138             DocumentBuilder JavaDoc builder = dbf.newDocumentBuilder();
139             Document JavaDoc testDoc = builder.parse(testFile);
140             
141             XObject xo = XPathAPI.eval(testDoc, "/testcase/cfg/base14kerning");
142             String JavaDoc s = xo.str();
143             boolean base14kerning = ("true".equalsIgnoreCase(s));
144             FopFactory effFactory = (base14kerning ? fopFactoryWithBase14Kerning : fopFactory);
145             
146             //Setup Transformer to convert the testcase XML to XSL-FO
147
Transformer JavaDoc transformer = getTestcase2FOStylesheet().newTransformer();
148             Source JavaDoc src = new DOMSource JavaDoc(testDoc);
149             
150             //Setup Transformer to convert the area tree to a DOM
151
TransformerHandler JavaDoc athandler = tfactory.newTransformerHandler();
152             athandler.setResult(domres);
153             
154             //Setup FOP for area tree rendering
155
FOUserAgent ua = effFactory.newFOUserAgent();
156             ua.setBaseURL(testFile.getParentFile().toURL().toString());
157             XMLRenderer atrenderer = new XMLRenderer();
158             atrenderer.setUserAgent(ua);
159             atrenderer.setContentHandler(athandler);
160             ua.setRendererOverride(atrenderer);
161             fop = effFactory.newFop(ua);
162             
163             SAXResult JavaDoc fores = new SAXResult JavaDoc(fop.getDefaultHandler());
164             transformer.transform(src, fores);
165         } finally {
166             ElementListObserver.removeObserver(elCollector);
167         }
168         
169         Document JavaDoc doc = (Document JavaDoc)domres.getNode();
170         if (this.areaTreeBackupDir != null) {
171             saveAreaTreeXML(doc, new File JavaDoc(this.areaTreeBackupDir, testFile.getName() + ".at.xml"));
172         }
173         FormattingResults results = fop.getResults();
174         LayoutResult result = new LayoutResult(doc, elCollector, results);
175         checkAll(testFile, result);
176     }
177     
178     /**
179      * Factory method to create checks from DOM elements.
180      * @param el DOM element to create the check from
181      * @return The newly create check
182      */

183     protected LayoutEngineCheck createCheck(Element JavaDoc el) {
184         String JavaDoc name = el.getTagName();
185         Class JavaDoc clazz = (Class JavaDoc)CHECK_CLASSES.get(name);
186         if (clazz != null) {
187             try {
188                 Constructor JavaDoc c = clazz.getDeclaredConstructor(new Class JavaDoc[] {Node JavaDoc.class});
189                 LayoutEngineCheck instance = (LayoutEngineCheck)c.newInstance(new Object JavaDoc[] {el});
190                 return instance;
191             } catch (Exception JavaDoc e) {
192                 throw new RuntimeException JavaDoc("Error while instantiating check '"
193                         + name + "': " + e.getMessage());
194             }
195         } else {
196             throw new IllegalArgumentException JavaDoc("No check class found: " + name);
197         }
198     }
199     
200     /**
201      * Perform all checks on the area tree.
202      * @param testFile Test case XML file
203      * @param result The layout results
204      * @throws TransformerException if a problem occurs in XSLT/JAXP
205      */

206     protected void checkAll(File JavaDoc testFile, LayoutResult result) throws TransformerException JavaDoc {
207         Transformer JavaDoc transformer = getTestcase2ChecksStylesheet().newTransformer();
208         Source JavaDoc src = new StreamSource JavaDoc(testFile);
209         DOMResult JavaDoc res = new DOMResult JavaDoc();
210         transformer.transform(src, res);
211         
212         List JavaDoc checks = new java.util.ArrayList JavaDoc();
213         Document JavaDoc doc = (Document JavaDoc)res.getNode();
214         NodeList JavaDoc nodes = doc.getDocumentElement().getChildNodes();
215         for (int i = 0; i < nodes.getLength(); i++) {
216             Node JavaDoc node = nodes.item(i);
217             if (node instanceof Element JavaDoc) {
218                 checks.add(createCheck((Element JavaDoc)node));
219             }
220         }
221         
222         if (checks.size() == 0) {
223             throw new RuntimeException JavaDoc("No checks are available!");
224         }
225         Iterator JavaDoc i = checks.iterator();
226         while (i.hasNext()) {
227             LayoutEngineCheck check = (LayoutEngineCheck)i.next();
228             check.check(result);
229         }
230     }
231     
232     /**
233      * Save the area tree XML for later inspection.
234      * @param doc area tree as a DOM document
235      * @param target target file
236      * @throws TransformerException if a problem occurs during serialization
237      */

238     protected void saveAreaTreeXML(Document JavaDoc doc, File JavaDoc target) throws TransformerException JavaDoc {
239         Transformer JavaDoc transformer = tfactory.newTransformer();
240         Source JavaDoc src = new DOMSource JavaDoc(doc);
241         Result JavaDoc res = new StreamResult JavaDoc(target);
242         transformer.transform(src, res);
243     }
244 }
245
Popular Tags