/** Test passing reportContext */
 @SuppressWarnings("unchecked")
 @Test
 public void testExecute1() {
   try {
     final IReportEngine reportEngine = ReportEngine.getReportEngine();
     final InputStream is =
         this.getClass().getResourceAsStream("/reports/test_display_parameters.rptdesign");
     final IReportRunnable design = reportEngine.openReportDesign(is);
     final IGetParameterDefinitionTask paramTask =
         reportEngine.createGetParameterDefinitionTask(design);
     List<EngineException> errors = null;
     try {
       final IRunAndRenderTask rrTask = reportEngine.createRunAndRenderTask(design);
       final Map<String, Object> appContext = rrTask.getAppContext();
       final ClassLoader classLoader = getClass().getClassLoader();
       appContext.put(EngineConstants.APPCONTEXT_CLASSLOADER_KEY, classLoader);
       // rrTask.setAppContext(appContext);
       try {
         final ByteArrayOutputStream os = new ByteArrayOutputStream();
         final RenderOption options = new HTMLRenderOption();
         options.setOutputFormat("HTML");
         options.setOutputStream(os);
         rrTask.setRenderOption(options);
         rrTask.run();
         errors = rrTask.getErrors();
         String output = os.toString("utf-8");
         System.out.println(output);
         Assert.assertTrue(output.indexOf("Australian Collectors, Co.") >= 0);
         Assert.assertTrue(output.indexOf("NewParameter") >= 0);
         Assert.assertTrue(output.indexOf("abc") >= 0);
       } finally {
         rrTask.close();
       }
     } finally {
       paramTask.close();
     }
     if (errors != null) {
       Iterator<EngineException> iterator = errors.iterator();
       if (iterator.hasNext()) {
         EngineException error = iterator.next();
         Assert.fail("Engine exception: " + error.getMessage());
       }
     }
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
     Assert.fail(e.toString());
   } catch (BirtException e) {
     e.printStackTrace();
     Assert.fail(e.toString());
   }
 }
Example #2
0
  @SuppressWarnings("unchecked")
  public static synchronized void startBirtEngine(IPlatformContext context) {
    log.info("Starting BIRT Engine and OSGI Platform using: " + context.getClass().getName());

    HTMLServerImageHandler imageHandler = new HTMLServerImageHandler();

    HTMLRenderOption emitterConfig = new HTMLRenderOption();
    emitterConfig.setActionHandler(new HTMLActionHandler());
    emitterConfig.setImageHandler(imageHandler);

    EngineConfig config = new EngineConfig();
    config.setEngineHome("");
    config.setPlatformContext(context);
    config.setLogConfig(null, Level.ALL);
    config.getEmitterConfigs().put("html", emitterConfig);

    try {
      Platform.startup(config);
    } catch (BirtException e) {
      log.error("BirtException", e);
    }

    IReportEngineFactory factory =
        (IReportEngineFactory)
            Platform.createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);

    birtEngine = factory.createReportEngine(config);

    log.info("BIRT Engine Started");

    birtEngine.changeLogLevel(Level.SEVERE);
  }
  private Map<String, Object> discoverAndSetParameters(
      IReportRunnable report, HttpServletRequest request) throws Throwable {

    Map<String, Object> parms = new HashMap<String, Object>();
    IGetParameterDefinitionTask task = birtEngine.createGetParameterDefinitionTask(report);
    @SuppressWarnings("unchecked")
    Collection<IParameterDefnBase> params = task.getParameterDefns(true);
    for (IParameterDefnBase param : params) {
      Assert.isInstanceOf(
          IScalarParameterDefn.class,
          param,
          "the parameter must be assignable to " + IScalarParameterDefn.class.getName());
      IScalarParameterDefn scalar = (IScalarParameterDefn) param;
      if (this.reportParameters != null && this.reportParameters.get(param.getName()) != null) {
        String format = scalar.getDisplayFormat();
        // todo will this step on the Spring MVC converters?
        ReportParameterConverter converter =
            new ReportParameterConverter(format, request.getLocale());

        Object value = this.reportParameters.get(param.getName());
        parms.put(param.getName(), value);

        //                       /* converter.parse(*/  this.reportParameters.get(param.getName()),
        // scalar.getDataType()/*)*/);
      } else if (StringUtils.hasText(getParameter(request, param.getName()))) {
        parms.put(param.getName(), getParamValueObject(request, scalar));
      }
    }
    task.close();
    return parms;
  }
Example #4
0
  private void internalShowReport(RptMain report, RptProperties properties, boolean showParams) {
    // используем BIRT Report Viewer только для HTML отчетов, остальные сразу генерируем в нужном
    // формате
    if (properties.getOutputFormat() == null
        || properties.getOutputFormat() == RptProperties.OutputFormat.HTML) {
      StringBuilder sb1 =
          new StringBuilder(reportFolder)
              .append(File.separatorChar)
              .append("report")
              .append(Math.abs(new Random().nextInt()))
              /*.append(report.getCode().trim())*/ .append(REPORT_SUFFIX);
      String relativeFileName = sb1.toString();
      try {
        File f =
            new File(
                sb1.insert(0, File.separatorChar)
                    .insert(0, engine.getConfig().getBIRTHome())
                    .toString());
        FileOutputStream fos = new FileOutputStream(f);
        fos.write(report.getTemplate());
        fos.flush();
        fos.close();
      } catch (Exception e) {
        log.error("Create report file failed", e);
        throw new ReportException(e);
      }

      showHTMLReportViewer(report, relativeFileName, properties, showParams);
    } else fillReport(report, properties);
  }
  private void createInfomation(Composite parent) {

    Font font = parent.getFont();
    Composite continer = createComposite(parent, font, 2, 2, GridData.FILL_BOTH, 0, 0);
    continer.setBackground(fBackgroundColor);
    IReportDocument document = null;
    try {
      document = engine.openReportDocument(getFileName());
      createScriptgLabel(continer, Messages.getString("ReportDocumentEditor.3")); // $NON-NLS-1$
      createScriptgLabel(continer, document.getName());

      createScriptgLabel(continer, Messages.getString("ReportDocumentEditor.4")); // $NON-NLS-1$
      createScriptgLabel(continer, document.getVersion());

      createScriptgLabel(continer, Messages.getString("ReportDocumentEditor.5")); // $NON-NLS-1$
      createScriptgLabel(continer, "" + document.getPageCount()); // $NON-NLS-1$

    } catch (EngineException e) {
      this.e = e;
      createErrorControl(continer);
    } finally {
      if (document != null) {
        document.close();
      }
    }
  }
Example #6
0
 public void init() throws BirtException {
   config = new EngineConfig();
   Platform.startup(config);
   IReportEngineFactory factory =
       (IReportEngineFactory)
           Platform.createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);
   engine = factory.createReportEngine(config);
   engine.changeLogLevel(java.util.logging.Level.WARNING);
 }
Example #7
0
  public void destroy() {
    if (birtEngine == null) return;

    birtEngine.destroy();
    Platform.shutdown();
    birtEngine = null;

    log.info("BIRT Engine and OSGI Platform Shutdown");
  }
Example #8
0
  public void testRunWithArchiveView() throws Exception {
    // 1. create document from ORIGINAL_REPORT_DESIGN_RESOURCE first
    copyResource(ORIGINAL_REPORT_DESIGN_RESOURCE, ORIGINAL_REPORT_DESIGN);
    IReportRunnable report = engine.openReportDesign(ORIGINAL_REPORT_DESIGN);
    IRunTask task = engine.createRunTask(report);
    try {
      task.run(ORIGINAL_REPORT_DOCUMENT);
    } finally {
      task.close();
    }

    // 2. create document from CHANGED_REPORT_DESIGN_RESOURCE
    copyResource(CHANGED_REPORT_DESIGN_RESOURCE, CHANGED_REPORT_DESIGN);

    ArchiveView view = new ArchiveView(ARCHIVE_VIEW_DOCUMENT, ORIGINAL_REPORT_DOCUMENT, "rw");

    try {
      report = engine.openReportDesign(CHANGED_REPORT_DESIGN);
      task = engine.createRunTask(report);
      try {
        // 3. new view archive and render
        ArchiveWriter writer = new ArchiveWriter(view);
        task.setDataSource(new ArchiveReader(view));
        task.run(writer);
      } finally {
        task.close();
      }

      // 3. create golden report document
      report = engine.openReportDesign(CHANGED_REPORT_DESIGN);
      task = engine.createRunTask(report);
      try {
        task.run(CHANGED_REPORT_DOCUMENT);
      } finally {
        task.close();
      }
      IReportDocument goldenDocument = engine.openReportDocument(CHANGED_REPORT_DOCUMENT);
      try {
        IReportDocument ivDocument =
            engine.openReportDocument(null, new ArchiveReader(view), new HashMap());

        try {
          // 5. compare two report document
          compare(goldenDocument, ivDocument);
        } finally {
          ivDocument.close();
        }
      } finally {
        goldenDocument.close();
      }
    } finally {
      view.close();
    }
  }
Example #9
0
  public byte[] getReport(ServletContext sc, HttpServletRequest req) {
    LOG.info("开始渲染报表");
    long start = System.currentTimeMillis();
    float total = (float) Runtime.getRuntime().totalMemory() / 1000000;

    this.birtReportEngine = BirtReportEngine.getBirtEngine(sc);
    IReportRunnable design;
    try {
      LOG.info("report path:" + reportPath);
      reportPath = FileUtils.getAbsolutePath(reportPath);
      LOG.info("report path:" + reportPath);
      design = birtReportEngine.openReportDesign(reportPath);
      IRunAndRenderTask task = birtReportEngine.createRunAndRenderTask(design);

      task.getAppContext().put("BIRT_VIEWER_HTTPSERVLET_REQUEST", req);
      task.setParameterValue("title", "用户图形报表");
      task.setParameterValue("tip", "测试用户报表");

      HTMLRenderOption options = new HTMLRenderOption();
      options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_HTML);
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      options.setOutputStream(out);
      options.setImageHandler(new HTMLServerImageHandler());
      options.setBaseImageURL(SystemListener.getContextPath() + "/platform/reports/images");
      options.setImageDirectory(FileUtils.getAbsolutePath("/platform/reports/images"));
      task.setRenderOption(options);

      task.run();
      task.close();
      total = (float) Runtime.getRuntime().totalMemory() / 1000000 - total;
      LOG.info(
          "完成渲染报表,耗时:"
              + ConvertUtils.getTimeDes(System.currentTimeMillis() - start)
              + " ,耗费内存:"
              + total
              + "M");
      return out.toByteArray();
    } catch (EngineException | NumberFormatException e) {
      LOG.error("输出报表出错", e);
    }
    return null;
  }
  private void init() {
    engineConfig = new LauncherEngineConfig();

    IReportEngineFactory factory =
        (IReportEngineFactory)
            Platform.createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);

    configEngine();
    this.engine = factory.createReportEngine(engineConfig);
    engine.changeLogLevel(Level.WARNING);
  }
Example #11
0
  /** Заполнение отчёта */
  private void fillReport(RptMain report, RptProperties properties) {
    String reportDoc = generateReportFileName(report, properties);

    IReportDocument rd = null;
    byte[] reportResult = null;

    try {
      IRunTask runTask = engine.createRunTask(design);
      setupEngineTask(runTask, properties);
      try {
        runTask.run(reportDoc);
      } finally {
        runTask.close();
      }

      rd = engine.openReportDocument(reportDoc);

      IRenderTask rendTask = engine.createRenderTask(rd);
      setupRenderTask(rendTask, properties);

      try {
        rendTask.render();

        reportResult =
            ((ByteArrayOutputStream) rendTask.getRenderOption().getOutputStream()).toByteArray();
      } finally {
        rendTask.close();
      }
    } catch (EngineException e) {
      if (e.getCause() instanceof ApplicationException) throw (ApplicationException) e.getCause();
      else throw new ReportException(Messages.getInstance().getMessage(Messages.BIRT_ERROR), e);
    } finally {
      if (rd != null) rd.close();
      File f = new File(reportDoc);
      f.delete();
      f = null;
    }

    showReport(report, reportResult, properties);
  }
Example #12
0
  @SuppressWarnings("unchecked")
  private void prepareReportParams(RptProperties properties) {
    externalParams = new HashSet<String>();
    reportParams =
        new LinkedHashMap<
            String,
            ReportParameter>(); // use LinkedHashMap
                                // http://issues.m-g.ru/bugzilla/show_bug.cgi?id=4577
    IGetParameterDefinitionTask paramTask = engine.createGetParameterDefinitionTask(design);
    try {
      Collection<IParameterDefnBase> paramsC = paramTask.getParameterDefns(true);
      for (IParameterDefnBase param : paramsC) {
        if (param instanceof IParameterGroupDefn)
          addGroupReportParameter(
              properties, param.getName(), (IParameterGroupDefn) param, paramTask);
        else if (param instanceof IScalarParameterDefn)
          addReportParameter(
              properties,
              param.getName(),
              (IScalarParameterDefn) param,
              null,
              paramTask.getDefaultValue(param));
      }
    } finally {
      paramTask.close();
    }

    /*
     * BIRT не даёт работать с поименованными параметрами, приходится
     * обходить
     */
    List<DataSetHandle> dshL =
        (List<DataSetHandle>) design.getDesignHandle().getModuleHandle().getAllDataSets();

    for (DataSetHandle dsH : dshL) {
      if (dsH instanceof OdaDataSetHandle
          && MERP_DATASET_ID.equals(((OdaDataSetHandle) dsH).getExtensionID())) {
        ArrayList<String> paramNames = new ArrayList<String>();
        ArrayList<DataSetParameter> prms =
            (ArrayList<DataSetParameter>) dsH.getListProperty("parameters");
        if (prms != null) {
          for (DataSetParameter prm : prms) paramNames.add(prm.getName());

          datasetParams.put(dsH.getStringProperty(BAI_CODE), paramNames);
        }
      }
    }
    // *********************************************************//
  }
Example #13
0
  /**
   * загрузить список значений параметра отчета
   *
   * @param paramName имя параметра
   * @return список значений
   */
  public List<SelectionChoice> getParameterSelectionList(String paramName) {
    IGetParameterDefinitionTask task = null;
    try {
      task = engine.createGetParameterDefinitionTask(design);
      if (task != null) {
        setupEngineTask(task, rptProperties);
        return SelectionChoiceImpl.convertEngineParameterSelectionChoice(
            task.getSelectionList(paramName));
      }
    } finally {
      if (task != null) task.close();
    }

    return null;
  }
Example #14
0
  /**
   * загрузить список значений каскадного параметра
   *
   * @param paramName имя параметра
   * @param groupName имя каскадной группы
   * @param groupKeys список значений параметров находящихся выше по иерархии в каскадной группе
   * @return список значений
   */
  @SuppressWarnings("deprecation")
  public List<SelectionChoice> getSelectionListForCascadingGroup(
      String paramName, String groupName, Object[] groupKeys) {
    IGetParameterDefinitionTask task = null;
    try {
      task = engine.createGetParameterDefinitionTask(design);
      if (task != null) {
        setupEngineTask(task, rptProperties);
        task.evaluateQuery(groupName);
        return SelectionChoiceImpl.convertEngineParameterSelectionChoice(
            task.getSelectionListForCascadingGroup(groupName, groupKeys));
      }
    } finally {
      if (task != null) task.close();
    }

    return null;
  }
Example #15
0
 protected String renderPage(IReportDocument doc, long pageNo) throws Exception {
   ByteArrayOutputStream buffer = new ByteArrayOutputStream();
   assertTrue(pageNo <= doc.getPageCount());
   IRenderTask renderTask = engine.createRenderTask(doc);
   try {
     HTMLRenderOption options = new HTMLRenderOption();
     options.setOutputFormat("html");
     options.setOutputStream(buffer);
     renderTask.setRenderOption(options);
     renderTask.setPageNumber((long) pageNo);
     renderTask.render();
     List errors = renderTask.getErrors();
     assertEquals(0, errors.size());
   } finally {
     renderTask.close();
   }
   return new String(buffer.toString("UTF-8"));
 }
Example #16
0
  static {
    final EngineConfig config = new EngineConfig();
    config.setEngineHome(EMPSettings.birt_home);
    config.setResourcePath("reports/images");
    try {
      // config.setLogConfig(c:/temp, Level.FINE);

      Platform.startup(config); // If using RE API in Eclipse/RCP
      // application this is not needed.
      IReportEngineFactory factory =
          (IReportEngineFactory)
              Platform.createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);
      engine = factory.createReportEngine(config);
      engine.changeLogLevel(Level.SEVERE);

    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Example #17
0
  private void internalRun(RptMain report, RptProperties properties) {
    if (report == null) {
      log.debug("Report entity is null");
      return;
    }

    byte[] reportTemplate = report.getTemplate();
    if (reportTemplate == null)
      throw new ReportException(Messages.getInstance().getMessage(Messages.REPORT_TEMPLATE_NULL));

    try {
      design = engine.openReportDesign(new ByteArrayInputStream(reportTemplate));
    } catch (EngineException ex) {
      throw new ReportException(Messages.getInstance().getMessage(Messages.BIRT_ERROR), ex);
    }

    this.rptProperties = properties;
    prepareReportParams(properties);

    if (!reportParams.isEmpty()) executeParamsDialog(report, properties);
    else internalShowReport(report, properties, true);
  }
Example #18
0
 private void shutdown() {
   engine.destroy();
   Platform.shutdown();
 }
Example #19
0
  private void runTasks(int reportType, String date) throws EngineException, IOException {
    File reportDesign = null;
    String outFile = EMPSettings.path_to_report_private_folder + "/";
    StringBuffer feederContent = new StringBuffer();
    feederContent.append("title;file;date;frequency;type\n");
    switch (reportType) {
      case BirtIntegration.SMP_IMAGES:
        String date1 = date.split("#")[0];
        String date2 = date.split("#")[1];
        reportDesign = new File("reports/smp-previous.rptdesign");
        outFile += "images/image" + date2 + ".html";
        FileInputStream fis = new FileInputStream(reportDesign);
        IReportRunnable design = engine.openReportDesign(fis);
        IRunAndRenderTask task = engine.createRunAndRenderTask(design);
        task.setLocale(new Locale("en-US"));
        task.getAppContext()
            .put(
                EngineConstants.APPCONTEXT_CLASSLOADER_KEY, BirtIntegration.class.getClassLoader());
        task.setParameterValue("dateToForecast", (date1));
        task.setParameterValue("dateToForecast2", (date2));
        task.validateParameters();
        HTMLRenderOption options = new HTMLRenderOption();
        options.setOutputFileName(outFile);
        options.setOutputFormat("html");
        options.setEmbeddable(true);
        task.setRenderOption(options);
        task.run();
        task.close();
        System.out.println("Wait a second !");
        try {
          Thread.sleep(1000);
        } catch (Exception e) {
        }
        Document doc = Jsoup.parse(new File(outFile), "UTF-8", "");
        String imagePath = doc.select("#__bookmark_1").attr("src");
        File afile = new File(imagePath.replace("file:", ""));
        System.out.println("temp image path is : " + afile);
        String newPath = EMPSettings.smp_photos + "/smp_" + date2 + ".png";
        File bfile = new File(newPath);
        System.out.println("moving temp image to : " + newPath);
        InputStream inStream = null;
        OutputStream outStream = null;
        System.out.println("opening file to read...");
        inStream = new FileInputStream(afile);
        System.out.println("opening file to write ...");
        outStream = new FileOutputStream(bfile);
        byte[] buffer = new byte[1024];
        int length;
        System.out.print("copying file contents...");
        while ((length = inStream.read(buffer)) > 0) {
          System.out.print(".");
          outStream.write(buffer, 0, length);
        }
        System.out.println("\\nFinished !");
        inStream.close();
        outStream.close();
        return;
      case BirtIntegration.EMP_DAILY_POWER:
        reportDesign = new File("reports/emp_daily.rptdesign");
        outFile +=
            EMPSettings.energy_path
                + "/"
                + EMPSettings.daily_path
                + "/"
                + EMPSettings.report_prefix
                + "-"
                + EMPSettings.power_prefix
                + "-"
                + EMPSettings.daily_prefix
                + "_"
                + date
                + ".pdf";
        feederContent.append(
            "energy_daily_"
                + date
                + ";sites/all/files/private/energy/daily/"
                + EMPSettings.report_prefix
                + "-"
                + EMPSettings.power_prefix
                + "-"
                + EMPSettings.daily_prefix
                + "_"
                + date
                + ".pdf"
                + ";"
                + date
                + ";Daily;Energy");
        try {
          runTasks(BirtIntegration.SMP_IMAGES, date + "#7");
          runTasks(BirtIntegration.SMP_IMAGES, date + "#15");
          runTasks(BirtIntegration.SMP_IMAGES, date + "#30");
          runTasks(BirtIntegration.SMP_IMAGES, date + "#60");
          runTasks(BirtIntegration.SMP_IMAGES, date + "#90");
          runTasks(BirtIntegration.SMP_IMAGES, date + "#180");
          runTasks(BirtIntegration.SMP_IMAGES, date + "#360");
        } catch (Exception e) {
          e.printStackTrace();
        }
        break;
      case BirtIntegration.EMP_WEEKLY_POWER:
        reportDesign = new File("reports/emp_weekly.rptdesign");
        outFile +=
            EMPSettings.energy_path
                + "/"
                + EMPSettings.weekly_path
                + "/"
                + EMPSettings.report_prefix
                + "-"
                + EMPSettings.power_prefix
                + "-"
                + EMPSettings.weekly_prefix
                + "_"
                + date
                + ".pdf";
        feederContent.append(
            "energy_weekly_"
                + date
                + ";sites/all/files/private/energy/weekly/"
                + EMPSettings.report_prefix
                + "-"
                + EMPSettings.power_prefix
                + "-"
                + EMPSettings.weekly_prefix
                + "_"
                + date
                + ".pdf"
                + ";"
                + date
                + ";Weekly;Energy");
        break;
      case BirtIntegration.EMP_WEEKLY_EMMISSIONS:
        reportDesign = new File("reports/emp_emissions.rptdesign");
        outFile +=
            EMPSettings.emissions_path
                + "/"
                + EMPSettings.weekly_path
                + "/"
                + EMPSettings.report_prefix
                + "-"
                + EMPSettings.emmissions_prefix
                + "-"
                + EMPSettings.weekly_prefix
                + "_"
                + date
                + ".pdf";
        feederContent.append(
            "emissions_weekly_"
                + date
                + ";sites/all/files/private/emissions/weekly/"
                + EMPSettings.report_prefix
                + "-"
                + EMPSettings.emmissions_prefix
                + "-"
                + EMPSettings.weekly_prefix
                + "_"
                + date
                + ".pdf"
                + ";"
                + date
                + ";Weekly;Emission");
        break;
      default:
        break;
    }

    FileOutputStream fos = new FileOutputStream(new File(EMPSettings.feeder_file_path));
    fos.write(feederContent.toString().getBytes());
    fos.close();

    // Open the report design
    FileInputStream fis = new FileInputStream(reportDesign);
    IReportRunnable design = engine.openReportDesign(fis);
    // Create task to run and render the report,
    IRunAndRenderTask task = engine.createRunAndRenderTask(design);
    task.setLocale(new Locale("en-US"));
    // Set parent classloader for engine
    task.getAppContext()
        .put(EngineConstants.APPCONTEXT_CLASSLOADER_KEY, BirtIntegration.class.getClassLoader());

    // Set parameter values and validate
    task.setParameterValue("dateToForecast", (date));
    task.validateParameters();

    // Setup rendering to HTML
    PDFRenderOption options = new PDFRenderOption();
    options.setOutputFileName(outFile);
    options.setOutputFormat("pdf");

    task.setRenderOption(options);
    // run and render report
    task.run();
    task.close();

    // Call cron of the drupal site to manage the feed
    try {
      InputStream resp = new URL(EMPSettings.cron).openStream();
    } catch (MalformedURLException e) {

    } catch (IOException e) {

    }
  }
  @SuppressWarnings("unchecked")
  protected void renderMergedOutputModel(
      Map<String, Object> modelData, HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    FileInputStream fis = null;
    IReportRunnable runnable = null;
    IReportDocument document = null;
    try {

      if (this.reportParameters == null) this.reportParameters = new HashMap<String, Object>();

      for (String k : modelData.keySet()) this.reportParameters.put(k, modelData.get(k));

      // 2) reportName property
      // 1) report name parameter is available, use that

      String reportName;
      reportName =
          StringUtils.hasText(this.reportName)
              ? this.reportName
              : request.getParameter(this.reportNameRequestParameter); // 'cat'
      String fullReportName = canonicalizeName(reportName);

      String documentName;
      documentName =
          StringUtils.hasText(this.documentName)
              ? this.documentName
              : request.getParameter(this.documentNameRequestParameter); // 'cat'
      String fullDocumentName = canonicalizeDocName(documentName);
      if (documentName == null) {
        fullDocumentName = reportName.replaceAll(".rptdesign", ".rptdocument");
      }

      String format;
      if (this.reportOutputFormat != null) {
        format = this.reportOutputFormat;
      } else {
        format = request.getParameter(this.reportFormatRequestParameter);
      }
      ServletContext sc =
          request.getServletContext(); // / avoid creating an HTTP session if possible.

      if (format == null) {
        format = "html";
      }

      Map<String, Object> mapOfOptions = new HashMap<String, Object>();
      mapOfOptions.put(
          IModuleOption.RESOURCE_FOLDER_KEY,
          birtViewResourcePathCallback.resourceDirectory(sc, request, reportName));
      mapOfOptions.put(IModuleOption.PARSER_SEMANTIC_CHECK_KEY, Boolean.FALSE);

      // set content type
      String contentType = birtEngine.getMIMEType(format);
      response.setContentType(contentType);
      setContentType(contentType);

      Map<String, Object> appContextMap = new HashMap<String, Object>();
      appContextMap.put(EngineConstants.APPCONTEXT_BIRT_VIEWER_HTTPSERVET_REQUEST, request);

      if (this.dataSource != null) {
        appContextMap.put(IConnectionFactory.PASS_IN_CONNECTION, this.dataSource.getConnection());

        if (this.closeDataSourceConnection)
          appContextMap.put(IConnectionFactory.CLOSE_PASS_IN_CONNECTION, Boolean.TRUE);
      }

      IEngineTask task = null;
      String pathForReport =
          birtViewResourcePathCallback.pathForReport(sc, request, fullReportName);
      fis = new FileInputStream(pathForReport);
      runnable = birtEngine.openReportDesign(fullReportName, fis, mapOfOptions);

      if (runnable != null && this.taskType == AbstractSingleFormatBirtView.RUNRENDERTASK) {
        task = birtEngine.createRunAndRenderTask(runnable);
        task.setParameterValues(discoverAndSetParameters(runnable, request));
        IRunAndRenderTask runAndRenderTask = (IRunAndRenderTask) task;
        IRenderOption options = null == this.renderOption ? new RenderOption() : this.renderOption;
        options.setActionHandler(actionHandler);
        IRenderOption returnedRenderOptions =
            renderReport(
                modelData,
                request,
                response,
                this.birtViewResourcePathCallback,
                appContextMap,
                reportName,
                format,
                options);
        for (String k : appContextMap.keySet())
          runAndRenderTask.getAppContext().put(k, appContextMap.get(k));
        runAndRenderTask.setRenderOption(returnedRenderOptions);
        runAndRenderTask.run();
        runAndRenderTask.close();
      } else {

        // Run then Render
        if (runnable != null) {
          task = birtEngine.createRunTask(runnable);
          task.setParameterValues(discoverAndSetParameters(runnable, request));
          IRunTask runTask = (IRunTask) task;
          for (String k : appContextMap.keySet())
            runTask.getAppContext().put(k, appContextMap.get(k));
          String pathForDocument =
              birtViewResourcePathCallback.pathForDocument(sc, request, fullDocumentName);
          runTask.run(pathForDocument);
          runTask.close();
          document = birtEngine.openReportDocument(fullDocumentName, pathForDocument, mapOfOptions);
          task = birtEngine.createRenderTask(document);
          IRenderTask renderTask = (IRenderTask) task;
          IRenderOption options =
              null == this.renderOption ? new RenderOption() : this.renderOption;
          options.setActionHandler(actionHandler);
          IRenderOption returnedRenderOptions =
              renderReport(
                  modelData,
                  request,
                  response,
                  this.birtViewResourcePathCallback,
                  appContextMap,
                  reportName,
                  format,
                  options);
          for (String k : appContextMap.keySet())
            renderTask.getAppContext().put(k, appContextMap.get(k));
          if (renderRange != null) {

            renderTask.setPageRange(renderRange);
          }
          renderTask.setRenderOption(returnedRenderOptions);
          renderTask.render();
          renderTask.close();
          document.close();
        }
      }

    } catch (Throwable th) {
      throw new RuntimeException(th); // nothing useful to do here
    } finally {
      if (null != fis) IOUtils.closeQuietly(fis);
      if (null != document) document.close();
    }
  }
Example #21
0
 public void tearDown() {
   removeFile(ORIGINAL_REPORT_DESIGN);
   removeFile(CHANGED_REPORT_DESIGN);
   engine.destroy();
 }