KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > fop > servlet > FopServlet


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: FopServlet.java 426576 2006-07-28 15:44:37Z jeremias $ */
19
20 package org.apache.fop.servlet;
21
22 import java.io.File JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.io.PrintWriter JavaDoc;
25
26 import javax.servlet.ServletException JavaDoc;
27 import javax.servlet.http.HttpServlet JavaDoc;
28 import javax.servlet.http.HttpServletRequest JavaDoc;
29 import javax.servlet.http.HttpServletResponse JavaDoc;
30 import javax.xml.transform.Result JavaDoc;
31 import javax.xml.transform.Source JavaDoc;
32 import javax.xml.transform.Transformer JavaDoc;
33 import javax.xml.transform.TransformerException JavaDoc;
34 import javax.xml.transform.TransformerFactory JavaDoc;
35 import javax.xml.transform.URIResolver JavaDoc;
36 import javax.xml.transform.sax.SAXResult JavaDoc;
37 import javax.xml.transform.stream.StreamSource JavaDoc;
38
39 import org.apache.commons.io.output.ByteArrayOutputStream;
40 import org.apache.commons.logging.impl.SimpleLog;
41
42 import org.apache.fop.apps.FOUserAgent;
43 import org.apache.fop.apps.Fop;
44 import org.apache.fop.apps.FOPException;
45 import org.apache.fop.apps.FopFactory;
46 import org.apache.fop.apps.MimeConstants;
47
48 /**
49  * Example servlet to generate a PDF from a servlet.
50  * <br/>
51  * Servlet param is:
52  * <ul>
53  * <li>fo: the path to a XSL-FO file to render
54  * </ul>
55  * or
56  * <ul>
57  * <li>xml: the path to an XML file to render</li>
58  * <li>xslt: the path to an XSLT file that can transform the above XML to XSL-FO</li>
59  * </ul>
60  * <br/>
61  * Example URL: http://servername/fop/servlet/FopServlet?fo=readme.fo
62  * <br/>
63  * Example URL: http://servername/fop/servlet/FopServlet?xml=data.xml&xslt=format.xsl
64  * <br/>
65  * For this to work with Internet Explorer, you might need to append "&ext=.pdf"
66  * to the URL.
67  *
68  * @author <a HREF="mailto:fop-dev@xmlgraphics.apache.org">Apache FOP Development Team</a>
69  * @version $Id: FopServlet.java 426576 2006-07-28 15:44:37Z jeremias $
70  * (todo) Ev. add caching mechanism for Templates objects
71  */

72 public class FopServlet extends HttpServlet JavaDoc {
73
74     /** Name of the parameter used for the XSL-FO file */
75     protected static final String JavaDoc FO_REQUEST_PARAM = "fo";
76     /** Name of the parameter used for the XML file */
77     protected static final String JavaDoc XML_REQUEST_PARAM = "xml";
78     /** Name of the parameter used for the XSLT file */
79     protected static final String JavaDoc XSLT_REQUEST_PARAM = "xslt";
80
81     /** Logger to give to FOP */
82     protected SimpleLog log = null;
83     /** The TransformerFactory used to create Transformer instances */
84     protected TransformerFactory JavaDoc transFactory = null;
85     /** The FopFactory used to create Fop instances */
86     protected FopFactory fopFactory = null;
87     /** URIResolver for use by this servlet */
88     protected URIResolver JavaDoc uriResolver;
89
90     /**
91      * @see javax.servlet.GenericServlet#init()
92      */

93     public void init() throws ServletException JavaDoc {
94         this.log = new SimpleLog("FOP/Servlet");
95         log.setLevel(SimpleLog.LOG_LEVEL_WARN);
96         this.uriResolver = new ServletContextURIResolver(getServletContext());
97         this.transFactory = TransformerFactory.newInstance();
98         this.transFactory.setURIResolver(this.uriResolver);
99         //Configure FopFactory as desired
100
this.fopFactory = FopFactory.newInstance();
101         this.fopFactory.setURIResolver(this.uriResolver);
102         configureFopFactory();
103     }
104     
105     /**
106      * This method is called right after the FopFactory is instantiated and can be overridden
107      * by subclasses to perform additional configuration.
108      */

109     protected void configureFopFactory() {
110         //Subclass and override this method to perform additional configuration
111
}
112
113     /**
114      * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest, HttpServletResponse)
115      */

116     public void doGet(HttpServletRequest JavaDoc request,
117                       HttpServletResponse JavaDoc response) throws ServletException JavaDoc {
118         try {
119             //Get parameters
120
String JavaDoc foParam = request.getParameter(FO_REQUEST_PARAM);
121             String JavaDoc xmlParam = request.getParameter(XML_REQUEST_PARAM);
122             String JavaDoc xsltParam = request.getParameter(XSLT_REQUEST_PARAM);
123
124             //Analyze parameters and decide with method to use
125
if (foParam != null) {
126                 renderFO(foParam, response);
127             } else if ((xmlParam != null) && (xsltParam != null)) {
128                 renderXML(xmlParam, xsltParam, response);
129             } else {
130                 response.setContentType("text/html");
131                 PrintWriter JavaDoc out = response.getWriter();
132                 out.println("<html><head><title>Error</title></head>\n"
133                           + "<body><h1>FopServlet Error</h1><h3>No 'fo' "
134                           + "request param given.</body></html>");
135             }
136         } catch (Exception JavaDoc ex) {
137             throw new ServletException JavaDoc(ex);
138         }
139     }
140
141     /**
142      * Converts a String parameter to a JAXP Source object.
143      * @param param a String parameter
144      * @return Source the generated Source object
145      */

146     protected Source JavaDoc convertString2Source(String JavaDoc param) {
147         return new StreamSource JavaDoc(new File JavaDoc(param));
148     }
149
150     private void sendPDF(byte[] content, HttpServletResponse JavaDoc response) throws IOException JavaDoc {
151         //Send the result back to the client
152
response.setContentType("application/pdf");
153         response.setContentLength(content.length);
154         response.getOutputStream().write(content);
155         response.getOutputStream().flush();
156     }
157     
158     /**
159      * Renders an XSL-FO file into a PDF file. The PDF is written to a byte
160      * array that is returned as the method's result.
161      * @param fo the XSL-FO file
162      * @param response HTTP response object
163      * @throws FOPException If an error occurs during the rendering of the
164      * XSL-FO
165      * @throws TransformerException If an error occurs while parsing the input
166      * file
167      * @throws IOException In case of an I/O problem
168      */

169     protected void renderFO(String JavaDoc fo, HttpServletResponse JavaDoc response)
170                 throws FOPException, TransformerException JavaDoc, IOException JavaDoc {
171
172         //Setup source
173
Source JavaDoc foSrc = convertString2Source(fo);
174
175         //Setup the identity transformation
176
Transformer JavaDoc transformer = this.transFactory.newTransformer();
177         transformer.setURIResolver(this.uriResolver);
178
179         //Start transformation and rendering process
180
render(foSrc, transformer, response);
181     }
182
183     /**
184      * Renders an XML file into a PDF file by applying a stylesheet
185      * that converts the XML to XSL-FO. The PDF is written to a byte array
186      * that is returned as the method's result.
187      * @param xml the XML file
188      * @param xslt the XSLT file
189      * @param response HTTP response object
190      * @throws FOPException If an error occurs during the rendering of the
191      * XSL-FO
192      * @throws TransformerException If an error occurs during XSL
193      * transformation
194      * @throws IOException In case of an I/O problem
195      */

196     protected void renderXML(String JavaDoc xml, String JavaDoc xslt, HttpServletResponse JavaDoc response)
197                 throws FOPException, TransformerException JavaDoc, IOException JavaDoc {
198
199         //Setup sources
200
Source JavaDoc xmlSrc = convertString2Source(xml);
201         Source JavaDoc xsltSrc = convertString2Source(xslt);
202
203         //Setup the XSL transformation
204
Transformer JavaDoc transformer = this.transFactory.newTransformer(xsltSrc);
205         transformer.setURIResolver(this.uriResolver);
206
207         //Start transformation and rendering process
208
render(xmlSrc, transformer, response);
209     }
210
211     /**
212      * Renders an input file (XML or XSL-FO) into a PDF file. It uses the JAXP
213      * transformer given to optionally transform the input document to XSL-FO.
214      * The transformer may be an identity transformer in which case the input
215      * must already be XSL-FO. The PDF is written to a byte array that is
216      * returned as the method's result.
217      * @param src Input XML or XSL-FO
218      * @param transformer Transformer to use for optional transformation
219      * @param response HTTP response object
220      * @throws FOPException If an error occurs during the rendering of the
221      * XSL-FO
222      * @throws TransformerException If an error occurs during XSL
223      * transformation
224      * @throws IOException In case of an I/O problem
225      */

226     protected void render(Source JavaDoc src, Transformer JavaDoc transformer, HttpServletResponse JavaDoc response)
227                 throws FOPException, TransformerException JavaDoc, IOException JavaDoc {
228
229         FOUserAgent foUserAgent = getFOUserAgent();
230
231         //Setup output
232
ByteArrayOutputStream out = new ByteArrayOutputStream();
233
234         //Setup FOP
235
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);
236
237         //Make sure the XSL transformation's result is piped through to FOP
238
Result JavaDoc res = new SAXResult JavaDoc(fop.getDefaultHandler());
239
240         //Start the transformation and rendering process
241
transformer.transform(src, res);
242
243         //Return the result
244
sendPDF(out.toByteArray(), response);
245     }
246     
247     /** @return a new FOUserAgent for FOP */
248     protected FOUserAgent getFOUserAgent() {
249         FOUserAgent userAgent = fopFactory.newFOUserAgent();
250         //Configure foUserAgent as desired
251
return userAgent;
252     }
253
254 }
255
Popular Tags