I want to view report by using customerId.
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, ?, ?);// How to fill?
I tried :
BLManager.java
public void report(int custId) throws JRException, FileNotFoundException {
Session session = sessionFactory.openSession();
Criteria criteria = session.createCriteria(Customer.class);
criteria.add(Restrictions.eq("custId", custId));
Customre customer = (Customer) criteria.uniqueResult();
FileInputStream fis = new FileInputStream("src/com/customer/reports/report.jrxml");
BufferedInputStream bis = new BufferedInputStream(fis);
JasperReport jasperReport = (JasperReport) JasperCompileManager.compileReport(bis);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, ?, ?);// How to fill?
JasperViewer.viewReport(jasperPrint, false);
}
Further I calling this method on buttonClick
Client Class
#FXML
private void viewReport(ActionEvent e) {
Customer customer = customerTable.getSelectionModel().getSelectedItem();
if (customer != null) {
int custId = customer.getCustId();
try {
bLManager.report(custId);
} catch (FileNotFoundException | JRException ex) {
Logger.getLogger(FollowUpController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
When you use fillReport method of JasperFillManager, you can pass a parameterMap.
A parameterMap is a HashMap where you put as key the name of paramter managed by the report, and as value the object instance.
This is my code to fill parameterMap (you can use as example for your case):
Map<String, Object> parameterMap = new HashMap<String, Object>;
parameterMap.put("datasource", jRdataSource);
parameterMap.put("MyComplexObject", myComplexObject); // you can pass a pojo
parameterMap.put("Title", "My report title");
You can see the documentation about JasperFillManager methods here
Related
I'm new to Geotools. Now I want to insert a custom area (Polygon) in a Shapefile of Austria.
My code:
public static void main(String[] args) throws IOException {
File file = new File("src/main/java/org/geotools/austria.shp");
Map<String, Object> map = new HashMap<>();
map.put("url", file.toURI().toURL());
DataStore dataStore = DataStoreFinder.getDataStore(map);
String typeName = dataStore.getTypeNames()[0];
FeatureSource<SimpleFeatureType, SimpleFeature> source =
dataStore.getFeatureSource(typeName);
MapContent showmap = new MapContent();
showmap.setTitle("Austria");
Style style = SLD.createSimpleStyle(source.getSchema());
Layer layer = new FeatureLayer(source, style);
showmap.addLayer(layer);
// display the map
JMapFrame.showMap(showmap);
}
My current result:
This image shows my current output. I drew a red hexagon to show what I want to have in future.
How can I insert and display this Polygon into a Shapefile?
First you need to create a new Shapefile (you could overwrite the old one but it is easy to lose your data that way).
SimpleFeatureType TYPE = dataStore.getSchema(typeName);
File newFile = new File("output.shp");
ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
Map<String, Serializable> params = new HashMap<String, Serializable>();
params.put("url", URLs.fileToURL(newFile));
params.put("create spatial index", Boolean.TRUE);
ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
newDataStore.createSchema(TYPE);
Then you need to copy the existing polygons to the new file (I'm assuming they are in a SimpleFeatureCollection called collection) followed by the new feature(s):
Transaction transaction = new DefaultTransaction("create");
String typeName = newDataStore.getTypeNames()[0];
SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName);
if (featureSource instanceof SimpleFeatureStore) {
SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
featureStore.setTransaction(transaction);
try {
featureStore.addFeatures(collection);
// Now add the hexagon
featureStore.addFeatures(DataUtilities.collection(hexagon));
transaction.commit();
} catch (Exception problem) {
problem.printStackTrace();
transaction.rollback();
System.exit(-1);
} finally {
transaction.close();
}
} else {
System.out.println(typeName + " does not support read/write access");
System.exit(1);
}
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");
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 try to create dynamic crosstab. When I try, I have an error java.lang.ClassCastException Jasper Report Crosstab than I solved it. But my report is empty. I don't get it why. I check my result set is empty or not. But it does not empty.
Here is my code:
public class DynamicJasperTemplate{
.....//variables define here
public void buildReport() throws Exception{
....//I create query here and get row column and measure field name
JRDataSource ds = getDataSource(query,a,b,c);//I get data from db as jrdatasource
DynamicReport dr = buildReportLayout(a,b,c,ds); // build report layout and add it crosstab in this method.
params.put("sr",ds);//I set report parameter value
JasperReport jr = DynamicJasperHelper.generateJasperReport(dr, new ClassicLayoutManager(), params);
JasperPrint jp = JasperFillManager.fillReport(jr, params, ds);
JasperExportManager.exportReportToPdfFile(jp,"C:/report-out.pdf");
}
private DynamicReport buildReportLayout(String[] a,String[] b,String[] c, JRDataSource ds) {
FastReportBuilder drb = new FastReportBuilder();
drb.setWhenNoDataAllSectionNoDetail();
initStyles();
CrosstabBuilder cb = new CrosstabBuilder();
cb.setHeight(200)
.setWidth(500)
.setHeaderStyle(mainHeaderStyle)
.setDatasource("sr",DJConstants.DATA_SOURCE_ORIGIN_REPORT_DATASOURCE, DJConstants.DATA_SOURCE_TYPE_JRDATASOURCE)
.setUseFullWidth(true)
.setColorScheme(4)
.setAutomaticTitle(true)
.setCellBorder(Border.PEN_1_POINT());
Object obj="NUMBER";
Object obj1="VARCHAR2";
String type = null;
for(int i=0; i<a.length; i++) {
DJCrosstabRow row = new CrosstabRowBuilder().setProperty(a[i],String.class.getName())
.setHeaderWidth(100).setHeight(0)
.setTitle(a[i])
.setShowTotals(true).setTotalStyle(totalStyle)
.setTotalHeaderStyle(totalHeader).setHeaderStyle(colAndRowHeaderStyle)
.build();
cb.addRow(row);
}
DJCrosstabColumn col =new CrosstabColumnBuilder().setProperty(b.toString(),"java.sql.Timestamp")
.setHeaderHeight(60).setWidth(50)
.setTitle(b.toString()).setShowTotals(true)
.setTotalStyle(totalStyle).setTotalHeaderStyle(totalHeader)
.setHeaderStyle(colAndRowHeaderStyle)
.build();
cb.addColumn(col);
cb.addMeasure(c[0],"java.math.BigDecimal", DJCalculation.NOTHING , c[0],measureStyle);
djcross = cb.build();
drb.addHeaderCrosstab(djcross);
drb.setUseFullPageWidth(true);
drb.addParameter("sr", "java.util.Collection");
DynamicReport dr = drb.build();
return dr;
}
private void initStyles() {
....//here ı define styles
}
private JRDataSource getDataSource(String query,String[] a,String[] b,String[] c) throws SQLException, JRException {
Connection con = new getConnection().conn();
List<Map<String, ?>> arr = new ArrayList<Map<String, ?>>();
String columnValue;
Map data = new HashMap();
JRResultSetDataSource result = null;
ResultSet rs = null;
int i;
try{
if(con!=null){
Statement stmt = con.createStatement();
rs = stmt.executeQuery(query);
JRDataSource ds = new JRResultSetDataSource(rs);
return ds;
}
......
I hope you can tell me the what I make wrong.
I solved my problem here solution :
when ı delete drb.addParameter("sr", "java.util.Collection"); and b.toString() i make error as unknown column change it b[0] than my problem solved.
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;
}