• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

hazendaz / displaytag / 1558

08 Dec 2025 01:09AM UTC coverage: 77.32% (-0.04%) from 77.358%
1558

push

github

web-flow
Merge pull request #1042 from hazendaz/renovate/javax-support-org.apache.commons-commons-text-1.x

Update dependency org.apache.commons:commons-text to v1.15.0 (javax-support)

1435 of 1999 branches covered (71.79%)

Branch coverage included in aggregate %.

4030 of 5069 relevant lines covered (79.5%)

0.8 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

56.18
/displaytag/src/main/java/org/displaytag/export/FopExportView.java
1
/*
2
 * Copyright (C) 2002-2025 Fabrizio Giustina, the Displaytag team
3
 *
4
 * Permission is hereby granted, free of charge, to any person obtaining a copy
5
 * of this software and associated documentation files (the "Software"), to deal
6
 * in the Software without restriction, including without limitation the rights
7
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
 * copies of the Software, and to permit persons to whom the Software is
9
 * furnished to do so, subject to the following conditions:
10
 *
11
 * The above copyright notice and this permission notice shall be included in
12
 * all copies or substantial portions of the Software.
13
 *
14
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20
 * THE SOFTWARE.
21
 */
22
package org.displaytag.export;
23

24
import java.io.ByteArrayInputStream;
25
import java.io.File;
26
import java.io.IOException;
27
import java.io.InputStream;
28
import java.io.OutputStream;
29
import java.io.StringReader;
30
import java.io.StringWriter;
31
import java.nio.charset.StandardCharsets;
32
import java.nio.file.Files;
33
import java.nio.file.Path;
34

35
import javax.servlet.jsp.JspException;
36
import javax.xml.transform.Result;
37
import javax.xml.transform.Source;
38
import javax.xml.transform.Transformer;
39
import javax.xml.transform.TransformerConfigurationException;
40
import javax.xml.transform.TransformerException;
41
import javax.xml.transform.TransformerFactory;
42
import javax.xml.transform.sax.SAXResult;
43
import javax.xml.transform.stream.StreamResult;
44
import javax.xml.transform.stream.StreamSource;
45

46
import org.apache.commons.lang3.StringUtils;
47
import org.apache.fop.apps.FOPException;
48
import org.apache.fop.apps.Fop;
49
import org.apache.fop.apps.FopFactory;
50
import org.apache.fop.fo.ValidationException;
51
import org.displaytag.model.TableModel;
52
import org.slf4j.Logger;
53
import org.slf4j.LoggerFactory;
54

55
/**
56
 * Exports the data to a totaled xml format, and then transforms that data using XSL-FO to a pdf. The stylesheet can be
57
 * fed in as a string from the property export.pdf.fo.stylesheetbody, or you can use a default stylesheet named by the
58
 * property export.pdf.fo.stylesheet. When you are developing a stylesheet, this class will output the raw FO if you set
59
 * your log level to debug, which is very handy if you are getting errors or unexpected pdf output. See asFo_us.xsl for
60
 * a sample XSL-FO stylesheet. The basic structure of the intermediate XML is
61
 *
62
 * <pre>
63
 * &lt;table&gt;
64
 *   &lt;header&gt;
65
 *     &lt;header-cell&gt;AntColumn&lt;/header-cell&gt;
66
 *   &lt;/header&gt;
67
 *   &lt;data&gt;
68
 *     &lt;subgroup grouped-by="0"&gt;
69
 *       &lt;row&gt;
70
 *         &lt;cell grouped="true"&gt;Ant&lt;/cell&gt;
71
 *       &lt;/row&gt;
72
 *       &lt;subtotal&gt;
73
 *         &lt;subtotal-cell&gt; &lt;/subtotal-cell&gt;
74
 *       &lt;/subtotal&gt;
75
 *     &lt;/subgroup&gt;
76
 *   &lt;/data&gt;
77
 * &lt;/table&gt;
78
 * </pre>
79
 *
80
 * @see FopExportView#SPECIFIC_STYLESHEET the property that contains the text of a stylesheet
81
 * @see FopExportView#DEFAULT_STYLESHEET the default stylesheet location
82
 * @see XmlTotalsWriter
83
 */
84
public class FopExportView implements BinaryExportView {
1✔
85

86
    /** The log. */
87
    private static Logger log = LoggerFactory.getLogger(FopExportView.class);
1✔
88

89
    /**
90
     * Default stylesheet.
91
     */
92
    public static final String DEFAULT_STYLESHEET = "export.pdf.fo.stylesheet"; //$NON-NLS-1$
93

94
    /**
95
     * A stylesheet as a string on a property.
96
     */
97
    public static final String SPECIFIC_STYLESHEET = "export.pdf.fo.stylesheetbody"; //$NON-NLS-1$
98

99
    /**
100
     * TableModel to render.
101
     */
102
    protected TableModel model;
103

104
    /**
105
     * Sets the parameters.
106
     *
107
     * @param tableModel
108
     *            the table model
109
     * @param exportFullList
110
     *            the export full list
111
     * @param includeHeader
112
     *            the include header
113
     * @param decorateValues
114
     *            the decorate values
115
     *
116
     * @see org.displaytag.export.ExportView#setParameters(TableModel, boolean, boolean, boolean)
117
     */
118
    @Override
119
    public void setParameters(final TableModel tableModel, final boolean exportFullList, final boolean includeHeader,
120
            final boolean decorateValues) {
121
        this.model = tableModel;
1✔
122
    }
1✔
123

124
    /**
125
     * Gets the mime type.
126
     *
127
     * @return "application/pdf"
128
     *
129
     * @see org.displaytag.export.BaseExportView#getMimeType()
130
     */
131
    @Override
132
    public String getMimeType() {
133
        return "application/pdf"; //$NON-NLS-1$
1✔
134
    }
135

136
    /**
137
     * Load the stylesheet.
138
     *
139
     * @return the stylesheet
140
     *
141
     * @throws IOException
142
     *             if we cannot locate it
143
     */
144
    public InputStream getStyleSheet() throws IOException {
145

146
        InputStream styleSheetStream;
147
        final String styleSheetString = this.model.getProperties().getProperty(FopExportView.SPECIFIC_STYLESHEET);
1✔
148
        if (StringUtils.isNotEmpty(styleSheetString)) {
1✔
149
            styleSheetStream = new ByteArrayInputStream(styleSheetString.getBytes(StandardCharsets.UTF_8));
1✔
150
        } else {
151
            final String styleSheetPath = this.model.getProperties().getProperty(FopExportView.DEFAULT_STYLESHEET);
1✔
152
            styleSheetStream = this.getClass().getResourceAsStream(styleSheetPath);
1✔
153
            if (styleSheetStream == null) {
1!
154
                throw new IOException("Cannot locate stylesheet " + styleSheetPath); //$NON-NLS-1$
×
155
            }
156
        }
157
        return styleSheetStream;
1✔
158
    }
159

160
    /**
161
     * Don't forget to enable debug if you want to see the raw FO.
162
     *
163
     * @param out
164
     *            output writer
165
     *
166
     * @throws IOException
167
     *             Signals that an I/O exception has occurred.
168
     * @throws JspException
169
     *             the jsp exception
170
     */
171
    @Override
172
    public void doExport(final OutputStream out) throws IOException, JspException {
173
        final String xmlResults = this.getXml();
1✔
174

175
        final FopFactory fopFactory = FopFactory.newInstance(Path.of(".").toUri());
1✔
176
        final Source xslt = new StreamSource(this.getStyleSheet());
1✔
177
        final TransformerFactory factory = TransformerFactory.newInstance();
1✔
178
        Transformer transformer;
179
        try {
180
            transformer = factory.newTransformer(xslt);
1✔
181
        } catch (final TransformerConfigurationException e) {
×
182
            throw new JspException("Cannot configure pdf export " + e.getMessage(), e); //$NON-NLS-1$
×
183
        }
1✔
184

185
        final boolean outputForDebug = FopExportView.log.isDebugEnabled();
1✔
186
        if (outputForDebug) {
1!
187
            this.logXsl(xmlResults, transformer, null);
×
188
        }
189

190
        Fop fop;
191
        try {
192
            fop = fopFactory.newFop(org.apache.xmlgraphics.util.MimeConstants.MIME_PDF, out);
1✔
193
        } catch (final FOPException e) {
×
194
            throw new JspException("Cannot configure pdf export " + e.getMessage(), e); //$NON-NLS-1$
×
195
        }
1✔
196

197
        final StreamSource src = new StreamSource(new StringReader(xmlResults));
1✔
198
        Result res;
199
        try {
200
            res = new SAXResult(fop.getDefaultHandler());
1✔
201
        } catch (final FOPException e) {
×
202
            throw new JspException("error setting up transform ", e); //$NON-NLS-1$
×
203
        }
1✔
204
        try {
205
            transformer.transform(src, res);
1✔
206
        } catch (final TransformerException e) {
×
207
            if (!(e.getCause() instanceof ValidationException)) {
×
208
                throw new JspException("error creating pdf output", e); //$NON-NLS-1$
×
209
            }
210
            // recreate the errant fo
211
            final ValidationException ve = (ValidationException) e.getCause();
×
212
            this.logXsl(xmlResults, transformer, ve);
×
213

214
        }
1✔
215
    }
1✔
216

217
    /**
218
     * Gets the xml.
219
     *
220
     * @return the xml
221
     *
222
     * @throws JspException
223
     *             the jsp exception
224
     */
225
    protected String getXml() throws JspException {
226
        final XmlTotalsWriter totals = new XmlTotalsWriter(this.model);
1✔
227
        totals.writeTable(this.model, "-1");
1✔
228
        return totals.getXml();
1✔
229
    }
230

231
    /**
232
     * log it.
233
     *
234
     * @param xmlResults
235
     *            raw
236
     * @param transformer
237
     *            the transformer
238
     * @param e
239
     *            the optional exception
240
     *
241
     * @throws JspException
242
     *             wrapping an existing error
243
     */
244
    protected void logXsl(final String xmlResults, final Transformer transformer, final Exception e)
245
            throws JspException {
246
        final StreamResult debugRes = new StreamResult(new StringWriter());
×
247
        final StreamSource src = new StreamSource(new StringReader(xmlResults));
×
248
        try {
249
            transformer.transform(src, debugRes);
×
250
            if (e != null) {
×
251
                FopExportView.log.error("xslt-fo error {}", e.getMessage(), e); //$NON-NLS-1$
×
252
                FopExportView.log.error("xslt-fo result of {}", debugRes.getWriter()); //$NON-NLS-1$
×
253
                throw new JspException("Stylesheet produced invalid xsl-fo result", e); //$NON-NLS-1$
×
254
            }
255
            FopExportView.log.info("xslt-fo result of {}", debugRes.getWriter()); //$NON-NLS-1$
×
256
        } catch (final TransformerException ee) {
×
257
            throw new JspException("error creating pdf output " + ee.getMessage(), ee); //$NON-NLS-1$
×
258
        }
×
259
    }
×
260

261
    /**
262
     * If you are authoring a stylesheet locally, this is highly recommended as a way to test your stylesheet against
263
     * dummy data.
264
     *
265
     * @param xmlSrc
266
     *            xml as string
267
     * @param styleSheetPath
268
     *            the path to the stylesheet
269
     * @param f
270
     *            the f
271
     *
272
     * @throws Exception
273
     *             if trouble
274
     */
275
    public static void transform(final String xmlSrc, final String styleSheetPath, final File f) throws Exception {
276

277
        final FopFactory fopFactory = FopFactory.newInstance(Path.of(".").toUri());
1✔
278
        final InputStream styleSheetStream = FopExportView.class.getResourceAsStream(styleSheetPath);
1✔
279

280
        final Source xslt = new StreamSource(styleSheetStream);
1✔
281
        final TransformerFactory factory = TransformerFactory.newInstance();
1✔
282
        Transformer transformer;
283
        try {
284
            transformer = factory.newTransformer(xslt);
1✔
285
        } catch (final TransformerConfigurationException e) {
×
286
            throw new JspException("Cannot configure pdf export " + e.getMessage(), e); //$NON-NLS-1$
×
287
        }
1✔
288
        Fop fop;
289
        try {
290
            final OutputStream fw = Files.newOutputStream(f.toPath());
1✔
291
            fop = fopFactory.newFop(org.apache.xmlgraphics.util.MimeConstants.MIME_PDF, fw);
1✔
292
        } catch (final FOPException e) {
×
293
            throw new JspException("Cannot configure pdf export " + e.getMessage(), e); //$NON-NLS-1$
×
294
        }
1✔
295

296
        final Source src = new StreamSource(new StringReader(xmlSrc));
1✔
297
        Result res;
298
        try {
299
            res = new SAXResult(fop.getDefaultHandler());
1✔
300
        } catch (final FOPException e) {
×
301
            throw new JspException("error setting up transform ", e); //$NON-NLS-1$
×
302
        }
1✔
303
        try {
304
            transformer.transform(src, res);
1✔
305
        } catch (final TransformerException e) {
×
306
            throw new JspException("error creating pdf output " + e.getMessage(), e); //$NON-NLS-1$
×
307
        }
1✔
308
    }
1✔
309
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc