aboutsummaryrefslogtreecommitdiffstats
path: root/test/java/org/apache/fop/intermediate/AbstractIntermediateTestCase.java
blob: 63e293afe9008771f0ceb0470c853d6acdf8efa7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* $Id$ */

package org.apache.fop.intermediate;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;

import javax.xml.transform.ErrorListener;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.custommonkey.xmlunit.XMLTestCase;
import org.w3c.dom.Document;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;

import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.MimeConstants;
import org.apache.fop.util.ConsoleEventListenerForTests;

/**
 * Abstract base class for intermediate format tests.
 */
public abstract class AbstractIntermediateTestCase extends XMLTestCase {

    /** the FOP factory */
    protected static FopFactory fopFactory = FopFactory.newInstance();

    /** the JAXP transformer factory */
    protected static SAXTransformerFactory tFactory
            = (SAXTransformerFactory)SAXTransformerFactory.newInstance();

    /** the main base directory for tests */
    protected File mainDir = new File("test/layoutengine");
    /** the directory containing the tests */
    protected File testDir = new File(mainDir, "standard-testcases");
    /** the output directory for any files generated by the tests */
    protected File outputDir;

    private static Templates stylesheet = null;

    /** the test file */
    protected File testFile;
    /** the intermediate format document as DOM */
    protected Document intermediate;

    /**
     * Constructor for the test suite that is used for each test file.
     * @param testFile the test file to run
     */
    public AbstractIntermediateTestCase(File testFile) {
        super(testFile.getName());
        this.testFile = testFile;
    }

    /** {@inheritDoc} */
    protected void setUp() throws Exception {
        super.setUp();
        setupOutputDirectory();
        intermediate = buildIntermediateDocument(
                new StreamSource(testFile), getStylesheet());
        if (outputDir != null) {
            saveDOM(intermediate, new File(outputDir,
                    getName() + ".1" + getIntermediateFileExtension()));
        }
    }

    /** {@inheritDoc} */
    protected void tearDown() throws Exception {
        this.intermediate = null; //Release memory
        super.tearDown();
    }

    /**
     * Returns the file extension for the intermediate file format.
     * @return the file extension
     */
    protected abstract String getIntermediateFileExtension();

    /**
     * Returns the MIME type for which to test or to mimic for the intermediate format.
     * @return the MIME type
     */
    protected String getTargetMIME() {
        return MimeConstants.MIME_PDF;
    }

    /**
     * Builds an intermediate format document from a source file.
     * @param source the source file
     * @param templates the (optional) stylesheet
     * @return the intermediate format document as a DOM
     * @throws Exception if an error occurs while processing the document
     */
    protected abstract Document buildIntermediateDocument(
            Source source, Templates templates) throws Exception;

    /**
     * Returns the stylesheet that transforms layout engine test cases into normal FO files.
     * @return the stylesheet
     * @throws TransformerConfigurationException if the stylesheet cannot be instantiated
     */
    protected Templates getStylesheet() throws TransformerConfigurationException {
        if (stylesheet == null) {
            File xsltFile = new File(mainDir, "testcase2fo.xsl");
            stylesheet = tFactory.newTemplates(new StreamSource(xsltFile));
        }
        return stylesheet;
    }

    /**
     * Saves a DOM to a file.
     * @param doc the DOM Document
     * @param tgtFile the target file
     * @throws Exception if an error occurs while serializing the DOM
     */
    protected void saveDOM(Document doc, File tgtFile) throws Exception {
        Transformer transformer = tFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        Source src = new DOMSource(doc);
        Result res = new StreamResult(tgtFile);
        transformer.transform(src, res);
    }

    /**
     * Creates a new FOP user agent.
     * @return the user agent
     */
    protected FOUserAgent createUserAgent() {
        FOUserAgent userAgent = fopFactory.newFOUserAgent();
        try {
            userAgent.setBaseURL(testDir.toURI().toURL().toExternalForm());
            userAgent.getEventBroadcaster().addEventListener(
                    new ConsoleEventListenerForTests(testFile.getName()));
        } catch (MalformedURLException e) {
            //ignore, won't happen
        }
        return userAgent;
    }

    /**
     * Sets up the output directory.
     */
    protected void setupOutputDirectory() {
        String s = System.getProperty("fop.intermediate.outdir");
        if (s != null && s.length() > 0) {
            outputDir = new File(s);
            outputDir.mkdirs();
        }
    }

    /**
     * Tests the area tree parser by running the parsed area tree again through the area tree
     * renderer. The source and result documents are compared to each other.
     * @throws Exception if the test fails
     */
    public void testParserToIntermediateFormat() throws Exception {
        Source src = new DOMSource(intermediate);
        Document doc = parseAndRenderToIntermediateFormat(src);
        if (outputDir != null) {
            File tgtFile = new File(outputDir, getName() + ".2" + getIntermediateFileExtension());
            saveDOM(doc, tgtFile);
        }

        assertXMLEqual(intermediate, doc);
    }

    /**
     * Parses the intermediate file and renders it back to the intermediate format.
     * @param src the source for the intermediate file
     * @return a DOM Document with the re-created intermediate file
     * @throws Exception if an error occurs while processing the document
     */
    protected abstract Document parseAndRenderToIntermediateFormat(Source src) throws Exception;

    /**
     * Tests the area tree parser by sending the parsed area tree to the PDF Renderer. Some
     * errors might be caught by the PDFRenderer.
     * @throws Exception if the test fails
     */
    public void testParserToPDF() throws Exception {
        OutputStream out;
        if (outputDir != null) {
            File tgtFile = new File(outputDir, getName() + ".pdf");
            out = new FileOutputStream(tgtFile);
            out = new BufferedOutputStream(out);
        } else {
            out = new ByteArrayOutputStream();
        }
        try {
            Source src = new DOMSource(intermediate);
            parseAndRender(src, out);
        } finally {
            IOUtils.closeQuietly(out);
        }
    }

    /**
     * Parses and renders an intermediate format document to a final format.
     * @param src the source document
     * @param out the target output stream
     * @throws Exception if an error occurs while rendering the document
     */
    protected abstract void parseAndRender(Source src, OutputStream out)
            throws Exception;

    /**
     * Sets an error listener which doesn't swallow errors like Xalan's default one.
     * @param transformer the transformer to set the error listener on
     */
    protected void setErrorListener(Transformer transformer) {
        transformer.setErrorListener(new ErrorListener() {

            public void error(TransformerException exception) throws TransformerException {
                throw exception;
            }

            public void fatalError(TransformerException exception) throws TransformerException {
                throw exception;
            }

            public void warning(TransformerException exception) throws TransformerException {
                //ignore
            }

        });
    }

}