Servlets. How to use Apache FOP in a Servlet $Revision: $ Table of contents

Similar documents
Servlets. How to use Apache FOP in a Servlet $Revision: $ Table of contents

This page discusses topic all around using FOP in a servlet environment. 2. Example Servlets in the FOP distribution

Apache FOP: Embedding

CodeCharge Studio Java Deployment Guide Table of contents

<title> An XML based web service for an electronic logbook </title>

Generating Images and PDFs with JSP, Servlets and XML. Chád (shod) Darby. aquariussolutions.com. Chád (shod) Darby

Java Programming with XSLT

1 Copyright 2013, Oracle and/or its affiliates. All rights reserved.

SDN Community Contribution

Copyright 2005, by Object Computing, Inc. (OCI). All rights reserved. Database to Web

Advanced Topics in Operating Systems. Manual for Lab Practices. Enterprise JavaBeans

The Basic Web Server CGI. CGI: Illustration. Web based Applications, Tomcat and Servlets - Lab 3 - CMPUT 391 Database Management Systems 4

Java Servlets. Preparing your System

LAB 1 PREPARED BY : DR. AJUNE WANIS ISMAIL FACULTY OF COMPUTING UNIVERSITI TEKNOLOGI MALAYSIA

Servlets1. What are Servlets? Where are they? Their job. Servlet container. Only Http?

CHAPTER 1 USING JAXP FOR XML TRANSFORMATIONS

Writing Servlets and JSPs p. 1 Writing a Servlet p. 1 Writing a JSP p. 7 Compiling a Servlet p. 10 Packaging Servlets and JSPs p.

This tutorial will teach you how to use Java Servlets to develop your web based applications in simple and easy steps.

Archive Services for SAP Administration Guide

Introduction to Servlets. After which you will doget it

Connecting the RISC Client to non-javascriptinterfaces

INTRODUCTION TO SERVLETS AND WEB CONTAINERS. Actions in Accord with All the Laws of Nature

OpenClinica: Towards Database Abstraction, Part 1

Generating the Server Response: HTTP Response Headers

Servlets by Example. Joe Howse 7 June 2011

Advanced Internet Technology Lab # 4 Servlets

Strut2 jasper report plugin - War deployment

KNSP: A Kweelt - Niagara based Quilt Processor Inside Cocoon over Apache

Web based Applications, Tomcat and Servlets - Lab 3 -

9.3.5 Accessing the Vote Service

Signicat Connector for Java Version 2.6. Document version 3

Tutorial: Developing a Simple Hello World Portlet

BiZZdesign. InSite Server Installation Guide

Servlet for Json or CSV (or XML) A servlet serving either Json or CSV (or XML) based on GET parameter - This version uses org.json

XSLT-process minor mode

Agenda. Summary of Previous Session. XML for Java Developers G Session 6 - Main Theme XML Information Processing (Part II)

Sentences Installation Guide. Sentences Version 4.0

The Servlet Life Cycle

OpenOffice Documents with Lenya

JAVA SERVLET. Server-side Programming INTRODUCTION

Web Services. GC: Web Services Part 3: Rajeev Wankar

CH -7 RESPONSE HEADERS

Servlet and JSP Review

Generating the Server Response: HTTP Status Codes

EMC Documentum PDF Annotation Services

Re3gistry development & testing - Bug #2895 Problems installing registry

SSC - Web applications and development Introduction and Java Servlet (I)

Cisco CVP VoiceXML 3.1. Installation Guide

Kony MobileFabric. Sync Windows Installation - Manual - WebSphere. On-Premises. Release 7.2. Document Relevance and Accuracy

FCSLA PRODUCER GATEWAY

Perceptive Experience Content Apps

Tivoli Common Reporting V Cognos report in a Tivoli Integrated Portal dashboard

Oracle 1Z Java EE 6 Web Component Developer(R) Certified Expert.

Setting Up the Development Environment

Introduction. This course Software Architecture with Java will discuss the following topics:

Servlet Basics. Agenda

Standards and the Portals Project

Getting started with Geomajas. Geomajas Developers and Geosparc

Installing on WebLogic Server

Dspace Installation Guide (Windows 2003 Server)

CSC 8205 Advanced Java

Lab session Google Application Engine - GAE. Navid Nikaein

Introduction. Literature: Steelman & Murach, Murach s Java Servlets and JSP. Mike Murach & Associates Inc, 2003

Cisco Remote Expert Manager Agent s Workstation Setup Guide

Discovery data feed for Eid 2.0

Getting Started With Tornado

CS433 Technology Overview

Configuring Optional and Advanced Tasks for External Content Integration

Introduction to Java Servlets. SWE 432 Design and Implementation of Software for the Web

IBM WebSphere Transcoding Publisher Version 4.0 Developer's Guide

Xerces Http Apache Org Xml Features Validation Schema Full Checking

FOP FAQ. Table of contents

FINALTERM EXAMINATION Spring 2009 CS506- Web Design and Development Solved by Tahseen Anwar

CS506 Web Design & Development Final Term Solved MCQs with Reference

Security Guide. Configuration of Permissions

servlets and Java JSP murach s (Chapter 2) TRAINING & REFERENCE Mike Murach & Associates Andrea Steelman Joel Murach

Supplement IV.E: Tutorial for Tomcat For Introduction to Java Programming By Y. Daniel Liang

RTView Data Server SL Corporation. All Rights Reserved Sherrill-Lubinski Corporation. All Rights Reserved.

Exceptions and Libraries

Document Revision History

Easy Web Reports and Documents with JODReports

HTTP status codes. Setting status of an HTTPServletResponse

WA1787 Designing and Developing Higher Performance Web Services. Classroom Setup Guide. Web Age Solutions Inc. Copyright Web Age Solutions Inc.

Tradeoffs and Guidelines for Selecting Technologies to Generate Web Content from Relational Data Stores

Release Bulletin InfoMaker 11.2

Powering Pipelines with JAXP

Using SOAP Message Handlers

Database Explorer Quickstart

PHEWR Installation Guide (version 3)

Expand Your IBM Case Manager System - Integrating with Cognos Real-Time Monitor

JOURNAL OF OBJECT TECHNOLOGY

Installation Instructions for spamtracker components:

To follow the Deitel publishing program, sign-up now for the DEITEL BUZZ ON-

BEAAquaLogic Enterprise Repository. IBM Rational ClearCase and IBM Rational ClearQuest Integration Guide

2. Follow the installation directions and install the server on ccc. 3. We will call the root of your installation as $TOMCAT_DIR

Generating the Server Response:

EMC Documentum External Viewing Services for SAP

TGWeb. Step 1: Installer Files Step 2: Installing JAVA Runtime Step 3: Installing Apache/Tomcat Step 4: MSSQL Setup Step 5: DBSelect Utility

XML for Java Developers G Session 2 - Sub-Topic 1 Beginning XML. Dr. Jean-Claude Franchitti

MapXtreme Java Edition 3.1 Readme

Transcription:

How to use Apache FOP in a Servlet $Revision: 493717 $ Table of contents 1 Overview...2 2 Example Servlets in the FOP distribution...2 3 Create your own Servlet...2 3.1 A minimal Servlet...2 3.2 Adding XSL tranformation (XSLT)...3 3.3 Custom configuration... 4 3.4 Improving performance... 4 4 Notes on Microsoft Internet Explorer... 4 5 Servlet Engines... 5 5.1 Tomcat...5 5.2 WebSphere 3.5... 5 6 Handling complex use cases... 6

1. Overview This page discusses topic all around using Apache FOP in a servlet environment. 2. Example Servlets in the FOP distribution In the directory {fop-dir}/src/java/org/apache/fop/servlet, you'll find a working example of a FOP-enabled servlet. The servlet is automatically built when you build Apache FOP using the supplied Ant script. After building the servlet, drop fop.war into the webapps directory of Apache Tomcat (or any other web container). Then, you can use URLs like the following to generate PDF files: http://localhost:8080/fop/fop?fo=/home/path/to/fofile.fo http://localhost:8080/fop/fop?xml=/home/path/to/xmlfile.xml&xsl=/home/path/to/xslfile.xsl The source code for the servlet can be found under {fop-dir}/src/java/org/apache/fop/servlet/fopservlet.java. This example servlet should not be used on a public web server connected to the Internet as it does not contain any measures to prevent Denial-of-Service-Attacks. It is provided as an example and as a starting point for your own servlet. 3. Create your own Servlet This section assumes you are familiar with embedding FOP. 3.1. A minimal Servlet Here is a minimal code snippet to demonstrate the basics: private FopFactory fopfactory = FopFactory.newInstance(); private TransformerFactory tfactory = TransformerFactory.newInstance(); public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException { try { response.setcontenttype("application/pdf"); Page 2

Fop fop = fopfactory.newfop(mimeconstants.mime_pdf, response.getoutputstream()); Transformer transformer = tfactory.newtransformer(); Source src = new StreamSource("foo.fo"); Result res = new SAXResult(fop.getDefaultHandler()); transformer.transform(src, res); } catch (Exception ex) { throw new ServletException(ex); } } There are numerous problems with the code snippet above. Its purpose is only to demonstrate the basic concepts. See below for details. 3.2. Adding XSL tranformation (XSLT) A common requirement is to transform an XML source to XSL-FO using an XSL transformation. It is recommended to use JAXP for this task. The following snippet shows the basic code: private FopFactory fopfactory = FopFactory.newInstance(); private TransformerFactory tfactory = TransformerFactory.newInstance(); public void init() throws ServletException { //Optionally customize the FopFactory and TransformerFactory here } [..] //Setup a buffer to obtain the content length ByteArrayOutputStream out = new ByteArrayOutputStream(); //Setup FOP Fop fop = fopfactory.newfop(mimeconstants.mime_pdf, out); //Setup Transformer Source xsltsrc = new StreamSource(new File("foo-xml2fo.xsl")); Transformer transformer = tfactory.newtransformer(xsltsrc); //Make sure the XSL transformation's result is piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); //Setup input Source src = new StreamSource(new File("foo.xml")); //Start the transformation and rendering process transformer.transform(src, res); //Prepare response response.setcontenttype("application/pdf"); Page 3

response.setcontentlength(out.size()); //Send content to Browser response.getoutputstream().write(out.tobytearray()); response.getoutputstream().flush(); Buffering the generated PDF in a ByteArrayOutputStream is done to avoid potential problems with the Acrobat Reader Plug-in in Microsoft Internet Explorer. The Source instance used above is simply an example. If you have to read the XML from a string, supply a new StreamSource(new StringReader(xmlstring)). Constructing and reparsing an XML string is generally less desirable than using a SAXSource if you generate your XML. You can alternatively supply a DOMSource as well. You may also use dynamically generated XSL if you like. Because you have an explicit Transformer object, you can also use it to explicitely set parameters for the transformation run. 3.3. Custom configuration You can easily set up your own FOUserAgent as demonstrated on the Embedding page. 3.4. Improving performance There are several options to consider: Instead of java.io.bytearrayoutputstream consider using the ByteArrayOutputStream implementation from the Jakarta Commons IO project which allocates less memory. The full class name is: org.apache.commons.io.output.bytearrayoutputstream In certain cases it can help to write the generated PDF to a temporary file so you can quickly reuse the file. This is especially useful, if Internet Explorer calls the servlet multiple times with the same request or if you often generate equal PDFs. Of course, the performance hints from the Embedding page apply here, too. 4. Notes on Microsoft Internet Explorer Some versions of Internet Explorer will not automatically show the PDF or call the servlet multiple times. These are well-known limitations of Internet Explorer and are not a problem of the servlet. However, Internet Explorer can still be used to download the PDF so that it can be viewed later. Here are some suggestions in this context: Page 4

Use an URL ending in.pdf, like http://myserver/servlet/stuff.pdf. Yes, the servlet can be configured to handle this. If the URL has to contain parameters, try to have both the base URL as well as the last parameter end in.pdf, if necessary append a dummy parameter, like http://myserver/servlet/stuff.pdf?par1=a&par2=b&d=.pdf. The effect may depend on IEx version. Give IEx the opportunity to cache. In particular, ensure the server does not set any headers causing IEx not to cache the content. This may be a real problem if the document is sent over HTTPS, because most IEx installations will by default not cache any content retrieved over HTTPS. Setting the Expires header entry may help in this case: response.setdateheader("expires", System.currentTimeMillis() + cacheexpiringduration * 1000); Consult your server manual and the relevant RFCs for further details on HTTP headers and caching. Cache in the server. It may help to include a parameter in the URL which has a timestamp as the value min order to decide whether a request is repeated. IEx is reported to retrieve a document up to three times, but never more often. 5. Servlet Engines When using a servlet engine, there are potential CLASSPATH issues, and potential conflicts with existing XML/XSLT libraries. Servlet containers also often use their own classloaders for loading webapps, which can cause bugs and security problems. 5.1. Tomcat Check Tomcat's documentation for detailed instructions about installing FOP and Cocoon. There are known bugs that must be addressed, particularly for Tomcat 4.0.3. 5.2. WebSphere 3.5 Put a copy of a working parser in some directory where WebSphere can access it. For example, if /usr/webapps/yourapp/servlets is the CLASSPATH for your servlets, copy the Xerces jar into it (any other directory would also be fine). Do not add the jar to the servlet CLASSPATH, but add it to the CLASSPATH of the application server which contains your web application. In the WebSphere administration console, click on the "environment" button in the "general" tab. In the "variable name" box, enter "CLASSPATH". In the "value" box, enter the correct path to the parser jar file (/usr/webapps/yourapp/servlets/xerces.jar in our example here). Press "OK", then apply the change and restart the application server. Page 5

6. Handling complex use cases Sometimes the requirements for a servlet get quite sophisticated: SQL data sources, multiple XSL transformations, merging of several datasources etc. In such a case consider using Apache Cocoon instead of a custom servlet to accomplish your goal. Page 6