<?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>Blog de desenvolvimento da Milfont Consulting, Client e Server-side &#187; JSON</title>
	<atom:link href="http://www.milfont.org/tech/tag/json/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.milfont.org/tech</link>
	<description>Blog da Comunidade Milfont Consulting, uma empresa especializada em desenvolvimento Web, principalmente Javascript, node.js e muito Javascript.</description>
	<lastBuildDate>Thu, 26 Jan 2012 11:30:28 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Extjs e DWR</title>
		<link>http://www.milfont.org/tech/2009/07/02/extjs-e-dwr/</link>
		<comments>http://www.milfont.org/tech/2009/07/02/extjs-e-dwr/#comments</comments>
		<pubDate>Thu, 02 Jul 2009 19:11:42 +0000</pubDate>
		<dc:creator>cmilfont</dc:creator>
				<category><![CDATA[Ajax]]></category>
		<category><![CDATA[DWR]]></category>
		<category><![CDATA[Ext]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Model 3]]></category>
		<category><![CDATA[RIA]]></category>
		<category><![CDATA[web2.0]]></category>
		<category><![CDATA[ExtJS]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://www.milfont.org/tech/?p=705</guid>
		<description><![CDATA[Nesse artigo eu pretendo trabalhar dois conceitos principais de uso do Extjs, extensão/customização de componentes e acesso a dados server-side com base em experiência recente em um projeto que desenvolvemos. Esse projeto em questão é um ERP que tinha a necessidade de manter a usabilidade similar a sua versão antiga, feita em Delphi, para o [...]]]></description>
			<content:encoded><![CDATA[<p>Nesse artigo eu pretendo trabalhar dois conceitos principais de uso do <a href="http://www.milfont.org/tech/tag/extjs/">Extjs</a>, extensão/customização de componentes e acesso a dados server-side com base em experiência recente em um projeto que desenvolvemos. Esse projeto em questão é um ERP que tinha a necessidade de manter a usabilidade similar a sua versão antiga, feita em Delphi, para o desktop.</p>
<p>Para suprir essa necessidade de usabilidade tivemos que adotar alguns conceitos, como ser totalmente stateless e modificar a arquitetura MVC2 para o <a href="http://www.milfont.org/tech/2008/09/08/mvc-model-3-e-camadas/">MVC3</a>. No server-side trabalhamos com um domain model baseado em Hibernate, Spring e Facades e Services com DWR. Nada de frameworks MVC2, não nos preocupamos com renderização e sim com a API. No lado cliente usamos Extjs com algumas modificações que fiz para integrar de forma suave com o DWR.</p>
<p>Primeiro precisamos entender como o Extjs trabalha com herança. Basicamente há um método no objeto Ext que faz esse trabalho de extensão dos componentes, funciona da seguinte maneira:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">//Formato:</span>
<span style="color: #003366; font-weight: bold;">var</span> NovoComponente <span style="color: #339933;">=</span> Ext.<span style="color: #660066;">extend</span><span style="color: #009900;">&#40;</span>velhoComponente<span style="color: #339933;">,</span> <span style="color: #009900;">&#123;</span> 
          <span style="color: #009966; font-style: italic;">/* metodos e propriedades que serão reescritas */</span> 
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">//Exemplo:</span>
<span style="color: #003366; font-weight: bold;">var</span> MilfontGridPanel <span style="color: #339933;">=</span> Ext.<span style="color: #660066;">extend</span><span style="color: #009900;">&#40;</span>Ext.<span style="color: #660066;">grid</span>.<span style="color: #660066;">GridPanel</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #006600; font-style: italic;">//novo construtor</span>
        constructor<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>config<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #006600; font-style: italic;">// Seu preprocessamento vai aqui</span>
        	MilfontGridPanel.<span style="color: #660066;">superclass</span>.<span style="color: #660066;">constructor</span>.<span style="color: #660066;">apply</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">,</span> arguments<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #006600; font-style: italic;">// Seu pos-processamento vai aqui</span>
        <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
&nbsp;
        NovoMethod<span style="color: #339933;">:</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: #006600; font-style: italic;">// algum novo método que você queira criar para o novo componente</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Para esse projeto, criei um Ext.data.DataProxy (<a href="http://www.milfont.org/tech/2009/06/29/introducao-ao-ext/">como visto no artigo passado</a>) especialista para o DWR, criativamente denominado DWRProxy. A idéia é modificar o comportamento de buscar os dados para usar um <a href="http://www.milfont.org/tech/tag/dwr/">Creator do DWR</a>.</p>
<p>Definimos primeiro o objeto e suas propriedades necessárias:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">Ext.<span style="color: #660066;">ux</span>.<span style="color: #660066;">data</span>.<span style="color: #660066;">DWRProxy</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>dwr_facade<span style="color: #339933;">,</span> dwr_filter<span style="color: #339933;">,</span> dwr_errorHandler<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
&nbsp;
    Ext.<span style="color: #660066;">ux</span>.<span style="color: #660066;">data</span>.<span style="color: #660066;">DWRProxy</span>.<span style="color: #660066;">superclass</span>.<span style="color: #660066;">constructor</span>.<span style="color: #660066;">call</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #009966; font-style: italic;">/* Propriedade que receberá a classe Java configurada como Creator */</span>
    <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">data</span> <span style="color: #339933;">=</span> dwr_facade<span style="color: #339933;">;</span>
    <span style="color: #006600; font-style: italic;">/*
	 * Propriedade que receberá uma classe java configurada como converter
	 * que servirá como filtro de busca
	 */</span>
&nbsp;
	<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">dwr_filter</span> <span style="color: #339933;">=</span> dwr_filter<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #006600; font-style: italic;">/**
	 *
	 * Propriedade para fazer paginação, indica que deve cachear a consulta de
	 * total de elementos o controlador [fachada] deve implementar a logica de
	 * negocios adequada, quando for false consulta o total, quando for true
	 * consulta apenas a listagem e repete o total
	 */</span>
&nbsp;
	<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">dwr_total_cache</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">dwr_errorHandler</span> <span style="color: #339933;">=</span> dwr_errorHandler<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Após isso extendemos do Ext.data.DataProxy :</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">Ext.<span style="color: #660066;">extend</span><span style="color: #009900;">&#40;</span>Ext.<span style="color: #660066;">ux</span>.<span style="color: #660066;">data</span>.<span style="color: #660066;">DWRProxy</span><span style="color: #339933;">,</span> Ext.<span style="color: #660066;">data</span>.<span style="color: #660066;">DataProxy</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #006600; font-style: italic;">/**
     * Método Load do Ext.data.DataProxy overrided
     */</span>
&nbsp;
    load <span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>params<span style="color: #339933;">,</span> reader<span style="color: #339933;">,</span> callback<span style="color: #339933;">,</span> scope<span style="color: #339933;">,</span> arg<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #006600; font-style: italic;">/**
	 * Escopo &quot;this&quot; mapeado para a variável &quot;s&quot; porque dentro do callback do
	 * DWR o escopo &quot;this&quot; não pertence ao objeto Ext.ux.data.DWRProxy.
	 */</span>
&nbsp;
	<span style="color: #003366; font-weight: bold;">var</span> s <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">;</span>
&nbsp;
        params <span style="color: #339933;">=</span> params <span style="color: #339933;">||</span> <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>params.<span style="color: #660066;">cache</span> <span style="color: #339933;">!=</span> undefined<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">dwr_total_cache</span> <span style="color: #339933;">=</span> params.<span style="color: #660066;">cache</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>params.<span style="color: #660066;">filter</span> <span style="color: #339933;">!=</span> undefined<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">dwr_filter</span> <span style="color: #339933;">=</span> params.<span style="color: #660066;">filter</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #003366; font-weight: bold;">var</span> result<span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000066; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">data</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">dwr_filter</span><span style="color: #339933;">,</span> params.<span style="color: #660066;">start</span><span style="color: #339933;">,</span> params.<span style="color: #660066;">limit</span><span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">dwr_total_cache</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#123;</span>
			callback<span style="color: #339933;">:</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>response<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                                <span style="color: #006600; font-style: italic;">//aqui passamos o retorno do DWR </span>
                               <span style="color: #006600; font-style: italic;">// que chamei de response,  para o extjs</span>
				result <span style="color: #339933;">=</span> reader.<span style="color: #660066;">readRecords</span><span style="color: #009900;">&#40;</span>response<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				callback.<span style="color: #660066;">call</span><span style="color: #009900;">&#40;</span>scope<span style="color: #339933;">,</span> result<span style="color: #339933;">,</span> arg<span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
			errorHandler<span style="color: #339933;">:</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>a<span style="color: #339933;">,</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
				scope.<span style="color: #660066;">fireEvent</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;loadexception&quot;</span><span style="color: #339933;">,</span> s<span style="color: #339933;">,</span> arg<span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">null</span><span style="color: #339933;">,</span> e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				s.<span style="color: #660066;">dwr_errorHandler</span><span style="color: #009900;">&#40;</span>a<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
			timeout<span style="color: #339933;">:</span><span style="color: #CC0000;">100000</span>
		<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">dwr_total_cache</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">true</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #009900;">&#125;</span> <span style="color: #000066; font-weight: bold;">catch</span><span style="color: #009900;">&#40;</span>e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">fireEvent</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;loadexception&quot;</span><span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">,</span> arg<span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">null</span><span style="color: #339933;">,</span> e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            callback.<span style="color: #660066;">call</span><span style="color: #009900;">&#40;</span>scope<span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">null</span><span style="color: #339933;">,</span> arg<span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000066; font-weight: bold;">return</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>A fachada DWR é uma classe comum, segue um exemplo de uso com Hibernate:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">//classe para satisfazer o transporte para o Extjs</span>
<span style="color: #003366; font-weight: bold;">public</span> final <span style="color: #003366; font-weight: bold;">class</span> DataTransferObject <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">private</span> int total<span style="color: #339933;">;</span>
    <span style="color: #003366; font-weight: bold;">private</span> List<span style="color: #339933;">&lt;?</span> <span style="color: #003366; font-weight: bold;">extends</span> Object<span style="color: #339933;">&gt;</span> results<span style="color: #339933;">;</span>
    <span style="color: #006600; font-style: italic;">//sets e gets</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">public</span> <span style="color: #003366; font-weight: bold;">class</span> AjaxFacade <span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">//injeta um repositorio, whatever</span>
    <span style="color: #003366; font-weight: bold;">private</span> Repository repository <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">null</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #003366; font-weight: bold;">public</span> DataTransferObject find<span style="color: #009900;">&#40;</span>Object filter<span style="color: #339933;">,</span> int start<span style="color: #339933;">,</span> int limit<span style="color: #339933;">,</span> boolean cache<span style="color: #339933;">,</span> HttpSession session<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        DataTransferObject dto <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> DataTransferObject<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #006600; font-style: italic;">//verifica se o Proxy está passando true </span>
        <span style="color: #006600; font-style: italic;">// indicando que está paginando</span>
        <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>cache<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            Integer total <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Integer<span style="color: #009900;">&#41;</span> session.<span style="color: #660066;">getAttribute</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;totalObject&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            dto.<span style="color: #660066;">setTotal</span><span style="color: #009900;">&#40;</span>total<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
       <span style="color: #009900;">&#125;</span> <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
            session.<span style="color: #660066;">removeAttribute</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;totalObject&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            Integer total <span style="color: #339933;">=</span> repository.<span style="color: #660066;">count</span><span style="color: #009900;">&#40;</span>filter<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            dto.<span style="color: #660066;">setTotal</span><span style="color: #009900;">&#40;</span>total<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            session.<span style="color: #660066;">setAttribute</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;totalObject&quot;</span><span style="color: #339933;">,</span> total<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        List<span style="color: #339933;">&lt;</span>Object<span style="color: #339933;">&gt;</span> retorno <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>List<span style="color: #339933;">&lt;</span>Object<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#41;</span> repository.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span>filter<span style="color: #339933;">,</span> start<span style="color: #339933;">,</span> limit<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        dto.<span style="color: #660066;">setResults</span><span style="color: #009900;">&#40;</span>retorno<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">return</span> dto<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span></pre></div></div>

<p>Para o Grid visto no artigo passado, basta instanciar assim no javscript:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> store <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Ext.<span style="color: #660066;">data</span>.<span style="color: #660066;">Store</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
    proxy<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">new</span> Ext.<span style="color: #660066;">ux</span>.<span style="color: #660066;">data</span>.<span style="color: #660066;">DWRProxy</span><span style="color: #009900;">&#40;</span>
        AjaxFacade.<span style="color: #660066;">find</span><span style="color: #339933;">,</span> 
        <span style="color: #009900;">&#123;</span>$dwrClassName<span style="color: #339933;">:</span><span style="color: #3366CC;">&quot;Project&quot;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> 
        errorHandler
    <span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
    reader<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">new</span> Ext.<span style="color: #660066;">data</span>.<span style="color: #660066;">JsonReader</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
            root<span style="color: #339933;">:</span> <span style="color: #3366CC;">'results'</span><span style="color: #339933;">,</span>totalProperty<span style="color: #339933;">:</span> <span style="color: #3366CC;">'total'</span><span style="color: #339933;">,</span>id<span style="color: #339933;">:</span> <span style="color: #3366CC;">'id'</span>
        <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> 
        <span style="color: #009900;">&#91;</span><span style="color: #3366CC;">'id'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'name'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'manager.name'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'manager.address.country'</span><span style="color: #009900;">&#93;</span>
    <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Para entender o<em> {$dwrClassName:&#8221;Project&#8221;}</em> <a href="http://www.milfont.org/tech/2008/12/24/dwr-3-release-candidate-1/">visite esse post</a>.</p>
<p>Dessa forma o DWR se torna um proxy para todos os componentes do Extjs.</p>
<p>Código fonte da modificação do javascript eu <a href="http://github.com/cmilfont/MilfontExtjs/tree/master">coloquei aqui no github</a> e uma <a href="https://github.com/cmilfont/example-dwr-extjs/tree">aplicação demo aqui</a>. No próximo vou integrar o DWR com o Rails, aguardem que sai logo&#8230; ou não.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.milfont.org/tech/2009/07/02/extjs-e-dwr/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Introdução ao DWR</title>
		<link>http://www.milfont.org/tech/2009/03/20/introducao-ao-dwr/</link>
		<comments>http://www.milfont.org/tech/2009/03/20/introducao-ao-dwr/#comments</comments>
		<pubDate>Fri, 20 Mar 2009 10:24:04 +0000</pubDate>
		<dc:creator>cmilfont</dc:creator>
				<category><![CDATA[Ajax]]></category>
		<category><![CDATA[DWR]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[JSON]]></category>

		<guid isPermaLink="false">http://www.milfont.org/tech/?p=23</guid>
		<description><![CDATA[Material básico que eu usava nos cursos em 2007 para configuração do DWR em uma aplicação web em java, principalmente a partir da página 10. O DWR tem uma vantagem, desde 2005 &#8211; em suas primeiras versões &#8211; que praticamente é a mesma configuração, com mudanças poucos significativas. Esse material continua válido em sua plenitude. [...]]]></description>
			<content:encoded><![CDATA[<p>Material básico que eu usava nos cursos em 2007 para configuração do DWR em uma aplicação web em java, principalmente a partir da página 10.</p>
<p>O DWR tem uma vantagem, desde 2005 &#8211; em suas primeiras versões &#8211; que praticamente é a mesma configuração, com mudanças poucos significativas. Esse material continua válido em sua plenitude.</p>
<div id="__ss_1172050" style="width: 425px; text-align: left;"><a style="font:14px Helvetica,Arial,Sans-serif;display:block;margin:12px 0 3px 0;text-decoration:underline;" title="Tw Dwr 2007 Ap01" href="http://www.slideshare.net/cmilfont/tw-dwr-2007-ap01?type=powerpoint">Tw Dwr 2007 Ap01</a><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="425" height="355" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowScriptAccess" value="always" /><param name="src" value="http://static.slideshare.net/swf/ssplayer2.swf?doc=twdwr2007ap01-090319212458-phpapp01&amp;stripped_title=tw-dwr-2007-ap01" /><embed type="application/x-shockwave-flash" width="425" height="355" src="http://static.slideshare.net/swf/ssplayer2.swf?doc=twdwr2007ap01-090319212458-phpapp01&amp;stripped_title=tw-dwr-2007-ap01" allowscriptaccess="always" allowfullscreen="true"></embed></object></p>
<div style="font-size: 11px; font-family: tahoma,arial; height: 26px; padding-top: 2px;">View more <a style="text-decoration:underline;" href="http://www.slideshare.net/">presentations</a> from <a style="text-decoration:underline;" href="http://www.slideshare.net/cmilfont">Christiano Milfont</a>.</div>
</div>
<p><img src="http://www.milfont.org/tech/wp-content/upload/dwrworks.png" alt="" /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.milfont.org/tech/2009/03/20/introducao-ao-dwr/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>DWR 3 Release Candidate 1</title>
		<link>http://www.milfont.org/tech/2008/12/24/dwr-3-release-candidate-1/</link>
		<comments>http://www.milfont.org/tech/2008/12/24/dwr-3-release-candidate-1/#comments</comments>
		<pubDate>Wed, 24 Dec 2008 15:33:43 +0000</pubDate>
		<dc:creator>cmilfont</dc:creator>
				<category><![CDATA[Ajax]]></category>
		<category><![CDATA[DWR]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[Joe Walker]]></category>

		<guid isPermaLink="false">http://www.milfont.org/tech/?p=481</guid>
		<description><![CDATA[Joe Walker anunciou que saiu a RC1 do DWR3 com pequeno atraso com novidades interessantes como suporte a Varargs, Method Overloading, entre outras coisas. Mas destaco algo que deveria ter há tempos e sentíamos falta para construções repetitivas como CRUD (principalmente) que é o que chamou de &#8220;Lightweight typed parameters&#8220;. Até a versão 2 temos [...]]]></description>
			<content:encoded><![CDATA[<p>Joe Walker <a href="http://directwebremoting.org/blog/joe/2008/12/16/dwr_version_3_0_release_candidate_1.html">anunciou</a> que saiu a <a href="http://directwebremoting.org/dwr/download">RC1</a> do <a href="http://directwebremoting.org/dwr">DWR3</a> com <a href="http://www.milfont.org/tech/2008/03/11/dwr-3-em-junho/">pequeno atraso</a> com novidades interessantes como suporte a Varargs, Method Overloading, entre outras coisas. Mas destaco algo que deveria ter há tempos e sentíamos falta para construções repetitivas como CRUD (principalmente) que é o que chamou de &#8220;<strong>Lightweight typed parameters</strong>&#8220;.</p>
<p>Até a versão 2 temos que construir métodos no <a href="http://directwebremoting.org/dwr/server/dwrxml/creators">Creator</a> com implementação nos argumentos devido ao DWR não ter como fazer o binding entre o Javascript e o Java sem saber quem é o objeto. Algo assim:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> AjaxFacade <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> User teste<span style="color: #009900;">&#40;</span>User param<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		param.<span style="color: #006633;">setDescription</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Teste funcionou&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">return</span> param<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>No javascript:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">AjaxFacade.<span style="color: #660066;">teste</span><span style="color: #009900;">&#40;</span>
	<span style="color: #009900;">&#123;</span>
		id<span style="color: #339933;">:</span><span style="color: #CC0000;">42</span> <span style="color: #006600; font-style: italic;">//JSON que representa o objeto User</span>
	<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> 
	<span style="color: #009900;">&#123;</span>
		callback<span style="color: #339933;">:</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>retorno<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span>retorno.<span style="color: #660066;">toSource</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
		errorHandler<span style="color: #339933;">:</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>error<span style="color: #339933;">,</span> message<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span>message<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> 
		timeout<span style="color: #339933;">:</span><span style="color: #CC0000;">5000</span>
	<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Agora foi adicionado a propriedade <strong><em>$dwrClassName</em></strong> no <a href="http://directwebremoting.org/dwr/server/dwrxml/converters">Converter</a> onde você pode trabalhar com a interface ao invés da implementação. Vejamos com o Object como argumento no mesmo método:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> AjaxFacade <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Object</span> teste<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> param<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #666666; font-style: italic;">//puramente ilustrativo não peça fundamentação lógica :)</span>
		<span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>param <span style="color: #000000; font-weight: bold;">instanceof</span> User<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> 
			<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>User<span style="color: #009900;">&#41;</span> param<span style="color: #009900;">&#41;</span>.<span style="color: #006633;">setDescription</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Teste funcionou&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #000000; font-weight: bold;">return</span> param<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>No javascript:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">AjaxFacade.<span style="color: #660066;">teste</span><span style="color: #009900;">&#40;</span>
	<span style="color: #009900;">&#123;</span>
		id<span style="color: #339933;">:</span><span style="color: #CC0000;">42</span> <span style="color: #006600; font-style: italic;">//JSON que representa o objeto User,</span>
		$dwrClassName<span style="color: #339933;">:</span><span style="color: #3366CC;">&quot;User&quot;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> 
	<span style="color: #009900;">&#123;</span>
		callback<span style="color: #339933;">:</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>retorno<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span>retorno.<span style="color: #660066;">toSource</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
		errorHandler<span style="color: #339933;">:</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>error<span style="color: #339933;">,</span> message<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span>message<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> 
		timeout<span style="color: #339933;">:</span><span style="color: #CC0000;">5000</span>
	<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Agora aquelas centenas de classes que fazem a mesma coisa [CRUDzão velho de guerra] podem ser resumidas em uma única Facade que faz suas validações e aciona um Repository ou sua estrutura de persistência.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> AjaxFacade <span style="color: #009900;">&#123;</span>
	@Autowired <span style="color: #003399;">Repository</span> repository<span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Object</span> persistir<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> param<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>param <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> ...
		<span style="color: #006633;">repository</span>.<span style="color: #006633;">persist</span><span style="color: #009900;">&#40;</span>param<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">return</span> param<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Agora não tem como não termos um Feliz Natal!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.milfont.org/tech/2008/12/24/dwr-3-release-candidate-1/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>JSONRequest para evitar o Eval</title>
		<link>http://www.milfont.org/tech/2008/01/04/jsonrequest-para-evitar-o-eval/</link>
		<comments>http://www.milfont.org/tech/2008/01/04/jsonrequest-para-evitar-o-eval/#comments</comments>
		<pubDate>Fri, 04 Jan 2008 12:07:27 +0000</pubDate>
		<dc:creator>cmilfont</dc:creator>
				<category><![CDATA[Ajax]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[XMLHttpRequest]]></category>
		<category><![CDATA[Crockford]]></category>
		<category><![CDATA[Douglas Crockford]]></category>
		<category><![CDATA[JSONRequest]]></category>
		<category><![CDATA[W3C]]></category>
		<category><![CDATA[XHR]]></category>

		<guid isPermaLink="false">http://www.milfont.org/tech/2008/01/04/jsonrequest-para-evitar-o-eval/</guid>
		<description><![CDATA[Em artigo passado, vimos a proposta de Douglas Crockford, denominado de JSON (JavaScript Object Notation) para a troca de dados. Ele propôs também uma especificação para um novo objeto como serviço nativo nos navegadores, JSONRequest, devido a ineficiência do objeto XMLHttpRequest para as novas aplicações nas próximas geração WEB (WEB 2+). Um dos pontos principais [...]]]></description>
			<content:encoded><![CDATA[<p>Em <a href="http://www.milfont.org/tech/2007/11/04/o-que-e-json/">artigo passado</a>, vimos a proposta de Douglas <a href="http://www.crockford.com/">Crockford</a>, denominado de <a href="http://www.json.org/">JSON</a> (JavaScript Object Notation) para a troca de dados. Ele propôs também uma especificação para um novo objeto como serviço nativo nos navegadores, <a href="http://www.json.org/JSONRequest.html">JSONRequest</a>, devido a ineficiência do objeto <a href="http://www.milfont.org/tech/2007/10/03/destilando-o-xmlhttprequest/">XMLHttpRequest</a> para as novas aplicações nas próximas geração WEB (WEB 2+). Um dos pontos principais desse novo objeto é a troca segura de objetos por meio de JSON entre o lado cliente e servidor sem expô-los ao perigo.</p>
<p>A especificação do <a href="http://www.milfont.org/tech/2007/10/03/destilando-o-xmlhttprequest/">XHR</a> define, por medida de segurança, que uma chamada remota só pode ser efetuada ao mesmo caminho de onde o script foi baixado, o JSONRequest resolveria esse problema habilitando o navegador a uma chamada remota a outros servidores diferentes do host original da página, possibilitando a facilidade de acesso a WEB Services REST na camada javascript.</p>
<p>Hoje como alternativa a esse modelo do <a href="http://www.milfont.org/tech/2007/10/03/destilando-o-xmlhttprequest/">XHR</a> temos o <a href="http://www.milfont.org/tech/2007/10/08/script-tag/">Scripttag</a>, dessa forma conseguimos acessar recursos remotos de outros servidores mas com o problema de XSS (cross site scripting). O problema principal do XSS é a injeção de código malicioso pelo parser a partir do método &#8220;Eval&#8221; para processar o código recebido. Vimos uma <a href="http://www.milfont.org/tech/2007/10/02/eval-is-evil/">alternativa de contornar</a> o problema mas mesmo assim não é suficiente. Uma das vantagens principais do JSONRequest seria evitar o XSS.</p>
<p>Esse objeto JSONRequest seria nativo e global, desenhado para ser simples, teria apenas 3 métodos: get, post e cancel.</p>
<p>Existe já plugin para o <a href="http://crypto.stanford.edu/jsonrequest/">Firefox</a>  que habilita o navegador a oferecer nativamente o objeto JSONRequest.</p>
<p>Para todos os navegadores somente com javascript na camada mais alta, para isso existe também o projeto <a href="http://www.devpro.it/JSON/files/JSON-js.html">JSONRequest</a> de <a href="http://www.3site.eu/">Andrea Giammarchi</a>, que criou o objeto em javascript seguindo a especificação. Compatível com os principais navegadores: Opera, IE, Firefox, Safari e konqueror.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
    JSONRequest.<span style="color: #660066;">get</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;processaJSON.jsp&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>sn<span style="color: #339933;">,</span> response<span style="color: #339933;">,</span> exception<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
             <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span>exception <span style="color: #339933;">||</span> response<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>
<span style="color: #009900;">&#125;</span> <span style="color: #000066; font-weight: bold;">catch</span><span style="color: #009900;">&#40;</span>e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
      <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span>e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>O W3C <a href="http://www.w3.org/TR/access-control/">especificou</a> medidas seguras para acesso a recursos web em outro servidores, assim como já existem <a href="http://wiki.mozilla.org/Cross_Site_XMLHttpRequest">movimentos</a> para uma nova especificação do um novo <a href="http://lists.w3.org/Archives/Public/public-webapi/2006Jun/0012">XHR</a>, seria algo como um <a href="http://www.w3.org/2006/webapi/track/products/8">XHR2</a>. A diferença no meu entendimento é que o JSONRequest trata exclusivamente da troca de objetos nativos com base em JSON entre os dois ambientes físicos, enquanto o XHR trata da troca via XML, portanto uma nova especificação do XHR não seria suficiente para substituir a proposta do JSONRequest, a não ser que ele fizesse o parser também de JSON como faz com XML.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.milfont.org/tech/2008/01/04/jsonrequest-para-evitar-o-eval/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>O que é JSON</title>
		<link>http://www.milfont.org/tech/2007/11/04/o-que-e-json/</link>
		<comments>http://www.milfont.org/tech/2007/11/04/o-que-e-json/#comments</comments>
		<pubDate>Sun, 04 Nov 2007 09:21:35 +0000</pubDate>
		<dc:creator>cmilfont</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[Crockford]]></category>
		<category><![CDATA[ECMAScript]]></category>

		<guid isPermaLink="false">http://www.milfont.org/tech/2007/11/04/o-que-e-json/</guid>
		<description><![CDATA[A especificação do &#8220;ECMA Script&#8221; (ECMA262, 3rd Edition, December 1999), que formaliza o Javascript, define na página 2 (4.2) a sentença: &#8220;An ECMAScript object is an unordered collection of properties each with zero or more attributes&#8230;&#8221; Essa definição é o que chamamos de objeto literal, uma coleção não ordenada de propriedades com um ou mais [...]]]></description>
			<content:encoded><![CDATA[<p>A especificação do &#8220;ECMA  Script&#8221; (<a href="http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf">ECMA262</a>, 3rd Edition, December 1999), que formaliza o Javascript, define na página 2 (4.2) a sentença:</p>
<p><cite>&#8220;An ECMAScript object is an unordered collection of properties each with zero or more attributes&#8230;&#8221; </cite></p>
<p>Essa definição é o que chamamos de objeto literal, uma coleção não ordenada de propriedades com um ou mais elementos, onde esses elementos podem ser valores primitivos comuns a todas as linguagens como: inteiro, string ou char; ou outros objetos.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> Produto <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>
	nome<span style="color: #339933;">:</span><span style="color: #3366CC;">&quot;Microprocessador AMD Turion 64&quot;</span><span style="color: #339933;">,</span>
	value<span style="color: #339933;">:</span><span style="color: #CC0000;">150</span><span style="color: #339933;">,</span>
	custo<span style="color: #339933;">:</span><span style="color: #CC0000;">50</span><span style="color: #339933;">,</span>
	getValue<span style="color: #339933;">:</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: #000066; font-weight: bold;">return</span> <span style="color: #009900;">&#40;</span>value <span style="color: #339933;">+</span> custo<span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Douglas <a href="http://www.crockford.com/">Crockford</a>, propôs um  formato de troca de dados simples com base no objeto literal do JavaScript, que denominou de <a href="http://www.json.org/">JSON</a> (JavaScript Object Notation). Esse mecanismo simples é um subconjunto do objeto literal e é facil de qualquer linguagem processar e gerar por ser baseado no formato texto, como linguagem completamente independente que usa conceitos similares às linguagens C-like. Esses motivos tornam o JSON o formato ideal de troca de dados.</p>
<p>JSON é construído com base em uma coleção de pares chave/valor (que definem as propriedades e seus valores), iniciado com &#8220;{&#8221; (chave aberta) e finalizado com &#8220;}&#8221; (chave fechada) . Cada chave é seguida de &#8220;:&#8221; (dois pontos) e os pares são separados por &#8220;,&#8221; (vírgula).</p>
<p><img src="http://json.org/object.gif" alt="objeto json" /></p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> Contato <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #3366CC;">&quot;nome&quot;</span><span style="color: #339933;">:</span><span style="color: #3366CC;">&quot;Christiano Milfont&quot;</span><span style="color: #339933;">,</span>
	<span style="color: #3366CC;">&quot;email&quot;</span><span style="color: #339933;">:</span><span style="color: #3366CC;">&quot;cmilfont@gmail.com&quot;</span><span style="color: #339933;">,</span>
	<span style="color: #3366CC;">&quot;aniversário&quot;</span><span style="color: #339933;">:</span><span style="color: #3366CC;">&quot;28/12/1977&quot;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Um array pode ser usado como valor para uma chave, iniciado por &#8220;[" (colchete aberto) e finalizado por "]&#8221; (colchete fechado). Cada valor do array é separado por &#8220;,&#8221; (vírgula).</p>
<p><img src="http://json.org/array.gif" alt="array json" /></p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> Contato <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #3366CC;">&quot;nome&quot;</span><span style="color: #339933;">:</span><span style="color: #3366CC;">&quot;Christiano Milfont&quot;</span><span style="color: #339933;">,</span>
	<span style="color: #3366CC;">&quot;telefones&quot;</span><span style="color: #339933;">:</span><span style="color: #009900;">&#91;</span>
		<span style="color: #3366CC;">'91942365'</span><span style="color: #339933;">,</span>
		<span style="color: #3366CC;">'88293759'</span>
	<span style="color: #009900;">&#93;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Um valor pode ser uma String em aspas duplas (em javascript o valor pode ser aspa simples, é preferível que o parser resolva as duas formas, apesar de que em linguagens como java as aspas simples representam um char), ou um número, ou um booleano, ou um null, ou um outro objeto ou um array.</p>
<p><img src="http://json.org/value.gif" alt="valores json" /></p>
<p>No caso do objeto e do array, essas estrutura podem ser aninhadas.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> Contato <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #3366CC;">&quot;nome&quot;</span><span style="color: #339933;">:</span><span style="color: #3366CC;">&quot;Christiano Milfont&quot;</span><span style="color: #339933;">,</span>
	<span style="color: #3366CC;">&quot;endereco&quot;</span><span style="color: #339933;">:</span><span style="color: #009900;">&#123;</span>
		<span style="color: #3366CC;">&quot;rua&quot;</span><span style="color: #339933;">:</span><span style="color: #3366CC;">&quot;Eurico Medina&quot;</span><span style="color: #339933;">,</span>
		<span style="color: #3366CC;">&quot;numero&quot;</span><span style="color: #339933;">:</span><span style="color: #CC0000;">185</span><span style="color: #339933;">,</span>
		<span style="color: #3366CC;">&quot;mapa&quot;</span><span style="color: #339933;">:</span><span style="color: #009900;">&#123;</span>
			<span style="color: #3366CC;">&quot;latitude&quot;</span><span style="color: #339933;">:</span><span style="color: #3366CC;">&quot;&quot;</span><span style="color: #339933;">,</span>
			<span style="color: #3366CC;">&quot;longitude&quot;</span><span style="color: #339933;">:</span><span style="color: #3366CC;">&quot;&quot;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
	<span style="color: #3366CC;">&quot;telefones&quot;</span><span style="color: #339933;">:</span><span style="color: #009900;">&#91;</span>
		<span style="color: #3366CC;">'91942365'</span><span style="color: #339933;">,</span>
		<span style="color: #3366CC;">'88293759'</span>
	<span style="color: #009900;">&#93;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>String é uma coleção de zero ou mais caracteres <a href="http://pt.wikipedia.org/wiki/Unicode">Unicode</a>, onde a barra invertida pode ser usada para passar caracteres especais como quebra de linha, tab, entre outros. Números podem ser inteiros ou reais, menos hexadecimal ou octal.</p>
<p>Existem códigos de processamento JSON prontos em dezenas de linguagens, praticamente em todas as linguagens modernas voce encontra no <a href="http://www.json.org/">site do projeto</a>.</p>
<p>A vantagem do JSON sobre o XML como formato de troca de dados é a diminuição do tamanho da resposta, facilidade de entendimento para o programador (já que o código é similiar a linguagem que você usa), e principalmente, no caso de javascript, o parser facilitado porque é baseado em sua especificação de objeto.</p>
<p>Código de retorno do Flickr em <a href="http://www.flickr.com/services/rest/?method=flickr.test.echo&amp;format=soap2&amp;foo=bar&amp;api_key=08d9221b2468be6ccfe5bc229db50181">XML</a> e <a href="http://www.flickr.com/services/rest/?method=flickr.test.echo&amp;format=json&amp;api_key=08d9221b2468be6ccfe5bc229db50181">JSON</a> respectivamente:</p>
<p>&lt;?xml version=&#8221;1.0&#8243; encoding=&#8221;utf-8&#8243; ?&gt;<br />
&lt;s:Envelope xmlns:s=&#8221;http://www.w3.org/2003/05/soap-envelope&#8221;&gt;<br />
&lt;s:Body&gt;<br />
&lt;FlickrResponse xmlns=&#8221;http://flickr.com/ns/api#&#8221;&gt;<br />
&lt;method&gt;flickr.test.echo&lt;/method&gt;<br />
&lt;format&gt;soap2&lt;/format&gt;<br />
&lt;foo&gt;bar&lt;/foo&gt;<br />
&lt;api_key&gt;08d9221b2468be6ccfe5bc229db50181&lt;/api_key&gt;<br />
&lt;/FlickrResponse&gt;<br />
&lt;/s:Body&gt;<br />
&lt;/s:Envelope&gt;</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">&nbsp;
jsonFlickrApi<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
	<span style="color: #3366CC;">&quot;method&quot;</span><span style="color: #339933;">:</span><span style="color: #009900;">&#123;</span>
		<span style="color: #3366CC;">&quot;_content&quot;</span><span style="color: #339933;">:</span><span style="color: #3366CC;">&quot;flickr.test.echo&quot;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
	<span style="color: #3366CC;">&quot;format&quot;</span><span style="color: #339933;">:</span><span style="color: #009900;">&#123;</span>
		<span style="color: #3366CC;">&quot;_content&quot;</span><span style="color: #339933;">:</span><span style="color: #3366CC;">&quot;json&quot;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
	<span style="color: #3366CC;">&quot;api_key&quot;</span><span style="color: #339933;">:</span><span style="color: #009900;">&#123;</span>
		<span style="color: #3366CC;">&quot;_content&quot;</span><span style="color: #339933;">:</span><span style="color: #3366CC;">&quot;08d9221b2468be6ccfe5bc229db50181&quot;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
	<span style="color: #3366CC;">&quot;stat&quot;</span><span style="color: #339933;">:</span><span style="color: #3366CC;">&quot;ok&quot;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span></pre></div></div>

<p>Dessa forma você pode usar as estratégias de &#8220;<a href="http://www.milfont.org/tech/2007/10/02/eval-is-evil/">Eval</a>&#8221;  ou &#8220;<a href="http://www.milfont.org/tech/2007/10/08/script-tag/">Scripttag</a>&#8221; para processar o JSON de forma transparente em sua aplicação AJAX. Usado como configuração em aplicações no lado servidor, você pode construir uma arquitetura com base em interfaces para validar os dados, assim como validaria usando schemas no XML.</p>
<p>A maioria das APIs  de web services dos principais Players no mercado WEB, passaram a oferecer o JSON como alternativa ao XML pela facilidade de interpretação para a arquitetura REST. <a href="http://developer.yahoo.com/common/json.html">Yahoo</a> e <a href="http://code.google.com/apis/gdata/json.html">Google</a> são os principais expoentes desse mecanismo.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.milfont.org/tech/2007/11/04/o-que-e-json/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

