Java’s Functional and Declarative Evolution

Java 8 is the largest change in the Java platform to date. One of the primary goals was to move the language from an imperative model to a declarative model. Before Java 8, software engineers wrote code that explicitly modified the state of the program and provided instruction on how all operations should be performed. Let’s discuss the evolution of Java development. Consider this example:

We have an Array collection with a bunch of numbers {1, 2, 2, 3, 5, 8} and need to find the “sum of all numbers.” Using Java 4 or lower (imperative) you have to loop through the array like this:

int sum=0;
for(int x=0; x<array.size(); x++){
// do the summation
 sum+=array[x];
}

This code explicitly loops through the array, one element at a time. Java 5 simplified things a bit, with the introduction of the more concise For loop:

int sum=0;
for(int x:array){
 sum+=x;
}

So no longer care about the length, we just loop through the collection. But if you compare this to the previous code, it’s still the same approach – we tell Java to explicitly loop through each and every element in the array. We still need the same amount of code to do it (minus some < and ++ operators) and readability is more or less the same. We wrote more logic just looping the array than our actual business logic.

We can also use the Iterator pattern like this:

int sum=0;
Iterator i = array.iterator();
while(i.hasNext()){
sum+=i.next();
}

If we compare all three options, they’re all similar amount of code and complexity. The iterator pattern actually introduces even more objects for the JVM to manage.

Onto Functional Style
With the introduction of Java 8, we get two things: Lambadas and the ‘forEach’ method on all Collections. ForEach provides us with a reference to all items in the collection. The implementation is specific to the type of collection. We just have to call the ForEach method. Java will execute and provide us the implementation. This is a classic example of polymorphism. Here’s how we use it:

int sum=0;
array.forEach(n -> {
//implementation here
sum+=n;
});

With this approach, we don’t care how the array is looped — there is no need to manage iteration values or indexes. ForEach will handle it for us and call the body of our function, for every element in the array (commented area). The code that is in the forEach: (n-> { … }) is lambda notation.

This lets us focus on implementing the solution to our problem (summing the contents of the array), rather than worrying about how to access our Array. It’s the job of the Java API to handle things it *already* knows how to do.

Compared to our Java 5 implementation, the functional style is easier to read, is less complex, and helps us focus on code that represents our business logic.

More Features
This is just an example of how Java 8 will change the way developers write code. I’ll talk about further improvements including the Stream / Map / Reduce / Predicate APIs in my next article.

Google Glass: Development & GDK!

Learning the Glass Development Kit was one of my immediate goals after getting Glass. So, just like learning any new Platform, I built a  “HelloWorld” LiveCard application 🙂

The GDK itself is not finalized and is still in preview stages. Google has some decent samples here.  Turns out, getting your development environment ready is a little tricky. The Quick Start Guide is a great place to start, but I’ll summarize the entire process here:

  1. Download the ADT Bundle. This contains the SDK Manager and Eclipse based Android Development Tools (ADT) IDE.
  2. Unzip the bundle. Run the SDK Manager and install the supported Glass Android version (currently, 4.4.2). Make sure you include the SDK Platform and Glass Development Preview Kit.sdk-manager
  3. You will need to install the newest Android SDK Build-tool (currently 19.0.1). I accidentally installed 19.0 and ended up with runtime issues.
  4. Finally, install the Google USB Driver. This allows the ADT to communicate with Glass. When installed, it will be located in <your install folder>/sdk/extras/google/usb_driver/.usb driver
  5. Next, you need to prepare Glass itself to accept custom built software. Go into the “Settings” live card, then scroll until you see “Device Info”. Tap once, choose “Debug” and enable it.
    settings
  6. Unfortunately, the provided USB Driver is not compatible with Glass. You’ll have to modify the “android_winusb.inf” file to include Glass entries before Windows will accept the driver. Add the following to the [Google. NTx86] and [Google. NTamd64] sections:
    ;Google Glass
    %SingleAdbInterface% = USB_Install, USB\VID_18D1&amp;amp;PID_4E11&amp;amp;REV_0216&amp;amp;MI_01
    %CompositeAdbInterface% = USB_Install, USB\VID_18D1&amp;amp;PID_4E11&amp;amp;MI_01
    

    Note: The actual VID , PID, REV, and MI values must match what your actual hardware device ID says. You can get your specific values by plugging Glass into your USB port. Open up your Device Manager, browse to the Glass device that has a missing driver (marked with !). Right click, goto Properties –> Details Tab –> Hardware IDs dropdown.
    adb device

  7. Install the USB Driver to Windows.  Open up your Device Manager, browse to the Glass device. Right click and choose Update Driver. Browse to the above folder (Step 4) and proceed with the install.
  8. With Glass plugged in, go back to <your install directory>/eclipse and start Eclipse. Switch to the DDMS perspective (Window –> Open Perspective –> DDMS).
  9. You should see Glass in the Devices tab.
  10. Now you’re all set!

Processing Form Posts with JAX-RS

Here’s a quick example on how to use JAX-RS to accept & process POST data, for example from a user submtting a Form.

First, you need to tag a method with the @POST annotation. It will instruct a method to respond to requests that are POSTED.

Second, the @Consumes annotation must be added so that JAX-RS will respond to Content-Type: application/x-www-form-urlencoded/. You do this by specifying MediaType APPLICATION_FORM_URLENCODED on the annotation.

Third, all form fields should be added as parameters to the method. The @FormParam annotation should be used to tag all parameters you expect the form submission to populate.

Here’s an example:


@Path("/test")
public class RestTest(){

	@POST
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public Response acceptForm(@FormParam("name") String name,
			@FormParam("password") String password){
		//@Context HttpServletResponse servletResponse

		System.out.println(name + password);
		Response res = Response.ok("<response>200</response>").type("text/xml").build();

		return res;
		//servletResponse.sendRedirect("../create_todo.html");
	}
}
	

This would accept data from a form that has two fields (name and password). When the form data is posted, JAX-RS will call this method and populate the proper parameters, by name. The form action should point to the REST path, so in this case /test.

If the request was AJAX based, you might respond with a XML string or plain text, as seen in the example. Your client can then proceed based on the response.

If it is a traditional request, you will probably want to forward the user to a new page. In that case, you can use the code that is commented out and change the method return type to a void.

		@Context HttpServletResponse servletResponse

		servletResponse.sendRedirect("/somewhere.jsp");
	

Injecting EJBs into Struts 2 Actions

I think Sun/Oracle has done a great job of simplifying the EJB mess. I’ve been integrating Stateless EJB3 beans with the Struts 2 layer recently and it’s been working pretty well. To create a stateless EJB, you simply annotate the class with @Stateless. Nothing else is needed! No XML configs, no Remote interfaces, NOTHING!

Then when you want to use the EJB, just inject it. For any normal container managed classes you can inject a EJB3 bean by using the @EJB annotation. For example, if you wanted to inject the MyEjbLocal bean, just tag it with @EJB like this:

@EJB
MyEjbLocal myEjbLocal;

However, I wanted to make use of EJBs in my Struts 2 actions. Using the above method doesn’t work because Struts Actions aren’t managed by the Container/App server. You could perform a Initial Context look up everytime but that seemed to be a silly work around.

Instead, just write your own annotation that performs the lookup and then take advantage of the Struts 2 Interceptor stack. In your struts.xml config, you’ll need to define a new interceptor that points to your custom class:

<interceptor name="ejb3" class="com.opensymphony.xwork2.ejb3plugin.InjectEJBInterceptor"></interceptor>

You can find this code freely available on the web or contact me if you would like full src code. This interceptor defines an annotation like this: @InjectEJB.

Then make sure its added to your struts stack. Note ‘defaultStack’ is built into Struts 2:

<interceptor-stack name="new.stack">
  <interceptor-ref name="ejb3" />
  <interceptor-ref name="defaultStack" />
</interceptor-stack>

Finally, inject your new interceptor stack into your actions:

<action name="index" class="com.usps.TestAction">
   <interceptor-ref name="new.stack"/>
   <result name="success" type="tiles">index.tiles</result>
</action>

Now you can use the @InjectEJB annotation in place of @EJB in any of your Struts Actions!

@InjectEJB
MyEjbLocal myEjbLocal;

Diving into Groovy/Grails …

I always like to learn a new language or software platform every year. A couple years ago it was Ruby on Rails. I used RoR very extensively with my time at Rosetta Stone. I liked RoR but it definitely had its problems. This year I decided to learn something similar: Groovy on Grails, or GoG.

I am no expert at GoG by any means, but I really like what I see so far. The language is obviously based on Ruby but unlike ruby, it actually compiles and runs in the JVM. Weird concept but is pretty cool.

The strangest thing to me is the fact methods don’t have return signatures. So the below returns an array of Books, but never explicitly defines the return type.

def hello = {
 [bookList: Book.list()] 
}

GoG is definitely a younger platform and I haven’t really found a good use for it but it’s an excuse to learn another “language” …

Netbeans Rant

Netbeans is an awesome IDE (my fav one), but one thing that annoys me is the lack of support for JAR files that depend on Native Libraries. Java Native Access allows Java APIs access to functionality bundled in a DLL. With JNA you can call directly into a DLL and access its methods. Most often used for integrating with C/C++ code.

One way to set this up is to include a MANIFEST.MF file in your JAR. You add a line like this:

Bundle-NativeCode: [Directory to the DLLs] 

Now you can distribute the JAR and required DLLs easily. With Eclipse this is easy – you simply add the JAR to your Project Build Library. Then expand the node and configure the “Native Library location” option to point to your DLL(s).

However, in Netbeans if you try to add a JAR that has DLLs specified, the IDE immediately crashes and throws a “Class not found” error. As far as I can tell – there is no way at all to setup a Native Library JAR file in Netbeans. If anyone has done this please let me know how! 🙂

Your options are:
1. Use Eclipse
2. Add the DLL path to the Java executable like so:

java -Djava.library.path=[path to native lib folder]

Usually adding the DLL(s) path to the PATH environment variable does the trick. Then go into the MANIFEST.MF file and remove the line for “Bundle-NativeCode”. Finally, add the JAR in Netbeans and it will work!

Hibernate and JPA Thoughts

I’ve been using Hibernate’s implementation of the JPA 2.0 spec a lot recently. Here’s some thoughts:

I think Sun/Oracle did a great job pushing the JPA spec. It’s forced all the random vendors to agree and implement a spec that isn’t crazy complex with XML configs all over the place. The biggest issue in the Java ORM world was the wide variety of implementations with no common ground, ie. complexity.

All of my previous experience has been in straight Hibernate, without JPA – but I have to say that I’m impressed. I’ve never used JPA v1.0 so I didn’t experience the shortfalls of v1.0 spec, however v2.0 is pretty darn good.

In Hibernate (without JPA), I created Hibernate HBM/XML config files for every Class I wanted to persist. I realize it supported Annotations but I didn’t use them until Hibernate implemented JPA. Having to look at a Class and then refer to a separate Mapping file for the Database mappings was the most annoying part of the process.

With JPA 2.0, I think most people have moved to the Annotations method. Its cleaner, easier to maintain, and doesn’t require you to create XML configs all over the place. Most vendors (Eclipse, IBM, Hibernate, etc) have also moved their APIs to support JPA.

As I was learning the spec, I found some really awesome tutorials. If you’re learning JPA you should definitely check out these:

  • JavaWorld
  • Tips
  • If you’re looking for a book on JPA, Pro JPA 2 is probably the best book I’ve seen by far.

    First Post!

    I decided to start a blog.  It seems like a cool way to share some thoughts on things that interest me. I’m a Web Applications Software Engineer so I’ll try to focus the blog on related topics. Mostly Ruby on Rails, Java, and related things 🙂

    That’s all for now … more to come later!