I am not aware if the issue has been solved by others, but when I tried to
use JasperReportViewServlet for displaying charts/images in html files, it
didn't work. Then I checked the source code, there is a line marked "// todo
fixme... currently not working...". After exploring more on Jasper report
document, I got the problem solved. Basically we need to load images from
IMAGES_MAP. The following is the modified code. Anybody can check the code
and compile it into the lib?

Thanks.
Manyuan Jin


/*
 * Copyright (c) 2002-2003 by OpenSymphony
 * All rights reserved.
 */
package com.opensymphony.webwork.views.jasperreports;

import com.opensymphony.webwork.ServletActionContext;
import com.opensymphony.xwork.util.OgnlValueStack;
import dori.jasper.engine.*;
import dori.jasper.engine.export.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * Provide a view of a webwork action as a jasper report. The report format
will be determined by
 * the format parameter passed in the xwork action definition.
 * Example action definition:
 *
 * <action name="jasperTest"
class="com.opensymphony.webwork.views.jasperreports.example.OrderListAction"
>
 *    <param name="dataSource">orders</param>
 *    <param name="format">PDF</param>
 *    <result name="success" type="dispatcher">
 *        <param name="location">orderList.jasper</param>
 *    </result>
 *    <interceptor-ref name="defaultStack"/>
 * </action>
 *
 * Valid report format strings are the following:
 * <ul>
 * <li>PDF</li>
 * <li>XML</li>
 * <li>HTML</li>
 * <li>XLS</li>
 * <li>CSV</li>
 * </ul>
 * It will then look for a compiled report definition of the form
<code><view name>.jasper</code>,
 * run it to the appropriate output format and stream the results as the
HTTP response.
 *
 * Ported to WebWork2:
 *
 * @author <a href="[EMAIL PROTECTED]">Rainer Hermanns</a>
 * @version $Id: JasperReportViewServlet.java,v 1.1 2003/10/03 05:45:27
cameronbraid Exp $
 */
public class JasperReportViewServlet extends HttpServlet implements
JasperReportConstants {

    //~ Static fields/initializers
/////////////////////////////////////////////
    protected static Log log =
LogFactory.getLog(JasperReportViewServlet.class);

    //~ Instance fields
////////////////////////////////////////////////////////

    protected String IMAGES_URI = "/images/";

    //~ Methods
////////////////////////////////////////////////////////////////

    /* (non-Javadoc)
     * @see javax.servlet.GenericServlet#init()
     */
    public void init() throws ServletException {
        super.init();

        if (getServletConfig().getInitParameter("IMAGES_URI") != null) {
            IMAGES_URI = getServletConfig().getInitParameter("IMAGES_URI");
        }
    }


     /**
     * Service a HTTP request
     * @param request the request to service
     * @param response the response to send to the client
     */
    public void service(HttpServletRequest request, HttpServletResponse
response) throws ServletException {
        String imageName=request.getParameter("image");
        //load image from IMAGES_MAP
  if(imageName !=null){
            Map imagesMap = (Map)
request.getSession().getAttribute("IMAGES_MAP");
   if (imagesMap != null){
    byte[] imageData = (byte[]) imagesMap.get(imageName);
               try{
     response.setContentLength(imageData.length);
     ServletOutputStream ouputStream = response.getOutputStream();
     ouputStream.write(imageData, 0, imageData.length);
     ouputStream.flush();
     ouputStream.close();
    }
    catch(IOException ioe){
     log.warn(ioe.toString());
    }
   }
        }
        else{
        //construct the data source for the report
        OgnlValueStack stack =
ServletActionContext.getContext().getValueStack();
        String dataSource = "" + request.getAttribute("dataSource");
        OgnlValueStackDataSource stackDataSource = new
OgnlValueStackDataSource(stack, dataSource);

        //get the output format
        String outputFormat = "" + request.getAttribute("format");
        // (Map) ActionContext.getContext().getSession().get("IMAGES_MAP");
        if (outputFormat == null) {
            outputFormat = FORMAT_PDF;
        }

        if (!"contype".equals(request.getHeader("User-Agent"))) {
            // Determine the directory that the report file is in and set
the reportDirectory parameter
            String systemId =
getServletContext().getRealPath(request.getServletPath());
            Map parameters = new OgnlValueStackShadowMap(stack);
            File directory = new File(systemId.substring(0,
systemId.lastIndexOf(File.separator)));
            parameters.put("reportDirectory", directory);

            byte[] output = null;
            JasperPrint jasperPrint = null;

            // Fill the report and produce a print object
            try {
                JasperReport jasperReport =
JasperManager.loadReport(systemId);
                jasperPrint = JasperFillManager.fillReport(jasperReport,
parameters, stackDataSource);
            } catch (JRException e) {
                log.error("Error building report for uri " + systemId, e);
                throw new ServletException(e.getMessage(), e);
            }

            // Export the print object to the desired output format
            try {
                if (outputFormat.equals(FORMAT_PDF)) {
                    response.setContentType("application/pdf");

                    // response.setHeader("Content-disposition", "inline;
filename=report.pdf");
                    output =
JasperExportManager.exportReportToPdf(jasperPrint);
                } else {
                    JRExporter exporter = null;

                    if (outputFormat.equals(FORMAT_CSV)) {
                        response.setContentType("text/plain");
                        exporter = new JRCsvExporter();
                    } else if (outputFormat.equals(FORMAT_HTML)) {
                        response.setContentType("text/html");

                        Map imagesMap = new HashMap();

                        request.getSession().setAttribute("IMAGES_MAP",
imagesMap);
                        exporter = new JRHtmlExporter();

exporter.setParameter(JRHtmlExporterParameter.IMAGES_MAP, imagesMap);

exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI,
"*.jasper?image=");

                    } else if (outputFormat.equals(FORMAT_XLS)) {
                        response.setContentType("application/vnd.ms-excel");
                        exporter = new JRXlsExporter();
                    } else if (outputFormat.equals(FORMAT_XML)) {
                        response.setContentType("text/xml");
                        exporter = new JRXmlExporter();
                    } else {
                        throw new ServletException("Unknown report format: "
+ outputFormat);
                    }

                    output = exportReportToBytes(jasperPrint, exporter);
                }
            } catch (JRException e) {
                String message = "Error producing " + outputFormat + "
report for uri " + systemId;
                log.error(message, e);
                throw new ServletException(e.getMessage(), e);
            }

            response.setContentLength(output.length);

            ServletOutputStream ouputStream;

            try {
                if (log.isDebugEnabled()) {
                    //log.debug("Writing " + output.length + " bytes to
output stream");
                }

                ouputStream = response.getOutputStream();
                ouputStream.write(output);
                ouputStream.flush();
                ouputStream.close();
            } catch (IOException e) {
                log.error("Error writing report output", e);
                throw new ServletException(e.getMessage(), e);
            }
        } else {
            // Code to handle "contype" request from IE
            try {
                ServletOutputStream outputStream;
                response.setContentType("application/pdf");
                response.setContentLength(0);
                outputStream = response.getOutputStream();
                outputStream.close();
            } catch (IOException e) {
                log.error("Error writing report output", e);
                throw new ServletException(e.getMessage(), e);
            }
        }
        }
    }

    /**
     * Run a Jasper report to CSV format and put the results in a byte array
     * @param jasperPrint The Print object to render as CSV
     * @param exporter The exporter to use to export the report
     * @return A CSV formatted report
     * @throws dori.jasper.engine.JRException If there is a problem running
the report
     */
    private byte[] exportReportToBytes(JasperPrint jasperPrint, JRExporter
exporter) throws JRException {
        byte[] output;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        exporter.setParameter(JRExporterParameter.JASPER_PRINT,
jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);

        exporter.exportReport();

        output = baos.toByteArray();

        return output;
    }
}



-------------------------------------------------------
This SF.net email is sponsored by: Perforce Software.
Perforce is the Fast Software Configuration Management System offering
advanced branching capabilities and atomic changes on 50+ platforms.
Free Eval! http://www.perforce.com/perforce/loadprog.html
_______________________________________________
Opensymphony-webwork mailing list
[EMAIL PROTECTED]
https://lists.sourceforge.net/lists/listinfo/opensymphony-webwork

Reply via email to