Netbeans 6.1 & Jasper Reports – a Marriage made in heaven or somewhere else nice.

Ok

I’m nearly ready to roll out a big course booking application so I needed to start implementing the reports and just like everyone else I chose Jasper Reports netbeans plugin.

BRILLIANT, we are delivering the reports in PDF format so its easy for the customer to email or print them as required.

How is it done?

1. Install the Netbans Jasper Reports plugin file (NBM download from the Jasper Reports website)

2. Add the Jasper Reports Snapshot viewer library to your project

3. Right click your web project, then Add a Jasper Report – I decided it would be nice to use the wizard and go from there –

a. hint – you need to add the extension .jrxml to the filename so netbeans knows what it is.
b. FOLDER – put it in the WEB folder

4. Edit your report and save

Now the dirty code….

I modded this code from another site to make it work with Netbeans 6 and with having the file located in the WEB directory.

/**
 * <p>Generate the specified report, in the specified output
 * format, based on the specified data.</p>
 *
 * @param name Report name to be rendered
 * @param type Content type of the requested report ("application/pdf"
 *  or "text/html")
 * @param data <code>ResultSet</code> containing
 *  the data to report
 *
 * @exception IllegalArgumentException if the specified
 *  content type is not recognized
 * @exception IllegalArgumentException if no compiled report definition
 * for the specified name can be found
*/
public void jasperReport(String name, String type,
ResultSet data) {
jasperReport(name, type, data, new HashMap());
}

/**
 * <p>Generate the specified report, in the specified output
 * format, based on the specified data.</p>
 *
 * @param name Report name to be rendered
 * @param type Content type of the requested report ("application/pdf"
 *  or "text/html")
 * @param data <code>ResultSet</code> containing the data to report
 * @param params <code>Map</code> of additional
 *   report parameters
 *
 * @exception IllegalArgumentException if the specified
 *  content type is not recognized
 * @exception IllegalArgumentException if no compiled report definition
 * for the specified name can be found
*/
public void jasperReport(String name, String type,
ResultSet data, Map params) {

// Validate that we recognize the report type
// before potentially wasting time filling the
// report with data
boolean found = false;
for (int i = 0; i < VALID_TYPES.length; i++) {
if (VALID_TYPES[i].equals(type)) {
found = true;
break;
}
}
if (!found) {
throw new IllegalArgumentException("Invalid report type '"
+ type
+ "' requested");
}

// Look up the compiled report design resource
ExternalContext econtext = getExternalContext();
InputStream stream = econtext.getResourceAsStream(PREFIX + name
+ SUFFIX);
if (stream == null) {
throw new IllegalArgumentException("Unknown report name '"
+ name
+ "' requested");
}

try {
data.beforeFirst();
} catch (Exception e) {
throw new FacesException(e);
}

// Fill the requested report with the specified data
JRResultSetDataSource ds = new JRResultSetDataSource(data);
JasperPrint jasperPrint = null;
try {
jasperPrint = JasperFillManager.fillReport(
stream, params, ds);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new FacesException(e);
} finally {
try {
stream.close();
} catch (IOException e) {

}
}

// Configure the exporter to be used, along with the custom
// parameters specific to the exporter type
JRExporter exporter = null;
HttpServletResponse response = (HttpServletResponse)
econtext.getResponse();
FacesContext fcontext = FacesContext.getCurrentInstance();
try {
response.setContentType(type);
if ("application/pdf".equals(type)) {
exporter = new JRPdfExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT,
jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
response.getOutputStream());
} else if ("text/html".equals(type)) {
exporter = new JRHtmlExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT,
jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_WRITER,
response.getWriter());
// Make images available for the HTML output
HttpServletRequest request =
(HttpServletRequest)
fcontext.getExternalContext().getRequest();
request.getSession().setAttribute(
ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,
jasperPrint);
exporter.setParameter(
JRHtmlExporterParameter.IMAGES_MAP, new HashMap());
// The following statement requires mapping /image
// to the imageServlet in the web.xml.
//
// This servlet serves up images including the px
// images for spacing.
//
// Serve up the images directly so we
// don't incur the extra overhead associated with
// with a JSF request for a non-JSF entity.
exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI,
request.getContextPath() + "/image?image=");
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new FacesException(e);
}

// Enough with the preliminaries ...
// export the report already
try {
exporter.exportReport();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new FacesException(e);
}

// Tell JavaServer Faces that no output is required
fcontext.responseComplete();

}

private void jasperReport(String name, String type, ResultSet data, HashMap hashMap) {
throw new UnsupportedOperationException("Not yet implemented");
}

Now to code a button to print to a PDF. Create a table and drop some data in it. Then also go look at the XML source code of your report, you’ll see the SQL query there you’ll need to copy that and paste it in.

In this case my grid has created a CachedDataRowProvider1() so I use that to supply the data for the report. Note that I also set up a Static Text box and named it txtRESULT just incase I get any problems (don’t forget to add the binding attribute).

public String button3_action() {
Map fillParams = new HashMap();
// The above statement generates warnings with Java SE 1.5
// To eliminate the warnings, replace with the
// following statement:
// Map<String, URL> fillParams =
//   new HashMap<String, URL.>>();
try {
String sSaveSQL=getSessionBean1().getCoursesRowSet1().getCommand();
// Set up the data provider to match your SQL code from the report.
getSessionBean1().getCoursesRowSet1().setCommand(
"SELECT  courses.`coursetitle` AS courses_coursetitle," +
" courses.`coursedescription` AS courses_coursedescription, " +
" courses.`price` AS courses_price, "+
" courses.`kitprovided` AS courses_kitprovided, "+
" courses.`days` AS courses_days "+
" FROM `courses` courses "+
" ORDER BY courses.`coursetitle`");
getSessionBean1().getCoursesRowSet1().execute();
getApplicationBean1().jasperReport
("Courses", "application/pdf",
getSessionBean1().getCoursesRowSet1(), fillParams);
getSessionBean1().getCoursesRowSet1().setCommand(sSaveSQL);
} catch (Exception e) {
txtRESULT.setText("Exception generating report: " + e);
}
return null;

}

and that should do it. My thanks for getting me started (and most of the code goes to this) http://www.netbeans.org/kb/55/vwp-reports.html

Note that you do not have to do most of the setup in that document as Netbeans now does it for you. Just install the plugin, add the libraries, use the code and off you go.

Advertisements

About Paul C

I am a Senior Java programmer/Web Technologies, Play in a band called Mandolin Monday, I have a cat and I live on a boat.

Posted on April 17, 2008, in Uncategorized. Bookmark the permalink. 13 Comments.

  1. Will I only need to copy-and-paste the code above?
    Sorry, noob here…
    I have created a sample webapp that also displays a report, but it shows the report using the JasperViewer. Is there anyway that I can instruct the iReport plugin to generate the output to HTML?
    Thanks!

  2. Yes. Change the callling code where it says

    application/pdf

    to

    text/html

  3. pls i am also a very patrotic user of netbean but with all the hip about jasperreport i also tried it out but no matter the way i try, i can not yet succes full bulid a repot .it always came out with an error
    below is a sample code that i found on the net but it refuse to work even after i setup the database i relly needed help because i really fell in love with JAVA but i can not succesfull create a reprot and i can make use of the printer

    import java.io.IOException;
    import java.sql.SQLException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import net.sf.jasperreports.engine.JRException;

    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    import net.sf.jasperreports.engine.JasperReport;

    /**
    *
    * @author Awo
    */
    import java.sql.Connection;
    import java.sql.DriverManager;
    public class NewMain {

    /**
    * @param args the command line arguments
    */
    NewMain()
    {
    try {
    javax.swing.JFileChooser jfc= new javax.swing.JFileChooser();
    Class.forName(“com.mysql.jdbc.Driver”);
    Connection con=
    DriverManager.getConnection(“jdbc:mysql://localhost/library”,”root”,””);//employees
    java.io.File f=jfc.getSelectedFile();
    f= new java.io.File(“./src/classic.jrxml”);//.jasper”);
    java.io.InputStream is= new java.io.FileInputStream(f);
    net.sf.jasperreports.engine.JasperPrint jp= new net.sf.jasperreports.engine.JasperPrint();

    System.out.println(f.toString());
    System.out.println(f.getAbsolutePath());
    System.out.println(f.getCanonicalPath());
    net.sf.jasperreports.engine.design.JasperDesign jd=net.sf.jasperreports.engine.xml.JRXmlLoader.load(is);//”src/koko” +”.rjxml”);//is);
    d=net.sf.jasperreports.engine.JasperManager.loadXmlDesign(“src/devx_report_1″ +”.jrxml”);//”src/devx_report_2″
    java.util.Map parameters = new java.util.HashMap();
    parameters.put(“title”, “A user-customized title”);

    net.sf.jasperreports.engine.design.JRJavacCompiler jk= new net.sf.jasperreports.engine.design.JRJavacCompiler();
    JasperReport compileReport = jk.compileReport(jd);

    net.sf.jasperreports.view.JasperViewer.viewReport(is, true);
    }
    catch (IOException ex) {
    Logger.getLogger(NewMain.class.getName()).log(Level.SEVERE, null, ex);
    }

    catch (ClassNotFoundException ex) {
    Logger.getLogger(NewMain.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
    Logger.getLogger(NewMain.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JRException ex) {
    Logger.getLogger(NewMain.class.getName()).log(Level.SEVERE, null, ex);
    }
    }
    public static void main(String[] args) {

    NewMain obj= new NewMain();
    }

    }

    but it always come out with the following runtime error

    12-Jul-2008 15:51:38 NewMain
    SEVERE: null
    net.sf.jasperreports.engine.JRException: Error compiling report java source files : C:\Users\Awo\Documents\NetBeansProjects\ReportConverter\classic_1215874298909_891766.java
    at net.sf.jasperreports.engine.design.JRJavacCompiler.compileClasses(JRJavacCompiler.java:93)
    at net.sf.jasperreports.engine.design.JRAbstractClassCompiler.compileUnits(JRAbstractClassCompiler.java:67)
    at net.sf.jasperreports.engine.design.JRAbstractCompiler.compileReport(JRAbstractCompiler.java:190)
    at NewMain.(NewMain.java:50)
    at NewMain.main(NewMain.java:81)
    Caused by: java.io.IOException: Cannot run program “javac”: CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:459)
    at java.lang.Runtime.exec(Runtime.java:593)
    at java.lang.Runtime.exec(Runtime.java:466)
    at net.sf.jasperreports.engine.design.JRJavacCompiler.compileClasses(JRJavacCompiler.java:62)
    … 4 more
    Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.(ProcessImpl.java:81)
    at java.lang.ProcessImpl.start(ProcessImpl.java:30)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:452)
    … 7 more

    is there something wrong with my code or is there something am not doing pls i need help or tutorial ASAP
    Thansk yours
    GIGACODE

    • Hi Olanrewaju
      I also m writing project with jasper report in Netbeans 6.1. But I have the same errors as you. Pls help me if you have correct technology.

  4. i want jasper vidio tutorials

  5. Unfortunately I don’t have the equipment to do this at present and don’t forget that I do this as a service to the Netbeans community, I don’t get paid for it!

  6. java.io.IOException: Cannot run program “javac”: CreateProcess error=2, The system cannot find the file specified

    your java runtime is not setup right

  7. Hi guys. I’m new to netbeans and java. I’m trying to use jasper reports with JSP and tomcat in netbeans. Can you tell me a good starting point?

  8. String sSaveSQL=getSessionBean1().getCoursesRowSet1().getCommand();
    getSessionBean1().getCoursesRowSet1().setCommand(sSaveSQL);
    getSessionBean1().getCoursesRowSet1().execute();

    here it gets the command from the rowset and executes but if we want to give parameters to the command how we can pass.

  9. there is a problem that package”java.sql.*” %>

    <%@ page import=”net.sf.
    does not exist, what is the real steps to create jasper report using jsp

  10. i will like to use jasper report with my netbeans IDE so i can view it on my machine not on any website.

  11. i use jasper report and iReport to design my database (i use mysql) in netbeans 6.0.1. I got an error message when i made report datasource. it said :

    ClassNotFoundError!
    Msg: com.mysql.jdbc.Driver
    Possible not found class: com.mysql.jdbc.Driver

    Message:
    java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
    Level:
    SEVERE
    Stack Trace:
    com.mysql.jdbc.Driver
    com.jaspersoft.ireport.designer.connection.DriverPool.registerDriver(DriverPool.java:156)
    com.jaspersoft.ireport.designer.connection.JDBCConnection.getConnection(JDBCConnection.java:98)
    com.jaspersoft.ireport.designer.connection.JDBCConnection.test(JDBCConnection.java:420)
    com.jaspersoft.ireport.designer.connection.gui.ConnectionDialog.jButtonTestActionPerformed(ConnectionDialog.java:316)
    com.jaspersoft.ireport.designer.connection.gui.ConnectionDialog.access$300(ConnectionDialog.java:25)
    com.jaspersoft.ireport.designer.connection.gui.ConnectionDialog$4.actionPerformed(ConnectionDialog.java:271)
    javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
    javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
    javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
    javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
    javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
    java.awt.Component.processMouseEvent(Component.java:6041)
    javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
    java.awt.Component.processEvent(Component.java:5806)
    java.awt.Container.processEvent(Container.java:2058)
    java.awt.Component.dispatchEventImpl(Component.java:4413)
    java.awt.Container.dispatchEventImpl(Container.java:2116)
    java.awt.Component.dispatchEvent(Component.java:4243)
    java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
    java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
    java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
    java.awt.Container.dispatchEventImpl(Container.java:2102)
    java.awt.Window.dispatchEventImpl(Window.java:2440)
    java.awt.Component.dispatchEvent(Component.java:4243)
    java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
    java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
    java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:177)
    java.awt.Dialog$1.run(Dialog.java:1045)
    java.awt.Dialog$3.run(Dialog.java:1097)
    java.security.AccessController.doPrivileged(Native Method)
    java.awt.Dialog.show(Dialog.java:1095)
    java.awt.Component.show(Component.java:1422)
    java.awt.Component.setVisible(Component.java:1375)
    java.awt.Window.setVisible(Window.java:806)
    java.awt.Dialog.setVisible(Dialog.java:985)
    com.jaspersoft.ireport.designer.connection.gui.ConnectionsDialog.jButtonNewParameterActionPerformed(ConnectionsDialog.java:539)
    com.jaspersoft.ireport.designer.connection.gui.ConnectionsDialog.access$200(ConnectionsDialog.java:54)
    com.jaspersoft.ireport.designer.connection.gui.ConnectionsDialog$6.actionPerformed(ConnectionsDialog.java:203)
    javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
    javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
    javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
    javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
    javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
    java.awt.Component.processMouseEvent(Component.java:6041)
    javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
    java.awt.Component.processEvent(Component.java:5806)
    java.awt.Container.processEvent(Container.java:2058)
    java.awt.Component.dispatchEventImpl(Component.java:4413)
    java.awt.Container.dispatchEventImpl(Container.java:2116)
    java.awt.Component.dispatchEvent(Component.java:4243)
    java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
    java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
    java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
    java.awt.Container.dispatchEventImpl(Container.java:2102)
    java.awt.Window.dispatchEventImpl(Window.java:2440)
    java.awt.Component.dispatchEvent(Component.java:4243)
    java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
    java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
    java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:177)
    java.awt.Dialog$1.run(Dialog.java:1045)
    java.awt.Dialog$3.run(Dialog.java:1097)
    java.security.AccessController.doPrivileged(Native Method)
    java.awt.Dialog.show(Dialog.java:1095)
    java.awt.Component.show(Component.java:1422)
    java.awt.Component.setVisible(Component.java:1375)
    java.awt.Window.setVisible(Window.java:806)
    java.awt.Dialog.setVisible(Dialog.java:985)
    com.jaspersoft.ireport.designer.connection.gui.ConnectionsDialog.setVisible(ConnectionsDialog.java:605)
    com.jaspersoft.ireport.designer.menu.DatasourcesAction.performAction(DatasourcesAction.java:23)
    org.openide.util.actions.CallableSystemAction$1.run(CallableSystemAction.java:118)
    org.netbeans.modules.openide.util.ActionsBridge.doPerformAction(ActionsBridge.java:77)
    org.openide.util.actions.CallableSystemAction.actionPerformed(CallableSystemAction.java:114)
    javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
    javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
    javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
    javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
    javax.swing.AbstractButton.doClick(AbstractButton.java:357)
    javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1220)
    javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:1261)
    java.awt.Component.processMouseEvent(Component.java:6041)
    javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
    java.awt.Component.processEvent(Component.java:5806)
    java.awt.Container.processEvent(Container.java:2058)
    java.awt.Component.dispatchEventImpl(Component.java:4413)
    java.awt.Container.dispatchEventImpl(Container.java:2116)
    java.awt.Component.dispatchEvent(Component.java:4243)
    java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
    java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
    java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
    java.awt.Container.dispatchEventImpl(Container.java:2102)
    java.awt.Window.dispatchEventImpl(Window.java:2440)
    java.awt.Component.dispatchEvent(Component.java:4243)
    java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
    java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
    java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
    java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
    java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
    java.awt.EventDispatchThread.run(EventDispatchThread.java:121)

    can u help me?
    how can i fix it?
    it can’t connect with mysql eventhough i was setting mysql-connector-java-5.0.7-bin.jar in CLASSPATH

  12. Hi,

    I wanted to create an html page from .jasper file.BUt instead of opening the file in browser i get the path of html page printed on the html page and an html file(empty) is created on the web path.I am using netbeans 6.1
    What could be the reason???

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: