RSS .92| RSS 2.0| ATOM 0.3
  • Home
  • Artigos
  • Publicações
  • Apresentações
  • Interviews
  • Livros
  • Contact
  • About
  • Hypermedia as the engine of application state

    April 5th, 2009

    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.

    Para quem tiver interesse no assunto, recomendo demais a leitura dessa thread. A discussão é de altíssimo nível, e certamente pode trazer várias idéias bacanas.


    I’m a SlideShare RockStar!

    April 1st, 2009

    Recebi hoje de manhã um e-mail do SlideShare me falando que eu sou um RockStar! :)

    “Hi blpsilva,

    We’ve noticed that your slideshow on SlideShare has been getting a LOT of views in the last 24 hours. Great job … you must be doing something right. ;-)

    Why don’t you tweet or blog this? Use the hashtag #bestofslideshare so we can track the conversation.”

    A única apresentação que coloquei até hoje foi a de Web Service REST, logo após o aniversário do CEJUG ano passado. 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’m doing something right :)

    Preciso em algum momento preparar mesmo um curso de Web Services, incluindo REST e WS-*, já que o interesse nisso parece grande, e eu venho acumulando muita experiência nessa área.

    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.

    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 :)


    Migrando para REST: exposição de Recursos x exposição do domínio

    March 22nd, 2009

    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 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.

    O exemplo que vou descrever aqui é o do Comando CmdFinalizaCompra. Este Comando é 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 (”FazerEstaOperacao”), e o pessoal estava em dúvida sobre como redesenhar este modelo e colocá-lo num desenho declarativo, à maneira RESTFul.

    Vou mencionar resumidamente a estrutura de comunicação dos comandos do ISP para que o resto da discussão fique claro. Cada Comando é constituído de 2 classes Java. CmdNomeComando e CmdNomeComandoSrv. A primeira classe corresponde ao Comando do lado do cliente, e a segunda corresponde ao Comando do lado do servidor.

    Na execução do comando, o cliente invoca um EJB 2.1 stateless no servidor, e envia a classe CmdNomeComando 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.

    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.

    Podemos ver a classe CmdNomeComando como o “parâmetro de entrada” da operação, e a classe CmdNomeComandoSrv 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.

    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 possibilidade de desenho definiria como recursos: Assinante, Usuario, Produto, Promocao e Desconto. Isto seria mapeável diretamente na implementação do domínio deles. O que vocês acham disso?

    Bom, não vejo nada errado em expor um recurso Assinante, outro Usuario, etc. Isto pode fazer sentido para outras “operações”, maravilha. Entretanto, para este caso isso levantou a seguinte dúvida para eles: “Eu vou ter que fazer vários POSTs para realizar a operação do CmdFinalizaCompra” ?

    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 Orquestração, 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 Proxy Service invocando alguns Business Services. Algum de vocês se sente tentado a usar esta abordagem? Eu não!

    O que eu sugiro neste exemplo é a criação de um recurso chamado Compra, 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.

    Na implementação do servidor, eu vejo somente este POST sendo realizado. O cliente não precisa saber (e é melhor que não saiba) como é implementado o domínio no servidor. Ele precisa conhecer os recursos expostos, e como interagir com eles.

    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.

    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.

    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.


    JSR-311 finally approved!

    September 24th, 2008

    Yesterday the JSR-311 (Java API for RESTFul Web Services - JAX-RS) was finally approved!

    I’m using Jersey (the JSR’s reference implementation) for more than 6 months and I was anxious to have the specification approved.

    In my team we’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’ll wait for both Jersey and JBoss RESTEasy to release their final versions and we’ll analyse both to see which one we’ll use in our RESTFul services.

    If anyone wants to give me good reasons to use either one of the implementations, now it’s the perfect time! I’m hearing… :)


    WSO2 Registry now working in JBoss 4.0.5

    September 24th, 2008

    After some extra effort today, I did manage to get WSO2 Registry working in JBoss 4.0.5

    The huge amount of jdbc error messages in the server logs were not actually errors. JBoss datasources have a configuration element called <track-statements>. When this option is turned on, JBoss logs massively when there are Statements or ResultSets that are left open. The application server closes the Statements and the ResultSets, and shows many many logs indicating this. The log messages I was seeing were not errors in the Registry, they were only JBoss warnings.

    All our datasources in my team have this option turned on, and we always take care to close the ResultSets and Statements in all our applications. But since the server closes the ResultSets and Statements, I can live with the way the Registry does :)

    I had to do some things to get the Registry working in JBoss. First, I had to remove the log4j the Registry had packed inside its war file. Our JBoss servers use the Unified Classloader, for several years already. This setup was there before I even joined the company, and it’d complicated to change this now, because it’d make us modify several applications. Not being able to change the Classloader, the log4j packed inside the Registry (1.2.13) would conflict with the one present in JBoss itself (1.2.8), so I had to remove it from the Registry’s war. The application worked just fine using log4j 1.2.8, so it’s ok to do this.

    After fixing this, I had to enable Java 1.5 code in the jsps. JBoss by default does not allow Java 1.5 code in the jsps, and to modify this, I had to uncomment the code below inside JBOSS_HOME/server/default/deploy/jbossweb-tomcat55.sar/conf/web.xml:

    <init-param>
    <param-name>compilerSourceVM</param-name>
    <param-value>1.5</param-value>
    </init-param>

    This init-param belongs to <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>, and solves the jsp compilation problem.

    Well, that’s what I had to do to make WSO2 Registry work in JBoss. Most of the problems I faced were not Registry’s fault, so I’m sorry for having a wrong impression after some setup problems this week.

    I’m currently integrating WSO2 Registry in our architecture and once I finish, I’ll document our architecture here, so that other people can see what uses we’re making of the product.


    RESTFul Registry update

    September 23rd, 2008

    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 and Mule Galaxy before my last post, but after another evaluation of them, I concluded I can use them in this case.

    Last week I developed a Java client to consume my publications from WSO2 Registry. It wasn’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.

    Since I had to use JDK 1.4, I used XStream for my Java <-> XML mappings. Not being able to use the Registry’s Java client, I also had to consume data from their AtomPub API. I used Apache Abdera 0.3 for this task, which was their last version supporting JDK 1.4 (through retroweaver).

    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’s when I got in trouble.

    Unfortunately I hadn’t seen this page 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 download page it says: “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.”

    Well, I’m probably just dumb. They didn’t say “a servlet container“. They said “the servlet container“. This certainly means “the servlet container we support, which is Tomcat 6″. But this is not written there, so dumb people like me will be subject to mistakes.

    “Heck, this is open source, I’m gonna make it work on JBoss!”. This was my first thought. And then I started setting up the Registry in JBoss, right after lunch today.

    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’t be a problem, but anyone who has experienced some of the JBoss Classloader Hell knows that it’s not a wise decision to bring a newer version of log4j inside your application if you’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.

    After fixing this, I was gettings errors trying to open the Registry’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’t smell right.

    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.

    Well, since it’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’t figure out where the problem was.

    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 try/catch blocks, where they treated SQLExceptions. I didn’t see the finally blocks closing the PreparedStatements and the ResultSets. This explains JBoss’s complaints about the PreparedStatements.

    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.

    I just downloaded Mule Galaxy and now I’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’ll be a successful effort, but it’s hard to say anything after my problems with WSO2 Registry today.

    But knowing Dan Diephouse’s work for several years, I’m pretty confident in this new attempt. I’ll post the results later this week.


    Vídeos e slides da palestra de REST em Fortaleza

    September 21st, 2008

    Foram publicados os vídeos da minha palestra de REST no aniversário do CEJUG, no dia 16/09/2008. Eu os coloquei embutidos abaixo para facilitar a visualização por parte dos interessados.

    Deixo enormes agradecimentos ao René por ter filmado e pelo esforço heróico de publicar todos esses vídeos no Youtube, para que todos tivessem acesso.

    Como ainda sou um palestrante amador, todo feedback será bem-vindo, para me ajudar a progredir aos poucos. :)

    Web Services Rest

    View SlideShare presentation or Upload your own. (tags: rest)

  • rheumatoid arthritis medications
  • medicine for pets
  • natural treatments for insomnia
  • sleep disorder treatment
  • anti vomiting
  • blood sugars
  • generic reglan
  • pharmacy no prescription
  • drugs for sale
  • muscles human body
  • anabolic creatine
  • online diet meds
  • acne cure pills
  • cialis benefits
  • metronidazole dose
  • women body building
  • otc claritin
  • cetirizine drug
  • cialis 5mg
  • baby acne
  • lipitor use
  • throat gonorrhea
  • cheap phentermine without a prescription
  • how does viagra work?
  • valium high
  • chest pain symptoms
  • prescription drug store online
  • cheap pain meds
  • acne face medication
  • pet health websites
  • anxiety order
  • what is premature ejaculation
  • dog skin
  • hair loss drug
  • online paxil
  • coupon zantac
  • effects of folic acid
  • buy canada drugs
  • curing premature ejaculation
  • carisoprodol cheapest
  • side effects of cancer treatments
  • women heart attack
  • lowest price generic viagra
  • pet supplies plus
  • vitamin supplement ratings
  • diabetes treatment
  • zoloft discount
  • coupon claritin
  • women insomnia
  • buy aciphex
  • cialis on line
  • treatment for hepatitis b
  • order metformin online
  • cialis cheap cialis online
  • claritin allergies
  • mexico pharmacies
  • how to lower blood pressure
  • diclofenac tablet
  • ordering medications online
  • cancer drugs
  • diflucan purchase
  • how to get birth control
  • dog skin infection
  • lowering blood pressure naturally
  • clonazepam pharma
  • health products women
  • buy cialis
  • soma or valium
  • pre diabetes
  • side effects blood pressure tablets
  • discount pain relief
  • dog med
  • osteoporosis calcium drug
  • tramadol without a prescription
  • zoloft drug
  • treatment high blood pressure
  • sildenafil 100mg
  • discount herbals and vitamins
  • aricept generic
  • asthma information
  • bupropion anxiety
  • free acai
  • top hair loss
  • yeast diflucan
  • health care for dogs
  • green tea products
  • cheapest place to buy phentermine
  • canada pharmacy drug perscription
  • high cholesterol treatment
  • viagra free trial
  • cancer cure
  • treatment to stop smoking
  • arthritis pain medicine
  • buy vardenafil online
  • generic viagra generic
  • vitamin list
  • discount soma online
  • facial skin care products
  • buy vitamin supplement
  • cialis alternative
  • viagra for cheap
  • sildenafil
  • online diet drugs
  • online drug
  • benicar tablets
  • purchase medicine on line
  • what is ambien
  • online prescription drug
  • hair loss disease
  • medicine that prevents blood clots
  • antifungal drug
  • medicine for vomiting
  • how to take a beta-blocker
  • san diego soma
  • vascular edema
  • acne skin care treatment products
  • how does viagra work?
  • reduce blood pressure
  • phentermine with no prescription
  • chlamydia treatment online
  • buy levitra on-line
  • beta blocker uses
  • viagra fedex
  • giving cats pills
  • menopause natural treatment
  • oral fluconazole
  • stop smoking today
  • prescription pain medicines
  • menopause natural treatment
  • fda avandia
  • actonel dosage
  • haldol medication
  • how to burn fat
  • all natural antibiotics
  • healthy dog food recipe
  • reduce swelling methods
  • prescription drugs on line
  • drugs use in arthritis
  • weight loss meds on line
  • cheap weight loss
  • pain in chest
  • chlamydia treatment
  • acai cleanse
  • online pharmacies with no prescription needed
  • cancer medications
  • clomid dosage
  • generic pravachol
  • what pills look like phentermine
  • dosage of viagra
  • how to prevent pregnancy
  • treatment for cancer
  • buy generic cialis
  • when is viagra needed
  • no hangover
  • water pills
  • what is generic viagra
  • antianxiety
  • buy asthma meds
  • acyclovir information
  • bronchitis pregnancy
  • treatment for alzheimer's disease
  • medicine chlamydia
  • mail order medicine
  • new treatments for lung diseases
  • cheap pain pills
  • constipation large stool
  • hand pain
  • stopping hair loss
  • antibiotics diarrhea
  • medication without prescription
  • help for infertility
  • weight loss diet
  • body building diets
  • atenolol interaction
  • medical heart failure
  • small dog products
  • stress pills
  • singulair generic
  • what is heart failure
  • new diet pills
  • discount viagra generic
  • order alli
  • treatment for infant diarrhea
  • buy prescription medication online
  • insomnia disorders
  • medical treatments for acne
  • skin disorders in cats
  • zantac medication
  • antibiotics bactrim
  • high blood calcium levels
  • vitamin supplement store
  • jelly kamagra
  • stress drug
  • health products for men
  • health supplement woman
  • us online pharmacy
  • energy saving products
  • about zocor
  • high amount of acid in blood
  • malaria medicines
  • Bruno Pereira is Digg proof thanks to caching by WP Super Cache!