Search in sources :

Example 6 with JasperPrint

use of net.sf.jasperreports.engine.JasperPrint in project midpoint by Evolveum.

the class ReportCreateTaskHandler method run.

@Override
public TaskRunResult run(Task task) {
    // TODO Auto-generated method stub
    OperationResult parentResult = task.getResult();
    OperationResult result = parentResult.createSubresult(ReportCreateTaskHandler.class.getSimpleName() + ".run");
    TaskRunResult runResult = new TaskRunResult();
    runResult.setOperationResult(result);
    recordProgress(task, 0, result);
    long progress = task.getProgress();
    JRSwapFile swapFile = null;
    // http://community.jaspersoft.com/wiki/virtualizers-jasperreports
    JRAbstractLRUVirtualizer virtualizer = null;
    try {
        ReportType parentReport = objectResolver.resolve(task.getObjectRef(), ReportType.class, null, "resolving report", task, result);
        Map<String, Object> parameters = completeReport(parentReport, task, result);
        JasperReport jasperReport = ReportTypeUtil.loadJasperReport(parentReport);
        LOGGER.trace("compile jasper design, create jasper report : {}", jasperReport);
        PrismContainer<ReportParameterType> reportParams = (PrismContainer) task.getExtensionItem(ReportConstants.REPORT_PARAMS_PROPERTY_NAME);
        if (reportParams != null) {
            PrismContainerValue<ReportParameterType> reportParamsValues = reportParams.getValue();
            List<Item<?, ?>> items = reportParamsValues.getItems();
            if (items != null) {
                for (Item item : items) {
                    PrismProperty pp = (PrismProperty) item;
                    String paramName = ItemPath.getName(pp.getPath().lastNamed()).getLocalPart();
                    Object value = null;
                    if (isSingleValue(paramName, jasperReport.getParameters())) {
                        value = pp.getRealValues().iterator().next();
                    } else {
                        value = pp.getRealValues();
                    }
                    parameters.put(paramName, value);
                }
            }
        }
        String virtualizerS = parentReport.getVirtualizer();
        Integer virtualizerKickOn = parentReport.getVirtualizerKickOn();
        Integer maxPages = parentReport.getMaxPages();
        Integer timeout = parentReport.getTimeout();
        if (maxPages != null && maxPages > 0) {
            LOGGER.trace("Setting hardlimit on number of report pages: " + maxPages);
            jasperReport.setProperty(MaxPagesGovernor.PROPERTY_MAX_PAGES_ENABLED, Boolean.TRUE.toString());
            jasperReport.setProperty(MaxPagesGovernor.PROPERTY_MAX_PAGES, String.valueOf(maxPages));
        }
        if (timeout != null && timeout > 0) {
            LOGGER.trace("Setting timeout on report execution [ms]: " + timeout);
            jasperReport.setProperty(TimeoutGovernor.PROPERTY_TIMEOUT_ENABLED, Boolean.TRUE.toString());
            jasperReport.setProperty(TimeoutGovernor.PROPERTY_TIMEOUT, String.valueOf(timeout));
        }
        if (virtualizerS != null && virtualizerKickOn != null && virtualizerKickOn > 0) {
            String virtualizerClassName = JASPER_VIRTUALIZER_PKG + "." + virtualizerS;
            try {
                Class<?> clazz = Class.forName(virtualizerClassName);
                if (clazz.equals(JRSwapFileVirtualizer.class)) {
                    swapFile = new JRSwapFile(TEMP_DIR, 4096, 200);
                    virtualizer = new JRSwapFileVirtualizer(virtualizerKickOn, swapFile);
                } else if (clazz.equals(JRGzipVirtualizer.class)) {
                    virtualizer = new JRGzipVirtualizer(virtualizerKickOn);
                } else if (clazz.equals(JRFileVirtualizer.class)) {
                    virtualizer = new JRFileVirtualizer(virtualizerKickOn, TEMP_DIR);
                } else {
                    throw new ClassNotFoundException("No support for virtualizer class: " + clazz.getName());
                }
                LOGGER.trace("Setting explicit Jasper virtualizer: " + virtualizer);
                virtualizer.setReadOnly(false);
                parameters.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);
            } catch (ClassNotFoundException e) {
                LOGGER.error("Cannot find Jasper virtualizer: " + e.getMessage());
            }
        }
        LOGGER.trace("All Report parameters : {}", parameters);
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters);
        LOGGER.trace("fill report : {}", jasperPrint);
        String reportFilePath = generateReport(parentReport, jasperPrint);
        LOGGER.trace("generate report : {}", reportFilePath);
        saveReportOutputType(reportFilePath, parentReport, task, result);
        LOGGER.trace("create report output type : {}", reportFilePath);
        result.computeStatus();
    } catch (Exception ex) {
        LOGGER.error("CreateReport: {}", ex.getMessage(), ex);
        result.recordFatalError(ex.getMessage(), ex);
        runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR);
        runResult.setProgress(progress);
        return runResult;
    } finally {
        if (swapFile != null) {
            swapFile.dispose();
        }
        if (virtualizer != null) {
            virtualizer.cleanup();
        }
    }
    // This "run" is finished. But the task goes on ...
    runResult.setRunResultStatus(TaskRunResultStatus.FINISHED);
    runResult.setProgress(progress);
    LOGGER.trace("CreateReportTaskHandler.run stopping");
    return runResult;
}
Also used : OperationResult(com.evolveum.midpoint.schema.result.OperationResult) JasperReport(net.sf.jasperreports.engine.JasperReport) Item(com.evolveum.midpoint.prism.Item) TaskRunResult(com.evolveum.midpoint.task.api.TaskRunResult) PrismContainer(com.evolveum.midpoint.prism.PrismContainer) JRFileVirtualizer(net.sf.jasperreports.engine.fill.JRFileVirtualizer) ReportType(com.evolveum.midpoint.xml.ns._public.common.common_3.ReportType) ReportParameterType(com.evolveum.midpoint.xml.ns._public.common.common_3.ReportParameterType) JRSwapFileVirtualizer(net.sf.jasperreports.engine.fill.JRSwapFileVirtualizer) JasperPrint(net.sf.jasperreports.engine.JasperPrint) JRSwapFile(net.sf.jasperreports.engine.util.JRSwapFile) JRAbstractLRUVirtualizer(net.sf.jasperreports.engine.fill.JRAbstractLRUVirtualizer) JRGzipVirtualizer(net.sf.jasperreports.engine.fill.JRGzipVirtualizer) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) SystemException(com.evolveum.midpoint.util.exception.SystemException) JRException(net.sf.jasperreports.engine.JRException) PrismProperty(com.evolveum.midpoint.prism.PrismProperty) PrismObject(com.evolveum.midpoint.prism.PrismObject)

Example 7 with JasperPrint

use of net.sf.jasperreports.engine.JasperPrint in project bamboobsc by billchen198318.

the class JReportUtils method fillReportToResponse.

public static void fillReportToResponse(String reportId, Map<String, Object> paramMap, HttpServletResponse response) throws ServiceException, Exception {
    if (StringUtils.isBlank(reportId)) {
        throw new java.lang.IllegalArgumentException("error, reportId is blank");
    }
    TbSysJreport sysJreport = new TbSysJreport();
    sysJreport.setReportId(reportId);
    DefaultResult<TbSysJreport> result = sysJreportService.findEntityByUK(sysJreport);
    if (result.getValue() == null) {
        throw new ServiceException(result.getSystemMessage().getValue());
    }
    sysJreport = result.getValue();
    String jasperFileFullPath = Constants.getDeployJasperReportDir() + "/" + sysJreport.getReportId() + "/" + sysJreport.getReportId() + ".jasper";
    File jasperFile = new File(jasperFileFullPath);
    if (!jasperFile.exists()) {
        jasperFile = null;
        throw new Exception("error, Files are missing : " + jasperFileFullPath);
    }
    InputStream reportSource = new FileInputStream(jasperFile);
    Connection conn = null;
    try {
        conn = DataUtils.getConnection();
        ServletOutputStream ouputStream = response.getOutputStream();
        JasperPrint jasperPrint = JasperFillManager.fillReport(reportSource, paramMap, conn);
        response.setContentType("application/pdf");
        response.setHeader("Content-disposition", "inline; filename=" + sysJreport.getReportId() + ".pdf");
        JRPdfExporter jrPdfExporter = new JRPdfExporter();
        jrPdfExporter.setExporterInput(new SimpleExporterInput(jasperPrint));
        jrPdfExporter.setExporterOutput(new SimpleOutputStreamExporterOutput(ouputStream));
        SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
        jrPdfExporter.setConfiguration(configuration);
        configuration.setOwnerPassword(Constants.getEncryptorKey1());
        jrPdfExporter.exportReport();
        ouputStream.flush();
        ouputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        DataUtils.doReleaseConnection(conn);
        if (null != reportSource) {
            try {
                reportSource.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        reportSource = null;
        jasperFile = null;
    }
}
Also used : TbSysJreport(com.netsteadfast.greenstep.po.hbm.TbSysJreport) ServletOutputStream(javax.servlet.ServletOutputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) SimpleOutputStreamExporterOutput(net.sf.jasperreports.export.SimpleOutputStreamExporterOutput) JasperPrint(net.sf.jasperreports.engine.JasperPrint) Connection(java.sql.Connection) SimpleExporterInput(net.sf.jasperreports.export.SimpleExporterInput) JRPdfExporter(net.sf.jasperreports.engine.export.JRPdfExporter) IOException(java.io.IOException) JRException(net.sf.jasperreports.engine.JRException) IOException(java.io.IOException) ServiceException(com.netsteadfast.greenstep.base.exception.ServiceException) FileInputStream(java.io.FileInputStream) ServiceException(com.netsteadfast.greenstep.base.exception.ServiceException) SimplePdfExporterConfiguration(net.sf.jasperreports.export.SimplePdfExporterConfiguration) ZipFile(net.lingala.zip4j.core.ZipFile) File(java.io.File)

Example 8 with JasperPrint

use of net.sf.jasperreports.engine.JasperPrint in project jgnash by ccavanaugh.

the class DynamicJasperReportPanel method saveAction.

private void saveAction() {
    Preferences p = Preferences.userNodeForPackage(DynamicJasperReportPanel.class);
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setMultiSelectionEnabled(false);
    saveContributors.forEach(fileChooser::addChoosableFileFilter);
    // restore the last save format
    if (p.get(LAST_CONTRIBUTOR, null) != null) {
        String last = p.get(LAST_CONTRIBUTOR, null);
        for (JRSaveContributor saveContributor : saveContributors) {
            if (saveContributor.getDescription().equals(last)) {
                fileChooser.setFileFilter(saveContributor);
                break;
            }
        }
    } else if (!saveContributors.isEmpty()) {
        fileChooser.setFileFilter(saveContributors.get(0));
    }
    if (p.get(LAST_DIRECTORY, null) != null) {
        fileChooser.setCurrentDirectory(new File(p.get(LAST_DIRECTORY, null)));
    }
    int retValue = fileChooser.showSaveDialog(this);
    if (retValue == JFileChooser.APPROVE_OPTION) {
        FileFilter fileFilter = fileChooser.getFileFilter();
        File file = fileChooser.getSelectedFile();
        p.put(LAST_DIRECTORY, file.getParent());
        JRSaveContributor contributor = null;
        if (fileFilter instanceof JRSaveContributor) {
            // save format chosen from the list
            contributor = (JRSaveContributor) fileFilter;
        } else {
            for (JRSaveContributor saveContributor : saveContributors) {
                // need to determine the best match
                if (saveContributor.accept(file)) {
                    contributor = saveContributor;
                    break;
                }
            }
            if (contributor == null) {
                JOptionPane.showMessageDialog(this, resourceBundle.getString("error.saving"));
            }
        }
        if (contributor != null) {
            p.put(LAST_CONTRIBUTOR, contributor.getDescription());
            try {
                if (contributor instanceof JRSingleSheetXlsSaveContributor) {
                    LOG.info("Formatting for xls file");
                    JasperPrint print = report.createJasperPrint(true);
                    contributor.save(print, file);
                } else if (contributor instanceof JRCsvSaveContributor) {
                    LOG.info("Formatting for csv file");
                    JasperPrint print = report.createJasperPrint(true);
                    contributor.save(print, file);
                } else {
                    contributor.save(jasperPrint, file);
                }
            } catch (final JRException ex) {
                LOG.log(Level.SEVERE, ex.getMessage(), ex);
                JOptionPane.showMessageDialog(this, resourceBundle.getString("error.saving"));
            }
        }
    }
}
Also used : JRSingleSheetXlsSaveContributor(net.sf.jasperreports.view.save.JRSingleSheetXlsSaveContributor) JFileChooser(javax.swing.JFileChooser) JRException(net.sf.jasperreports.engine.JRException) JasperPrint(net.sf.jasperreports.engine.JasperPrint) JRSaveContributor(net.sf.jasperreports.view.JRSaveContributor) Preferences(java.util.prefs.Preferences) FileFilter(javax.swing.filechooser.FileFilter) File(java.io.File) JasperPrint(net.sf.jasperreports.engine.JasperPrint) JRCsvSaveContributor(net.sf.jasperreports.view.save.JRCsvSaveContributor)

Example 9 with JasperPrint

use of net.sf.jasperreports.engine.JasperPrint in project dhis2-core by dhis2.

the class DefaultReportService method renderReport.

// -------------------------------------------------------------------------
// ReportService implementation
// -------------------------------------------------------------------------
@Override
public JasperPrint renderReport(OutputStream out, String reportUid, Period period, String organisationUnitUid, String type) {
    I18nFormat format = i18nManager.getI18nFormat();
    Report report = getReport(reportUid);
    Map<String, Object> params = new HashMap<>();
    params.putAll(constantService.getConstantParameterMap());
    Date reportDate = new Date();
    if (period != null) {
        params.put(PARAM_PERIOD_NAME, format.formatPeriod(period));
        reportDate = period.getStartDate();
    }
    OrganisationUnit orgUnit = organisationUnitService.getOrganisationUnit(organisationUnitUid);
    if (orgUnit != null) {
        int level = orgUnit.getLevel();
        params.put(PARAM_ORGANISATIONUNIT_COLUMN_NAME, orgUnit.getName());
        params.put(PARAM_ORGANISATIONUNIT_LEVEL, level);
        params.put(PARAM_ORGANISATIONUNIT_LEVEL_COLUMN, ORGUNIT_LEVEL_COLUMN_PREFIX + level);
        params.put(PARAM_ORGANISATIONUNIT_UID_LEVEL_COLUMN, ORGUNIT_UID_LEVEL_COLUMN_PREFIX + level);
    }
    JasperPrint print = null;
    try {
        JasperReport jasperReport = JasperCompileManager.compileReport(IOUtils.toInputStream(report.getDesignContent(), StandardCharsets.UTF_8));
        if (// Use JR data source
        report.hasReportTable()) {
            ReportTable reportTable = report.getReportTable();
            Grid grid = reportTableService.getReportTableGrid(reportTable.getUid(), reportDate, organisationUnitUid);
            print = JasperFillManager.fillReport(jasperReport, params, grid);
        } else // Use JDBC data source
        {
            if (report.hasRelativePeriods()) {
                List<Period> relativePeriods = report.getRelatives().getRelativePeriods(reportDate, null, false);
                String periodString = getCommaDelimitedString(getIdentifiers(periodService.reloadPeriods(relativePeriods)));
                String isoPeriodString = getCommaDelimitedString(IdentifiableObjectUtils.getUids(relativePeriods));
                params.put(PARAM_RELATIVE_PERIODS, periodString);
                params.put(PARAM_RELATIVE_ISO_PERIODS, isoPeriodString);
            }
            if (report.hasReportParams() && report.getReportParams().isParamOrganisationUnit() && orgUnit != null) {
                params.put(PARAM_ORG_UNITS, String.valueOf(orgUnit.getId()));
                params.put(PARAM_ORG_UNITS_UID, String.valueOf(orgUnit.getUid()));
            }
            Connection connection = DataSourceUtils.getConnection(dataSource);
            try {
                print = JasperFillManager.fillReport(jasperReport, params, connection);
            } finally {
                DataSourceUtils.releaseConnection(connection, dataSource);
            }
        }
        if (print != null) {
            JRExportUtils.export(type, out, print);
        }
    } catch (Exception ex) {
        throw new RuntimeException("Failed to render report", ex);
    }
    return print;
}
Also used : OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) JasperReport(net.sf.jasperreports.engine.JasperReport) Report(org.hisp.dhis.report.Report) HashMap(java.util.HashMap) JasperPrint(net.sf.jasperreports.engine.JasperPrint) Grid(org.hisp.dhis.common.Grid) Connection(java.sql.Connection) ReportTable(org.hisp.dhis.reporttable.ReportTable) Period(org.hisp.dhis.period.Period) I18nFormat(org.hisp.dhis.i18n.I18nFormat) TextUtils.getCommaDelimitedString(org.hisp.dhis.commons.util.TextUtils.getCommaDelimitedString) JasperReport(net.sf.jasperreports.engine.JasperReport) Date(java.util.Date) JasperPrint(net.sf.jasperreports.engine.JasperPrint)

Example 10 with JasperPrint

use of net.sf.jasperreports.engine.JasperPrint in project opennms by OpenNMS.

the class AbstractMeasurementQueryExecutorTest method createReport.

protected void createReport(String reportName, ReportFiller filler) throws JRException, IOException {
    JasperReport jasperReport = JasperCompileManager.compileReport(getClass().getResourceAsStream("/reports/" + reportName + ".jrxml"));
    JasperPrint jasperPrint = fill(jasperReport, filler);
    createPdf(jasperPrint, reportName);
    createXhtml(jasperPrint, reportName);
    createCsv(jasperPrint, reportName);
    // this is ugly, but we verify that the reports exists and have a file size > 0
    verifyReport(reportName, "pdf");
    verifyReport(reportName, "html");
    verifyReport(reportName, "csv");
}
Also used : JasperPrint(net.sf.jasperreports.engine.JasperPrint) JasperReport(net.sf.jasperreports.engine.JasperReport)

Aggregations

JasperPrint (net.sf.jasperreports.engine.JasperPrint)17 JasperReport (net.sf.jasperreports.engine.JasperReport)9 JRException (net.sf.jasperreports.engine.JRException)8 File (java.io.File)5 Connection (java.sql.Connection)5 HashMap (java.util.HashMap)5 IOException (java.io.IOException)4 SQLException (java.sql.SQLException)4 PrismObject (com.evolveum.midpoint.prism.PrismObject)2 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)2 FileInputStream (java.io.FileInputStream)2 ClassicLayoutManager (ar.com.fdvs.dj.core.layout.ClassicLayoutManager)1 AutoText (ar.com.fdvs.dj.domain.AutoText)1 DJGroupLabel (ar.com.fdvs.dj.domain.DJGroupLabel)1 DynamicReport (ar.com.fdvs.dj.domain.DynamicReport)1 Style (ar.com.fdvs.dj.domain.Style)1 ColumnBuilder (ar.com.fdvs.dj.domain.builders.ColumnBuilder)1 DynamicReportBuilder (ar.com.fdvs.dj.domain.builders.DynamicReportBuilder)1 GroupBuilder (ar.com.fdvs.dj.domain.builders.GroupBuilder)1 DJGroup (ar.com.fdvs.dj.domain.entities.DJGroup)1