Archive for December, 2009

Alteração de feed RSS

Galera, a todos que utilizam o RSS para ver as novidades do meu blog, peço que por gentileza atualizem para os novos endereços:

Blog em português: http://feeds.feedburner.com/RodrigoLazotiBlog

Blog em inglês: http://feeds.feedburner.com/RodrigoLazotiBlog2

Fiz algumas mudanças no meu blog e agora ele está dividido em três partes, sendo um com o blog em português, uma outra com o blog em inglês e uma para meus aplicativos para iphone/ipod touch disponíveis na apple app store.

As urls ficaram assim:

http://www.rodrigolazoti.com.br/pt/
http://www.rodrigolazoti.com.br/en/
http://www.rodrigolazoti.com.br/iphone/

Também criei um página inicial para que o usuário possa escolher entre uma das três possibilidades. Esta página pode ser vista em:

http://www.rodrigolazoti.com.br/

Agradeço a compreensão de todos e que venha 2010.
:)

Testando JavaEE 6 com Glassfish e Eclipse

Neste post, vou mostrar algumas novidades do Java EE 6.
Eu vou usar os seguintes softwares:

Glassfish v3
Eclipse Galileo JEE Edition

Depois de instalá-los, vou criar um Dynamic Web Project no Eclipse chamado de FirstProjectJEE6:

Agora vou substituir o conteúdo do arquivo web.xml por este abaixo:

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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-app_3_0.xsd"
	version="3.0">
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

Para compilar nosso projeto, precisamos adicionar um jar externo chamado javaee.jar ao projeto (Build Path), o arquivo jar pode ser encontrado em [glassfish_directory]/glassfish/lib/javaee.jar

Criei também um script ant para fazer o deploy da nossa aplicação diretamente no glassfish. Este script deve ser salvo na raiz do projeto, salvei ele com o nome de build.xml. A seguir segue seu conteúdo:

<?xml version="1.0" encoding="UTF-8"?>
<project name="FirstProject JavaEE 6" basedir="." default="deploy">
	<property name="warfile" value="FirstProject" />
	<target name="create">
		<war destfile="${warfile}.war" webxml="WebContent/WEB-INF/web.xml" update="true">
			<classes dir="build/classes" />
			<fileset dir="WebContent">
				<exclude name="WEB-INF/web.xml" />
			</fileset>
		</war>
	</target>
	<target name="copy">
		<copy todir="/Users/rodrigolazoti/Programs/glassfishv3/glassfish/domains/domain1/autodeploy" overwrite="true">
			<fileset dir=".">
				<include name="*.war" />
			</fileset>
		</copy>
	</target>
	<target name="deploy">
		<antcall target="create" />
		<antcall target="copy" />
	</target>
</project>

Note que esse local:
/Users/rodrigolazoti/Programs/glassfishv3/glassfish/domains/domain1/autodeploy
Deve ser substituído por:
[your glassfish]/glassfish/domains/domain1/autodeploy

Agora, vamos codificar um pouco, primeiro vamos criar dois EJB’s usando um pouco da nova especificação.
Vou criar um EJB Stateless e um EJB Staleful, o stateful servirá apenas para representar o número de requisições feitas e o stateless servirá para retornar alguma mensagem para o usuário.

Esse é o código do EJB Stateless:

package br.com.rodrigolazoti.firstproject.service;

import javax.ejb.Stateless;

@Stateless
public class MyStatelessSessionBean {

	public String createMessage( String username ) {
		String message = "Hello World, ";

		if ( username != null && !"".equals( username.trim() ) ) {
			message += username + "!";
		}
		else {
			message += "stranger!";
		}

		return message;
	}

}

E este é o código do EJB Stateful:

package br.com.rodrigolazoti.firstproject.service;

import javax.ejb.Stateful;

@Stateful
public class MyStatefulSessionBean {

	private int amountOfrequests = 0;

	public int getAmountOfrequests() {
		return ++amountOfrequests;
	}

}

Note que em ambos EJB’s, não foi necessário criar interfaces locais ou remotas. :)

Com nossos EJB’s prontos, vamos criar um servlet para responder ao seguintes métodos http GET e POST.

package br.com.rodrigolazoti.firstproject.controller;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.rodrigolazoti.firstproject.service.MyStatefulSessionBean;
import br.com.rodrigolazoti.firstproject.service.MyStatelessSessionBean;

@WebServlet( name = "MyServlet", urlPatterns = { "/hello" } )
public class MyServlet extends HttpServlet {

	private static final long serialVersionUID = -2206981309178199835L;

	@EJB
	private MyStatefulSessionBean myStatefulSessionBean;

	@EJB
	private MyStatelessSessionBean myStatelessSessionBean;

	@Override
	protected void doGet( HttpServletRequest request, HttpServletResponse response )
			throws ServletException, IOException {
		String message = myStatelessSessionBean.createMessage( null );
		request.setAttribute( "message", message );

		int amountOfRequests = myStatefulSessionBean.getAmountOfrequests();
		request.setAttribute( "amountOfRequests", amountOfRequests );

		request.getRequestDispatcher( "/hello.jsp" ).forward( request, response );
	}

	@Override
	protected void doPost( HttpServletRequest request, HttpServletResponse response )
			throws ServletException, IOException {
		String username = request.getParameter( "username" );
		String message = myStatelessSessionBean.createMessage( username );
		request.setAttribute( "message", message );

		int amountOfRequests = myStatefulSessionBean.getAmountOfrequests();
		request.setAttribute( "amountOfRequests", amountOfRequests );

		request.getRequestDispatcher( "/hello.jsp" ).forward( request, response );
	}

}

E finalmente, vamos criar os arquivos jsp. O arquivo index.jsp servirá pra fazer as chamados ao servlet e o arquivo hello.jsp irá mostrar o resultado do servlet.

Conteúdo do arquivo index.jsp:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="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">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
  <meta name="author" content="Rodrigo Lazoti"/>
  <title>First Java EE 6 Example</title>
</head>
<body>
  <p><a href="hello">Execute Servlet (GET)</a></p>

  <hr width="100%" noshade="noshade"/>

  <form action="hello" method="post">
    <p>Name:<input type="text" name="username"/></p>
    <p><button type="submit">Execute Servlet (POST)</button></p>
  </form>
</body>
</html>

E o conteúdo do arquivo hello.jsp:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="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">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
  <meta name="author" content="Rodrigo Lazoti"/>
  <title>First Java EE 6 Example</title>
</head>
<body>
  <h2>Result: ${requestScope.message}</h2><br/>
  <h3>This servlet was executed ${requestScope.amountOfRequests} time(s).</h3><br/>
  <hr width="100%" noshade="noshade"/>
  <h4><a href="index.jsp">Back to main page</a></h4>
</body>
</html>

Pronto, nosso exemplo já esta pronto e pode ser testado. Com vimos algumas novidades como:

  • Interface local e remota são opcionais no EJB 3.1.
  • No EJB 3.1, vôce pode empacotar seus EJB’s em arquivos WAR junto com componentes da camada web. Você não precisa ter sua classes EJB definidas em um arquivo ejb-jar.
  • Agora as annotations podem ser usadas em mais tipos de componentes Java EE e o conjunto de anotações usados para injeção de dependência foi padronizada.
  • Ao invés de criar deployment descriptors, você pode anotar as classes para especificar que ela é um servlet.

Este exemplo criado está disponível no github: http://github.com/rlazoti/tutorial-javaee6-first-project

Testing JavaEE 6 with Glassfish and Eclipse

In this post, I’ll show some news of the Java EE 6.
I’ll use the following softwares:

Glassfish v3
Eclipse Galileo JEE Edition

After install them, we go create a dynamic web project in the Eclipse called FirstProjectJEE6:

Now, I’ll replace the contents of the web.xml file for this:

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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-app_3_0.xsd"
	version="3.0">
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

To compile our project, we need to add a external jar (javaee.jar) to the project, the jar file is in the path [glassfish_directory]/glassfish/lib/javaee.jar

I’ll create a ant script to make the deploy of our application in glassfish. It must be saved in the project root and should be called build.xml

<?xml version="1.0" encoding="UTF-8"?>
<project name="FirstProject JavaEE 6" basedir="." default="deploy">
	<property name="warfile" value="FirstProject" />
	<target name="create">
		<war destfile="${warfile}.war" webxml="WebContent/WEB-INF/web.xml" update="true">
			<classes dir="build/classes" />
			<fileset dir="WebContent">
				<exclude name="WEB-INF/web.xml" />
			</fileset>
		</war>
	</target>
	<target name="copy">
		<copy todir="/Users/rodrigolazoti/Programs/glassfishv3/glassfish/domains/domain1/autodeploy" overwrite="true">
			<fileset dir=".">
				<include name="*.war" />
			</fileset>
		</copy>
	</target>
	<target name="deploy">
		<antcall target="create" />
		<antcall target="copy" />
	</target>
</project>

Note that this path:
/Users/rodrigolazoti/Programs/glassfishv3/glassfish/domains/domain1/autodeploy
Should be replaced by the:
[your glassfish]/glassfish/domains/domain1/autodeploy

Now, we let’s code a little, first we let’s create two EJB using the new specification.
I’ll create one stateless and one staleful EJB, the stateful ejb will serve only to represent the number of requests and the stateless will serve to return a message to the User.

The code of stateless ejb:

package br.com.rodrigolazoti.firstproject.service;

import javax.ejb.Stateless;

@Stateless
public class MyStatelessSessionBean {

	public String createMessage( String username ) {
		String message = "Hello World, ";

		if ( username != null && !"".equals( username.trim() ) ) {
			message += username + "!";
		}
		else {
			message += "stranger!";
		}

		return message;
	}

}

And the code of the stateful ejb:

package br.com.rodrigolazoti.firstproject.service;

import javax.ejb.Stateful;

@Stateful
public class MyStatefulSessionBean {

	private int amountOfrequests = 0;

	public int getAmountOfrequests() {
		return ++amountOfrequests;
	}

}

Note that in both ejb, was not necessary to create a local or remote interface. :)

With our EJBs ready, we’ll create a servlet to respond to http methods: GET and POST.

package br.com.rodrigolazoti.firstproject.controller;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.rodrigolazoti.firstproject.service.MyStatefulSessionBean;
import br.com.rodrigolazoti.firstproject.service.MyStatelessSessionBean;

@WebServlet( name = "MyServlet", urlPatterns = { "/hello" } )
public class MyServlet extends HttpServlet {

	private static final long serialVersionUID = -2206981309178199835L;

	@EJB
	private MyStatefulSessionBean myStatefulSessionBean;

	@EJB
	private MyStatelessSessionBean myStatelessSessionBean;

	@Override
	protected void doGet( HttpServletRequest request, HttpServletResponse response )
			throws ServletException, IOException {
		String message = myStatelessSessionBean.createMessage( null );
		request.setAttribute( "message", message );

		int amountOfRequests = myStatefulSessionBean.getAmountOfrequests();
		request.setAttribute( "amountOfRequests", amountOfRequests );

		request.getRequestDispatcher( "/hello.jsp" ).forward( request, response );
	}

	@Override
	protected void doPost( HttpServletRequest request, HttpServletResponse response )
			throws ServletException, IOException {
		String username = request.getParameter( "username" );
		String message = myStatelessSessionBean.createMessage( username );
		request.setAttribute( "message", message );

		int amountOfRequests = myStatefulSessionBean.getAmountOfrequests();
		request.setAttribute( "amountOfRequests", amountOfRequests );

		request.getRequestDispatcher( "/hello.jsp" ).forward( request, response );
	}

}

And finally, we’ll create our jsp files. The index.jsp file will make the calls to the servlet and the hello.jsp file will show the result of calls.

The index.jsp file:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="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">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
  <meta name="author" content="Rodrigo Lazoti"/>
  <title>First Java EE 6 Example</title>
</head>
<body>
  <p><a href="hello">Execute Servlet (GET)</a></p>

  <hr width="100%" noshade="noshade"/>

  <form action="hello" method="post">
    <p>Name:<input type="text" name="username"/></p>
    <p><button type="submit">Execute Servlet (POST)</button></p>
  </form>
</body>
</html>

And the hello.jsp file:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="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">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
  <meta name="author" content="Rodrigo Lazoti"/>
  <title>First Java EE 6 Example</title>
</head>
<body>
  <h2>Result: ${requestScope.message}</h2><br/>
  <h3>This servlet was executed ${requestScope.amountOfRequests} time(s).</h3><br/>
  <hr width="100%" noshade="noshade"/>
  <h4><a href="index.jsp">Back to main page</a></h4>
</body>
</html>

Some news that I used this example:

  • Local business interfaces are optional in EJB 3.1.
  • In EJB 3.1, you can place enterprise bean classes in the .war file along with web tier components. You don’t have to put EJB classes in the ejb-jar file.
  • Annotations can now be used in more types of Java EE components. And the set of annotations used for dependency injection has been standardized.
  • Instead of creating deployment descriptors, you can annotate classes to specify servlet-related deployment information.

This example is available at github: http://github.com/rlazoti/tutorial-javaee6-first-project

[Video] Testing the Chromium OS in Virtual Box

Like most people, I also wanted to know about the new operating system Google’s Chromium OS, then in a quick search I found a link to download a virtual machine with Virtual Box Chromium OS.

An interesting point about the new OS is that logging in, you must have a Gmail account.

The link to download the VM is http://www.ausgamers.com/news/read/2816103

I made a video showing how to use the VM in Virtual Box.

Colando um Splash Screen no seu iPhone app

Adicionar um Splash Screen em um aplicativo do iPhone parece ser uma tarefa complicada mas é extremamente simples.

Neste artigo vou mostrar duas formas de fazer isso, a primeira irá utilizar toda a lógica do iPhone SDK e com isso não precisaremos codificar nada, já na segunda a nossa aplicação irá gerenciar o splash e por conta disso teremos que codificar um pouco.

Nos exemplos desse artigo irei utilizar a seguinte imagem como splash screen:

Splash Screen

Esta imagem deve ter o nome Default.png, vou criar um novo aplicativo para iPhone SDK do tipo View-Based Application chamado splash-screen e adicionar esta esta imagem na pasta chamada Resources e pronto a primeira forma já esta pronto. É só rodar o aplicativo no simulador e o splash vai ser apresentado no carregamento do aplicativo.

Na outra forma, teremos que codificar um pouco então abra a interface splash_screenViewController.h e adicione dois métodos e um novo atributo:

@interface iCrazyFaceViewController : UIViewController {
IBOutlet UIView *splashScreenView;
}

- (void)showSplash;
- (void)hideSplash;

@end

Agora na classe splash_screenViewController.m vamos colocar a implementação desses métodos:

-(void)showSplash
{
UIViewController *modalViewController = [[UIViewController alloc] init];
modalViewController.view = splashScreenView;
[self presentModalViewController:modalViewController animated:NO];
[self performSelector:@selector(hideSplash) withObject:nil afterDelay:2.0];
}

//hide splash screen
- (void)hideSplash{
[[self modalViewController] dismissModalViewControllerAnimated:YES];
}

Abra pelo Interface Builder o arquivo splash_screenViewController.xib, adicione uma nova view e renomeie-a para SplashScreenView.
Nesta nova view criada, adicione um UIImageView e na propriedade image desse componente selecione a nossa imagem Default.png.
Conforme imagem a seguir, vamos fazer a ligação da view (SplashScreenView) com o Outlet que criamos na classe iCrazyFaceViewController chamado splashScreenView.

Ligando outlet pelo interface builder

Ligando outlet pelo interface builder

Pronto, o exemplo já está pronto! Salve o arquivo no Interface Builder, volte para o Xcode e execute a aplicação para conferir o resultado. :)

O projeto criado neste exemplo está disponível para download no git:

http://github.com/rlazoti/iphonesdk-splash-screen