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.

Saturday, September 24, 2011

Development Environment to Work with WebLogic

I have to confess that, despite not evolving as fast as the Java EE specification, Oracle WebLogic is a f*** good application server. Its stability is impressive and works smoothly with popular IDEs, such as Eclipse and Netbeans. Of course its qualities come with a cost, which is expensive for poor developers like us, but it's worthwhile for companies.

The official name of WebLogic is "Oracle WebLogic Server 11g Standard Edition". It is part of a broader range of products called "Oracle Fusion Middleware", which offers a complete support for enterprise service-oriented applications (SOA). I'm currently working with WebLogic 10.3.4, which is the first version that supports JSF 2.0, my favority web framework. WebLogic is available for download on Oracle's website. Go to the download page to get your copy. To install it:
  1. Unzip the file in your development folder. For example /home/you/java/weblogic.
  2. Create the environment variable JAVA_HOME, pointing to your JDK installation.
  3. Create the environment variable MW_HOME pointing to /home/you/java/weblogic.
  4. Go to the command line and run the installation configuration script $MW_HOME/configure.[sh/cmd].
  5. Create the domain to start working with WebLogic, running the command MW_HOME/wlserver/common/bin/config.[sh/cmd] and following the instructions on the screen.
  6. Start a web browser and open the url http://localhost:7001/console to access the administration console.

Now, we have to configure the IDE to start, debug, and stop WebLogic, as well as deploy Java EE applications. Because most developers actually use Eclipse as a working IDE, let's configure it, installing the necessary plugin. I'm using Oracle Enterprise Pack for Eclipse (OEPE), a plugin that empowers Eclipse to develop Enterprise Java Application for Oracle Products. To install it:
  1. Open Eclipse and go to the menu Help - Install New Software...
  2. Add a new repository by clicking on Add...
  3. Inform the name Oracle Enterprise Pack for Eclipse and the URL http://download.oracle.com/otn_software/oepe/indigo if you are using Eclipse Indigo, or http://download.oracle.com/otn_software/oepe/helios if you are still using Eclipse Helios.
  4. Follow the instructions and restart Eclipse to finalize.
 Finally, configure the plugin to integrate the IDE with Eclipse:
  1. Go to the menu Windows - Show View and select Servers.
  2. Click with the right button of the mouse on the working area of the view and select New - Server.
  3. In the list of server types, go to the category Oracle and select Oracle WebLogic Server 11gR1 (10.3.4), or the version of WebLogic that you have installed. It's important to select the right version, otherwise an error will continously occur.
  4. Make sure that the field Server's host name contains the value localhost and press Next.
  5. In the field WebLogic home inform the path /home/you/java/weblogic/wlserver.
  6. In the field Java home inform the path to your JDK installation.
  7. You can optionally install some server extensions. I recommend to install all available extensions, clicking on Install, besides each item. Press Next to continue.
  8. Leave the option Local selected in the Server type field and inform the location of the domain. The domain was created in the first part of this tutorial, when we executed the configuration assistent. 
  9. Press Finish to conclude.
That's it! Make sure to select this server when creating a new Java EE application. Don't hesitate to share your experience while following this tutorial.