use of net.sf.jasperreports.engine.JasperPrint in project opennms by OpenNMS.
the class DefaultReportService method runReport.
/** {@inheritDoc}
* @throws ReportRunException */
@Override
public synchronized String runReport(Report report, String reportDirectory) throws ReportRunException {
String outputFile = null;
try {
outputFile = generateReportName(reportDirectory, report.getReportName(), report.getReportFormat());
JasperPrint print = runAndRender(report);
outputFile = saveReport(print, report, outputFile);
} catch (JRException e) {
LOG.error("Error running report: {}", e.getMessage(), e);
throw new ReportRunException("Caught JRException: " + e.getMessage());
} catch (Throwable e) {
LOG.error("Unexpected exception: {}", e.getMessage(), e);
throw new ReportRunException("Caught unexpected " + e.getClass().getName() + ": " + e.getMessage());
}
return outputFile;
}
use of net.sf.jasperreports.engine.JasperPrint in project midpoint by Evolveum.
the class TestReport method f.
@Test
public void f() throws Exception {
OperationResult initResult = new OperationResult("generate report");
JasperDesign jd = JRXmlLoader.load(new File("src/test/resources/reports/report-users-ds.jrxml"));
JasperReport jr = JasperCompileManager.compileReport(jd);
Task task = taskManager.createTaskInstance();
Map<String, Object> params = new HashMap<String, Object>();
// params.put(MidPointQueryExecutorFactory.PARAMETER_MIDPOINT_CONNECTION, modelService);
// params.put(MidPointQueryExecutorFactory.PARAMETER_PRISM_CONTEXT, prismContext);
// params.put(MidPointQueryExecutorFactory.PARAMETER_TASK_MANAGER, taskManager);
// params.put(MidPointQueryExecutorFactory.PARAMETER_EXPRESSION_FACTORY, expressionFactory);
params.put("userName", new PolyString("administrator"));
reportTaskHandler.run(task);
// byte[] reportTemplatebase64 = "".getBytes();
// byte[] reportTemplate = Base64.decodeBase64("UEdwaGMzQmxjbEpsY0c5eWRDQU5DaUFnSUNBSkNYaHRiRzV6UFNKb2RIUndPaTh2YW1GemNHVnljbVZ3YjNKMGN5NXpiM1Z5WTJWbWIzSm5aUzV1WlhRdmFtRnpjR1Z5Y21Wd2IzSjBjeUlnRFFvSkNRbDRiV3h1Y3pwNGMyazlJbWgwZEhBNkx5OTNkM2N1ZHpNdWIzSm5Mekl3TURF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1FrOEwyUmxkR0ZwYkQ0TkNna0pQQzlxWVhOd1pYSlNaWEJ2Y25RKw==".getBytes());
//
// byte[] decoded = Base64.decodeBase64(reportTemplate);
// String s = new String(decoded);
// System.out.println(s);
File f = new File("src/test/resources/reports/reportAccounts.txt");
// DataOutputStream fos = new DataOutputStream(new FileOutputStream(f));
// fos.writeUTF(s);
// fos.close();
JasperPrint jasperPrint = JasperFillManager.fillReport(jr, params);
f = new File("src/test/resources/reports/report5.pdf");
JasperExportManager.exportReportToPdfFile(jasperPrint, f.getAbsolutePath());
// System.out.println("output: " + output);
// jr.
// jr.getQuery().getLanguage();
// jr.getQuery().getText();
}
use of net.sf.jasperreports.engine.JasperPrint in project adempiere by adempiere.
the class ReportStarter method startProcess.
/**
* Start the process.
* Called then pressing the Process button in R_Request.
* It should only return false, if the function could not be performed
* as this causes the process to abort.
* @author rlemeill
* @param ctx context
* @param pi standard process info
* @param trx
* @return true if success
*/
public boolean startProcess(Properties ctx, ProcessInfo pi, Trx trx) {
processInfo = pi;
String Name = pi.getTitle();
int AD_PInstance_ID = pi.getAD_PInstance_ID();
int Record_ID = pi.getRecord_ID();
log.info("Name=" + Name + " AD_PInstance_ID=" + AD_PInstance_ID + " Record_ID=" + Record_ID);
String trxName = null;
if (trx != null) {
trxName = trx.getTrxName();
}
ReportData reportData = getReportData(pi, trxName);
if (reportData == null) {
reportResult(AD_PInstance_ID, "Can not find report data", trxName);
return false;
}
String reportPath = reportData.getReportFilePath();
if (Util.isEmpty(reportPath, true)) {
reportResult(AD_PInstance_ID, "Can not find report", trxName);
return false;
}
JasperData data = null;
File reportFile = null;
String fileExtension = "";
HashMap<String, Object> params = new HashMap<String, Object>();
addProcessParameters(AD_PInstance_ID, params, trxName);
addProcessInfoParameters(params, pi.getParameter());
reportFile = getReportFile(reportPath, (String) params.get("ReportType"));
if (reportFile == null || reportFile.exists() == false) {
log.severe("No report file found for given type, falling back to " + reportPath);
reportFile = getReportFile(reportPath);
}
if (reportFile == null || reportFile.exists() == false) {
String tmp = "Can not find report file at path - " + reportPath;
log.severe(tmp);
reportResult(AD_PInstance_ID, tmp, trxName);
}
if (reportFile != null) {
data = processReport(reportFile);
if (data.getJasperReport() == null) {
log.severe("Could not load Jasper Report " + reportPath);
return false;
}
fileExtension = reportFile.getName().substring(reportFile.getName().lastIndexOf("."), reportFile.getName().length());
} else {
return false;
}
JasperReport jasperReport = data.getJasperReport();
String jasperName = data.getJasperName();
String name = jasperReport.getName();
File reportDir = data.getReportDir();
// Add reportDir to class path
ClassLoader scl = ClassLoader.getSystemClassLoader();
try {
java.net.URLClassLoader ucl = new java.net.URLClassLoader(new java.net.URL[] { reportDir.toURI().toURL() }, scl);
net.sf.jasperreports.engine.util.JRResourcesUtil.setThreadClassLoader(ucl);
} catch (MalformedURLException me) {
log.warning("Could not add report directory to classpath: " + me.getMessage());
}
if (jasperReport != null) {
File[] subreports;
// Subreports
if (reportPath.startsWith("http://") || reportPath.startsWith("https://")) {
// Locate and download subreports from remote webcontext
subreports = getHttpSubreports(jasperName + "Subreport", reportPath, fileExtension);
} else if (reportPath.startsWith("attachment:")) {
subreports = getAttachmentSubreports(reportPath);
} else if (reportPath.startsWith("resource:")) {
subreports = getResourceSubreports(name + "Subreport", reportPath, fileExtension);
} else // TODO: Implement file:/ lookup for subreports
{
// Locate subreports from local/remote filesystem
subreports = reportDir.listFiles(new FileFilter(jasperName + "Subreport", reportDir, fileExtension));
}
for (int i = 0; i < subreports.length; i++) {
// @Trifon - begin
if (subreports[i].getName().toLowerCase().endsWith(".jasper") || subreports[i].getName().toLowerCase().endsWith(".jrxml")) {
JasperData subData = processReport(subreports[i]);
if (subData.getJasperReport() != null) {
params.put(subData.getJasperName(), subData.getJasperFile().getAbsolutePath());
}
}
// @Trifon - end
}
if (Record_ID > 0)
params.put("RECORD_ID", new Integer(Record_ID));
// contribution from Ricardo (ralexsander)
// in iReports you can 'SELECT' AD_Client_ID, AD_Org_ID and AD_User_ID using only AD_PINSTANCE_ID
params.put("AD_PINSTANCE_ID", new Integer(AD_PInstance_ID));
// FR [3123850] - Add continiuosly needed parameters to Jasper Starter - Carlos Ruiz - GlobalQSS
params.put("AD_CLIENT_ID", new Integer(Env.getAD_Client_ID(Env.getCtx())));
params.put("AD_ROLE_ID", new Integer(Env.getAD_Role_ID(Env.getCtx())));
params.put("AD_USER_ID", new Integer(Env.getAD_User_ID(Env.getCtx())));
Language currLang = Env.getLanguage(Env.getCtx());
String printerName = null;
MPrintFormat printFormat = null;
PrintInfo printInfo = null;
ProcessInfoParameter[] pip = pi.getParameter();
// Get print format and print info parameters
if (pip != null) {
for (int i = 0; i < pip.length; i++) {
if (ServerReportCtl.PARAM_PRINT_FORMAT.equalsIgnoreCase(pip[i].getParameterName())) {
printFormat = (MPrintFormat) pip[i].getParameter();
}
if (ServerReportCtl.PARAM_PRINT_INFO.equalsIgnoreCase(pip[i].getParameterName())) {
printInfo = (PrintInfo) pip[i].getParameter();
}
if (ServerReportCtl.PARAM_PRINTER_NAME.equalsIgnoreCase(pip[i].getParameterName())) {
printerName = (String) pip[i].getParameter();
}
}
}
if (printFormat != null) {
if (printInfo != null) {
// Set the language of the print format if we're printing a document
if (printInfo.isDocument()) {
currLang = printFormat.getLanguage();
}
}
// Set printer name unless already set.
if (printerName == null) {
printerName = printFormat.getPrinterName();
}
}
params.put("CURRENT_LANG", currLang.getAD_Language());
params.put(JRParameter.REPORT_LOCALE, currLang.getLocale());
// Resources
File resFile = null;
if (reportPath.startsWith("attachment:") && attachment != null) {
resFile = getAttachmentResourceFile(jasperName, currLang);
} else if (reportPath.startsWith("resource:")) {
resFile = getResourcesForResourceFile(jasperName, currLang);
// TODO: Implement file:/ for resources
} else {
resFile = new File(jasperName + "_" + currLang.getLocale().getLanguage() + ".properties");
if (!resFile.exists()) {
resFile = null;
}
if (resFile == null) {
resFile = new File(jasperName + ".properties");
if (!resFile.exists()) {
resFile = null;
}
}
}
if (resFile != null) {
try {
PropertyResourceBundle res = new PropertyResourceBundle(new FileInputStream(resFile));
params.put("RESOURCE", res);
} catch (IOException e) {
;
}
}
Connection conn = null;
try {
conn = trx != null ? trx.getConnection() : getConnection();
jasperPrint = JasperFillManager.fillReport(jasperReport, params, conn);
if (reportData.isDirectPrint() && !processInfo.isPrintPreview()) {
log.info("ReportStarter.startProcess print report -" + jasperPrint.getName());
//RF 1906632
if (!processInfo.isBatch()) {
// Get printer job
PrinterJob printerJob = org.compiere.print.CPrinter.getPrinterJob(printerName);
// Set print request attributes
// Paper Attributes:
PrintRequestAttributeSet prats = new HashPrintRequestAttributeSet();
// add: copies, job-name, priority
if (// @Trifon
printInfo == null || printInfo.isDocumentCopy() || printInfo.getCopies() < 1)
prats.add(new Copies(1));
else
prats.add(new Copies(printInfo.getCopies()));
Locale locale = Language.getLoginLanguage().getLocale();
// @Trifon
String printFormat_name = printFormat == null ? "" : printFormat.getName();
int numCopies = printInfo == null ? 0 : printInfo.getCopies();
prats.add(new JobName(printFormat_name + "_" + pi.getRecord_ID(), locale));
prats.add(PrintUtil.getJobPriority(jasperPrint.getPages().size(), numCopies, true));
// Create print service exporter
JRPrintServiceExporter exporter = new JRPrintServiceExporter();
;
// Set parameters
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE, printerJob.getPrintService());
exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE_ATTRIBUTE_SET, printerJob.getPrintService().getAttributes());
exporter.setParameter(JRPrintServiceExporterParameter.PRINT_REQUEST_ATTRIBUTE_SET, prats);
exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG, Boolean.FALSE);
exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG, Boolean.FALSE);
// Print report / document
exporter.exportReport();
} else {
// Used For the PH
try {
File PDF = File.createTempFile("mail", ".pdf");
JasperExportManager.exportReportToPdfFile(jasperPrint, PDF.getAbsolutePath());
processInfo.setPDFReport(PDF);
} catch (IOException e) {
log.severe("ReportStarter.startProcess: Can not make PDF File - " + e.getMessage());
}
}
// You can use JasperPrint to create PDF
// JasperExportManager.exportReportToPdfFile(jasperPrint, "BasicReport.pdf");
} else {
log.info("ReportStarter.startProcess run report -" + jasperPrint.getName());
JRViewerProvider viewerLauncher = getReportViewerProvider();
//viewerLauncher.openViewer(jasperPrint, pi.getTitle()+" - " + reportPath);
viewerLauncher.openViewer(jasperPrint, pi.getTitle() + "_" + pi.getRecord_ID() + ".pdf");
}
} catch (JRException e) {
log.severe("ReportStarter.startProcess: Can not run report - " + e.getMessage());
} finally {
if (conn != null && trx == null)
try {
conn.close();
} catch (SQLException e) {
throw new AdempiereException("@Error@ " + e);
}
}
}
reportResult(AD_PInstance_ID, null, trxName);
return true;
}
use of net.sf.jasperreports.engine.JasperPrint in project jgnash by ccavanaugh.
the class BaseDynamicJasperReport method createJasperPrint.
@SuppressWarnings("ConstantConditions")
protected final JasperPrint createJasperPrint(final AbstractReportTableModel model, final boolean formatForCSV) {
logger.info(rb.getString("Message.ProcessingReportData"));
DynamicReportBuilder drb = new DynamicReportBuilder();
try {
if (formatForCSV) {
drb.setIgnorePagination(true);
}
final List<AbstractColumn> columns = new ArrayList<>();
final int[] columnsToHide = model.getColumnsToHide();
assignPageFormat(drb);
drb.setHeaderHeight(getStyle(model.getColumnHeaderStyle(0), formatForCSV).getFont().getFontSize() * 2);
drb.setDetailHeight(getBaseFontSize() * 2);
logger.info("Creating column model for report");
// create columns and add to the list
for (int i = 0; i < model.getColumnCount(); i++) {
if (Arrays.binarySearch(columnsToHide, i) >= 0) {
// don't add any hidden columns
continue;
}
if (model.getColumnStyle(i) != ColumnStyle.GROUP && model.getColumnStyle(i) != ColumnStyle.GROUP_NO_HEADER) {
Style columnTypeStyle = getStyle(model.getColumnStyle(i), formatForCSV);
Style columnHeaderStyle = getStyle(model.getColumnHeaderStyle(i), formatForCSV);
int width = AWTFontUtilities.getStringWidth(model.getColumnPrototypeValueAt(i), getTypeFooterStyle());
int hWidth = AWTFontUtilities.getStringWidth(model.getColumnName(i), columnHeaderStyle);
if (hWidth > width) {
width = hWidth;
}
ColumnBuilder builder = ColumnBuilder.getNew();
builder.setColumnProperty(COLUMN_PROPERTY + i, model.getColumnClass(i).getName());
builder.setTitle(model.getColumnName(i));
builder.setWidth(width);
builder.setStyle(columnTypeStyle);
builder.setHeaderStyle(columnHeaderStyle);
builder.setTruncateSuffix("…");
// set the format pattern for decimal values
if (model.getColumnStyle(i) == ColumnStyle.AMOUNT_SUM || model.getColumnStyle(i) == ColumnStyle.BALANCE || model.getColumnStyle(i) == ColumnStyle.BALANCE_WITH_SUM || model.getColumnStyle(i) == ColumnStyle.BALANCE_WITH_SUM_AND_GLOBAL || model.getColumnStyle(i) == ColumnStyle.CROSSTAB_TOTAL) {
String pattern = CommodityFormat.getFullNumberPattern(model.getCurrency());
builder.setPattern(pattern);
} else if (model.getColumnStyle(i) == ColumnStyle.PERCENTAGE) {
NumberFormat nf = ReportFactory.getPercentageFormat();
String pattern = ((DecimalFormat) nf).toPattern();
builder.setPattern(pattern);
} else if (model.getColumnStyle(i) == ColumnStyle.QUANTITY) {
NumberFormat nf = ReportFactory.getQuantityFormat();
String pattern = ((DecimalFormat) nf).toPattern();
builder.setPattern(pattern);
} else if (model.getColumnStyle(i) == ColumnStyle.SHORT_DATE) {
builder.setTextFormatter(DateUtils.getShortDateFormatter().toFormat());
} else if (model.getColumnStyle(i) == ColumnStyle.TIMESTAMP) {
builder.setTextFormatter(DateUtils.getShortDateTimeFormatter().toFormat());
} else if (model.getColumnStyle(i) == ColumnStyle.SHORT_AMOUNT) {
String pattern = CommodityFormat.getShortNumberPattern(model.getCurrency());
builder.setPattern(pattern);
}
if (model.isColumnFixedWidth(i) && !formatForCSV) {
builder.setFixedWidth(true);
}
columns.add(builder.build());
} else if (model.getColumnStyle(i) == ColumnStyle.GROUP || model.getColumnStyle(i) == ColumnStyle.GROUP_NO_HEADER) {
ColumnBuilder builder = ColumnBuilder.getNew();
builder.setColumnProperty(COLUMN_PROPERTY + i, model.getColumnClass(i).getName());
builder.setTitle(model.getColumnName(i));
builder.setStyle(getTypeHeaderStyle());
columns.add(builder.build());
}
}
boolean group = false;
boolean header = true;
logger.info("Searching for report groups");
// determine if a group needs to be created
for (int i = 0; i < model.getColumnCount(); i++) {
if (model.getColumnStyle(i) == ColumnStyle.GROUP) {
group = true;
break;
} else if (model.getColumnStyle(i) == ColumnStyle.GROUP_NO_HEADER) {
group = true;
header = false;
break;
}
}
if (group) {
// group columns
logger.info("Building report groups");
GroupBuilder gb = new GroupBuilder();
gb.setDefaultHeaderVariableStyle(getTypeHeaderStyle());
gb.setDefaultFooterVariableStyle(getTypeFooterStyle());
for (int i = 0; i < columns.size(); i++) {
if (model.getColumnStyle(i) == ColumnStyle.GROUP || model.getColumnStyle(i) == ColumnStyle.GROUP_NO_HEADER) {
gb.setCriteriaColumn((PropertyColumn) columns.get(i));
} else if (model.getColumnStyle(i) == ColumnStyle.AMOUNT_SUM || model.getColumnStyle(i) == ColumnStyle.BALANCE_WITH_SUM || model.getColumnStyle(i) == ColumnStyle.BALANCE_WITH_SUM_AND_GLOBAL || model.getColumnStyle(i) == ColumnStyle.CROSSTAB_TOTAL) {
gb.addFooterVariable(columns.get(i), DJCalculation.SUM);
}
}
if (header) {
gb.setGroupLayout(GroupLayout.VALUE_IN_HEADER);
} else {
gb.setGroupLayout(GroupLayout.EMPTY);
}
// adds a group footer label if it is not null or zero length
if (getGroupFooterLabel() != null && !getGroupFooterLabel().isEmpty()) {
DJGroupLabel label = new DJGroupLabel(getGroupFooterLabel(), getTypeFooterStyle(), LabelPosition.LEFT);
gb.setFooterLabel(label);
}
DJGroup group1 = gb.build();
boolean global = false;
for (int i = 0; i < columns.size(); i++) {
final AbstractColumn c = columns.get(i);
drb.addColumn(c);
if (model.getColumnStyle(i) == ColumnStyle.BALANCE_WITH_SUM_AND_GLOBAL || model.getColumnStyle(i) == ColumnStyle.CROSSTAB_TOTAL) {
drb.addGlobalFooterVariable(c, DJCalculation.SUM, getTypeFooterStyle());
global = true;
}
}
drb.addGroup(group1);
if (global) {
drb.setGrandTotalLegendStyle(getGlobalFooterStyle());
drb.setGrandTotalLegend(getGrandTotalLegend());
}
} else {
// no groups exist, just add the columns
for (final AbstractColumn column : columns) {
drb.addColumn(column);
}
}
} catch (Exception e) {
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
}
buildTitle(drb);
// use the full page width
drb.setUseFullPageWidth(true);
if (!formatForCSV) {
final Style footerStyle = getPageFooterStyle();
final int halfWidth = (int) (getPageFormat().getWidth() * .5);
final AutoText date = new AutoText(AutoText.AUTOTEXT_CREATED_ON, AutoText.POSITION_FOOTER, HorizontalBandAlignment.LEFT, AutoText.PATTERN_DATE_DATE_TIME, halfWidth);
date.setStyle(footerStyle);
final AutoText pageNum = new AutoText(AutoText.AUTOTEXT_PAGE_X_SLASH_Y, AutoText.POSITION_FOOTER, HorizontalBandAlignment.RIGHT, (byte) 0, 80, 50);
pageNum.setStyle(footerStyle);
drb.addAutoText(date);
drb.addAutoText(pageNum);
}
logger.info(rb.getString("Message.CompilingReport"));
DynamicReport dr = drb.build();
logger.info(rb.getString("Message.ReportCompileComplete"));
JRDataSource ds = new JRTableModelDataSource(model);
JasperPrint jp = null;
try {
logger.info(rb.getString("Message.ReportCreateView"));
jp = DynamicJasperHelper.generateJasperPrint(dr, new ClassicLayoutManager(), ds);
} catch (final JRException e) {
logger.log(Level.WARNING, "Exception", e);
logger.warning(rb.getString("Message.ReduceFont"));
displayError(rb.getString("Message.ReduceFont"));
}
return jp;
}
use of net.sf.jasperreports.engine.JasperPrint in project jgnash by ccavanaugh.
the class JasperViewerDialogController method setPageIndex.
/**
* Updates the status line and {@code pageIndex property} with the correct page index.
*
* @param index active page index
*/
private void setPageIndex(final int index) {
final JasperPrint jasperPrint = this.jasperPrint.get();
if (jasperPrint != null && jasperPrint.getPages() != null && !jasperPrint.getPages().isEmpty()) {
if (index >= 0 && index < pageCount.get()) {
pageIndex.setValue(index);
updateStatus(MessageFormat.format(resources.getString("Pattern.Pages"), index + 1, pageCount.get()));
}
} else {
updateStatus("");
}
}
Aggregations