Announcement Announcement Module
Collapse
No announcement yet.
Jasper applet viewer Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Jasper applet viewer

    I folks,

    I have followed this conversation http://forum.springframework.org/vie...ghlight=jasper to some time, and would like to contribute of any form.

    I tired to try to understand because the JasperReports present different layouts when presenting reports in HTML for different browsers. I tried to use the Acrobat Reader to facilitate this, but many customers had not liked the idea and at some moments the report was not presented. Then I saw that the version 0.6.4 I could use an applet to present the report.

    I studed the idea and see that the applet needed a JasperPrint serialized in the reponse stream and the Spring solution at the moment don't support it.

    Finally I make an public class JasperReportsPrintView extends AbstractJasperReportsSingleFormatView to solve this, and I would like to share the idea with yours.

    Code:
    package ...presentation.web.support.springframework;
    
    import java.io.ObjectOutputStream;
    import java.util.Map;
    
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServletResponse;
    
    import net.sf.jasperreports.engine.JRAbstractExporter;
    import net.sf.jasperreports.engine.JRDataSource;
    import net.sf.jasperreports.engine.JasperFillManager;
    import net.sf.jasperreports.engine.JasperPrint;
    import net.sf.jasperreports.engine.JasperReport;
    
    import org.springframework.web.servlet.view.jasperreports.AbstractJasperReportsSingleFormatView;
    
    public class JasperReportsPrintView extends
    		AbstractJasperReportsSingleFormatView {
    
    	/**
    	 * Default Constructor
    	 */
    	public JasperReportsPrintView() {
    		setContentType("application/octet-stream");
    	}
    
    	/**
    	 * Perform rendering for a single Jasper Reports exporter,
    	 * i.e. a pre-defined output format.
    	 */
    	protected void renderReport(
    			JasperReport report, Map parameters, JRDataSource dataSource, HttpServletResponse response)
    			throws Exception {
    
    		JasperPrint jasperPrint = JasperFillManager.fillReport(report, parameters, dataSource);
    
    		ServletOutputStream ouputStream = response.getOutputStream();
    			
    		ObjectOutputStream oos = new ObjectOutputStream(ouputStream);
    		oos.writeObject(jasperPrint);
    		oos.flush();
    		oos.close();
    
    		ouputStream.flush();
    		ouputStream.close();
    	}
    
    	/**
    	 * @see org.springframework.web.servlet.view.jasperreports.AbstractJasperReportsSingleFormatView#createExporter()
    	 */
    	protected JRAbstractExporter createExporter() {
    		return null;
    	}
    
    	/**
    	 * @see org.springframework.web.servlet.view.jasperreports.AbstractJasperReportsSingleFormatView#useWriter()
    	 */
    	protected boolean useWriter() {
    		return false;
    	}
    
    }
    and for a context overview

    1) The servlet report config:
    Code:
    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http&#58;//www.springframework.org/dtd/spring-beans.dtd">
    <beans>
        <bean id="reportController"
            class="...reportController"
            autowire="byName">
            <property name="facade">
                <ref bean="businessDelegate" />
            </property>
        </bean>
        <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
            <property name="mappings">
                <props>
                    <prop key="**/report.jasper">reportController</prop>
                </props>
            </property>
        </bean>
        <bean id="jasperReportsViewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
            <property name="basename">
                <value>jasper</value>
            </property>
        </bean>
    </beans>
    The jasper.propeties file:
    Code:
    ##############################
    # JasperReports View Classes
    ##############################
    # org.springframework.web.servlet.view.jasperreports.JasperReportsCsvView
    # org.springframework.web.servlet.view.jasperreports.JasperReportsHtmlView
    # org.springframework.web.servlet.view.jasperreports.JasperReportsPdfView
    # org.springframework.web.servlet.view.jasperreports.JasperReportsXlsView
    
    ################
    # Reports
    ################
    report.class=...presentation.web.support.springframework.JasperReportsPrintView
    report.url=/WEB-INF/reports/Report.jrxml
    report.reportDataKey=reportData
    The report Controller class:
    Code:
    package ...presentation.web.classes.owner.report;
    
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.servlet.ServletContext;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.mvc.Controller;
    
    import ...facade.BusinessDelegate;
    import ...presentation.web.support.WebSupportUtils;
    import ...presentation.web.support.jasper.JRHibernateQueryResultDataSource;
    
    public class ReportController implements Controller  &#123;
    
        protected BusinessDelegate facade;
    
        /**
         *
         * @param facade BusinessDelegate
         */
        public void setFacade&#40;BusinessDelegate facade&#41; &#123;
            this.facade = facade;
        &#125;
    
        /**
         *
         * @param request HttpServletRequest
         * @param response HttpServletResponse
         * @throws Exception
         * @return ModelAndView
         */
        public ModelAndView handleRequest&#40;HttpServletRequest request,
                                          HttpServletResponse response&#41; throws Exception &#123;
    
            Collection dataSource = facade.ownerReport&#40;
                 WebSupportUtils.getAuthenticatedOwner&#40;request.getSession&#40;&#41;, true&#41;&#41;;
    
            String&#91;&#93; fields = new String&#91;&#93; &#123;"field1",
                                            "field2",
                                            "field3",
                                            "field4",
                                            "field5",
                                            "field6",
                                            "field7"&#125;;
    
            Map model = new HashMap&#40;&#41;;
            ServletContext context = request.getSession&#40;&#41;.getServletContext&#40;&#41;;
    
            model.put&#40;"framesup_img01", context.getRealPath&#40;"imagens/framesup_img01.jpg"&#41;&#41;;
            model.put&#40;"framesup_img02", context.getRealPath&#40;"imagens/framesup_img02.jpg"&#41;&#41;;
            model.put&#40;"framesup_img03", context.getRealPath&#40;"imagens/framesup_img03.jpg"&#41;&#41;;
            model.put&#40;"reportData", new JRHibernateQueryResultDataSource&#40;dataSource, fields&#41;&#41;;
    
            return new ModelAndView&#40;"report", model&#41;;
        &#125;
    &#125;
    The EmbeddedViewerApplet class:
    Code:
    /*
     * ============================================================================
     *                   The JasperReports License, Version 1.0
     * ============================================================================
     * 
     * Copyright &#40;C&#41; 2001-2004 Teodor Danciu &#40;[email protected]&#41;. All rights reserved.
     * 
     * Redistribution and use in source and binary forms, with or without modification,
     * are permitted provided that the following conditions are met&#58;
     * 
     * 1. Redistributions of source code must retain the above copyright notice,
     *    this list of conditions and the following disclaimer.
     * 
     * 2. Redistributions in binary form must reproduce the above copyright notice,
     *    this list of conditions and the following disclaimer in the documentation
     *    and/or other materials provided with the distribution.
     * 
     * 3. The end-user documentation included with the redistribution, if any, must
     *    include the following acknowledgment&#58; "This product includes software
     *    developed by Teodor Danciu &#40;http&#58;//jasperreports.sourceforge.net&#41;."
     *    Alternately, this acknowledgment may appear in the software itself, if
     *    and wherever such third-party acknowledgments normally appear.
     * 
     * 4. The name "JasperReports" must not be used to endorse or promote products 
     *    derived from this software without prior written permission. For written 
     *    permission, please contact [email protected].
     * 
     * 5. Products derived from this software may not be called "JasperReports", nor 
     *    may "JasperReports" appear in their name, without prior written permission
     *    of Teodor Danciu.
     * 
     * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
     * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
     * FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
     * APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
     * INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES &#40;INCLU-
     * DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
     * OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION&#41;  HOWEVER CAUSED AND ON
     * ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
     * &#40;INCLUDING  NEGLIGENCE OR  OTHERWISE&#41; ARISING IN  ANY WAY OUT OF THE  USE OF
     * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     */
    
    /*
     * ============================================================================
     *                   GNU Lesser General Public License
     * ============================================================================
     *
     * JasperReports - Free Java report-generating library.
     * Copyright &#40;C&#41; 2001-2004 Teodor Danciu [email protected]
     * 
     * This library is free software; you can redistribute it and/or
     * modify it under the terms of the GNU Lesser General Public
     * License as published by the Free Software Foundation; either
     * version 2.1 of the License, or &#40;at your option&#41; any later version.
     * 
     * This library is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     * Lesser General Public License for more details.
     * 
     * You should have received a copy of the GNU Lesser General Public
     * License along with this library; if not, write to the Free Software
     * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307, USA.
     * 
     * Teodor Danciu
     * 173, Calea Calarasilor, Bl. 42, Sc. 1, Ap. 18
     * Postal code 030615, Sector 3
     * Bucharest, ROMANIA
     * Email&#58; [email protected]
     */
    import net.sf.jasperreports.engine.*;
    import net.sf.jasperreports.engine.util.*;
    import net.sf.jasperreports.view.*;
    
    import java.io.*;
    import java.net.*;
    import java.awt.BorderLayout;
    import javax.swing.JOptionPane;
    
    
    /**
     * @author Teodor Danciu &#40;[email protected]&#41;
     * @version $Id&#58; EmbeddedViewerApplet.java,v 1.4 2004/06/01 20&#58;46&#58;04 teodord Exp $
     */
    public class EmbeddedViewerApplet extends javax.swing.JApplet
    &#123;
    
    
    	/**
    	 *
    	 */
    	private JasperPrint jasperPrint = null;
    
    
    	/** Creates new form AppletViewer */
    	public EmbeddedViewerApplet&#40;&#41;
    	&#123;
    		initComponents&#40;&#41;;
    	&#125;
    
    
    	/**
    	*
    	*/
    	public void init&#40;&#41;
    	&#123;
    		String url = getParameter&#40;"REPORT_URL"&#41;;
    		if &#40;url != null&#41;
    		&#123;
    			try
    			&#123;
    				jasperPrint = &#40;JasperPrint&#41;JRLoader.loadObject&#40;new URL&#40;getCodeBase&#40;&#41;, url&#41;&#41;;
    				if &#40;jasperPrint != null&#41;
    				&#123;
    					JRViewerSimple viewer = new JRViewerSimple&#40;jasperPrint&#41;;
    					this.pnlMain.add&#40;viewer, BorderLayout.CENTER&#41;;
    				&#125;
    			&#125;
    			catch &#40;Exception e&#41;
    			&#123;
    				StringWriter swriter = new StringWriter&#40;&#41;;
    				PrintWriter pwriter = new PrintWriter&#40;swriter&#41;;
    				e.printStackTrace&#40;pwriter&#41;;
    				JOptionPane.showMessageDialog&#40;this, swriter.toString&#40;&#41;&#41;;
    			&#125;
    		&#125;
    		else
    		&#123;
    			JOptionPane.showMessageDialog&#40;this, "Source URL not specified"&#41;;
    		&#125;
    	&#125;
    
    
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING&#58; Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
         */
        private void initComponents&#40;&#41; &#123;//GEN-BEGIN&#58;initComponents
            pnlMain = new javax.swing.JPanel&#40;&#41;;
    
            pnlMain.setLayout&#40;new java.awt.BorderLayout&#40;&#41;&#41;;
    
            getContentPane&#40;&#41;.add&#40;pnlMain, java.awt.BorderLayout.CENTER&#41;;
    
        &#125;//GEN-END&#58;initComponents
        
        
        // Variables declaration - do not modify//GEN-BEGIN&#58;variables
        private javax.swing.JPanel pnlMain;
        // End of variables declaration//GEN-END&#58;variables
        
    &#125;
    The JSP report applet viewer:
    Code:
    <%@ page errorPage="/layouts/erro.jsp" %>
    
    <%
      String appletWidth = "750";
      String appletHeight = "600";
    %>
    
    <html>
    <head>
    <title>Report Viewer</title>
    </head>
    <body BGCOLOR="#ffffff" LINK="#000099">
    <!--"CONVERTED_APPLET"-->
    <!-- HTML CONVERTER -->
    <SCRIPT LANGUAGE="JavaScript"><!--
        var _info = navigator.userAgent; 
        var _ns = false; 
        var _ns6 = false;
        var _ie = &#40;_info.indexOf&#40;"MSIE"&#41; > 0 && _info.indexOf&#40;"Win"&#41; > 0 && _info.indexOf&#40;"Windows 3.1"&#41; < 0&#41;;
    //--></SCRIPT>
    <COMMENT>
    <SCRIPT LANGUAGE="JavaScript1.1"><!--
            var _ns = &#40;navigator.appName.indexOf&#40;"Netscape"&#41; >= 0 && &#40;&#40;_info.indexOf&#40;"Win"&#41; > 0 && _info.indexOf&#40;"Win16"&#41; < 0 && java.lang.System.getProperty&#40;"os.version"&#41;.indexOf&#40;"3.5"&#41; < 0&#41; || &#40;_info.indexOf&#40;"Sun"&#41; > 0&#41; || &#40;_info.indexOf&#40;"Linux"&#41; > 0&#41; || &#40;_info.indexOf&#40;"AIX"&#41; > 0&#41; || &#40;_info.indexOf&#40;"OS/2"&#41; > 0&#41;&#41;&#41;;
            var _ns6 = &#40;&#40;_ns == true&#41; && &#40;_info.indexOf&#40;"Mozilla/5"&#41; >= 0&#41;&#41;;
    //--></SCRIPT>
    </COMMENT>
    
    <SCRIPT LANGUAGE="JavaScript"><!--
        if &#40;_ie == true&#41; document.writeln&#40;'<OBJECT classid="clsid&#58;8AD9C840-044E-11D1-B3E9-00805F499D93" WIDTH="<%= appletWidth %>" HEIGHT="<%= appletHeight %>" codebase="http&#58;//java.com/en/download/windows_automatic.jsp"><NOEMBED><XMP>'&#41;;
        else if &#40;_ns == true && _ns6 == false&#41; document.writeln&#40;'<EMBED type="application/x-java-applet;version=1.1.2" CODE = "EmbeddedViewerApplet.class" CODEBASE = "applet" ARCHIVE = "jasperreports-0.6.4-applet.jar" WIDTH="<%= appletWidth %>" HEIGHT="<%= appletHeight %>" REPORT_URL = "<%= request.getParameter&#40;"REPORT_URL"&#41; %>" scriptable=false pluginspage="http&#58;//java.com/en/download/windows_automatic.jsp"><NOEMBED><XMP>'&#41;;
    //--></SCRIPT>
    <APPLET CODE="EmbeddedViewerApplet.class" CODEBASE="applet"
    	ARCHIVE="jasperreports-0.6.4-applet.jar" WIDTH="<%= appletWidth %>" HEIGHT="<%= appletHeight %>"></XMP>
    	<PARAM NAME=CODE VALUE="EmbeddedViewerApplet.class">
    	<PARAM NAME=CODEBASE VALUE="applet">
    	<PARAM NAME=ARCHIVE VALUE="jasperreports-0.6.4-applet.jar">
    
    	<PARAM NAME="type" VALUE="application/x-java-applet;version=1.2.2">
    	<PARAM NAME="scriptable" VALUE="false">
    	<PARAM NAME="REPORT_URL" VALUE="<%= request.getParameter&#40;"REPORT_URL"&#41; %>">
    
    
    </APPLET>
    </NOEMBED>
    </EMBED>
    </OBJECT>
    
    <!--
    <APPLET CODE = "EmbeddedViewerApplet.class" CODEBASE = "applet" ARCHIVE = "jasperreports-0.6.4-applet.jar" WIDTH="<%= appletWidth %>" HEIGHT="<%= appletHeight %>">
    <PARAM NAME = "REPORT_URL" VALUE ="<%= request.getParameter&#40;"REPORT_URL"&#41; %>">
    
    
    </APPLET>
    -->
    <!--"END_CONVERTED_APPLET"-->
    
    </body>
    </html>
    1) The applet make the /site/report.jasper request;
    2) The ReportController handle the request
    3) The JasperReportsPrintView intercepts, compile and return the JasperPrint object to the applet

    TIA

  • #2
    I've added a JIRA issue for this and targeted it for inclusion in Spring 1.2

    Rob

    Comment


    • #3
      i had a puzzle with your example

      when i type the test.japser request in ie.i meet a mistake
      the infomation is
      org.springframework.beans.factory.BeanCreationExce ption: Error creating bean with name 'report' defined in null: Instantiation of bean failed; nested exception is org.springframework.beans.FatalBeanException: Could not instantiate class [com.JasperReportsPrintView]; constructor threw exception; nested exception is java.lang.IllegalAccessError: tried to access method net.sf.jasperreports.engine.design.JRDefaultCompil er.<init>()V from class org.springframework.web.servlet.view.jasperreports .AbstractJasperReportsView
      org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.createBean(AbstractAuto wireCapableBeanFactory.java:370)

      would i copy someothers jars to lib?
      i user the jasperreport-1.0.1.jar
      thanks for your help

      Comment


      • #4
        Probably you are using an incompatible jar version - try using the jasperreports jar from the Spring distribution.

        Comment


        • #5
          similar problem

          i have a similar problem.
          i am trying to include jasperreports into a spring application. I define a controller that is supposed to generate a pdf-view of some database data. in the dispatcher-servlet i declare a beanNameViewResolver and a JasperReportsPdfView:

          <bean id="jasperViewResolver" class="org.springframework.web.servlet.view.BeanNa meViewResolver">
          <property name="order" value="0"/>
          </bean>

          <bean id="pdfLayout" class="org.springframework.web.servlet.view.jasper reports.JasperReportsPdfView">
          <property name="url" value="/WEB-INF/fileadmin_report.jrxml"/>
          </bean>


          they cooperate with a BaseCommandController:

          ...
          // methods
          protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

          List listOfFolders = folderDao.showFolderList();
          Map model = new HashMap();
          model.put("dataSource", new JRBeanCollectionDataSource (listOfFolders));
          return new ModelAndView(viewName, model);
          }

          I can deploy the application to a Tomcat but when trying to start it I get the error message:

          exception

          javax.servlet.ServletException: Servlet.init() for servlet fileadmin threw exception
          org.apache.catalina.valves.ErrorReportValve.invoke (ErrorReportValve.java:105)
          org.apache.catalina.connector.CoyoteAdapter.servic e(CoyoteAdapter.java:148)
          org.apache.coyote.http11.Http11Processor.process(H ttp11Processor.java:856)
          org.apache.coyote.http11.Http11Protocol$Http11Conn ectionHandler.processConnection(Http11Protocol.jav a:744)
          org.apache.tomcat.util.net.PoolTcpEndpoint.process Socket(PoolTcpEndpoint.java:527)
          org.apache.tomcat.util.net.LeaderFollowerWorkerThr ead.runIt(LeaderFollowerWorkerThread.java:80)
          org.apache.tomcat.util.threads.ThreadPool$ControlR unnable.run(ThreadPool.java:684)
          java.lang.Thread.run(Thread.java:595)

          root cause

          org.springframework.beans.factory.BeanCreationExce ption: Error creating bean with name 'pdfLayout' defined in ServletContext resource [/WEB-INF/fileadmin-servlet.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.FatalBeanException: Could not instantiate class [org.springframework.web.servlet.view.jasperreports .JasperReportsPdfView]; constructor threw exception; nested exception is java.lang.IllegalAccessError: tried to access method net.sf.jasperreports.engine.design.JRDefaultCompil er.<init>()V from class org.springframework.web.servlet.view.jasperreports .AbstractJasperReportsView
          org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.createBean(AbstractAuto wireCapableBeanFactory.java:370)
          org.springframework.beans.factory.support.Abstract BeanFactory.getBean(AbstractBeanFactory.java:226)
          org.springframework.beans.factory.support.Abstract BeanFactory.getBean(AbstractBeanFactory.java:147)
          org.springframework.beans.factory.support.DefaultL istableBeanFactory.preInstantiateSingletons(Defaul tListableBeanFactory.java:275)
          org.springframework.context.support.AbstractApplic ationContext.refresh(AbstractApplicationContext.ja va:318)
          org.springframework.web.context.support.AbstractRe freshableWebApplicationContext.refresh(AbstractRef reshableWebApplicationContext.java:134)
          org.springframework.web.servlet.FrameworkServlet.c reateWebApplicationContext(FrameworkServlet.java:3 05)
          org.springframework.web.servlet.FrameworkServlet.i nitWebApplicationContext(FrameworkServlet.java:250 )
          org.springframework.web.servlet.FrameworkServlet.i nitServletBean(FrameworkServlet.java:219)
          org.springframework.web.servlet.HttpServletBean.in it(HttpServletBean.java:112)
          javax.servlet.GenericServlet.init(GenericServlet.j ava:211)
          org.apache.catalina.valves.ErrorReportValve.invoke (ErrorReportValve.java:105)
          org.apache.catalina.connector.CoyoteAdapter.servic e(CoyoteAdapter.java:148)
          org.apache.coyote.http11.Http11Processor.process(H ttp11Processor.java:856)
          org.apache.coyote.http11.Http11Protocol$Http11Conn ectionHandler.processConnection(Http11Protocol.jav a:744)
          org.apache.tomcat.util.net.PoolTcpEndpoint.process Socket(PoolTcpEndpoint.java:527)
          org.apache.tomcat.util.net.LeaderFollowerWorkerThr ead.runIt(LeaderFollowerWorkerThread.java:80)
          org.apache.tomcat.util.threads.ThreadPool$ControlR unnable.run(ThreadPool.java:684)
          java.lang.Thread.run(Thread.java:595)

          anyone any idea?

          Comment

          Working...
          X