Pages

Saturday, January 21, 2012

The NetBeans 7.1 IDE has a feature that has been around for a while, but does not get as much attention as it should. NetBeans allows you to take advantage of using remote databases for doing Java development. There are a number of wizards which can take advantage of connections created in the Services → Database tab.

In the demonstration video, I connect to a remote Apache Derby Database, but the same principals apply to any database as long as you have JDBC drivers available.

Tips & Tricks

To verify that a remote database is Apache Derby (Java DB) which is listening on port 1527 (default Derby port). I connect to the remote application and append XXX;create=true; to the end of the connection string. When I test the database connection, if it is Apache Derby, it will create the new database which confirms our suspicion.

This 3 minute video demonstrates this valuable feature which developers should use for all their database needs.

This is a real world demonstration of the incredible and powerful new capabilities in the IDE. What is particularly interesting is that the Apache Commons IO project does a great job of providing unit tests to validate our changes.

I created a 20 minute video which demonstrates this really vital new functionality to help you migrate your projects to JDK 7.

Friday, January 20, 2012

JAX-RS (Jersey) offers a GZIP filter to compress data for responses, and to handle GZIP compressed requests. This functionality is very easy to enable, and is configurable for both requests, and responses.
That does not get much easier.

You can prove that this works by querying your resource with Firebug, or Developer Tools (depending on browser). You can also confirm that it is working by performing a query like:

Tuesday, January 17, 2012

Did you know that you can make an OPTIONS method call to a JAX-RS resource to determine its capabilites? JAX-RS supports a complete set of HTTP methods including OPTIONS.

If you make a specific URI request to a resource, it will return the supported methods like GET, PUT, HEAD, and OPTIONS. In addition, Jersey supports returning the WADL file by default. This allows tools like NetBeans to take advantage of the resource.

So I guess some examples are in order. The first example is a request to the server URI which in this case is GlassFish 3.1.1. This is followed by a request to a specific resource on the server instance.

As you can see the command reports that GlassFish supports all standard HTTP 1.1 methods as denoted by the Allow: header. This example calls a specific resource on the server which only supports a subset of the HTTP methods based on the annotations in the resource. The methods always supported by a resource are HEAD and OPTIONS, but this has two methods annotated as @GET and @POST. Additionally, not that the Content-Type: application/vnd.sun.wadl+xml is returned which includes the WADL for this particular resource.

Web application developers often use UTF-8 as the encoding in their applications, but fail to change the server defaults. This applies to anything which uses Servlets (including JSP, and JSF). You can change the defaults in the sun-web.xml, or glassfish-web.xml as shown below by setting the parameter-encoding element. This remove a number of default encoding warnings like this:

WARNING: WEB0500: default-locale attribute of locale-charset-info element is being ignored
WARNING: PWC4011: Unable to set request character encoding to UTF-8 from context /, because request parameters have already been read, or ServletRequest.getReader() has already been called.

Thursday, January 12, 2012

One of the less discussed aspects of JAX-RS based on the HTTP 1.1 specification is client negotiation. We often write our applications from the server side and expect the client to send us an Accept: */* header which details which media types the client can accept. The server simply returns whatever we have coded for example @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}).
However I bet a number of you have seen something like this before:

The first example is not very subtle. It tells you the client wants a mydoc.doc by requesting a specific format. The second example is more subtle, and the end user (client) may not notice. I made it a "little" more obvious by changing it to .xml. However, most folks would have missed it if I used mydoc.doc. You would have assumed it was a MS Word document to start with. In actuality, the media type returned here is controlled by the file extension.

Note: Updated the source code to include header based negotiation, but this is just mimicking server content negotiation.

The first example returns JSON by default, and other media formats as requested. If it does not understand the media type requested, it simply returns plain text.

On the second example which uses the media type extension, I return a 400 - Bad Request instead of plain text like the first example. This subtlety is based on the fact that the client is requesting a specific type based on extension. If you ask for .pdf and get .txt, the result may cause an unanticipated consequence so it is better to throw an exception.

Wednesday, January 11, 2012

One of the really nice features of JAX-RS is the ability to implement fine grained control over the response returned from the server based on the client request. The Response.ResponseBuilder gives us incredible flexibility to generate the response. Since it uses the builder pattern, it is easy to daisy-chain the information we want into a custom response.

I would highly recommend that you consider returning a custom response for all requests. I would like to explain with an example. I would like to perform a @POST request where I am creating a new object on the server. Since it is a HTTP 1.1 request, I look at Hypertext Transfer Protocol -- HTTP/1.1 (RFC-2616) to see what I must, should, and may return. The difference in the word choices has specific meaning in the specification. In my case, I would like to be completely compliant.

10.2.2 201 Created
The request has been fulfilled and resulted in a new resource being created. The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field. The response SHOULD include an entity containing a list of resource characteristics and location(s) from which the user or user agent can choose the one most appropriate. The entity format is specified by the media type given in the Content-Type header field. The origin server MUST create the resource before returning the 201 status code. If the action cannot be carried out immediately, the server SHOULD respond with 202 (Accepted) response instead.
A 201 response MAY contain an ETag response header field indicating the current value of the entity tag for the requested variant just created, see section 14.19.

OK, the basic response must return 201 - Created status, and a Location header. It should contain an entity (which may only be entity-headers) and may contain an ETag. This is all very easy to do with Jersey.
As you can see from the code snippet, we read the @FormParam information from a form, and create an object which we add to a List<Widget%gt; objects signified by the ws.add(widget) we get the index value for use in our URI. Next we create a URI from our request, and add a path to it for our index.

Finally we use Apache Commons CodecHex to generate a hex string for our ETag.
Finally this is all combined in a Response sent back to the client. This can be seen below.

Saturday, January 07, 2012

I wrote an article on how to use Secure Mercurial in GlassFish using SSL a few weeks ago. After the article was published, I was asked about URL rewriting. I had not really messed with it in the past except with PrettyFaces (which works like a champ for reference).

I tried a framework called Url Rewrite Filter which did a decent job of rewriting URLs. It is a simple library added to your project which uses a servlet filter to handle the URL re-writing. Add the filter to the web.xml, and a urlrewrite.xml which handles the rewrites. It works much in the same manner as PrettyFaces, but is targeted at JSP/Servlets.

In my case, I have an Apple G5 PPC which is the main server for my source repository for Mercurial. This presents some challenges since the Java version is limited to 1.5, and therefore GlassFish can't be upgraded to v3 from v2.1.1. I did manage to get GlassFish v3 to run with OpenJDK 1.7 (BSD Port), but the Zero VM is too slow to handle the load. Kurt Miller has a couple of the builds for Mac PPC There are a number of reasons for my interest, the primary one for URL rewriting is that GlassFish v3 supports AJP out of the box.

Enabling JK Listener (mod_jk)

Using GlassFish v3 would provide a more optimal solution as you can see from the administration console. I decided to try using the mod_jk articles I found for GlassFish v2 from Amy Roh: GlassFish supports configurable AJP Connector and Jean-Francois Arcand's Running GlassFish with Apache httpd. I tried to combine these with mod_proxy and mod_proxy_ajp. The articles are focused on a specific build, and I was unsuccessful in using them. I am sure it has to framework versions, but I did not want spend too much time troubleshooting.

Finally, I tried using a simple mod_proxy arrangement along with mod_rewrite. This arrangement was surprisingly easy to configure, and worked the first time I tried it.

Here is the configuration I used:

httpd.conf

httpd-vhosts.conf

Those simple changes allowed me to rewrite the URL, and open only two ports on my firewall 80 and 443 which are a very good arrangement. As noted in Secure Mercurial in GlassFish using SSL, I am using GlassFish SSL and security to handle my authentication so this is truly a very good solution.

Thursday, January 05, 2012

I just wanted to post a generally good idea on downloading code. I recently downloaded some code from an Apache mirror site which I checked against its MD5 checksum and it failed. At first I thought that the file was corrupt and re-downloaded it. Again it failed the MD5 check, so I checked its cryptographic (GPG) signature and it failed.

I downloaded the code from another mirror and everything worked correctly. I notified the mirror site of the inconsistency, and carried on. However, I often wonder how much we shortcut our work, and fail to check that vital information.

Here is a gentle reminder. If the code has an MD5, SHA, and cryptographic signature, please take the extra 5 minutes to check all three. It will verify your downloads, are safe.

Also keep in mind that if you don't, and make a war file that contains these potentially infected sources, you are propagating the problem.

I am not a fan of using cookies in REST based services. I think that it makes the service less usable since the client must be able to store and retrieve cookies. This limits usage of the service, and introduces state outside of the service. Even the RFC for cookies is called HTTP State Management Mechanism. curl can be used to send cookies to test so not all is lost.

Alright, if I have not talked you out of using them yet, you must have a need for them. (Please rethink the idea though).

Use of cookies is accomplished by using the @CookieParam annotation. Also you can return responses as shown in the code below which include cookies.

Cookies have a limitations on the use of some characters, and names so please look at the RFC noted above for additional limitations. I demonstrate a couple of limitations which include the use of semi-colons (;), and commas(,). The nice thing about this example is you can see the output in a real browser (Internet Explorer not included) since most can handle application/json objects which are returned.

Wednesday, January 04, 2012

A question was posed to me the other day on how to use OpenJDK 1.7 on NetBeans on a Mac since there is only a Developer Preview available. I decided that a video does a better explanation. This applies to NetBeans 6+ as well when using JDK 7 on a default platform of JDK 6.