Posts tagged ‘Visual Web Pack’

ObjectListDataProvider Tutorial

This is a tutorial for using the ObjectListDataProvider in a Visual Web Project. A ObjectListDataProvider is useful if the underlaying data is from a datasource not supported by NetBeans. Some samples for such datasources are a JPA or hibernate connection, other legacy systems such SAP or Lotus Notes and files in various formats.

In this tutorial we use a text file with customer records as datasource for our application.

Creating the project

In the first step you create a normal VWP project named OldpSample:

Project settings OLDP

Address POJO

For data storage we use a simple POJO object. Right click the oldpsample package under «Source Packages» and select «New -> Java Class». Name the class Address.

Create Address class

  1. package oldpsample;
  2.  
  3. public class Address {
  4.  
  5. private String id;
  6. private String title;
  7. private String lastname;
  8. private String firstname;
  9. private String street;
  10. private String city;
  11. private String state;
  12. private String country;
  13.  
  14. /** Creates a new instance of Address */
  15. public Address() {
  16. }
  17.  
  18. public String getId() {
  19. return id;
  20. }
  21.  
  22. public void setId(String id) {
  23. this.id = id;
  24. }
  25.  
  26. public String getTitle() {
  27. return title;
  28. }
  29.  
  30. public void setTitle(String title) {
  31. this.title = title;
  32. }
  33.  
  34. public String getLastname() {
  35. return lastname;
  36. }
  37.  
  38. public void setLastname(String lastname) {
  39. this.lastname = lastname;
  40. }
  41.  
  42. public String getFirstname() {
  43. return firstname;
  44. }
  45.  
  46. public void setFirstname(String firstname) {
  47. this.firstname = firstname;
  48. }
  49.  
  50. public String getStreet() {
  51. return street;
  52. }
  53.  
  54. public void setStreet(String street) {
  55. this.street = street;
  56. }
  57.  
  58. public String getCity() {
  59. return city;
  60. }
  61.  
  62. public void setCity(String city) {
  63. this.city = city;
  64. }
  65.  
  66. public String getState() {
  67. return state;
  68. }
  69.  
  70. public void setState(String state) {
  71. this.state = state;
  72. }
  73.  
  74. public String getCountry() {
  75. return country;
  76. }
  77.  
  78. public void setCountry(String country) {
  79. this.country = country;
  80. }
  81.  
  82. }

Create AddressDataProvider

Now we create the class AddressDataProvider. We create a new class and derive it from ObjectListDataProvider. Right click the oldpsample package under «Source Packages» and select «New -> Java Class».

Create AdressDataProvider class

Our class stores all data in a ArrayList, so we need a member variable of type ArrayList. In the constructor we must tell the underlying ObjectListDataProvider where the data comes from (method setList) and of which type the data is (method setObjectType). We also need methods to load the data from file or stream.

  1. package oldpsample;
  2.  
  3. import com.sun.data.provider.impl.ObjectListDataProvider;
  4. import java.io.BufferedReader;
  5. import java.io.FileInputStream;
  6. import java.io.InputStream;
  7. import java.io.InputStreamReader;
  8. import java.util.ArrayList;
  9.  
  10. public class AddressDataProvider extends ObjectListDataProvider {
  11.  
  12. private ArrayList addressList = new ArrayList();
  13.  
  14. /** Creates a new instance of AddressDataProvider */
  15. public AddressDataProvider() {
  16. setList( addressList );
  17. setObjectType( Address.class );
  18. }
  19.  
  20. public void load(InputStream istream ) {
  21. try {
  22. InputStreamReader sr = new InputStreamReader( istream );
  23.  
  24. while ( br.ready() ) {
  25. String line = br.readLine();
  26. String[] cols = line.split( ";" );
  27.  
  28. if ( cols.length == 8 ) {
  29. Address address = new Address();
  30. address.setId( cols[0] );
  31. address.setTitle( cols[1] );
  32. address.setLastname( cols[2] );
  33. address.setFirstname( cols[3] );
  34. address.setStreet( cols[4] );
  35. address.setCity( cols[5] );
  36. address.setState( cols[6] );
  37. address.setCountry( cols[7] );
  38. getList().add( address );
  39. }
  40. }
  41.  
  42. } catch ( Exception e ) {
  43. e.printStackTrace();
  44. }
  45. }
  46.  
  47. public void load(String filename) {
  48. try {
  49. FileInputStream fs = new FileInputStream( filename );
  50. load( fs );
  51. } catch ( Exception e ) {
  52. e.printStackTrace();
  53. }
  54. }
  55.  
  56. }

Add AddressDataProvider to SessionBean1

In the outline view right click on SessionBean1 and select «Add->Property» from the context menu. Name the property «addressDataProvider» and enter «AddressDataProvider» as Type. Leave all other options on the default values.

New Property addressDataProvider

Double click SessionBean1 in the outline view. Find the line

  1. private AddressDataProvider addressDataProvider;

and change it to

  1. private AddressDataProvider addressDataProvider = new AddressDataProvider();

You must build, close and reopen your VWP project now (as of NetBeans 5.5.1). If not, NetBeans doesn't detect our ObjectListDataProvider. This should hopefully not been necessary in future NetBeans releases.

Design Web Page

The project wizard has generated a default web page Page1.jsp. Open this page and the visual designer starts.

Select a table component from the palette and drop it onto your page. Right click the table component and select «Bind to Data...». Select «addressDataProvider (SessionBean1)» from the dropdown list. Reorder the fields with the «Up» and «Down» buttons, so it look like this:

Select Data Provider

Press «OK» and our page has a table component bound to the AddressDataProvider.

To show some data in the table component we let the user upload a CSV file. Drop a File Upload and a Button component from the palette onto the page. Set the text property of the button to «Upload file». Your page should look like this:

Page Design

Double click on the «Upload file» button and enter the following code into the event handler:

  1. public String button1_action() {
  2. if ( fileUpload1.getUploadedFile().getSize() > 0 ) {
  3. try {
  4. getSessionBean1().getAddressDataProvider().load(
  5. getFileUpload1().getUploadedFile().getInputStream() );
  6. } catch ( Exception e ) {
  7. e.printStackTrace();
  8. }
  9. }
  10. return null;
  11. }

Run your project. Use this sample CSV data file to test the application:

1;Mr.;Able;Tony;216 King St;San Francisco;CA;USA
2;Mr.;Black;Tom;655 Divisadero St;San Francisco;CA;USA
3;Mr.;Kent;Richard;509 Valencia St;San Francisco;CA;USA
4;Mr.;Chen;Larry;407 Ellis St;San Francisco;CA;USA
5;Mrs.;Donaldson;Sue;314 Columbus Ave;San Francisco;CA;USA
6;Mr.;Murrell;Tony;4124 Geary Blvd;San Francisco;CA;USA

This sample project can also be downloaded.

Fill a treeview programmatically

You must build a collection of TreeNode objects and add this collection to the TreeView control. Each TreeNode object has several properties to set up the visual appearance and functionality.

Important TreeNode properties

expanded - Shows this node expaned with children
ext - Title text of the node
target - Target browser window
toolTip - Tooltip text to display
url - Hyperlink to navigate to
action - Name of method to call if user selects this node
actionListenerExpression - Expression for action listener method.

Adding icon to TreeNode

To add a icon to the TreeNode you must first create a ImageComponent. Now you can set the theme specific icon with the setIcon method. Use a constant of class ThemeImages for the icon name. Add the created ImageComponent as facet to the TreeNode.

Sample:

  1. ImageComponent image = new ImageComponent();
  2. image.setIcon( TreeImages.TREE_FOLDER );
  3. treeNode.getFacets().put( treeNode.IMAGE_FACET_KEY, image );

Setting Action Expression for TreeNode

To set the Action Expression of a TreeNode you must use the method setActionExpression of the TreeNode object. This method needs a MethodExpression object as parameter.

Sample code:

  1. ExpressionFactory ef = FacesContext.
  2. getCurrentInstance().
  3. getApplication().
  4. getExpressionFactory();
  5. ELContext elContext = FacesContext.
  6. getCurrentInstance().
  7. getELContext();
  8. MethodExpression me = ef.createMethodExpression(
  9. elContext,
  10. "#{Page1.treeNode_action}",
  11. String.class, new Class[]{} );
  12. treeNode.setActionExpression( me );

ICEFaces installation for NetBeans IDE

ICEFaces is a Java Server Faces component library. To integrate ICEFaces into the NetBeans IDE and the Visual Web Pack the following steps are necessary.

Download of ICEFaces components

The following downloads from the ICEFaces website are needed:

  • ICEfaces-<version>-libs-NetBeans.zip
  • ICEfaces-NetBeans-IDE-<version>.zip
  • ICEfaces-<version>-complib-NetBeans.zip

Installation of ICEFaces runtime library

Unpack the file ICEfaces-<version>-libs-NetBeans.zip and import the included com-icesoft-ide-netbeans-libs-module.nbm module with the NetBeans Update Manager.

Installation of ICEFaces IDE integration

Unpack the file ICEfaces-NetBeans-IDE-<version>.zip and install the module com-icesoft-faces-vwp-ide.nbm. This module must also be installed with the NetBeans Update Manager.

Installation of ICEFaces component library

Unpack file icefaces-webui.complib from ICEfaces-<version>-complib-NetBeans.zip and copy it to your <netbeans-install-dir>/rave2.0/samples folder.

Import the component library with the Component Library Manager under «Tools->Component Library Manager» into your IDE.

Use of ICEFaces components in a Visual Web Pack project

To use the ICEFaces components in a Visual Web Pack application you must add the ICEFaces Component Suite to your project.

Using Jasper Reports with Visual Web Pack

This tutorial illustrates the use of Jasper Reports with a Visual Web Pack application.

Register Jasper Reports library

Use the NetBeans Library Manager to create a library for the Jasper Reports class libraries. You need at least the following files from the distribution:

  • dist/jasperreports-<version>.jar
  • lib/commons-beanutils-1.7.jar
  • lib/commons-collections-2.1.jar
  • lib/commons-digester-1.7.jar
  • lib/commons-logging-1.0.2.jar
  • lib/itext-1.3.1.jar

Register Jasper Reports image servlet

The image servlet is needed if you want html rendered reports (also without any graphical elements, because report placeholders uses images from this servlet). So you must register it in the web.xml configuration file. You can use the NetBeans web.xml editor to do so.

Servlet name  : ImageServlet
Servlet class : net.sf.jasperreports.j2ee.servlets.ImageServlet
URL           : /image

Insert methods for report output to application bean

The following methods in the application bean can be used to output a precompiled report as html or pdf. In this sample a collection of java objects is used as data source. For other data sources see the Jasper Reports documentation.

  1. /**
  2.  * Output Jasper Report
  3.  *
  4.  * @param filename Precompiled report filename
  5.  * @param type Content type of report ("application/pdf" or "text/html")
  6.  * @param data Collection of value objects
  7.  */
  8. public void jasperReport( String filename, String type, Collection data ) {
  9. jasperReport( filename, type, data, new HashMap() );
  10. }
  11.  
  12. /**
  13.  * Output Jasper Report
  14.  *
  15.  * @param filename Precompiled report filename
  16.  * @param type Type of report ("application/pdf" or "text/html")
  17.  * @param data Collection of value objects
  18.  * @param params Map with parameters
  19.  */
  20. public void jasperReport( String filename, String type, Collection data, Map params ) {
  21. final String[] VALID_TYPES = { "text/html", "application/pdf" };
  22. // First check if type is supported
  23. boolean found = false;
  24. for ( int i = 0; i < VALID_TYPES.length; i++ ) {
  25. if ( VALID_TYPES[i].equals( type ) ) {
  26. found = true;
  27. break;
  28. }
  29. }
  30.  
  31. if ( !found ) {
  32. throw new IllegalArgumentException( "Report type '" + type + "' not supported." );
  33. }
  34.  
  35. // InputStream for compiled report
  36. ExternalContext econtext = getExternalContext();
  37. InputStream stream = econtext.getResourceAsStream( filename );
  38.  
  39. if ( stream == null ) {
  40. throw new IllegalArgumentException( "Report '" + filename + "' could not be opened." );
  41. }
  42.  
  43. // Use collection as data source
  44. JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource( data );
  45. JasperPrint jasperPrint = null;
  46.  
  47. try {
  48. jasperPrint = JasperFillManager.fillReport( stream, params, ds );
  49. } catch ( RuntimeException e ) {
  50. throw e;
  51. } catch ( Exception e ) {
  52. throw new FacesException( e );
  53. } finally {
  54. try {
  55. stream.close();
  56. } catch ( IOException e ) {
  57. }
  58. }
  59.  
  60. // Configure exporter and set parameters
  61. JRExporter exporter = null;
  62. HttpServletResponse response = (HttpServletResponse) econtext.getResponse();
  63. FacesContext fcontext = FacesContext.getCurrentInstance();
  64.  
  65. try {
  66. response.setContentType( type );
  67.  
  68. if ( "application/pdf".equals( type ) ) {
  69. exporter = new JRPdfExporter();
  70. exporter.setParameter( JRExporterParameter.JASPER_PRINT, jasperPrint );
  71. exporter.setParameter( JRExporterParameter.OUTPUT_STREAM,
  72. response.getOutputStream() );
  73. } else if ( "text/html".equals( type ) ) {
  74. exporter = new JRHtmlExporter();
  75. exporter.setParameter( JRExporterParameter.JASPER_PRINT, jasperPrint );
  76. exporter.setParameter( JRExporterParameter.OUTPUT_WRITER, response.getWriter() );
  77. HttpServletRequest request = (HttpServletRequest)
  78. fcontext.getExternalContext().getRequest();
  79. request.getSession().setAttribute(
  80. ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint );
  81. exporter.setParameter( JRHtmlExporterParameter.IMAGES_MAP, new HashMap() );
  82. exporter.setParameter(
  83. JRHtmlExporterParameter.IMAGES_URI,
  84. request.getContextPath() + "/image?image=" );
  85. }
  86. } catch ( RuntimeException e ) {
  87. throw e;
  88. } catch ( Exception e ) {
  89. throw new FacesException( e );
  90. }
  91.  
  92. // Export report
  93. try {
  94. exporter.exportReport();
  95. } catch ( RuntimeException e ) {
  96. throw e;
  97. } catch ( Exception e ) {
  98. throw new FacesException( e );
  99. }
  100.  
  101. // Tell JavaServer faces that no more processing is necessary
  102. fcontext.responseComplete();
  103. }

Start report output from page bean

The output of a report can initiated from a ActionEvent with the following code:

  1. try {
  2. getApplicationBean().jasperReport(
  3. "/reports/report.jasper",
  4. "application/pdf",
  5. getSessionBean().getSuchergebnisDataProvider().getList() );
  6. } catch ( Exception e ) {
  7. Logger.getLogger(getClass().getName()).severe( e.getMessage() );
  8. }
  9.  
  10. return null;

Center VWP components

There isn't any standard function in the Visual Web Pack to center components on the page. You can only use absolute or flow layout.

If you want center your components horizontally or vertically, you need CSS. This is done with the style setting of your component.

position: absolute;
left: 50%;
top: 50%;

This setting would center the left upper corner of your component on the page, but not the whole component. To center the whole component you must adjust the margins. The margins can be negative, so substract the half of the vertical and horizontal size from the corresponding margin. In this sample assume that the component has a height of 100 pixels and a width of 200 pixels.

position: absolute;
left: 50%;
top: 50%;
margin-top: -50px;
margin-left: -100px;