提问者:小点点

将Pentaho报告与JavaWeb应用程序集成


我正在尝试将我的Pentaho生成的报告与Java应用程序集成。我的报告基于OLAP数据并使用MDX查询编写。我在其中一个博客上找到了一个示例并将其用作基础。我的代码是:

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:
 * <ol>
 * <li>The report definition file is a .prpt file which will be loaded and parsed
 * <li>The data factory is a simple JDBC data factory using HSQLDB
 * <li>There are no runtime report parameters used
 * </ol>
 */
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:
   * <ul>
   * <li><b>Report Title</b> - The title text on the top of the report</li>
   * <li><b>Customer Names</b> - an array of customer names to show in the report</li>
   * <li><b>Col Headers BG Color</b> - the background color for the column headers</li>
   * </ul>
   *
   * @return <code>null</code> indicating the report generator does not use any report parameters
   */
  public Map<String, Object> getReportParameters()
  {
      final Map parameters = new HashMap<String, Object>();
        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.
   * <p/>
   * The output of this report will be a PDF file located in the current directory and will be named
   * <code>SimpleReportGeneratorExample.pdf</code>. 
   *
   * @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 <code>embedding</code>
 * of the reporting engine and report generation. All example embedded implementations will need to extend this class
 * and perform the following:
 * <ol>
 * <li>Implement the <code>getReportDefinition()</code> method and return the report definition (how the report
 * definition is generated is up to the implementing class).
 * <li>Implement the <code>getTableDataFactory()</code> method and return the data factory to be used (how
 * this is created is up to the implementing class).
 * <li>Implement the <code>getReportParameters()</code> method and return the set of report parameters to be used.
 * If no report parameters are required, then this method can simply return <code>null</code>
 * </ol>
 */
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 <code>null</code>,
   * the report generation process will throw a <code>NullPointerException</code>.
   *
   * @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 <code>null</code>,
   * 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 <code>null</code> <code>Map</code>
   *
   * @return the set of report parameters to be used by the report generation process, or <code>null</code> if no
   *         parameters are required.
   */
  public abstract Map<String, Object> getReportParameters();

  /**
   * Generates the report in the specified <code>outputType</code> and writes it into the specified
   * <code>outputFile</code>.
   *
   * @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 <code>outputType</code> and writes it into the specified
   * <code>outputStream</code>.
   * <p/>
   * It is the responsibility of the caller to close the <code>outputStream</code>
   * 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<String, Object> 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

但是我收到错误,无法预览我的报告。请帮帮我。


共1个答案

匿名用户

我已经成功地将报表引擎嵌入到Web应用程序中,但我必须修复一些类路径错误才能使其正常工作。

请确保您的战争包括report-engine-Classic. core.jar和lib*。jar来自pentaho-库。如果您使用图表,则需要额外的依赖项。

你犯了什么样的错误?