This is my source cord to print my invoice page. My report is in Java package. I kept it inside a folder called "report".
try {
String date1 = new SimpleDateFormat("yyyy-MM-dd").format(isdate.getDate());
String time1 = istime.getValue().toString().split(" ")[3];
date1 = date1 + " " + time1;
String date2 = new SimpleDateFormat("yyyy-MM-dd").format(redate.getDate());
String time2 = retime.getValue().toString().split(" ")[3];
date2 = date2 + " " + time2;
JRTableModelDataSource dataSource = new JRTableModelDataSource(jTable1.getModel());
String reportsource = " D:/Catering/report/report1.jrxml";
Map<String, Object> params = new HashMap<String, Object>();
params.put("inid", txtInvoiceID.getText());
params.put("cuname", txtCuName.getText());
params.put("cuadd", txtCuid.getText());
params.put("cutp", txtTPNo.getText());
params.put("isdate", date1);
params.put("redate", date2);
params.put("advance", txtAdvance.getText());
params.put("due", txtDue.getText());
params.put("total", txtGtotal.getText());
JasperReport jasperReport = JasperCompileManager.compileReport(reportsource);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, dataSource);
JasperViewer.viewReport(jasperPrint, true);
JOptionPane.showMessageDialog(null, "Done");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "jasper error"+e);
}
It would be better make the report an embedded resource, but where possible you should not rely on absolute paths, as these may change between installs...
Try changing
String reportsource = " D:/Catering/report/report1.jrxml";
^---- Did you notice the white space here?
To
String reportsource = "report/report1.jrxml";
It is, also, generally better to pre-compile the report so you don't need to do it at run time...
You could write a simple program that compiled it for you using something like...
String templateFile = "report/report1.jrxml"
String compiledReport = "report/report1.jasper"
JasperCompileManager.compileReportToFile(templateFile, compiledReport);
The method takes two Strings, basically one is the jrxml file and other is the expected jasper file.
You could use JasperReports' Ant task and make apart of your build process.
Or you could use iReports...
Once compiled, you can simply load the jasper file at run time...
String compiledReport = "report/report1.jasper";
JasperReport report = (JasperReport)JRLoader.loadObjectFromFile(compiledReport );
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, dataSource);
Updated with Quick Compile example
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
public class QuickCompile {
public static void main(String[] args) {
try {
String template = "...";
String compiled = "...";
JasperCompileManager.compileReportToFile(template, compiled);
// Just as a test...
JasperReport jr = (JasperReport) JRLoader.loadObjectFromFile(compiled);
} catch (JRException exp) {
exp.printStackTrace();
}
}
}
Related
My scenario is I'm getting same error page on few button/link click on my website.I have a sample of code for taking screenshot according to the date timestamp, but I also want to fetch its occurence on which button or link click event it occured and want to append that event name to the screenshot file.
Please help out.
Thanks in advance
As of now this is what I have.
try{
My code where the error occures on button click
}
catch(Exception ex)
{
File scrn=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// extracting date for folder name.
SimpleDateFormat sdfDate1 = new SimpleDateFormat("yyyy-MM-dd");//dd/MM/yyyy
Date now1 = new Date();
String strDate1 = sdfDate1.format(now1);
// extracting date and time for snapshot file
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");//dd/MM/yyyy
Date now = new Date();
String strDate = sdfDate.format(now);
String filefolder="D:/Home/Snapshot/"+strDate1+"/"; // create a folder as snapshot in your project directory
// Creating folders and files
File f = new File(filefolder+strDate+".jpeg");
FileUtils.copyFile(scrn, new File(f.getPath()));
}
Put the entire code for the screenshot in a method, like take_screenshot and put it in a common place like and pass it one argument with the name of the even where it occurred.
try {
// some action which causes an error
}
catch(Exception ex)
{
MyLib.TakeScreenshot("click button") // argument name, 'action' for example
// do other things for error handling
}
And MyLib.TakeScreenshot has the code you've put above. For the line
// Creating folders and files
File f = new File(filefolder+strDate+".jpeg");
Change that to:
File f = new File(filefolder + strDate + action + ".jpeg"); //action name added to filename
/**
* Define path for Screenshot file.
*/
public String getScreenshotSavePath() {
String className = this.getClass().getName();
File dir = new File(System.getProperty("user.dir")+File.separator+"screenshots"+File.separator + className + File.separator);
dir.mkdirs();
return dir.getAbsolutePath();
}
/**
* Take Screenshot on failure.
*/
public void getScreenshot() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String date = sdf.format(new Date());
String url = driver.getCurrentUrl().replaceAll("[\\/:*\\?\"<>\\|]", "_");
String ext = ".png";
String path = getScreenshotSavePath().toString()+ File.separator + date + "_" + url + ext;
try {
if (driver instanceof TakesScreenshot) {
File tmpFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
org.openqa.selenium.io.FileHandler.copy(tmpFile, new File(path));
auto_logs.error("Captured Screenshot for Failure: "+path);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
One way to do this is to create a proxy class that implements the WebDriver interface (or only the methods you need) and has the real WebDriver object as a constructor argument. This way you can use the methods of the proxy object, which will take a screenshot with information about the event that threw the exception.
public class WebDriverProxy {
private WebDriver driver;
public WebDriverProxy(WebDriver driver) {
this.driver = driver;
}
public void clickLink (String linkText) {
try{
driver.click(By.linkText(linkText);
} catch (Exception e) {
this.takeScreenshot(linkText);
throw e;
}
}
private void takeScreenshot(String event) {
/** take the screenshot and save it with String event in the filename **/
}
}
How do you get a compiled jasper report to load from within the jar file, instead of via a specific path on your hard drive?
My report was working fine on my machine as I had set the path to the reports with:
jasperReport1 = (JasperReport) JRLoader.loadObjectFromFile("/Users/admin/Documents/HCCE/Semester 2/OOP/Projects2/TestApp/src/ie/test/OMACYTDReportFinalpg1.jasper");
jasperReport2 =(JasperReport) JRLoader.loadObjectFromFile("/Users/admin/Documents/HCCE/Semester 2/OOP/Projects2/TestApp/src/ie/test/OMACYTDReportFinalpg2.jasper");
But the reports were not loading when working from the finished jar on a different computer. So I am trying to use Input stream and passing it to JasperFillManager but nothing is working - the InputStream is not finding the files. Have I the path wrong?
InputStream jasper1 = getClass().getResourceAsStream("src/ie/test/OMACYTDReportFinalpg1.jasper");
InputStream jasper2 = getClass().getResourceAsStream("src/ie/test/OMACYTDReportFinalpg2.jasper");
My original working code:
private void yTDReportBtnActionPerformed(java.awt.event.ActionEvent evt) {
try
{
JasperReport jasperReport1 = null;
JasperReport jasperReport2 = null;
JasperPrint jasperPrint = null;
JasperDesign jasperDesign = null;
Map parameters = new HashMap();
SimpleDateFormat formatter = new SimpleDateFormat("dd-mmm-yyyy");
String today = formatter.format(new java.util.Date());
//load just the compiled jasper files, to save time
//First merge the two jasper reports into one to get page1 and page 2 in same document
jasperReport1 = (JasperReport) JRLoader.loadObjectFromFile("/Users/admin/Documents/HCCE/Semester 2/OOP/Projects2/TestApp/src/ie/test/OMACYTDReportFinalpg1.jasper");
jasperReport2 =(JasperReport) JRLoader.loadObjectFromFile("/Users/admin/Documents/HCCE/Semester 2/OOP/Projects2/TestApp/src/ie/test/OMACYTDReportFinalpg2.jasper");
JasperPrint jp1 = JasperFillManager.fillReport(jasperReport1, parameters,new JRBeanCollectionDataSource(ie.test.BeanFactory.getCalcs()));
JasperPrint jp2 = JasperFillManager.fillReport(jasperReport2, parameters, new JRBeanCollectionDataSource(ie.test.BeanFactory.getCalcs()));
List pages = jp2 .getPages();
for (int j = 0; j < pages.size(); j++) {
JRPrintPage object = (JRPrintPage)pages.get(j);
jp1.addPage(object);
jp1.setName(unitNameLbl.getText() + " - Financial Year To Date - " + today );
}
JasperViewer.viewReport(jp1, false);
}
catch(Exception ex)
{
System.out.println("EXCEPTION: "+ex.getMessage() + ex);
}
}
And now the changed code that is not working:
private void yTDReportBtnActionPerformed(java.awt.event.ActionEvent evt) {
try
{
JasperReport jasperReport1 = null;
JasperReport jasperReport2 = null;
JasperPrint jasperPrint = null;
JasperDesign jasperDesign = null;
Map parameters = new HashMap();
SimpleDateFormat formatter = new SimpleDateFormat("dd-mmm-yyyy");
String today = formatter.format(new java.util.Date());
//load just the compiled jasper files, to save time
//First merge the two jasper reports into one to get page1 and page 2 in same document
InputStream jasper1 = getClass().getResourceAsStream("src/ie/test/OMACYTDReportFinalpg1.jasper");
InputStream jasper2 = getClass().getResourceAsStream("src/ie/test/OMACYTDReportFinalpg2.jasper");
JasperPrint jp1 = JasperFillManager.fillReport(jasper1, parameters,new JRBeanCollectionDataSource(ie.test.BeanFactory.getCalcs()));
JasperPrint jp2 = JasperFillManager.fillReport(jasper2, parameters, new JRBeanCollectionDataSource(ie.test.BeanFactory.getCalcs()));
List pages = jp2 .getPages();
for (int j = 0; j < pages.size(); j++) {
JRPrintPage object = (JRPrintPage)pages.get(j);
jp1.addPage(object);
jp1.setName(unitNameLbl.getText() + " - Financial Year To Date - " + today );
}
JasperViewer.viewReport(jp1, false);
}
catch(Exception ex)
{
System.out.println("EXCEPTION: "+ex.getMessage() + ex);
}
}
Any help greatly appreciated!
Ok update: I got the InputStreams to work by creating a new package called "reports" and using
InputStream jasper1 = getClass().getResourceAsStream("/reports/OMACYTDReportFinalpg1.jasper");
InputStream jasper2 = getClass().getResourceAsStream("/reports/OMACYTDReportFinalpg2.jasper");
And this works fine in Netbeans BUT it still won't load the files when I compile to jar!!?
Any ideas what I'm doing wrong?
you should put jasper reports in
yourapp/src/main/resources/reports
then you invoke that reports from class java
JasperReport jp = JasperCompileManager.compileReport(getClass().getResourceAsStream("/reports/yourReport.jrxml"));
See you!
Old topic, but could be useful.
I thing where is no src folder inside your jar.
InputStream jasper2 = getClass().getResourceAsStream("/ie/test/OMACYTDReportFinalpg2.jasper");
Where is more advanced way:
Put your jasper reports, images and other resources into jar.
Put YourClass inside jar file and load resources using class.getResourceAsStream() and you need to add loader extention before load resource
(JasperReport) JRLoader.loadObject("stream or path");
// DefaultJasperReportsContext user ExtensionsEnvironment
ExtensionsEnvironment.setThreadExtensionsRegistry(LoaderExtention.INSTANCE);
The following example of loading resources
public class LoaderService
implements RepositoryService
{
public static final RepositoryService INSTANCE = new LoaderService();
#Override
public void setContext(RepositoryContext repositoryContext)
{
}
#Override
public void revertContext()
{
}
#Override
public InputStream getInputStream(String file)
{
LOGGER.fine(String.format("getInputStream('%s')", file));
return <YourClass>.class.getResourceAsStream(file);
}
#Override
public Resource getResource(String file)
{
LOGGER.fine(String.format("getResource('%s') not implemented", file));
return null;
}
#Override
public <K extends Resource> K getResource(String file, Class<K> cls)
{
LOGGER.fine(String.format("getResource('%s', %s)", file, cls != null? cls.getName(): null));
try
{
if (cls == ReportResource.class)
{
InputStream resource = getInputStream(file);
if (resource != null)
{
JasperReport report = (JasperReport) JRLoader.loadObject(resource);
if (report != null)
{
ReportResource res = new ReportResource();
res.setName(file);
res.setReport(report);
return (K) res;
}
}
}
else if (cls == InputStreamResource.class)
{
InputStream resource = getInputStream(file);
if (resource != null)
{
InputStreamResource res = new InputStreamResource();
res.setInputStream(resource);
return (K) res;
}
}
}
catch (JRException e)
{
}
return null;
}
#Override
public void saveResource(String string, Resource resource)
{
// TODO Implement this method
}
}
public class LoaderExtention
implements ExtensionsRegistry
{
public static final LoaderExtention INSTANCE = new LoaderExtention();
#Override
public <T extends Object> List<T> getExtensions(Class<T> cls)
{
ExtensionsRegistry system = ExtensionsEnvironment.getSystemExtensionsRegistry();
List<T> services = null;
if (system != null)
services = system.getExtensions(cls);
if (cls == RepositoryService.class)
{
List<T> servicesAll = new ArrayList<T>();
if (services != null)
servicesAll.addAll(services);
servicesAll.add((T) LoaderService.INSTANCE); // Try to use system resource loaders then my
services = servicesAll;
}
LOGGER.fine(String.format("getExtensions(%s) = %s", cls.getName(), services));
return services;
}
}
I use JasperReport 5.5
Have fun.
InputStream jasper1 = getClass().getResourceAsStream("src/ie/test/OMACYTDReportFinalpg1.jasper");
InputStream jasper2 = getClass().getResourceAsStream("src/ie/test/OMACYTDReportFinalpg2.jasper");
it works fine in when I run it in Netbeans but it's won't show in executable jar file here's my codes
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
rep.siapkan_report_dengan_parameter("report4.jrxml", "Report", "periode",tCari.getText());
this.setCursor(Cursor.getDefaultCursor());
}
public void siapkan_report_dengan_parameter(
String nama_report,
String direktori,
String namaparameter,
String isiparameter){
konek.openConnection();
Properties systemProp = System.getProperties();
// Ambil current dir
String currentDir = systemProp.getProperty("user.dir");
File dir = new File(currentDir);
String reportName = nama_report;
String reportDirName = direktori;
File fileRpt;
String fullPath = "";
if (dir.isDirectory()) {
String[] isiDir = dir.list();
for (int i = 0; i < isiDir.length; i++) {
fileRpt = new File(currentDir + File.separatorChar + isiDir[i] + File.separatorChar +
reportDirName + File.separatorChar + reportName);
if (fileRpt.isFile()) { // Cek apakah file ada
fullPath = fileRpt.toString();
}
}
}
String[] subRptDir = fullPath.split(reportName);
try {
// Persiapkan parameter untuk Report
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put(namaparameter, isiparameter);
try {
JasperReport JRpt = JasperCompileManager.compileReport(fullPath);
JasperPrint JPrint = JasperFillManager.fillReport(JRpt, parameters,konek.conn);
if(JPrint.getPages().isEmpty()){
JOptionPane.showMessageDialog(null,
"Data Untuk Kriteria :\n" + isiparameter +"\nTidak Ada",
"Peringatan",
JOptionPane.ERROR_MESSAGE);
}else{
JasperViewer.viewReport(JPrint, false);
}
} catch (Exception rptexcpt) {
JOptionPane.showMessageDialog(null,
"a",
"Peringatan",
JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null,
"b",
"Peringatan",
JOptionPane.ERROR_MESSAGE);
}
}
thanks in advance!
my libraries are:
common-beanutils-1.7
commons-collections-2.1
commons-digester-1.7
commons-javaflow-20060411
commons-logging-1.1
jasperreports-3.0.1
jdt-compiler-3.1.1
jfreechart-1.0.3
poi-3.0.1-FINAL-20070705
The problem is that you are not loading jasper report as a stream. So, try adding this:
InputStream st = getClass().getResourceAsStream(fullPath);
try {
JasperDesign jd = JRXmlLoader.load(st);
JasperReport JRpt = JasperCompileManager.compileReport(jd);
JasperPrint JPrint = JasperFillManager.fillReport(JRpt, parameters,konek.conn);
if(JPrint.getPages().isEmpty()){
JOptionPane.showMessageDialog(null,
"Data Untuk Kriteria :\n" + isiparameter +"\nTidak Ada",
"Peringatan",
JOptionPane.ERROR_MESSAGE);
}else{
JasperViewer.viewReport(JPrint, false);
}
} catch (Exception rptexcpt) {
JOptionPane.showMessageDialog(null,
"a",
"Peringatan",
JOptionPane.ERROR_MESSAGE);
}
Also, add your .jrxml files in some package in your project before you export it to .jar.
Path (fullPath) you will pass will be something like: /com/report/nameofreport.jrxml.
Problem is not with your code... Just add following libraries. Don't use latest jasper libraries. that is the reason to not load your reports through jar executable. (use ireport 5.5.0 libraries). Code i use is below
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
org.apache.log4j.BasicConfigurator.configure(new NullAppender());
//InputStream st = getClass().getResourceAsStream("/Reports/SalesInvoiceCustomerCopy.jrxml");
try
{
Connection connect = conn.open();
String report2 = "H:\\Higher Diploma Project\\FinalHD\\src\\Reports\\SalesInvoiceCustomerCopy.jrxml";
JasperReport rep2 = JasperCompileManager.compileReport(report2);
JasperPrint rep_print2 = JasperFillManager.fillReport(rep2,null,connect);
JasperPrintManager.printReport(rep_print2,false);
String report = "H:\\Higher Diploma Project\\FinalHD\\src\\Reports\\SalesInvoice.jrxml";
JasperReport rep = JasperCompileManager.compileReport(report);
JasperPrint rep_print = JasperFillManager.fillReport(rep,null,connect);
JasperPrintManager.printReport(rep_print,false);
try
{
pst =conn.open().prepareStatement("INSERT INTO invoice_balanace VALUES (?,?,?,?)") ;
pst.setString(1, txtInvoiceNo.getText());
pst.setString(2, txtValue.getText());
pst.setString(3, totDisc.getText());
pst.setString(4, txtNetVal.getText());
pst.executeUpdate();
}catch(Exception e){JOptionPane.showMessageDialog(null, e);}
idUpdater();
}catch(Exception e){JOptionPane.showMessageDialog(null,""+ e);}
}
It is not quite efficient to use a compiled jasper report into your jar file. I'll suggest you reference the report from a location on your pc e.g., C: drive.
It'll also be Best if you have a permanent folder that can be easily accessed. It could be C:/<project name>/report/<your-report>.
This approach enables you to distribute it with ease.
I have a main report with a main query and a Table (with subdataset) inside of it, which has its own Query.
I know how to specify the Query for the main report, but I don't know how the to specify Query for the subdatset in my Java code of creation reports.
Can anyone help, please ?
My code:
public static java.sql.Connection cx = Connexion.SetConOn();
public static void Create report(String Query, String model, String title, String art) {
try {
JRDesignQuery jrd = new JRDesignQuery();
JasperDesign design = JRXmlLoader.load(model);
jrd.setText(Query);
design.setQuery(jrd);
Map map = new HashMap();
JasperReport etat = JasperCompileManager.compileReport(design);
JasperPrint print = JasperFillManager.fillReport(etat, map, cx);
File f = new File("C:\\" + fdg);
f.mkdir();
JasperExportManager.exportReportToPdfFile(print, f.getPath() + "\\" + title + ".pdf");
JasperViewer jv = new JasperViewer(print, false, Locale.FRENCH);
try {
java.awt.image.BufferedImage bi = javax.imageio.ImageIO.read(jv.getClass().getResource("/cycloplan/Images/Burn-icon1.png"));
javax.swing.ImageIcon myImg = new javax.swing.ImageIcon(bi);
jv.setIconImage(myImg.getImage());
} catch (java.io.IOException ex) {
ex.printStackTrace();
}
jv.setTitle(title);
jv.setAlwaysOnTop(true);
jv.setVisible(true);
} catch (JRException ex) {
ex.printStackTrace();
}
}
The JasperDesign class has a few different ways to access subdatasets; take a look at the javadoc [link]. I think the following code should work to set the subdataset query, where subQueryString is the query you want to use and datasetName is the name given to the subdataset element in the JRXML.
JRDesignQuery subQuery = new JRDesignQuery();
subQuery.setText(subQueryString);
Map<String, JRDataset> datasetMap = design.getDatasetMap();
JRDesignDataset subDataset = (JRDesignDataset) datasetMap.get(datasetName);
subDataset.setQuery(subQuery);
(* I haven't actually tested this code. YMMV)
I am trying to create JR report which is taking start_date and end_date as parameters.
The query:
SELECT * FROM emp WHERE joining_date BETWEEN $P{frm_date} AND $P{to_date}
The code:
Date from_date = dt_from_date.getDate();
Date to_date = dt_to_date.getDate();
java.sql.Date frm_dte = new java.sql.Date(from_date.getTime());
java.sql.Date to_dte = new java.sql.Date(to_date.getTime());
try {
HashMap map = new HashMap();
map.put("$P{frm_date}", frm_dte);
map.put("$P{to_date}", to_dte);
JasperPrint jp = JasperFillManager.fillReport(is, map, con);
JRViewer jv = new JRViewer(jp);
JFrame jf = new JFrame();
jf.getContentPane().add(jv);
jf.validate();
jf.setVisible(true);
jf.setSize(new Dimension(800, 600));
jf.setLocation(300, 100);
jf.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
} catch (JRException ex) {
ex.printStackTrace();
}
Can we pass Two Parameters to same Column in the table? Eg:
map.put("joining_date", frm_dte);
map.put("joining_date", to_dte);
You can pass date as string format type as follow,
if(from_date!=null)
{
formattedEndDate=new SimpleDateFormat("yyyy-MM-dd").format(from_date);
}
if(getStartDate()!=null)
{
formattedStartDate=new SimpleDateFormat("yyyy-MM-dd").format(to_date);
}
Your code is wrong.
You should pass parameters as below:
Map<String, Object> map = new HashMap<String, Object>();
map.put("frm_date", frm_dte);
map.put("to_date", to_dte);
You don't need to add P${} to the parameter's name.
There are a lot of samples in JasperReports distribution package.
You can look at this sample for more details.
private JasperPrint generateReport() {
Connection conn = null;
JasperPrint myJPrint = null;
try {
conn =yourconnectionName;
// parameters to be passed to the report
Map<String, Object> params = new HashMap();
// Loading my jasper file
JasperDesign jasperDesign = null;
JasperReport jasperReport = null;
params.put("REPORT_DIR",yourClassName.class.getClassLoader()
.getResource("yourJasperFileName.jrxml").toString().replace("yourJasperFileName.jrxml", ""));
jasperDesign = JasperManager.loadXmlDesign(yourClassName.class
.getClassLoader().getResourceAsStream("yourJasperFileName.jrxml"));
params.put("joining_date", frm_dte);
params.put("leaving_date", frm_dte);
jasperReport = JasperCompileManager.compileReport(jasperDesign);
/*
* Filling the report with data from the database based on the
* parameters passed.
*/
myJPrint = JasperFillManager.fillReport(jasperReport, params, conn);
params.clear();
} catch (JRException ex) {
ex.printStackTrace();
}
return myJPrint;
}