February 28th, 2010  | Tags: , , , ,

This is the second part of a series of posts about JPA 2 and Netbeans 6. This series has the goal to show up how to get started with JPA 2, as well as creating complex model using relationship and inheritance.
Part two is gonna use the same example than Part 1, but now we’re going to work on a web environment.

Requirement

  • Understand JPA concepts - If you have no idea what JPA is, please google it first
  • Netbeans 6.8 and glassfish v3 installed
  • MySQL database installed - If you have another one, make sure you have the JDBC driver
  • Read Part 1 and have the database and POJO already created.

Creating the project within Netbeans

Let’s getting started through the project creation. Within Netbeans, go to File -> New Project -> Java Web -> Web Application. Choose a name, like JPAWebExample01 and Glassfish v3 as Server. On third screen, select JavaServer Faces and accept the default.

Note: don’t worry if you aren’t familiar with JSF. For this example we’ll focus on JPA only.

Creating the DataSource

Different than Stand-Alone application, in web application we could create a datasource to obtain and manage the database connection. This datasource lives in the Server, in our case, Glassfish.
Fortunately we can create it directly inside Netbeans in an easy way. Let’s do that now.
Similar than the post 1, let’s open the screen to create a entity class from the database. To do that, right mouse click on the project name and go to New -> Other -> Persistence -> Entity Classes from Database. On the new screen, you’re gonna see the Data Source field. Click on it and select New Data Source.

On the JNDI Name, fill up the field with the value jdbc/MySQL_jpatutorial. Database Connection select the previous connection you’ve done in Part 1. Click OK and the DataSource will be created.

Creating the Model and persistence.xml

After you have created the datasource, you should see the table products listed. Now, you can follow exactly the same step from Part 1 to create the persistence.xml and the model.

Creating a Manged-Bean

Our application uses JSF 2.0 and because of this we can create a Managed Bean to handle the requests coming from view. If you don’t know what Managed Bean is, think he is a Java class that handles requests from view. It is similar a Controller from MVC, but it is directly binding with the view.
In our example, the ManagedBean will obtain the EntityManager and call the NamedQuery.
To create a ManagedBean with Netbeans, follow the following steps:
Right mouse click on the project’s name New -> Other -> JavaServer Faces -> JSF Managed Bean. In the Class Name put JPATutorialBean and the Package put mbeans.

In th JPATutorialBean.java, let’s add a method called listAllProducts. The content looks like:

package mbeans;
 
import entities.Products;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
 
@ManagedBean(name="jpaTutorialBean")
@RequestScoped
public class JPATutorialBean {
 
    @PersistenceContext
    private EntityManager em;
 
    public void listAllProducts() {
       List<Products> listProducts = em.createNamedQuery("Products.findAll").getResultList();
        for (Products product : listProducts) {
            System.out.println("Product: " + product.getDescription());
            System.out.println("Price: " + product.getPrice());
            System.out.println("---------------------------------------");
        }
    }
}

The method listAllProducts has no mistery. It is similar than the first post. Simply create a named query and prints out the result. However, pay attention on the lines:

    @PersistenceContext
    private EntityManager em;

We’ve used an annotation called @PersistenceContext. Different than StandAlone application, where we had to obtain a EntityManagerFactory and after that create the EntityManager, in a web based application, the container is responsible to inject the EntityManager for us. Really simple, doesn’t it?

Editing the index.xhtml

How can we call the method listAllProducts from ManagedBean? We can do that editing the index.xhtml and creating a link to access this method. Edit the current index.xhtml and add the following:

<?xml version='1.0' encoding='UTF-8' ?>
<!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">
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>
        Hello from Facelets
        <h:form>
            <h:commandLink action="#{jpaTutorialBean.listAllProducts}">
                <h:outputText value="List All Products" />
            </h:commandLink>
        </h:form>
    </h:body>
</html>

The code above is HTML and JSF stuff. Look at the h:commandLink and you’re gonna see where we bind the link with the method. JSF also makes our life easier.

Running and Testing the code

Now all changes are done, right mouse click on the project and select the Run option. A new page is gonna be opened in your browser and then click on the link.
Look at Netbeans console and you should see an output like below:

INFO: Product: product 1
INFO: Price: 100.0
INFO: ---------------------------------------
INFO: Product: product 2
INFO: Price: 200.0
INFO: ---------------------------------------
INFO: Product: product 3
INFO: Price: 200.5
INFO: ---------------------------------------

Conclusion

Doesn’t matter if you’re in a standalone or web application, the model (entity) is gonna be the same and the code to handle the JPA also, the biggest diffrence is the way to obtain the EntityManager. In a web application, the container is responsible to inject the EntityManager for us.

In the next topic we’re going talk about the strategies to retrieve values from JPA, such as: NamedQuery (already used), JPAQL and the newest feature, Criteria.

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

February 23rd, 2010  | Tags: , , , ,

This is the first part of a series of posts about JPA 2 and Netbeans 6. This series has the goal to show up how to get started with JPA 2, as well as creating complex model using relationship and inheritance.
This part one is going to show up the steps to create your first application that access the database using JPA 2 (Stand alone application). Using Netbeans 6, this process is easy and takes less than five minutes.

Requirement

  • Understand JPA concepts - If you have no idea what JPA is, please google it first
  • Netbeans 6.8 and glassfish v3 installed
  • MySQL database installed - If you have another one, make sure you have the JDBC driver

Preparing the database

Before we get started with Netbeans, let’s prepare our database. The instructions below are regarding MySQL, but if you’re using another database, you may need to change the scripts to work out.
Firstly, connect to your database:

mysql -u root -p

Then, create the database and select it. Let’s call it as “jpatutorial”

create database jpatutorial;
use jpatutorial;

Now, run the script below. Basically it creates a table called “products” and insert three products by default.

create table products (id int not null auto_increment, description varchar(40), price double, primary key(id));
insert into products (description, price) values ('product 1',100); 
insert into products (description, price) values ('product 2',200); 
insert into products (description, price) values ('product 3',200.50);

Creating the project within Netbeans

Now the “magic” starts. Open up Netbeans and create a simple Java program called “JPAExample01″. Netbeans also creates a “Main” class for you.

Creating the Model and persistence.xml

After the project is created, right mouse click on it and go to New -> Other -> Persistence -> Entity Classes from Database. On next screen, select Database Connection -> New Database Connection and type the information from your database. After that, the table “products” should appear on the screen.

Select “products” and click on “Add” and then “Next”.
On third screen, you must create our “Persistence Unit”. Click on Create Persistence Unit… button. Now, we must select the provider we want. By default, Netbeans brings the EclipseLink, but you’re free to change it. Also, you can change the Unit name and table generation strategy, but let’s keep the default so far.

The persistence.xml file has created, now click next until the end and finish the process (you can accept all the default options).
Take a look at the Project and you’re gonna see a new folder called “META-INF” with the file persistence.xml and the file “Products.java” created.

Examining the Products.java

Usually a model is a simple POJO. With JPA, the POJO has annotations that define the primary key, columns, relationship and so on. Netbeans has already done these annotations for us. Open the Products.java and have a look.

@Entity
@Table(name = "products")
@NamedQueries({
    @NamedQuery(name = "Products.findAll", query = "SELECT p FROM Products p"),
    @NamedQuery(name = "Products.findById", query = "SELECT p FROM Products p WHERE p.id = :id"),
    @NamedQuery(name = "Products.findByDescription", query = "SELECT p FROM Products p WHERE p.description = :description"),
    @NamedQuery(name = "Products.findByPrice", query = "SELECT p FROM Products p WHERE p.price = :price")})
public class Products implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Column(name = "description")
    private String description;
    @Column(name = "price")
    private Double price;

Attention: The netbeans has already generated some NamedQueries for us too, Thanks Netbeans team :)

Running and testing the JPA

To test JPA, we must a EntityManager. In a stand-alone application, to get it, we must a EntityManagerFactory. Let’s change our Main class and initialize a EntityManager and call a simple NamedQuery. The Main class looks like:

package jpaexample01;
 
import entities.Products;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
 
public class Main {
 
    public static void main(String[] args) {
        EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("JPAExample01PU");
        EntityManager em = emFactory.createEntityManager();
        List<Products> listProducts = em.createNamedQuery("Products.findAll").getResultList();
        for (Products product : listProducts) {
            System.out.println("Product: " + product.getDescription());
            System.out.println("Price: " + product.getPrice());
            System.out.println("---------------------------------------");
        }
    }
}

Pay attention on main method. We get a EntityManagerFactory, then an EntityManager, we call a NamedQuery already done and finally we iterate over the list and print out the description and price of the product.
Before run the code, you must add the JDBC driver into the project’s classpath. To do that right mouse click on the project Properties -> Libraries -> Add Library -> MySQL JDBC Driver
Now you can run the application and if everything is fine, you are gonna see in the console:

Product: product 1
Price: 100.0
---------------------------------------
Product: product 2
Price: 200.0
---------------------------------------
Product: product 3
Price: 200.5
---------------------------------------

Conclusion

As you can see, Netbeans has a great support for JPA 2. You were able to create your first application in few minutes.

This post finishes here, in the next one we are going to talk about JPA 2 in a web environment. You’re gonna see the code is similar, but the way to obtain the EntityManager is different.
If you have any comment or question about this post, fell free to leave your message below.

February 21st, 2010  | Tags: , , ,

Sun VirtualBoxVirtualMachine is a reality nowadays. If you have a base operating system (called host) and want to use another one on the base (called guest), you can use a VM to do that.
Sun VirtualBox is a great free tool to do that in an easy and fast way. However, by default on Ubuntu, the USB doesn’t work properly. Inside the guest operating system, the USB is not accessible at all.
In this topic, I’ll show up how to setup Ubuntu to enable the USB on guest operating system. Fortunately it is straightforward and doesn’t hurt :)

Downloading and installing Sun VirtualBox

Downloading the Sun VirtualBox directly from its website.For Ubuntu, there’s a .deb file. Simply download it and double click on it install it. After that the VirtualBox is installed. Now, you can install the Operating system that you want.

Setup Ubuntu

If you have already run Sun VirtualBox, probably you notified that USB didn’t appear. It happens because you need to make some changes on Ubuntu. Let’s do that now.
First, open the terminal and type the following:

grep vboxusers /etc/group

Memorize the number that appear for you. In my example, the number is 121.

Now, go to System -> Administration -> Users and Groups. After that, click on “Change button” and enter your password.

After that, click on Manage Groups. Find and select the vboxusers and click on Properties button. On the screen, select your user and type the Group ID that you picked early.

The changes are done. Now restart the Ubuntu and in the next time you run VM, the USB are gonna appear for you.

PS: When you start the USB on guest machine, the USB port on host machine is closed and vice-versa.

This is a simple post but I hope it be helpful for anyone else. If you have any question or comment, fell free to leave your comment below.

February 12th, 2010  | Tags:

O meu último post no blog foi no dia 12 de Novembro de 2009, ou seja, exatos 3 meses sem escrever aqui.
Certamente os meses de Novembro, Dezembro e início de Janeiro foram os mais desafiadores dentro da IBM para mim. Tinhamos algumas atividades monstruosas para desenvolvermos em tempo recorde. Eu fiz o papel de liderar o time técnico e felizmente, graças ao grande trabalho do meu time (Gustavo Oliva, Victor, Gisele, Renato, Gustavo Castellano e Marcela), conseguimos atingir o objetivo com excelente qualidade.
Esse foi um dos motivos que não tive tempo para postar novidades no blog, mas isso não significa que nesse tempo eu não tenha acompanhado as novidades no mundo de TI.
Cheguei a fazer alguns exemplos do JSF 2.0 e JPA 2.0, a princípio gostei bastante de ambos. Dentro do projeto fiz algumas coisas com o Hibernate que nunca tinha feito antes, utilizei alguns design patterns que ajudaram muito no projeto, implantamos testes unitários úteis utilizando JUnit e EasyMock, enfim foram meses de pura tecnologia.
2010 começa e eu vou tentar ser mais ativo no blog. Alguns posts já estão na cabeça, mas ainda falta pique para iniciá-los. No próximo dia 22 eu tiro férias de 13 dias e isso certamente vai servir para carregar as pilhas e ter mais um ano cheio de desafios.
Uma coisa que já voltei a fazer com mais frequência é acessar o GUJ.com.br diariamente.
Esse ano vou voltar de fato estudar Ruby e Scala, duas grandes linguagens que eu abandonei um tempo atrás. Internamente na empresa será o ano de entregar o segmento 1 do projeto e também pretendo tirar a certificação interna de IT Specialist.
Enfim, 2010 será cheio de desafios, mas nós da área de TI sempre temos que arrumar tempo para estudar tecnologias novas e também compartilhar nosso conhecimento, seja através de blog, fórum, palestras, eventos, etc etc etc
Bom 2010 para todos.

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.

TOP