<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>DestaqueBlog &#187; javaee</title>
	<atom:link href="http://weblog.destaquenet.com/tag/javaee/feed/" rel="self" type="application/rss+xml" />
	<link>http://weblog.destaquenet.com</link>
	<description>Blog da equipe Destaquenet.</description>
	<lastBuildDate>Tue, 23 Nov 2010 17:06:50 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Debugando aplicações JavaEE no Glassfish v2</title>
		<link>http://weblog.destaquenet.com/2008/09/22/debugando-aplicacoes-javaee-no-glassfish-v2/</link>
		<comments>http://weblog.destaquenet.com/2008/09/22/debugando-aplicacoes-javaee-no-glassfish-v2/#comments</comments>
		<pubDate>Tue, 23 Sep 2008 01:51:40 +0000</pubDate>
		<dc:creator>Daniel Martins</dc:creator>
				<category><![CDATA[Português]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[Tutoriais]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[dicas]]></category>
		<category><![CDATA[glassfish]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[javaee]]></category>
		<category><![CDATA[netbeans]]></category>

		<guid isPermaLink="false">http://weblog.destaquenet.com/?p=50</guid>
		<description><![CDATA[Este post, na verdade, é uma dica rápida para quem possui aplicações JavaEE rodando em servidores Glassfish e está tendo dificuldades na hora de rastrear a origem de possíveis bugs no código. Habilitando o modo de debug Existem duas maneiras &#8230; <a href="http://weblog.destaquenet.com/2008/09/22/debugando-aplicacoes-javaee-no-glassfish-v2/">Continue lendo <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Este <em>post</em>, na verdade, é uma dica rápida para quem possui aplicações <a href="http://java.sun.com/javaee/">JavaEE</a> rodando em servidores <a href="http://glassfish.dev.java.net/">Glassfish</a> e está tendo dificuldades na hora de rastrear a origem de possíveis <em>bugs</em> no código. <span id="more-50"></span></p>
<h3>Habilitando o modo de debug</h3>
<p>Existem duas maneiras de se habilitar o modo de <em>debug</em> no Glassfish: através do painel de administração ou durante a inicialização do domínio.</p>
<p>Para habilitar o modo de <em>debug</em> por padrão, através do painel de administração, basta marcar o campo <em>Debug</em> na tela <em>JVM Settings</em> e clicar em <em>Save</em>:</p>
<div id="attachment_51" class="wp-caption aligncenter" style="width: 310px"><a href="http://weblog.destaquenet.com/wp-content/uploads/2008/09/debug_mode.png"><img src="http://weblog.destaquenet.com/wp-content/uploads/2008/09/debug_mode-300x254.png" alt="Habilitando o modo de Debug" title="Modo de Debug" width="300" height="254" class="size-medium wp-image-51" /></a><p class="wp-caption-text">Habilitando o modo de Debug</p></div>
<p>Basta reiniciar o domínio para ver que o servidor abre a porta <code>9009</code>, através da qual podemos conectar um <em>debugger</em>:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">asadmin start-domain domain1</pre></div></div>

<p>Eis um resumo da saída ecoada pelo Glassfish:</p>
<pre>
Starting Domain domain1, please wait.
Log redirected to .../server.log.
Redirecting output to .../server.log
Listening for transport dt_socket at address: 9009
Application server is listening at address 9009 for debugger to attach using transport dt_socket
...
</pre>
<p>A outra forma de se habilitar o modo de <em>debug</em> é fornecer o parâmetro <code>--debug</code> ao iniciar o domínio. Por exemplo:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">asadmin start-domain <span style="color: #660033;">--debug</span> domain1</pre></div></div>

<h3>Conectando o debugger da IDE ao servidor</h3>
<p>Agora, basta usar os recursos de <em>debugging</em> presentes na sua IDE Java para debugar o código. Por exemplo, se você usa o <a href="http://netbeans.org/">NetBeans</a> 5.5, basta acessar o menu <em>Run &#8211; Attach Debugger&#8230;</em> e o configurar da seguinte forma:</p>
<div id="attachment_52" class="wp-caption aligncenter" style="width: 310px"><a href="http://weblog.destaquenet.com/wp-content/uploads/2008/09/screenshot-attach.png"><img src="http://weblog.destaquenet.com/wp-content/uploads/2008/09/screenshot-attach-300x152.png" alt="Anexando o debugger do NetBeans" title="Anexando o debugger" width="300" height="152" class="size-medium wp-image-52" /></a><p class="wp-caption-text">Anexando o debugger do NetBeans</p></div>
<p>O procedimento é semelhante em outras IDEs Java.</p>
<p>Pronto! Feito isso, é só colocar os <em>breakpoints</em> e disparar a execução do código problemático.</p>
]]></content:encoded>
			<wfw:commentRss>http://weblog.destaquenet.com/2008/09/22/debugando-aplicacoes-javaee-no-glassfish-v2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaEE 5 interceptors</title>
		<link>http://weblog.destaquenet.com/2008/09/21/javaee-5-interceptors/</link>
		<comments>http://weblog.destaquenet.com/2008/09/21/javaee-5-interceptors/#comments</comments>
		<pubDate>Sun, 21 Sep 2008 03:30:58 +0000</pubDate>
		<dc:creator>Daniel Martins</dc:creator>
				<category><![CDATA[Português]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[Tutoriais]]></category>
		<category><![CDATA[annotations]]></category>
		<category><![CDATA[aop]]></category>
		<category><![CDATA[container]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[ejb]]></category>
		<category><![CDATA[ioc]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[javaee]]></category>
		<category><![CDATA[reflection]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://weblog.destaquenet.com/?p=41</guid>
		<description><![CDATA[É inegável que a não-tão-nova versão 5 da especificação JavaEE veio numa hora mais do que necessária. Todo mundo parecia &#8212; e com razão &#8212; evitá-la ao máximo, pois seu uso demandava muito tempo e caixas de calmante. Hoje, criar &#8230; <a href="http://weblog.destaquenet.com/2008/09/21/javaee-5-interceptors/">Continue lendo <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>É inegável que a não-tão-nova <a href="http://jcp.org/aboutJava/communityprocess/pfd/jsr244/">versão 5</a> da especificação JavaEE veio numa hora mais do que necessária. Todo mundo parecia &#8212; e com razão &#8212; evitá-la ao máximo, pois seu uso demandava muito tempo e caixas de calmante.</p>
<p>Hoje, criar e manter uma aplicação com <acronym title="Enterprise JavaBeans">EJBs</acronym> é relativamente simples. E, por este motivo, a adoção da tecnologia passou a ser mais expressiva, mesmo em projetos menores.</p>
<p>Alguns aspectos da especificação, entretanto, ainda deixam a desejar. Um exemplo seria a parte de injeção de dependências, que é limitada apenas a componentes gerenciados pelo <em>container</em>. O que isso quer dizer? Isso quer dizer que, para você poder tirar proveito do esquema de injeção de dependências, todos os seus componentes precisam ser EJBs.</p>
<p>Mas, nesta versão, os EJBs não são <acronym title="Plain Old Java Object">POJO</acronym>s? Sim, mas ter de expor classes simples como EJBs &#8212; só para ganhar essa &#8220;injetabilidade&#8221; de presente &#8212; não parece correto. E, da mesma forma, espalhar instanciações de objetos pelos vários componentes da aplicação definitivamente também não parece.<span id="more-41"></span></p>
<p>Por isso, mostrarei a seguir um exemplo de como melhorar a parte de injeção de dependências para que possamos injetar POJOs declarativamente em objetos gerenciados. Como o <a href="http://www.springframework.org/">Spring</a> é (de longe) o <em>framework</em> mais conhecido, eu o usarei para me ajudar nesta tarefa.</p>
<h3>O exemplo</h3>
<p>Para demonstrar o efeito desejado, veja o trecho de código a seguir:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> Calculator <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">int</span> mult<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> a, <span style="color: #000066; font-weight: bold;">int</span> b<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> CalculatorImpl <span style="color: #000000; font-weight: bold;">implements</span> Calculator <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">int</span> mult<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> a, <span style="color: #000066; font-weight: bold;">int</span> b<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> a<span style="color: #339933;">*</span>b<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
@<span style="color: #003399;">Remote</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> MultiplicationRuler <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> rulerFor<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> number, <span style="color: #000066; font-weight: bold;">int</span> from, <span style="color: #000066; font-weight: bold;">int</span> to<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
@Stateless
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MultiplicationRulerBean <span style="color: #000000; font-weight: bold;">implements</span> MultiplicationRuler <span style="color: #009900;">&#123;</span>
&nbsp;
    @InjectBean
    <span style="color: #000000; font-weight: bold;">private</span> Calculator calculator<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> rulerFor<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> number, <span style="color: #000066; font-weight: bold;">int</span> from, <span style="color: #000066; font-weight: bold;">int</span> to<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">int</span> total <span style="color: #339933;">=</span> to<span style="color: #339933;">-</span>from<span style="color: #339933;">+</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> ruler <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span>total<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> total<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            ruler<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> calculator.<span style="color: #006633;">mult</span><span style="color: #009900;">&#40;</span>number, from<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">return</span> ruler<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>O objetivo aqui é implementar um componente POJO que multiplica dois números. Este componente é usado por um segundo &#8212; este sim um EJB &#8212; que fornece um método que funciona mais ou menos igual aquelas réguas de tabuada; o método recebe o número desejado e dois outros números que representam os limites da tabuada. Por exemplo, a chamada abaixo retorna os resultados da tabuada de 10, começando no número 1 e indo até o 15:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">MultiplicationRulerBean ruler <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MultiplicationRulerBean<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
ruler.<span style="color: #006633;">rulerFor</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">10</span>,<span style="color: #cc66cc;">1</span>,<span style="color: #cc66cc;">15</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Note, na classe <code>MultiplicationRulerBean</code>, que o atributo <code>Calculator</code> está anotado com <code>@InjectBean</code>. Esta anotação servirá para indicar que este campo representa uma dependência que deve ser resolvida injetando-se uma instância de <code>Calculator</code>.</p>
<h3>Usando o Spring para obter dependências</h3>
<p>Segue um exemplo de arquivo de contexto <code>appcontext-services.xml</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;beans<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;calculatorBean&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;CalculatorImpl&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/beans<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Como nossa única dependência externa é uma instância de <code>Calculator</code>, então o arquivo se resume a apenas uma entrada <code>&lt;bean&gt;</code>. Agora, precisamos criar uma classe que será usada para obter os objetos declarados no arquivo mostrado:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> SpringBeanContext <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> SpringBeanContext instance<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #009900;">&#123;</span>
        instance <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> SpringBeanContext<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> ApplicationContext context<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> SpringBeanContext<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        context <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ClassPathXmlApplicationContext<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;META-INF/spring/appcontext-*.xml&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Object</span> getBean<span style="color: #009900;">&#40;</span>Class<span style="color: #339933;">&lt;?&gt;</span> clazz<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        Map<span style="color: #339933;">&lt;?</span>,<span style="color: #339933;">?&gt;</span> beans <span style="color: #339933;">=</span> context.<span style="color: #006633;">getBeansOfType</span><span style="color: #009900;">&#40;</span>clazz<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>beans <span style="color: #339933;">!=</span> <span style="color: #000066; font-weight: bold;">null</span> <span style="color: #339933;">&amp;&amp;</span> beans.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">return</span> beans.<span style="color: #006633;">values</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">iterator</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">next</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> NoSuchBeanDefinitionException<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;There's no bean of type &quot;</span> <span style="color: #339933;">+</span> clazz<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> SpringBeanContext getInstance<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> instance<span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// retorna o singleton</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Como apenas precisamos de um objeto da classe <code>SpringBeanContext</code>, esta foi programada como sendo um <a href="http://en.wikipedia.org/wiki/Singleton_pattern">Singleton</a>. Podemos ver que, quando o Singleton é instanciado, os arquivos de contexto &#8212; que seguem a convenção <code>appcontext-[modulo].xml</code> &#8212; são carregados pelo Spring. O método <code>getBean()</code> foi criado para que possamos obter objetos gerenciados pelo Spring.</p>
<h3>Definindo a anotação @InjectBean</h3>
<p>Agora, precisamos criar uma anotação que utilizaremos para indicar as dependências de nossos EJBs:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Retention<span style="color: #009900;">&#40;</span>RetentionPolicy.<span style="color: #006633;">RUNTIME</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> @<span style="color: #000000; font-weight: bold;">interface</span> InjectBean <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span></pre></div></div>

<p>A anotação <code>@InjectBean</code>, que não possui parâmetros e é visível em <em>Runtime</em>, servirá para indicar os atributos que representam dependências. O <em>interceptor</em>, que definiremos a seguir, irá procurar por essa anotação nos EJBs interceptados. Então, para cada campo anotado com essa anotação, o <em>interceptor</em> irá obter o objeto correspondente do contexto do Spring e injetá-lo.</p>
<h3>O Interceptor</h3>
<p>Finalmente chegamos à classe que é responsável por fazer o trabalho pesado:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> SpringBeanInterceptor <span style="color: #009900;">&#123;</span>
&nbsp;
    @PostConstruct
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> injectSpringBean<span style="color: #009900;">&#40;</span>InvocationContext context<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003399;">Object</span> target <span style="color: #339933;">=</span> context.<span style="color: #006633;">getTarget</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Field</span> field <span style="color: #339933;">:</span> getAnnotatedFields<span style="color: #009900;">&#40;</span>target.<span style="color: #006633;">getClass</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            injectBean<span style="color: #009900;">&#40;</span>target, field<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        context.<span style="color: #006633;">proceed</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">protected</span> List<span style="color: #339933;">&lt;</span>Field<span style="color: #339933;">&gt;</span> getAnnotatedFields<span style="color: #009900;">&#40;</span>Class<span style="color: #339933;">&lt;?&gt;</span> clazz<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        List<span style="color: #339933;">&lt;</span>Field<span style="color: #339933;">&gt;</span> fields <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> LinkedList<span style="color: #339933;">&lt;</span>Field<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Field</span> field<span style="color: #339933;">:</span> clazz.<span style="color: #006633;">getDeclaredFields</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>field.<span style="color: #006633;">getAnnotation</span><span style="color: #009900;">&#40;</span>InjectBean.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">!=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                fields.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>field<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">return</span> fields<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000066; font-weight: bold;">void</span> injectBean<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> target, <span style="color: #003399;">Field</span> field<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003399;">Object</span> bean <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
        bean <span style="color: #339933;">=</span> SpringBeanContext.<span style="color: #006633;">getInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getBean</span><span style="color: #009900;">&#40;</span>field.<span style="color: #006633;">getType</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>field.<span style="color: #006633;">isAccessible</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            field.<span style="color: #006633;">setAccessible</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        field.<span style="color: #006633;">set</span><span style="color: #009900;">&#40;</span>target, bean<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Nada de outro mundo, não? Perceba que usamos a anotação <code>@PostConstruct</code>, o que indica que o método anotado deve ser executado para um EJB após sua criação pelo <em>container</em>. Todo método interceptador deve retornar <code>void</code> e esperar um parâmetro do tipo <code>InvocationContext</code>. Neste método, utilizamos um pouco de <a href="http://en.wikipedia.org/wiki/Reflection_%28computer_science%29">Reflection</a> para injetar o objeto fornecido pelo Spring. Por fim, para que outros possíveis <em>interceptors</em> (e o próprio método sendo interceptado) possam ser invocados, chamamos <code>InvocationContext.proceed()</code>.</p>
<p>Para finalizar o exemplo, nos resta associar este <em>interceptor</em> com o EJB da aplicação. Uma forma simples de fazer isso seria através do uso da anotação <code>@Interceptors</code> nas classes e métodos desejados. Por exemplo:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Stateless
@Interceptors<span style="color: #009900;">&#40;</span>SpringBeanInterceptor.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MultiplicationRulerBean <span style="color: #000000; font-weight: bold;">implements</span> MultiplicationRuler <span style="color: #009900;">&#123;</span>
&nbsp;
    @InjectBean
    <span style="color: #000000; font-weight: bold;">private</span> Calculator calculator<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// ...</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Claro que, para este pequeno exemplo, esta abordagem poderia ser utilizada sem nenhum problema. Porém, definir o <em>interceptor</em> dessa forma é muito trabalhoso em situações onde temos muitos EJBs.</p>
<p>Para que possamos evitar o uso repetido da anotação <code>@Interceptors</code>, podemos fazer a configuração via <acronym title="eXtensible Markup Language">XML</acronym>, o que nos permite associar um <em>interceptor</em> a vários EJBs através do uso de curingas. Para isso, basta modificar o arquivo <code>ejb-jar.xml</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ejb-jar<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;interceptors<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;interceptor<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;description<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Spring-aware interceptor<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/description<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;interceptor-class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>com.destaquenet.tutorial.interceptor.SpringBeanInterceptor<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/interceptor-class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/interceptor<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/interceptors<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;assembly-descriptor<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;interceptor-binding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ejb-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>*<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ejb-name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;interceptor-class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>com.destaquenet.tutorial.interceptor.SpringBeanInterceptor<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/interceptor-class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/interceptor-binding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/assembly-descriptor<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ejb-jar<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Neste caso, estamos associando o <em>interceptor</em> automaticamente a <strong>todos</strong> os EJBs, nos livrando de ter que configurar manualmente a associação do <em>interceptor</em> com possíveis novos EJBs que a aplicação venha a ter.</p>
<h3>Conclusão</h3>
<p>Venho observando que <em>frameworks</em> como o Spring e a especificação JavaEE estão trilhando caminhos diretamente opostos; enquando os primeiros estão crescendo descontroladamente e ficando cada vez mais complexos, o segundo está tirando a gordura e ficando mais simples de usar. Claro que cada desenvolvedor tem seus motivos para escolher um ou outro, mas eu particularmente já não vejo tanta vantagem em se adotar o Spring ao EJB. Por outro lado, penso ser mais interessante a <strong>junção</strong> dessas tecnologias de modo que cada uma contribua com o seu melhor.</p>
<p>Como vimos, a especificação JavaEE 5 &#8212; que foi projetada para ser estensível e fácil de usar &#8212; conta com componentes denominados <em>interceptors</em>, que nos fornecem um recurso <em>à la</em> <acronym title="Aspect Oriented Programming">AOP</acronym>, nos permitindo executar código em pontos bem definidos durante a execução da aplicação.</p>
<p>Eu nem preciso dizer que os <em>interceptors</em> podem ser usados para outras coisas além da mostrada aqui. Apenas para citar um exemplo, o <em>framework</em> <a href="http://www.jboss.com/products/seam">Seam</a> usa <em>interceptors</em> para implementar o que seus autores chamam de <a href="http://docs.jboss.com/seam/2.0.0.CR1/reference/en/html/concepts.html#d0e2958">Bijeção</a> &#8212; que permite que um componente qualquer possa receber/ejetar dependências de/para um contexto.</p>
<p>Os conceitos apresentados aqui podem ser adaptados para uso com outros <em>frameworks</em> de injeção de dependências, como <a href="http://code.google.com/p/google-guice/">Guice</a> e <a href="http://www.picocontainer.org/">PicoContainer</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://weblog.destaquenet.com/2008/09/21/javaee-5-interceptors/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>2 (boas) formas de testar clientes JavaMail</title>
		<link>http://weblog.destaquenet.com/2008/09/20/2-boas-formas-de-testar-clientes-javamail/</link>
		<comments>http://weblog.destaquenet.com/2008/09/20/2-boas-formas-de-testar-clientes-javamail/#comments</comments>
		<pubDate>Sat, 20 Sep 2008 04:00:27 +0000</pubDate>
		<dc:creator>Daniel Martins</dc:creator>
				<category><![CDATA[Português]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[Tutoriais]]></category>
		<category><![CDATA[email]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[javaee]]></category>
		<category><![CDATA[javamail]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[mock-javamail]]></category>
		<category><![CDATA[mocking]]></category>
		<category><![CDATA[smtp]]></category>
		<category><![CDATA[subethasmtp wiser]]></category>
		<category><![CDATA[testes]]></category>

		<guid isPermaLink="false">http://weblog.destaquenet.com/?p=29</guid>
		<description><![CDATA[Sem sombra de dúvidas, a API Java mais usada para resolver a questão do envio e recebimento de emails é o JavaMail. Apesar de existirem outras opções, como o Spring Mail e Commons Email, no fim das contas é o &#8230; <a href="http://weblog.destaquenet.com/2008/09/20/2-boas-formas-de-testar-clientes-javamail/">Continue lendo <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Sem sombra de dúvidas, a <acronym title="Application Programming Interface">API</acronym> Java mais usada para resolver a questão do envio e recebimento de emails é o <a href="http://java.sun.com/products/javamail/">JavaMail</a>. Apesar de existirem outras opções, como o <a href="http://static.springframework.org/spring/docs/2.0.x/reference/mail.html">Spring Mail</a> e <a href="http://commons.apache.org/email/">Commons Email</a>, no fim das contas é o próprio JavaMail quem faz todo o trabalho sujo, já que tais APIs são baseadas no próprio JavaMail.</p>
<p>Apesar de dar conta do recado, a referida API conta com alguns problemas bastante complicados, dentre os quais eu destaco o <em>design</em> (horrível, diga-se de passagem) de <a href="http://java.sun.com/products/javamail/javadocs/index.html">suas classes e interfaces</a>, que parecem fazer o possível para dificultar a testabilidade dos seus &#8220;clientes&#8221;. <span id="more-29"></span></p>
<h3>Entendendo o problema</h3>
<p>Uma técnica de testes bastante utilizada atualmente consiste no uso de <em>frameworks</em> para <a href="http://en.wikipedia.org/wiki/Mock_object">Mocking de objetos</a>. Esses <em>frameworks</em> permitem testar código que faça uso de quaisquer recursos externos e que são, por natureza, difíceis de testar. Classes que necessitam acessar recursos de infraestrutura, como arquivos em disco, impressoras e bancos de dados, são ótimas candidatas a serem &#8220;mockadas&#8221;.</p>
<p>O grande problema é que, para que tais <em>frameworks</em> possam ser usados, o código a ser &#8220;mockado&#8221; tem de seguir <a href="http://www.artima.com/interfacedesign/contents.html">algumas regrinhas de codificação</a>. Por exemplo, alguns <em>frameworks</em> não conseguem &#8220;mockar&#8221; uma classe concreta; outros por sua vez, conseguem &#8220;mockar&#8221; classes concretas desde que elas não sejam finais.</p>
<p>Bom, só para resumir, o ideal seria que o código todo &#8212; tanto das classes de infraestrutura quanto das classes que fazem uso das primeiras &#8212; seja orientado a interfaces. Isso é necessário pois <a href="http://www.jmock.org/">grande</a> <a href="http://www.easymock.org/">parte</a> dos <em>frameworks</em> Java para Mocking de objetos se apoiam na <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/lang/reflect/Proxy.html">API Proxy</a> para fazer seu trabalho e, como muitos já devem saber, não é possível criar <em>proxies</em> de classes contretas através do uso dessa API.</p>
<p>Para ilustrar melhor o que estou tentando dizer, segue um exemplo de código que envia um e-mail com a API JavaMail:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">Properties</span> props <span style="color: #339933;">=</span> <span style="color: #003399;">System</span>.<span style="color: #006633;">getProperties</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
props.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;mail.smtp.host&quot;</span>, <span style="color: #0000ff;">&quot;smtp.middlenet.com&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
Session session <span style="color: #339933;">=</span> Session.<span style="color: #006633;">getDefaultInstance</span><span style="color: #009900;">&#40;</span>props<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
MimeMessage message <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MimeMessage<span style="color: #009900;">&#40;</span>session<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
message.<span style="color: #006633;">setFrom</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> InternetAddress<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Frodo&quot;</span>, <span style="color: #0000ff;">&quot;frodo@theshire.com&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
message.<span style="color: #006633;">addRecipient</span><span style="color: #009900;">&#40;</span>RecipientType.<span style="color: #006633;">TO</span>, <span style="color: #000000; font-weight: bold;">new</span> InternetAddress<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Gandalf&quot;</span>, <span style="color: #0000ff;">&quot;blog@gandalf.com&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
message.<span style="color: #006633;">setSubject</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Be careful&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
message.<span style="color: #006633;">setText</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Sauron is looking for the One Ring!&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
Transport.<span style="color: #006633;">send</span><span style="color: #009900;">&#40;</span>message<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Veja, por exemplo, que o objeto <code>Session</code> é obtido através da chamada ao método estático <code>getDefaultInstance()</code>; de modo semelhante, temos também a chamada ao método estático <code>send()</code>, na última linha do código. Ah claro, sem contar que a classe <code>Session</code> é <code><strong>final</strong></code>! Como podemos fazer para testar o que vai para e o que volta da API JavaMail?</p>
<h3>Uma solução</h3>
<p>Apesar de não ser possível testar o código anterior usando um <em>framework</em> para Mocking de objetos &#8220;tradicional&#8221;, felizmente há uma luz no fim do túnel.</p>
<p>Uma opção bastante interessante é a utilização de um servidor <acronym title="Simple Mail Transfer Protocol">SMTP</acronym> &#8220;de mentirinha&#8221;, para o qual as mensagens são enviadas. Assim, podemos verificar o que acontece quando o código &#8220;conversa&#8221; com um servidor.</p>
<p>A boa notícia é que não precisamos <a href="http://www.faqs.org/rfcs/rfc821.html">implementar</a> um servidor SMTP do zero! Uma opção de servidor como esse é o <a href="http://subethasmtp.tigris.org/wiser.html">SubEthaSMTP Wiser</a> (!). Com ele, podemos subir um servidor SMTP numa porta qualquer. Então, basta configurar nossa classe de envio de e-mails de modo que tal servidor seja usado no lugar do servidor de produção. As mensagens enviadas a esse servidor podem ser consultadas e verificadas através de asserções no código de testes.</p>
<h4>Usando o SubEthaSMTP Wiser com o Maven</h4>
<p>Se você usa o <a href="http://maven.apache.org/">Maven</a>, então basta adicionar a dependência no seu POM para tornar as classes do SubEthaSMTP Wiser disponíveis no seu ambiente de testes:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>org.subethamail<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>subethasmtp-wiser<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>1.2<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;scope<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>test<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/scope<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Talvez você veja uma mensagem de erro indicando que a dependência <code>javax.activation:1.0.2</code> não foi encontrada. Se isso acontecer, você deverá baixar essa versão do <a href="http://java.sun.com/products/archive/javabeans/jaf102.html">site da Sun</a> e fazer a instalação manualmente no seu repositório local. (o Maven informa qual comando rodar para fazer essa instalação).</p>
<h4>Exemplo de uso</h4>
<p>Usar esse servidor é uma tarefa bem simples. A maior dificuldade é configurar a nossa classe de envio de e-mails para se conectar nesse servidor em vez do servidor de produção. Veja só:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">EmailMessage message <span style="color: #339933;">=</span> ... <span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// objeto com os dados da mensagem</span>
&nbsp;
<span style="color: #666666; font-style: italic;">/* inicia o servidor */</span>
Wiser server <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Wiser<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
server.<span style="color: #006633;">setPort</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">2500</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
server.<span style="color: #006633;">start</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">/* configura o cliente */</span>
<span style="color: #003399;">Properties</span> prop <span style="color: #339933;">=</span> <span style="color: #003399;">System</span>.<span style="color: #006633;">getProperties</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
prop.<span style="color: #006633;">setProperty</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;mail.smtp.host&quot;</span>, <span style="color: #0000ff;">&quot;localhost&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
prop.<span style="color: #006633;">setProperty</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;mail.smtp.port&quot;</span>, <span style="color: #0000ff;">&quot;2500&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
session <span style="color: #339933;">=</span> Session.<span style="color: #006633;">getDefaultInstance</span><span style="color: #009900;">&#40;</span>prop<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
EmailSender sender <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> JavaMailEmailSender<span style="color: #009900;">&#40;</span>session<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// minha classe</span>
sender.<span style="color: #006633;">send</span><span style="color: #009900;">&#40;</span>message<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// o parâmetro contém os dados de envio e corpo da mensagem</span>
&nbsp;
server.<span style="color: #006633;">stop</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// pára o servidor</span>
&nbsp;
<span style="color: #666666; font-style: italic;">/* verifica o que foi enviado */</span>
assertEquals<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span>, server.<span style="color: #006633;">getMessages</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
assertEquals<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Sauron is looking for the One Ring!&quot;</span>, server.<span style="color: #006633;">getMessages</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getMimeMessage</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getContent</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Nas primeiras linhas iniciamos o servidor. Em seguida, configuramos a <code>Session</code> do JavaMail para que ela se conecte ao nosso servidor &#8220;de mentirinha&#8221;. A partir desse ponto, tudo funciona como de costume, com a vantagem de podermos realizar asserções para verificar se as mensagens chegaram ao servidor da forma esperada. Isso é especialmente útil quando utilizamos algum tipo de <a href="http://velocity.apache.org/">processador</a> de <em>templates</em> durante o envio das mensagens, permitindo que possamos testar o que exatamente chegou ao servidor.</p>
<h3>Para quem não gostou dessa abordagem&#8230;</h3>
<p>Existe ainda uma outra opção que podemos utilizar para testar classes que fazem uso do JavaMail. Trata-se de um projeto chamado <a href="https://mock-javamail.dev.java.net/">mock-javamail</a> que, ao contrário do SubEthaSMTP Wiser, não usa um servidor SMTP &#8220;de mentirinha&#8221; para receber as mensagens; o que ele faz é configurar o JavaMail em <em>runtime</em> de modo que as mensagens enviadas sejam armazenadas em memória.</p>
<h4>Usando o mock-javamail com o Maven</h4>
<p>Primeiramente precisamos adicionar <a href="http://download.java.net/maven/2">o repositório Maven</a> do <a href="http://java.net/">java.net</a>:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;repositories<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;repository<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>java.net2<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;url<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>http://download.java.net/maven/2<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/url<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/repository<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/repositories<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Feito isso, basta declarar a dependência:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>org.jvnet.mock-javamail<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>mock-javamail<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>1.3<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<h4>Exemplo de uso</h4>
<p>Este projeto é mais simples de se utilizar que o SubEthaSMTP Wiser justamente pelo fato de não precisarmos iniciar um servidor SMTP. Isso fica evidente no exemplo abaixo, que é uma adaptação do código anterior:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">EmailMessage message <span style="color: #339933;">=</span> ... <span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// objeto com os dados da mensagem</span>
&nbsp;
<span style="color: #666666; font-style: italic;">/* configura o cliente */</span>
<span style="color: #003399;">Properties</span> prop <span style="color: #339933;">=</span> <span style="color: #003399;">System</span>.<span style="color: #006633;">getProperties</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
prop.<span style="color: #006633;">setProperty</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;mail.smtp.host&quot;</span>, <span style="color: #0000ff;">&quot;localhost&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
prop.<span style="color: #006633;">setProperty</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;mail.smtp.port&quot;</span>, <span style="color: #0000ff;">&quot;2500&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
session <span style="color: #339933;">=</span> Session.<span style="color: #006633;">getDefaultInstance</span><span style="color: #009900;">&#40;</span>prop<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
EmailSender sender <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> JavaMailEmailSender<span style="color: #009900;">&#40;</span>session<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// minha classe</span>
sender.<span style="color: #006633;">send</span><span style="color: #009900;">&#40;</span>message<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// o parâmetro contém os dados de envio e corpo da mensagem</span>
&nbsp;
<span style="color: #666666; font-style: italic;">/* verifica o que foi enviado */</span>
assertEquals<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span>, Mailbox.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;gandalf@asskickers.com&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
assertEquals<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Sauron is looking for the One Ring!&quot;</span>, Mailbox.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;gandalf@asskickers.com&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getContent</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://weblog.destaquenet.com/2008/09/20/2-boas-formas-de-testar-clientes-javamail/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

