Friday, April 29, 2016

Java EE 8, What is the Current Status: Case Study for Completed Work Since Late 2015

For anyone who pays close attention to Java EE, it has become clear in the past six months that there has been a decline of activity...especially in those JSRs for which Oracle maintains the lead.  What's the deal?  There has been a lot of conversation in the Java EE community in this regard lately, and I think it is important that the developer community be given a fair timeline of what we can expect for the future of Java EE.  The uncertainty is becoming long in the tooth, and the community is becoming more concerned with the future of Java SE and Java EE as time goes on.

Let me give you a bit of background.  I'm an expert group member on a couple of JSRs targeted for Java EE 8, those being JSR 372 (JavaServer Faces 2.3), and JSR 378 (Portlet 3.0 Bridge for JavaServer Faces 2.2).  At the beginning of 2016, I had noticed that since October 2015 the number of emails on the Expert Group list for JSR 372 had really slowed down.   In fact, in the final quarter of 2015, the activity on JSR 372 had slowed down to a near halt, whereas it should be picking up momentum as time moves forward closer to the eventual final release.  In late January, I was contacted by a couple of members of the Java EE community, indicating that they also had seen a slowdown of activity and were very concerned.  I was then asked to join a community of concerned Java EE advocates on a Slack community...and when I joined and read the backlog of messages I could clearly see that it looked as though Oracle had stopped activity in just about every area of Java EE, specifically work on all of the JSRs that were Oracle-led.

I began to do some homework and started looking into the statistics a bit.  I wanted to see some clear evidence.  What I found is that in some JSRs, it was difficult to see a decline in activity on Oracle's part, but these JSRs, in particular, did not have a specification lead that was from Oracle.  Some JSRs, especially those not under Oracle's purview, are just overall more active than others.  On the converse, for those JSRs where Oracle does maintain the specification lead, the activity had almost come to a complete halt.  I'd like to share my findings for a couple JSRs, those being JSR 372: JavaServer Faces 2.3, and JSR 368: Java Message Service 2.1.

I gleaned the following information from the JSR 372 and JSR 368 public archives/records, including the JIRA (Mojarra JIRA and JMS JIRA), mailing list archives (JSR 372 EG Mailing ListJSR 378 EG Mailing List), and the GitHub repository (https://github.com/javaserverfaces/mojarra).

JSR 372 Statistics

First and foremost, I want to mention that the specification leads for JSR 372 are top notch, and they've done a spectacular job of leading the project.  That said, it seems that their activity has dropped off quite a bit since October 2015.  Here are some charts to display the data.

As I had mentioned previously, the JSR 372 specification leads have done a great job.  As such, they've still maintained a role in the email to the JSR 372 expert group mailing list.  That said, these numbers only reflect those through 03/2016...and there has not been much activity since.

If we take a look at the number of commits towards JSR 372 (captured from GitHub), we can see the there is a major decline in the work that has been done from Oracle.  Most of the work that has been done since October 2015 is from the community, mainly the most active JSF developers:  Arjan Tijms and Bauke Scholtz.

Another significant area of decline is in the number of issue resolutions from Oracle.  The following data was gleaned from Github, and the work from Oracle on JSR 372 since March 2016 is much the same.


The graphs above clearly indicate a decline in Oracle's involvement towards the eventual completion of JSR 372.  This is troubling because the work for JSR 372, as well as others encompassed in Java EE 8, is targeted for public release in less than a year (March 2017), and it seems as though that target is becoming more of a wishful goal now than an actual release date for Java EE 8.

JSR 368 Statistics

The statistics for JSR 368 show even more of a decline in activity from Oracle specification lead perspective.  Again, the spec lead has done a superb job leading the project until the changes seem to have been made in late October from the Oracle standpoint.

First, looking at the email, it is plain to see that there has been a drop off.  However, it seems that JMS 2.1 email has been slow for much of 2015.

 The number of commits for JMS 2.1 tell a different story, it looks as though there haven't been any commits done since late 2015.




As far as issue resolutions go, there has been little activity at all for the JMS 2.1 lifecycle.


That is all well and good, but comparing this data against the JMS 2.0 data is where there is a very clear indication that there is not as much effort going into the development of JMS for the 2.1 release.

The main purpose of this post is to alert the Java SE and Java EE communities that there has been a clear decline in the Oracle involvement towards Java EE 8.  I, like much of the rest of the community, am very concerned that the effort going into the Java EE 8 JSRs has declined at an alarming rate, seeming to indicate that this release is not ranking very high on the priority list.

That said, with the exception of the past year's activities, I think Oracle has done a fantastic job in the previous five or six years activating the Java SE and Java EE communities.  I have been proud to wear my GlassFish beanie and Oracle Java EE 7 t-shirts...letting everyone know how great it is to be a part of this community.  I enjoy speaking at conferences about the latest Java EE technologies, and writing posts to share the knowledge.

I think the rest of the community stands with me in saying that it would be good to have a clear statement from Oracle with regards to their intentions for the future of Java EE.  Not only would it help to clear the uncertainty that looms in the air, but it would also help the many customers and organizations that rely upon Java EE to have a clear understanding of what is to come.

I hope that we see activity pick up soon so that we can continue leading the way towards another significant Java EE release in the near future, maintaining the platform's edge when it comes to cutting edge technology.  Looking forward to hopefully seeing the Java SE and Java EE platforms continue to evolve long into the future!

Thursday, April 07, 2016

NetBeans Java EE Tip #7: Overlooked Java Class and XHTML Editor Shortcuts


Sometimes the most helpful features of an IDE are the most overlooked.  In this post, I will outline five NetBeans Java and XHTML editor shortcuts that can be used when developing Java EE applications.

#1 - Easily Fix Namespaces and Classes

Perhaps you have added a new JSF tag to a view for which the namespace has not yet been declared, or maybe you removed a tag that is no longer required, and the namespace is no longer needed.  NetBeans provides the SHIFT+CMD+I (OS X) and CTRL+SHIFT+I (PC) shortcuts to fix namespaces in the current file.  Much in the same manner, the same shortcut can be used in a Java class to fix all imports.  This shortcut enables easier management of namespaces in XHTML and imports in Java classes.

Figure 1:  Fix imports in Java Class


Figure 2:  Fix namespaces in XHTML



#2 - Autocompletion within XHTML and HTML

Sometimes it is easy to forget the name of that controller class when adding an EL expression to your XHTML view.  Other times we remember the name, but don't want to type out the entire path to the controller and method or property.  NetBeans provides auto-completion for Expression Language within XHTML files to remedy these issues.  Just start typing within an EL expression to see the auto-completion for all of the JSF controllers and/or properties/methods for the current project.


Figure 3:  Auto-completion in Expression Language

#3 - Quick Navigation to controller class or backing bean method

To quickly navigate to a JSF controller or property/method declaration that is referenced within an EL expression, simply hold down the CMD (OS x) or CTRL (PC) button and mouse click on the name.


#4 - Quickly Navigate to JavaScript

To quickly navigate to a referenced JavaScript function, hold down the CMD (OS x) or CTRL (PC) button and mouse click on the reference.
Figure 4: CTRL or CMD + click on function name

#5 - Navigate Directly to Stylesheet

To quickly navigate to a CSS Style, hold down the CMD (OS x) or CTRL (PC) button and mouse click on the "id" or "class" attribute of the element that is referencing the style, and a drop-down list of all matches will be displayed



Figure 5:  CTRL or CMD + click on "id", "class", or "styleClass" attribute
.

Saturday, March 19, 2016

NetBeans Java EE Tip #6: Create WebSocket Endpoint

The introduction of WebSocket support with the release of Java EE 7 provided a means for utilizing full duplex communication in your Java EE applications.  To utilize WebSockets, one must create an endpoint to which the client can connect for communication purposes.  NetBeans provides an easy-to-use wizard for developing WebSocket endpoints with a few clicks.

1)  Create your endpoint class.  First, select "New"->"Web"->"WebSocket Endpoint":
Figure 1.  Select WebSocket Endpoint

2)  Next, name your endpoint accordingly, provide a package into which the endpoint will be created, and also provide a WebSocket URI.  This is the URI that the client will connect to in order to send a message.


Figure 2.  WebSocket Endpoint Generation

3)  The NetBeans IDE will generate the initial WebSocket endpoint code.  All that is left to do is implementation of the onMessage() method to suit your application.



I will show you how to easily generate a client to communicate with a WebSocket endpoint using NetBeans in a future Java EE tip!

Friday, March 11, 2016

NetBeans Java EE Tip #5 - Custom Bean Validation Constraints

Bean Validation was added to the Java EE platform with the release of Java EE 6.  It brings a standard means of easily performing annotation-based validation to the platform.  There are several built-in bean validation constraints such as @NotNull, @Size, and @Pattern to name a few.  Please take a look at the Java EE documentation for a complete listing.

Sometimes there is a need to generate a custom bean validation constraint to suit the needs of an application.  In such cases, one must generate a custom validator class, as well as an annotation class for use with the validation class.  NetBeans makes it simple to do so, as it provides a wizard that produces skeleton classes that suit the specified criteria for your constraint.

To get started, right-click on the "Source Packages" node of your project or on an existing package, and choose "New"->"Bean Validation"->"Validation Constraint" (Figure 1).
Figure 1:  Select "Validation Constraint"

Next, choose a class name for the bean validation annotation class.  The name you elect to use will also be used for the annotation.  Provide a package name into which you wish to have the bean validation class created.  If you wish to have NetBeans automatically generate a validator class, then select the checkbox indicating as such.  If you elect to have the validator class generated, then provide a validator class name and a Java type to validate (Figure 2).

Figure 2:  Provide Class Name and Options

Once you click finish, the bean validation annotation class will be generated, as well as the validator class, if chosen.  You can then customize the class, as needed, to implement the validator.


Figure 3:  Generated Bean Validation Annotation Class

Figure 4:  Generated Validator Class with Custom Implementation

Once you've implemented the validator, it is ready to use.  As seen in Figure 5, simply annotate the field(s) that you wish to have validated.

Figure 5:  Utilizing the Custom Bean Validation Class



Recommended Reading on Bean Validation:

http://dataverse.org/files/dataverseorg/files/bean_validation.pdf?m=1448384482


Friday, March 04, 2016

NetBeans Java EE Tip #4 - RESTful Web Service JavaScript Client

In NetBeans Java EE Tip #3, I demonstrated how easy it is to create a RESTful web service using NetBeans.  In this tip, we will take a look at how quickly one can generate a JavaScript client for an existing RESTful web service.

To get started building the JavaScript client, right-click on the "Web Pages" folder of the NetBeans Web Application project, and choose "New"->"Web Services"->"RESTful JavaScript Client" (Figure 1).

Figure 1:  RESTful JavaScript Client

Next, provide a file name for the JavaScript file that will be generated for your client.  The wizard also allows you to choose a RESTful Web Service to utilize, and your choice of UI for the front end client site (Figures 2 and 3).

Figure 2:  Name JavaScript File & Choose Web Service

Figure 3:  Choosing Web Service

In Figure 4, you can see that I chose to use the Tablesorter UI for the front end. 

Figure 4:  Resulting UI Choice

Lastly, create the HTML page that will be utilized for your client.  Simply provide the name and optionally change the path to the file that will be generated.

Figure 4:  Name the HTML file

Once the wizard completes, your new HTML and JavaScript client will be ready to deploy and use!  

Figure 5:  HTML/JavaScript Client

The IDE will automatically reference the required JavaScript libraries to generate the client.  View the HTML sources, or click on the NetBeans project's "Remote Files" section to see which libraries are used.

Figure 6:  Remote Files in use by NetBeans Project

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.





Monday, December 28, 2015

Utilizing the JSF 2.3 f:convertDateTime Tag with the Java 8 Date-Time API

One of the features that is in-progress for the upcoming JSF 2.3 release is support for the Java 8 Date-Time API.  This support was added to the Mojarra 2.3.0 - Milestone 4 Snapshot before JavaOne 2015.  In this post, we'll take a brief look at this newly added support, which allows one to utilize the Java 8 Date-Time API with the standard JSF components via usage of the enhanced f:convertDateTime tag.  We will take a look at running an example application so that you can begin testing the features of JSF 2.3 today.

There are a number of posts covering the new f:convertDateTime functionality.  My fellow JSF 2.3 Expert Group member Arjan Tijms has an excellent post covering the new features of JSF 2.3:  http://arjan-tijms.omnifaces.org/p/jsf-23.html#1370  Anghel Leonard also has a repository with some great test sources:  https://github.com/AnghelLeonard/JSF-2.3/tree/master/JSF23convertDateTime.

In short, the f:convertDateTime tag now supports type attribute values that cover the Java 8 Date-Time data types.  Namely, you can now specify: both, date, time, localDate, localTime, localDateTime, offsetTime, offsetDateTime, and zonedDateTime.  You can then specify the pattern attribute on the tag to convert to the appropriate Date-Time format.

I have modified the sources for an application that I had written last year, AcmePools, such that it now supports the JSF 2.3 constructs when compiled and executed against Mojarra 2.3.0 - Milestone 4.  The updated sources have been posted to a new repository for JSF 2.3 testing purposes:  https://github.com/juneau001/AcmePools-JSF23. My post from 2014, Building and Testing JSF.next, has been updated to include details on utilizing the new Git repository for Mojarra.  It covers the basics of building Mojarra, and testing against the snapshot.  Please follow the directions in the post to get started.  Next, clone the new AcmePools sources that are compatible with JSF 2.3, and open the project in NetBeans, as shown in Figure 1.
Figure 1:  AcmePools-JSF23 in NetBeans

Once you've got the project open in NetBeans, you are ready to begin testing.  Take a look at the /job/List.xhtml view, and look at the "Job Date" column of the dataTable.  The h:outputText component has an f:convertDateTime tag applied to it, which will convert the date to the localDate type, as seen below.

<p:column>
         <f:facet name="header">
             <h:outputText value="Job Date"/>
         </f:facet>
         <h:outputText value="#{item.jobDate}">
              <f:convertDateTime type="localDate" pattern="MM/dd/yyyy"/>
         </h:outputText>
</p:column>


Taking a look at the jobDate field of the Jobs entity, you can see that it is of type LocalDate:

@Column(name = "JOB_DATE")
private LocalDate jobDate;

Similarly, if we look at the /job/Create.xhtml view, you can see that the standard inputText component can contain an embedded f:convertDateTime tag to perform the required input conversion.  In this case, we are using the PrimeFaces tag library, which also works with the f:convertDateTime tag.

<p:inputText id="jobDate" value="#{jobController.selected.jobDate}" title="Job Date">
     <f:convertDateTime type="localDate" pattern="MM/dd/yyyy"/>
</p:inputText>

Behind the scenes, this all works because of some changes made in the Mojarra javax.faces.convert.DateTimeFormatter class.  JSF 2.3 requires the use of Java 8, which enables the JSF developers to directly modify the sources to include Java 8 Date-Time classes.  As a quick test, I've modified the index.xhtml view of the application to include a Date-Time testing panel at the top.

<p:panel header="Date Test Panel">
    <p:inputText value="#{testController.todaysDate}">
        <f:convertDateTime type="localDate" pattern="dd-MM-yyyy"/>
    </p:inputText>
    <br/><br/>
    <h:outputText value="#{testController.todaysDate}">
        <f:convertDateTime type="localDate" dateStyle="short" />
    </h:outputText>
    <br/>
    <h:outputText value="#{testController.todaysDate}">
        <f:convertDateTime type="localDate" dateStyle="long"/>
    </h:outputText>
    <br/><br/>
    <h:outputText value="Today's Date is (old): #{testController.oldStyleDate}">
        <f:convertDateTime type="date"/>
    </h:outputText>
</p:panel>

The test panel looks like that in Figure 2.
Figure 2:  Date-Time Test Panel


Note that the AcmePools-JSF23 project can also be used to test other new JSF 2.3 features.  Download the sources, along with Mojarra 2.3.0 and get started testing JSF 2.3!

Tuesday, December 08, 2015

Jython - Mature, but Fresh!

The Jython team has been doing a lot of work over the years to maintain one of the most mature alternative languages for the JVM.  Jython is of course Python for the JVM, and the latest iteration of Jython is 2.7, which brings it ever closer to matching the complete functionality of the  C-based Python 1 for 1.  For instance, Jython 2.7 provides built in support for setuptools, which is an essential part of the Python ecosystem for installation of Python modules, and adds support for dictionary comprehensions.  It also provides more robust integration between Java and Python, so that Python modules can be used more easily from Java, and vice versa.

I had the pleasure of writing an article about the latest version of Jython recently with Jim Baker, one of the key Jython developers.  I've known Jim for a long time now, and it was great to have the opportunity to write an article with him, and his expertise really makes the article, as he delves into technical information behind Jython...giving key insight to how it works.  In the article, readers are provided with a brief introduction to Jython, then they are taken through some of the key features in Jython 2.7 via an example-driven explanation.  Readers learn how to work with Java libraries from Jython, how to install Python modules, and more.

I want to thank Oracle and Andrew Binstock for giving Jim and I the opportunity to write an article for the excellent Java Magazine.  I also want to thank Jim for taking the time to work on this article...it turned out excellent and it was great working with you.

You can read the article entitled "Jython 2.7: Integrating Python and Java" in the Nov/Dec 2015 issue of Java Magazine.

Thursday, October 01, 2015

CJUG Adopt-A-JSR - September 2015 Meetup

On Tuesday, September 29th, the Chicago Java User Group (CJUG) held its second online only session that focused on the Adopt-a-JSR initiative for Java and Java EE.  CJUG has formally adopted JSR 366 - Java Platform, Enterprise Edition 8 (Java EE 8) Specification, and the group has been partaking in the Adopt-a-JSR initiative by promoting information regarding the upcoming Java EE release, and specifically targeting the JSRs that are part of the all-encompassing JSR 366 umbrella.

During this latest session, we provided a brief overview of the current status for each of the JSRs that are part of Java EE 8, and we paid special attention to those that are already in-progress.  To the point, the following JSRs are currently in active movement:

JSR 365 - CDI 2.0
JSR 367 - JSON-B
JSR 368 - JMS 2.1
JSR 369 - Servlet 4.0
JSR 370 - JAX-RS 2.1
JSR 371 - MVC 1.0
JSR 372 - JSF 2.3
JSR 374 - JSON-P
...and most recently, there has been mention of Java Batch 1.1 getting started...

It is also worth mentioning that there are a number of other JSRs planned for inclusion with Java EE 8, but they've not had much activity, as yet.

While not each of these JSRs have active sources that are ready for testing, they have all made some progress either via mailing list discussion, or early specification drafts.  After providing the overview, we delved into a couple of the more active JSRs, including JSR 372:  JSF 2.3, and JSR 374:  JSON-P.  In doing so, we demonstrated how to check out the sources for these JSRs, add them to an IDE, such as NetBeans, and then perform a build and testing.  While we did not have enough time to get into any specific issues in detail, we also looked at the JIRA for JSR 374 and held short discussions on a few of the issues.

We then took a break from Java EE, and focused a bit on OpenJDK and the JDK 9 project.  Bob Paulin demonstrated how it is possible to pull down the JDK 9 sources and begin working with early builds of the modularity solution now.  During Bob's demonstration, he created a fully-functional modular program.  We also discussed the possibility of future CJUG involvement in the Adopt-a-JSR program for Java SE.

In summary, the September 2015 Adopt-a-JSR session was a great chance for us to provide a current status of the ongoing efforts towards Java EE 8, and it also gave us a chance to demonstrate what is currently possible with JDK 9.

If you are interested in listening to the audio from the Adopt-a-JSR session, please use the following link:  Audio for CJUG Adopt-a-JSR Sept 2015

We plan to hold more sessions online that focus on Adopt-a-JSR in the near future.  Please stay tuned for more...

Friday, June 05, 2015

Utilizing the Java 8 Date-Time API with JSF and Java EE 7

If you are using Java 8 with Java EE 7, then there may be some quirks that you run into when trying to utilize some of the Java 8 new features.  One such quirk is that the new Date-Time API does not work with many of the Java EE 7 APIs by default since they are built to work with java.util.Date and/or the older Date APIs.  However, this is not a road block, as there are many ways to work around such issues.  In this post, I will demonstrate how you can tweak your JSF application to allow use of the Java 8 Date-Time APIs along with JPA and date converters.

First things first, if you wish to persist dates using the new LocalDate class (or others that are part of the Java 8 Date-Time API), you need to develop a converter which will automatically convert from java.time.LocalDate to java.util.Date and vice versa in order to work with JPA 2.1.  This is easy enough to do, especially since there is no need to configure any XML to establish the converter.  The following code is a converter that is used to provide Java 8 Date-Time support for JPA:

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.ZoneId;
import java.util.Date;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

/**
 * Converter to provide Java 8 Date/Time API Support to JPA
 * 
 * @author Juneau
 */
@Converter(autoApply = true)
public class LocalDatePersistenceConverter implements AttributeConverter<LocalDate, Date> {
    @Override
    public Date convertToDatabaseColumn(LocalDate entityValue) {
        LocalTime time = LocalTime.now();
        Instant instant = time.atDate(entityValue).atZone(ZoneId.systemDefault()).toInstant();
        return Date.from(instant);
    }

    @Override
    public LocalDate convertToEntityAttribute(Date databaseValue) {
        Instant instant = Instant.ofEpochMilli(databaseValue.getTime());
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).toLocalDate();
    }
}

Looking at the code, the convertToDatabaseColumn() method accepts a LocalDate from the entity, class and then utilizes some of the Java 8 Date-Time API utilities to convert it to a java.util.Date so that it can be stored into the database.  The second method, convertToEntityAttribute() takes a java.util.Date from JPA and converts it in the opposite direction into a LocalDate object for use with your Java 8 based application.  The @Converter annotation registers the class as a converter, and implementing AttributeConverter applies the converter to an entity class in order to convert the state to a database column and back again.

Next, if you attempt to apply a JSF converter to a Java 8 LocalDate within your application, say within a view, you will experience issues unless you write a special FacesConverter implementation to apply against the component that you wish to convert to the LocalDate.  Writing a FacesConverter is just as simple as the entity class attribute converter, and registration is as easy as applying an annotation to the converter.  The following class is an example of the FacesConverter that will convert a java.time.LocalDate to a java.util.Date for use within a JSF component.  Note:  This also works with popular JSF component libraries, such as PrimeFaces.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.FacesConverter;

/**
 * Faces converter for support of LocalDate
 * @author Juneau
 */
@FacesConverter(value="localDateTimeConverter")
public class LocalDateTimeConverter implements javax.faces.convert.Converter {

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
          return LocalDate.parse(value);
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {

        LocalDate dateValue = (LocalDate) value;
        
        return dateValue.format(DateTimeFormatter.ofPattern("MM/dd/yyyy"));
    }
    
}
Now let's look at the code a bit.  This FacesConverter class is registered via the @FacesConverter annotation, and the class can simply implement the javax.faces.convert.Converter interface.  Next, take a look at the implementation.  The getAsObject() method is used to parse a String from the component and return it as a java.time.LocalDate, whereas the getAsString() method accepts a LocalDate object and returns it as a String in the specified date format.  This demonstrates another nice feature of Java 8...the DateTimeFormatter class, which makes it easy to format a java.time.* object.  

That's it...not too difficult to use the nice Java 8 Date-Time API within a Java EE 7 application.  Now let's apply the converter to a date component.  The following markup demonstrates how to apply the converter to a PrimeFaces calendar component.

<p:calendar id="enterDate" converter="localDateTimeConverter" style="width: 100%;"

  readonly="true" value="#{myExcellentJsfController.current.enterDate}">

  </p:calendar>

Wednesday, April 22, 2015

Getting Started with Jython 2.7 in NetBeans IDE 8.0.2

The Jython 2.7 release is on the horizon.  In fact, Jython 2.7 release candidates are available from the Jython site at the time of this writing.  For a list of the new features and repairs, please refer to the Git repository.

Whether you are a seasoned Python or Jython developer, or whether you are looking to learn a new language, the NetBeans IDE makes for an excellent tool to get going with Jython development.  The Python module is easy to install, and it allows one to create new Python/Jython projects from scratch, or create projects from existing sources.  For the most recent information on the NetBeans Python module, please refer to the online documentation at NetBeans.org.

To use Jython 2.7 with the NetBeans Python module.  You must first create a Python Platform within the IDE that points to your installation of Jython 2.7.  After you've successfully installed the Python module, go to the NetBeans "Tools" menu, and select "Python Platforms".  The Python Platform Manager dialog will open, allowing you to add one or more Python Platforms for use (Figure 1).

Figure 1:  NetBeans Python Platform Manager

To add Jython 2.7 as a platform, click on "New" and then traverse to the Jython installation bin directory, and then select the jython executable.  You can also manage your Python Path and Java Path from this dialog. 

NetBeans provides a great tool for working with Jython, as it allows for easy management of applications, Python eggs, testing, and debugging.