How to pass Date as parameter to jasper report - java

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;
}

Related

GeoTools: insert custom Polygons into existiong .shp file

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 to fill jasper report using criteria.uniqueResult();?

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

How to fix FileNotFoundException

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();
}
}
}

How to specify the subdataset query when executing report from a Java application

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)

Using DynamicJasper API: Getting empty report with crosstab

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.

Categories