<?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>Gilliard Cordeiro &#187; JavaEE</title>
	<atom:link href="http://blog.gilliard.eti.br/category/javaee/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.gilliard.eti.br</link>
	<description>tá nervoso? vai programar!</description>
	<lastBuildDate>Wed, 21 Sep 2011 05:22:19 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Como trabalhar com ViewScope e Page</title>
		<link>http://blog.gilliard.eti.br/2010/11/como-trabalhar-com-viewscope-e-page/</link>
		<comments>http://blog.gilliard.eti.br/2010/11/como-trabalhar-com-viewscope-e-page/#comments</comments>
		<pubDate>Tue, 23 Nov 2010 20:06:06 +0000</pubDate>
		<dc:creator>Gilliard Cordeiro</dc:creator>
				<category><![CDATA[JavaEE]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[bookmarking]]></category>
		<category><![CDATA[JavaServer Faces]]></category>
		<category><![CDATA[page-scope]]></category>
		<category><![CDATA[Seam]]></category>
		<category><![CDATA[view-scope]]></category>

		<guid isPermaLink="false">http://blog.gilliard.eti.br/?p=275</guid>
		<description><![CDATA[Uma coisa que não é muito intuitiva é a forma como o ViewScope do JSF e o scope Page do Seam funcionam. Como estamos acostumados com o escopo request, que termina quando a próxima view é renderizada, tendemos a pensar que esses escopos funcionam da mesma forma. Mas na verdade o escopo morre no momento [...]]]></description>
			<content:encoded><![CDATA[<p>Uma coisa que não é muito intuitiva é a forma como o <code><strong>ViewScope</strong></code> do JSF e o scope <code><strong>Page</strong></code> do Seam funcionam. Como estamos acostumados com o escopo request, que termina quando a próxima view é renderizada, tendemos a pensar que esses escopos funcionam da mesma forma. Mas na verdade o escopo morre no momento que uma nova view é setada. O problema é que depois que isso acontece ainda temos toda a fase 6 do jsf.</p>
<p>Para entendermos melhor o funcionamento, vamos considerar como exemplo uma tela de listagem de produtos (<code>produtoLista.xhtml</code>) onde selecionamos um produto e este é exibido em outra view, que mostra os detalhes desse produto (<code>produtoForm.xhtml</code>). Nessa aplicação vou usar o mesmo managed bean com <code><strong>@ViewScope</strong></code> para a listagem e para a tela do produto.</p>
<p>Usando o escopo <code><strong>view</strong></code>, quando clicamos num <code>h:command(Button | Link)</code> que tem dentro um <code>f:setPropertyActionListener</code> temos a impressão que o jsf não colocou o produto selecionado no <code>target</code>, no caso o <code><strong>produtoController.produto</strong></code>. Na verdade ele fez isso sim, mas assim que mudou da view de listagem para a de produto o <code>produtoController</code>, que continha o produto selecionado foi descartado. Então um novo <code>produtoController</code> é instanciado, e esse obviamente não conhece o produto selecionado. O funcionamento é simples, só não é intuitivo (vou fazer essa afirmação várias vezes que é pra ficar no subconsciente hehehe).</p>
<p>Na minha opinião, um bom comportamento padrão seria como o <a href="http://wiki.apache.org/myfaces/Extensions/CDI/DevDoc/Drafts/ViewConversationScoped" target="_blank">@ViewConversationScoped</a>. Mas como ninguém liga para a minha opinião, o jeito é usarmos os parâmetros de url para segurar esses valores. Pra variar já escrevi muito, então vamos ver na prática como fazer isso.</p>
<p>Na classe <code>Produto</code> vou simplesmente ignorar os getters e setters, <a href="http://groovy.codehaus.org/Groovy+Beans">Groovy like</a> =)</p>
<p>Entidade Produto</p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;">@<span style="color: #003399; font-weight: bold;">Entity</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Produto <span style="color: #009900;">&#123;</span>
&nbsp;
	@Id @GeneratedValue
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399; font-weight: bold;">Integer</span> id<span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399; font-weight: bold;">String</span> nome<span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399; font-weight: bold;">String</span> descricao<span style="color: #339933;">;</span>
&nbsp;
        @<span style="color: #003399; font-weight: bold;">Override</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399; font-weight: bold;">String</span> toString<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> <span style="color: #0000ff;">&quot;Produto [descricao=&quot;</span> + descricao + <span style="color: #0000ff;">&quot;, id=&quot;</span> + id + <span style="color: #0000ff;">&quot;, nome=&quot;</span> + nome + <span style="color: #0000ff;">&quot;]&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>O Controlador</p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;">@ManagedBean
@ViewScope
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ProdutoController <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Produto produto<span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399; font-weight: bold;">List</span><span style="color: #339933;">&lt;</span>Produto<span style="color: #339933;">&gt;</span> produtos<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">//método init serve só para vermos em que momento o bean é destruído</span>
	@PostConstruct
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #006600; font-weight: bold;">void</span> init<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		<span style="color: #003399; font-weight: bold;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;ProdutoController.init()&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		atribuirEstadoInicial<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: #008000; font-style: italic; font-weight: bold;">/**
	 * Deixa o bean em um estado inicial válido tanto para edição quanto para listagens
	 */</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #006600; font-weight: bold;">void</span> atribuirEstadoInicial<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #003399; font-weight: bold;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;ProdutoController.atribuirEstadoInicial()&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #666666; font-style: italic;">//serve para deixar o bean em um estado onde pode acontecer uma nova edição</span>
		produto = <span style="color: #000000; font-weight: bold;">new</span> Produto<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #666666; font-style: italic;">//limpa a listagem previamente carregada pois ela não contém um elemento novo ou contém um recém excluído</span>
		produtos = <span style="color: #006600; font-weight: bold;">null</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: #006600; font-weight: bold;">void</span> salvar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #003399; font-weight: bold;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;ProdutoController.salvar()&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		JpaUtil.<span style="color: #006633;">getEntityManager</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getTransaction</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">begin</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		JpaUtil.<span style="color: #006633;">getEntityManager</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">merge</span><span style="color: #009900;">&#40;</span>produto<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		JpaUtil.<span style="color: #006633;">getEntityManager</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getTransaction</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">commit</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		atribuirEstadoInicial<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;">public</span> Produto getProduto<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> produto<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #006600; font-weight: bold;">void</span> setProduto<span style="color: #009900;">&#40;</span>Produto produto<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003399; font-weight: bold;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;ProdutoController.setProduto(): &quot;</span> + produto<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">produto</span> = produto<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@<span style="color: #003399; font-weight: bold;">SuppressWarnings</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;unchecked&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399; font-weight: bold;">List</span><span style="color: #339933;">&lt;</span>Produto<span style="color: #339933;">&gt;</span> getProdutos<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;">if</span> <span style="color: #009900;">&#40;</span>produtos == <span style="color: #006600; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			produtos = JpaUtil.<span style="color: #006633;">getEntityManager</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">createQuery</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;select p from Produto p&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getResultList</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;">return</span> produtos<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #006600; font-weight: bold;">void</span> setProdutos<span style="color: #009900;">&#40;</span><span style="color: #003399; font-weight: bold;">List</span><span style="color: #339933;">&lt;</span>Produto<span style="color: #339933;">&gt;</span> produtos<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">produtos</span> = produtos<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>E o converter</p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;">@FacesConverter<span style="color: #009900;">&#40;</span>forClass=Produto.<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> ProdutoConverter <span style="color: #000000; font-weight: bold;">implements</span> Converter <span style="color: #009900;">&#123;</span>
&nbsp;
	@<span style="color: #003399; font-weight: bold;">Override</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399; font-weight: bold;">Object</span> getAsObject<span style="color: #009900;">&#40;</span>FacesContext context, UIComponent component, <span style="color: #003399; font-weight: bold;">String</span> string<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003399; font-weight: bold;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;ProdutoConverter.getAsObject(): &quot;</span> + string<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>string == <span style="color: #006600; font-weight: bold;">null</span> || string.<span style="color: #006633;">isEmpty</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;">return</span> <span style="color: #006600; font-weight: bold;">null</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #000000; font-weight: bold;">return</span> JpaUtil.<span style="color: #006633;">getEntityManager</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">find</span><span style="color: #009900;">&#40;</span>Produto.<span style="color: #000000; font-weight: bold;">class</span>, <span style="color: #003399; font-weight: bold;">Integer</span>.<span style="color: #006633;">valueOf</span><span style="color: #009900;">&#40;</span>string<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@<span style="color: #003399; font-weight: bold;">Override</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399; font-weight: bold;">String</span> getAsString<span style="color: #009900;">&#40;</span>FacesContext context, UIComponent component, <span style="color: #003399; font-weight: bold;">Object</span> object<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		Produto produto = <span style="color: #009900;">&#40;</span>Produto<span style="color: #009900;">&#41;</span> object<span style="color: #339933;">;</span>
		<span style="color: #003399; font-weight: bold;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;ProdutoConverter.getAsString(): &quot;</span> + produto<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>produto == <span style="color: #006600; font-weight: bold;">null</span> || produto.<span style="color: #006633;">getId</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> == <span style="color: #006600; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #006600; font-weight: bold;">null</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #003399; font-weight: bold;">String</span>.<span style="color: #006633;">valueOf</span><span style="color: #009900;">&#40;</span>produto.<span style="color: #006633;">getId</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: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Na verdade, até aqui não tem muita novidade. No resto também não vai ter novidade <img src='http://blog.gilliard.eti.br/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  mas vamos lá.</p>
<p>A listagem de produtos:</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;h:dataTable</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;#{produtoController.produtos}&quot;</span> <span style="color: #000066;">var</span>=<span style="color: #ff0000;">&quot;produto&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:column<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:facet</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;header&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>ID<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/f:facet<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		#{produto.id}
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:column<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:column<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:facet</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;header&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>Nome<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/f:facet<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		#{produto.nome}
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:column<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:column<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:facet</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;header&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>Descrição<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/f:facet<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		#{produto.descricao}
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:column<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:column<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:facet</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;header&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>Ações<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/f:facet<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:link</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;editar 1&quot;</span> <span style="color: #000066;">outcome</span>=<span style="color: #ff0000;">&quot;produtoForm&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:param</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;id&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;#{produto.id}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:link<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:commandLink</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;editar 2&quot;</span> <span style="color: #000066;">action</span>=<span style="color: #ff0000;">&quot;produtoForm?faces-redirect=true&amp;amp;includeViewParams=true&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:setPropertyActionListener</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;#{produto}&quot;</span> <span style="color: #000066;">target</span>=<span style="color: #ff0000;">&quot;#{produtoController.produto}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:commandLink<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:column<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:dataTable<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
...</pre></div></div>

<p>E o form de produto:</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;f:view<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:metadata<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:viewParam</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;id&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;#{produtoController.produto}&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/f:metadata<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:head<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;title<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Detalhes do Produto<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/title<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:head<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:body<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:form<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:panelGrid</span> <span style="color: #000066;">columns</span>=<span style="color: #ff0000;">&quot;2&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
				Nome: <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:inputText</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;#{produtoController.produto.nome}&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
				Descrição: <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:inputText</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;#{produtoController.produto.descricao}&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
				<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:commandButton</span> <span style="color: #000066;">action</span>=<span style="color: #ff0000;">&quot;#{produtoController.salvar}&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;Salvar&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:panelGrid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:form<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:body<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/f:view<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
...</pre></div></div>

<p>Por fim, vamos analisar o log do click nos links &#8220;editar 1&#8243; e &#8220;editar 2&#8243;</p>
<p>link &#8220;editar 1&#8243;</p>

<div class="wp_syntax"><div class="code"><pre class="console" style="font-family:monospace;">ProdutoController.init()
ProdutoController.atribuirEstadoInicial()
ProdutoConverter.getAsObject(): 1
ProdutoController.setProduto(): Produto [descricao=Fermento em Pó, id=1, nome=Fermento]
ProdutoConverter.getAsString(): Produto [descricao=Fermento em Pó, id=1, nome=Fermento]</pre></div></div>

<p>link &#8220;editar 2&#8243;</p>

<div class="wp_syntax"><div class="code"><pre class="console" style="font-family:monospace;">ProdutoController.setProduto(): Produto [descricao=Fermento em Pó, id=1, nome=Fermento]
ProdutoConverter.getAsString(): Produto [descricao=Fermento em Pó, id=1, nome=Fermento]
ProdutoController.init()
ProdutoController.atribuirEstadoInicial()
ProdutoConverter.getAsObject(): 1
ProdutoController.setProduto(): Produto [descricao=Fermento em Pó, id=1, nome=Fermento]
ProdutoConverter.getAsString(): Produto [descricao=Fermento em Pó, id=1, nome=Fermento]</pre></div></div>

<p><br/><br/><br />
Beleza, agora sim tem código pra caramba&#8230; boa parte dele aliás bem parecido com o <a href="http://blog.gilliard.eti.br/2009/05/urls-amigaveis-no-jsf-2/">desse post</a>. No meio disso tudo o que temos que prestar atenção é nos dois botões editar da produtoLista.xhtml. O link <strong>&#8220;editar 1&#8243;</strong> é exatamente igual ao apresentado no post que acabei de citar. O valor é passado por GET e o converter do viewParam faz o trabalho de nos deixar trabalhar sempre OO.</p>
<p>Agora vamos ver o link <strong>&#8220;editar 2&#8243;</strong>. Nesse exemplo a gente tem um post para uma view que usa um ManagedBean com escopo <code><strong>@ViewScope</strong></code> para uma outra view cujo MB é o mesmo, mas isso é um detalhe. </p>
<p>Na primeira linha temos o <code><strong>f:setPropertyActionListener</strong></code> trabalhando e chamando o set da propriedade, e na segunda linha vimos o converter gerando o texto (nesse caso id) que irá representar esse objeto na url da próxima view, pois deixamos o <code><strong>includeViewParams=true</strong></code>. Note que em momento algum passamos a propriedade que vai representar o produto na url como fizemos no <strong>&#8220;editar 1&#8243;</strong>. Quem vai fazer isso é o conversor. </p>
<p>Depois, entre as linhas 2 e 3 a view é trocada e o MB é perdido, mas como a url agora já tem o valor a ser mantido, fica igual o exemplo anterior. A única coisa que pode parecer é que teremos buscas desnecessárias ao banco. Mas como você vai estar usando algo mais esperto do que buscar no braço, a JPA já vai estar com esse objeto no cache de primeiro nível &#8211; pois estou usando o padrão <code><a href="http://community.jboss.org/wiki/OpenSessioninView">OpenEntityManagerInView</a></code> &#8211; e não haverá nenhum overhead por causa dessa outra forma de fazer. E isso é muito importante, apesar de termos um converter no meio, e do POST em vez de GET rodar o restore view do jsf, o objeto selecionado não será em momento algum trazido mais de uma vez no banco pois o <code><strong>EntityManager</strong></code> está com ele no cache (para isso não precisa de configuração nenhuma). Como estamos com o bean em escopo view, também não será buscado novamente a lista do banco. Então a única perda real nesse caso é não termos a url montada já na tela de listagem &#8211; o que pode nem ser uma perda. De fato todo o &#8220;overhead&#8221; dessa abordagem resume-se a chamadas de métodos locais como getters. Então provavelmente se sua aplicação ficar lenta aqui, o problema é outro.</p>
<p>Novamente o que incomoda é a falta de intuitividade dessa abordagem. Mas o funcionamento é simples. Só temos que lembrar que nessa abordagem do <strong>&#8220;editar 2&#8243;</strong> só vai funcionar se tivermos o <code><strong>includeViewParams</strong></code> ativo, seja no link ou na regra de navegação do <code><strong>faces-config.xml</strong></code>. Sem isso o JSF não se preocupa em incluir na próxima view os parâmetros de url.</p>
<p><br/><br/></p>
<h3>
Importante! (update)<br />
</h3>
<p><br/><br/></p>
<p>Apesar da abordagem do link <strong>&#8220;editar 1&#8243;</strong>, que usa GET ser a forma mais bacana de se trabalhar, e inclusive é a &#8220;novidade&#8221; do JSF 2, a abordagem do <strong>&#8220;editar 2&#8243;</strong> tem se mostrado mais segura. Isso porque até a versão atual do JSF (2.1) a remoção do bean no escopo view não ocorre da forma esperada quando usamos GET para sair da página, porém quando usamos POST (jeitão que o JSF já está bem acostumado) a coisa rola corretamente.</p>
<p>Agora caso você queria usar um escopo que dure mais que uma página como <a href="http://blog.gilliard.eti.br/2010/11/como-trabalhar-com-viewscope-e-page/#comment-17878">comentado pelo Rodrigo</a> a melhor solução na minha opinião é usar conversação. Solução que inclusive permite trocar de páginas usando GET sem o problema do escopo <code>view</code>, que desse modo não remove o bean, pois na conversação, se você não matar, o timeout mata.<br />
Uma forma simples de usar é iniciar a conversação quando abrimos a view. Para isso podemos fazer de <a href="http://stackoverflow.com/questions/6161618/postconstruct-called-multiple-time-for-conversationscoped-bean">várias formas</a>, mas a mais simples é usando o <a href="http://seamframework.org/Seam3/FacesModule">seam-faces</a>:</p>
<p><strong>Código da view</strong></p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;">&nbsp;
<span style="color: #339933;">&lt;</span>f:metadata<span style="color: #339933;">&gt;</span>
   <span style="color: #339933;">&lt;</span>s:viewAction action=<span style="color: #0000ff;">&quot;#{meuBean.init}&quot;</span> <span style="color: #000000;  font-weight: bold;">if</span>=<span style="color: #0000ff;">&quot;#{conversation.transient}&quot;</span> /<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;</span>/f:metadata<span style="color: #339933;">&gt;</span></pre></div></div>

<p><strong>Código do Bean</strong></p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;">@Named
@ConversationScoped
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MeuBean<span style="color: #009900;">&#123;</span>
    @Begin 
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #006600; font-weight: bold;">void</span> init<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Ou</p>
<p><strong>Código do Bean (alternativo)</strong></p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;">@Named
@ConversationScoped
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MeuBean<span style="color: #009900;">&#123;</span>
&nbsp;
    @In
    Conversation conversation
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #006600; font-weight: bold;">void</span> init<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        conversation.<span style="color: #006633;">begin</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: #009900;">&#125;</span></pre></div></div>

<p>Mas não estou dizendo para criar conversação e largar, tem que matar ela. Só estou falando que se for pra largar pra trás (coisa feia <img src='http://blog.gilliard.eti.br/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> ) é melhor fazer com conversação do que com view ou session.</p>
<p>E ainda outra forma de usar um escopo view em mais de uma página é usar o <a href="https://cwiki.apache.org/confluence/display/EXTCDI/JSF+Usage#JSFUsage-ViewAccessScope">@ViewAccessScope</a> do apache CODI (<a href="http://blog.gilliard.eti.br/2010/11/como-trabalhar-com-viewscope-e-page/#comment-13202">citado</a> também pelo João). Ele funciona como o &#8220;bom e velho&#8221; <a href="http://docs.jboss.org/richfaces/latest_3_3_X/en/devguide/html/a4j_keepAlive.html">Keep Alive</a> (anotação ao tag), e em vez de matar o bean na troca de página, ele espera o fim do response, e se o bem não for usado, aí sim é removido. O única problema é que a configuração do apache CODI, principalmente quando já estamos rodando o seam-faces, é um pouquinho mais charope. Mas funciona.</p>
<p><br/><br/></p>
<h3>
Concluindo&#8230;<br />
</h3>
<p><br/><br/></p>
<p>Nada do que mostrei aqui é novo ou difícil. Mas resolvi escrever pois em uma semana tive três dúvidas iguais aqui no blog sobre esse assunto. E nos cursos de Seam (escopo Page) e JSF 2 que ministro vejo que esse assunto demora para ser digerido também. Então espero que esse post tenha sido útil para minimizar essas dúvidas. Usar esse recurso do JSF 2 (ou Seam) é simples, mas se te incomodar muito, ou se você quiser usar uma conversação em uma única view (<code><strong>@ViewScope</strong></code> não segura o <code><strong>EntityManager</strong></code> aberto e com isso não evita <code><strong>LazyinitializationException</strong></code>), lembre-se que JEE6 define extensões portáveis. Então uma boa coisa é procurar coisas como o escopo que eu citei no início do post.</p>
<p>Sei que o pessoal do Java é meio purista, as vezes torce o nariz para o que não é especificado, mas se ganha muito procurando a solução para o seu problema em um projeto opensource bacana em vez de passar raiva e esperar até sair a próxima versão de alguma especificação, o que obviamente vai demorar mais do que uma novidade nascida direto da comunidade (apache, jboss.org, etc). Mas isso é assunto para um próximo post.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.gilliard.eti.br/2010/11/como-trabalhar-com-viewscope-e-page/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Desenvolvendo uma aplicação Desktop com Weld – Final</title>
		<link>http://blog.gilliard.eti.br/2010/05/aplicacao-desktop-com-weld-final/</link>
		<comments>http://blog.gilliard.eti.br/2010/05/aplicacao-desktop-com-weld-final/#comments</comments>
		<pubDate>Tue, 25 May 2010 18:30:56 +0000</pubDate>
		<dc:creator>Gilliard Cordeiro</dc:creator>
				<category><![CDATA[CDI]]></category>
		<category><![CDATA[JavaEE]]></category>
		<category><![CDATA[CDI SE]]></category>
		<category><![CDATA[JavaEE 6]]></category>
		<category><![CDATA[JSR-299]]></category>
		<category><![CDATA[JSR-330]]></category>
		<category><![CDATA[WebBeans]]></category>
		<category><![CDATA[Weld]]></category>
		<category><![CDATA[Weld-SE]]></category>

		<guid isPermaLink="false">http://blog.gilliard.eti.br/?p=254</guid>
		<description><![CDATA[Depois da parte 1 e parte 2, chegamos à parte final do nosso exemplo. Disponibilizei o código e vou mostrar mais algumas coisas. Só uma observação sobre o código: é o mesmo utilizado na apresentação de 14 de Novembro de 2009, quando ainda não tínhamos as mesmas versões de hoje. Mas o exemplo é totalmente [...]]]></description>
			<content:encoded><![CDATA[<p>Depois da <a href="http://blog.gilliard.eti.br/2010/03/aplicacao-desktop-com-weld-parte-1/">parte 1</a> e <a href="http://blog.gilliard.eti.br/2010/05/aplicacao-desktop-com-weld-parte-2/">parte 2</a>, chegamos à parte final do nosso exemplo. Disponibilizei o <a href="http://blog.gilliard.eti.br/arquivos/javaneiros-weld.zip">código</a> e vou mostrar mais algumas coisas.<br />
Só uma observação sobre o código: é o mesmo utilizado na apresentação de 14 de Novembro de 2009, quando ainda não tínhamos as mesmas versões de hoje. Mas o exemplo é totalmente funcional. Acabei deixando fixa a versão no pom.xml, então para testar a última versão você vai ter que alterá-lo.</p>
<p>Agora voltando ao post&#8230;</p>
<p><br/></p>
<h3>Alternatives</h3>
<p><br/></p>
<p>Alternatives são a forma de trocarmos um objeto por outro. É parecido com um decorator, mas em vez de incrementar funcionalidades, um alternative serve para substituir um bean.</p>
<p>No nosso exemplo, temos o seguinte objeto como alternativa ao nosso CaixaEletronico:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">@Alternative
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> CaixaEletronicoSubstituto <span style="color: #000000; font-weight: bold;">extends</span> CaixaEletronico<span style="color: #009900;">&#123;</span>
&nbsp;
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> depositar<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">float</span> valor<span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;@@@@@@ CaixaEletronicoMock.depositar():&quot;</span> <span style="color: #339933;">+</span> valor<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> sacar<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">float</span> valor<span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;@@@@@@ CaixaEletronicoMock.sacar():&quot;</span> <span style="color: #339933;">+</span> valor<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p><br/></p>
<p>E para habilitar temos que mudar novamente nosso META-INF/beans.xml:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
</pre></td><td class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;beans</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/xml/ns/javaee&quot;</span> <span style="color: #000066;">xmlns:xsi</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xsi:schemaLocation</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
	<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;class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>br.com.jugms.weldse.intercept.ContaInterceptor<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/class<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;decorators<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>br.com.jugms.weldse.intercept.CaixaDecorator<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/decorators<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;alternatives<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>br.com.jugms.weldse.model.CaixaEletronicoSubstituto<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/alternatives<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<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></td></tr></table></div>

<p><br/></p>
<p>Agora se executarmos nosso código a saída sera:</p>
<pre>
hello
CaixaDecorator.sacar()
@@@@@@ CaixaEletronicoMock.sacar():200.0
ContaInterceptor.protege(antes) >> getSaldo
ContaInterceptor.protege(depois) >> getSaldo
2000.0
CaixaDecorator.depositar()
@@@@@@ CaixaEletronicoMock.depositar():300.0
ContaInterceptor.protege(antes) >> getSaldo
ContaInterceptor.protege(depois) >> getSaldo
2000.0
</pre>
<p><br/></p>
<p>Como podemos ver, nosso decorator decora o alternative e o interceptor continua funcionando normalmente.<br />
Podemos também declarar uma anotação própria e anotá-la como alternative. Mas em vez de tentar explicar, vou mostrar um outro exemplo que servirá como base para este.</p>
<p><br/></p>
<h3>Estereótipos próprios</h3>
<p><br/></p>
<p>Podemos criar nossos próprios estereótipos, e dessa forma não só reduzir a quantidade de anotações em cima dos nossos beans, mas também deixar a leitura das anotações mais condizentes com nosso linguajar do dia a dia.</p>
<p>Vamos pegar como exemplo o nosso objeto ContaBancaria:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">br.com.jugms.weldse.model</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.enterprise.context.ApplicationScoped</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.enterprise.event.Observes</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.inject.Inject</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.inject.Named</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">br.com.jugms.weldse.intercept.Seguro</span><span style="color: #339933;">;</span>
&nbsp;
@ApplicationScoped
@Seguro
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ContaBancaria <span style="color: #009900;">&#123;</span>
	<span style="color: #666666; font-style: italic;">//o código já foi visto antes</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p><br/></p>
<p>Já vimos este código e o corpo da classe não tem relação com o que vamos ver agora. Agora o mais importante é observarmos as anotações. Temos duas, mas poderíamos ter mais. Para deixar isso mais limpo e com mais significado no meu negócio, poderia criar um estereótipo próprio como o seguinte:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
</pre></td><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">br.com.jugms.weldse.model</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">static</span> java.<span style="color: #006633;">lang</span>.<span style="color: #006633;">annotation</span>.<span style="color: #006633;">ElementType</span>.<span style="color: #006633;">TYPE</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">static</span> java.<span style="color: #006633;">lang</span>.<span style="color: #006633;">annotation</span>.<span style="color: #006633;">RetentionPolicy</span>.<span style="color: #006633;">RUNTIME</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.lang.annotation.Retention</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.lang.annotation.Target</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.enterprise.context.ApplicationScoped</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.enterprise.inject.Stereotype</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">br.com.jugms.weldse.intercept.Seguro</span><span style="color: #339933;">;</span>
&nbsp;
@ApplicationScoped
@Seguro
@Stereotype
@Target<span style="color: #009900;">&#40;</span>TYPE<span style="color: #009900;">&#41;</span>
@Retention<span style="color: #009900;">&#40;</span>RUNTIME<span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> @<span style="color: #000000; font-weight: bold;">interface</span> JavaneirosBean <span style="color: #009900;">&#123;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p><br/></p>
<p>E depois mudar nosso ContaBancaria deixando ele assim:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">br.com.jugms.weldse.model</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.enterprise.event.Observes</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.inject.Inject</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.inject.Named</span><span style="color: #339933;">;</span>
&nbsp;
@JavaneirosBean
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ContaBancaria <span style="color: #009900;">&#123;</span>
	<span style="color: #666666; font-style: italic;">//o código já foi visto antes</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p><br/></p>
<p>Com isso o resultado será o mesmo de antes. Nosso objeto ContaBancaria é @Seguro e @ApplicationScoped. Além disso se depois quisermos dizer que nosso @JavaneirosBean é também um @Alternative ou qualquer outro estereótipo pré-existente ou mesmo um outro estereótipo customizado, basta anotar nossa anotação @JavaneirosBean com a anotação desejada.</p>
<p>Pode parecer estranho usarmos anotações de anotações, mas para exemplificar, se a JPA suportasse isso eu poderia ter uma anotação @Entidade que seria uma @Entity (JPA) e ao mesmo tempo @Named (CDI) e assim poder utilizá-la diretamente nas minhas view JSF com uma única anotação.</p>
<p><br/></p>
<h3>Conceitos gerais</h3>
<p><br/></p>
<p>Eu disse que ao final do exemplo iria entrar mais na parte teórica de como a CDI trata mais extamente a injeção de dependência, seleção de candidatos etc. Porém por questão de organização, vou deixar isso em um post separado.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.gilliard.eti.br/2010/05/aplicacao-desktop-com-weld-final/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Desenvolvendo uma aplicação Desktop com Weld – Parte 2</title>
		<link>http://blog.gilliard.eti.br/2010/05/aplicacao-desktop-com-weld-parte-2/</link>
		<comments>http://blog.gilliard.eti.br/2010/05/aplicacao-desktop-com-weld-parte-2/#comments</comments>
		<pubDate>Tue, 25 May 2010 15:09:52 +0000</pubDate>
		<dc:creator>Gilliard Cordeiro</dc:creator>
				<category><![CDATA[CDI]]></category>
		<category><![CDATA[JavaEE]]></category>
		<category><![CDATA[CDI SE]]></category>
		<category><![CDATA[JavaEE 6]]></category>
		<category><![CDATA[JSR-299]]></category>
		<category><![CDATA[JSR-330]]></category>
		<category><![CDATA[WebBeans]]></category>
		<category><![CDATA[Weld]]></category>
		<category><![CDATA[Weld-SE]]></category>

		<guid isPermaLink="false">http://blog.gilliard.eti.br/?p=241</guid>
		<description><![CDATA[Continuando então no nosso exemplo, vamos comentar mais sobre a &#8220;parte prática&#8221; do exemplo e depois eu comento mais sobre os tipos de injeção que a CDI faz. E só pra contextualizar, quando eu disse &#8220;ejeção&#8221; no último post, não quer dizer que a CDI tem um @Out como o Seam, e sim que ele [...]]]></description>
			<content:encoded><![CDATA[<p>Continuando então no nosso exemplo, vamos comentar mais sobre a &#8220;parte prática&#8221; do exemplo e depois eu comento mais sobre os tipos de injeção que a CDI faz. E só pra contextualizar, quando eu disse &#8220;ejeção&#8221; no <a href="http://blog.gilliard.eti.br/2010/03/aplicacao-desktop-com-weld-parte-1/">último post</a>, não quer dizer que a CDI tem um @Out como o Seam, e sim que ele tem uma forma de produzir objetos para um determinado escopo assim como um @Factory do Seam ou Spring. </p>
<p><br/></p>
<h3>Interceptors</h3>
<p><br/></p>
<p>No final do <a href="http://blog.gilliard.eti.br/2010/03/aplicacao-desktop-com-weld-parte-1/">ultimo post</a> vimos que nossa <code>ContaBancaria</code> estava anotada com @Seguro. Essa é uma anotação da nossa aplicação:</p>
<p><br/></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
</pre></td><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">br.com.jugms.weldse.intercept</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">static</span> java.<span style="color: #006633;">lang</span>.<span style="color: #006633;">annotation</span>.<span style="color: #006633;">ElementType</span>.<span style="color: #006633;">METHOD</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">static</span> java.<span style="color: #006633;">lang</span>.<span style="color: #006633;">annotation</span>.<span style="color: #006633;">ElementType</span>.<span style="color: #006633;">TYPE</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">static</span> java.<span style="color: #006633;">lang</span>.<span style="color: #006633;">annotation</span>.<span style="color: #006633;">RetentionPolicy</span>.<span style="color: #006633;">RUNTIME</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.lang.annotation.Retention</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.lang.annotation.Target</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.interceptor.InterceptorBinding</span><span style="color: #339933;">;</span>
&nbsp;
@InterceptorBinding
@Target<span style="color: #009900;">&#40;</span> <span style="color: #009900;">&#123;</span> METHOD, TYPE <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>
@Retention<span style="color: #009900;">&#40;</span>RUNTIME<span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> @<span style="color: #000000; font-weight: bold;">interface</span> Seguro <span style="color: #009900;">&#123;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p><br/></p>
<p>No meio de um monte de anotações percebemos a que define nossa anotação como uma @InterceptorBinding. Agora basta anotar quem queremos interceptar com a mesma anotação usada na definição do interceptor (@Seguro) para &#8220;bindar&#8221; interceptador e interceptado.</p>
<p><br/></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
</pre></td><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">br.com.jugms.weldse.intercept</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.interceptor.AroundInvoke</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.interceptor.Interceptor</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.interceptor.InvocationContext</span><span style="color: #339933;">;</span>
&nbsp;
&nbsp;
@Interceptor @Seguro
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ContaInterceptor <span style="color: #009900;">&#123;</span>
&nbsp;
	@AroundInvoke
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Object</span> protege<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;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;ContaInterceptor.protege(antes) &gt;&gt; &quot;</span> <span style="color: #339933;">+</span> context.<span style="color: #006633;">getMethod</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #003399;">Object</span> object <span style="color: #339933;">=</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>
&nbsp;
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;ContaInterceptor.protege(depois) &gt;&gt; &quot;</span> <span style="color: #339933;">+</span> context.<span style="color: #006633;">getMethod</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">return</span> object<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p><br/></p>
<p>Esse é o nosso interceptador. Olhando o código quase não preciso explicar nada. Aqui coloquei Conta no meio do nome porque é uma aplicação de exemplo, mas na prática poderia ter um uso mais genérico. Esse código tem o jeitão de um interceptador comum. O método &#8220;protege&#8221; está anotado com @AroundInvoke, e isso me dá o poder de envolver, e com isso até mesmo trocar a implementação original do objeto interceptado. É bem parecido com <a href="http://pt.wikipedia.org/wiki/Programa%C3%A7%C3%A3o_orientada_a_aspecto">AOP</a>. Mas a regra do <a href="http://pt.wikipedia.org/wiki/Ben_Parker">tio Ben</a> se aplica aqui também: <em>&#8220;Grandes poderes trazem grandes responsabilidades&#8221;</em>! Então isso não serve para ficar adicionando regra de negócio na aplicação, senão depois você não vai achar mais nada no sistema e vai falar que viu isso aqui. A idéia de um interceptor é prover funcionalidades ortogonais para o sistema, assim como AOP. Então se você não gosta de AOP ou interceptor é provavelmente porque está colocando código no local errado.</p>
<p>Nesse exemplo usei para prover segurança, protegendo meus objetos marcados com @Seguro. Mas minha implementação simplesmente mostra no console que o nosso método foi chamado.</p>
<p>Além de interceptors, temos <a href="http://en.wikipedia.org/wiki/Decorator_pattern">decorators</a>, que veremos daqui a pouco. Mas para já ter uma idéia da diferença, o interceptor geralmente é para requisitos não funcionais, enquanto os decorators adicionam funcionalidades em objetos do nosso sistema. Mas o foco aqui não é padrões de projeto, então para saber mais basta dar uma pesquisada. O que importa para o contexto desse post é que tanto interceptors quanto decorators não estão habilitados por padrão. Para colocá-los para rodar precisamos &#8220;ligá-los&#8221; no arquivo /META-INF/beans.xml. Abaixo vemos como fica nosso arquivo com esse interceptor ligado.</p>
<p><br/></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;beans</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/xml/ns/javaee&quot;</span> <span style="color: #000066;">xmlns:xsi</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xsi:schemaLocation</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
	<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;class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>br.com.jugms.weldse.intercept.ContaInterceptor<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/class<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;/beans<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></td></tr></table></div>

<p><br/></p>
<p>Eu sei que sou repetitivo, mas mais uma vez eu digo: não precisamos habilitar beans injetáveis ou gerenciáveis quando usamos CDI. Basta que os objetos estejam em um bean package para tudo acontecer, e um bean package é um módulo (jar, projeto, etc) que tenha um arquivo /META-INF/beans.xml vazio (só com cabeçalho). Pronto, só precisa disso. As exceções são para interceptors, decorators e alternatives (esse ultimo falo depois). Esses sim precisam ser habilitados.</p>
<p>Agora que já temos tudos os arquivos, executando a aplicação temos a seguinte saída:</p>
<pre>
hello
ContaInterceptor.protege(antes) >> recebeMovimento
ContaInterceptor.protege(depois) >> recebeMovimento
ContaInterceptor.protege(antes) >> getSaldo
ContaInterceptor.protege(depois) >> getSaldo
1800.0
ContaInterceptor.protege(antes) >> recebeMovimento
ContaInterceptor.protege(depois) >> recebeMovimento
ContaInterceptor.protege(antes) >> getSaldo
ContaInterceptor.protege(depois) >> getSaldo
2100.0
</pre>
<p>Como estamos usando @AroundInvoke, colocamos uma mensagem antes e uma depois de cada método.</p>
<p><br/></p>
<h3>Decorators</h3>
<p><br/></p>
<p>Agora que vimos o interceptor, fica mais fácil entendermos o decorator. Vamos ao código</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
</pre></td><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">br.com.jugms.weldse.intercept</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.decorator.Decorator</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.decorator.Delegate</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.inject.Inject</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">br.com.jugms.weldse.model.CaixaEletronico</span><span style="color: #339933;">;</span>
&nbsp;
@Decorator
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> CaixaDecorator <span style="color: #000000; font-weight: bold;">extends</span> CaixaEletronico <span style="color: #009900;">&#123;</span>
&nbsp;
	@Inject
	@<span style="color: #003399;">Delegate</span>
	<span style="color: #000000; font-weight: bold;">private</span> CaixaEletronico delegate<span style="color: #339933;">;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> sacar<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">float</span> valor<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;CaixaDecorator.sacar()&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		delegate.<span style="color: #006633;">sacar</span><span style="color: #009900;">&#40;</span>valor<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> depositar<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">float</span> valor<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;CaixaDecorator.depositar()&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		delegate.<span style="color: #006633;">depositar</span><span style="color: #009900;">&#40;</span>valor<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p><br/></p>
<p>Um decorator precisa ter condições de <a href="http://pt.wikipedia.org/wiki/Princ%C3%ADpio_da_substitui%C3%A7%C3%A3o_de_Liskov">substituir</a> o objeto original (extender, implementar mesma interface). Além disso temos o objeto original que é injetado através da anotação @Delegate juntamente com a @Inject. Aqui também podemos utilizar diversos estereótipos para &#8220;selecionar&#8221; o objeto a ser decorado. Como os demais exemplos dessa nossa aplicação, esse decorator é extremamente complexo ao printar no console que ele foi executado <img src='http://blog.gilliard.eti.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' />  .</p>
<p>Agora basta adicionarmos ele no beans.xml:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;beans</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/xml/ns/javaee&quot;</span> <span style="color: #000066;">xmlns:xsi</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">xsi:schemaLocation</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
	<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;class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>br.com.jugms.weldse.intercept.ContaInterceptor<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/class<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;decorators<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>br.com.jugms.weldse.intercept.CaixaDecorator<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/class<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/decorators<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<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></td></tr></table></div>

<p><br/></p>
<p>E agora a saída no console é a seguinte:</p>
<pre>
hello
CaixaDecorator.sacar()
ContaInterceptor.protege(antes) >> recebeMovimento
ContaInterceptor.protege(depois) >> recebeMovimento
ContaInterceptor.protege(antes) >> getSaldo
ContaInterceptor.protege(depois) >> getSaldo
1800.0
CaixaDecorator.depositar()
ContaInterceptor.protege(antes) >> recebeMovimento
ContaInterceptor.protege(depois) >> recebeMovimento
ContaInterceptor.protege(antes) >> getSaldo
ContaInterceptor.protege(depois) >> getSaldo
2100.0
</pre>
<p><br/></p>
<p>Apesar da saída no console mostrar nosso decorator antes do nosso interceptor, isso é porque estamos decorando e interceptando coisas diferentes, pois decorators são chamados <strong>depois</strong> dos interceptors.</p>
<p>Em seguida posto como funcionam os alternatives e o que faltou colocar nesses dois primeiros posts.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.gilliard.eti.br/2010/05/aplicacao-desktop-com-weld-parte-2/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Desenvolvendo uma aplicação Desktop com Weld – Parte 1</title>
		<link>http://blog.gilliard.eti.br/2010/03/aplicacao-desktop-com-weld-parte-1/</link>
		<comments>http://blog.gilliard.eti.br/2010/03/aplicacao-desktop-com-weld-parte-1/#comments</comments>
		<pubDate>Wed, 17 Mar 2010 15:06:56 +0000</pubDate>
		<dc:creator>Gilliard Cordeiro</dc:creator>
				<category><![CDATA[CDI]]></category>
		<category><![CDATA[JavaEE]]></category>
		<category><![CDATA[CDI SE]]></category>
		<category><![CDATA[JavaEE 6]]></category>
		<category><![CDATA[JSR-299]]></category>
		<category><![CDATA[JSR-330]]></category>
		<category><![CDATA[WebBeans]]></category>
		<category><![CDATA[Weld]]></category>
		<category><![CDATA[Weld-SE]]></category>

		<guid isPermaLink="false">http://blog.gilliard.eti.br/?p=196</guid>
		<description><![CDATA[Como havia comentado, em Novembro do ano passado eu apresentei uma palestra no Javaneiros, evento anual sobre Java organizado pelo JUGMS. Os slides eu já disponibilizei no post anterior, e agora vou de fato colocar aqui no blog o que mostrei na palestra, pois slides sem explicação não serve para muita coisa né? Como acho [...]]]></description>
			<content:encoded><![CDATA[<p>Como havia comentado, em Novembro do ano passado eu apresentei uma palestra no Javaneiros, evento anual sobre Java organizado pelo JUGMS. Os slides eu já disponibilizei no post anterior, e agora vou de fato colocar aqui no blog o que mostrei na palestra, pois slides sem explicação não serve para muita coisa né? </p>
<p>Como acho que um post só vai ficar muito grande, vou publicar o conteúdo em partes.</p>
<p><br/></p>
<h3>Intradução</h3>
<p><br/></p>
<p><img src="http://blog.gilliard.eti.br/wp-content/uploads/2010/03/cdi1.png" alt="" title="Vários nomes envolvidos na JSR-299" class="alignnone size-full wp-image-231" /></p>
<p>Primeiramente eu gostaria de explicar, para quem não está familiarizado, o que é a CDI. Hoje em dia está mais difundido que na época da palestra, mas até para manter a coerência com os slides vou comentar rapidamente alguma coisa. Se seu objetivo é ver código, pode pular esse tópico.</p>
<p>A CDI, ou &#8220;<strong>Context and Dependency Injection for the Java EE platform</strong>&#8221; é uma especificação que define uma forma padrão de trabalharmos com DI em aplicações Java. Pelo nome já vemos que ela é voltada para Java EE, mas está seguindo os mesmos passos da JPA, que foi introduzida no Java EE 5 mas é usada sem problemas em aplicações SE.</p>
<p>Talvez a coisa que valha mais a pena comentar antes de entrar na prática é o monte de nomes envolvidos nessa JSR. O primeiro &#8220;nome&#8221; é a própria identificação da JSR: &#8220;JSR-299&#8243;. Acho que até quem nunca foi ligado em número de JSR já ouviu falar dessa tal de 299. Para resumir a história, ela já se chamou WebBeans antes de se chamar CDI, e até hoje muita coisa na internet, principalmente as discussões iniciais você vai encontrar esse nome. Além disso tem a implementação de referência dela, que também já chamou WebBeans e agora é Weld. Ou seja, de WebBeans não sobrou nada.</p>
<p><img src="http://blog.gilliard.eti.br/wp-content/uploads/2010/03/cdi2.png" alt="" title="Evolução dos nomes na linha do tempo" class="aligncenter size-full wp-image-232" /></p>
<p>Outra coisa que veio dar uma cofundida nesses nomes foi a JSR-330, &#8220;<strong>Dependency Injection for Java</strong>&#8220;, que nada mais é do que a extração das anotações da CDI para uma especificação menor, tornando assim mais fácil que frameworks como Spring e Guice utilizem anotações padrão mesmo não sendo uma implementação da CDI. Isso gerou muita polêmica também, pois em tese a CDI já deveria ser mínima e não faz sentido alguém usar as anotações dela sem ter o mesmo comportamento. Mas isso já é outra história.</p>
<p><br/></p>
<h3>Ainda antes de começar&#8230;</h3>
<p><br/></p>
<p>A CDI sofreu muita influência do Seam e Guice, além é claro de não ser difícil de compreender para quem trabalha com Spring, pois no fim das contas os conceitos são os mesmos.</p>
<p>Uma premissa muito forte da CDI é a injeção de dependência &#8220;<em>type safe</em>&#8220;, o que já a diferencia bastante do Seam que trabalha muito com Strings. Nesse ponto já fica mais perto para quem trabalha com Spring do que quem tá acostumado com Seam.</p>
<p>Outra coisa que temos que ter em mente é que diferentemente do Spring ou Seam onde uma classe simples não é considerada uma candidata à injeção de dependência a menos que seja marcada (via xml ou anotação), na CDI se a classe está dentro de um <em>bean package</em> então ela automaticamente é elegível. Mas isso nós vamos ver na aplicação de exemplo.</p>
<p>Outra coisa que temos que ter em mente é que o objetivo da CDI não é substituir o Seam. O Seam tem um mundo de coisas como facilitadores para e-mail, pdf, bpm, segurança, jsf, etc. A CDI define apenas o core o que será o core do Seam 3, ou seja, a parte da DI, interceptors e mais algumas coisas. Então não vamos comparar coisas tão diferentes com comentários tipo &#8220;O Seam é muito melhor que o Weld. O Weld não faz nada, o Seam faz um monte de coisas&#8221;.</p>
<p><img src="http://blog.gilliard.eti.br/wp-content/uploads/2010/03/cdi3.png" alt="" title="Relação do Seam com Weld e CDI" class="aligncenter size-full wp-image-233" /></p>
<p>A primeira coisa que precisamos saber para trabalhar com a CDI é o que é um <em>bean package</em>. Na prática um <em>bean package</em> vai ser um jar (ou pode estar explodido mesmo) onde temos um arquivo <code>META-INF/beans.xml</code>. Se a CDI encontrar esse cara, ela escaneia tudo e considera todas classes dentro desse &#8220;<em>módulo</em>&#8221; como beans injetáveis. É análogo ao seam.properties, mas no caso do Seam ainda precisa ter a anotação ou estar no <em>components.xml</em> para a classe ser considerada.</p>
<p>Outra coisa que vamos ver no exemplo é que o mesmo se trata de uma aplicação SE de console. Aí nos perguntamos: mas no nome da especificação não fala que é para Java EE? Pois é, mas a especificação define também a criação de extensões portáveis. Isso quer dizer que você pode fazer uma extensão da CDI e rodar em qualquer implementação dela. Pois bem, o Weld tem uma extensão que permite que rodemos tudo isso num ambiente SE, porém com limitações, claro.</p>
<p><br/></p>
<h3>Agora vamos à pratica</h3>
<p><br/></p>
<p>O nosso exemplo é bem simples, e consiste em realizarmos um saque e um depósito em uma conta bancária via um caixa eletrônico. Para simplificar o exemplo, temos apenas uma conta e um caixa eletrônico.</p>
<p>Nossa aplicação inicia com a classe MovimentacaoControl.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
</pre></td><td class="code"><pre class="java5" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">br.com.jugms.weldse.control</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.enterprise.context.ApplicationScoped</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.enterprise.event.Observes</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.inject.Inject</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.jboss.weld.environment.se.events.ContainerInitialized</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">br.com.jugms.weldse.model.CaixaEletronico</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">br.com.jugms.weldse.model.ContaBancaria</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #008000; font-style: italic; font-weight: bold;">/**
* @author http://gilliard.eti.br
*/</span>
@ApplicationScoped
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MovimentacaoControl<span style="color: #009900;">&#123;</span>
&nbsp;
    @Inject <span style="color: #000000; font-weight: bold;">private</span> ContaBancaria contaBancaria<span style="color: #339933;">;</span>
    @Inject <span style="color: #000000; font-weight: bold;">private</span> CaixaEletronico caixaEletronico<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #006600; font-weight: bold;">void</span> executar<span style="color: #009900;">&#40;</span>@Observes ContainerInitialized init<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
        <span style="color: #003399; font-weight: bold;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;hello&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        caixaEletronico.<span style="color: #006633;">sacar</span><span style="color: #009900;">&#40;</span>200.0f<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #003399; font-weight: bold;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>contaBancaria.<span style="color: #006633;">getSaldo</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        caixaEletronico.<span style="color: #006633;">depositar</span><span style="color: #009900;">&#40;</span>300.0f<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #003399; font-weight: bold;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>contaBancaria.<span style="color: #006633;">getSaldo</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Como podemos ver essa classe possui a anotação @ApplicationScoped, mas essa anotação não serve para habilitar o gerenciamento dos objetos dessa classe, pois como eu disse anteriormente, isso é automático já que estamos em um bean package.</p>
<p>Essa classe também não possui um método main. Para executar o exemplo executamos a classe <code>org.jboss.weld.environment.se.StartMain</code>, e essa sim possui um método main, que inicializa todo o framework e quando termina de inicializar o container ele avisa lançando um evento do tipo <code>org.jboss.weld.environment.se.events.ContainerInitialized</code>. Para iniciarmos nossa aplicação, basta escutarmos esse evento como é feito no método &#8220;<code>executar</code>&#8220;. Deu para perceber que escutar um evento é algo muito complicado <img src='http://blog.gilliard.eti.br/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . Nesse caso não faremos nada com o objeto init que é o que representa o evento, mas no decorrer do exemplo veremos como isso funciona.</p>
<p>No nosso exemplo, nós realizamos um saque de 200, depois olhamos o saldo, depositamos 300 e olhamos o saldo de novo. Parece bobo (e não vou negar isso), mas é útil para testarmos os diferentes escopos. Pois quando mudamos os scopos para stateless (default, sem a anotação @ApplicationScoped) percebemos que a conta sempre volta a ter o valor inicial.</p>
<p>Nesse exemplo estou trabalhando com classes, mas para trabalhar com interfaces o procedimento é o mesmo, ao ver que você pediu para injetar um objeto tipado por uma determinada interface a CDI vai procurar por uma implementação da mesma, e encontrando injeta. Agora se ela encontrar nenhuma ou mais de uma, aí será lançada uma excessão. &#8220;Poxa, mas e se eu tiver mais de uma implementação no bean package&#8221;? <a href="http://pt.wikipedia.org/wiki/El_Chapul%C3%ADn_Colorado" target="_blank">Palma, palma, palma, não priemos cânico</a>, vamos chegar a ver isso.</p>
<p><br/></p>
<h3>Manipulação de eventos</h3>
<p><br/></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
</pre></td><td class="code"><pre class="java5" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">br.com.jugms.weldse.model</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.enterprise.event.Event</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.inject.Inject</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #008000; font-style: italic; font-weight: bold;">/**
* @author http://gilliard.eti.br
*/</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> CaixaEletronico <span style="color: #009900;">&#123;</span>
&nbsp;
    @Inject <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399; font-weight: bold;">Event</span><span style="color: #339933;">&lt;</span>Movimentacao<span style="color: #339933;">&gt;</span> eventMovimentacao<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #006600; font-weight: bold;">void</span> depositar<span style="color: #009900;">&#40;</span><span style="color: #006600; font-weight: bold;">float</span> valor<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        eventMovimentacao.<span style="color: #006633;">fire</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Movimentacao<span style="color: #009900;">&#40;</span>valor<span style="color: #009900;">&#41;</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;">public</span> <span style="color: #006600; font-weight: bold;">void</span> sacar<span style="color: #009900;">&#40;</span><span style="color: #006600; font-weight: bold;">float</span> valor<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        eventMovimentacao.<span style="color: #006633;">fire</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Movimentacao<span style="color: #009900;">&#40;</span>-<span style="color: #cc66cc;">1</span> <span style="color: #339933;">*</span> valor<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
</pre></td><td class="code"><pre class="java5" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">br.com.jugms.weldse.model</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #008000; font-style: italic; font-weight: bold;">/**
* @author http://gilliard.eti.br
*/</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Movimentacao <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #006600; font-weight: bold;">float</span> valor<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> Movimentacao<span style="color: #009900;">&#40;</span><span style="color: #006600; font-weight: bold;">float</span> valor<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">valor</span> = valor<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #006600; font-weight: bold;">float</span> getValor<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> valor<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Como podemos ver, a classe <code>CaixaEletronico</code> não tem nenhuma anotação para &#8220;ativá-la&#8221; como injetável, e ainda assim ela é injetada no nosso objeto da classe <code>MovimentacaoControl</code>. Podemos ver também que nossa classe <code>CaixaEletronico</code> não debita diretamente da nossa conta (que nesse exemplo simplista só existe uma). O <code>CaixaEletronico</code> envia uma mensagem que é representada pela classe <code>Movimentacao</code>. Para disparar esse evento nosso <code>CaixaEletronico</code> pede para que seja injetado nele um &#8216;cara&#8217; que sabe disparar eventos do tipo <code>Movimentacao</code>. E então no depósito ele dispara uma movimentação com valor positivo e no saque uma com valor negativo. Bem simples.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
</pre></td><td class="code"><pre class="java5" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">br.com.jugms.weldse.model</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.enterprise.context.ApplicationScoped</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.enterprise.event.Observes</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.inject.Inject</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.inject.Named</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">br.com.jugms.weldse.intercept.Seguro</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #008000; font-style: italic; font-weight: bold;">/**
* @author http://gilliard.eti.br
*/</span>
@ApplicationScoped
@Seguro
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ContaBancaria <span style="color: #009900;">&#123;</span>
&nbsp;
    @Inject @Named
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #006600; font-weight: bold;">float</span> saldoInicial = 1000.0f<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #006600; font-weight: bold;">void</span> recebeMovimento<span style="color: #009900;">&#40;</span>@Observes Movimentacao movimentacao<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        saldoInicial += movimentacao.<span style="color: #006633;">getValor</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;">public</span> <span style="color: #006600; font-weight: bold;">float</span> getSaldo<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> saldoInicial<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Agora na classe <code>ContaBancaria</code> vemos como consumir um evento. Na verdade já tinhamos visto na classe <code>MovimentacaoControl</code>, mas agora vamos de fato utilizar o objeto do evento. Como na <code>MovimentacaoControl</code>, para escutarmos um evento basta termos um método com um parâmetro do tipo do objeto do evento anotado com @Observes. Além disso podemos ver o escopo desse objeto, que é de aplicação. Comente esse escopo e você vai perceber que serão criadas várias contas bancárias, e dessa forma vamos debitar em uma e creditar na outra.</p>
<p>Podemos ver também a injeção de um &#8216;cara&#8217; do tipo float, mas além de @Inject usamos um @Named para isso. O @Named é um qualificador. Nós também podemos, em vários casos vamos &#8220;precisar&#8221;, criar nosso próprios qualificadores. Um qualificador serve para especificar melhor qual candidato à injeção queremos que seja escolhido. Seria como uma cláusula &#8220;where&#8221; na pesquisa por injetáveis. No caso desse float, obviamente algém vai ter que colocá-lo no contexto para que possamos recuperá-lo, e podemos ver isso na classe Produtores.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
</pre></td><td class="code"><pre class="java5" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">br.com.jugms.weldse.model</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.enterprise.inject.Produces</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.inject.Named</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #008000; font-style: italic; font-weight: bold;">/**
* @author http://gilliard.eti.br
*/</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Produtores <span style="color: #009900;">&#123;</span>
&nbsp;
    @Produces @Named
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #006600; font-weight: bold;">float</span> getSaldoInicial<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> 2000.0f<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Essa classe agrega todos os métodos produtores da nossa aplicação (que por ser extremamente complexa tem exatamente um <img src='http://blog.gilliard.eti.br/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ). Um método produtor (anotado com @Produces) é o oposto do consumidor (@Inject), logo em vez de pegar, ele joga um obejto no contexto, usando como qualificador o @Named que permite darmos um nome ao componente. Só temos que tomar cuidado para não usarmos demais isso e acabarmos tendo tudo ligado via Strings. Nesse exemplo, o nome usado para registrar esse componente é &#8220;saldoInicial&#8221;, pois segue o padrão java bean.</p>
<p>Podemos ver também que que na classe <code>ContaBancaria</code> deixei um saldo inicial de 1000, e depois mandei injetar nessa propriedade o valor de um componente do tipo float chamado &#8220;saldoInicial&#8221; que está com valor 2000. Na prática ficará valendo o 2000, pois o 1000 só vai valer antes que as injeções sejam executadas.</p>
<p>Nos próximos posts eu faço uma sessão específica para comentar as possibilidade de injeção e &#8220;ejeção&#8221; que a CDI provê. E também vou explicar o funcionamento dos interceptadores como podemos ver através da anotação @Seguro da classe <code>ContaBancaria</code>, e também como especificarmos qual implementação de uma interface vamos querer que seja selecionada. Como dá para perceber esse assunto vai longe. Então até o próximo post.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.gilliard.eti.br/2010/03/aplicacao-desktop-com-weld-parte-1/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Apresentacao sobre CDI (JSR-299) no Javaneiros2009</title>
		<link>http://blog.gilliard.eti.br/2010/02/apresentacao-sobre-cdi-jsr-299-no-javaneiros2009/</link>
		<comments>http://blog.gilliard.eti.br/2010/02/apresentacao-sobre-cdi-jsr-299-no-javaneiros2009/#comments</comments>
		<pubDate>Thu, 25 Feb 2010 16:33:13 +0000</pubDate>
		<dc:creator>Gilliard Cordeiro</dc:creator>
				<category><![CDATA[CDI]]></category>
		<category><![CDATA[JavaEE]]></category>
		<category><![CDATA[CDI SE]]></category>
		<category><![CDATA[JavaEE 6]]></category>
		<category><![CDATA[JSR-299]]></category>
		<category><![CDATA[JSR-330]]></category>
		<category><![CDATA[Seam]]></category>
		<category><![CDATA[Seam 3]]></category>
		<category><![CDATA[WebBeans]]></category>
		<category><![CDATA[Weld]]></category>
		<category><![CDATA[Weld-SE]]></category>

		<guid isPermaLink="false">http://blog.gilliard.eti.br/?p=179</guid>
		<description><![CDATA[Estou a um bom tempo sem postar, mas nesse tempo fiz bastante coisa que acabei não postando aqui. Uma delas foi uma palestra no Javaneiros2009, falando sobre a JSR-299. Ainda vou postar aqui o exemplo, mas como pretendo explicar cada parte, e isso vai levar mais tempo, já vou postando os slides até para tirar [...]]]></description>
			<content:encoded><![CDATA[<p>Estou a um bom tempo sem postar, mas nesse tempo fiz bastante coisa que acabei não postando aqui. Uma delas foi uma palestra no Javaneiros2009, falando sobre a JSR-299.</p>
<p>Ainda vou postar aqui o exemplo, mas como pretendo explicar cada parte, e isso vai levar mais tempo, já vou postando os slides até para tirar a poeira do blog.</p>
<p><strong>Update:</strong><br />
<a href="http://blog.gilliard.eti.br/2010/03/aplicacao-desktop-com-weld-parte-1/">Desenvolvendo uma aplicação Desktop com Weld – Parte 1</a><br />
<a href="http://blog.gilliard.eti.br/2010/05/aplicacao-desktop-com-weld-parte-2/">Desenvolvendo uma aplicação Desktop com Weld – Parte 2</a><br />
<a href="http://blog.gilliard.eti.br/2010/05/aplicacao-desktop-com-weld-final/">Desenvolvendo uma aplicação Desktop com Weld – Final</a></p>
<div style="width:425px" id="__ss_3122974"><strong style="display:block;margin:12px 0 4px"><a href="http://www.slideshare.net/gscordeiro/do-seam-ao-cdi-jsr299" title="Do Seam à CDI (JSR-299)">Do Seam à CDI (JSR-299)</a></strong><object width="425" height="355"><param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=doseamaocdi-100210075749-phpapp02&#038;stripped_title=do-seam-ao-cdi-jsr299" /><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=doseamaocdi-100210075749-phpapp02&#038;stripped_title=do-seam-ao-cdi-jsr299" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"></embed></object>
<div style="padding:5px 0 12px">View more <a href="http://www.slideshare.net/">presentations</a> from <a href="http://www.slideshare.net/gscordeiro">gscordeiro</a>.</div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://blog.gilliard.eti.br/2010/02/apresentacao-sobre-cdi-jsr-299-no-javaneiros2009/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Mojarra (JSF RI) 2.0 disponível</title>
		<link>http://blog.gilliard.eti.br/2009/10/mojarra-jsf-ri-2-0-disponivel/</link>
		<comments>http://blog.gilliard.eti.br/2009/10/mojarra-jsf-ri-2-0-disponivel/#comments</comments>
		<pubDate>Mon, 19 Oct 2009 18:47:31 +0000</pubDate>
		<dc:creator>Gilliard Cordeiro</dc:creator>
				<category><![CDATA[JavaEE]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[JavaServer Faces]]></category>

		<guid isPermaLink="false">http://blog.gilliard.eti.br/2009/10/mojarra-jsf-ri-2-0-disponivel/</guid>
		<description><![CDATA[Depois de uma boa espera, está disponível a versão final do JSF 2.0. Nos demais post deste blog você pode ver alguns exemplos de novas funcionalidades e baixar projetos com JSF 2 (não a versão final) rodando. Como faz algum tempo que eu venho postando sobre isso, alguns exemplos podem ter pequenas diferenças do que [...]]]></description>
			<content:encoded><![CDATA[<p>Depois de uma boa espera, está disponível a versão final do <a href="https://javaserverfaces.dev.java.net/servlets/ProjectDocumentList?folderID=11852">JSF 2.0</a>.</p>
<p>Nos <a href="http://blog.gilliard.eti.br/category/jsf/">demais post</a> deste blog você pode ver alguns exemplos de novas funcionalidades e baixar projetos com JSF 2 (não a versão final) rodando.</p>
<p>Como faz algum tempo que eu venho postando sobre isso, alguns exemplos podem ter pequenas diferenças do que está agora na versão final, mas nada que prejudique o entendimento, pois apesar da implementação estar saindo agora, a especificação já está pronta há algum tempo.</p>
<p>Tem vários assuntos que não tive tempo de escrever um post, mas hoje em dia já não está difícil encontrar exemplos de JSF 2 na internet.</p>
<p>Outros links:</p>
<p><a href="https://javaserverfaces.dev.java.net/">https://javaserverfaces.dev.java.net/</a><br />
<a href="https://javaserverfaces.dev.java.net/nonav/rlnotes/2.0.0/index.html">https://javaserverfaces.dev.java.net/nonav/rlnotes/2.0.0/index.html</a><br />
<a href="https://javaserverfaces.dev.java.net/maven2">https://javaserverfaces.dev.java.net/maven2</a></p>
<p>Boa diversão <img src='http://blog.gilliard.eti.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.gilliard.eti.br/2009/10/mojarra-jsf-ri-2-0-disponivel/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>URLs amigáveis no JSF 2.0</title>
		<link>http://blog.gilliard.eti.br/2009/05/urls-amigaveis-no-jsf-2/</link>
		<comments>http://blog.gilliard.eti.br/2009/05/urls-amigaveis-no-jsf-2/#comments</comments>
		<pubDate>Thu, 28 May 2009 03:36:19 +0000</pubDate>
		<dc:creator>Gilliard Cordeiro</dc:creator>
				<category><![CDATA[JavaEE]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[bookmarking]]></category>
		<category><![CDATA[JavaServer Faces]]></category>

		<guid isPermaLink="false">http://blog.gilliard.eti.br/?p=163</guid>
		<description><![CDATA[Hoje vou falar de mais uma novidade do JSF 2, cuja falta era motivo de muita reclamação: URLs amigávies, bookmarking, método GET e outros nomes que podemos dar. O suporte a essa nova funcionalidade é dado por dois pares de componentes, de um lado h:button e h:link e do outro f:metadata e f:viewParam. Os componentes [...]]]></description>
			<content:encoded><![CDATA[<p>Hoje vou falar de mais uma novidade do JSF 2, cuja falta era motivo de muita reclamação: URLs amigávies, bookmarking, método GET e outros nomes que podemos dar. O suporte a essa nova funcionalidade é dado por dois pares de componentes, de um lado h:button e h:link e do outro f:metadata e f:viewParam.</p>
<p>Os componentes h:button e h:link servem para originar as ações jsf assim como os componentes h:command{Button|Link}, porém usando GET em vez de POST. Esses componentes possuem um atributo chamado <strong>outcome</strong>, que representa a regra de navegação do JSF, assim como seria colocar uma String diretamente na action do h:command{Button|Link}. Para passar parâmetros colocamos a tag f:param dentro do h:link ou h:button.</p>
<p>Como exemplo vamos ver uma aplicaçãozinha que tem uma tela de listagem e outra de visualização de Pessoas. A seguir um trecho da página de listagem de pessoas, <strong>listarPessoas.xhtml</strong>:</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;h:form<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:dataTable</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;#{pessoaController.pessoas}&quot;</span> <span style="color: #000066;">var</span>=<span style="color: #ff0000;">&quot;pessoa&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:column<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			#{pessoa.nome}
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:column<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:column<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:link</span> <span style="color: #000066;">outcome</span>=<span style="color: #ff0000;">&quot;/verPessoa&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;Editar&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
				<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:param</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;pessoa&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;#{pessoa.nome}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:link<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:column<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:dataTable<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:form<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Nesse exemplo, no outcome eu já estou usando o esquema novo de navegação comentado no <a href="http://blog.gilliard.eti.br/2009/05/implicit-navigation-jsf-2/">post passado</a>. O link acima vai gerar uma url parecida com <strong><em>http://localhost:8080/exemplojsf2/verPessoa.jsf?pessoa=fulano_0</em></strong>.</p>
<p>Agora do lado da página que recebe a requisição temos os componentes f:metadata e f:viewParam. A primeira é apenas uma tag que engloba as f:viewParam. Já as tags f:viewParam se comportam de forma muito parecida com um h:inputText, podemos dizer que praticamente a única diferença é no input a gente digita em um formulário, enquanto na f:viewParam escrevemos na URL.</p>
<p>A tag f:viewParam possue os seguintes atributos: converter, converterMessage, required, requiredMessage, validator, validatorMessage, value, valueChangeListener, maxlength e for (este último voltado para o novo esquema de component composition do Facelets). Como podemos ver, é praticamente um h:inputText.</p>
<p>Vamos ver então um trecho do código da página que recebe a requisição, <strong>verPessoa.xhtml</strong>:</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;f:view<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:metadata<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	    	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:viewParam</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;pessoa&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;#{pessoaController.pessoaSelecionada}&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
   	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/f:metadata<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:head<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;title<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Ver Pessoa<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/title<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:head<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:body<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:form<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		Nome: #{pessoaController.pessoaSelecionada.nome}
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:form<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:body<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/f:view<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Não precisei colocar um converter no f:viewParam pois configurei um converter &#8220;<strong>forClass</strong>&#8221; como veremos mais a frente.</p>
<p>Agora a nossa classe</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> Pessoa <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> nome<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> Pessoa<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #000000; font-weight: bold;">public</span> Pessoa<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> nome<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">nome</span> <span style="color: #339933;">=</span> nome<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">//getter e setter suprimido</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Isso mesmo, a classe é complexa desse jeito  <img src='http://blog.gilliard.eti.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Como o intuito é só um exemplo, eu nem me preocupei com banco de dados ou algum mecanismo mais interessante, apenas criei um conversor para mostrar que o novo esquema não permite apenas o uso de Strings. Segue o código do conversor:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@FacesConverter<span style="color: #009900;">&#40;</span>forClass<span style="color: #339933;">=</span>Pessoa.<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> PessoaConverter <span style="color: #000000; font-weight: bold;">implements</span> Converter <span style="color: #009900;">&#123;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Object</span> getAsObject<span style="color: #009900;">&#40;</span>FacesContext context, UIComponent component, <span style="color: #003399;">String</span> string<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> Pessoa<span style="color: #009900;">&#40;</span>string<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> getAsString<span style="color: #009900;">&#40;</span>FacesContext context, UIComponent component, <span style="color: #003399;">Object</span> object<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>Pessoa<span style="color: #009900;">&#41;</span>object<span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getNome</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: #009900;">&#125;</span></pre></div></div>

<p>E agora nosso managed bean que recebe não uma String, e sim objetos do nosso domínio. Eu falo isso o tempo todo pois preciso deixar isso bem claro, senão eu fico doido de ver uma aplicação usando JSF passando String e Integer de um lado pro outro <img src='http://blog.gilliard.eti.br/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> </p>
<p>Mas tudo bem, deixando o desabafo pra lá vamos ao código:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@ManagedBean<span style="color: #009900;">&#40;</span>name<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;pessoaController&quot;</span><span style="color: #009900;">&#41;</span>
@RequestScoped
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> PessoaController <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Pessoa pessoaSelecionada<span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">private</span> List<span style="color: #339933;">&lt;</span>pessoa<span style="color: #339933;">&gt;</span> pessoas<span style="color: #339933;">;</span>
&nbsp;
	@PostConstruct
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> init<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		pessoas <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ArrayList<span style="color: #339933;">&lt;</span>pessoa<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: #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> <span style="color: #cc66cc;">10</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			pessoas.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Pessoa<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;fulano_&quot;</span> <span style="color: #339933;">+</span> i<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">//getters e setters suprimidos</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Acredito que por hoje seja suficiente. Vou ver se em breve escrevo algo mais específico sobre facelets.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.gilliard.eti.br/2009/05/urls-amigaveis-no-jsf-2/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>implicit navigation do JSF 2.0</title>
		<link>http://blog.gilliard.eti.br/2009/05/implicit-navigation-jsf-2/</link>
		<comments>http://blog.gilliard.eti.br/2009/05/implicit-navigation-jsf-2/#comments</comments>
		<pubDate>Tue, 19 May 2009 01:32:24 +0000</pubDate>
		<dc:creator>Gilliard Cordeiro</dc:creator>
				<category><![CDATA[JavaEE]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[JavaServer Faces]]></category>

		<guid isPermaLink="false">http://blog.gilliard.eti.br/?p=138</guid>
		<description><![CDATA[O JSF 2 teve o mecanismo de navegação melhorado. Agora além de regras de navegação implícitas foi adicionado um teste que pode ser feito usando a tag &#60;if&#62; dentro do &#60;navigation-case&#62;. E para finalizar a tag &#60;to-view-id&#62; aceita EL, o que torna tudo mais dinâmico. Mas como são várias coisas, vamos por partes Implicit Navigation [...]]]></description>
			<content:encoded><![CDATA[<p>O JSF 2 teve o mecanismo de navegação melhorado. Agora além de regras de navegação implícitas foi adicionado um teste que pode ser feito usando a tag &lt;if&gt; dentro do &lt;navigation-case&gt;. E para finalizar a tag &lt;to-view-id&gt; aceita EL, o que torna tudo mais dinâmico.</p>
<p>Mas como são várias coisas, vamos por partes</p>
<h2>Implicit Navigation</h2>
<p>Agora quando retornamos um outcome na nossa action, caso nenhuma regra de navegação compatível seja encontrada, a navegação implícita entra em cena.</p>
<p>Vamos considerar os seguintes dados</p>
<table border="1">
<tr>
<th>from-view-id</th>
<th>outcome</th>
<th>to-view-id implícita</th>
</tr>
<tr>
<td>/pasta1/view1.xhtml</td>
<td>view2</td>
<td>/pasta1/view2.xhtml</td>
</tr>
<tr>
<td>/pasta1/view1.xhtml</td>
<td>/view2</td>
<td>/view2.xhtml</td>
</tr>
<tr>
<td>/pasta1/view1.xhtml</td>
<td>/pasta2/view3</td>
<td>/pasta2/view3.xhtml</td>
</tr>
<tr>
<td>/pasta1/view1.xhtml</td>
<td>view2.groovy</td>
<td>/pasta1/view2.groovy</td>
</tr>
<tr>
<td>/pasta1/view1.xhtml</td>
<td>/outrapasta/view2.groovy</td>
<td>/outrapasta/view2.groovy</td>
</tr>
</table>
<p><br/><br />
Acredito que a tabela seja auto explicativa, mas só para consolidar: caso o outcome devolvido comece com &#8220;/&#8221; será considerado como caminho absoluto, senão a view será procurada na mesma pasta da view que originou a action. Além disso se nenhuma extensão de arquivo for informada, será considerada a mesma extensão da view que originou a action.</p>
<p>E por fim, podemos definir o atributo &#8220;<strong>faces-redirect=true</strong>&#8221; para informar que queremos que seja usado um redirect, assim como faríamos com <redirect/> se tivéssemos definido nossa regra de navegação via xml, como por exemplo &#8220;<strong>meuOutcome?faces-redirect=true</strong>&#8220;.</p>
<h2>Navigation case com &lt;if&gt;</h2>
<p>Assim como as implicit navigation, o Seam também tem o &lt;if&gt; como o do JSF 2, porém no Seam esse &lt;if&gt; fica no pages.xml, um arquivo do Seam. Como sempre, vamos ver um exemplo para facilitar o entendimento.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@ManagedBean<span style="color: #009900;">&#40;</span>name<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;pessoaBean&quot;</span><span style="color: #009900;">&#41;</span>
@RequestScoped
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> PessoaBean<span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> EntityManager em<span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//injetado por algum mecanismo</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Pessoa pessoa <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Pessoa<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> actionSalvar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		em.<span style="color: #006633;">persist</span><span style="color: #009900;">&#40;</span>pessoa<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">//getters e setters suprimidos</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>agora vamos ver o faces-config.xml</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;navigation-rule<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;from-view-id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>/cadastroPessoa.xhtml<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/from-view-id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;navigation-case<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;if<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>#{pessoaBean.pessoa.id != null}<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/if<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;to-view-id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>/listagemPessoas.xhtml<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;to-view-id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/navigation-case<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/navigation-rule<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
...</pre></div></div>

<p>No nosso exemplo acima, mesmo sem retornar nenhum outcome, a navegação acontece da view &#8220;<strong>/cadastroPessoa.xhtml</strong>&#8221; para a view &#8220;<strong>/listagemPessoas.xhtml</strong>&#8220;, graças ao &lt;if&gt; do nosso &lt;navigation-case&gt;. Na expressão do exemplo usei algo bem simples, considerei que se o id da pessoa está diferente de nulo é porque a ação de salvar foi executada com sucesso. Obviamente podemos evoluir esse exemplo, mas como a finalidade aqui é didática acredito que seja sufucuente como está.</p>
<h2>EL no &lt;to-view-id&gt;</h2>
<p>Para finalizar vamos dar uma olhada no exemplo do uso da EL no &lt;to-view-id&gt;. Vamos ver esse outro exemplo.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@ManagedBean<span style="color: #009900;">&#40;</span>name<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;cidadeBean&quot;</span><span style="color: #009900;">&#41;</span>
@RequestScoped
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> CidadeBean<span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> EntityManager em<span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//injetado por algum mecanismo</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Cidade cidade <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Cidade<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> nextView<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> actionSalvar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		em.<span style="color: #006633;">persist</span><span style="color: #009900;">&#40;</span>cidade<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		nextView <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;/listagemCidades.xhtml&quot;</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;sucesso&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">//getters e setters suprimidos</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>E no faces-config.xml temos o seguinte</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;navigation-rule<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;from-view-id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>/cadastroCidade.xhtml<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/from-view-id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;navigation-case<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;from-outcome<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>sucesso<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/from-outcome<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;to-view-id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>#{cidadeBean.nextView}<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;to-view-id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/navigation-case<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/navigation-rule<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
...</pre></div></div>

<p>Com isso fechamos a parte de NavigationHandler do JSF 2. Na verdade ainda tem como novidade a possibilidade de consultarmos os NavigationCase&#8217;s de forma programática. Mas isso eu comento melhor quando for falar do que podemos fazer de forma programática no JSF 2 usando a implementação de referência, Mojarra (pois essas configurações programáticas que irei comentar não são especificadas).</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.gilliard.eti.br/2009/05/implicit-navigation-jsf-2/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Conversation Scope usando @CustomScoped do JSF 2.0</title>
		<link>http://blog.gilliard.eti.br/2009/05/conversation-scope-usando-customscoped-do-jsf-2/</link>
		<comments>http://blog.gilliard.eti.br/2009/05/conversation-scope-usando-customscoped-do-jsf-2/#comments</comments>
		<pubDate>Tue, 12 May 2009 15:28:25 +0000</pubDate>
		<dc:creator>Gilliard Cordeiro</dc:creator>
				<category><![CDATA[JavaEE]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[JavaServer Faces]]></category>

		<guid isPermaLink="false">http://blog.gilliard.eti.br/?p=131</guid>
		<description><![CDATA[Apesar do título, o JSF 2 não vai ter um escopo Conversation ou coisa parecida como tem no Seam ou Orchestra. O que vai ter é o suporte direto a escopos personalizados, o que torna simples a criação de um escopo como Conversation. Nesse exemplo eu desenvolvi um escopo de conversação simples, mas não é [...]]]></description>
			<content:encoded><![CDATA[<p>Apesar do título, o JSF 2 não vai ter um escopo Conversation ou coisa parecida como tem no Seam ou Orchestra. O que vai ter é o suporte direto a escopos personalizados, o que torna simples a criação de um escopo como Conversation.</p>
<p>Nesse exemplo eu desenvolvi um escopo de conversação simples, mas não é difícil melhorá-lo para suportar diversas conversações simultâneas, assimilando a idéia a gente vê que não é nenhum bicho de sete cabeças. Claro que o principal objetivo é o aprendizado de como tudo funciona, e não ficar implementando o que já tem pronto em diversos frameworks.</p>
<p>Vamos então ao exemplo.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@ManagedBean<span style="color: #009900;">&#40;</span>name<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;testeBean&quot;</span><span style="color: #009900;">&#41;</span>
@CustomScoped<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;#{conversacao}&quot;</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> TesteBean <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Integer</span> contador<span style="color: #339933;">;</span>
&nbsp;
	@PostConstruct
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> init<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;TesteBean.init()&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		contador <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</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: #000066; font-weight: bold;">void</span> incrementarContador<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		contador<span style="color: #339933;">++;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> iniciaConversacao<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		Conversacao.<span style="color: #006633;">instancia</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">iniciar</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;">public</span> <span style="color: #000066; font-weight: bold;">void</span> finalizaConversacao<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		Conversacao.<span style="color: #006633;">instancia</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">finalizar</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;">public</span> <span style="color: #003399;">Integer</span> getContador<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> contador<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setContador<span style="color: #009900;">&#40;</span><span style="color: #003399;">Integer</span> contador<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">contador</span> <span style="color: #339933;">=</span> contador<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Acima está um managed bean que chamei de &#8220;beanTeste&#8221;. Coloquei um <em>println</em> no método <strong>init()</strong> e anotei esse método com <strong>@PostConstruct</strong>. Na prática isso quer dizer que toda vez que o managed bean for construído esse método será chamado, e consequentemente aparecerá no console. Isso é útil para vermos que o escopo de conversação realmente está funcionando. Já que estamos falando de escopo personalizado, quem faz isso é a anotação <strong>@CustomScoped</strong>, que recebe como valor uma EL que será resolvida por um EL Resolver que vamos criar.</p>
<p>Agora vamos ver a tela</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">Contador atualizado via ajax e mantido com a conversação: <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:outputText</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;output3&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;#{testeBean.contador}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;br</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:commandButton</span> <span style="color: #000066;">action</span>=<span style="color: #ff0000;">&quot;#{testeBean.incrementarContador}&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;Incrementar Contador&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:ajax</span> <span style="color: #000066;">render</span>=<span style="color: #ff0000;">&quot;output3&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:commandButton<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:commandButton</span> <span style="color: #000066;">action</span>=<span style="color: #ff0000;">&quot;#{testeBean.iniciarConversacao}&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;Iniciar Conversação&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:ajax</span> <span style="color: #000066;">render</span>=<span style="color: #ff0000;">&quot;@none&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:commandButton<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:commandButton</span> <span style="color: #000066;">action</span>=<span style="color: #ff0000;">&quot;#{testeBean.finalizarConversacao}&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;Finalizar Conversação&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:ajax</span> <span style="color: #000066;">render</span>=<span style="color: #ff0000;">&quot;@none&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:commandButton<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Tanto o exemplo da tela quanto do managed bean estão simplificados para o nosso exemplo, mas a versão disponível para download contém uns exemplos para testarmos o funcionamento do ajax também.</p>
<p>A idéia do nosso escopo &#8220;conversacao&#8221; é o mesmo do Seam, ele funciona como request até que seja explicitamente iniciada a conversação. Quando isso ocorre, o escopo passa a ser statefull até que a conversação seja finalizada, fazendo com que ela funcione como request novamente.</p>
<p>Seguindo essa idéia, o contador que aparece na tela não vai sair de &#8220;1&#8243; até que a conversação seja iniciada, pois como o escopo é request, toda vez que executamos a ação &#8220;incrementaContador&#8221; o managed bean será criado novamente (contador = 0), depois a ação será executada (contador = 1) e então a página será renderizada (exibe contador = 1). Agora se a conversação for iniciada o managed bean será mantido entre as requisições, e o contador não será zerado até que a conversação termine.</p>
<p>Para nosso escopo funcionar, precisamos de um <strong>ELResolver</strong>, que será quem vai conseguir dizer para o faces de onde virá os objetos relacionados ao escopo &#8220;conversacao&#8221;. Registramos nosso ELResolver no faces-config.xml assim</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;">'1.0'</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">'UTF-8'</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;faces-config</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/xml/ns/javaee&quot;</span></span>
<span style="color: #009900;">              <span style="color: #000066;">xmlns:xsi</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span>
<span style="color: #009900;">              <span style="color: #000066;">xsi:schemaLocation</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd&quot;</span></span>
<span style="color: #009900;">              <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;2.0&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;application<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;el-resolver<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>br.eti.gilliard.exemplojsf2.conversacao.ConversacaoELResolver<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/el-resolver<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/application<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/faces-config<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>E a implementação fica assim</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ConversacaoELResolver <span style="color: #000000; font-weight: bold;">extends</span> ELResolver <span style="color: #009900;">&#123;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Object</span> getValue<span style="color: #009900;">&#40;</span>ELContext elContext, <span style="color: #003399;">Object</span> base, <span style="color: #003399;">Object</span> property<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>property <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>
			<span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> PropertyNotFoundException<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;A Propriedade não pode ser nula!&quot;</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;">if</span> <span style="color: #009900;">&#40;</span>base <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>
&nbsp;
			<span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>Conversacao.<span style="color: #006633;">NOME_ESCOPO</span>.<span style="color: #006633;">equals</span><span style="color: #009900;">&#40;</span>property.<span style="color: #006633;">toString</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>
				Conversacao conversacao <span style="color: #339933;">=</span> Conversacao.<span style="color: #006633;">instancia</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				elContext.<span style="color: #006633;">setPropertyResolved</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: #000000; font-weight: bold;">return</span> conversacao<span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
&nbsp;
			Conversacao conversacao <span style="color: #339933;">=</span> Conversacao.<span style="color: #006633;">instancia</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;">return</span> getValue<span style="color: #009900;">&#40;</span>conversacao, property.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, elContext<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>base <span style="color: #000000; font-weight: bold;">instanceof</span> Conversacao<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">return</span> getValue<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>Conversacao<span style="color: #009900;">&#41;</span> base, property.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, elContext<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> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Object</span> getValue<span style="color: #009900;">&#40;</span>Conversacao conversacao, <span style="color: #003399;">String</span> property, ELContext elContext<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003399;">Object</span> objeto <span style="color: #339933;">=</span> conversacao.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>property<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		elContext.<span style="color: #006633;">setPropertyResolved</span><span style="color: #009900;">&#40;</span>objeto <span style="color: #339933;">!=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">return</span> objeto<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// os outros métodos foram suprimidos nesse exemplo</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Essa é uma implementação comum de EL Resolver, onde eu uso o objeto retornado por Conversacao.instancia() para localizar as propriedades solicitadas.</p>
<p>Para o jsf um escopo nada mais é do que um <strong>java.util.Map</strong>, e de fato a classe Conversacao estende <strong>ConcurrentHashMap</strong>, ou seja, é um Map como pede o jsf. Fora isso os métodos get e put foram sobrescritos para funcionarem de acordo com nossa especificação de conversação, ou seja, se ela não foi iniciada tudo deve funcionar como request, agora quando a conversação é iniciada, os valores passam a ser guardados dentro da sessão do usuário, fazendo assim ficar statefull. Depois que a conversação é finalizada os valores voltam a ser guardados no request.</p>
<p>Antes de ver a implementação da classe <strong>Conversacao</strong>, o mais importante é entender como o mecanismo de resolução de EL funciona. Como visto no faces-config.xml, não existe nenhuma ligação da nossa implementação de <strong>ELResolver</strong> com a El &#8220;#{conversacao}&#8221; que colocamos na anotação <strong>@CustomScoped</strong> do nosso managed bean. Toda vez que uma EL é encontrada ela é passada para os ELResolvers contidos na aplicação. Obviamente existem outras implementações padrões já disponíveis, e a nossa vai entrar nessa fila. Como nenhuma das outras implementações vai saber resolver essa EL, ela acaba vindo para a nossa implementação, e então quando encontramos o objeto procurado utilizamos o método &#8220;<strong>ElContext.setPropertyResolved(boolean b)</strong>&#8221; passando <strong>true</strong> para informar que não precisa continuar perguntando para os demais <strong>ELResolver</strong>&#8216;s, pois o nosso já descobriu quem é o objeto.</p>
<p>Existem alguns detalhes que devemos seguir ao implementar um escopo personalizado, como o de avisar, utilizando o novo sistema de eventos do JSF 2, que estamos criando ou destruindo nosso escopo.</p>
<p>Além disso para fazer essa implementação suportar múltiplas conversações seria necessário apenas colocar um nível a mais de mapa na nossa implementação, onde teríamos uma identificação da conversação e então seu contexto. Em vez de um simples Map, ficaria um Map de Map <img src='http://blog.gilliard.eti.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' />  . Então para saber qual Map interno devolver a gente buscaria a conversação atual de algum contexto da nossa escolha, e poderíamos deixar um combobox sempre visível na tela para o usuária escolher a conversação que ele quer usar. Novamente nada de novo, tudo igual o funcionamento do Seam, por exemplo.</p>
<p>Agora sim vamos à implementação da classe <strong>Conversacao</strong>.</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> Conversacao <span style="color: #000000; font-weight: bold;">extends</span> ConcurrentHashMap<span style="color: #339933;">&lt;</span>string,Object<span style="color: #339933;">&gt;</span><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> <span style="color: #000066; font-weight: bold;">long</span> serialVersionUID <span style="color: #339933;">=</span> 7556965369432050706L<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">String</span> NOME_ESCOPO <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;conversacao&quot;</span><span style="color: #339933;">;</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> <span style="color: #003399;">String</span> CONVERSACAO_ATUAL <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;exemplojsf2.conversacao.ConversacaoAtual&quot;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">boolean</span> conversacaoNaoIniciada <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">true</span><span style="color: #339933;">;</span>
&nbsp;
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Conversacao<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</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> Conversacao instancia<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		Map<span style="color: #339933;">&lt;</span>string, Object<span style="color: #339933;">&gt;</span> sessionMap <span style="color: #339933;">=</span> FacesContext.<span style="color: #006633;">getCurrentInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getExternalContext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getSessionMap</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		Conversacao conversacao <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Conversacao<span style="color: #009900;">&#41;</span> sessionMap.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>CONVERSACAO_ATUAL<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>conversacao <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>
			conversacao <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Conversacao<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			sessionMap.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span>CONVERSACAO_ATUAL, conversacao<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> conversacao<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> get<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> propriedade<span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #666666; font-style: italic;">//se a conversacao nao for iniciada funciona como request</span>
		<span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>conversacaoNaoIniciada<span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">return</span> pegarDoRequest<span style="color: #009900;">&#40;</span>propriedade<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;">return</span> <span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>propriedade<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@SuppressWarnings<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;unchecked&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Object</span> pegarDoRequest<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> propriedade<span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		Map<span style="color: #339933;">&lt;</span>string, Object<span style="color: #339933;">&gt;</span> requestConversation <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Map<span style="color: #339933;">&lt;</span>string, Object<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#41;</span> FacesContext.<span style="color: #006633;">getCurrentInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getExternalContext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getRequestMap</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>CONVERSACAO_ATUAL<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>requestConversation <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>
			<span style="color: #000000; font-weight: bold;">return</span> requestConversation.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>propriedade<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> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Object</span> put<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> key, <span style="color: #003399;">Object</span> value<span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #666666; font-style: italic;">//se a conversacao nao for iniciada funciona como request</span>
		<span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>conversacaoNaoIniciada<span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">return</span> colocarNoRequest<span style="color: #009900;">&#40;</span>key, value<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;">return</span> <span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span>key, value<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@SuppressWarnings<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;unchecked&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Object</span> colocarNoRequest<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> key, <span style="color: #003399;">Object</span> value<span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
&nbsp;
		Map<span style="color: #339933;">&lt;</span>string, Object<span style="color: #339933;">&gt;</span> requestMap <span style="color: #339933;">=</span> FacesContext.<span style="color: #006633;">getCurrentInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getExternalContext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getRequestMap</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		Map<span style="color: #339933;">&lt;</span>string, Object<span style="color: #339933;">&gt;</span> requestConversation <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Map<span style="color: #339933;">&lt;</span>string, Object<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#41;</span> requestMap.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>CONVERSACAO_ATUAL<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>requestConversation <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>
			requestConversation <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ConcurrentHashMap<span style="color: #339933;">&lt;</span>string, Object<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			requestMap.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span>CONVERSACAO_ATUAL, requestConversation<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #000000; font-weight: bold;">return</span> requestConversation.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span>key, value<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">return</span> requestConversation.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span>key, value<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: #000066; font-weight: bold;">void</span> iniciar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		conversacaoNaoIniciada <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #339933;">;</span>
		promoverRequestParaConversacao<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		notificarCriacao<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@SuppressWarnings<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;unchecked&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> promoverRequestParaConversacao<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		Map<span style="color: #339933;">&lt;</span>string, Object<span style="color: #339933;">&gt;</span> requestConversation <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Map<span style="color: #339933;">&lt;</span>string, Object<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#41;</span> FacesContext.<span style="color: #006633;">getCurrentInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getExternalContext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getRequestMap</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>CONVERSACAO_ATUAL<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006633;">putAll</span><span style="color: #009900;">&#40;</span>requestConversation<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> <span style="color: #000066; font-weight: bold;">void</span> notificarCriacao<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		ScopeContext context <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ScopeContext<span style="color: #009900;">&#40;</span>NOME_ESCOPO, <span style="color: #000000; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		FacesContext facesContext <span style="color: #339933;">=</span> FacesContext.<span style="color: #006633;">getCurrentInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		facesContext.<span style="color: #006633;">getApplication</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">publishEvent</span><span style="color: #009900;">&#40;</span>facesContext, PostConstructCustomScopeEvent.<span style="color: #000000; font-weight: bold;">class</span>, context<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: #000066; font-weight: bold;">void</span> finalizar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		notificarFinalizacao<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		conversacaoNaoIniciada <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">true</span><span style="color: #339933;">;</span>
		rebaixarConversacaoParaRequest<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@SuppressWarnings<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;unchecked&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> rebaixarConversacaoParaRequest<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		Map<span style="color: #339933;">&lt;</span>string, Object<span style="color: #339933;">&gt;</span> requestMap <span style="color: #339933;">=</span> FacesContext.<span style="color: #006633;">getCurrentInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getExternalContext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getRequestMap</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		Map<span style="color: #339933;">&lt;</span>string, Object<span style="color: #339933;">&gt;</span> requestConversation <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Map<span style="color: #339933;">&lt;</span>string, Object<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#41;</span> requestMap.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>CONVERSACAO_ATUAL<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>requestConversation <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>
			requestConversation <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ConcurrentHashMap<span style="color: #339933;">&lt;</span>string, Object<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			requestMap.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span>CONVERSACAO_ATUAL, requestConversation<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		requestConversation.<span style="color: #006633;">putAll</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">clear</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		FacesContext.<span style="color: #006633;">getCurrentInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getExternalContext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getSessionMap</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">remove</span><span style="color: #009900;">&#40;</span>CONVERSACAO_ATUAL<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> <span style="color: #000066; font-weight: bold;">void</span> notificarFinalizacao<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		ScopeContext context <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ScopeContext<span style="color: #009900;">&#40;</span>NOME_ESCOPO, <span style="color: #000000; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		FacesContext facesContext <span style="color: #339933;">=</span> FacesContext.<span style="color: #006633;">getCurrentInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		facesContext.<span style="color: #006633;">getApplication</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">publishEvent</span><span style="color: #009900;">&#40;</span>facesContext, PreDestroyCustomScopeEvent.<span style="color: #000000; font-weight: bold;">class</span>, context<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>O download do exemplo pode ser feito <a href="http://blog.gilliard.eti.br/arquivos/exemplo-conversacao-jsf2.war">aqui</a>.</p>
<p>Com certeza deve ter algum errinho nessa implementação, mas se tiver não se desespere, por essas e outras que você certamente deve estar usando um framework mais confiável na tua aplicação do que uma implementação de &#8220;fundo de quintal&#8221; <img src='http://blog.gilliard.eti.br/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  . De qualquer forma encontrando os errinhos me diga que eu vou corrigindo.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.gilliard.eti.br/2009/05/conversation-scope-usando-customscoped-do-jsf-2/feed/</wfw:commentRss>
		<slash:comments>27</slash:comments>
		</item>
		<item>
		<title>f:ajax no JSF 2.0</title>
		<link>http://blog.gilliard.eti.br/2009/05/ajax-no-jsf-2/</link>
		<comments>http://blog.gilliard.eti.br/2009/05/ajax-no-jsf-2/#comments</comments>
		<pubDate>Mon, 11 May 2009 13:50:58 +0000</pubDate>
		<dc:creator>Gilliard Cordeiro</dc:creator>
				<category><![CDATA[JavaEE]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[JavaServer Faces]]></category>

		<guid isPermaLink="false">http://blog.gilliard.eti.br/?p=120</guid>
		<description><![CDATA[Depois de muito tempo sem escrever estou eu aqui de novo falando de JSF 2.0 Neste post irei mostrar como está ficando o suporte a ajax do JSF 2. Já adianto que está ficando bem parecido com o Ajax4Jsf. Em outros posts eu já havia comentado sobre o suporte a ajax que a nova versão [...]]]></description>
			<content:encoded><![CDATA[<p>Depois de muito tempo sem escrever estou eu aqui de novo falando de JSF 2.0</p>
<p>Neste post irei mostrar como está ficando o suporte a ajax do JSF 2. Já adianto que está ficando bem parecido com o Ajax4Jsf. Em outros posts eu já havia comentado sobre o suporte a ajax que a nova versão do jsf vai suportar. Mas agora vou falar do componente de tela para facilitar o uso, no outro post falei apenas da API JavaScript, que eu usei <a href="http://blog.gilliard.eti.br/2009/02/exemplo-com-jsf-2/">nesse exemplo</a>.</p>
<p>O componente &lt;f:ajax&gt; parece o &lt;a4j:support&gt;. Essa nova tag pode ser usada tanto dentro de uma tag específica, tornando-a ajax, assim como fazemos com o &lt;a4j:support&gt; ou pode ser colocada em volta de vários componentes, tornando todos os componentes dentro dela ajax.</p>
<p>Por exemplo:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:panelGroup</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;panelGroupX&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:panelGroup<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:outputText</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;outputY&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;...&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:commandButton</span> <span style="color: #000066;">action</span>=<span style="color: #ff0000;">&quot;...&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:ajax</span> <span style="color: #000066;">execute</span>=<span style="color: #ff0000;">&quot;@form&quot;</span> <span style="color: #000066;">render</span>=<span style="color: #ff0000;">&quot;panelGroupX outputY&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:commandButton<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Nesse exemplo temos uma página como já estamos acostumados, até onde o novo componente aparece. Nesse caso a tag &lt;f:ajax&gt; está habilitando ajax no commandButton, e os dois principais atributos da tag são &#8220;execute&#8221; e &#8220;render&#8221;. O primeiro serve para informarmos o que será enviado ao servidor na nossa requisição ajax, e o segundo é como o &#8220;reRender&#8221; do ajax4jsf, e serve para informarmos o que será renderizado novamente. Ambos aceitam uma lista de ids, separados por espaço em branco, ou então os seguintes valores pré-definidos:</p>
<ul>
<li><strong>@this</strong> &#8211; o próprio componente que dispara a requisição ajax</li>
<li><strong>@form</strong> &#8211; o formulário que envolve o componente @this</li>
<li><strong>@all</strong> &#8211; a view inteira</li>
<li><strong>@none</strong> &#8211; nenhum componente</li>
</ul>
<p>Lembrando novamente que esses valores servem tanto para informar o que vai (execute) e o que volta (render) em uma requisição ajax.</p>
<p>Agora outro exemplo</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:ajax</span> <span style="color: #000066;">event</span>=<span style="color: #ff0000;">&quot;onmouseover&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:panelGroup</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;panelGroupX&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    ...
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:panelGroup<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:outputText</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;outputY&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;...&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:commandButton</span> <span style="color: #000066;">action</span>=<span style="color: #ff0000;">&quot;...&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:ajax</span> <span style="color: #000066;">event</span>=<span style="color: #ff0000;">&quot;action&quot;</span> <span style="color: #000066;">execute</span>=<span style="color: #ff0000;">&quot;@form&quot;</span> <span style="color: #000066;">render</span>=<span style="color: #ff0000;">&quot;panelGroupX outputY&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:commandButton<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/f:ajax<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Nesse caso a tag &lt;f:ajax&gt; envolve os demais componentes, fazendo com que tudo que está dentro dela passe a disparar eventos ajax. Cada tipo de componente possui um evento padrão que dispara a requisição ajax: um input dispara a requisição quando tem seu valor alterado e um botão ou link quando é clicado, por exemplo.</p>
<p>Porém nesse exemplo eu especifiquei que o evento padrão que executará o ajax para todos os componentes dentro da tag &lt;f:ajax&gt; é o &#8220;onmouseover&#8221;, mas como mostrado no commandButton eu posso sobrescrever os valores definidos na tag &lt;f:ajax&gt; de fora com uma tag dentro do próprio componente. Eu usei a propriedade &#8220;<strong>event</strong>&#8220;, mas poderia ter usado qualquer outra na tag ajax de fora, fornecendo assim um mesmo comportamente default para todos.</p>
<p>No último exemplo usei a propriedade &#8220;<strong>event</strong>&#8220;, que como visto no exemplo serve para dizer qual evento executará a requisição ajax. Essa propríedade suporta todos os eventos DOM e ainda &#8220;valueChange&#8221; para componentes de entrada de dados (ou mais especificamente um EditableValueHolder) e &#8220;action&#8221; para componentes de ação (um ActionSource).</p>
<p>A tag &lt;f:ajax&gt; suporta ainda os atributos:</p>
<ul>
<li><strong>listener</strong> &#8211; serve para fazer binding com um método que a seguinte assinatura &#8220;<em>public void <nome>(javax.faces.event.AjaxBehaviorEvent event) throws javax.faces.event.AbortProcessingException</em>&#8220;. Com isso podemos executar um código java quando um evento qualquer é disparado.</li>
<li><strong>disabled</strong> &#8211; seria o equivalente ao rendered de um componente visual, se o valor definido aqui for true o suporta a ajax fica desabilitado.</li>
<li><strong>immediate</strong> &#8211; igual o immediate dos componentes jsf comuns.</li>
<li><strong>onevent</strong> &#8211; função js que será chamada quando o evento especificado for executado</li>
<li><strong>onerror</strong> &#8211; função js que será chamada quando um erro ocorrer na requisição</li>
</ul>
<p>Esse post foi curto por falta de tempo, mas novos posts virão em breve (assim espero ). Já estou com um exemplo pronto de implementação de conversation usando o suporte a escopos customizados do JSF 2.0, mas isso vai ter que ficar para o próximo post <img src='http://blog.gilliard.eti.br/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.gilliard.eti.br/2009/05/ajax-no-jsf-2/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>

