<?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>Bruno Pereira &#187; rest</title>
	<atom:link href="http://brunopereira.org/tag/rest/feed/" rel="self" type="application/rss+xml" />
	<link>http://brunopereira.org</link>
	<description>Open source, Java, web, python, client-side e outros hobbies :)</description>
	<lastBuildDate>Thu, 20 Oct 2011 00:47:23 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Uso de Hypermedia em protocolos REST</title>
		<link>http://brunopereira.org/2010/08/03/uso-de-hypermedia-em-protocolos-rest/</link>
		<comments>http://brunopereira.org/2010/08/03/uso-de-hypermedia-em-protocolos-rest/#comments</comments>
		<pubDate>Tue, 03 Aug 2010 12:18:44 +0000</pubDate>
		<dc:creator>blpsilva</dc:creator>
				<category><![CDATA[design]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[hypermedia]]></category>
		<category><![CDATA[rest]]></category>

		<guid isPermaLink="false">http://brunopereira.org/?p=370</guid>
		<description><![CDATA[Algumas vezes amigos já me questionaram sobre o uso de Hypermedia em protocolos REST. É sem dúvida um assunto que me agrada bastante, e acho que a discussão pode trazer boas idéias para quem implementar serviços REST interessantes.
Começando do começo: o que é Hypermedia?
Hypermedia é uma extensão lógica de Hypertext, na qual conseguimos combinar gráficos, [...]]]></description>
			<content:encoded><![CDATA[<p>Algumas vezes amigos já me questionaram sobre o uso de Hypermedia em protocolos REST. É sem dúvida um assunto que me agrada bastante, e acho que a discussão pode trazer boas idéias para quem implementar serviços REST interessantes.</p>
<h2>Começando do começo: o que é Hypermedia?</h2>
<p><a title="Hypermedia" href="http://en.wikipedia.org/wiki/Hypermedia" target="_blank">Hypermedia</a> é uma extensão lógica de <a title="Hypertext" href="http://en.wikipedia.org/wiki/Hypertext" target="_blank">Hypertext</a>, na qual conseguimos combinar gráficos, áudio, vídeo, texto plano e hyperlinks para criar um fluxo de navegação não-linear. (Definição retirada da Wikipedia).</p>
<h2>Motivação: REST sem Hypermedia</h2>
<p>No <a title="Artigo REST" href="http://brunopereira.org/webservicesrest-indice/" target="_blank">artigo de REST</a> que escrevi no começo de 2008 eu falei sobre diversos aspectos importantes em um protocolo de comunicação REST. Recomendo a leitura para quem ainda não tenha visto o artigo. Naquele artigo, cobri praticamente todos os detalhes aos quais devemos prestar atenção &#8211; a exceção ficou por conta de Hypermedia.</p>
<p>Para ilustrar uma resposta REST sem uso de Hypermedia, copio aqui uma listagem que usei no <a title="Artigo REST" href="http://brunopereira.org/artigos/" target="_blank">artigo de REST da Java Magazine</a>.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">HTTP/1.1 200 OK
Date: nnn
Content-Type: text/xml; charset=utf-8
Content-Length: nnn
Last-Modified: Sat, 19 Feb 2008 13:40:03 GMT
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ofertasDoItem<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;oferta<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;codOferta<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>23c32440-959a-4c33-b6ee-caff8e41422a<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/codOferta<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;valor<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>111.22<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/valor<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dataModificacao<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>2008-02-05<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dataModificacao<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;item<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;codItem<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>b7d24e54-0c0d-4fa0-b4fe-d7cf60180ed7<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/codItem<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;novo<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>false<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/novo<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;vendido<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>false<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/vendido<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/item<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ofertante<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;codUsuario<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>505ab9d4-4b4b-4ce6-b128-b7408268126c<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/codUsuario<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ofertante<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;vencedora<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>false<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/vencedora<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/oferta<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;oferta<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;codOferta<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>41ffac11-5ba2-405b-acc8-8e3d0904b158<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/codOferta<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;valor<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>111.22<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/valor<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dataModificacao<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>2008-02-14<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dataModificacao<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;item<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;codItem<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>b7d24e54-0c0d-4fa0-b4fe-d7cf60180ed7<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/codItem<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;novo<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>false<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/novo<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;vendido<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>false<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/vendido<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/item<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ofertante<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;codUsuario<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>505ab9d4-4b4b-4ce6-b128-b7408268126c<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/codUsuario<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ofertante<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;vencedora<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>false<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/vencedora<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/oferta<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ofertasDoItem<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Se você julga que isso parece um grafo de objetos serializado, você não está enganado, é exatamente isso.</p>
<h2>O que temos a ganhar com Hypermedia?</h2>
<p>Quando implementamos a API REST da autenticação/autorização/cadastro da Globo.com, o protocolo REST sem Hypermedia atendeu perfeitamente. A comunicação funcionou, permitiu integração de clientes de todas as plataformas, de forma desacoplada tecnologicamente. No que será que Hypermedia poderia ajudar?</p>
<p>O cerne do benefício de Hypermedia está no conhecimento prévio que os clientes devem ter sobre o seu protocolo. Repare no seguinte fragmento da resposta:</p>
<p>&lt;item&gt;<br />
&lt;codItem&gt;b7d24e54-0c0d-4fa0-b4fe-d7cf60180ed7&lt;/codItem&gt;<br />
&lt;novo&gt;false&lt;/novo&gt;<br />
&lt;vendido&gt;false&lt;/vendido&gt;<br />
&lt;/item&gt;</p>
<p>O que podemos dizer sobre ele? Ele traz informações &#8220;quase&#8221; completas sobre o item em questão. Todos os atributos estão presentes, porém não dizemos nada ao cliente sobre como interagir com este recurso, não é verdade? Um cliente que receba este XML conseguirá manipulá-lo <strong>SE JÁ SOUBER PREVIAMENTE COMO</strong>! O cliente já deve conhecer as URIs de cada recurso e saber quais manipulações ele pode fazer sobre os mesmos.</p>
<p>Como Hypermedia pode nos levar além? Com Hypermedia podemos dizer aos clientes como manipular os recursos, e com isso diminuir a inteligência embutida nos clientes.</p>
<h2>Exemplo de resposta usando Hypermedia</h2>
<p>Agora pegarei um trecho do meu artigo sobre AtomPub para exemplificar uma resposta com uso de Hypermedia:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;atom:entry</span> <span style="color: #000066;">xmlns:atom</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2005/Atom&quot;</span></span>
<span style="color: #009900;"><span style="color: #000066;">xmlns:apps</span>=<span style="color: #ff0000;">&quot;http://schemas.google.com/apps/2006&quot;</span></span>
<span style="color: #009900;"><span style="color: #000066;">xmlns:gd</span>=<span style="color: #ff0000;">&quot;http://schemas.google.com/g/2005&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;atom:id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>https://www.google.com/a/feeds/example.com/user/2.0/SusanJones<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/atom:id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;atom:updated<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>1970-01-01T00:00:00.000Z<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/atom:updated<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;atom:category</span> <span style="color: #000066;">scheme</span>=<span style="color: #ff0000;">&quot;http://schemas.google.com/g/2005#kind&quot;</span></span>
<span style="color: #009900;"><span style="color: #000066;">term</span>=<span style="color: #ff0000;">&quot;http://schemas.google.com/apps/2006#user&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;atom:title</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;text&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>SusanJones<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/atom:title<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;atom:link</span> <span style="color: #000066;">rel</span>=<span style="color: #ff0000;">&quot;self&quot;</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;application/atom+xml&quot;</span></span>
<span style="color: #009900;"><span style="color: #000066;">href</span>=<span style="color: #ff0000;">&quot;https://www.google.com/a/feeds/example.com/user/2.0/SusanJones&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;atom:link</span> <span style="color: #000066;">rel</span>=<span style="color: #ff0000;">&quot;edit&quot;</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;application/atom+xml&quot;</span></span>
<span style="color: #009900;"><span style="color: #000066;">href</span>=<span style="color: #ff0000;">&quot;https://www.google.com/a/feeds/example.com/user/2.0/SusanJones&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;apps:login</span> <span style="color: #000066;">userName</span>=<span style="color: #ff0000;">&quot;SusanJones&quot;</span> <span style="color: #000066;">suspended</span>=<span style="color: #ff0000;">&quot;false&quot;</span> <span style="color: #000066;">admin</span>=<span style="color: #ff0000;">&quot;false&quot;</span> <span style="color: #000066;">changePasswordAtNextLogin</span>=<span style="color: #ff0000;">&quot;false&quot;</span> <span style="color: #000066;">agreedToTerms</span>=<span style="color: #ff0000;">&quot;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;apps:name</span> <span style="color: #000066;">familyName</span>=<span style="color: #ff0000;">&quot;Jones&quot;</span> <span style="color: #000066;">givenName</span>=<span style="color: #ff0000;">&quot;Susan&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;gd:feedLink</span> <span style="color: #000066;">rel</span>=<span style="color: #ff0000;">&quot;http://schemas.google.com/apps/2006#user.nicknames&quot;</span></span>
<span style="color: #009900;"><span style="color: #000066;">href</span>=<span style="color: #ff0000;">&quot;https://www.google.com/a/feeds/example.com/nickname/2.0?</span>
<span style="color: #009900;">username=Susy-1321&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;gd:feedLink</span> <span style="color: #000066;">rel</span>=<span style="color: #ff0000;">&quot;http://schemas.google.com/apps/2006#user.emailLists&quot;</span></span>
<span style="color: #009900;"><span style="color: #000066;">href</span>=<span style="color: #ff0000;">&quot;https://www.google.com/a/feeds/example.com/emailList/2.0?</span>
<span style="color: #009900;">recipient=us-sales@example.com&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/atom:entry<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Qual é a principal diferença aqui? Através do uso de <strong>links</strong> conseguimos indicar uma URI para manipulação do recurso, e através do atributo <strong>rel</strong>, indicamos QUAL é a manipulação. Algumas coisas ainda ficam implícitas. Por exemplo, se o link indica um <strong>rel=&#8221;edit&#8221;</strong>, a manipulação em questão provavelmente será feita com uma requisição HTTP PUT. Se o link tiver um <strong>rel=&#8221;show&#8221;</strong>, a manipulação deve ser uma leitura, feita com HTTP GET.</p>
<h2>Hypermedia x Acoplamento</h2>
<p>Neste ponto deve ter ficado claro que o uso de Hypermedia confere maior significado ao protocolo de comunicação. Em vez de trafegar dados crus, enviamos também metadados que permitem a construção de clientes mais genéricos dos nossos serviços.</p>
<p>Reduzindo o conhecimento que os clientes têm sobre o servidor, naturalmente o acoplamento diminui. O servidor precisa manter fixa apenas  a URI inicial da conversação, pois as posteriores serão informadas durante a comunicação.</p>
<p>O servidor pode também utilizar múltiplos tipos de conteúdo, de forma que alguns clientes consigam interagir de forma mais ampla. Um exemplo seria um IPod que sabe consumir podcasts, enquanto estes seriam ignorados por um browser comum.</p>
<h2>Precisamos de Hypermedia em um protocolo REST?</h2>
<p><strong>Resposta curta</strong>: na minha opinião não.</p>
<p><strong>Resposta longa</strong>: espero que minha resposta curta não tenha deixado a impressão de que não valorizo Hypermedia. Muito pelo contrário, acho que um protocolo que use Hypermedia será muito elegante e terá baixo acomplamento.</p>
<p>Entretanto, construir protocolos para clientes genéricos é bem mais difícil. Em alguns casos a decisão de diminuir o acoplamento aumenta na mesma proporção a complexidade do protocolo de comunicação envolvido.</p>
<p>É perfeitamente possível criar um excelente protocolo de comunicação sem Hypermedia. Você poderá ter clientes de múltiplas plataformas, conversando com seu servidor em múltiplos formatos de conteúdo.</p>
<p>Há um ponto de atenção no quanto seus clientes conhecem sobre seus formatos de URIs. Sem Hypermedia, mudanças de URIs podem quebrar seus clientes, o que traz um nível de acoplamento maior do que o existente com Hypermedia.</p>
<p><strong>Recomendação geral</strong>: o uso de Hypermedia é consistente com a arquitetura da web, utilizada há muitos anos com sucesso. Quando um protocolo de comunicação REST faz uso de Hypermedia, o acoplamento fica baixo e nos dá bastante liberdade para evolução. O ideal é tentar usar Hypermedia ao máximo desde o começo, mas sempre ponderando o nível de complexidade na construção dos clientes.</p>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 1066px; width: 1px; height: 1px; overflow: hidden;">
<p style="margin-bottom: 0in;" lang="en-US"><span style="font-family: Courier New,monospace;"><span style="font-size: xx-small;">xml version=&#8221;1.0&#8243; encoding=&#8221;UTF-8&#8243;?&gt;</span></span></p>
<p style="margin-bottom: 0in;" lang="en-US"><span style="font-family: Courier New,monospace;"><span style="font-size: xx-small;">&lt;atom:entry xmlns:atom=&#8221;http://www.w3.org/2005/Atom&#8221;</span></span></p>
<p style="margin-bottom: 0in;" lang="en-US"><span style="font-family: Courier New,monospace;"><span style="font-size: xx-small;">xmlns:apps=&#8221;http://schemas.google.com/apps/2006&#8243;</span></span></p>
<p style="margin-bottom: 0in;" lang="en-US"><span style="font-family: Courier New,monospace;"><span style="font-size: xx-small;">xmlns:gd=&#8221;http://schemas.google.com/g/2005&#8243;&gt;</span></span></p>
<p style="margin-bottom: 0in;" lang="en-US"><span style="font-family: Courier New,monospace;"><span style="font-size: xx-small;">&lt;atom:id&gt;https://www.google.com/a/feeds/example.com/user/2.0/SusanJones&lt;/atom:id&gt;</span></span></p>
<p style="margin-bottom: 0in;" lang="en-US"><span style="font-family: Courier New,monospace;"><span style="font-size: xx-small;">&lt;atom:updated&gt;1970-01-01T00:00:00.000Z&lt;/atom:updated&gt;</span></span></p>
<p style="margin-bottom: 0in;" lang="en-US"><span style="font-family: Courier New,monospace;"><span style="font-size: xx-small;">&lt;atom:category scheme=&#8221;http://schemas.google.com/g/2005#kind&#8221;</span></span></p>
<p style="margin-bottom: 0in;" lang="en-US"><span style="font-family: Courier New,monospace;"><span style="font-size: xx-small;">term=&#8221;http://schemas.google.com/apps/2006#user&#8221;/&gt;</span></span></p>
<p style="margin-bottom: 0in;" lang="en-US"><span style="font-family: Courier New,monospace;"><span style="font-size: xx-small;">&lt;atom:title type=&#8221;text&#8221;&gt;SusanJones&lt;/atom:title&gt;</span></span></p>
<p style="margin-bottom: 0in;" lang="en-US"><span style="font-family: Courier New,monospace;"><span style="font-size: xx-small;">&lt;atom:link rel=&#8221;self&#8221; type=&#8221;application/atom+xml&#8221; </span></span></p>
<p style="margin-bottom: 0in;" lang="en-US"><span style="font-family: Courier New,monospace;"><span style="font-size: xx-small;">href=&#8221;https://www.google.com/a/feeds/example.com/user/2.0/SusanJones&#8221;/&gt;</span></span></p>
<p style="margin-bottom: 0in;" lang="en-US"><span style="font-family: Courier New,monospace;"><span style="font-size: xx-small;">&lt;atom:link rel=&#8221;edit&#8221; type=&#8221;application/atom+xml&#8221; </span></span></p>
<p style="margin-bottom: 0in;" lang="en-US"><span style="font-family: Courier New,monospace;"><span style="font-size: xx-small;">href=&#8221;https://www.google.com/a/feeds/example.com/user/2.0/SusanJones&#8221;/&gt;</span></span></p>
<p style="margin-bottom: 0in;" lang="en-US"><span style="font-family: Courier New,monospace;"><span style="font-size: xx-small;">&lt;apps:login userName=&#8221;SusanJones&#8221; suspended=&#8221;false&#8221; admin=&#8221;false&#8221; changePasswordAtNextLogin=&#8221;false&#8221; agreedToTerms=&#8221;true&#8221;/&gt;</span></span></p>
<p style="margin-bottom: 0in;" lang="en-US"><span style="font-family: Courier New,monospace;"><span style="font-size: xx-small;">&lt;apps:name familyName=&#8221;Jones&#8221; givenName=&#8221;Susan&#8221;/&gt;</span></span></p>
<p style="margin-bottom: 0in;" lang="en-US"><span style="font-family: Courier New,monospace;"><span style="font-size: xx-small;">&lt;gd:feedLink rel=&#8221;http://schemas.google.com/apps/2006#user.nicknames&#8221; </span></span></p>
<p style="margin-bottom: 0in;" lang="en-US"><span style="font-family: Courier New,monospace;"><span style="font-size: xx-small;">href=&#8221;https://www.google.com/a/feeds/example.com/nickname/2.0?</span></span></p>
<p style="margin-bottom: 0in;" lang="en-US"><span style="font-family: Courier New,monospace;"><span style="font-size: xx-small;"> username=Susy-1321&#8243;/&gt;</span></span></p>
<p style="margin-bottom: 0in;" lang="en-US"><span style="font-family: Courier New,monospace;"><span style="font-size: xx-small;">&lt;gd:feedLink rel=&#8221;http://schemas.google.com/apps/2006#user.emailLists&#8221; </span></span></p>
<p style="margin-bottom: 0in;" lang="en-US"><span style="font-family: Courier New,monospace;"><span style="font-size: xx-small;">href=&#8221;https://www.google.com/a/feeds/example.com/emailList/2.0?</span></span></p>
<p style="margin-bottom: 0in;" lang="en-US"><span style="font-family: Courier New,monospace;"><span style="font-size: xx-small;"> recipient=us-sales@example.com&#8221;/&gt;</span></span></p>
<p style="margin-bottom: 0in;" lang="en-US"><span style="font-family: Courier New,monospace;"><span style="font-size: xx-small;">&lt;/atom:entry&gt;</span></span></p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://brunopereira.org/2010/08/03/uso-de-hypermedia-em-protocolos-rest/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Ajax com validação no VRaptor c/ jQuery</title>
		<link>http://brunopereira.org/2010/06/17/ajax-com-validacao-no-vraptor-c-jquery/</link>
		<comments>http://brunopereira.org/2010/06/17/ajax-com-validacao-no-vraptor-c-jquery/#comments</comments>
		<pubDate>Fri, 18 Jun 2010 00:57:45 +0000</pubDate>
		<dc:creator>blpsilva</dc:creator>
				<category><![CDATA[client-side]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[vraptor]]></category>

		<guid isPermaLink="false">http://brunopereira.org/?p=348</guid>
		<description><![CDATA[Depois de um longo inverno estou voltando a escrever, e estou com algumas coisas na fila que devem sair em breve. Sem muita cerimônia, quero mostrar uma abordagem que me agrada de ajax com validação no VRaptor usando o jQuery.
O código é bem sucinto e simplório, somente com o necessário para falar do que quero. [...]]]></description>
			<content:encoded><![CDATA[<p>Depois de um longo inverno estou voltando a escrever, e estou com algumas coisas na fila que devem sair em breve. Sem muita cerimônia, quero mostrar uma abordagem que me agrada de ajax com validação no VRaptor usando o jQuery.</p>
<p>O código é bem sucinto e simplório, somente com o necessário para falar do que quero. Primeiro a classe JsonController, com 2 métodos que serão acessados pelo client jQuery. Um deles ilustra uma requisição com sucesso e o outro uma requisição com erro.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.ArrayList</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.List</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">br.com.caelum.vraptor.Get</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">br.com.caelum.vraptor.Path</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">br.com.caelum.vraptor.Resource</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">br.com.caelum.vraptor.Result</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">br.com.caelum.vraptor.view.Results</span><span style="color: #339933;">;</span>
&nbsp;
@Resource
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> JsonController <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Result result<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> JsonController<span style="color: #009900;">&#40;</span>Result result<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;">result</span> <span style="color: #339933;">=</span> result<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Get
	@Path<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;/json/erro&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> jsonErro<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		List<span style="color: #339933;">&lt;</span>String<span style="color: #339933;">&gt;</span> erros <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ArrayList<span style="color: #339933;">&lt;</span>String<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		erros.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Erro 1&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		erros.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Erro 2&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #666666; font-style: italic;">//Results.http() em vez de Status.badRequest(), pois este força uma página de erro, que ñ serve p/ um cliente ajax </span>
		result.<span style="color: #006633;">use</span><span style="color: #009900;">&#40;</span>Results.<span style="color: #006633;">http</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">setStatusCode</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">400</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
		result.<span style="color: #006633;">use</span><span style="color: #009900;">&#40;</span>Results.<span style="color: #006633;">json</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">from</span><span style="color: #009900;">&#40;</span>erros, <span style="color: #0000ff;">&quot;erros&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">serialize</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><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Get
	@Path<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;/json/sucesso&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> jsonSucesso<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		List<span style="color: #339933;">&lt;</span>String<span style="color: #339933;">&gt;</span> strings <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ArrayList<span style="color: #339933;">&lt;</span>String<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		strings.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Texto 1&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		strings.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Texto 2&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		result.<span style="color: #006633;">use</span><span style="color: #009900;">&#40;</span>Results.<span style="color: #006633;">http</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">setStatusCode</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">200</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		result.<span style="color: #006633;">use</span><span style="color: #009900;">&#40;</span>Results.<span style="color: #006633;">json</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">from</span><span style="color: #009900;">&#40;</span>strings, <span style="color: #0000ff;">&quot;strings&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">serialize</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><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Observação importante sobre o Controller: quem me conhece sabe da minha predileção por bons designs com REST, então neste exemplo essa premissa é seguida. O caso de sucesso retorna um HTTP 200 indicando o sucesso, e o caso de erro retorna HTTP 400 (Bad Request), indicando ao cliente que sua requisição tinha problemas que precisam ser corrigidos.</p>
<p>Ambos os casos retornam JSON para o cliente Ajax. No caso de sucesso o jQuery consome isto diretamente. No caso de erro o JSON com os erros será consumido do responseText do XmlHttpRequest.</p>
<p>Criei um HTML simples para teste, com 2 botões para gerar os requests ajax de sucesso e de erro.</p>

<div class="wp_syntax"><div class="code"><pre class="html4strict" style="font-family:monospace;"><span style="color: #00bbdd;">&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot; &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">html</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">head</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">meta</span> <span style="color: #000066;">http-equiv</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;Content-Type&quot;</span> <span style="color: #000066;">content</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/html;charset=UTF-8&quot;</span> <span style="color: #66cc66;">/</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">title</span>&gt;</span>Ajax com validação<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">title</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">head</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">body</span> <span style="color: #000066;">id</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;public&quot;</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">id</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;container&quot;</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">h1</span> <span style="color: #000066;">id</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;logo&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">h1</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">form</span> <span style="color: #000066;">id</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;teste-json&quot;</span> <span style="color: #000066;">name</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;teste-json&quot;</span> <span style="color: #000066;">enctype</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;application/x-www-form-urlencoded&quot;</span> <span style="color: #000066;">method</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;post&quot;</span> <span style="color: #000066;">action</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;/json/erro&quot;</span>&gt;</span>
&nbsp;
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;info&quot;</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">h2</span>&gt;</span>Teste JSON<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">h2</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;info&quot;</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">ul</span> <span style="color: #000066;">id</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;campos-cadastro&quot;</span>&gt;</span>	
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">li</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;buttons &quot;</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">input</span> <span style="color: #000066;">id</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;erro&quot;</span> <span style="color: #000066;">name</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;erro&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;button&quot;</span> <span style="color: #000066;">value</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;Teste Erro&quot;</span> <span style="color: #66cc66;">/</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">li</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">li</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;buttons &quot;</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">input</span> <span style="color: #000066;">id</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;sucesso&quot;</span> <span style="color: #000066;">name</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;sucesso&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;button&quot;</span> <span style="color: #000066;">value</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;Teste Sucesso&quot;</span> <span style="color: #66cc66;">/</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">li</span>&gt;</span>	
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">ul</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">form</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">img</span> <span style="color: #000066;">id</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;bottom&quot;</span> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;/images/bottom.png&quot;</span> <span style="color: #000066;">alt</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;&quot;</span> <span style="color: #66cc66;">/</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">script</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;/scripts/jquery-1.4.2.min.js&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">script</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">script</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;/scripts/teste-json.js&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">script</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">body</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">html</span>&gt;</span></pre></div></div>

<p>Para completar, o javascript que trata do clique nos botões, faz os requests e consome o JSON de sucesso e o JSON com as mensagens de erro.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span>document<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">ready</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span> 
	$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;input#erro&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">click</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		$.<span style="color: #660066;">ajax</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
		   type<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;GET&quot;</span><span style="color: #339933;">,</span>
		   url<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;/json/erro&quot;</span><span style="color: #339933;">,</span>
		   dataType<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;json&quot;</span><span style="color: #339933;">,</span>
		   success<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>json<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>    		
    		<span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> x <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> x <span style="color: #339933;">&lt;</span> json.<span style="color: #660066;">erros</span>.<span style="color: #660066;">length</span><span style="color: #339933;">;</span> x<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    			<span style="color: #003366; font-weight: bold;">var</span> erro <span style="color: #339933;">=</span> json.<span style="color: #660066;">erros</span><span style="color: #009900;">&#91;</span>x<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    			<span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Erro: &quot;</span> <span style="color: #339933;">+</span> erro<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    		<span style="color: #009900;">&#125;</span>    	    
    	  <span style="color: #009900;">&#125;</span>
    	<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;input#erro&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">ajaxError</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>e<span style="color: #339933;">,</span> xhr<span style="color: #339933;">,</span> settings<span style="color: #339933;">,</span> exception<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003366; font-weight: bold;">var</span> errosStr <span style="color: #339933;">=</span> xhr.<span style="color: #660066;">responseText</span><span style="color: #339933;">;</span>
		<span style="color: #003366; font-weight: bold;">var</span> json <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">eval</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;(&quot;</span> <span style="color: #339933;">+</span> errosStr <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;)&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>		
		<span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> x <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> x <span style="color: #339933;">&lt;</span> json.<span style="color: #660066;">erros</span>.<span style="color: #660066;">length</span><span style="color: #339933;">;</span> x<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #003366; font-weight: bold;">var</span> erro <span style="color: #339933;">=</span> json.<span style="color: #660066;">erros</span><span style="color: #009900;">&#91;</span>x<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
                        <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Erro: &quot;</span> <span style="color: #339933;">+</span> erro<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;input#sucesso&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">click</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		$.<span style="color: #660066;">ajax</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
		   type<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;GET&quot;</span><span style="color: #339933;">,</span>
		   url<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;/json/sucesso&quot;</span><span style="color: #339933;">,</span>
		   dataType<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;json&quot;</span><span style="color: #339933;">,</span>
		   success<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>json<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>    		
    		<span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> x <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> x <span style="color: #339933;">&lt;</span> json.<span style="color: #660066;">strings</span>.<span style="color: #660066;">length</span><span style="color: #339933;">;</span> x<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    			<span style="color: #003366; font-weight: bold;">var</span> texto <span style="color: #339933;">=</span> json.<span style="color: #660066;">strings</span><span style="color: #009900;">&#91;</span>x<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    			<span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Texto: &quot;</span> <span style="color: #339933;">+</span> texto<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    		<span style="color: #009900;">&#125;</span>    	    
    	  <span style="color: #009900;">&#125;</span>
    	<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;input#sucesso&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">ajaxError</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>e<span style="color: #339933;">,</span> xhr<span style="color: #339933;">,</span> settings<span style="color: #339933;">,</span> exception<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003366; font-weight: bold;">var</span> errosStr <span style="color: #339933;">=</span> xhr.<span style="color: #660066;">responseText</span><span style="color: #339933;">;</span>
		<span style="color: #003366; font-weight: bold;">var</span> json <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">eval</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;(&quot;</span> <span style="color: #339933;">+</span> errosStr <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;)&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>		
		<span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> x <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> x <span style="color: #339933;">&lt;</span> json.<span style="color: #660066;">erros</span>.<span style="color: #660066;">length</span><span style="color: #339933;">;</span> x<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #003366; font-weight: bold;">var</span> erro <span style="color: #339933;">=</span> json.<span style="color: #660066;">erros</span><span style="color: #009900;">&#91;</span>x<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
			<span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Erro: &quot;</span> <span style="color: #339933;">+</span> erro<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>				 
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>    
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://brunopereira.org/2010/06/17/ajax-com-validacao-no-vraptor-c-jquery/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Hypermedia as the engine of application state</title>
		<link>http://brunopereira.org/2009/04/05/hypermedia-as-the-engine-of-application-state/</link>
		<comments>http://brunopereira.org/2009/04/05/hypermedia-as-the-engine-of-application-state/#comments</comments>
		<pubDate>Sun, 05 Apr 2009 15:08:23 +0000</pubDate>
		<dc:creator>blpsilva</dc:creator>
				<category><![CDATA[design]]></category>
		<category><![CDATA[posts em português]]></category>
		<category><![CDATA[hateoas]]></category>
		<category><![CDATA[hypermedia]]></category>
		<category><![CDATA[rest]]></category>

		<guid isPermaLink="false">http://brunopereira.org/?p=305</guid>
		<description><![CDATA[Este é o significado de HATEOAS, uma nova sigla cunhada recentemente no domínio de serviços REST. O principal aspecto envolvido nisso é a navegabilidade de recursos, e a maneira de exposição dos mesmos. Alcançar plenamente isso não é fácil, e embora eu tenha ciência dos benefícios disso há um certo tempo, ainda não cheguei a [...]]]></description>
			<content:encoded><![CDATA[<p>Este é o significado de HATEOAS, uma nova sigla cunhada recentemente no domínio de serviços REST. O principal aspecto envolvido nisso é a navegabilidade de recursos, e a maneira de exposição dos mesmos. Alcançar plenamente isso não é fácil, e embora eu tenha ciência dos benefícios disso há um certo tempo, ainda não cheguei a ter a navegabilidade de recursos plenamente implementada em nenhum projeto.</p>
<p>Para quem tiver interesse no assunto, recomendo demais a leitura <a href="http://tech.groups.yahoo.com/group/rest-discuss/messages/12357?threaded=1&amp;m=e&amp;var=1&amp;tidx=1" target="_blank">dessa thread</a>. A discussão é de altíssimo nível, e certamente pode trazer várias idéias bacanas.</p>
]]></content:encoded>
			<wfw:commentRss>http://brunopereira.org/2009/04/05/hypermedia-as-the-engine-of-application-state/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>I&#8217;m a SlideShare RockStar!</title>
		<link>http://brunopereira.org/2009/04/01/im-a-slideshare-rockstar/</link>
		<comments>http://brunopereira.org/2009/04/01/im-a-slideshare-rockstar/#comments</comments>
		<pubDate>Wed, 01 Apr 2009 12:57:13 +0000</pubDate>
		<dc:creator>blpsilva</dc:creator>
				<category><![CDATA[posts em português]]></category>
		<category><![CDATA[#bestofslideshare]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[slideshare]]></category>
		<category><![CDATA[web services]]></category>
		<category><![CDATA[web services rest]]></category>

		<guid isPermaLink="false">http://brunopereira.org/?p=304</guid>
		<description><![CDATA[Recebi hoje de manhã um e-mail do SlideShare me falando que eu sou um RockStar!  
&#8220;Hi blpsilva,
We&#8217;ve noticed that your slideshow on SlideShare has been getting a LOT of views in the last 24 hours. Great job &#8230; you must be doing something right.  
Why don&#8217;t you tweet or blog this? Use the [...]]]></description>
			<content:encoded><![CDATA[<p>Recebi hoje de manhã um e-mail do SlideShare me falando que eu sou um RockStar! <img src='http://brunopereira.org/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><em>&#8220;Hi blpsilva,</p>
<p>We&#8217;ve noticed that your slideshow on SlideShare has been getting a LOT of views in the last 24 hours. Great job &#8230; you must be doing something right. <img src='http://brunopereira.org/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>Why don&#8217;t you tweet or blog this? Use the hashtag #bestofslideshare so we can track the conversation.&#8221;</em></p>
<p>A única apresentação que coloquei até hoje foi a de <a href="http://www.slideshare.net/blpsilva/web-services-rest-presentation" target="_blank">Web Service REST</a>, logo após <a href="http://brunopereira.org/2008/09/20/aniversario-do-cejug-retrospectiva/" target="_blank">o aniversário do CEJUG ano passado</a>. Acessei minha conta lá e vi que a apresentação lá passou de 30 mil visualizações, em 6 meses. Eu não imaginava que isso pudesse ter um alcance tão grande, fiquei bem contente. Seems like I&#8217;m doing something right <img src='http://brunopereira.org/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Preciso em algum momento preparar mesmo um <a href="http://brunopereira.org/2008/05/30/curso-de-web-services-rest/" target="_blank">curso de Web Services</a>, incluindo REST e WS-*, já que o interesse nisso parece grande, e eu venho acumulando muita experiência nessa área.</p>
<p>Uma idéia que tive um tempo atrás seria de discutir aqui no blog algumas dúvidas sobre como utilizar REST e Web Services de forma efetiva em situações reais. Eu já conversei com muitas pessoas sobre isso, e algumas dúvidas são freqüentes, e outras são mais sofisticadas e diferentes. Eu terei um enorme prazer em discutir isso aqui, pois me trará situações novas para analisar e é um exercício interessante que pode contribuir para mim e para outras pessoas que estejam trabalhando na área.</p>
<p>Vou saborear meu momento de RockStar do SlideShare então, e incentivo a todos que queiram propôr discussões sobre REST (e web services em geral) que entre em contato para vermos o que surge de interessante <img src='http://brunopereira.org/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://brunopereira.org/2009/04/01/im-a-slideshare-rockstar/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Migrando para REST: exposição de Recursos x exposição do domínio</title>
		<link>http://brunopereira.org/2009/03/22/migrando-para-rest-exposicao-de-recursos-x-exposicao-do-dominio/</link>
		<comments>http://brunopereira.org/2009/03/22/migrando-para-rest-exposicao-de-recursos-x-exposicao-do-dominio/#comments</comments>
		<pubDate>Sun, 22 Mar 2009 23:30:15 +0000</pubDate>
		<dc:creator>blpsilva</dc:creator>
				<category><![CDATA[design]]></category>
		<category><![CDATA[posts em português]]></category>
		<category><![CDATA[acoplamento]]></category>
		<category><![CDATA[business service]]></category>
		<category><![CDATA[orchestration]]></category>
		<category><![CDATA[orquestração]]></category>
		<category><![CDATA[proxy service]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[web services]]></category>

		<guid isPermaLink="false">http://brunopereira.org/?p=299</guid>
		<description><![CDATA[Meus camaradas do ISP da Globo estão estudando a migração da arquitetura imperativa com EJBs para uma arquitetura RESTFul.
Esta migração tem muitos aspectos semelhantes à que fizemos no time de cadastro/autenticação no ano passado, e eu já conversei algumas vezes com o pessoal do ISP sobre isso, pois conheço bem o domínio deles. Entretanto, o [...]]]></description>
			<content:encoded><![CDATA[<p>Meus camaradas do <a href="http://atendimento.globo.com/Portal/ISP/assineja/panfletos/panfleto_home_globo" target="_blank">ISP</a> da <a href="http://www.globo.com" target="_blank">Globo</a> estão estudando a migração da <a href="http://brunopereira.org/webservicesrest-arquitetura/" target="_blank">arquitetura imperativa</a> com EJBs para uma <a href="http://brunopereira.org/webservicesrest-arquitetura/" target="_blank">arquitetura RESTFul</a>.</p>
<p>Esta migração tem muitos aspectos semelhantes à que fizemos no time de <a href="http://cadastro.globo.com/cadastro/1727" target="_blank">cadastro</a>/<a href="http://login.globo.com/login/1" target="_blank">autenticação</a> no ano passado, e eu já conversei algumas vezes com o pessoal do ISP sobre isso, pois conheço bem o domínio deles. Entretanto, o domínio do ISP é um pouco mais complexo que o do cadastro, e isso torna a modelagem de recursos um pouco mais sofisticada e interessante.</p>
<p>O exemplo que vou descrever aqui é o do <strong><a href="http://en.wikipedia.org/wiki/Command_pattern" target="_blank">Comando</a></strong> CmdFinalizaCompra. Este <strong>Comando</strong> é invocado no final de qualquer operação do ISP que modifique a cesta de produtos/serviços do assinante. Pelo próprio nome, fica óbvio que ele foi constituído de maneira imperativa (&#8220;FazerEstaOperacao&#8221;), e o pessoal estava em dúvida sobre como redesenhar este modelo e colocá-lo num desenho declarativo, à maneira RESTFul.</p>
<p>Vou mencionar resumidamente a estrutura de comunicação dos comandos do ISP para que o resto da discussão fique claro. Cada <strong>Comando</strong> é constituído de 2 classes Java. <em><strong>CmdNomeComando</strong></em> e <em><strong>CmdNomeComandoSrv</strong></em>. A primeira classe corresponde ao Comando do lado do cliente, e a segunda corresponde ao Comando do lado do servidor.</p>
<p>Na execução do comando, o cliente invoca um EJB 2.1 stateless no servidor, e envia a classe <em><strong>CmdNomeComando</strong></em> serializada, via RMI. O servidor recebe a classe, deserializa-a, executa a operação em questão e retorna a classe novamente para o cliente, com ou sem modificações, dependendo do caso.</p>
<p>Este modelo é semelhante à chamada de serviços SOAP, em que é invocada uma operação SOAP com um documento XML de entrada e alguma coisa na saída.</p>
<p>Podemos ver a classe <em><strong>CmdNomeComando</strong></em> como o &#8220;parâmetro de entrada&#8221; da operação, e a classe <em><strong>CmdNomeComandoSrv</strong></em> como a implementação da operação em questão. Este exemplo do CmdFinalizaCompra envolve vários componentes do modelo do ISP. Não sei dos detalhes de cabeça, mas este processo envolve Assinante, Usuario, Produto, Promocao, Desconto e possivelmente mais alguns elementos do domínio.</p>
<p>Assim, um objeto CmdFinalizaCompra é composto de vários objetos deste domínio. A dúvida deles é sobre a definição dos recursos neste contexto. É uma dúvida pertinente, pois isto foge bastante a um CRUD óbvio. Uma <em><strong>possibilidade</strong></em> de desenho definiria como recursos: <strong>Assinante</strong>, <strong>Usuario</strong>, <strong>Produto</strong>, <strong>Promocao</strong> e <strong>Desconto</strong>. Isto seria mapeável diretamente na implementação do domínio deles. O que vocês acham disso?</p>
<p>Bom, não vejo nada errado em expor um recurso Assinante, outro Usuario, etc. Isto pode fazer sentido para outras &#8220;operações&#8221;, maravilha. Entretanto, para este caso isso levantou a seguinte dúvida para eles: &#8220;<em><strong>Eu vou ter que fazer vários POSTs para realizar a operação do CmdFinalizaCompra</strong></em>&#8221; ?</p>
<p>Imagine a complexidade de garantir o sucesso transacional dos vários POSTs independentes que compõem esta operação! No universo WS-* existe o conceito chamado <a href="http://en.wikipedia.org/wiki/Orchestration_(computers)" target="_blank">Orquestração</a>, no qual um determinado componente agrega e invoca várias operações pequenas em uma única operação/transação. Utilizando nomes pomposos, isto seria um <em><strong>Proxy Service</strong></em> invocando alguns <em><strong>Business Services</strong></em>. Algum de vocês se sente tentado a usar esta abordagem? Eu não!</p>
<p>O que eu sugiro neste exemplo é a criação de um recurso chamado <strong>Compra</strong>, que pode ser representado por um grafo sofisticado de objetos do domínio do ISP. Para substituir o CmdFinalizaCompra, eu vejo a criação de uma instância do recurso Compra, com todas as informações pertinentes à compra em questão. A criação deste recurso estaria associada a uma única transação, seja lá o que tenha que ser feito por baixo dos panos no servidor.</p>
<p>Na implementação do servidor, eu vejo somente este POST sendo realizado. <span style="color: #ff0000;"><strong>O cliente não precisa saber (e é melhor que não saiba) como é implementado o domínio no servidor</strong></span>. Ele precisa conhecer os <strong>recursos expostos</strong>, e como interagir com eles.</p>
<p>Pense numa compra na Amazon, por exemplo. Eles poderiam expôr este mesmo recurso Compra que eu falei, que seria composto pelos produtos, pelo cliente e talvez a opção de pagamento.</p>
<p>Isso seria exposto pelo recurso, mas dentro da Amazon uma compra poderia envolver N operações: reserva de estoque, criação de ordem de entrega, lançamento da cobrança, criação de comissão para o distribuidor, etc. O cliente do Recurso só conhece os detalhes do que foi exposto, e isso não implica em detalhes de implementação no servidor.</p>
<p>Lembrem que um dos principais objetivos para uma arquitetura RESTFul é ter baixo acoplamento, então tenham a liberdade de modelar seu domínio e seus recursos como fizer mais sentido.</p>
]]></content:encoded>
			<wfw:commentRss>http://brunopereira.org/2009/03/22/migrando-para-rest-exposicao-de-recursos-x-exposicao-do-dominio/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>À procura de uma maneira produtiva de trabalhar com web services SOAP</title>
		<link>http://brunopereira.org/2008/12/08/a-procura-de-uma-maneira-produtiva-de-trabalhar-com-web-services-soap/</link>
		<comments>http://brunopereira.org/2008/12/08/a-procura-de-uma-maneira-produtiva-de-trabalhar-com-web-services-soap/#comments</comments>
		<pubDate>Tue, 09 Dec 2008 00:28:03 +0000</pubDate>
		<dc:creator>blpsilva</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[posts em português]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[apache cxf]]></category>
		<category><![CDATA[aqualogic]]></category>
		<category><![CDATA[axis]]></category>
		<category><![CDATA[axis 2]]></category>
		<category><![CDATA[bea]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[glassfish]]></category>
		<category><![CDATA[jboss]]></category>
		<category><![CDATA[metro]]></category>
		<category><![CDATA[netbeans]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[soap]]></category>
		<category><![CDATA[Sun]]></category>
		<category><![CDATA[web services]]></category>
		<category><![CDATA[wsdl]]></category>

		<guid isPermaLink="false">http://brunopereira.org/?p=262</guid>
		<description><![CDATA[Com a minha mudança de alocação da Globo.com para a Globosat, continuo trabalhando bastante com integração de aplicações, mas agora com um ferramental e paradigmas diferentes.
Na Globo.com eu trabalhei muito com open source, e estava acostumado a montar as aplicações a partir de componentes &#8220;crus&#8221;, em vez de usar ferramentas sofisticadas. Open source faz parte [...]]]></description>
			<content:encoded><![CDATA[<p>Com a minha <a href="http://brunopereira.org/2008/11/28/adeus-globocom-foi-um-grande-prazer/" target="_blank">mudança de alocação</a> da <a href="http://www.globo.com" target="_blank">Globo.com</a> para a <a href="http://globosat.globo.com/" target="_blank">Globosat</a>, continuo trabalhando bastante com integração de aplicações, mas agora com um ferramental e paradigmas diferentes.</p>
<p>Na Globo.com eu trabalhei muito com open source, e estava acostumado a montar as aplicações a partir de componentes &#8220;crus&#8221;, em vez de usar ferramentas sofisticadas. Open source faz parte da cultura da empresa, e tínhamos uma boa liberdade de escolha de tecnologias e arquiteturas.</p>
<p>Como falei algumas vezes no passado, nós migramos boa parte da arquitetura legada com EJBs para serviços <a href="http://brunopereira.org/tag/rest/" target="_blank">REST</a> usando por baixo o <a href="https://jersey.dev.java.net/" target="_blank">Jersey</a>, <a href="http://www.springframework.org/" target="_blank">Spring</a> e <a href="http://ibatis.apache.org/" target="_blank">Ibatis</a>. A produtividade no desenvolvimento de serviços REST me agrada muito, e mesmo alguém que não conheça muito de serviços REST consegue desenvolver um serviço sem tanto esforço.</p>
<p>Agora vou trabalhar mais com serviços SOAP, mas usando ferramentas muito produtivas, como o <a href="http://www.bea.com/framework.jsp?CNT=index.htm&amp;FP=/content/products/aqualogic/service_bus/" target="_blank">Aqualogic ESB</a> e o <a href="http://www.bea.com/framework.jsp?CNT=index.htm&amp;FP=/content/products/weblogic/workshop/" target="_blank">Workshop</a>, entre outros. Essas ferramentas facilitam muito o trabalho oferecendo <a href="http://brunopereira.org/2008/12/04/abstracoes-transparentes-e-abstracoes-opacas/" target="_blank">Abstrações Opacas</a>. Como ainda estou muito ligado ao trabalho com Open Source, eu venho tentando no meu tempo vago encontrar ferramentas open source com a mesma proposta.</p>
<p>Neste momento estou tentando encontrar a maneira mais produtiva de se trabalhar com web services SOAP usando open source. No passado eu desenvolvi serviços com o <a href="http://xfire.codehaus.org/" target="_blank">XFire</a>, com o <a href="http://ws.apache.org/axis2/" target="_blank">Axis 2</a> e com o <a href="https://jax-ws.dev.java.net/" target="_blank">JAX-WS</a>, mas achei interessante reavaliar as opções existentes atualmente.</p>
<p>Nos últimos dias eu fiz testes com o Axis 2, com o <a href="http://cxf.apache.org/" target="_blank">Apache CXF</a> e com o JAX-WS.</p>
<p>Eu não gosto muito do Axis 2. Você até consegue desenvolver serviços rapidamente com ele, mas ele gera um código tão sujo que é muito triste colocar qualquer coisa em produção com ele, sabendo que você vai ter que manter depois aquele código. Além disso, para utilizá-lo você precisa levar nada menos que 51 jars para sua aplicação, o que transforma qualquer aplicação em um mastodonte. Um outro problema dessa lista massiva de dependências é que a chance de uma aplicação pré-existente ter conflitos de dependências com o Axis é grande.</p>
<p>Na prática, eu só utilizaria o Axis 2 (e mesmo assim com má vontade) para desenvolver serviços se fosse numa estrutura como o <a href="http://wso2.org/projects/wsas/java" target="_blank">WSO2 Web Services Application Server</a>, que é um servidor de aplicações &#8220;dedicado&#8221; a serviços Axis.</p>
<p>O Apache CXF oferece um &#8220;front-end&#8221; com JAX-WS (que é o mais recomendado) e um &#8220;front-end&#8221; alternativo, que usa o Aegis Databinding. Por enquanto olhei apenas o front-end com JAX-WS, mas não vi nenhuma vantagem em utilizar o CXF em vez da implementação de referência presente no <a href="https://glassfish.dev.java.net/" target="_blank">Glassfish</a>. Se pintar disposição eu darei uma olhada no front-end com Aegis Databinding, mas por enquanto não tenho grandes expectativas em relação a ele não.</p>
<p>Para finalizar, fiz muitos experimentos com a implementação de referência do JAX-WS, embutido no Glassfish V2. A forma de trabalho que achei mais produtiva nestes meus testes foi desenvolvendo com JAX-WS no <a href="http://www.netbeans.org" target="_blank">Netbeans</a> (utilizei a versão 6.5).</p>
<p>Tentei desenvolver a partir de classes Java, e a partir do <a href="http://www.w3.org/TR/wsdl" target="_blank">WSDL</a>, e esta última me trouxe melhores resultados.A melhor forma que achei foi começar desenhando os schemas XML com o editor do Netbeans:</p>
<p><a href="http://brunopereira.org/wp-content/uploads/2008/12/xml_schema_editor.jpg"><img class="alignnone size-full wp-image-263" title="xml_schema_editor" src="http://brunopereira.org/wp-content/uploads/2008/12/xml_schema_editor.jpg" alt="" width="471" height="586" /></a></p>
<p>Criei um Complex Type para cada classe de domínio, e 1 Complex Type para o Request de cada operação e 1 Complex Type para o Response de cada operação. Tendo feito isso, criei depois 1 Element para o Request de cada operação e 1 Element para o Response de cada operação. Com o schema XML criado dessa forma, criei em seguida o WSDL, com o editor do Netbeans também:</p>
<p><a href="http://brunopereira.org/wp-content/uploads/2008/12/wsdl_editor.jpg"><img class="alignnone size-full wp-image-264" title="wsdl_editor" src="http://brunopereira.org/wp-content/uploads/2008/12/wsdl_editor.jpg" alt="" width="418" height="702" /></a></p>
<p>Na criação do WSDL, coloquei nas mensagens de Request/Response das operações os <strong><em>Elementos</em></strong> declarados no schema XML anterior. É importante prestar atenção nisso. Usando Elementos nas mensagens, você está criando serviços no modelo <em><strong>Document/Literal</strong></em>. Se você colocar nas mensagens um <em><strong>Complex Type</strong></em> diretamente, em vez de colocar um <em><strong>Elemento</strong></em>, você estará criando um serviço no modelo <strong><em>RPC/Literal</em></strong>. Eu particularmente prefiro Document/Literal, e o código gerado pelo JAX-WS neste modelo me agrada mais.</p>
<p>A implementação do serviço com JAX-WS ficou parecida com isso aqui:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">org.brunopereira.cadastro</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.jws.WebService</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.brunopereira.schema.cadastroclientes.CadastroClienteRequestType</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.brunopereira.schema.cadastroclientes.CadastroClienteResponseType</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.brunopereira.schema.cadastroclientes.Cliente</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.brunopereira.wsdl.cadastrocliente.CadastroClientePortType</span><span style="color: #339933;">;</span>
&nbsp;
@WebService<span style="color: #009900;">&#40;</span>serviceName <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;CadastroClienteService&quot;</span>, portName <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;CadastroClientePort&quot;</span>,
endpointInterface <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;org.brunopereira.wsdl.cadastrocliente.CadastroClientePortType&quot;</span>,
targetNamespace <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;http://brunopereira.org/wsdl/CadastroCliente&quot;</span>,
wsdlLocation <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;WEB-INF/wsdl/CadastroCliente/CadastroCliente.wsdl&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> CadastroCliente <span style="color: #000000; font-weight: bold;">implements</span> CadastroClientePortType <span style="color: #009900;">&#123;</span>
<span style="color: #000000; font-weight: bold;">public</span> CadastroClienteResponseType cadastrarCliente<span style="color: #009900;">&#40;</span>CadastroClienteRequestType request<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;Cadastro de cliente foi invocado!! Será feito o roteamento para o serviço adequado!!&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
Cliente cliente <span style="color: #339933;">=</span> request.<span style="color: #006633;">getCliente</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
CadastroClienteResponseType response <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> CadastroClienteResponseType<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
response.<span style="color: #006633;">setCliente</span><span style="color: #009900;">&#40;</span>cliente<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">return</span> response<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>O código do cliente foi gerado bem facilmente a partir do WSDL também, e ficou bem limpo. O que achei bem fraco foi a parte de teste dos serviços tanto no Netbeans como no Eclipse. No Eclipse você só consegue usar os plugins de teste se você tiver desenvolvido os serviços dentro do Eclipse, o que inviabilizou o meu uso. E o Netbeans tem um suporte que só serve pra HelloWorld, pra aqueles serviços de Calculadora, que você passa uns parâmetros primitivos e recebe um resultado simples. A interface do testador do meu serviço ficou dessa forma:<br />
<a href="http://brunopereira.org/wp-content/uploads/2008/12/web_services_tester.jpg"><img class="alignnone size-full wp-image-265" title="web_services_tester" src="http://brunopereira.org/wp-content/uploads/2008/12/web_services_tester.jpg" alt="" width="800" height="500" /></a></p>
<p>Dá pra ver que não serve para nada além de um HelloWorld basicão.</p>
<p>Bom, de uma maneira geral, o suporte a Web Services no Netbeans é muito melhor do que no Eclipse, que pra piorar só suporta a criação de serviços com o Axis. Até agora a maneira mais produtiva que encontrei de trabalhar com serviços SOAP foi essa que descrevi. Nos próximos dias olharei o que tem de interessante no projeto Metro e no JBoss ESB. Se encontrar coisas interessantes falarei mais por aqui. Ah, e se alguém tiver dicas para melhorar esta forma de trabalho que descrevi, por favor me avisem, pois estou avaliando muita coisa e não dá tempo de dedicar tanto tempo a cada opção dessas.</p>
]]></content:encoded>
			<wfw:commentRss>http://brunopereira.org/2008/12/08/a-procura-de-uma-maneira-produtiva-de-trabalhar-com-web-services-soap/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Adeus Globo.com, foi um grande prazer</title>
		<link>http://brunopereira.org/2008/11/28/adeus-globocom-foi-um-grande-prazer/</link>
		<comments>http://brunopereira.org/2008/11/28/adeus-globocom-foi-um-grande-prazer/#comments</comments>
		<pubDate>Fri, 28 Nov 2008 10:34:39 +0000</pubDate>
		<dc:creator>blpsilva</dc:creator>
				<category><![CDATA[carreira]]></category>
		<category><![CDATA[posts em português]]></category>
		<category><![CDATA[capixaba]]></category>
		<category><![CDATA[concrete]]></category>
		<category><![CDATA[concrete solutions]]></category>
		<category><![CDATA[ejv]]></category>
		<category><![CDATA[globo.com]]></category>
		<category><![CDATA[globosat]]></category>
		<category><![CDATA[paraense]]></category>
		<category><![CDATA[prudentino]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[scrum]]></category>

		<guid isPermaLink="false">http://brunopereira.org/?p=258</guid>
		<description><![CDATA[Depois de mais de 2 anos e meio, hoje é o meu último dia alocado na Globo.com. A partir de segunda-feira (01/12) já estarei alocado em um novo projeto, também nas Organizações Globo, mas desta vez na Globosat.
Eu levarei várias boas lembranças, de um período que foi muito positivo para mim. Comparando a minha experiência [...]]]></description>
			<content:encoded><![CDATA[<p>Depois de mais de 2 anos e meio, hoje é o meu último dia alocado na <a href="http://www.globo.com" target="_blank">Globo.com</a>. A partir de segunda-feira (01/12) já estarei alocado em um novo projeto, também nas Organizações Globo, mas desta vez na <a href="http://globosat.globo.com/" target="_blank">Globosat</a>.</p>
<p>Eu levarei várias boas lembranças, de um período que foi muito positivo para mim. Comparando a minha experiência e maturidade agora com o momento em que entrei na Globo, a diferença é enorme. Tive a oportunidade de trabalhar com profissionais de altíssimo nível e em projetos de enorme importância técnica e de negócio. Tive também a sorte de atuar em áreas com as quais tenho muita afinidade e interesse, o que ajuda bastante no envolvimento de qualquer profissional.</p>
<p>Quando cheguei à Globo pude vivenciar uma situação nova para mim. Passei a ter a satisfação de ir trabalhar feliz todos os dias. Atuando em um ótimo ambiente de trabalho no qual o software fica em primeiro plano. Com o benefício extra de saber que meu trabalho teria a visibilidade do maior portal de internet da América Latina.</p>
<p>Além disso, posso dizer que vivi muitos progressos dentro da empresa. Acompanhei o surgimento de produtos como o <a href="http://g1.globo.com/" target="_blank">G1</a>, o <a href="http://www.8p.com.br/flog/home" target="_blank">8P</a>, o <a href="http://futpedia.globo.com/" target="_blank">Futpedia</a> e o <a href="http://globoesporte.globo.com/Esportes/Futebol/Brasileirao/musa/0,,9855,00.html" target="_blank">Musas</a>, além de um progresso fantástico na plataforma de <a href="http://video.globo.com/" target="_blank">Vídeos</a>. Acompanhei de perto a produção interna para eventos como a Copa de 2006 e as Olimpíadas de Pequim. Poder vivenciar esse crescimento da empresa foi muito interessante.</p>
<p>Também me deixou muito feliz a abordagem da Globo.com em relação a Open Source. Quando cheguei na empresa, todo mundo usava Windows, o servidor de aplicações mais usado era o Weblogic e embora já existisse o uso de muitos softwares open source, isso não fazia parte da cultura da empresa.</p>
<p>Hoje em dia a relação da Globo com Open Source é excelente. Todos apostam no uso de Open Source, os desenvolvedores todos usam Linux, nossos servidores de aplicação são quase todos Open Source, já há vários projetos com banco de dados open source, e a maturidade dos profissionais em relação a Open Source aumentou muito. Pra mim isso foi muito gratificante. Durante mais de 1 ano e meio eu tive a satisfação de trabalhar full time com Linux, e acredito que consegui contribuir um pouco também para que outros utilizassem de forma produtiva.</p>
<p>Ainda mais importante do que a relação com open source foi a adoção de metodologias ágeis. Quando cheguei na Globo.com a maioria dos projetos era no estilo Waterfall. Não é necessário explicar com detalhes aqui, mas era muito perceptível que os projetos não andavam na velocidade que poderiam.</p>
<p>Aos poucos o Scrum começou a ser utilizado, e alguns meses depois isso desencadeou uma série de mudanças positivas na empresa. Este ano inteiro eu trabalhei em um time Scrum, e foi uma experiência excelente. Passamos a ter uma equipe multi-disciplinar, tendo contato diário com um designer, com um arquiteto de informação e um desenvolvedor client-side. Isso foi muito benéfico para mim. Acompanhar de perto o trabalho de profissionais de outra especialidade me ensinou muito sobre a atuação deles, e claro, aprendi muito sobre client-side e passei a gostar disso, o que é fundamental para qualquer desenvolvedor web.</p>
<p>Ao longo do ano nós amadurecemos muito a nossa forma de trabalho, e a utilização de práticas ágeis foi fundamental nisso. Claro que ainda existem arestas a serem aparadas e pontos que precisamos melhorar, mas sem dúvida nosso time evoluiu muito esse ano.</p>
<p>Tecnicamente o ano foi muito bom para mim também. Participei de projetos muito interessantes como a migração para o <a href="http://login.globo.com/login/1" target="_blank">e-mail no Google</a>, onde atuei diretamente na integração entre as empresas. Outros projetos muito bacanas foram o <a href="http://cadastro.globo.com/cadastro/807" target="_blank">novo cadastro</a> e a nova <a href="http://brunopereira.org/wp-admin/login.globo.com/login/464" target="_blank">Central do Usuário</a>.</p>
<p>O projeto de integração com o Google foi o primeiro projeto crítico no qual utilizamos <a href="http://brunopereira.org/webservicesrest-indice/" target="_blank">REST</a>, e como tivemos muito sucesso, todas as nossas aplicações já estão usando REST, e falta mais um pouquinho só para que nossa arquitetura seja 100% migrada de comunicações via EJB para REST. Aprendi muuuuuuuito nesse processo, foi uma experiência excelente.</p>
<p>Os projetos do Cadastro e da Central foram muito interessantes do ponto de vista de produto e do ponto de vista de desenvolvimento. As 2 aplicações foram desenhadas para terem módulos dinâmicos de cadastro. Isso permite que cada produto tenha o seu próprio template de cadastro, e as informações requisitadas dos usuários são configuradas por uma ferramenta de administração.</p>
<p>O desenvolvimento destas aplicações exigiu um trabalho muito interessante de modelagem e desenvolvimento, com muitas refatorações até que chegássemos no modelo final. Aprendi muito também com esses dois projetos.</p>
<p>Mas nem só de software vive uma pessoa <img src='http://brunopereira.org/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />   Nesse meu período na Globo.com eu conheci muitas pessoas fantásticas e fiz muitos amigos. O ambiente de trabalho e as pessoas da Globo.com são um dos maiores motivos para que tenha sido tão legal trabalhar na empresa, e com certeza vou sempre me lembrar disso.</p>
<p>Meu time de desenvolvimento esse ano é muito bem entrosado e positivo. Tacaram na mesma mistura 2 cariocas, 1 <a href="http://pt.wikipedia.org/wiki/Capixaba" target="_blank">capixaba</a>, 1 <a href="http://pt.wikipedia.org/wiki/Presidente_prudente" target="_blank">prudentino</a> e 1 <a href="http://pt.wikipedia.org/wiki/Par%C3%A1" target="_blank">paraense</a>, e deu muito certo <img src='http://brunopereira.org/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Gostei muito da experiência, e vou com certeza sentir falta desses picaretas <img src='http://brunopereira.org/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Estou indo agora para um novo projeto na <a href="http://www.concretesolutions.com.br" target="_blank">Concrete</a>, atuando na <a href="http://globosat.globo.com/" target="_blank">Globosat</a>. O pouco que sei do projeto até agora me pareceu muito interessante, e essa mudança de cliente é fundamental para as minhas perspectivas dentro da empresa. Torço muito para essa minha nova empreitada seja tão interessante e produtiva como meu período dentro da Globo.com, e claro, espero contribuir bastante para o sucesso da Concrete em um novo cliente e novo projeto.</p>
<p>No final das contas, sinceramente espero que eu tenha contribuído tanto com a Globo.com quanto ela contribuiu para a minha carreira e o meu amadurecimento. Foram 2 anos e meio sensacionais e tenho certeza de que a empresa continuará no seu caminho de enorme sucesso, que pude acompanhar neste período.</p>
<p>Chegou então o momento de dizer Adeus Globo.com, foi um grande prazer para mim!</p>
]]></content:encoded>
			<wfw:commentRss>http://brunopereira.org/2008/11/28/adeus-globocom-foi-um-grande-prazer/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>JSR-311 finally approved!</title>
		<link>http://brunopereira.org/2008/09/24/jsr-311-finally-approved/</link>
		<comments>http://brunopereira.org/2008/09/24/jsr-311-finally-approved/#comments</comments>
		<pubDate>Thu, 25 Sep 2008 02:10:44 +0000</pubDate>
		<dc:creator>blpsilva</dc:creator>
				<category><![CDATA[design]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[java ee]]></category>
		<category><![CDATA[jboss]]></category>
		<category><![CDATA[jboss resteasy]]></category>
		<category><![CDATA[jersey]]></category>
		<category><![CDATA[jsr-311]]></category>
		<category><![CDATA[rest]]></category>

		<guid isPermaLink="false">http://brunopereira.org/?p=214</guid>
		<description><![CDATA[Yesterday the JSR-311 (Java API for RESTFul Web Services &#8211; JAX-RS) was finally approved!
I&#8217;m using Jersey (the JSR&#8217;s reference implementation) for more than 6 months and I was anxious to have the specification approved.
In my team we&#8217;re currently using Jersey 0.7 in production, and were waiting for the JSR to be approved to analyse the [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday the <a href="https://jsr311.dev.java.net/" target="_blank">JSR-311</a> (Java API for RESTFul Web Services &#8211; JAX-RS) was finally <a href="http://jcp.org/en/jsr/results?id=4715" target="_blank">approved</a>!</p>
<p>I&#8217;m using <a href="https://jersey.dev.java.net/" target="_blank">Jersey</a> (the JSR&#8217;s reference implementation) for more than 6 months and I was anxious to have the specification approved.</p>
<p>In my team we&#8217;re currently using Jersey 0.7 in production, and were waiting for the JSR to be approved to analyse the final version of its implementations. Now we&#8217;ll wait for both Jersey and <a href="http://wiki.jboss.org/wiki/RESTeasyJAXRS" target="_blank">JBoss RESTEasy</a> to release their final versions and we&#8217;ll analyse both to see which one we&#8217;ll use in our RESTFul services.</p>
<p>If anyone wants to give me good reasons to use either one of the implementations, now it&#8217;s the perfect time! I&#8217;m hearing&#8230; <img src='http://brunopereira.org/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://brunopereira.org/2008/09/24/jsr-311-finally-approved/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>RESTFul Registry update</title>
		<link>http://brunopereira.org/2008/09/23/restful-registry-update/</link>
		<comments>http://brunopereira.org/2008/09/23/restful-registry-update/#comments</comments>
		<pubDate>Wed, 24 Sep 2008 02:25:54 +0000</pubDate>
		<dc:creator>blpsilva</dc:creator>
				<category><![CDATA[design]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[atom]]></category>
		<category><![CDATA[atompub]]></category>
		<category><![CDATA[dan diephouse]]></category>
		<category><![CDATA[jboss]]></category>
		<category><![CDATA[mule]]></category>
		<category><![CDATA[mule galaxy]]></category>
		<category><![CDATA[mulesource]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[tomcat]]></category>
		<category><![CDATA[wso2]]></category>
		<category><![CDATA[wso2 registry]]></category>

		<guid isPermaLink="false">http://brunopereira.org/?p=212</guid>
		<description><![CDATA[Well, as I said recently, we want to use a registry to keep URIs of our services and also some configurations that are currently in properties files.
After looking better at WSO2 Registry, I figured out how to do what I need with the product. I had a very short time to evaluate properly WSO2 Registry [...]]]></description>
			<content:encoded><![CDATA[<p>Well, as <a href="http://brunopereira.org/2008/09/08/restful-services-registry/" target="_self">I said recently</a>, we want to use a registry to keep URIs of our services and also some configurations that are currently in properties files.</p>
<p>After looking better at <a href="http://wso2.org/projects/registry" target="_blank">WSO2 Registry</a>, I figured out how to do what I need with the product. I had a very short time to evaluate properly WSO2 Registry and <a href="http://www.mulesource.org/display/GALAXY/Home" target="_blank">Mule Galaxy</a> before my last post, but after another evaluation of them, I concluded I can use them in this case.</p>
<p>Last week I developed a Java client to consume my publications from WSO2 Registry. It wasn&#8217;t much fun to develop, because I had to make it compatible with JDK 1.4. This prevented me from using their client API, which runs only on JDK 1.5 and above.</p>
<p>Since I had to use JDK 1.4, I used <a href="http://xstream.codehaus.org/" target="_blank">XStream</a> for my Java &lt;-&gt; XML mappings. Not being able to use the Registry&#8217;s Java client, I also had to consume data from their <a href="http://www.atompub.org/" target="_blank">AtomPub</a> API. I used <a href="http://incubator.apache.org/abdera/" target="_blank">Apache Abdera</a> 0.3 for this task, which was their last version supporting JDK 1.4 (through retroweaver).</p>
<p>So far so good. Last week I had a prototype client consuming stuff from the Registry, so I moved on to some other tasks. Well, today I started integrating the Registry in my application. That meant moving from Tomcat 6 to JBoss 4.0.5. And that&#8217;s when I got in trouble.</p>
<p>Unfortunately I hadn&#8217;t seen <a href="http://wso2.org/wiki/display/registry/Registry+1.1" target="_blank">this page</a> before. It turns out that the only application server they have tested enough is Tomcat. And not any Tomcat, only Tomcat 6. Since their distribution format is a .war file, I never would think they support only Tomcat. In their <a href="http://wso2.org/downloads/registry/" target="_blank">download page</a> it says: <strong>&#8220;This distribution includes the Webapp module with relevant JAR files and other resources to be deployed in the servlet container, providing a Web UI and an APP interface.&#8221;</strong></p>
<p>Well, I&#8217;m probably just dumb. They didn&#8217;t say &#8220;<strong>a servlet container</strong>&#8220;. They said &#8220;<strong>the servlet container</strong>&#8220;. This certainly means &#8220;the servlet container we support, which is Tomcat 6&#8243;. But this is not written there, so dumb people like me will be subject to mistakes.</p>
<p>&#8220;Heck, this is open source, I&#8217;m gonna make it work on JBoss!&#8221;. This was my first thought. And then I started setting up the Registry in JBoss, right after lunch today.</p>
<p>The first thing I noticed is that the Registry packs a newer version (1.2.13) of log4j than the one present in JBoss (1.2.8). This shouldn&#8217;t be a problem, but anyone who has experienced some of the JBoss Classloader Hell knows that it&#8217;s not a wise decision to bring a newer version of log4j inside your application if you&#8217;re going to run on JBoss. This is not a Registry fault, so I gladly fixed the problem by removing the log4j they had packed inside the .war file.</p>
<p>After fixing this, I was gettings errors trying to open the Registry&#8217;s index page on JBoss. I quickly found out that their jsps had scriptlets using JDK 1.5 code, and JBoss was not able to compile the jsps. This was easy to fix by uncommenting a init-param in the web.xml in the Tomcat module inside JBoss. However, the amount of scriplets inside their pages was the first symptom that something didn&#8217;t smell right.</p>
<p>After fixing the jsp problem, I configured the Registry to connect to MySql through a JBoss datasource. I then could open their index page and even use some features. However, when I started checking the server logs I was shocked. A huge amount of errors in jdbc operations. I had no clue of what was going wrong, because the UI was apparently working normally and the database was being manipulated.</p>
<p>Well, since it&#8217;s an open source product, I promptly checked out their code and started looking for problems. Most errors occured in simple jdbc operations like the creation of a prepared statement. The application logs were not very helpful, and I couldn&#8217;t figure out where the problem was.</p>
<p>However, something scared me a lot. Between the zillions of jdbc errors, I saw JBoss screaming for help, saying that the PreparedStatements were left open. I went to look at their jdbc code, and it definitely needs care. There were a LOT of jdbc operations inside <strong>try/catch</strong> blocks, where they treated SQLExceptions. I didn&#8217;t see the <strong>finally</strong> blocks closing the PreparedStatements and the ResultSets. This explains JBoss&#8217;s complaints about the PreparedStatements.</p>
<p>After several hours trying to use WSO2 Registry inside JBoss and looking at their code, I must say I am VERY discouraged to put anything in production right now using the product.</p>
<p>I just downloaded Mule Galaxy and now I&#8217;m gonna try to integrate it in my application. A very good sign is that they say I can use it with ANY servlet container, including Tomcat and Jetty. I think it&#8217;ll be a successful effort, but it&#8217;s hard to say anything after my problems with WSO2 Registry today.</p>
<p>But knowing <a href="http://netzooid.com/blog/" target="_blank">Dan Diephouse</a>&#8217;s work for several years, I&#8217;m pretty confident in this new attempt. I&#8217;ll post the results later this week.</p>
]]></content:encoded>
			<wfw:commentRss>http://brunopereira.org/2008/09/23/restful-registry-update/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>RESTFul services registry</title>
		<link>http://brunopereira.org/2008/09/08/restful-services-registry/</link>
		<comments>http://brunopereira.org/2008/09/08/restful-services-registry/#comments</comments>
		<pubDate>Tue, 09 Sep 2008 01:17:17 +0000</pubDate>
		<dc:creator>blpsilva</dc:creator>
				<category><![CDATA[design]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[ibatis]]></category>
		<category><![CDATA[jdbc]]></category>
		<category><![CDATA[jersey]]></category>
		<category><![CDATA[mule]]></category>
		<category><![CDATA[mule galaxy]]></category>
		<category><![CDATA[registry]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[wadl]]></category>
		<category><![CDATA[wso2]]></category>
		<category><![CDATA[wso2 registry]]></category>

		<guid isPermaLink="false">http://brunopereira.org/?p=193</guid>
		<description><![CDATA[Today my team started a new Sprint, with several very interesting technical stories. We are progressively migrating an architecture that uses EJB 2.1 for client-server communication and also for transaction control. Our new architecture uses RESTFul services (currently with Jersey 0.7) for communication and Spring + Ibatis underneath.
One of the main issues with the old [...]]]></description>
			<content:encoded><![CDATA[<p>Today my team started a new Sprint, with several very interesting technical stories. We are progressively migrating an architecture that uses EJB 2.1 for client-server communication and also for transaction control. Our new architecture uses RESTFul services (currently with <a href="http://jersey.dev.java.net" target="_blank">Jersey</a> 0.7) for communication and <a href="http://www.springframework.org" target="_blank">Spring</a> + <a href="http://ibatis.apache.org/" target="_blank">Ibatis</a> underneath.</p>
<p>One of the main issues with the old architecture is the tight coupling between the server and the clients. The way it was designed, our server platform is limited by the oldest client&#8217;s platform.  To have more flexibility and loose coupling between server and clients, we decided to have an XML contract in the communication.</p>
<p>In this Sprint we must finish the implementation of a Java client to be distributed to the client applications. We have some optimization and refactoring tasks for this Sprint, and one of them includes a RESTFul registry. We don&#8217;t want the clients to have our URIs configured via properties files. This approach limits our flexibility to manage URIs, so a different approach is desirable.</p>
<p>Our client will access a repository to ASK FOR the URI corresponding to a given service AND version. That means: the client willing to access the login service will ask the repository for the URI of this service, in the client&#8217;s version. The client could ask for /repository/login/v2.0 and then receive back the URI http://login.globo.com/login/v2.0.</p>
<p>We could have several different versions of the same services, each of them with different contracts. Introducing the repository as an extra <a href="http://c2.com/cgi/wiki?LayerOfIndirection" target="_blank">layer of indirection</a>, we also have the flexibility to take down several server machines for a while and even update URIs if desired (although that&#8217;s unlikely).</p>
<p>I checked <a href="http://mule.mulesource.org/display/GALAXY/Home" target="_blank">Mule Galaxy</a> and <a href="http://wso2.com/products/registry/" target="_blank">WSO2 Registry</a>, but unfortunately they don&#8217;t give me what I need. They&#8217;re both open source registries, but they index SOAP services and some other things, but not RESTFul URIs. They offer a REST API to interact with their registries (unlike UDDI, which uses SOAP), but don&#8217;t index RESTFul URIs at this moment.</p>
<p>After this analysis of both, i decided to implement my own RESTFul registry. It shouldn&#8217;t be too sofisticated for this first release, but since it&#8217;s a frequent need in my team, I&#8217;m probably going to take some off-time to develop a nice registry that might be useful for a wider range of applications. My goal with this post is to gather some requirements for this registry and also its client. Features that would be useful for other people too.</p>
<p>The initial set of requirements that I wanna deliver in this Sprint is:</p>
<ul>
<li>Must have a RESTFul API to search for services</li>
<li>Should be possible to browse published services with a web browser (even IE, if you call it a browser)</li>
<li>Ajax clients should be able to access the registry easily</li>
<li>Java client must run on JDK 1.4 and above</li>
<li>Java client should require as few libraries as possible</li>
<li>Registry should access the database through a JDBC datasource</li>
<li>Offer an authenticated user interface to publish the services (probably with Java EE authentication)</li>
</ul>
<p>An extra list of desirable features (not for this Sprint) is:</p>
<ul>
<li>Import service URIs from <a href="https://wadl.dev.java.net/" target="_blank">WADL</a> document</li>
<li>Allow database access without a JDBC datasource</li>
<li>Show history of modifications in the registry</li>
<li>Registry should be distributed as .war</li>
<li>Offer other ways of authentication</li>
</ul>
<p>Well, that&#8217;s the first ideas that come to my mind. My intention is to implement a nice registry and offer it for everyone to use it. If you think of some other features that would be nice in the registry, please let me know. The idea of this post is to be an asynchronous brainstorm, so please help! <img src='http://brunopereira.org/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://brunopereira.org/2008/09/08/restful-services-registry/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
	</channel>
</rss>

