Java 7: The Top 8 Features

t’s been a while since the last major Java release and expectations were naturally high for the upcoming release. The Java 7 release initially included many JSRs with exciting features, like support for closures, which were later deferred to Java 8 in order to release JSRs that are already done. This effectively diluted what is now offered in Java 7 and has left some disappointed.

The Java language has undergone major changes since I started using it in 1998. Most of the changes were driven by the Java Community Process (JCP) which was established in 1998 as a formal and transparent process to let interested individuals and entities participate and influence how the language should evolve. This is done through the submission of a change request, known as Java Specification Request (JSR), followed by a review and a voting process. Changes or enhancements made to the language can be usually tracked back to a JSR where they were originally put forward for review. For example, the addition of Generics in Java 5 was done via JSR 14.

Java Releases

Here’s a quick snapshot of the past Java release dates (table 1). There are several small new features and enhancements in Java 7. Out of the 28 features that I looked at, here are the ones that I found useful.


New features and enhancements

#1 Strings in switch

In programming, we often encounter situations where we need to do different things based on different values of a variable. For Boolean variables, an if-then-else statement is the perfect way of branching code. For primitive variable types we use the switch statement. However, for String variables, we tend to resort to using multiple if-then-else branches as follows.

Java 6 and Before

One workaround for this is to convert the String into an enum and then switch on the enum.

Java 7

Java 7, however, has added a language level support for String in switch. Now you can rewrite the same code more elegantly:


Not only does this help us write more readable code, but it also helps the compiler generate more efficient byte code as compared to the if-then-else by actually switching on the hashcode() and then doing an equals() comparison. Please note that you will get a NullPointerException if the variable language in the above example resolves to null. I like this feature, but unlike some of the other enhancements in the past (like Generic in Java 5), I don’t anticipate using this feature a lot. Practically, I find myself using if-then-else for one or two values and resort to an Enum when the number of values are higher.

#2 try-with-resources statement

One of the most useful additions in Java 7 is the auto closing of resources like InputStream which helps us reduce boiler plate code from our programs. Suppose we were writing a program which reads a file and closes the FileInputStream when it’s done, here is how you would write the program:

With Java 6 and Before


I want to point out a couple of things in this code. Firstly, notice that we declare the FileInputStream outside the try block just so that it can be accessed in the finally block. The second observation is that we need to initialize the InputStream to null, so that it is guaranteed to be initialized when we access it in the finally block. Last but not the least, the is.close() in the finally block may throw an Exception as well, thereby hiding the original Exception thrown in the try block Exception from the caller. What we probably want is to handle the Exception thrown from is.close() and throw the original IOException.


The above code still has a shortcoming that the Exception thrown from finally is supressed and not accessible to the calling code. I’m not sure how often we want to get both the original Exception and also the Exception thrown from the finally block, but if we did want it, we could do always do something like this:


SuppressedException above is a user written Java bean with a field named suppressed of type Exception. The calling code can then call SupressedException.getThreadLocal().getException() to get the Exception that was supressed in the finally clause. Great, we solved all the problems associated with the try-catch-finally! Now we must remember to repeat this exact sequence with each use of try-catch-finally when handling files or other resources which need to be closed. Enter Java 7, and we can do the above without the boiler plate code.

With Java 7

 
try can now have multiple statements in the parenthesis and each statement should create an object which implements the new java.lang.AutoClosable interface. The AutoClosable interface consists of just one method.


Each AutoClosable resource created in the try statement will be automatically closed! If an exception is thrown in the try block and another Exception is thrown while closing the resource, the first Exception is the one eventually thrown to the caller. The second Exception is available to the caller via the ex.getSupressed() method. Throwable.getSupressed() is a new method added on Throwable in Java 7 just for this purpose.

GlassFish reduced to “toy product” as commercial offering axed

In a GlassFish and Java EE roadmap update yesterday, it was revealed that going forward there would be no more commercial major releases of the popular Oracle GlassFish Server. 
Oracle is ushering those looking for an alternative towards the WebLogic Server - however, it insists that GlassFish is in no way dead.
In terms of practicality, having two commercial servers in one company never made sense. Ultimately one was going to have to go, and unfortunately for GlassFish’s community, their product bit the dust.
For now, the plan is for GlassFish Server to continue to underpin Java EE reference implementations in future releases - however, it remains to be seen how the server will thrive now that it’s been cast out of the Oracle commercial fold.
The community around GlassFish certainly isn’t convinced. Java EE specialist Markus Eisele lamented in his blog that “GlassFish Server as we know it today is deprecated from a full blown product to a toy product”. He added that, with the lack of commercial support, overall quality and reliability was bound to suffer. Not to mention the fact that development will hugely slow, and users can expect far less frequent updates from now on.
There had been rumblings that something was afoot in Larry Ellison's empire. Two weeks ago, loyal Java EE and GlassFish evangelist Arun Gupta made an abrupt departure for software open sourcers Red Hat.
Whilst he couldn’t tell JAXenter whether he was aware that this move was coming, Gupta made it very clear that, with no commercial backing, GlassFish is simply not the viable option for Java EE that it once was.
He told  us that “now that Oracle is not planning any commercial support, WildFly definitely emerges as the leader in this space. So while all the rapid innovation will continue in WildFly, developers / customers can be assured that their deployments will be commercial supported with JBoss EAP”.
In recent years, Red Hat has set a bit of a precedent for picking up the slack when the Java stewards have left their dependents high and dry. This spring, the trilby crew stepped up with OpenJDK 6 when Oracle dusted its hands of Java 6, and with Arun and his huge band of followers, it seems likely that it’ll be gaining a host of new WildFly adherents in the months to come.

Oracle evangelist: “GlassFish Open Source Edition is not dead”

Following the fallout from Oracle’s decision to kill off the commercial version of GlassFish, Oracle evangelist Bruno Borges has hit back, insisting that GlassFish is very much still in good health.

On Monday, Oracle quietly announced the decision to end support for the commercial branch of GlassFish (known as Oracle GlassFish Server). Prominent Java EE blogger Markus Eisle quickly picked up on the news and didn’t mince his words. In a blog post titled “R.I.P. GlassFish - Thanks for all the fish”, he said the application server was being “deprecated from a full blown product to a toy product”. Judging by the reaction on Twitter, many commentators appear to agree.
However, Borges, cross-posting to both his personal and Oracle-hosted blogs, had a different spin on the news. GlassFish’s commercial twin might be gone, he said, but the open source edition is far from dead. In fact, he argued, this might be a positive thing for GlassFish, allowing it to be “free from any ties with commercial decisions”.
He also set out the combat other “FUD”, such as confusion over the price of WebLogic – the closed-source server Oracle is pushing current GlassFish customers towards – and emphasised that support will continue for old builds of Oracle GlassFish Server.
Many have suggested that GlassFish’s natural successor is JBoss WildFly, the open-source foundations for JBoss EAP – including ex-Oracle evangelist Arun Gupta. Gupta, who evangelised GlassFish before moving to Red Hat last month, told JAXenter that WildFly “definitely emerges as the leader in this space”.
In response to such claims, Borges pointed out that Red Hat does not provide commercial support for WildFly – only JBoss EAP, which will not share identical builds. It’s a similar case with IBM and WebSphere, he said: Oracle is far from alone in its policies.

Tomitribe steps up

In fact, only one open-source application server now has direct commercial support: Apache TomEE, courtesy of Tomitribe. The young company, recently founded by David Blevins, took the opportunity to reiterate its commitment to open source in a blog post of its own.
However, Blevins – who appears to be the author of the unsigned post – said selfish companies using GlassFish were as much to blame for the move as Oracle themselves.
“If you are a GlassFish user, how would you compare Oracle’s contribution to GlassFish to your own contribution to GlassFish?” he wrote. “For as much as we throw money around in our companies, it’s shocking we do not think to direct some of it at the communities of Open Source software we use.”
Tomitribe was launched at JavaOne this year with the explicit purpose of supporting the TomEE community and its contributors. Its strategy is to provide paid consulting, training and support services in order to fund TomEE’s development – and, presumably, build a profitable business too.
This need for a commercial base to open source software was echoed by Blevins in yesterday’s blog post. He concluded: “Not even IBM or Oracle can pick up the bill for Open Source forever. All Open Source communities need your support.”

From database to RESTful web service to HTML5 in FIVE minutes


http://jaxenter.com/assets/180/120/beans.1.jpg

In "From database to RESTful web service to HTML5 in 10 minutes", published near the beginning of this year, I described a set of tools that lets you expose data from a database via RESTful Web Services to an HTML5/Backbone.js/CSS front-end. And all this was done in 10 minutes.
You then had the basis of a complex application that already had your data integrated, and already had a basic user interface for you to get started with. The templates used were configurable - meaning that you could include your own company styles and logos and the application contained a set of best practices for organizations creating hybrid Java/HTML5 applications, which is still a relatively new combination of technologies.
You started by creating a Maven-based Java EE 7 application containing JPA entity classes and RESTful Web Services, all of which were generated via wizards and templates in NetBeans IDE. Then you created an HTML5 application in which you used tools in NetBeans IDE to generate a Backbone.js front-end from the Java EE backend. That was all well and good, but left several people wondering why they couldn't create their HTML5 front-end directly within their Java EE 7 application. In this article, I'll show how this can be achieved in NetBeans IDE 7.4, thus shortening the development cycle from 10 minutes to about 5.
Using the Java EE Platform
As before, start in the Services window, where you can register your database server, connect to your databases, and modify data as needed.
Next, create a new Maven Java Web Application, of course, without needing to install a Maven plugin into NetBeans IDE, because Maven support in NetBeans IDE is just there out of the box as soon as you start the IDE.

Click Next and provide the Maven properties relevant to your project, e.g., the Group ID and Version information.

When you complete the wizard, you have a brand new Maven Java Web project, ready to roll with Java EE 7 registered in the POM and visualized in the logical view in the IDE.

As you look through the generated code, note that you can tweak the SQL calls directly within the @NamedQueries, as shown in the screenshot below.


Next, let's generate our RESTful Web Services! The nice thing about convention over configuration is that tool providers know exactly where all the folders and files need to be created and what they need to contain, simply by following the conventions. We have our database, so we can point to it and let all the code be generated from there, while being able to tweak the templates used where needed.

Click Next and notice all the tables in the selected database are shown.

Select the table of interest, and the tables with foreign key relationships on the selected table will be automatically selected too:

You can then define the package where the classes will be created. Notice that when the database changes, you can come back into this wizard and regenerate all the code because you'll be able to select "Update" instead of "New", which will add new properties to the generated JPA entity classes, without removing anything you already added there.
On the final page of the wizard, specify where the RESTful Web Services will be created:

Completing the wizard, you now have a rather neat Maven Java Web application, a firm basis for whatever user interface you need to create:

Notice that the POM shows a graph of your Maven dependencies, which can be exported to an image to impress your boss with:

Combining @javax.ws.rs.ApplicationPath("webresources") in the "ApplicationConfig" class with the @Path("com.mycompany.customermanager.customer") in the "CustomerFacadeREST" class, you can browse to your payload in the browser, after deploying the application:

The "findAll" method is automatically invoked via our RESTful call, which we can tweak to the following to return JSON, as shown above, instead of XML:
@GET
@Override
@Produces({"application/json"})
public List<Customer> findAll() {
        return super.findAll();
}

Incorporating the HTML5 Platform
Now we're ready to create our HTML5 front-end. Use the "RESTful JavaScript Client" wizard to do so, as shown below, in the same application as where you created all the files above:

After specifying that you want a Backbone.js front-end, together with a JQuery Tablesorter UI, and the related JavaScript libraries, you're good to go:

Notice that when you click the second Browse button, the available RESTful Web Services will be shown for you to select:

Click Next and specify the name of the HTML file that will reference your JavaScript client:

Now your Backbone.js front-end is complete, browse through it, read the code, and understand what's been created as the basis of your application.

For example, notice that the URL to your RESTful Web Service is referenced in your Backbone.js front-end code.


In the toolbar, select the browser where you'd like to deploy the application:

If you deploy the application to a Chrome browser that has the NetBeans plugin install, you'll see a NetBeans icon that lets you switch to different form factors to check how your user interface will look on different platforms:

When you choose "Inspect in NetBeans Mode", you can see where items defined in the browser are defined back in the IDE:

Similarly, you can browse the live DOM view in the IDE and see where matching items are defined back in the browser.

Aside from the above, you can use the Java debugger and the JavaScript debugger at the same time to debug the front-end and back-end simultaneously. Also be aware that changes you make in Chrome Developer Tools will automatically be saved back in your files in the IDE. Yes, that's round tripping between NetBeans IDE to Chrome Developer Tools.
As you can see from the above, the time taken to get to the end of this article is significantly reduced from the previous version. Why? Simply because you can now integrate HTML5 front-ends into your Maven Java Web applications. Now you can choose whether you'd like a JSF front-end (via PrimeFaces or Vaadin, for example) or a JavaScript front-end via Backbone.js or some other JavaScript library. The choice is yours and depends on your skill sets and business needs. Whichever approach you choose, NetBeans IDE is there to help you from start to finish!