/** 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());
   }
 }
Esempio n. 2
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;
  }
  @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();
    }
  }
Esempio n. 4
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) {

    }
  }