June 3rd, 2009  | Tags: , , , ,

A common issue when we’re using Portlet is about sharing data between PortletSession and HttpSession. Frequently we find code like this:

Portlet snippet

PortletSession session = request.getPortletSession();
session.setAttribute("attribute_name","attribute_value");

JSP snippet - Using JSTL

<p>${sessionScope.attribute_name}</p>

Result: The JSP prints out an empty value.

Why does it happen ?

It happens because the PortletSession and HttpSession have different scopes. By default, PortletSession uses portlet scope, as well as HttpSession uses application scope. Hence, an object into portlet scope cannot be accessible into application scope.

Using the PortletSession into JSP

One way to print a PortletSession value into a JSP is use the PortletSession within the JSP. We can do that using the following:

<%
PortletSession session = renderRequest.getPortletSession();
out.println(session.getAttribute("attribute_name");
%>

This doesn’t sound good. We intend to use JSTL instead scriptlet and the approach above doesn’t fit in our requirement. Because of this we’re going to use one of the below approaches.

Converting PortletSession into HttpSession within a Portlet

Within the portlet, we can use a code like this:

HttpServletRequest httpRequest = WpsStrutsUtil.getHttpServletRequest(request);
HttpSession session = httpRequest.getSession(true);
session.setAttribute("attribute_name","attribute_value");

The code above simply retrieve a HttpServletRequest and then we created a HttpSession.

It definatelly works, but we can do even better. Check the next example out.

Changing the PortletSession scope

As describe above, by default the PortletSession scope is a Portlet scope. As you should know, JSTL reads Application Scope. Fortunately, there is a simple way to change the default PortletSession scope. Simply add one more parameter in the setAttribute method.

PortletSession session = request.getPortletSession();
session.setAttribute("attribute_name","attribute_value",PortletSession.APPLICATION_SCOPE);

Awesome, huh? In this way, we can use JSTL to get the values from Session.

Conclusion

I’m not a Portet specialist, however I’ve already found many problem regarding the PortletSession and HttpSession. If you’re facing a problem like this, check your code out and try the approaches above.

If you have any question or comment, fell free to leave your message below.

April 22nd, 2009  | Tags: , , , , , ,

In this topic, we’re going to talk an interesting subject: How to create a project using Maven, JSF 1.2 RI, Richfaces, Tomahawk and Hibernate all together. Maybe in the first time, it’ll take long time to download the required JARs files, but believe me, after that you’ll be able to create a new project in less than 5 minutes.

Before get started, if you have no idea what these frameworks do, please, take a look at their official sites and make sure you understand their functionalities.

Maven 2

First of all, we need to install Maven 2. It will be the responsible for creating the project, as well as manage the JARs files. You can download Maven 2 from its official site. Basically you should unzip the downloaded file and create a M2_HOME environment variable. All the needed information are here.

Creating the project

Now we’ve got Maven installed and running, it’s time to create the project. We’re going to use an archetype for web projects, maven-archetype-webapp. To create the project, simply type the following:

mvn archetype:create  -DgroupId=com.jairrillo  -DartifactId=TestMavenAndOtherStuffs -DarchetypeArtifactId=maven-archetype-webapp

A new project will be created with the name TestMavenAndOtherStuffs. The project’s structure looks like below:

TestMavenAndOtherStuffs
|-- pom.xml
`-- src
    `-- main
     |`-- resources
     |`--webapp
            |`-- WEB-INF
                    `--web.xml
            |`-- META-INF
                   `--MANIFEST.MF

There’s an issue with this archetype, it doesn’t create the src/main/java and src/test/java folders. We’re going to use both, so, let’s create them.

Note: If you type mvn package, Maven will package the project in a war file within the target directory. mvn clean cleans up the target directory. Fell free to run both.

POM.xml

As you should know, the pom.xml file is the core of maven. In this file, we’re going to set which frameworks/jars files we’re going to use. Maven reads this file and downloads the required JARs files.

As our project uses a lot of frameworks, there’re many entries in the POM.xml file. Hence, you can download the full POM.xml here.

WEB.xml

The web.xml must be modified. We need to put some configuration there. As we’re using many frameworks, there are many changes in the web.xml. Changing the web.xml file is boring, but I’ve already prepared it for you. Simply click here and download the proper file.

applicationContext.xml & faces-config.xml

As you should know, Spring uses an applicationContext.xml file and JSF uses a faces-config.xml file. Let’s create them.

applicationContext.xml

We’re going to use annotations to map our Service, hence, our applicationContext.xml is very simple. You must inform to spring where it will lookup for the service classes. In our example, the package is com.jairrillo. The applicationContext.xml looks like below:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
     xmlns:tx="http://www.springframework.org/schema/tx"
     xmlns:context="http://www.springframework.org/schema/context"  
     xsi:schemaLocation="http://www.springframework.org/schema/beans  
            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
            http://www.springframework.org/schema/context  
            http://www.springframework.org/schema/context/spring-context-2.5.xsd">  
	<context:component-scan base-package="com.jairrillo" annotation-config="true" />
	<context:annotation-config /> 
</beans>

faces-config.xml

The faces-config.xml for this example is simple too. We’ll only set some parameters from Spring and Facelets.
Note: In our application, Spring will control the dependency injection. Hence, we will not map the managed beans in the faces-config.xml, instead, we’re going to use annotations from Spring, tough.

<?xml version="1.0"?>
<faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd">
 
	<application>
		<!-- Spring Configuration -->
		<variable-resolver>org.springframework.web.jsf.SpringBeanVariableResolver</variable-resolver>		
		<!-- Facelets configuration -->
		<view-handler>com.sun.facelets.FaceletViewHandler</view-handler>		
	</application>	
</faces-config>

It’s done. Our application has been created and it is ready to be used. In the next time, it will not take more than 5 minutes.
Below, I’ll show up an example to run in this new project.

Creating the Spring’s Service

Now we’ve finished all configurations, it is time to code. Let’s get started by the Service. In our application, the Service is gonna be a simple class that receives a String and transform it to UpperCase. The code (interface and concrete class) look like below:

HelloWorldService.java

package com.jairrillo.service;
public interface HelloWorldService {
	public String convertToUpperCase(String word);
}

HelloWorldServiceImpl.java

package com.jairrillo.service;
 
import org.springframework.stereotype.Service;
 
@Service
public class HelloWorldServiceImpl implements HelloWorldService {
	@Override
	public String convertToUpperCase(String word) {
		return word.toUpperCase();
	}
}

Note: Check the annotation @Service out. It is similar than the mapping bean from applicationContext.xml, but much easier to use.

Creating the Managed Bean

The Managed Bean looks like below:

package com.jairrillo.mbeans;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
 
import com.jairrillo.service.HelloWorldService;
 
@Component("helloWorld")
@Qualifier("helloWorld")
@Scope("request")
public class HelloWorldBean {
 
	private String name;
 
	@Autowired
	private HelloWorldService helloWorldService;
 
	public String convertNameToUpperCase() {
		name = helloWorldService.convertToUpperCase(name);
		return "success";
	}
        //getters and setters
}

Again, check the annotations out. The @Component is similar than the managed-bean from faces-config.xml. Another important annotation is the @Autowired, it injects the Service into the ManagedBean. Did you see how simple is JSF + Spring?

Creating the Unit Testing

Before move to the view, let’s create a simple Unit Testing in the managed bean. Actually, in a real application, we should create am unit test for the Service and a different one for the ManagedBean. But to let our application simpler, let’s create only one that cover both classes.

package com.jairrillo.mbeans;
 
 
import static junit.framework.Assert.*;
 
import org.junit.Before;
import org.junit.Test;
 
import com.jairrillo.service.HelloWorldService;
import com.jairrillo.service.HelloWorldServiceImpl;
 
public class TestHelloWorldBean {
 
	private HelloWorldBean helloWorldBean;
	private HelloWorldService helloWorldService;
 
	@Before
	public void setUp() throws Exception {
		this.helloWorldService = new HelloWorldServiceImpl();
		this.helloWorldBean = new HelloWorldBean();
		this.helloWorldBean.setHelloWorldService(helloWorldService);
	}
 
	/**
	 * Test method convertNameToUpperCase() when all result are TRUE
	 */
	@Test
	public void testConvertNameToUpperCaseSuccessfully() {
		//jair
		helloWorldBean.setName("jair");
		helloWorldBean.convertNameToUpperCase();
		assertTrue(helloWorldBean.getName().equals("JAIR"));
		//molly
		helloWorldBean.setName("molly");
		helloWorldBean.convertNameToUpperCase();
		assertTrue(helloWorldBean.getName().equals("MOLLY"));
		//jully
		helloWorldBean.setName("jully");
		helloWorldBean.convertNameToUpperCase();
		assertTrue(helloWorldBean.getName().equals("JULLY"));
	}
 
	/**
	 * Test method convertNameToUpperCase() when all result are FALSE
	 */
	@Test
	public void testConvertNameToUpperCaseError() {
		//jair
		helloWorldBean.setName("jair");
		helloWorldBean.convertNameToUpperCase();
		assertFalse(helloWorldBean.getName().equals("jair"));
		//molly
		helloWorldBean.setName("molly");
		helloWorldBean.convertNameToUpperCase();
		assertFalse(helloWorldBean.getName().equals("molly"));
		//jully
		helloWorldBean.setName("jully");
		helloWorldBean.convertNameToUpperCase();
		assertFalse(helloWorldBean.getName().equals("jully"));
	}	
}

Note: This class must be created into the src/test/main folder previously created.

Now we have the classes created, let’s run the JUnit. To do that, in the console, type

mvn test

If everything is fine, you should get a BUILD SUCCESSFULLY.

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.jairrillo.mbeans.TestHelloWorldBean
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.047 sec
 
Results :
 
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
 
[INFO] ------------------------------------------------------------------------

Creating the View

We’re going to create 3 files: template.jspx, helloWorld.jspx and index.jsp. I’ll not detail all files, but keep in mind that we’re using the facelets.

template.jspx

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Test Maven and Other Stuffs</title>
<style type="text/css">
</style>
</head>
<body>
	<h1><ui:insert name="title">Default Title</ui:insert></h1>
	<p><ui:insert name="body" /></p>
</body>
</html>

helloWorld.jspx

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:t="http://myfaces.apache.org/tomahawk"
	xmlns:rich="http://richfaces.org/rich"
	xmlns:a4j="http://richfaces.org/a4j">
<body>
<ui:composition template="/template.jspx">
	<ui:define name="body">
		<h:form>
			<rich:panel header="Richfaces Panel Example" style="width: 315px">
				<t:outputText value="Type name: " />
				<t:inputText value="#{helloWorld.name}" />
				<a4j:commandButton value="Convert Name" reRender="nameConverted" action="#{helloWorld.convertNameToUpperCase}" />
			</rich:panel>
		</h:form>
		<h:panelGroup id="nameConverted">
			<h:outputText value="Hello, " rendered="#{not empty helloWorld.name}" />
			<h:outputText value="#{helloWorld.name}" />
		</h:panelGroup>
	</ui:define>
</ui:composition>
</body>
</html>

As you can see above, we tried to use one component from Richfaces, Ajax4JSF, Tomahawk and JSF RI 1.2.

index.jsp

<html>
<body>
	<% response.sendRedirect("helloWorld.jsf"); %>
</body>
</html>

All done.

Running the project

To deploy an application, you should first package it. With maven it is very simple, simply type mvn clean package and a war file will be created into target directory.
After that, deploy that file in your Application Server. In my case, I’m using Tomcat.
When you run the project above onto browser, you’ll get a screen like this:

IDE Integration

Even after you created a project through Maven, you can integrate it with other IDE, such as Eclipse, Netbeans and IntelliJ IDEA.
With Eclipse, simple type mvn eclipse:eclipse and then you can import the project within eclipse workspace. The same is for IntelliJ IDEA, type mvn ide:ide.
Netbeans is a little different. Firstly, you must install the Maven Plugin (within Tools | Plugins) and then
just go to File | Open Project and select the directory with the pom.xml file and we are ready to go.

Conclusion

In this article we showed how to create a project using Maven + JSF + RichFaces + Facelets + Tomahawk + Hibernate. Also, we showed a simple example.
Usually, when you try to integrate many frameworks, you’ve got many incompatibility problems, however, this topic shows you how to integrate these frameworks without headache.

I hope this topic be useful for anyone (beside me, of course). If you have any question or comment, fell free to leave your message below.

March 10th, 2009  | Tags: , , ,

The next Java EE release, version 6, is going to bring us many news. Among them, EJB 3.1 seems the most interesting, in my opinion.

Although it’s a draft yet, we can make some testing using Glassfish V3. To get started, we’re going to show up how to create a single Stateless Session Bean (without interface) and package it in a WAR file. That’s right!! Stateless without interface and package it in a WAR file. It belongs to EJB lite. Depends on the profile you’re going to use, the EJB Module is no longer used. Roberto Chinnici’s blog gives you a better explanation about profiles in Java EE 6. Check it out.

Installing Glassfish and adding support to Java EE 6

As I said, we’re able to make some testing in Glassfish V3. Because of this, let’s install Glassfish and add support for EJB 3.1 on it.

First of all, download the glassfish here. Make sure to download the proper version: GlassFish Server v3 Prelude.

Note: If you’re going to use Netbeans 6.5, Glassfish comes by default in its instalation, hence, you do not need to download it separately.

After the Glassfish v3 has been installed, it’s time to add support for EJB 3.1. In general speaking, there are two steps to go through:

Install the Glassfish’s Update tool:

To do that, go to GLASSFISH_DIR/bin and run the updatetool tool. In the first time, you’ll get a message like the image below:

The rest of the process is straightforward. After the tool is installed, run the updatetool again and a screen will come up.

Add EJB 3.1 support

On the Update Tool screen, make the following steps:

  1. From the left panel, pick the Available add-ons
  2. Click the glassfishv3-ejb checkbox and click install
  3. Click the glassfishv3-ejb checkbox and click install


It’s done. It was easy, wasn’t it?

Creating the Project

I’m going to use Netbeans 6.5 to test EJB 3.1, but you’re free to use another IDE or even a text editor.

As I already said, we’re going to package the EJB in a WAR file, hence, we’re going to create a simple Web Project. No EAR and EJB module are going to be used, that’s nice :).

To do that using Netbeans, go to menu File -> New Project -> Java Web -> Web Application. My web project’s name is TestEJB31.

Coding the Stateless Session Bean Component

Time to have fun. Let’s create a single Stateless Session Bean in our web project. The code looks like below:

package com.jairrillo.sessionbeans;
 
import javax.ejb.Stateless;
 
/**
 *
 * @author Jair Rillo Junior (jrjuniorsp@yahoo.com.br)
 */
@Stateless
public class HelloWorldEJB {
 
    public String sayHello() {
        return "Hello World EJB";
    }
}

Wait a moment! The code above looks like a simple POJO, except by the annotation @Stateless.

You’re right! The EJB 3.1 makes our life easier. No interface (at least for Local Session Beans), no inheritance, no xml mapping. EJB 3.1 is awesome, isn’t it?

Creating a Servlet to call the EJB 3.1 Session Bean Component

We need a client to call our EJB component. The best way to do that is create a Servlet. Let’s create a servlet with the name: TestServlet. The code looks like below:

package com.jairrillo.servlets;
 
import com.jairrillo.sessionbeans.HelloWorldEJB;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 *
 * @author jairrj
 */
public class TestServlet extends HttpServlet {
 
    @EJB
    private HelloWorldEJB helloWorldEJB;
 
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet TestServlet</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>" + helloWorldEJB.sayHello() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally { 
            out.close();
        }
    }
 
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 
}

Nothing special, huh? Servlet calls the EJB component and prints out the result in the output object.

Running the EJB 3.1 in a Web Project (WAR file)

Start up the Glassfish and deploy the WAR on it. After that, you can perform the Servlet using the URL: http://localhost:8080/TestEJB31/TestServlet. In the Netbeans 6.5, you can do that clicking on the TestServlet.java class and pressing the Shift + F6 buttons.

When you run the Servlet, you’ll get a screen with the phrase: Hello World EJB. It means the EJB 3 component worked fine in a WAR file.

Conclusion

Java EE 6 will bring us many new features. Among them, I think EJB 3.1 will be the most interesting. So far, we’re able to make some real testing in EJB 3.1 using Glassfish v3. In this topic, I showed you up how to do that.
EJB 3.1, as well as the whole Java EE specification is becoming more interesting and straightforward. If you get used to say that EJB is complicated, it’s time to chance your mind :).

I hope this topic be useful for anyone. See you in the next post.

February 9th, 2009  | Tags: , ,

Searching in the internet, I didn’t find an useful page explaining how to add hibernate depency into Maven. Although it seems an easy setup, I faced some problems that I’ll describe below.

First of all, I’d like to say that I’m using M2ECLIPSE plugin for Eclipse. There’s a simple instruction of how to install and use it here.

Even if you aren’t using M2ECLIPSE, you can follow this topic. I’ll show up the pom.xml file generated by the plugin.

Creating the PROJECT through Maven 2

The first thing to do is to create the project. You can use the Maven-archetypes to do that. There’re archetypes for desktop project, web projects, struts 2 projects and so on. Usually when you use the archetypes, it brings for you by default, the JUnit dependency already installed. Anything like this:

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8</version>
      <scope>test</scope>
    </dependency>

Note: You can edit this entry and change the JUnit’s version to 4.5 (the latest).

Adding Hibernate dependency

You can add the hibernate dependency either editing the pom.xml file or adding it through M2ECLIPSE. In POM.xml, simple add the following:

    <dependency>
    	<groupId>org.hibernate</groupId>
    	<artifactId>hibernate</artifactId>
    	<version>3.2.6.ga</version>
    </dependency>

Through M2ECLIPSE, right click on POM.xml file, go to Maven -> Add Dependency. Type org.hibernate into input file and double click into org.hibernate result. That process will add the same code above into POM.xml

Note: When I’ve done it, I had problem with the jta 1.0.1B jar file. To fix it, I had to download it and save it into jta folder manually.

Adding Hibernate-Annotations

If you’re a normal person you won’t waste time editing XML, because of this you’re going to use Annotations instead, am I right? Hence, you must add the Hibernate-annotation dependency in your project as well.

To do that, edit the pom.xml file and add the following:

    <dependency>
    	<groupId>org.hibernate</groupId>
    	<artifactId>hibernate-annotations</artifactId>
    	<version>3.4.0.GA</version>
    </dependency>

You can also add it through M2ECLIPSE. Repeat the process above and choose the hibernate-annotations rather than hibernate.

Adding slf4j-log4j12 dependency

Here is the trick. Although the two steps above are correct, you still need to add another dependency. org.hibernate adds the API slf4j, but it adds the wrong version. You must add the slf4j-log4j12 that is required by hibernate. To do that, as usual, add the following code into pom.xml:

    <dependency>
    	<groupId>org.slf4j</groupId>
    	<artifactId>slf4j-log4j12</artifactId>
    	<version>1.5.2</version>
    </dependency>

or you can do the same through M2ECLIPSE.

Full POM.XML file

After all changes, you should have a POM.xml file like below:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>TestHibernate</groupId>
  <artifactId>Testhibernate</artifactId>
  <packaging>jar</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>Testhibernate</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.5</version>
      <scope>test</scope>
    </dependency>
    <dependency>
    	<groupId>org.hibernate</groupId>
    	<artifactId>hibernate</artifactId>
    	<version>3.2.6.ga</version>
    </dependency>
    <dependency>
    	<groupId>org.hibernate</groupId>
    	<artifactId>hibernate-annotations</artifactId>
    	<version>3.4.0.GA</version>
    </dependency>
    <dependency>
    	<groupId>org.slf4j</groupId>
    	<artifactId>slf4j-log4j12</artifactId>
    	<version>1.5.2</version>
    </dependency>
   </dependencies>
</project>

If you’re using the M2ECLIPSE, you can see all dependencies through its editor. Double click into POM.XML file and go to Dependency Hierarchy tab. You should see a screen like below:

Conclusion

As described above, the trick in this integration with the org.slf4j dependency. After you solve that problem, the integration works perfect. Both frameworks are awesome and this post teachs you in the integration of them.

I hope this topic be useful for anyone. If you have any question or comment about it, fell free to leave your message below.

January 29th, 2009  | Tags: , ,

Criteria, in my opinion, is the most fantastic mechanism for querying ever created. Hibernate has an excellent API for Criteria and many users use it a lot, including me :). However by default, Hibernate Criteria uses INNER JOIN internally and depends on the situation, it doesn’t work as expected.

As you probably know, INNER and LEFT JOIN are quite different. Generally speaking, INNER JOIN is used when both sides of the associations exists, as long as LEFT JOIN is used when only the LEFT side of the relationship exists. Let’s look at a real example.

Supposing we have the following diagram:

As you can see above, there is a relationship One-To-Many between Person and Children. As usual, One Person can have none or more children, as well as a Children has only one Father (at least, biological).

Now, supposing we wanna a list of all People. If he/she has children, show up the list of them, otherwise, show up only the Person’s name. To do that, we could create an HQL like below:

Query query = getSession().createQuery("SELECT p FROM Person p LEFT JOIN p.listChildren children");

Note: We’ve used LEFT JOIN, but why? Because if the PERSON has no relationship (no children) the query MUST retrieve the values as well. If the query was like this:

Query query = getSession().createQuery("SELECT p FROM Person p INNER JOIN p.listChildren children");

The Person with no relationship (no children) will not be retrieved by the query. The INNER JOIN looks in both side of the relationship. It’s not good for that requirement.

Building the same query using Criteria

Supposing we’re going to create the same HQL above but using Criteria. The sintaxe could be:

Criteria criteria = getSession().createCriteria(Person.class);
criteria.addAlias("listChildren","children");
criteria.list();

Hibernate will read the code above and transform it in an HQL that uses INNER JOIN. The problem with that approach is that the Person with no Children will not be retrieved. So, how to change the default behavior from Hibernate Criteria Associations?

Using LEFT JOIN in Hibernate Criteria

Fortunatelly, there is a simple way to change the default behavior from Hibernate. Simply use the “CriteriaSpecification.LEFT_JOIN” argument. Hence, the Criteria above would be:

Criteria criteria = getSession().createCriteria(Person.class);
criteria.addAlias("listChildren","children",CriteriaSpecification.LEFT_JOIN);
criteria.list();

Conclusion

Criteria API is a powerful mechanism for querying in Hibernate. It can be used for simple and advanced queries. As you saw in this post, the Criteria API is also flexible. Try to use Criteria when you have dynamic parameters. Do not worry about SQL, HQL or anything else besides Objects :).

I hope this topic be useful. If you have any question or comment, fell free to leave your message below.

January 18th, 2009  | Tags: , ,

Java 1.5 brought an interesting feature: Annotations. Boring things, like mapping, can do now through Annotations.

Many frameworks are using Annotations, such as: Hibernate, Spring, EJB 3, JUnit and so on.

Struts 2 also uses the annotation feature, majority for validation, however many people do not know that a simple Action can be mapped through Annotation instead the struts.xml file. This post teaches how to do that, and believe, it’s really simple :).

The project

There are, at least, 3 ways to create a new Struts 2 project:

  1. Using the Struts 2 blank application
  2. Creating a new project and adding the required JARs yourself
  3. Using Maven 2 (archetypes) to create the application

My choice, as always, is the number 3. By the way, if you’re working in a real project without a build tool, consider to study/use MAVEN 2, it is really fantastic.

Creating the Project through Maven 2

First of all, you should install Maven 2 in your machine. If you’re using Eclipse, I advice you to install the M2Eclipse plugin. A good starting point is here.

To create a new project either using maven 2, simply type the following into the console:

mvn archetype:create -DgroupId=tutorial \
    -DartifactId=tutorial \
    -DarchetypeGroupId=org.apache.struts \
    -DarchetypeArtifactId=struts2-archetype-starter \
    -DarchetypeVersion=2.0.5-SNAPSHOT \
    -DremoteRepositories=http://people.apache.org/repo/m2-snapshot-repository

or using the M2Eclipse plugin, through File -> New -> Other -> Maven Project. Use struts2-archetype-starter as archetype.

Maven will create a Struts 2 project, with Spring framework as IoC, DWR, Sitemesh, JUnit, as well as two Action files and one DateConverter as example. As I said, Maven is fantastic, isn’t it?

Note: By default, Sitemesh is enabled in the Maven project. For our example, let’s disable it. To do that, simple edit the web.xml file and comment the filter and filter-mapping regarding sitemesh.

Coding the files. JSPs and Struts Action

Our example is really simple. There will be 2 JSPs (index.jsp and result.jsp) and a simple struts action (HelloWorldAction.java). Let’s code them and after that, let’s show up the difference between the tradicional mapping (through struts.xml) and annotations mapping.

Note: Who has created the project through maven, you’ll see some files already created. Fell free to remove them (before a backup, of course).

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib prefix="s" uri="/struts-tags" %>    
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Index Page</title>
</head>
<body>
	<h3>Index Page</h3>
	<s:form action="helloWorld">
		<s:textfield label="Type any text here" name="name"></s:textfield>
		<s:submit value="Submit"></s:submit>
	</s:form>
</body>
</html>

The index.jsp page has a single form, text field and a button. When the user clicks on submit button, the form sends out the data to the action called helloWorld.

result.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib prefix="s" uri="/struts-tags" %>    
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Result Page</title>
</head>
<body>
	<h3>Result Page</h3>
	<s:property value="name"/>
</body>
</html>

The result.jsp page simple prints out the value from name attribute.

HelloWorldAction.java

package com.jairrillo.struts2example;
 
import org.apache.struts2.config.ParentPackage;
import org.apache.struts2.config.Result;
 
import com.opensymphony.xwork2.ActionSupport;
 
@ParentPackage(value="struts-default")
@Result(name="success",value="result.jsp")
public class HelloWorldAction extends ActionSupport {
	private static final long serialVersionUID = 1L;
 
	private String name;
 
	public String execute() {
		name = name.toUpperCase();
		return SUCCESS;
	}
 
	//--- GETTERS AND SETTERS
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}    
}

Let’s analyse the code above together:

  • The execute method gets the name attribute and change its content to upper case.
  • The Action’s name is very important. As we’re not using the struts.xml file, the action’s name must follow a convention. As the form call the helloWorld.action, our action must be called HelloWorldAction.java.
  • The annotation @Result defines which page will be opened after the execute method
  • The annotation @ParentPackage defines which is the parent package from the current action. It’s the same than defined into struts.xml file

As you can see, in the code above, we created, implemented and also mapped the struts action. The question is: Where is the xml configuration? Answer: It doesn’t exist, very nice, huh?

Before run the application, we must setup another thing into web.xml file. How the struts will know where are the annotations? The need to inform him through the web.xml.

Into the web.xml file, add the following within FilterDispatcher.

    <filter>
        <filter-name>action2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
        <init-param>
        	<param-name>actionPackages</param-name>
        	<param-value>com.jairrillo.struts2example</param-value>
        </init-param>        
    </filter>

As you can see, we defined the package where the annotations are.

Running the application

Now, we can run our application. You can run it into any application server, like Tomcat, Jetty or IBM Websphere. The result should be a page like below:

Conclusion

As we can see in this topic, mapping an action through Struts 2 is very simple and productive. Besides the Action, we can use annotation for type conversion, validation and so on. You can download the application example here. Enjoy it.

I hope this topic be useful for anyone. If you have any comment or question, fell free to leave a message below.

January 1st, 2009  | Tags: , ,

A couple of months ago I started in a new project at IBM. That new project is a big challenge in my life, certainly it is the biggest project I have already worked.
As any new project, there are new tools, APIs, frameworks, that we need to learn. In that project for example, I had to learn the newest EasyMock. Actually, I’ve already used EasyMock a long time ago (maybe in 2005), but in the last years, I was using JMock instead.
Fortunately, the EasyMock 2.4 is similar than JMock, and because of this I had no trouble to learn it.
In this short topic, I’m going to show up how to get started with EasyMock 2.4. This topic doesn’t intend to be a tutorial, only an example of how the EasyMock is simple and can help us in the mockering.
Before get started, make sure that you hava Java 1.5 or higher installed and JUnit 4 (JUnit 3 is also supported, but I really like the annotations features :) ).

Downloading EasyMock

Basically you have to choices: Use a build tool (like Maven) to manage the JARs dependencies or to to the EasyMock’s official website: http://www.easymock.org/ and download its latest version (2.4). Probably you’re gonna download a file called easymock2.4.zip. Extract that file and a easymock2.4 folder will be created. There are documentation, javadoc and samples within the directory, but you will use only the easymock.jar file.

Creating the project

I’m going to use Maven and M2Eclipse plugin to create that project into Eclipse, but you’re free to use another IDE. You can check a Maven example here.
Besides create the project,also add the junit-4.5.jar and easymock.jar file into classpath. If you’re using Maven, add the junit-4.5 and easymock dependencies. The pom looks like below:

<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>EasyMockExample</groupId>
  <artifactId>EasyMockExample</artifactId>
  <packaging>jar</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>EasyMockExample</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.5</version>
      <scope>test</scope>
    </dependency>
    <dependency>
    	<groupId>org.easymock</groupId>
    	<artifactId>easymock</artifactId>
    	<version>2.4</version>
    </dependency>
  </dependencies>
</project>

Creating the Interfaces and Classes

Let’s use a common example that happens in the projects that use EJB2 and remote call. We have a service layer, that will look up for some values from Repository (DAO). That Repository will return the Entity and the Service must copy only the required values to the TO (Transfer Object).
We’re going to test the Service layer, hence, we must MOCK the Repository.
Note: Use the approach (BO and VO) only if you are using EJB2 (CMP entities) with remote call. This post is merely an example.
All the interfaces and classes could look like below:

Customer Entity

package com.jairrillo.easymockexample.entities;
public class Customer {
	private Integer id;
	private String name;
	private String phoneNumber;
	//Getters and Setters

Note: Supposing that is a CMP entity (not serializable). Hence, we cannot send it through the remote call (it must be serializable to do that)
CustomerTO : Transfer Object

package com.jairrillo.easymockexample.transferobjects;
import java.io.Serializable;
public class CustomerTO implements Serializable {
	private static final long serialVersionUID = 1L;
	private String name;
	public CustomerTO() {	
	}
	public CustomerTO(String name) {
		this.name = name;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

Note: That is a Serializable Object. We only copy the required values. In that case, only the Customer’s name is required.
CustomerRepository (DAO)

package com.jairrillo.easymockexample.repositories;
import java.util.List;
import com.jairrillo.easymockexample.entities.Customer;
public interface CustomerRepository {	
	public List<Customer> getListOfPendingCustomers();
}

CustomerService (Business Object layer)

package com.jairrillo.easymockexample.services;
import java.util.List;
import com.jairrillo.easymockexample.repositories.CustomerRepository;
import com.jairrillo.easymockexample.transferobjects.CustomerTO;
public interface CustomerService {
	public List<CustomerTO> getListOfPendingCustomers();
	public void setRepository(CustomerRepository repository);
}

As you can see above, we have two interfaces (CustomerRepository and CustomerService) and two concrete classes (Customer and CustomerVO). Also, we need a new concrete class to implement the CustomerService. The class looks like (no implementation yet).

package com.jairrillo.easymockexample.services;
 
import java.util.List;
 
import com.jairrillo.easymockexample.repositories.CustomerRepository;
import com.jairrillo.easymockexample.transferobjects.CustomerTO;
 
public class CustomerServiceImpl implements CustomerService {
 
	private CustomerRepository repository;
 
	public List<CustomerTO> getListOfPendingCustomers() {
		// TODO Auto-generated method stub
		return null;
	}
 
	/**
	 * Inject the Repository through that method.
	 * We can use Spring, EJB or even Google Guice to do that.
	 * 
	 * @param repository
	 */
	public void setRepository(CustomerRepository repository) {
		this.repository = repository;
	}
}

Creating the Test Case

We’re going to test the CustomerServiceImpl class and mock the CustomerRepository interface.
If you’re using Maven, you can create the test case into src/test/java directory. If not, create a test directory in the same level than src. Below, following our test case.

package com.jairrillo.easymockexample.services;
 
 
import static org.easymock.EasyMock.*;
 
import java.util.ArrayList;
import java.util.List;
 
import static junit.framework.Assert.*;
 
import org.junit.Before;
import org.junit.Test;
 
import com.jairrillo.easymockexample.entities.Customer;
import com.jairrillo.easymockexample.repositories.CustomerRepository;
import com.jairrillo.easymockexample.transferobjects.CustomerTO;
 
public class CustomerServiceImplTest {
	/**
	 * Class underTest
	 */
	private CustomerService customerService;
	/**
	 * Mock object
	 */
	private CustomerRepository mock;
 
	@Before
	public void setUp() throws Exception {
		//Starting the class underTest
		this.customerService = new CustomerServiceImpl();
		//Starting mock object
		this.mock = createStrictMock(CustomerRepository.class);
	}
	/**
	 * This method test the getListOfPendingCustomers when none value is returned from
	 * Repository
	 * In that case, the method must return an Empty {@link java.util.List}
	 */
	@Test
	public void testGetListOfPendingCustomersWhenNoneCustomerIsRetrieved() {
		//Adding behavior for that method
		expect(this.mock.getListOfPendingCustomers()).andReturn(new ArrayList<Customer>());
		replay(this.mock);
		//Injecting Repository into CustomerService
		this.customerService.setRepository(this.mock);
		//Testing the return
		assertEquals(true, this.customerService.getListOfPendingCustomers().isEmpty());
	}
 
	/**
	 * This method test the getListOfPendingCustomers when only ONE value is returned from the Repository
	 */
	@Test
	public void testGetListOfPendingCustomersWhenOneCustomerIsRetrieved() {
		List<Customer> listCustomers = new ArrayList<Customer>();
		Customer customer = new Customer();
		customer.setId(1);
		customer.setName("Jair Rillo Junior");
		customer.setPhoneNumber("123456789");
		listCustomers.add(customer);
		//Adding behavior for that method
		expect(this.mock.getListOfPendingCustomers()).andReturn(listCustomers);
		replay(this.mock);
		//Injecting Repository into CustomerService
		this.customerService.setRepository(this.mock);
		//Testing the return
		List<CustomerTO> listCustomersTO = this.customerService.getListOfPendingCustomers();
		assertEquals(false, listCustomersTO.isEmpty());
		assertEquals(1, listCustomersTO.size());
		//Testing the returned value
		CustomerTO customerTO = listCustomersTO.get(0);
		assertEquals("Jair Rillo Junior", customerTO.getName());
	}	
}

As you can see above, EasyMock is really simple to use. Like other mock object, we must start it, add the behavior and test it.

Running the Test Case

Right click on Test Case class, go to Run As -> JUnit. You’re gonna get a RED BAR. It means the test failed, but why? Because our implementation class isn’t implement yet (duh). Let’s do that now.

Implementing The CustomerServiceImpl

The CustomerServiceImpl implemented looks like below:

package com.jairrillo.easymockexample.services;
 
import java.util.ArrayList;
import java.util.List;
 
import com.jairrillo.easymockexample.entities.Customer;
import com.jairrillo.easymockexample.repositories.CustomerRepository;
import com.jairrillo.easymockexample.transferobjects.CustomerTO;
 
public class CustomerServiceImpl implements CustomerService {
 
	private CustomerRepository repository;
 
	public List<CustomerTO> getListOfPendingCustomers() {
		//List that will be returned
		List<CustomerTO> listCustomerTO = new ArrayList<CustomerTO>();
		//Retrieving values from Repository
		List<Customer> listCustomers = repository.getListOfPendingCustomers();
		//Copying (only required) values to TO
		for (Customer customer : listCustomers) {
			//Only NAME is required for that requirement
			CustomerTO customerTO = new CustomerTO(customer.getName());
			//adding the CustomerTO to list
			listCustomerTO.add(customerTO);
		}
		return listCustomerTO;
	}
 
	/**
	 * Inject the Repository through that method.
	 * We can use Spring, EJB or even Google Guice to do that.
	 * 
	 * @param repository
	 */
	public void setRepository(CustomerRepository repository) {
		this.repository = repository;
	}
}

Supposing our entity has many attributes, as well as many objects related, however we want only send up the NAME (In a remote call, you can use a TO to transfer objects over the network when the entity is not serializable).

Running the Test Case again

Run again the test case and in this time you should get the GREEN BAR!!

Conclusion

With this topic, you can have an idea of how the EasyMock works. Of course it has others features, but it can be a starting point. In a real software, you should create more than only two test method, but I leave this homework for you.
I hope this topic be useful for anyone. If you have any question or comment, fell free to leave a message below.
You can download the example below here.

December 31st, 2008  | Tags:

One single phrase for everyone:

Happy new year

Hopefully in the next year I can write more interesting posts. See you in 2009.

October 29th, 2008  | Tags:

Hi There,
I’ll be away from my blog for a while because I registered for Beta SCDJWS 5.0 and my exam will be on November 17th. The content for that exam seems long and because of this I will try to use my free time (when I have it) to study.
See you guys and good luck for everyone who will make that exam too.

TOP