alt
March 14th, 2010

by Ivan St. Ivanov

JSF 2 navigation upon POST

When writing a multi-page web applications, very often we give the user the possibility to enter some data in a form. When submitting the form, a POST HTTP request is generated from the browser to the server. If the web app just returns as a response the result page, and for some reason the user clicks the refresh button of the browser, then the POST request will be re-submitted. Which may not be what the intent of both the user and the developer are. That is why the web application developers usually do a redirect to the result page, which actually makes the browser to do a new (GET) request to it.

The author of the above short article shows how this POST-REDIRECT-GET pattern is implement in JSF 2. However, the current state of the implementation may be sometimes quite tedious and error prone – the URI to redirect to together with all the parameters are returned as a single string by the action method.

The author applies another common pattern for building the URI and the parameters. It uses the builder pattern together with a fluent interface. This integrates very well with the JSF pages as well through the NamedBean concept. For more details on the exact implementation, you may check the article.

The foundation of an OSGi-based application

Developer.com has started a series of articles on one of the most interesting topics in the industry – OSGi. The authors start with a very brief and short introduction on what OSGi is, how it emerged and what are its strengths. Then they introduce us to a case study for presenting how OSGi can be used in the practice.

The actual sample application performs user login to a certain user store (LDAP server in our case). In this installment you can see how it is all designed. The authors create two bundles – one for the user credential validation and one for the UI. They contain two and three services respectively and will be developed in the Eclipse Equinox environment. Thus the UI bundle will also use two eclipse plug-in extension points: splash screen and preference page.

This article contains just the requirements and design part of the application. In the next one we will hopefully read more on the implementation of the services and their integration with OSGi.

Class generation in Velocity

The Apache Velocity series on the InformIT Java Reference Guide continues this week with a more interesting example. After last week we were introduced into the project and created our first sample application, now we can see how can we generate all sorts of Java Beans.

The author creates an application that initializes a bean model class containing the package where our target bean resides and also its name and its fields together with their types. Next he creates a utility class with one helper method that will be later used by the template. These both classes are put into the velocity context. Finally comes the template itself. There you can see how you can do conditional logic (if and else) in Velocity template language (VTL), how to implement cycles, how to define and access local variables, how to access model data and call methods of classes that are put in the context.

Declarative hyperlinking in Jersey

When working with a REST-ful web service, sometimes you may need to code inside your app a link to a restful resource class in the form of a URI. For that you would use the UriBuilder class.

The author of this article provides us with some insight on what’s going on in the Jersey development these days. Jersey is the JAX-RS reference implementation so this blog post might be interesting for all of you who are developing or using RESTful web services.

So instead of using the UriBuilder to build a URI variable, the author proposes to annotate it with a new annotation. It is supposed to support all kinds of resource paths and parameters. Remember, it is a work in progress, but it’s worth taking a minute to look at it.

March 7th, 2010

by Ivan St. Ivanov

Last week I was not able to complete my regular review blog post. That is why today I will try to make up. I will link here articles not only from the last seven days, but also from the eighth week of the year. Read on!

Runtime compiling and running java classes

Issue 180 of the Java specialists newsletter is out. There the Java champion Heinz M. Kabutz describes how during the runtime of your program you get a String (actually a CharSequence) representing a java class, compile it and run in the same classloader as your main program.

As of Java 6, inside the javax.tools package (part of JDK’s tools.jar, not in JVM) you can find Java compiler API. That is what the author uses for compiling the string representing the source code into a class. After that he loads the generated class file into the current classloader and starts it (the example source represents a thread).

The author avoids to enter the classloader hell so he does not actually define a child classloader of the current one and run the generated class there. He actually generates a dynamic proxy of the generated class by calling the defineClass0 static method of the java.lang.reflect.Proxy class. As this is not a public method, it is invoked via reflection and before that it is explicitly made accessible.

Beware that this article requires much attention in order to understand. I also advise playing around with the sample code by merely doing it by yourself.

Fast O(n) integer sorting algorithm

Another core java article this week. Actually this one is dealing with concept common for most of the programming languages – sorting algorithms.

Here you can find a way to sort a huge array of positive integers. One peculiarity about this array is that its length should be about 2500 smaller than its greatest element. For example if the greatest element is 1 000 000 (one million), then for optimal results (and for a working algorithm at all), the length of the array should be about 40 000 elements.

The key for this sorting algorithm with linear complexity (O(n)) is that it uses the indexes of a temporary array. The original array is looped through. For each number there the element under the index of the temporary array which corresponds to the number of the original array is increased by one. For example if the first element of the array to sort is 5, then tempArray[5] is increased by one. In the end the temporary array is looped through and all its indexes, which element is greater than 0, are entered in the original array. And it is entered as many times, as great is the element in the temporary array.

Just look at the sort(int[], int, int) method in the sample code to get a better feeling.

Bean validation and JPA

Back in the days, when you wrote your web application (and not only web), you had to validate the user input in possibly different layers of the program. With Bean Validation it is no longer needed. Now you can annotate your model classes (java beans) with annotations like @NotNull, @Max, @Min, @Past, etc. These annotations are all specified in JSR 303 – bean validation. And it comes from the Hibernate Validator project, which is the reference implementation of the specification.

The author of this short blog entry first shows how easy it is to use bean validation with JPA 2.0. If you combine that with view technologies like JSF, the triggering of the validation process comes out of the box, without the need of you calling any validate() method on the API.

With JPA 1.0 is not so straightforward, but the validation can be activated there as well with the help of implementing you own JPA entity listener, which will execute the validation on certain entity manager events (like pre-persist, pre-update or pre-remove).

Finally the author asks Emmanuel Bernard – the spec lead of the bean validation JSR, what is the reason for validation upon deleting an entity. Which Emmanuel answers in his blog, where he describes a usecase, where an order has to be paid (i.e. its isPaid flag should be set) before it gets removed.

Search engine basics

If you are wondering how search engine (like Google) work, then this article is for you. It keeps the balance of not going too much in the details and in the same time not staying too much on the surface.

So, the search engines have four main functions.

1) They are “crawling” the internet pages and downloading new content locally

2) They are indexing each single word in the page they downloaded and are building a big table of all the relevant words and terms from the page

3) Upon user query they are looking for pages that potentially match the query string

4) The found pages are ranked based on their relevance

If you are interested in more details about the above steps and what are the challenges that the search engine developers are facing, then go and read this posting.

Rethinking multi-threaded design principles

With the advance of the hardware industry and the growing number of multi-core processors, writing multi-threaded applications is becoming more and more popular. But how to write an applications that is thread-safe (one thread does not touch the data of another one) and in the same time don’t make it so restrictive that it finally performs like a single-threaded app?

The above article summarizes the design principles in this direction. It starts by looking at the application data model, which is the most common shared resource between different threads. Next the author discusses some thread-safe structures that are part of the JDK. And finally discusses the ways to avoid deadlocks between different threads.

Introduction to Apache Velocity

Apache Velocity is the most common template engine in the industry. Its basic idea is to generate resources of a certain kind (XML, DB scripts, HTML) from a template based on a model data. A very good example of what a template engine does are the JSP pages. They contain some static HTML code as well as some templates. These templates are translated at runtime based on a model (usually a map of java beans) – the variables in the template are substituted with the real values coming from the model beans (usually the engine calls the beans getter methods).

If you are already interested in the matter, then go to the first article from the new series on Apache Velocity presented in the InformIT’s reference guides collection – by far the richest java guides collection I’ve seen. In the first installment you can see the above concepts explained in more details with the usual Hello World example at the end. Of course the next series will show the power of Velocity engine and its template language.

JAX-WS + CDI in Java EE 6

Another short article on one of the most valuable new features of Java EE 6 – Contexts and Dependency Injection. This is a specification (JSR 299) that with the help of the annotations from JSR 330 (Dependency Injection for Java) defines a way to inject common resources (data sources, transaction managers, other beans) to Java EE managed beans. The latter may be simple session EJBs, JSF backing beans, web services etc. Not only that, but the specification defines a way to configure the scope and the lifecycle of a bean.

In the sample application created by the blog author, he develops a simple shopping cart web service, where he injects a shopping cart bean (not EJB, but simple Java bean). The latter is configured to be session scoped, which means that the application server will create a new shopping cart for each HTTP session.

February 21st, 2010

Embed Glassfish in an existing OSGi environment

OSGi is something that is very fashionable in the industry these days. Every big software company makes sure that its products are running inside OSGi environment. Besides the ‘cloud’, OSGi is one of the most used buzzwords today.

Glassfish is the reference implementation application sever of the Java EE specification. It is itself built of modules that are run and managed by an OSGi environment. So the question that the author of the article answers is whether it can be bundled in another OSGi framework. Equinox is used for that purpose.

The author has developed a simple bundle activator. As Glassfish is itself modularized, the task of the bundle is to walk through the modules directory, register the modules that it finds there with the OSGi runtime, find Glassfish’s main bundle and to start it.

Very interesting post for those of you, who have some experience in the OSGi bundle business.

Rich Java web applications with Apache Wind and AJAX

After last week we read an article about one of Apache’s JAX-WS libraries (Apache CXF), now IBM developers works give us ASF’s proposal for the other web services standard – JAX-RS. Apache Wink is still an incubator project, but nevertheless you can see that it works great. It provides support for both the server side part for developing the web services as well as for the client part for consuming them.

The author explains in the beginning the benefits of JAX-RS: it is easier to use and understand than JAX-WS and the format (or the payload) of the documents that are transmitted between the communicating parties, is not always XML.

The last thing is actually elaborated in more details – in the example application the data is transmitted via JSON. It is less verbose than XML and there are plenty of libraries that convert a JSON file to an object and vice versa.

The second part of the article is for developing the client side of the application. As it is a web application, you can imagine that the author builds some web pages. One of the most popular technologies here is AJAX. Through AJAX, you can execute server request from within java script code of your page without the need reload the whole page. The combination of java script code and quick response time makes the AJAX-ified web applications look and behave nearly like desktop ones.

By reading the article you will not only get hands-on experience in building REST-ful web services, but you will learn how to combine it with the JSON format and how to call the web services from AJAX.

Short introduction to XML schemas

Continuing with the web services in this blog, I present you a short introduction to one very important aspect of the JAX-WS world: the XML schemas.

These are documents that describe the order and type of the XML elements in a document. XML schema documents are very useful for both validating the XML content and also for generating objects from XML. It is a successor of the document type definition (DTD) format, which most of you should know and maybe worked with. By applying XML namespaces, you can have an XML document, which uses and conforms to several XML schemata.

If you need a quick intro and do not have the time to go through the detailed w3c schools tutorials, then this is the article for you. You can also browse Inform IT’s Java guide section for another topic that might be interesting.

Version Control Tools

Another article by Martin Fowler. Virtually all the world developers work with version control tools. You use them everywhere, even for the open source projects that you develop by yourself. If you are not using one for your project, then you should consider choosing. As the author points version control tools are used for both tracking the different versions of the code you develop and also for collaboration.

There are a lot of tools that help us in that. The author reviews three of them, but before that he mentions which are the tools, the he would never use. He classifies the good tools in two groups – with centralized repository and with distributed repository.

If you want to understand more about the differences between Subversion, Mercurial and Git, then go and read the short article.