Tuesday, January 31, 2012

Choosing Between Vaadin and JSF

With the recent release of Primefaces 3.0, JSF finally reaches an unprecedent level of maturity and utility that puts it face to face with other popular Rich Internet Applications (RIA) options, such as Google Web Toolkit (GWT), ExtJS, Vaadin, Flex and others. This open source project also proved to be very active and in a constant growing path.

I have been working with JSF + Primefaces since October 2010, when I started developing the project JUG Management, a web application conceived to manage user groups or communities focused on a certain domain of knowledge, whose members are constantly sharing information and attending social and educational events. JSF is a standard Java framework for building user interfaces for web applications with well-established development patterns and built upon the experience of many preexisting Java Web development frameworks. It is component-based and server-side user interface rendering, sending to clients (web browsers) pre-processed web based content such as HTML, JavaScript and CSS. My experience on this technology is openly available on java.net.

Meanwhile, I had the opportunity to create a Proof of Concept (PoC) to compare JSF and Vaadin in order to help developers and architects to decide between one of them. Vaadin is a web application framework for RIA that offers robust server-side architecture, in contrast to other Javascript libraries and browser plugin-based solutions. The business logic runs on the server while a richer user interface, based on Google Web Toolkit (GWT), is fully rendered by the web browser, ensuring a fluent user experience.

The result of the PoC was surprisingly interesting :) It ended up proposing both technologies instead of eliminating one of them. I found out, exploring available books, articles, blogs and websites, that despite being able to implement all sorts of web applications, each technology has special characteristics, optimized to certain kinds of those applications. In practical terms, if we find out that JSF is better for a certain kind of application, that's because it would take more time and code to do the same with Vaadin. The inverse logic is also true. In order to understand that, we have to visit two fundamental concepts that have direct impact on web applications:
  • Context of Use considers the user who will operate the application, the environment where the user is inserted, and the device the user is interacting with.
  • Information Architecture considers the user of the application again, the business domain in which he or she works on and the content managed in that domain.
Notice in the figure bellow that the user is always the center of attention in both concepts. That's because we are evaluating two frameworks that have direct impact on the way users interact with web applications.

Visiting the concepts above we have:

Environment
Some applications are available for internal purpose only, such as the ones available on the intranet, other applications are used by external users, such as the company website.

Users of internal applications are more homogeneous and in limited number, which means that the UI can be a bit more complex to allow faster user interactions. That explains the fight Microsoft Office vs. Google Docs. The last one is not yet fully acceptable in the office environment because it has less functionalities than Microsoft Office. The latter is, on the other hand, more complex and more expensive. However, a limited number of users to a larger number of features makes acceptable to have some additional costs with training sessions to profit from the productivity features.

A company website targets heterogeneous users in unlimited environments. It is not possible to train all this people, thus simpler user interfaces with short and self-explanatory interactions are desirable.

Considering the environment, we would recommend Vaadin for homogeneous users in limited environments and JSF for heterogeneous users in unlimited environments.

Device
Different devices demand multiple sets of UI components, designed to look great from small to large screens. Fortunately, both frameworks have components to support the full range of screen sizes from regular desktops to mobile devices. The problem is that different devices bring different connectivity capabilities and the application should be ready to deal with short band-width and reduced transfer rates. In this case, Vaadin seems to be more suitable for multiple devices, as long as the variety of devices is not so extensive, because the user interface is rendered locally, using JavaScript, and it has a richer Ajax support to optimize the exchange of application data with the server.

Business Domain
In principle, good quality UI frameworks such as JSF and Vaadin can implement any business domain. The problem is how experienced the team is with the technology or how small is the learning curve to master it. Business is about timing and the technology that offers the best productivity will certainly win. If your team has previous experience with Swing then Vaadin is the natural choice. If the previous experience was more web-oriented, manipulating HTML, CSS ans Scripts, then JSF is recommended.

Content
Content is a very relevant criterion for choosing between Vaadin and JSF. In case the application needs to deal with volumous content of any type, such as long textual descriptions, videos, presentations, animations, graphics, charts and so on, then JSF is the recommended over Vaadin because JSF uses a web content rendering strategy to profit from all content-types supported by web browsers without the need for additional plugins or tags. The support for multiple content is only available on Vaadin through the use of plugins, which must be individually assessed before adoption.

User
Last, but not least, we have the user, who is the most important criterion when choosing a UI framework. We would emphasize two aspects:
  1. The user population: the largest is the target population the highest are the concerns about application compatibility. It must deal with several versions and types of browsers, operating systems, computers with different memory capacity and monitor resolution. All these without failures or security issues. For larger populations, the most appropriate technology is the most compatible one in a cross-platform environment, which is the case of JSF, since it uses a balanced combination of HTML, JavaScript and CSS, while Vaadin relies only on JavaScript and CSS. But shorter populations would have better profit with Vaadin because cross-browser compatibility is and will remain being a very hard work to be done by Vaadin's development team behind the scene.
  2. User's tasks: If the application is intensively operated by users then it is expected that it has more user's tasks implemented. On the other hand, if the application is rarely used or has short intervals of intensive use, then there is a lower concentration of user's tasks. According to the PoC, Vaadin is the technology that provides the best support on delivering user tasks with richer user interaction because of its fast visual response. JSF is less optimized on which concerns the user interaction.
In conclusion, instead of discarding one of these frameworks consider both on the shelf of the company's architectural choices, but visit the criteria above to make sure that you are using the right technology to implement the expected solution. A simple way to apply those criteria would be to assign weights to each criterion, according to the project's characteristics; set which technology is appropriate for each criterion; and sum the weights for each technology. The highest weight elects the technology to be used in the project.

Thursday, January 5, 2012

Becoming Part of the Java Code Geek Community

I'm glad to announce that I just became part of the Java Code Geeks (JCG) community! I have been following this community for a long time, consuming a lot of great Java articles, and now I'm part of it. This is a great honor and also a great responsibility because it is a way of pushing myself to write betters articles and do it in a more frequent way.
For those who don't know JCG, this is a community of bloggers whose articles are of interest to the Java developer community. They simplify the process of publishing selected blog articles by JCG members on a aggregator website.  This is a win-win game because JCGs enjoy substantially increased visibility and the audience enjoys great content.
I also had the opportunity to include CEJUG as a supporting user group. In the coming days I will find time to integrate JCG's posts with CEJUG's website using rss and let people know how I did it here.

Monday, October 10, 2011

EJB Lookup in a Vaadin Application

It has been a long time since the last Service Locator I have implemented. I thought it wouldn't be necessary anymore considering the maturity of the Java EE CDI (Contexts and Dependency Injection). My first implementation was to make use of EJBs in a Struts-based web application. After that, I started working with JSF, which only requires annotated attributes with @EJB or @Resource to communicate with the business layer. So far, it has been a great experience until they asked me to evaluate Vaadin as a front-end technology for business applications.

Before going too far, I have read the article "Adding JPA to the Address Book Demo", published on Vaadin's wiki, which explains how to call EJBs from Vaadin's classes to retrieve and persist data from the business layer. EJBs use JPA to get and put data in the database. They suggested to call EJBs from a custom servlet, which, according to the Java EE specification, has the ability to make EJB calls using CDI. If we have 1 or 3 EJBs to call, it seems to be an appropriate solution, but what to do in the Servlet when we have ~40 EJBs to deal with? How to pass all these references to Vaadin's application class? The interface of this class can go nuts! That's why I believe that the lookup using JNDI is desirable.

The following code is the Service Locator that I'm using in my Proof of Concept (PoC).

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class MyServiceLocator {
   private Context initialContext;
   private Map cache;
   private static ClientServiceLocator
           ourInstance = new ClientServiceLocator();

   public static ClientServiceLocator getInstance() {
      return ourInstance;
   }

   private ClientServiceLocator() {
      try {
         this.initialContext = new InitialContext();
         this.cache = Collections.synchronizedMap(new HashMap());
      }
      catch(NamingException ne) {
         System.err.printf(
            "Error in CTX looking up %s because of %s while %s",
            ne.getRemainingName(),
            ne.getCause(),
            ne.getExplanation());
      }
   }

   public Object lookupEjb(String ejbName) {
      if(this.cache.containsKey(ejbName)) {
         return this.cache.get(ejbName);
      }
      else {
         try {
            Object ejbRef =
               initialContext.lookup("java:comp/env/"+ ejbName);
            this.cache.put(ejbName, ejbRef);
            return ejbRef;
         } catch (NamingException ne) {
            throw new RuntimeException(ne);
         } catch (Exception e) {
            throw new RuntimeException(e);
         }
      }
   }
}

The class MyServiceLocator follows the Singleton design pattern, making sure that there is only one instance of the object to serve all requests from the web application. The unique instance is created at the class' initialization process and since the constructor is private, the class cannot be instantiated by another class, being available only through the method getInstance(). The constructor initializes the context and creates a synchronized map where we store all references already created. The method lookupEjb(String ejbName) locates EJBs whose names are available in the local JNDI context. This method only works for those EJBs whose references are declared in the web.xml file, as listed below.

<web-app version="2.5"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemalocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  
   <display-name>Information Systems</display-name>
   ...
   <ejb-local-ref>
      <ejb-ref-name>InformationSystemBean</ejb-ref-name>
      <ejb-ref-type>Session</ejb-ref-type>
      <local>
         example.business.InformationSystemBeanLocal
      </local>
      <ejb-link>
         eac-architecture-ejb.jar#InformationSystemBean
      </ejb-link>
   </ejb-local-ref>
</web-app>

The tag <ejb-local-ref> is used to declare a reference to a local EJB. The example above maps only one EJB. So, you have to repeat it for each EJB you want to map. Details about this tag can be found here. Once declared, we can get an instance of the EJB in any part of the application using the following code:

private InformationSystemLocal informationSystemBsn =
   (InformationSystemLocal)MyServiceLocator.getInstance()
                              .lookupEjb("InformationSystemBean");

The variable is typed with the EJB local interface, which is InformationSystemLocal. The service locator returns an instance of the EJB named as InformationSystemBean, which is by default the EJB's implementation class. Notice that none of the code above is necessary when we use CDI. The invocation of AjudaBsn would be simply like that:

@EJB
private InformationSystemLocal informationSystemBsn;

CDI is good and elegant, but not widely applicable. The way it is implemented today is the main weakness of the Java EE specification. Maybe there is some strong reason why EJB's annotations don't work in every Java class. I simply don't see this misterious reason because Spring has addressed this issue since long time ago simply using aspect orientation.

Saturday, October 8, 2011

My Favorite Steve Jobs' Lesson

"Your time is limited, so don’t waste it living someone else’s life. Don’t be trapped by dogma — which is living with the results of other people’s thinking. Don’t let the noise of others’ opinions drown out your own inner voice. And most important, have the courage to follow your heart and intuition. They somehow already know what you truly want to become. Everything else is secondary" - Steve Jobs (1955 - 2011)
R.I.P. Steve Jobs.

Monday, September 26, 2011

Some Interview Questions to Hire a Java EE Developer

The Internet is full of interview questions for Java developers. The main problem of those questions is that they only prove that the candidate has a good memory, remmembering all that syntax, structures, constants, etc. There is not real evaluation of his/her logical reasoning.

I'm listing bellow some examples of interview questions that check the knowledge of the candidate based on his/her experience. The questions were formulated to verify whether the candidate is capable of fulfilling the role of a Java enterprise applications developer. I'm also putting the anwsers in case anybody want to discuss the questions.

1. Can you give some examples of improvements in the Java EE5/6 specification in comparison to the J2EE specification?

The new specification favours convention over configuration and introduces annotations to replace the use of XML for configuration. Inheritance is not used to define components anymore. They are defined, instead, as POJOs. To empower those POJOs with enterprise features, dependency injection was put in place, simplifying the use of EJBs. The persistence layer was fully replaced by the Java Persistence API (JPA).

2. Considering two enterprise systems developed in different platforms, which good options do you propose to exchange data between them?

We can see as potential options nowadays the use of web services and message queues, depending on the scenario. For example: when a system needs to send data, as soon as they are available, to another system or make data available for several systems, then a message queuing system is recommended. When a system has data to be processed by another system and needs back the result of this processing synchronously, then web service is the most indicated option.

3. What do you suggest to implement asynchronous code in Java EE?

There are several options: one can post messages to a queue to be consumed by a Message-Driven Bean (MDB); or annotate a method with @Timer to define the time to execute the code programmatically; or annotate a method with @Scheduler to define the time to execute the code declaratively.

4. Can you illustrate the use of Stateless Session Bean, Statefull Session Bean and Singleton Session Bean?

Stateless Session Beans are used when there is no need to preserve the state of objects between several business transactions. Every transaction has its own instances and instances of components can be retrieved from pools of objects. It is recommended for most cases, when several operations are performed within a transaction to keep the database consistency.

Statefull Session Beans are used when there is the need to preserve the state of objects between business transactions. Every instance of the component has its own objects. These objects are modified by different transactions and they are discarded after reaching a predefined time of inactivity. They can be used to cache those data with intensive use, such as reference data and long record sets for pagination, in order to reduce the volume of IO operations with the database.

A singleton session bean is instantiated once per application and exists for the lifecycle of the application. Singleton session beans are designed for circumstances in which a single enterprise bean instance is shared across and concurrently accessed by clients. They maintain their state between client invocations, which requires a careful implementation to avoid conflicts when accessed concurrently. This kind of component can be used, for example, to initialize the application at its start-up and share a specific object across the application.

5. What is the difference between queue and topic in a message queuing system?

In a queue there is only one producer of messages and only one consumer of these messages (1 – 1). In a topic there is a publisher of messages and several subscribers that will receive those messages (1 - N).

6. Which strategies do you consider to import and export XML content?

If the XML document is formally defined in a schema, we can use JAXB to serialize and deserialize objects into/from XML according to the schema. If the XML document does not have a schema, then there are two situations: 1) when the whole XML content should be consider: In this case, serial access to the whole document is recommended using SAX, or accessed randomly using DOM; 2) when only parts of the XML content should be considered, than XPath can be used or StAX in case operations should be executed immediately after each desired part is found in the document.

7. Can you list some differences between a relational model and an object model?

An object model can be mapped to a relational model, but there are some differences that should be taken into consideration. In the relational model a foreign key has the same type of the target's primary key, but in the object model and attribute points to the entire related object. In the object model it is possible to have N-N relationships while in the relational model an intermediary entity is needed. There is no support for inheritance, interface, and polymorphism in the relational model.

8. What is the difference between XML Schema, XSLT, WSDL and SOAP?

A XML Schema describes the structure of an XML document and it is used to validate these documents. WSDL (Web Service Definition Language) describes the interface of SOAP-based web services. It can refer to XML schemas to define existing complex types passed by parameter or returned to the caller. SOAP (Simple Object Access Protocol) is the format of the message used to exchange data in a web service call. XSLT (eXtensible Stylesheet Language Transformation) is used to transform XML documents into other document formats.

9. How would you configure an environment to maximize productivity of a development team?

Every developer should have a personal environment capable of executing the whole application in his/her local workstation. The project should be synchronized between developers using a version control system. Integration routines must be executed periodically in order to verify the compatibility and communication between all components of the system. Unit and integration tests must be executed frequently.
---

You can increment this set of questions covering other subjects like unit testing, dependence injection,  version control and so on. Try to formulate the questions in a way that you don't get a single answer, but a short analysis from the candidate. People can easily find answers on the Internet, but good analysis can be provided only with accumulated experience.