Wednesday, June 11, 2014

JavaOne 2014 On the Horizon

This year, I submitted three proposals for the JavaOne conference, which takes place September 28 - October 2nd in San Francisco.  I am thrilled that two of them were accepted, and I am looking forward to presenting.  Here are a few details on the selected submissions:

Session ID: CON2038
Session Title: Java EE 7 Recipes
Abstract:
Learn important features of Java EE 7 through a number of examples, using a hands on approach, including working code demonstrations.  The examples are presented in a Problem, Solution, and How it Works recipe-style format, correlating usage of the APIs to real-life scenarios.  The presentation introduces topics using an easy-to-understand approach, and the examples showcase new features of Java EE 7, as well as mature Java EE features.  Recipes cover a variety of APIs from JSF to JPA to WebSockets, providing an overview of Java EE 7, along with examples using APIs together.  The talk explains server-side resources using GlassFish 4.
Attendees will walk away with a solid understanding of some of the most important features of Java EE 7.


Session ID: CON2258
Session Title: Java EE 7 Recipes for Concurrency
Abstract:
This session will demonstrate how to make use of the Concurrency Utilities for Java EE using a hands on approach, including working code demonstrations.  The examples will be presented in a Problem, Solution, and How it Works recipe-style format, which will correlate usage of the API to real-life scenarios.  Attendees will learn how to make use of ManagedExecutorService, ManagedScheduledExecutorService, ContextService, and ManagedThreadFactory resources via practical examples.  The talk will explain server-side resources and configuration via GlassFish, submitting tasks for asynchronous processing, and handling results.  In the end, attendees will be able to go back to the office and start making use of the Concurrency Utilities.

I want to thank all of the JavaOne content reviewers for their hard work, and I appreciate the opportunity to present!  I've seen lots of Twitter posts mentioning excellent sessions that have been selected from very prominent speakers.  I am grateful to be included as a presenter at one of the best Java conferences in the world, and I am looking forward to seeing all of the great presentations from others.  

See you in San Francisco this September!

Thursday, May 22, 2014

Developing a Data Export Utility with PrimeFaces

My day job involves heavy use of data.  We use relational databases to store everything, because we rely on enterprise level data management.  Sometimes it is useful to have the ability to extract the data into a simple format, such as a spreadsheet, so that we can manipulate it as-needed.  This post outlines the steps that I've taken to produce a effective and easy-to-use JSF-based data export utility using PrimeFaces 5.0.  The export utility produces a spreadsheet, including column headers.  The user has the ability to select which database fields to export, and in which order they should be exported.

We want to ensure that we have a clean user interface that is intuitive.  For that reason, I chose not to display any data on the screen.  Rather, the user interface contains a PrimeFaces PickList component that lists the different data fields to choose from, along with a button to produce the export.  Let's begin by setting up the database infrastructure to make this export utility possible.

For this post, I've enhanced the AcmePools application, which was developed via my article that was posted on OTN entitled PrimeFaces in the Enterprise.  The export utility allows one to export customer data into a spreadsheet.  The customer data is included in the sample database which is installed within Apache Derby by NetBeans, or you can use the SQL script for this post.  To follow along with the creation of this export utility, please download or create the AcmePools project within your environment.

There are two parts to the data export utility, the first part being a PrimeFaces PickList component for the user to select which fields to export, and the second being an export button which will extract the selected field contents into a spreadsheet.  The end result will resemble a user interface that looks like Figure 1.
Figure 1:  Data Export Utility


Developing the PickList Component

To begin, create the data infrastructure to support the PickList component.  This consists of a single database table to hold column names and labels for the entity data you wish to export, and optionally a database sequence to populate the primary key for that table.  In this case, the database table is named COLUMN_MODEL, and we populate the table with the entity field names that correspond to the database column names for the CUSTOMER database table.

-- Add support for data export
create table column_model(
id                  int primary key,
column_name         varchar(30),
column_label        varchar(150));
-- Optional sequence for primary key generation
create sequence column_model_s
start with 1
increment by 1;


-- Load with field (database column) names
insert into column_model values(
1,
'addressline1',
'Address Line 1');

insert into column_model values(
2,
'addressline2',
'Address Line 2');

insert into column_model values(
3,
'city',
'City');

insert into column_model values(
4,
'creditLimit',
'Credit Limit');

insert into column_model values(
5,
'customerId',
'Customer Id');

insert into column_model values(
6,
'discountCode',
'Discount Code');

insert into column_model values(
7,
'email',
'Email');

insert into column_model values(
8,
'fax',
'Fax');

insert into column_model values(
9,
'name',
'Name');

insert into column_model values(
10,
'phone',
'Phone');

insert into column_model values(
11,
'state',
'State');

insert into column_model values(
12,
'zip',
'Zip');


Next, create an entity class that can be used for accessing the column data from within the component.  If you use an IDE such as NetBeans, this can be done very easily via a wizard.  If using NetBeans, right click on the com.acme.acmepools.entity package, and select "New"-> "Entity Classes from Database", and then choose the data source for our sample database.  When the list of tables populates, select the COLUMN_MODEL table, as shown in Figure 2.  Lastly, choose "Next" and "Finish" to create the entity class.

Figure 2.  NetBeans IDE New Entity Classes from Database

Once completed, the entity class entitled ColumnModel should look as follows:

package com.acme.acmepools.entity;

import java.io.Serializable;
import java.math.BigDecimal;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author Juneau
 */
@Entity
@Table(name = "COLUMN_MODEL")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "ColumnModel.findAll", query = "SELECT c FROM ColumnModel c"),
    @NamedQuery(name = "ColumnModel.findById", query = "SELECT c FROM ColumnModel c WHERE c.id = :id"),
    @NamedQuery(name = "ColumnModel.findByColumnName", query = "SELECT c FROM ColumnModel c WHERE c.columnName = :columnName"),
    @NamedQuery(name = "ColumnModel.findByColumnLabel", query = "SELECT c FROM ColumnModel c WHERE c.columnLabel = :columnLabel")})
public class ColumnModel implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @NotNull
    @Column(name = "ID")
    private BigDecimal id;
    @Size(max = 30)
    @Column(name = "COLUMN_NAME")
    private String columnName;
    @Size(max = 150)
    @Column(name = "COLUMN_LABEL")
    private String columnLabel;

    public ColumnModel() {
    }

    public ColumnModel(BigDecimal id) {
        this.id = id;
    }

    public BigDecimal getId() {
        return id;
    }

    public void setId(BigDecimal id) {
        this.id = id;
    }

    public String getColumnName() {
        return columnName;
    }

    public void setColumnName(String columnName) {
        this.columnName = columnName;
    }

    public String getColumnLabel() {
        return columnLabel;
    }

    public void setColumnLabel(String columnLabel) {
        this.columnLabel = columnLabel;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof ColumnModel)) {
            return false;
        }
        ColumnModel other = (ColumnModel) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.acme.acmepools.entity.ColumnModel[ id=" + id + " ]";
    }
    
}


Next, create an EJB session bean for the newly generated entity class so that the component can query the column data.  You can use your IDE for this as well if you'd like.  If using NetBeans, right-click on the com.acme.acmepools.session package, and select "New"->"Session Beans for Entity Classes".  Once the dialog opens, select the entity class "com.acme.acmepools.entity.ColumnModel" from the left-hand list, and click "Finish" (Figure 3).

Figure 3:  NetBeans IDE Session Beans for Entity Classes Dialog

After the session bean has been created, add a method named findId(), which can be used for returning the column id value based upon a specified column name.  The full sources for the ColumnModelFacade should look as follows:
package com.acme.acmepools.session;

import com.acme.acmepools.entity.ColumnModel;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Juneau
 */
@Stateless
public class ColumnModelFacade extends AbstractFacade {
    @PersistenceContext(unitName = "com.acme_AcmePools_war_AcmePools-1.0-SNAPSHOTPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public ColumnModelFacade() {
        super(ColumnModel.class);
    }

    public ColumnModel findId(String columnName){
        return (ColumnModel) em.createQuery("select object(o) from ColumnModel as o " +
                              "where o.columnName = :columnName")
                              .setParameter("columnName", columnName)
                              .getSingleResult();
    }
    
}
Next, create a some helper classes that will be utilized for loading and managing the data within the PickList component. The first class is named ColumnBean, and it is used to store the entity data, which is later passed off to the PickList for use. The code for ColumnBean is a simple POJO:<
package com.acme.acmepools.bean;

import java.math.BigDecimal;

/**
 *
 * @author juneau
 */
public class ColumnBean {

    private BigDecimal id;
    private String columnName;
    private String columnLabel;

    public ColumnBean(BigDecimal id, String columnName, String columnLabel){
        this.id = id;
        this.columnName = columnName;
        this.columnLabel = columnLabel;
    }

    /**
     * @return the id
     */
    public BigDecimal getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(BigDecimal id) {
        this.id = id;
    }

    /**
     * @return the columnName
     */
    public String getColumnName() {
        return columnName;
    }

    /**
     * @param columnName the columnName to set
     */
    public void setColumnName(String columnName) {
        this.columnName = columnName;
    }

    /**
     * @return the columnLabel
     */
    public String getColumnLabel() {
        return columnLabel;
    }

    /**
     * @param columnLabel the columnLabel to set
     */
    public void setColumnLabel(String columnLabel) {
        this.columnLabel = columnLabel;
    }

}
The PickList component needs to use a PrimeFaces DualListModel for accessing and updating the data. Therefore, we must implement a class that can be used for coercing the entity data into our ColumnBean POJO, and then storing it into the DualListModel so that it can be utilized by the PickList component. In the following class, entitled PickListBean, the constructor accepts a List<ColumnModel>, which is the entity data as an argument, performs the coercion, and then stores it into a DualListModel<ColumnBean> collection for use by the component.
package com.acme.acmepools.bean;

/**
 *
 * @author juneau
 */

import java.util.ArrayList;
import java.util.List;
import com.acme.acmepools.entity.ColumnModel;

import org.primefaces.model.DualListModel;

public class PickListBean {

    private DualListModel<ColumnBean> columns;

    private List<ColumnBean> source = null;
    private List<ColumnBean> target = null;


    public PickListBean(List<ColumnModel> columnModelList) {
        //Columns  
        source = new ArrayList<ColumnBean>();
        target = new ArrayList<ColumnBean>();
   
        for(ColumnModel column:columnModelList){
            ColumnBean bean = new ColumnBean(column.getId(), column.getColumnName(), column.getColumnLabel());
            source.add(bean);
        }
        

        columns = new DualListModel<ColumnBean>(source, target);

    }

    public DualListModel<ColumnBean> getColumns() {
        return columns;
    }

    public void setColumns(DualListModel<ColumnBean> columns) {
        this.columns = columns;
    }

   
}


Lastly, we need to create a controller class to access all of this data. To do so, create a class named ColumnModelController within the com.acme.acmepools.jsf package, and make it a CDI managed bean by annotating it with @Named and @SessionScoped. Make the class implement Serializable. The initial controller class should look as follows (we will be updating it later to include methods to facilitate the export):
@Named
@SessionScoped
public class ColumnModelController implements Serializable {

    @EJB
    ColumnModelFacade ejbFacade;

    private PickListBean pickListBean;
    private List<ColumnModel> columns;

    public DualListModel<ColumnBean> getColumns() {
        pickListBean = new PickListBean(ejbFacade.findAll());

        return pickListBean.getColumns();
    }
    
    public void setColumns(DualListModel<ColumnBean> columns) {
        pickListBean.setColumns(columns);
    }
}
As you can see, the getColumns() method queries the ColumnModel entity, which populates the DualListModel<ColumnBean> via the PickListBean constructor.

That takes care of the database infrastructure and business logic...now let's look at the PrimeFaces component that is used for the PickList.  The following excerpt, taken from the WebPages/poolCustomer/CustomerExport.xhtml view, contains the markup for the PickList component:

 <p:panel header="Choose Columns for Export">
                    <p:picklist effect="bounce" itemlabel="#{column.columnLabel}" itemvalue="#{column.columnName}" showsourcecontrols="true" showtargetcontrols="true" value="#{columnModelController.columns}" var="column">
                        <f:facet name="sourceCaption">Columns</f:facet>
                        <f:facet name="targetCaption">Selected</f:facet>
                    </p:picklist>
             </p:panel>

As you can see, the PickList is using columnModelController.columns for the data, which then uses the columnLabel field for displaying the names of the entity fields for export.  The titles for the source and target PickList windows are customizable via a facet.

Adding the Export Functionality

Now that we've developed a functional pick list, we need to do something with the data that is selected.  In this exercise, we will use a PrimeFaces DataExporter component to extract the data and store it into an Excel spreadsheet.  In reality, we need to incorporate a DataTable into the view to display the data first, and then we can use the DataExporter component to export the data which resides in the table.

To construct the DataTable that will be used for displaying the data, we need to add a few methods to the ColumnModelController class.  These methods will allow us to process the DataTable dynamically, so that we can construct columns based upon those that are chosen within the PickList.  In reality, the DataTable will query all of the Customer data, and then it will only display those columns of data that are selected within the PickList.  (We could modify this query by adding a filter, but that is beyond the scope of this post).  To load the table with data, we simply call upon the com.acme.acmepools.jsf.CustomerController getItems() method to return all of the data.

...
    public List<Customer> getItems() {
        if (items == null) {
            items = getFacade().findAll();
        }
        return items;
    }
...

Now let's add the necessary methods to the ColumnModelController so that we can dynamically construct the table.  First, add a method that will be invoked when we click the "Export" button.  This method will be responsible for building the currently selected column list:
public void preProcess(Object document) {

        System.out.println("starting preprocess");

        updateColumns();

    }

Next, let's take a look at the code for updateColumns(), which is invoked by the preProcess() method:
/**

     * Called as preprocessor to export (after clicking Excel icon) to capture

     * the table component and call upon createDynamicColumns()

     */

    public void updateColumns() {

        //reset table state

        UIComponent table = FacesContext.getCurrentInstance().getViewRoot().findComponent(":customerExportForm:customerTable");

        table.setValueExpression("sortBy", null);



        //update columns

        createDynamicColumns();

    }

The updateColumns() method binds a UIComponent to the table within the JSF view.  It then has the capability of providing sorting, if elected.  Subsequently, lets now look at the createDynamicColumns() method that is called upon.
    private void createDynamicColumns() {

        String[] columnKeys = this.getIncludedColumnsByName().split(",");

        columns = new ArrayList<>();

        for (String columnKey : columnKeys) {

            String key = columnKey.trim();

            columns.add(new ColumnModel(getColumnLabel(key), key));



        }

    }

The createDynamicColumns() method does a few things.  First, it captures all of the selected columns from the PickList, and stores them into a String[] named columnKeys.  To do this we use the helper method named getIncludedColumnsByName(), and split the results by comma.  The sources for this method are as follows, and it basically grabs the currently selected columns from the PickListBean and appends each of them to a String, which is then returned to the caller.
    public String getIncludedColumnsByName() {

        String tempIncludedColString = null;



        System.out.println("Number of included columns:" + pickListBean.getColumns().getTarget().size());

        List localSource = pickListBean.getColumns().getTarget();

        for (int x = 0; x <= localSource.size() - 1; x++) {

            String tempModel = (String) localSource.get(x);

            if (tempIncludedColString == null) {

                tempIncludedColString = tempModel;

            } else {

                tempIncludedColString = tempIncludedColString + "," + tempModel;

            }

        }



        return tempIncludedColString;

    }

Next, the createDynamicColumns() method then uses a loop to parse through each of the selected columns within the String[], and add them to the columnList, which going to be used to construct the DataTable with the appropriate columns.

Now let's take a look at the markup that is used to construct the DataExport utility:
<p:datatable id="customerTable" rendered="false" value="#{customerController.items}" var="item" widgetvar="customerTable">                    
                    <p:columns columnindexvar="colIndex" value="#{columnModelController.dynamicColumns}" var="column">
                        <f:facet name="header">
                            <h:outputtext value="#{column.header}">
                        </h:outputtext></f:facet>
                        <h:outputtext value="#{item[column.property]}">
                    </h:outputtext></p:columns>
                </p:datatable>
                

<hr />
<h:outputtext value="Type of file to export: ">
                <h:commandlink>

                    <p:graphicimage value="/faces/resources/images/excel.png">
                    <p:dataexporter filename="customers" id="propertyXlsExport" preprocessor="#{columnModelController.preProcess}" target="customerTable" type="xls">
                </p:dataexporter></p:graphicimage></h:commandlink>
</h:outputtext>
As you can see, the DataTable is set to not render, because we really do not wish to display it. Instead, we wish to export its contents using the DataExporter component. To construct the DataTable dynamically, the columns call upon the columnModelController.dynamicColumns method to return the dynamic column list. This method looks as follows:

    public List<ColumnModel> getDynamicColumns() {
        return columns;
    }
Within the DataExporter utility component, the columnModelController.preProcess method is assigned to the preprocessor attribute to initiate the dynamic column list. The target is set to the customerTable widget, which is the DataTable that we've dynamically constructed based upon the selected columns. In order to export this to an xls spreadsheet, you must add the org.apache.poi dependency within the Maven POM for the project, as follows:

<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.7</version>
        </dependency>

That's it...now you should have a fully functional data export utility using PrimeFaces components.  The complete sources are available on GitHub using the link below.  This code has been written in NetBeans IDE 8.0, and deployed to GlassFish 4.0.  I utilized PrimeFaces 5.0 for this project.

GitHub Sources:  https://github.com/juneau001/AcmePools

Thursday, May 01, 2014

PrimeFaces 5.0 DataTable Column Toggler

I have had an opportunity to work a bit with the PrimeFaces 5.0 DataTable, and the enhancements are great.  Today, I wanted to show just one of the new features...the DataTable column toggler.  This feature enables one to choose which columns are displayed via a list of checkboxes.

To use a column toggler, simply add a commandButton to display picklist of column choices into the header of the table, as follows:
<p:commandButton icon="ui-icon-calculator" 
   id="toggler" style="float: right;" type="button" value="Columns"/>

Next, add a columnToggler component to the table header, and specify the DataTable ID as the data source. In this case, the DataTable ID is "datalist":
<p:columnToggler datasource="datalist" trigger="toggler"/>

That's it! In the end, a button is added to the header of the table, which allows the user to specify which columns are displayed (Figure 1).

Figure 1:  Column Toggler in Action
The full source listing for the DataTable in this example is as follows:
<p:dataTable id="datalist" paginator="true" rowkey="#{item.id}"
     rows="10" rowsperpagetemplate="10,20,30,40,50" 
     selection="#{poolController.selected}" selectionmode="single"
     value="#{poolController.items}" var="item" widgetvar="poolTable">

    <p:ajax event="rowSelect"
      update="createButton viewButton editButton deleteButton"/>

    <p:ajax event="rowUnselect"
      update="createButton viewButton editButton deleteButton"/>

    <f:facet name="header">
       <p:commandButton icon="ui-icon-calculator" id="toggler"
           style="float: right;" type="button" value="Columns"/>
       <p:columnToggler datasource="datalist" trigger="toggler"/>
       <div style="clear:both" />
    </f:facet>
    <p:column>
        <f:facet name="header">
            <h:outputText value="#{bundle.ListPoolTitle_id}"/>
        </f:facet>
        <h:outputText value="#{item.id}"/>
    </p:column>
    <p:column>
        <f:facet name="header">
            <h:outputText value="#{bundle.ListPoolTitle_style}"/>
        </f:facet>
        <h:outputText value="#{item.style}"/>
    </p:column>
    <p:column>
        <f:facet name="header">
            <h:outputText value="#{bundle.ListPoolTitle_shape}"/>
        </f:facet>
        <h:outputText value="#{item.shape}"/>
    </p:column>
    <p:column>
        <f:facet name="header">
            <h:outputText value="#{bundle.ListPoolTitle_length}"/>
        </f:facet>
        <h:outputText value="#{item.length}"/>
    </p:column>
    <p:column>
        <f:facet name="header">
            <h:outputText value="#{bundle.ListPoolTitle_width}"/>
        </f:facet>
        <h:outputText value="#{item.width}"/>
    </p:column>
    <p:column>
        <f:facet name="header">
            <h:outputText value="#{bundle.ListPoolTitle_radius}"/>
        </f:facet>
        <h:outputText value="#{item.radius}"/>
    </p:column>
    <p:column>
        <f:facet name="header">
            <h:outputText value="#{bundle.ListPoolTitle_gallons}"/>
        </f:facet>
        <h:outputText value="#{item.gallons}"/>
    </p:column>
    <f:facet name="footer">
        <p:commandButton id="createButton" icon="ui-icon-plus"
            value="#{bundle.Create}"
            actionListener="#{poolController.prepareCreate}"
            update=":PoolCreateForm"
            oncomplete="PF('PoolCreateDialog').show()"/>
        <p:commandButton id="viewButton"   icon="ui-icon-search"
            value="#{bundle.View}" update=":PoolViewForm"
            oncomplete="PF('PoolViewDialog').show()"
            disabled="#{empty poolController.selected}"/>
        <p:commandButton id="editButton"   icon="ui-icon-pencil" 
            value="#{bundle.Edit}" update=":PoolEditForm"
            oncomplete="PF('PoolEditDialog').show()"
            disabled="#{empty poolController.selected}"/>
        <p:commandButton id="deleteButton" icon="ui-icon-trash" 
            value="#{bundle.Delete}"
            actionListener="#{poolController.destroy}"
            update=":growl,datalist"
            disabled="#{empty poolController.selected}"/>
    </f:facet>
</p:dataTable>
Happy coding with PrimeFaces 5.0!  This example was generated using PrimeFaces 5.0 RC 2.  The final release should be out soon!

Wednesday, April 23, 2014

Testing PrimeFaces 5.0RC1 with a Maven-Based Web Project in NetBeans 8.0 IDE

The new PrimeFaces 5.0RC1 has been released!  Now it is time to begin testing the new release with your existing applications.  If you are using a Maven-based web project within NetBeans, it is easy to configure your PrimeFaces 4.x application to test using the new release candidate.  Here's what you need to do:

1)  Ensure that the project is not configured to make use of the "PrimeFaces" framework within the Properties -> Frameworks configuration.  If "PrimeFaces" is selected within the "Components" tab, be sure to de-select it.  You may be unable to deploy the application successfully if you forget this step!



2)  Add a new maven dependency for PrimeFaces 5.0RC1 to your POM.

        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>5.0.RC1</version>
        </dependency>

** You may need to add the PrimeFaces repository to your POM

        <repository>
            <url>http://repository.primefaces.org/</url>
            <id>PrimeFaces-maven-lib</id>
            <layout>default</layout>
            <name>Repository for library PrimeFaces-maven-lib</name>
        </repository>

You should now be able to successfully build and run your project under PrimeFaces 5.0RC1.  This configuration is not difficult, but be sure that you do not get stumped by forgetting to follow Step 1 above, as you will be unable to deploy your application if you do.

To go back to using PrimeFaces 4.x for production use, simply follow these steps once again, but this time make sure you add the PrimeFaces 4.0 dependency within the POM.

        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>4.0</version>
        </dependency>

Monday, March 31, 2014

Resource Library Contracts with NetBeans 8 and PrimeFaces


It is critical to organize an application in such a way that it is easy for users to navigate and perform their work.  PrimeFaces includes a layout component that makes it easy to select the most fitting layout for your application.  Assuming that the layout should be utilized across all application views, a Facelets template should be created, and the PrimeFaces layout should be configured within the template.  

To create the template within NetBeans 8.0, add a resource library contract to the application.  To do so, right-click on the “Web Pages” application directory and then choosing “New”->”Other…”, and select “JavaServer Faces” from the category menu, and finally choose “JSF Resource Library Contract” as the file type (Figure 1). 




Figure 1:  Adding Resource Library Contract within NetBeans

On the “New JSF Resource Library Contract” dialog, enter a contract name and click on the “Create Initial Template” checkbox (Figure 2).


Figure 2: New JSF Resource Library Contract

PrimeFaces offers a number of layouts to develop a user-friendly interface.  To use the layouts, declare the PrimeFaces namespace within the template, and then specify the PrimeFaces Layout component as the first element within the body of the template.  The layout component creates a complex borderLayout model, enabling the development of sophisticated user interfaces.  To add the layout component, use the <p:layout> tag, and specify attributes to customize the layout such as style along with a number of client side callback attributes.  In this post, the fullPage="true" attribute is specified to ensure that the layout spans the entire page.

A series of layout units can be specified within the layout component, and these units are used to arrange the layout in a particular order.  There are 5 different layout units:  top, left, right, top, and bottom. Each layout unit is specified with a <p:layoutUnit> element, and the position attribute indicates where the unit should be placed within the layout.  Add <ui:insert> tags into each of the <p:layout> sections as shown in Listing 1.  The code in Listing 1 specifies a full-page layout for an application.

Listing 1:  PrimeFaces Template Layout

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:p="http://primefaces.org/ui">

    <h:head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <h:outputStylesheet name="./css/default.css"/>
        <h:outputStylesheet name="./css/cssLayout.css"/>
        <ui:insert name="title">Acme Pools</ui:insert>
    </h:head>

    <h:body>

        <p:layout fullPage="true"> 

            <p:layoutUnit position="north" size="150" header="Acme Pools" resizable="false" closable="false" collapsible="false"> 
              <ui:insert name="top"></ui:insert>
            </p:layoutUnit> 

            <p:layoutUnit position="south" size="70" style="background-color: #dddddd" resizable="false" closable="false" collapsible="false"> 
                Copyright 2014
                <br/>
                Author: J. Juneau
            </p:layoutUnit> 

            <p:layoutUnit position="west" size="200" header="Navigation" resizable="false" closable="false" collapsible="true"> 
                <ui:insert name="left"/> 
            </p:layoutUnit> 

     

            <p:layoutUnit position="center"> 
                <ui:insert name="content">Content</ui:insert>
            </p:layoutUnit> 

        </p:layout> 

    </h:body>

</html>
After applying the template to the index view, it will resemble the layout shown in Figure 3.


Figure 3:  PrimeFaces Page Layout

The layout in the example utilizes custom animation to hide the navigation pane, and PrimeFaces provides this functionality without any additional configuration.  As you can see, PrimeFaces and NetBeans 8.0 make it easy to generate a sophisticated user layout.


Friday, March 21, 2014

GlassFish 4 - Let's Help as a Community

We know that GlassFish 4 works with JDK8, but it has not yet been officially sanctioned.  Let's help out as a community and test out GlassFish 4 using the latest nightly builds, and submit any issues that arise.  The more feedback that is provided, the more solid the next release of GlassFish will be!

Here's what you can do to help:

1)  Grab a recent nightly build of GlassFish 4 from here: http://dlc.sun.com.edgesuite.net/glassfish/4.0.1/nightly/

2)  Install the build, and configure it to use your installation of Java SE 8 by doing the following:

  Set the AS_JAVA property within your 
  <glassfish-path>\glassfish\config\asenv.conf configuration file equal to your Java 8 installation. 

  On OS X, this would look like the following:

AS_JAVA="/Library/Java/JavaVirtualMachines/jdk1.8.0.jdk/Contents/Home"

3)  Test your Java EE applications under GlassFish 4 using Java 8, and submit any reproducible issues to the Issue Tracker:  https://java.net/jira/browse/GLASSFISH

  - Please include the steps to reproduce the issue(s) when submitting them to the tracker.  The more information, the better!

If we do our part as a community, we can help GlassFish to become more stable on Java 8, and then we should see a stable 4.x release sanctioned for use with Java 8 sometime in the future.

HelloType helloLambda = 
          (String text) -> {System.out.println("Hello " + text);};

helloLambda.hello("GlassFish 4 on JDK 8");


Sunday, March 16, 2014

Running GlassFish 4 on Java 8: Experiment with Java 8 Functionality in Java EE 7 Applications

Do you want to use the features of Java 8 with your Java EE 7 application?  It is possible to run GlassFish 4.0 under JDK 8.  To explicitly define which JDK GlassFish 4.0 uses, set the AS_JAVA property within your <glassfish-path>\glassfish\config\asenv.conf configuration file equal to your JDK 8 installation.  On OS X, this would look like the following:

AS_JAVA="/Library/Java/JavaVirtualMachines/jdk1.8.0.jdk/Contents/Home"

Once you've set this property and then start the GlassFish 4.0 server, it should be running under JDK 8, allowing any of the applications to utilize new Java 8 features, such as streams or lambdas.



Note:  This is for experimental use only, as Java EE 7 has not been sanctioned for use with Java 8 at the time of this post.  


I have successfully configured GlassFish 4.0 to run under Java 8 in my environment, and tested the use of streams within a Java EE 7 application without issue.  Here are some sources demonstrating basic use of streams within a CDI bean:

@Named
@SessionScoped
public class PoolController implements Serializable {
    List pools = new ArrayList();
    
    public PoolController(){
        pools.add("Pool One");
        pools.add("Pool Two");
        pools.add("Pool Three");
    }
    
    public String getPool(){
        System.out.println("The number of pools " + pools.stream().count());
        return  pools.stream().findFirst().toString();
    }

}

Friday, March 14, 2014

JavaOne 2014 Call for Proposals

The JavaOne 2014 CFP is available.  If you have an idea for a presentation that you think others will enjoy, please put in a proposal to speak at this year's JavaOne.  JavaOne is one of the world's most highly attended gatherings of Java experts.  It is the place to be if you are interested in collaborating with other Java experts...this is your chance to share your expertise!

http://www.oracle.com/javaone/call-for-papers/index.html

Thursday, December 12, 2013

Five Favorite NetBeans Features

Geertjan Wielenga invited to me to share five of my favorite NetBeans features with Oracle.  Here is the article that I wrote on those features.  When using a great IDE like NetBeans, it is hard to choose just five great features.  I've been using NetBeans quite a few years now, and it just continues to get better with each release.  If you are a developer and have not yet tried NetBeans, I suggest that you give it a try...I think you'll be pleased.

http://netbeans.dzone.com/articles/5-favorite-netbeans-features-joshjuneau

Tuesday, September 24, 2013

JavaOne 2013 - Starting Off Strong

The past two days have been packed with great sessions, and I believe that this year's JavaOne is going very well so far.  After my initial visit to the Schedule Builder, I knew this conference was going to be good.  I found it nearly impossible to choose which sessions to add to my schedule, and which ones to pass up.  There are so many good sessions to choose from, that I am hard pressed to find a time slot that does not contain at least one session that peaks my interest.  

Each of the sessions that I have attended thus far have been packed with excellent information.  It is clear that JDK 8 is a very hot topic this year.  With many sessions covering new features, such as lambda and Nashorn, JDK 8 is everywhere.  Java EE 7 is also a hot topic at this year's conference.  Sessions covering features such as JSF 2.2, JAX-RS 2.0, JMS 2.0, WebSockets, and more...the benefits of using Java EE 7 are clearly being advertised.  Perhaps some of the most widely discussed buzz around EE 7 is the HTML 5 integration.  It is also nice to see some great PrimeFaces coverage at this year's JavaOne.

NetBeans is also getting a lot of coverage this year.  I have attended sessions covering EE 7 tips and tricks with NetBeans, Project Easel, and several sessions on Java EE that demonstrated how powerful the NetBeans and GlassFish combination can be.  I enjoyed the demos of NetBeans and Project Easel being used to develop apps that scale nicely on mobile devices...complete with live debugging on an iOS device.

JavaFX is looking excellent, and the FX team is doing a great job of showing off it's power.  There are many sessions on JavaFX 8, and some great coverage of FX on Raspberry Pi.  HTML5, CSS, MultiTouch...there are countless sessions demonstrating the use of JavaFX with various technologies.

Overall, the most important part of the conference is the community.  The community is stronger than ever this year.  I've met up with so many great faces in Java over the past couple of days.  The Taylor Street cafe is a great place to meet up, and the GlassFish party at the Thirsty Bear was excellent...thanks to the GlassFish team!  The Exhibition Hall and OTN Lounge are always packed...lots of great demos and discussions.

I have the next three days packed solid of excellent Java content...looking forward to many more great sessions!  Java and the community are strong, and it is a great time to be a Java developer.

Keep up with the latest by visiting OTN at oracle.com/technetwork/java


Friday, June 07, 2013

Java EE 7 Books: Java EE 7 Recipes & Introducing Java EE 7

I have been working hard for over a year now on my most recent publication entitled 'Java EE 7 Recipes: A Problem-Solution Approach', published by Apress (May 2013).  This book covers the Java EE stack from the ground-up, and it includes coverage of EE 7 specific features, such as JSF view actions, WebSocket API, and Concurrency Utilities for Java EE.  Therefore, I feel that the book will be a good read for beginner, intermediate, and advanced Java Enterprise developers.

The first chapter begins by walking readers through recipes regarding the setup of a Java Enterprise environment, including specifics on how to install and configure Glassfish v4, a fully Java EE 7 compliant application server.  It then quickly delves into the development of Java Servlets, including coverage of newer concepts such as registering servlets without WEB-XML, and non-blocking I/O.  

Chapter 2 covers JSP from the ground-up.  Although JSP is no longer the preferred option for enterprise application development, it is still a very viable and widely used technology.  Therefore, this chapter will be handy especially for beginner and intermediate level developers so that they can have a better understanding of how JSP technology works, and where it may be the most useful.

Next, the book delves into JavaServer Faces technology, with in-depth coverage that spans four chapters (Chapter 3 - Chapter 6).  Keeping with the theme of the book, readers will learn how to develop applications with JSF, including useful tips and techniques, as well as integration with third-party libraries such as PrimeFaces.  The JSF 2.2 release (which is new with the release of EE 7), includes useful features such as the ability to invoke managed bean actions on life-cycle phase events (viewActions), and better integration with HTML5.  This book will show seasoned JSF developers how to use these new features so that they can begin integrating them into new and existing applications.

No enterprise application would be complete without database access, and Chapters 7 and 8 provide coverage for JDBC and Object-Relational Mapping via the Java Persistence API (JPA).  Chapter 7 provides coverage for utilization of JDBC technology for database access.  The chapter covers everything from obtaining a connection, to handing errors, simplifying connection management, performing CRUD operations, and execution of database stored procedures.  For those developers more interested in utilizing server-side database connection pools, etc., Chapter 8 covers the Java Persistence API.  The chapter contains vital information for working with underlying data stores via JPA including data mapping and entity creation.  It also hits upon EE 7 specific updates, including schema generation support.

Chapter 9 covers EJB technology, along with its new features via the release of EJB 3.2.  Readers will learn how to utilize EntityManagers, differences between Stateless and Stateful Session beans, how to utilize EJB via JSF, and more.  The new features covered include asynchronous message-driven beans (MDB), explicit designation of remote and local interfaces, and opting out of stateful session bean passivation.  In Chapter 10, readers will learn how to query entities using the most up-to-date features in JPQL.   

If you want to work with Java EE 7, you will most likely utilize GlassFish 4 application server since it is the first EE 7 compliant server.  Chapter 11 includes content on how to get up-and running with GlassFish v4, utilizing the administration console for application and datasource management, and setting up authentication.

One of the most popular features of Java EE beginning with the release of EE 6 has been Contexts and Dependency Injection.  Chapter 12 covers CDI in full detail, including recipes on injection, using CDI beans via JSF views, and more.  It also covers new features such as the injection of bean metadata and the new @Veto annotation for marking classes as ignored by CDI.

Have you heard about the simplification of Java Message Service (JMS) in the new 2.0 release?  Readers will learn all about the new simplified JMS API in Chapter 13, along with other JMS basics such as creation of resources, creating/sending messages, and the new message delivery delay.

Chapter 14 is a bit of an extension on Chapter 11, as it covers authentication and security for Java Enterprise applications, specifically those deployed within a GlassFish container.  Almost every enterprise application requires a login form, and this chapter covers how to create one, and also how to utilize LDAP authentication for producing single-sign on solutions.

SOAP and RESTful web services have become significant technologies for the Java EE stack.  Chapter 15 covers web services, both SOAP and REST-based services using JAX-WS and JAX-RS.  Readers will learn how to create each type of web service, and utilize the new features of JAX-RS 2.0 such as the new client API.

Java is not the only language on the block any longer (or JVM, that is).  It is not uncommon to see different languages being utilized to create entire enterprise applications for the JVM, or even for integration with existing Java EE applications.  Chapter 16 includes a few short recipes showing how one may integrate Groovy or Jython into an EE application.

Since HTML5 and the new era of web applications is upon us, the new WebSockets and JSON-P APIs for EE 7 have become of major importance.  Chapter 17 covers these new APIs, demonstrating how to create and utilize WebSockets for full-duplex communication.  The chapter includes an example calling out to a WebSocket from JavaScript.  It also demonstrates how to utilize the new JSON-P API for creating and parsing JSON.

Chapter 18 covers the use of JavaFX for creation of enterprise applications.  It demonstrates how to develop JavaFX front-end applications, and bind them to EJBs for use with data.  There is also a recipe covering the use of JavaFX with RESTful web services.

Finally, both the Concurrency Utilities for Java EE and Batch Applications APIs have been added to EE 7.  These APIs provide a standard for developing concurrent and batch applications for the enterprise. Coverage includes the creation of server-side resources (ManagedExecutorService, etc.) for concurrent application development, and creation of item-oriented batch processes.

Overall, the Java EE 7 Recipes book is perfect for those that are interested in getting up-to-speed with Java EE, including the latest features.  For those who are already experts with Java EE and are only interested in the new features, stay tuned for the release of my upcoming book entitled 'Introducing Java EE 7', to be published by Apress within the next few weeks.


Saturday, November 03, 2012

Java EE 7 by JSR

The following is a listing of JSRs that are contained in the Java EE 7 Specification.

Java EE Platform Specification - http://java.net/projects/javaee-spec/pages/Home 

JSR 107 - JCache https://github.com/jsr107/jsr107spec http://jcp.org/en/jsr/detail?id=107
JSR 236 - Community Utilities for EE http://jcp.org/en/jsr/detail?id=236
JSR 338 - JPA 2.1 http://jcp.org/en/jsr/detail?id=338
JSR 339 - JAX-RS 2.0 http://jcp.org/en/jsr/detail?id=339
JSR 340 - Servlet 3.1 http://jcp.org//en/jsr/detail?id=340
JSR 341 - EL http://jcp.org/en/jsr/detail?id=341
JSR 342 - EE 7 http://jcp.org/en/jsr/detail?id=342
JSR 343 - JMS http://jcp.org/en/jsr/detail?id=343
JSR 344 - JSF 2.2 http://www.jcp.org/en/jsr/detail?id=344
JSR 345 - EJB 3.2 http://jcp.org/en/jsr/detail?id=345
JSR 346 - CDI 1.1 http://jcp.org/aboutJava/communityprocess/pr/jsr346/index.html
JSR 349 - Bean Validation http://jcp.org/en/jsr/detail?id=349
JSR 352 - Batch Applications for the Java Platform http://jcp.org/en/jsr/detail?id=352
JSR 353 - Java API for JSON Processing http://jcp.org/en/jsr/detail?id=353
JSR 365 - WebSockets

Thursday, December 29, 2011

Java 7 Recipes: A Problem-Solution Approach

This is a quick post to mention a new book that will be published soon entitled Java 7 Recipes. I had the pleasure of leading a team of excellent authors: Carl Dea, Mark Beaty, Freddy Guime, and John O' Conner in the authoring of this book. It features a problem-solution approach demonstrating how to get up and running quickly with the Java language. The book features some of the most common questions for newbies starting to develop with Java, and provides answers in an easy-to-learn and reuse manner. It also features some of the most common intermediate and advanced problems and solutions, as well as material that is new to the Java 7 release.

Carl Dea wrote several chapters on JavaFX 2.0, and the material covers enough information to get started with JavaFX 2.0 and then delves into some advanced examples as well. If you are looking to learn the latest in Java desktop and rich internet client development, you will want to check out the chapters on JavaFX 2.0.

Mark Beaty wrote a chapter covering data structures and iteration. He is an expert in object oriented Java concepts, and this chapter covers some of the most fundamental parts of the Java language. Mark also was a technical reviewer for the book, and he did an excellent job of working through the material and solidifying it. I would also like to give a shout out to David Coffin who also performed technical review on several of the chapters...great work!

Freddy Guime is a Java expert who wrote chapters on input/output, exceptions, concurrency, unit testing, and more. Freddy has presented at JavaOne several times and his material exploits his knowledge of the Java language.

John O' Conner has been an avid Java developer for years, and is seasoned in the language. He began his career with Sun Microsystems and helped to develop the internationalization and Unicode support libraries of the core Java SE platform. He authored chapters on those topics for the book, and more.

I authored chapters varying from Strings, object orientation, numbers and dates, database development, and more. We even threw in a chapter on Android so that interested Java developers could take a look at how to develop applications for the Android platform.

Check this book out soon, or pre-order now on Amazon the Apress site. This is a must-have for any Java developer!

I am currently working on my latest Apress book entitled Java EE 7 Recipes...it should be published late next year...stay tuned for more updates on that book!

Friday, March 04, 2011

Django-Jython 1.3.0 Final Available

The Django-Jython project is proud to announce the release of Django-Jython 1.3.0 Final!

This release adds Django 1.3.x compatibility for the Oracle, MySQL, MS SQL, and PostgreSQL backends. Please test with your Django-Jython apps and provide feedback.

Project Home: http://code.google.com/p/django-jython/
Documentation: http://packages.python.org/django-jython/

Thanks to all of those who helped out with this release, your time and effort is truly appreciated!

Support for Django 1.4 is coming soon...

Thursday, March 03, 2011

Jython 2.5.2 Final Released

The Jython development team is proud to announce the release of Jython 2.5.2 final! With this release comes new features, better performance, bug fixes, etc.

For the latest release info, please visit: http://jython.org/latest.html

Thanks to all of the developers for the hard work they put into this release. Looking forward to moving onto 2.6!

Tuesday, December 21, 2010

Oracle PL/SQL Recipes

Since the beginning of my career, I have worked with Oracle databases. I began as a database administrator, monitoring performance and creating database objects. From there, I became a more advanced DBA as I began writing PL/SQL code and creating triggers, functions, packages, and procedures in the database. After a while, I became interested in web application development because I was always receiving requests for creating database reports. Why write a SQL statement and re-run it every time someone wanted to see the output, when you could write a web query that accepted parameters as input and the user could run it on their own? That is the point when I discovered how to do web application development with PL/SQL and the Oracle PL/SQL web toolkit. My good friend and colleague, Matt Arena, showed me the ropes about developing PL/SQL web applications, and it was great! Now I was able to develop web-based queries whenever I had received a request for a report.

After a while, I began to write Java stored procedures because I was developing some sophisticated PL/SQL web applications by that time and I wanted to use some features that the Java language had to offer. Of course, this all worked very well...but I soon gained interest in developing Java Server Pages (JSP) based web Java web applications because they seemed a bit more versatile then PL/SQL web applications. I learned that I could more clearly separate business logic from display code using Java technologies, and began to learn more about it. Before long, I was a full-fledged Java application developer. I was developing Java enterprise applications for Oracle database, and using PL/SQL objects to help facilitate my applications where it made sense.

That brings me to where I am today. I still develop web applications for Oracle database using Java technologies and PL/SQL. I have broadened my horizons by using great languages such as Jython. Life couldn't be much better. This past year, I decided to author a book about PL/SQL that focuses on the basics...but also goes into advanced topics such as working with PL/SQL and Java to develop advanced solutions. I brought my highly respected coworker, Matt Arena, into the book as my co-author. Matt is the most advanced PL/SQL developer that I know, and he wrote the chapters that focus on PL/SQL web application development, collections, PL/SQL jobs, and performance. He taught me, and now he is sharing his great knowledge by teaching others. I authored many chapters that focus on the PL/SQL language fundamentals, and also some advanced chapters working with PL/SQL and Java application development.

Our book is entitled, Oracle PL/SQL Recipes - A Problem-Solution Approach. I recommend you picking it up if you are an Oracle applications developer. Learning PL/SQL is a great asset to any Oracle developer's toolbox. Even if you only work with Java applications, PL/SQL can help you to develop better-performing, and highly robust Oracle solutions. A big thanks goes to Apress and the entire editorial team, including my good friend Jonathan Gennick, who has done an excellent job editing this book. I look forward to working with him again on future projects. I also thank my colleague and great friend Matt Arena for showing me the ropes with PL/SQL web application development...leading my to where I am today in my career.

Oracle PL/SQL Recipes - A Problem-Solution Approach...publishing late December 2010.