title: Integrating Pentaho Reporting with Java web application
body: <p>I am trying to integrate my Pentaho generated reports with a Java application. My reports are based on OLAP data and written using MDX queries. I found an example on one of the blogs and used it as foundation. My code is:</p>
  
  <pre><code>package org.pentaho.reporting.engine.classic.samples;
  
  import in.nic.spaconsole.ServletContextProvider;
  
  import java.io.File;
  import java.io.IOException;
  import java.net.URL;
  import java.util.Map;
  import java.util.HashMap;
  
  import org.pentaho.reporting.engine.classic.core.DataFactory;
  import org.pentaho.reporting.engine.classic.core.MasterReport;
  import org.pentaho.reporting.engine.classic.core.ReportProcessingException;
  import org.pentaho.reporting.libraries.resourceloader.Resource;
  import org.pentaho.reporting.libraries.resourceloader.ResourceException;
  import org.pentaho.reporting.libraries.resourceloader.ResourceManager;
  
  /**
   * Generates a report in the following scenario:
   * &lt;ol&gt;
   * &lt;li&gt;The report definition file is a .prpt file which will be loaded and parsed
   * &lt;li&gt;The data factory is a simple JDBC data factory using HSQLDB
   * &lt;li&gt;There are no runtime report parameters used
   * &lt;/ol&gt;
   */
  public class Sample1 extends AbstractReportGenerator
  {
    /**
     * Default constructor for this sample report generator
     */
  
  
    public Sample1()
    {
    }
  
    /**
     * Returns the report definition which will be used to generate the report. In this case, the report will be
     * loaded and parsed from a file contained in this package.
     *
     * @return the loaded and parsed report definition to be used in report generation.
     */
    public MasterReport getReportDefinition(String reportPath)
    {
        ResourceManager manager = new ResourceManager();
  
        manager.registerDefaults();
  
  
        try {
         Resource res = manager.createDirectly(new URL(reportPath),
         MasterReport.class);
        MasterReport report = (MasterReport) res.getResource();
        return report;
         } catch (Exception e) {
        e.printStackTrace(); 
  
        }
         return null;
    }
  
    /**
     * Returns the data factory which will be used to generate the data used during report generation. In this example,
     * we will return null since the data factory has been defined in the report definition.
     *
     * @return the data factory used with the report generator
     */
    public DataFactory getDataFactory()
    {
      return null;
    }
  
    /**
     * Returns the set of runtime report parameters. This sample report uses the following three parameters:
     * &lt;ul&gt;
     * &lt;li&gt;&lt;b&gt;Report Title&lt;/b&gt; - The title text on the top of the report&lt;/li&gt;
     * &lt;li&gt;&lt;b&gt;Customer Names&lt;/b&gt; - an array of customer names to show in the report&lt;/li&gt;
     * &lt;li&gt;&lt;b&gt;Col Headers BG Color&lt;/b&gt; - the background color for the column headers&lt;/li&gt;
     * &lt;/ul&gt;
     *
     * @return &lt;code&gt;null&lt;/code&gt; indicating the report generator does not use any report parameters
     */
    public Map&lt;String, Object&gt; getReportParameters()
    {
        final Map parameters = new HashMap&lt;String, Object&gt;();
          parameters.put("stday", 28);
          parameters.put("styear", 2012);
          parameters.put("stmonth", 10);
          parameters.put("eday", 28);
          parameters.put("eyear", 2012);
          parameters.put("emonth", 10);
          parameters.put("Sitesearch","india.gov.in");
          parameters.put("firstResult",1);
          parameters.put("lastResult", 100);
          parameters.put("Pagenumber",1);
          return parameters;
    }
  
    /**
     * Simple command line application that will generate a PDF version of the report. In this report,
     * the report definition has already been created with the Pentaho Report Designer application and
     * it located in the same package as this class. The data query is located in that report definition
     * as well, and there are a few report-modifying parameters that will be passed to the engine at runtime.
     * &lt;p/&gt;
     * The output of this report will be a PDF file located in the current directory and will be named
     * &lt;code&gt;SimpleReportGeneratorExample.pdf&lt;/code&gt;. 
     *
     * @param args none
     * @throws IOException indicates an error writing to the filesystem
     * @throws ReportProcessingException indicates an error generating the report
     */
  
  
  
  
    public static void main(String[] args) throws IOException, ReportProcessingException
    {
  
        final File outputFilenamehtml = new File(Sample1.class.getSimpleName() + ".html");
        final File outputFilenamepdf = new File(Sample1.class.getSimpleName() + ".pdf");
          // Generate the report
  //     new Sample1().generateReport(AbstractReportGenerator.OutputType.PDF, outputFilenamepdf);
      //    System.err.println("Generated the report [" + outputFilenamepdf.getAbsolutePath() + "]");
       //   new Sample1().generateReport(AbstractReportGenerator.OutputType.HTML, outputFilenamehtml);
      // Output the location of the file
      //System.err.println("Generated the report111 [" + outputFilenamehtml.getAbsolutePath() + "]");
    }
  
  public void report(String Path) throws IllegalArgumentException, ReportProcessingException, IOException {
      // TODO Auto-generated method stub
  
       // final File outputFilenamehtml = new File(Sample1.class.getSimpleName() + ".html");
        final File outputFilenamepdf = new File(Sample1.class.getSimpleName() + ".pdf");
          // Generate the report
         new Sample1().generateReport(AbstractReportGenerator.OutputType.PDF, outputFilenamepdf,Path);
          System.err.println("Generated the report [" + outputFilenamepdf.getAbsolutePath() + "]");
        //  new Sample1().generateReport(AbstractReportGenerator.OutputType.HTML, outputFilenamehtml,Path);
    // Output the location of the file
   // System.err.println("Generated the report111 [" + outputFilenamehtml.getAbsolutePath() + "]");
  }
  }
  
  Abstractreportgenerator.java
  
  /*
   * This program is free software; you can redistribute it and/or modify it under the
   * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
   * Foundation.
   *
   * You should have received a copy of the GNU Lesser General Public License along with this
   * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
   * or from the Free Software Foundation, Inc.,
   * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
   *
   * This program 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.
   *
   * Copyright (c) 2009 Pentaho Corporation..  All rights reserved.
   */
  
  package org.pentaho.reporting.engine.classic.samples;
  
  import java.io.BufferedOutputStream;
  import java.io.File;
  import java.io.FileOutputStream;
  import java.io.IOException;
  import java.io.OutputStream;
  import java.util.Map;
  
  import org.pentaho.reporting.engine.classic.core.ClassicEngineBoot;
  import org.pentaho.reporting.engine.classic.core.DataFactory;
  import org.pentaho.reporting.engine.classic.core.MasterReport;
  import org.pentaho.reporting.engine.classic.core.ReportProcessingException;
  import org.pentaho.reporting.engine.classic.core.layout.output.AbstractReportProcessor;
  import org.pentaho.reporting.engine.classic.core.modules.output.pageable.base.PageableReportProcessor;
  import org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.PdfOutputProcessor;
  import org.pentaho.reporting.engine.classic.core.modules.output.table.base.FlowReportProcessor;
  import org.pentaho.reporting.engine.classic.core.modules.output.table.base.StreamReportProcessor;
  import org.pentaho.reporting.engine.classic.core.modules.output.table.html.AllItemsHtmlPrinter;
  import org.pentaho.reporting.engine.classic.core.modules.output.table.html.FileSystemURLRewriter;
  import org.pentaho.reporting.engine.classic.core.modules.output.table.html.HtmlOutputProcessor;
  import org.pentaho.reporting.engine.classic.core.modules.output.table.html.HtmlPrinter;
  import org.pentaho.reporting.engine.classic.core.modules.output.table.html.StreamHtmlOutputProcessor;
  import org.pentaho.reporting.engine.classic.core.modules.output.table.xls.FlowExcelOutputProcessor;
  import org.pentaho.reporting.libraries.repository.ContentLocation;
  import org.pentaho.reporting.libraries.repository.DefaultNameGenerator;
  import org.pentaho.reporting.libraries.repository.stream.StreamRepository;
  
  /**
   * This is the base class used with the report generation examples. It contains the actual &lt;code&gt;embedding&lt;/code&gt;
   * of the reporting engine and report generation. All example embedded implementations will need to extend this class
   * and perform the following:
   * &lt;ol&gt;
   * &lt;li&gt;Implement the &lt;code&gt;getReportDefinition()&lt;/code&gt; method and return the report definition (how the report
   * definition is generated is up to the implementing class).
   * &lt;li&gt;Implement the &lt;code&gt;getTableDataFactory()&lt;/code&gt; method and return the data factory to be used (how
   * this is created is up to the implementing class).
   * &lt;li&gt;Implement the &lt;code&gt;getReportParameters()&lt;/code&gt; method and return the set of report parameters to be used.
   * If no report parameters are required, then this method can simply return &lt;code&gt;null&lt;/code&gt;
   * &lt;/ol&gt;
   */
  public abstract class AbstractReportGenerator
  {
    /**
     * The supported output types for this sample
     */
    public static enum OutputType
    {
      PDF, EXCEL, HTML
    }
  
    /**
     * Performs the basic initialization required to generate a report
     */
    public AbstractReportGenerator()
    {
      // Initialize the reporting engine
      ClassicEngineBoot.getInstance().start();
    }
  
    /**
     * Returns the report definition used by this report generator. If this method returns &lt;code&gt;null&lt;/code&gt;,
     * the report generation process will throw a &lt;code&gt;NullPointerException&lt;/code&gt;.
     *
     * @return the report definition used by thus report generator
     */
    public abstract MasterReport getReportDefinition(String Path);
  
    /**
     * Returns the data factory used by this report generator. If this method returns &lt;code&gt;null&lt;/code&gt;,
     * the report generation process will use the data factory used in the report definition.
     *
     * @return the data factory used by this report generator
     */
    public abstract DataFactory getDataFactory();
  
    /**
     * Returns the set of parameters that will be passed to the report generation process. If there are no parameters
     * required for report generation, this method may return either an empty or a &lt;code&gt;null&lt;/code&gt; &lt;code&gt;Map&lt;/code&gt;
     *
     * @return the set of report parameters to be used by the report generation process, or &lt;code&gt;null&lt;/code&gt; if no
     *         parameters are required.
     */
    public abstract Map&lt;String, Object&gt; getReportParameters();
  
    /**
     * Generates the report in the specified &lt;code&gt;outputType&lt;/code&gt; and writes it into the specified
     * &lt;code&gt;outputFile&lt;/code&gt;.
     *
     * @param outputType the output type of the report (HTML, PDF, HTML)
     * @param outputStream2 the file into which the report will be written
     * @throws IllegalArgumentException  indicates the required parameters were not provided
     * @throws IOException               indicates an error opening the file for writing
     * @throws ReportProcessingException indicates an error generating the report
     */
    public void generateReport(final OutputType outputType,File outputFile,String Path)
        throws IllegalArgumentException, IOException, ReportProcessingException
    {
      if (outputFile == null)
      {
        throw new IllegalArgumentException("The output file was not specified");
      }
  
      OutputStream outputStream = null;
      try
      {
        // Open the output stream
        outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));
  
        // Generate the report to this output stream
        generateReport(outputType, outputStream,Path);
      }
      finally
      {
        if (outputStream != null)
        {
          outputStream.close();
        }
      }
    }
  
    /**
     * Generates the report in the specified &lt;code&gt;outputType&lt;/code&gt; and writes it into the specified
     * &lt;code&gt;outputStream&lt;/code&gt;.
     * &lt;p/&gt;
     * It is the responsibility of the caller to close the &lt;code&gt;outputStream&lt;/code&gt;
     * after this method is executed.
     *
     * @param outputType   the output type of the report (HTML, PDF, HTML)
     * @param outputStream the stream into which the report will be written
     * @throws IllegalArgumentException  indicates the required parameters were not provided
     * @throws ReportProcessingException indicates an error generating the report
     */
    public void generateReport(final OutputType outputType, OutputStream outputStream,String Path)
        throws IllegalArgumentException, ReportProcessingException
    {
      if (outputStream == null)
      {
        throw new IllegalArgumentException("The output stream was not specified");
      }
  
      // Get the report and data factory
      final MasterReport report = getReportDefinition(Path);
      final DataFactory dataFactory = getDataFactory();
  
      // Set the data factory for the report
      if (dataFactory != null)
      {
        report.setDataFactory(dataFactory);
      }
  
      // Add any parameters to the report
      final Map&lt;String, Object&gt; reportParameters = getReportParameters();
      if (null != reportParameters)
      {
        for (String key : reportParameters.keySet())
        {
          report.getParameterValues().put(key, reportParameters.get(key));
        }
      }
  
      // Prepare to generate the report
      AbstractReportProcessor reportProcessor = null;
      try
      {
        // Greate the report processor for the specified output type
        switch (outputType)
        {
          case PDF:
          {
            final PdfOutputProcessor outputProcessor =
                new PdfOutputProcessor(report.getConfiguration(), outputStream, report.getResourceManager());
            reportProcessor = new PageableReportProcessor(report, outputProcessor);
            break;
          }
  
          case EXCEL:
          {
            final FlowExcelOutputProcessor target =
                new FlowExcelOutputProcessor(report.getConfiguration(), outputStream, report.getResourceManager());
            reportProcessor = new FlowReportProcessor(report, target);
            break;
  
          }
  
          case HTML:
          {
            final StreamRepository targetRepository = new StreamRepository(outputStream);
            final ContentLocation targetRoot = targetRepository.getRoot();
            final HtmlOutputProcessor outputProcessor = new StreamHtmlOutputProcessor(report.getConfiguration());
            final HtmlPrinter printer = new AllItemsHtmlPrinter(report.getResourceManager());
            printer.setContentWriter(targetRoot, new DefaultNameGenerator(targetRoot, "index", "html"));
            printer.setDataWriter(null, null);
            printer.setUrlRewriter(new FileSystemURLRewriter());
            outputProcessor.setPrinter(printer);
            reportProcessor = new StreamReportProcessor(report, outputProcessor);
            break;
          }
        }
  
        // Generate the report
        reportProcessor.processReport();
      }
      finally
      {
        if (reportProcessor != null)
        {
          reportProcessor.close();
        }
      }
    }
  }
  
  and I have a controller that ivokes this sample1.java
  
  @POST
      @Path("/get/reportDisplay")
      @Consumes(MediaType.APPLICATION_JSON)
      @Produces(MediaType.TEXT_HTML)
      public Response exportReport(final ReportBean reportBean,
              @Context final HttpServletRequest request,
              @Context final HttpServletResponse response,
              @Context final ServletContext context) throws IOException,
              ParseException, InstantiationException, IllegalAccessException,
              ClassNotFoundException, SQLException, JRException, IllegalArgumentException,ReportProcessingException {
  
          String reportPath ="file://" +context.getRealPath("anor_admin.prpt");
          Sample1 sample=new Sample1();
          sample.report(reportPath);
          return Response.status(200).build();             
      }
      //End of Methods
  } //End of class
  </code></pre>
  
  <p>But I am getting errors and not able to preview my reports. Please help me with this.</p>