November 12th, 2009  | Tags:

No dia 08/11/2009 eu participei, oficialmente, da minha primeira maratona por equipes. A maratona em questão foi simplesmente a Ayrton Senna Racing Day. A nossa equipe era de 8 corredores e cada um era responsável por completar uma volta no circuito de interlagos. Embora a quilometragem não aparenta ser alta (5.3km), a dificuldade é imensa, ainda mais para uma pessoa que mal treinou. Abaixo segue um relato da corrida.
Eu gostei bastante da corrida, embora eu quase tenha morrido no final. São Pedro ajudou e não mandou aquele sol infernal. O tempo estava fechado porém quente.
Eu fui o último da equipe a correr, entrei na pista próximo da 12:00. Fiz todo o percurso (5.3 km) em 35 minutos, bem próximo da média que eu calculei (7 minutos por km). É claro que esse tempo é MUITO melhor que o do Rubinho né!!
O Evento é show de bola, porque você tem acesso a interlagos inteira (padock, boxes, arquibancadas, etc etc etc), porém a corrida é BEMMMM puxada.
No início é só empolgação. A saída é dos boxes e o S do Senna é uma descida animal, depois entra na reta oposta que embora seja grande, é bem plana. No final da reta oposta tinha a marcação do KM 1, nesse ponto eu vi que tinha feito em 5 minutos o quilômetro. No caso eu parei com a empolgação e me concentrei em fazer a minha meta. Fim da reta oposta tem mais um descidão (e várias marcas de pneu, inclusive uma derrapagem saindo da pista que só pode ser do Rubinho, hehehe). Começa o laranjinha, primeira subida do circuito. Nessa hora comecei a me esforçar um pouco mais. É uma subida bem grande em curva, no final da subida tem a placa de 2KM e você pensa, pqp, ainda tem 3 KMs pela frente). A parte mista do circuito é tranquila, com subidas e descidas. Nesse ponto é interessante conhecer coisa do circuito que não se vê facilmente na televisão, como por exemplo, uma pista de terra no estilo off-road, com rampas, barro, etc, e também um lago bem no meio do circuito (agora eu entendi porque tem uma curva que chama curva do lago).
Fim da junção e ai começa o pesadelo. Eu me lembro até agora que eu olhei para a direita e ví um morro do meu lado, era o início da subida!!! Nesse ponto você ainda está no KM3.
O interessante que você vê bastante gente andando e lá em cima tinha uma ambulância de prontidão, eu pensei: pelo menos até a ambulância eu chego. Começa a subida e meu ritmo vai diminuindo, diminuindo, diminuindo e eu penso: meu preparo físico está uma mer**, correr 6km na lagoa do taquaral é MUITO mais fácil. Eu estava prester a andar quando um senhor da terceira idade me ultrapassou, bom, isso feriu meu orgulho e fez eu continuar
A subida é insana e quando você acha que está terminando, você olha uma placa de 4km. Isso é o início da “reta”. Reta entre aspas, pois depois de 4km e uma subida monstro, aquilo está longe de ser uma simples reta. Nesse ponto você já está de frente com os boxes, paddock e arquibancada. Dá para ver o grid de largada e as marcas dos pneus também, além das luzes de largada. Embora você esteja cansado, anima um pouco porque você passa na frente da galera.
No traçado da maratona, você tem que ir até o final da reta e voltar até a entrada dos boxes, esse “pequeno” trajeto tem 1KM.
Após isso são os 300 metros finais. Para ficar mais divertido, esses 300 metros são em subida (já que a entrada dos boxes é uma subida). Nesse ponto eu usei as últimas forças para um sprint final. Não pensando em melhorar meu tempo, pelo contrário, para parar de correr o mais rápido possível.
Algumas coisas engraçadas aconteceram no meio da prova, como por exemplo, o asfalto cheio de gatorade que o pessoal derrubava no KM 3. Isso fazia com que o tenis ficava colado no chão. Outro detalhe foi o meu número da camisa que caiu no meio da prova, ai eu fiquei correndo segurando o número.

Resumindo: foi divertido porém bastante cansativo. Sinceramente não garanto que eu vá fazer uma insanidade dessa novamente, ja que correr não é algo divertido (diferente de futebol e tennis).

October 10th, 2009  | Tags: ,

As you should know, in JSF 1 the AJAX wasn’t default. To use AJAX we had to use an external component, such as Richfaces (ajax4jsf), IceFaces, etc. This raises some drawback, because you cannot use both components in the same project.
However, in version 2, the AJAX API comes by default. If you’re familiar with ajax4jsf, you’ll fee comfortable to use the AJAX API in JSF 2.0.Also, the JSF team promisses that you’ll be able to use external AJAX API, such as YUI, JQuery, etc, in JSF smoothly. Check it out this topic: http://weblogs.java.net/blog/driscoll/archive/2009/08/using_the_yui_c_1.html
Let’s create a simple example using our previous example that has been written here. Please, go to the previous post and download the example.

How the example works

In the previous example we had 2 JSPs and 1 ManagedBean. The principal.xhtml had a form with one field (name). A submit button calls the managed bean and this name attribute was converted to upper case. Finally, the success.xhtml showed the result.
Now, let’s use only the principal.xhtml file. It will have the form and then will show up the result.

Changing the principal.xhtml page

The first thing to do is setup the javascript library into page. To do that, simple add the following in the head content.

<h:outputScript name="jsf.js" library="javax.faces" target="head" />

Another change is in the h:form tag. Add the prependId=”false” attribute.
Note: All fields must have the id attribute setup. As you should know, AJAX looks for those IDs to make the request.

Adding AJAX call

So far we changed the principal.xhtml file to be able to make AJAX call, but where is the call itself?
It is done through a tag called f:ajax. This tag can be inserted into components, such as h:commandButton to make an ajax call.
So, let’s create a commandButton and add the AJAX functionality for it.

        	<h:commandButton value="Ajax Button" action="#{helloWorld.ajaxCall}">
        		<f:ajax event="action" execute="@form" render="out"/>        		
        	</h:commandButton>

Some important notes: The h:commandButton is common. It has a value and an action call. It could have other events, such as: onclick, onblur, etc.
Inside the button we have the f:ajax tag. Its event attribute tells to JSF with event will be called, in our example the action event. Other events, such as onclick can be used.
The execute attribute tells with data should be sent do the server. The @form value tells that all the form should be sent.
Finally, we have the render attribute. In this render we tell to JSF with component will be updated after the call.
Now, we just need to add our h:outputText component.

<h:outputText value="#{helloWorld.name}" id="out" />

After those changes, our entire principal.xhtml looks like:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!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:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
	<h:outputScript name="jsf.js" library="javax.faces" target="head" />
</h:head>      
<h:body>
    <f:view>
        <h2><h:outputText value="This is our first JSF 2.0 example" /></h2>
        <h:form prependId="false" id="form">
        	Name: <h:inputText value="#{helloWorld.name}" id="name" /><br />
        	<h:commandButton action="#{helloWorld.doSomething}" value="Something is gonna happen" /><br />
        	<h:commandButton value="Ajax Button" action="#{helloWorld.ajaxCall}">
        		<f:ajax event="action" execute="@form" render="out"/>        		
        	</h:commandButton> 
        	<h:outputText value="#{helloWorld.name}" id="out" />        	
        </h:form>        
    </f:view>
</h:body>
</html>

Note: We kept the old button there, thus you can have both example in the same project.

Chaning the ManagedBean

If you look at the AJAX Button, you’ll see that its call an ajaxCall method. So, let’s implement it into ManagedBean.
Open the HelloWorldMBean.java class and add the following method:

	public void ajaxCall() {
		name = name.toUpperCase();
	}

Note: the method doesn’t have a return. That’s simple, huh?

Running the code

After that, you can run the project, type something and click on AJAX Button. You’ll realize that a AJAX call was performed because only the result is in upper case, not the value in the field.

Conclusion

Certainly the JSF 2.0 brings great news and native AJAX support is one of them. Who knows in the future, we can use multiples AJAX components in our single project. Now you already know how to use AJAX support, try out combine it with other AJAX frameworks, such as YUI or JQuery.

If you have any comment, question or feedback, please, let your message below.

October 2nd, 2009  | Tags:

JSF 2.0 specification has already been approved, however its official version is gonna be released with JEE 6.
Although its stable version has not been released, we can get started with some examples and get familiar with the new changes, by the way, a lot of changes.
If you’re interesting about JSF 2.0 and would like to test an example, this post may be useful for you.

Creating the web project

The first thing to do is creating a web project. As usual, we’re going to use Maven to do that. Type the following onto console.

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

After that, edit the pom.xml file and add the content 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>com.jairrillo</groupId>
	<artifactId>JSF2FirstExample</artifactId>
	<packaging>jar</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>JSF2FirstExample</name>
	<url>http://maven.apache.org</url>
	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.0.2</version>
				<configuration>
					<target>1.6</target>
					<source>1.6</source>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.7</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>

Note: We didn’t setup the JSF’s libraries. Unfortunately the JSF 2 JAR files aren’t within the maven repository yet. We’ll copy them yourself.

Downloading JSF 2.0

Go to the official java server faces page and there download the lastest version. http://java.sun.com/javaee/javaserverfaces/. When I wrote this topic, the latest version was the mojarra-2.0.0-SNAPSHOT-binary version.
Probably you’re going to download a .zip file. After extract it, copy the jsf-api.jar and jsf-impl.jar to the project/src/main/webapp/WEB-INF/lib.

Modifying the XML

We must change the web.xml file and tell to the project that we’re going to use JSF 2.0. To do that, simply edit the web.xml file and add the following entries:

	<servlet>
		<servlet-name>Faces Servlet</servlet-name>
		<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
	</servlet>
 
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>*.jsf</url-pattern>
	</servlet-mapping>

That’s all about setting up, but what about the faces-config.xml? That’s a good news, no longer the faces-config.xml is needed!!!
Now we can register a managed bean through annotation and use convention over configuration for navigation. JSF 2.0 is much easier than its old version.

Coding the project

It’s time to have fun, let’s coding. But before get started, let’s understand our application. It is a simple application, it has 2 pages (principal and success) and one managed bean. The principal page has a form with one field. It calls the managed bean and then the success page is opened. Success page can open the principal page directly, no navigation rule is needed.

Changing the current index.jsp file

When we had used the webapp archetype to create the project for us, a index.jsp file had also been created. Edit it and put the following content:

<html>
  <body>
    <jsp:forward page="principal.jsf" />
  </body>
</html>

Now, let’s create a new file. Its name should be principal.xhtml. Here we’ve got a new feature. By default, JSF 2 has facelets as engine, therefore we’re using the xhtml extension. The content of the principal.xhtml is:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!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:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets">
<h:body>
    <f:view>
        <h2><h:outputText value="This is our first JSF 2.0 example" /></h2>
        <h:form>
        	Name: <h:inputText value="#{helloWorld.name}" />
        	<h:commandButton action="#{helloWorld.doSomething}" value="Something is gonna happen" />
        </h:form>        
    </f:view>
</h:body>
</html>

Note: We’ve got a new tag there!! h:body. JSF 2.0 brings new tags, such as: h:body, h:head, h:link, etc.
Nothing special in the file above. We’ve got a simple form with one field. This field uses the managed bean helloWorld and it is binding with the name attribute. Now, let’s create/implement this ManagedBean.

Creating the ManagedBean

By default, the folder src/main/java is not created by this maven archetype (honestly, I have no idea why), therefore, let’s create it ourself.
After that, create a HelloWorldMBean.java class with the following content:

package com.jairrillo.mbeans;
 
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
 
@ManagedBean(name="helloWorld")
@RequestScoped
public class HelloWorldMBean {
 
	private String name;
 
	public String doSomething() {
		name = name.toUpperCase();
		return "success";
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

Stop now, take a breath and let’s analyse three lines of the code above.
First of all, look at the @ManagedBean annotation. This is the annotation responsible to register the MBean. If you have already used JSF 1.2 + Spring, this annotation is not new. Also, we have a @RequestScoped annotation. You can guess there are other annotation for the other different scopes as well.
Check the return of the doSomthing method. It returns a String with the name success, which means the JSF 2.0, through convention over configuration, looks for a success.xhtml page and try to open it. That’s awesome, huh?

Creating the success.xhtml

Finally, create a success.xhtml file and put the content:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!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:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets">
<h:body>
    <f:view>
    	<h2><h:outputText value="Success page"/></h2>
    	<h:outputText value="Your name in uppercase is: "/>
    	<h:outputText value="#{helloWorld.name}" /><br />
    	<h:link value="Back do Principal" outcome="principal" />
    </f:view>
</h:body>
</html>

Stop again. What does h:link do? It’s another new feature from JSF 2.0. Different than its version 1, that all requests were POST, with JSF 2 we can use GET instead. h:link creates a simple a href on the page.

Running the application

If you reach this point, you will be able to run the application. I have tested in Tomcat 6 and Glassfish v2 and worked in both.

Conclusion

Certainly JSF 2 is easier than version 1. The JCP learned with the mistakes from version 1 and created a new version better. No doubt that this new version is gonna be more productive and funny.

This topic ends up here. You can download the First Example project HERE.
If you have any comment/question or feedback, leave your message below.

Thanks guys.

August 21st, 2009  | Tags: ,

Se você, assim como eu, utiliza dual-boot em sua máquina (provavelmente Linux e Windows) certamente deve usar o GRUB para o gerenciamento do boot.
O GRUB funciona muito bem, porém na sua configuração default, a cada atualização do Kernel do Linux uma nova opção de boot aparece na inicialização do computador. Isso acaba sendo inviável quando você tem várias atualizações.
Uma forma de “remover” as atualizações antigas é através da configuração do GRUB. A maneira mais fácil é editar diretamente o arquivo menu.lst que fica no diretório boot/grub. A dica foi retirada do seguinte post: http://brazovsky.blogspot.com/2007/04/configurar-o-grub-no-ubuntu.html

Fazendo o backup

A primeira coisa que devemos fazer é um backup do menu.lst original. Para isso, digite na shell o seguinte comando:

sudo cp /boot/grub/menu.lst /boot/grub/menu.lst_backup

Alterando as opções do GRUB

Após o backup, vamos editar o arquivo através do comando:

sudo gedit /boot/grub/menu.lst

Com o arquivo aberto, vá até o fim do mesmo. Lá iremos encontrar, após a sessão “End Default Options”, as opções do GRUB. Podemos apagar todas opções e deixarmos apenas a última, conforme exemplo abaixo:

## ## End Default Options ##
 
title		Ubuntu 9.04, kernel 2.6.28-15-generic
uuid		6e8438cb-be6c-42bb-8898-157d69148f51
kernel		/boot/vmlinuz-2.6.28-15-generic root=UUID=6e8438cb-be6c-42bb-8898-157d69148f51 ro quiet splash 
initrd		/boot/initrd.img-2.6.28-15-generic
quiet
 
title		Ubuntu 9.04, kernel 2.6.28-15-generic (recovery mode)
uuid		6e8438cb-be6c-42bb-8898-157d69148f51
kernel		/boot/vmlinuz-2.6.28-15-generic root=UUID=6e8438cb-be6c-42bb-8898-157d69148f51 ro  single
initrd		/boot/initrd.img-2.6.28-15-generic
 
title		Ubuntu 9.04, memtest86+
uuid		6e8438cb-be6c-42bb-8898-157d69148f51
kernel		/boot/memtest86+.bin
quiet
 
### END DEBIAN AUTOMAGIC KERNELS LIST

Pode salvar o arquivo e pronto, na próxima inicialização apenas 1 opção do Linux será visível.

Outras opções importantes

Como você pode ver nesse arquivo, existem várias opções que podemos configurar. Dentre elas vou destacar três que eu julgo importantes.
howmany: Por padrão ela vem comentada, porém você pode tirar o comentário e configurar quantas versão visíveis vão aparecer no GRUB. Eu sempre deixo 2, pois após a atualização do Kernel, se der algum problema no Kernel novo, eu tenho ainda a opção de voltar para o Kernel antigo.
default: Padrão é 0. Isso significa que o Linux será o padrão na tela do GRUB. Você pode mudar esse valor. Por exemplo: você deseja que a partição default seja o Windows, portanto, altere esse valor para 1.
timeout: Padrão é 10, ou seja, 10 segundos que o GRUB vai esperar até ele executar a opção padrão.

Bom pessoal, essa é uma dica simples porém útil para quem trabalha com dual-boot na máquina. Qualquer dúvida ou comentário, podem deixar sua mensagem abaixo. Até mais

August 19th, 2009  | Tags: , ,

Assim como a VMWare, o Sun VirtualBox também gera problemas após mudança de Kernel do Linux. Na verdade, após a mudança do Kernel, suas máquinas virtuais não irão mais funcionar.
Felizmente o processo para arrumar isso é simples. Basicamente você precisa reinstalar o VirtualBox. Nesse caso existem duas opções:

  1. Fazer novamente o download do VirtualBox, clicar duas vezes no arquivo .deb (se você estiver usando uma versão debian-like) e clicar no botão Reinstalar Pacote.
  2. Usar o comando abaixo para reconfigurar o pacote.
    sudo dpkg-reconfigure virtualbox-3.0

Após isso, pode usufruir novamente das suas máquinas virtuals.

Espero que esse post curto seja útil.

August 16th, 2009  | Tags: , , ,

One of the most interesting feature from JEE is the security behavior. If you’re using JEE, you do not need to worry about authentication and authorization, there is a security specification that talks about this issue.
However security is from the official JEE specification, the authentication portion varies from application server to application server. In this topic, I’m going to show how to setup authetication on Glassfish and Netbeans. Fortunately it is a simple and easy task, thanks glassfish/netbeans team.

Roles, User and Groups

Before get started, let’s understand the difference among roles, user and groups. All JEE Security must contain these three elements.
In general speaking, roles belong to the application scope. In the application we setup which functionalities can be accessed using a certain role. E.g.: administrator role has the permission to access the admin.jsp page.
User refers the user that will log in the system. The user information can be storaged in a file, JDBC or even in a LDAP server.
Groups is the group of a user. This group is associated with a role. E.g: the admin group is associated with the administrador role.

Authentication Realms

An authentication realm, also called a security policy domain or security domain, is a scope over which the Enterprise Server defines and enforces a common security policy. Enterprise Server is preconfigured with the file, certificate, and admin-realm realms. In addition, you can set up ldap, jdbc, solaris, or custom realms. An application can specify which realm to use in its deployment descriptor. If the application does not specify a realm, Enterprise Server uses its default realm (file).

Adding an User into the File Realm

First of all, let’s start up the glassfish server. After that, access its administrator screen, clicking on http://localhost:4848. The default user/password is admin and adminadmin.

To add an User, on the left menu, click on Configuration -> Security -> Realms. After that, click on file realm.

On this screen, click on Manage Users button and then New button.
Add a new user called test and password test123. Keep the admin as group list.

We just added an user into the File Realm.

Creating a Web Application

To test the security we need an application. Let’s create a web application on netbeans for a simple example of how to use security.
Within Netbeans, go to File -> New Project. Choose Java Web and then Web Application.

Security Role mapping

As I said early, each application server has its own configuration for authentication. On glassfish, we must change the sun-web.xml file to map the roles. On Netbeans, double click on this file and its content will appear on screen. This file is located into Web Pages -> WEB-INF directory.
Within sun-web.xml file, go to Security tab. There, click on Add Security Role Mapping button and type the following:

  • Security Role Name: administrator
  • Group name: admin


Save this file and go to the next step.

Adding the authentication

Now, double click on the web.xml file and go to the Security tab. Expand the Login Configuration and select the BASIC. Also, in the realm name, put the realm you’re using, in our case: file.

Add the administrator in the Security Roles. You must change the Security Contraints like the screenshot below.

According to the configuration above, if the user tries to access the admin.jsp page, a pop-up with user and password must appear.

Creating an admin.jsp page and changing the index.jsp

Create a simple admin.jsp page (its content doesn’t matter). Also, change the index.jsp source code and add a link to the admin.jsp page. After that, run the application.
The index.jsp page should open properly however when you click on link to access the admin.jsp, a pop-up should appear, like image below:

if you enter the correct user/password, then the admin.jsp will be accessed.

Conclusion

Many people have doubt when they’re dealing with JEE Security, however the process is simple and flexible. You can add/remove/modify roles and access without change the underlying code. Also, you can link the roles with the JDBC or LDAP users.
As you can see in this topic, Glassfish and Netbeans have a great graphical tools for these configurations.

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

July 24th, 2009  | Tags:

Entre os dias 27 à 31 de Julho eu e mais 3 colegas de trabalho vamos ministrar um curso de 40 horas sobre Java para WEB. Na verdade, o curso completo é de 120 horas onde além de Java, outros assuntos como banco de dados, orientação a objetos, servidor de aplicação, modelagem usando UML, etc, são abrangidos. Inicialmente irei ficar responsável por Java para WEB, que envolve JSP, Servlet, alguns padrões de projetos como DAO, MVC, Singleton e boas práticas de desenvolvimento.
O curso será ministrado diretamente para professores das ETECs do estado de São Paulo, com intuito deles propagarem esse conhecimento para seus alunos.
A IBM, provedora do curso, está fazendo essa iniciativa à alguns anos com objeto de treinar as pessoas para o mercado de trabalho (claro, usando as ferramentas dela, tais como: RAD, Websphere, DB2, Mainframe, cia) e já colheu excelentes resultados, como por exemplo, contratação de alguns ex-alunos para a sua grade de funcionários.
É uma excelente iniciativa para ambos os lados e quem tem a ganhar somos nós, especialistas em tecnologia.
Não preciso nem dizer que semana que vem estarei bem atarefado, pois além desse curso, eu tenho meus outros projetos para continuar.

July 19th, 2009  | Tags: , ,

In all projects we supposed to have three kinds of testing: Unit Testing, Integration Testing and Functional Testing.
Unit Testing is about the smaller piece of a software, the method. In this testing, we can use tools such as: JUnit, TestNG, EasyMock, JMock and so on.
Functional testing is a little harder to implement, however tools like Selenium let our life easier. Usually I suggest the web team to get started their job thinking about Selenium testing, in this way, they build the view tier using propers ids, components and so on.
Whether unit testing is responsible for single methods, what about the integration between them? what about the integration between the software and external resources such as databases and files? For this issue, we’ve got the integration testing.
Spring team thinks like mysefl: Integration testing is important and it should be performed without a container. but what does it mean? Many tools for integration testing, like Cactus, requires the container running to perform testing, even a single testing. In my experience, I notified that start up a container just to perform testing is painful.
Spring has its own spring-test module that eliminates the needed to run integration testing with the container online. Thus, you can test your bean, service layer and even DAO layer without the container. This post is gonna show up an example about integration testing with spring framework. You can reach more details about it in the spring official documentation.

Our example – Login application


Almost all applications have a login system. Let’s use this approach as example. In our application, we’ll have the JSF (JSF page + managed bean) in the view tier, application service class in the business tier and the dao class in the integration tier. We’re gonna use Hibernate as persistence layer and its entities as business object.
The managed bean is gonna be called: LoginMBean. It will have an instance of LoginService (our service) and the DAO is gonna be injected into the LoginService. Also, the transaction demarcation is gonna be inside the application service. Finally, all of these components are gonna be mapped with annotations. Thanks Spring 2.5 for provide us annotations.
Note: It’s not the best architecture for all applications, but it looks good for our example.

Downloading the project

I’ve created a project using maven webapp archetype. It is the easiest way to create a project, as well as add the required dependencies. Make sure you have Maven installed and then download the project here.
Unzip the project and then you can open it either with Eclipse (using import -> Existing project into workspace) or Netbeans (open project). Below following some details:

  • The JUnit version used is 4.4. If you try the version 4.5 or 4.6, youll get exception. It’s a known bug that spring team is fixing in version 3.0
  • LoginService is annotated with the @Service annotation
  • We’re using the GenericDAO provided by Hibernate. It’s annotated with @Repository annotation.
  • The injection are done using the @Autowired annotation
  • In the applicationContext.xml file has only the SessionFactory and the transaction demarcation
  • The application uses HSQL database. For testing purpose, we’re using the memory approach

Creating the Integratin Testing class

By default, the testing in maven are located into src/test/java folder. In the project you’ve downloaded, I left the LoginMBeanIntegrationTesting already done. Below following its code and the explanation.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/applicationContext.xml"})
/**
 * @author Jair Rillo Junior
 */
public class LoginMBeanIntegrationTest {	
	/*
	 * ManagedBean component. 
	 */
	private LoginMBean loginMBean;	
	/*
	 * Service object. It's gonna be injected into ManagedBean
	 */
	@Autowired
	private LoginService loginService;
	@Before
	public void setUp() throws Exception {
		//Start LoginMBean
		loginMBean = new LoginMBean();
		//Inject LoginService
		loginMBean.setLoginService(loginService);
		//By default, insert a sample user into database
		User user = createUser("jair","test123");
		//Insert the user
		loginService.insertUser(user);
	}
	@After
	public void tearDown() throws Exception {
		loginMBean = null;
	}	
	/**
	 * Test a login with correct information
	 * @throws Exception
	 */
	@Test
	public void testLoginSuccessful() throws Exception {
		//Create a user which exists into database
		User user = createUser("jair", "test123");
		//Inject the User into ManagedBean.
		//THis is the same behavior of JSF
		loginMBean.setUser(user);
		//Test if the return is "success"
		Assert.assertEquals("success", loginMBean.doLogin());
	}	
	/**
	 * Test a login with incorrect information
	 * @throws Exception
	 */
	@Test
	public void testLoginError() throws Exception {
		//Create a user with wrong password
		User user = createUser("jair", "test1234");
		//Inject the User into ManagedBean.
		//THis is the same behavior of JSF
		loginMBean.setUser(user);
		//Test if the return is "success"
		Assert.assertEquals("error", loginMBean.doLogin());
	}	
	private User createUser(String username, String password) {
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		return user;
	}
}

You can run the code and hopefully a green screen will show up.

On line 1 and line 2 above are located the resources that Spring provide us. In the first line, we tell to Spring to use its class runner. The second one is the location where is our applicationContext.xml. Note: Spring will search for this file into the classpath. If it is in another location, no problem, you can use the file schema, e.g: @ContextConfiguration(locations={“file:/src/main/java/webapp/WEB-INF//applicationContext.xml”})
If you check the code done (ManagedBean, Service and DAO) you will see how the resources are injected. In a normal integration testing, we should inject them ourself, however using the spring class runner, the resources are injected for itself.

Conclusion

Using this approach, you can run integration testing in a faster way. If you need the container, then move out the testing to the functional testing area.
As we can see in this post, making integration testing with Spring is really simple and efficient. If you’re using Spring in your project, do not hesitate to make your integration testing using Spring-Test module.
Thanks spring team for this great job.

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

July 10th, 2009  | Tags:

Português: Como estava dificil manter ambos os blogs (português e inglês) eu resolvi juntar todas as informações em um único blog. Nessa URL você irá encontrar posts escrito em português e outros em inglês. No geral, assuntos técnicos serão tratados em inglês, assim como outros assuntos em português. Se você estiver procurando pelos antigos posts, você pode olhar aqui: http://www.jairrillo.com/old_blog/
English: It was hard to keep both blogs (portuguese and english) and I’ve decided to merge all information in a unique blog. In this URL you’re gonna find entries written in portuguese and english. In general, technical issues are gonna be written in english, as well as any other issue are gonna be written in portuguese.

July 9th, 2009  | Tags: , , ,

One of the most interesting thing in JSF is the capability to create custom components and use them anywhere. With facelets the creating is even easier. In this topic, I’ll show you how to create a component and use it in your JSF project.

Creating the project

First of all, let’s create a simple project that will contain our component. We’re going to use Maven to do that (if you aren’t familiar with Maven, check it out its official site, as well as this blog for more information). Let’s use the quickstart archetype to create the project. Simply type the following:

mvn archetype:create \
  -DarchetypeGroupId=org.apache.maven.archetypes \
  -DgroupId=com.jairrillo.component \
  -DartifactId=MyJSFComponent

A directory MyJSFComponent is gonna be created.

Adding required JAR files

After the project has been created, we need to add the required JAR files. Fortunately it is an easy task with Maven. We simply need to change the pom.xml file. Below following a complete file.
pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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>com.jairrillo</groupId>
    <artifactId>MyJSFComponent</artifactId>
    <packaging>jar</packaging>
    <version>0.1</version>
    <name>MyJSFComponent</name>
    <url>http://maven.apache.org</url>
    <!-- Using Java version 1.6 -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.0.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <!-- SUN and JBoss' repositories -->
    <pluginRepositories>
        <pluginRepository>
            <id>maven.java.net</id>
            <name>Java.net Maven2 Repository</name>
            <url>http://download.java.net/maven/2</url>
        </pluginRepository>
        <pluginRepository>
            <id>repository.jboss.com</id>
            <url>http://repository.jboss.com/maven2/</url>
        </pluginRepository>
    </pluginRepositories>
 
    <dependencies>
	<!-- JSF -->
        <dependency>
            <groupId>javax.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>1.2_12</version>
        </dependency>
        <dependency>
            <groupId>javax.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>1.2_12</version>
        </dependency>
        <!-- JUnit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.6</version>
            <scope>test</scope>
        </dependency>
        <!-- Servlet and JSP APIs -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
        </dependency>
    </dependencies>
</project>

Basically, in the POM.xml we setup the SUN’s and JBoss’ repositories, the JARs from JSF, Servlet and JSP APIs. Those files are required for our project.

Creating the Component itself

There will be only one Java class in our example. It’s gonna be a new error message component that will display the messages within a border. (It’s a dummy example. This behavior can be achieved without creating a new component, but if you understand the process, you can create other useful components).

Below following the class. Create it into the component package. Like below:

package com.jairrillo.component;
 
import java.io.IOException;
import java.util.Iterator;
 
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
 
/**
 * @author Jair Rillo Junior
 */
public class ErrorMessageComponent extends UIComponentBase {
 
    public static final String COMPONENT_TYPE = "com.jairrillo.component.errorMessage";
    public static final String RENDER_TYPE = "com.jairrillo.component.ErrorMessageComponent";    
 
    /**
     * constructor for the component.
     */
    public ErrorMessageComponent() {
        super();
        setRendererType(null);
    }
 
    @Override
    public String getFamily() {
        return COMPONENT_TYPE;
    }
 
	@SuppressWarnings("unchecked")
	@Override
    public void encodeBegin(FacesContext context) throws IOException {
        Iterator iter = context.getMessages();
        //check if there are messages
        if (iter.hasNext()) {
        	StringBuffer messages = new StringBuffer();
            ResponseWriter writer = context.getResponseWriter();
            //going through all messages
            while (iter.hasNext()) {
                FacesMessage msg = (FacesMessage) iter.next();
                messages.append(msg.getSummary() + "<br />");
            }
            //print out the result
            writer.write("<div style='border: 1px solid black; width: 100%;'>");
            writer.write(messages.toString());
            writer.write("</div>");
        }
    }
    @Override
    public void encodeEnd(FacesContext context) throws IOException {
        super.encodeEnd(context);
    }
}

As you can see above, the encodeBegin method has the major implementation.

Registering the component

Besides the Java class (component) we need to register it in the faces-config.xml and taglib files. To do that, first you must create a resource directory. Its path is /src/main/resources. Also, create a META-INF folder within it. Put the files below within META-INF folder.

faces-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee" 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">
    <component>
        <component-type>com.jairrillo.component.errorMessage</component-type>
        <component-class>com.jairrillo.component.ErrorMessageComponent</component-class>
    </component>
</faces-config>

error_message-component.taglib.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE facelet-taglib PUBLIC  
"-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN"  
"http://java.sun.com/dtd/facelet-taglib_1_0.dtd">  
 
<facelet-taglib>  
    <namespace>http://my-own-component</namespace>
    <tag>  
        <tag-name>errorMessage</tag-name>
        <component>  
            <component-type>com.jairrillo.component.errorMessage</component-type>
            <renderer-type>com.jairrillo.component.ErrorMessageComponent</renderer-type>
        </component>  
    </tag> 
</facelet-taglib>

The configuration is over. Now simply package the component in a JAR file. In the console, type: mvn package and then the MyJSFComponent.jar is gonna be created into target directory.

Using it in a JSF/Facelets project

Now you can use the component in any JSF/Facelets project. Simply import the jar file (copying into WEB-INF/lib directory) and use the namespace (http://my-own-component) and taglib () into the xhtml file. It’s done!!!

Conclusion

Creating new component in JSF/Facelets is really simple. You can create many custom components and use them in varies projects. It is a great asset.

You can download the source code here. If you have any question or comment, fell free to let the message below.
I hope this topic be useful for anyone.

TOP