Friday, February 26, 2016

NetBeans Java EE Tip #3: RESTful Web Services from Database

Many modern web applications are moving towards the use of stateless communications using HTTP.  The REST (Representational State Transfer) architectural style is oftentimes utilized to design networked applications, and with Java EE 7 it is very easy to develop a RESTful backend for database communication.  Using a simple POJO (plain old Java object), one can provide a complete solution for stateless database communication by applying annotations to method signatures.

NetBeans allows developers to create RESTful solutions even more productively by providing tools such as the ability to generate RESTful Web Services from a database.  This allows a developer to select one or more database tables from which to generate RESTful web services without any coding at all.  Very similar to "Entity Classes from Database", this process takes it one step further and not only produces the required entity classes, but also a complete web service class for performing CRUD database operations in a RESTful manner.

To get started, right-click on your source package within NetBeans and choose "New"->"Web Services"->"RESTful Web Services from Database" (Figure 1).  This will open the "New RESTful Web Services from Database" dialog.
Figure 1:  Creating RESTful Web Services from Database

Figure 2:  New RESTful Web Services from Database Dialog

In this dialog, select the data source to which you would like to connect, and then choose one or more tables from the "Available Tables" list, and add to the list of "Selected Tables".  Choose "Next".  On the next dialog, you will have the ability to specify a package location, as well as which annotations to generate for your entity classes (Figure 3).

Figure 3:  Specify options for your entity classes

Next, you have the ability to specify the package location for your service classes.  The NetBeans wizard will also produce an ApplicationConfig class if one has not already been produced for your project, and place it into this resource package.  The ApplicationConfig is required to configure an access point for the RESTful web services in your application.

Figure 4:  Specify Resource Package Location

That's it...click "Finish" to generate the classes.  You will see that entity classes are generated for all of the database tables (and optionally those tables that are related).  In the elected resource package, web service classes are generated for each of the entity classes, and the ApplicationConfig class is also produced if it did not exist already (Figure 5).

Figure 5:  Classes Generated by Wizard

After following these procedures, you now have a completely usable web service for each of the database tables that you had selected.  These web service classes can be utilized to develop stateless applications that will communicate with your database.

Figure 6:  RESTful Web Service Class

Wednesday, February 17, 2016

NetBeans Java EE Tip #2: JPQL Syntax Checking

When using JPA (Java Persistence API), one of the most common ways to query entity classes is to utilize JPQL (Java Persistence Query Language).  Although JPQL makes it easy to query entity classes, it is not type safe JPQL queries are typed using a plain String.  This will certainly cause an issue if the JPQL query is typed incorrectly...for instance if the entity class or one of the field names is incorrectly spelled.  If such is the case, the application will deploy without issues, but there will be a nasty error when the query is executed.

NetBeans helps cut down on the number of JPQL errors by providing real-time checking of JPQL query syntax.  If a JPQL query is typed incorrectly, a yellow light bulb will appear in the left hand margin of the NetBeans source editor and the erroneous createQuery() call will be underlined yellow, indicating the incorrect syntax (Figure 1).

Figure 1:  NetBeans flags errors in JPQL query strings

Once the error is corrected, the yellow lightbulb and underline will disappear, as seen in Figure 2.

Figure 2:  Errors have been repaired

This is a helpful feature because it saves the developer heart ache that would occur if an erroneous JPQL query were deployed.


Wednesday, February 10, 2016

NetBeans Java EE Tip #1 - Entity Classes From Database

The NetBeans IDE is an excellent choice for developing applications of all kind.  Specifically, I use it on a daily basis for developing and maintaining Java EE applications.  Not only has Java EE become much more productive over the past few releases, but the NetBeans IDE has also reduced the time that it takes to develop an application...making Java EE and NetBeans an excellent match!

One of the features that I use the most is the ability to generate entity classes from the database.  NetBeans makes it easy to add an entity class to your project without any coding.

First, right-click on a project package, and choose "New->Entity Classes from Database" (Figure 1).

Figure 1:  New Entity Class from Database

Next, select a data source, and then choose at least one table from the "Available Tables" list, as shown in Figure 2.

Figure 2:  Choose Table from Available Tables list

Choose the Project, location, and package to which the entity class will be added.  Then specify any preferences to indicate if you'd like named queries, JAXB annotations, or MappedSuperClass instead of entities. (Figure 3)
Figure 3:  Specify Package name and preferences

Lastly, select mapping options for your entity class, as shown in Figure 4.

Figure 4:  Entity Class Mapping Options

Viola...you have an entity class that is ready to use...compliments of NetBeans IDE!


Figure 5:  Completed Entity Class

Monday, February 08, 2016

A Look at the Upcoming JSF 2.3 Push Support

As mentioned in previous posts, there are a number of enhancements being added to the next release of JavaServer Faces (Mojarra).  JSF 2.3 is slated to be released with Java EE 8 in 2017, but you can get your hands on some of the enhancements and updates to JSF for testing purposes now by building from source or running a milestone release.

One such enhancement to the API is the addition of one-way (server-to-client) websocket based push communication via the f:websocket tag and Push API.  The team at OmniFaces has developed the JSF solution based on the o:socket, which is part of the OmniFaces utility library.  Specifically, JSR 372 Expert Group members Bauke Scholtz and Arjan Tijms have contributed this and many other enhancements and fixes to the Mojarra codebase.  

The patch which enables f:websocket support has not yet been applied to the Mojarra 2.3 branch, but you can obtain the patch from issue JAVASERVERFACES_SPEC_PUBLIC-1396.  Prior to applying the patch to your local Mojarra clone, you should be sure to update your sources from the central 2.3 branch to ensure that you have the latest updates applied.  The usage is simple, very similar to the well documented o:socket feature on the OmniFaces site, perform the following steps to make use of f:websocket.

First, add the
javax.faces.ENABLE_WEBSOCKET_ENDPOINT 
context parameter to the web.xml of your application, and set the value to true.

<context-param>
    <param-name>javax.faces.ENABLE_WEBSOCKET_ENDPOINT</param-name>
    <param-value>true</param-value>
 </context-param>

Client-Side Code

On your client (JSF view), add the f:websocket tag, and specify the channel to which you wish to connect.  You must also specify an onmessage listener that will execute a specified JavaScript function once the message is received.  The optional attribute onclose can also be specified, allowing a specified JavaScript function to execute on close of connection.  In the following example, we specify that the socket will connect to a channel named "duke", along with an onmessage listener named dukeMessageListener:

<f:websocket channel="duke" onmessage="dukeMessageListener"/>

The onmessage listener can be invoked with three parameters (push message JSON object, channel name, message event).  If you simply wish to pass a message, it may look similar to the following:

function dukeMessageListener(message) {
        PF('broadcastGrowl').show(message);
}

If the optional onclose listener is specified, the corresponding function could accept three parameters (close reason code - integer , channel name, message event), but only the first is required.

In most cases, the intention is to blast out a message from the server to notify all client views having the same websocket channel specification.  There is an optional scope attribute on f:websocket that can be set to "session", and this will limit the messages to all client views with the same websocket channel in the current session only.

Lastly, the optional port attribute can be set to specify a TCP port number other than the HTTP port, if needed.

Server-side Code

Since we are planning to push a message from the server to all connected clients, let's take a look at the server side code.  The new PushContext can be injected into any CDI artifact by including an @Push annotation, and the name of the context can either correspond to the channel name, or an optional channel attribute can be specified on the @Push annotation to indicate the channel to which the message should be broadcast.

@Inject @Push
    private PushContext duke;
...
public void sendMessage(Object message){
    duke.send(message);
}

The message will be encoded as JSON and delivered to the message argument of the JavaScript function on the client that is specified for the onmessage attribute of f:websocket.  It is possible to send any type of container, be it a plain String, JavaBean, Map, Collection, etc., as the message.

Example Usage

Suppose that we have an administrative console for our web application, and we want to provide the administrators a means of alerting the clients of something.  The administrative console may have a text area for the message input, along with a commandButton to invoke the sending of the message, as such.

<h:inputText id="pushMessage" value="#{testBean.pushMessage}"/>
<h:commandButton action="#{testBean.sendAdminMessage}" value="Send Message"/>

The JSF controller class testBean would then have a method sendAdminMessage, which takes the message that is stored in the pushMessage String, and sends it to our sendMessage method.

@Inject @Push
    private PushContext duke;

...

public void sendAdminMessage(){
    sendMessage(pushMessage);
    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Message has been broadcasted"));
}

...

public void sendMessage(Object message){
    duke.send(message);
}

Any client that will receive the message should contain the f:websocket tag, pointing to the duke channel.  The client should also include minimally a JavaScript function to be invoked when the message is received.

<f:websocket channel="duke" onmessage="dukeMessageListener"/>

<p:growl id="messages"/>

function dukeMessageListener(message) {
        facesmessage.severity = 'info';
        PF('broadcastGrowl').show(message);
}

In this particular example, a PrimeFaces growl message component will be updated when the message is received.

JSF 2.3 is shaping up well thanks to all of the excellent contributions from the JSR 372 Expert Group members.