RSS .92| RSS 2.0| ATOM 0.3
  • Home
  • Artigos
  • Publicações
  • Apresentações
  • Interviews
  • Livros
  • Contact
  • About
  •  

    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)

    RESTFul services registry

    September 8th, 2008

    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 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’s platform.  To have more flexibility and loose coupling between server and clients, we decided to have an XML contract in the communication.

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

    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’s version. The client could ask for /repository/login/v2.0 and then receive back the URI http://login.globo.com/login/v2.0.

    We could have several different versions of the same services, each of them with different contracts. Introducing the repository as an extra layer of indirection, we also have the flexibility to take down several server machines for a while and even update URIs if desired (although that’s unlikely).

    I checked Mule Galaxy and WSO2 Registry, but unfortunately they don’t give me what I need. They’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’t index RESTFul URIs at this moment.

    After this analysis of both, i decided to implement my own RESTFul registry. It shouldn’t be too sofisticated for this first release, but since it’s a frequent need in my team, I’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.

    The initial set of requirements that I wanna deliver in this Sprint is:

    • Must have a RESTFul API to search for services
    • Should be possible to browse published services with a web browser (even IE, if you call it a browser)
    • Ajax clients should be able to access the registry easily
    • Java client must run on JDK 1.4 and above
    • Java client should require as few libraries as possible
    • Registry should access the database through a JDBC datasource
    • Offer an authenticated user interface to publish the services (probably with Java EE authentication)

    An extra list of desirable features (not for this Sprint) is:

    • Import service URIs from WADL document
    • Allow database access without a JDBC datasource
    • Show history of modifications in the registry
    • Registry should be distributed as .war
    • Offer other ways of authentication

    Well, that’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! :)


    Mais um projeto em produção, mais lições aprendidas

    August 19th, 2008

    Minha primeira semana após as férias foi do jeito ideal para recuperar o ritmo de trabalho: cheia de emoções :)

    Com subidas para produção durante o dia e longas noites de preparação para o fim de semana, consegui rapidamente trocar na minha cabeça o contexto das férias para a rotina de trabalho. No sábado às 23:30 cheguei à empresa para começar a janela de subida do novo e-mail da Globo.com. Fui sair de lá só no domingo ao meio-dia, mas foi uma janela bem sucedida e sem sustos, embora bem trabalhosa.

    Este projeto se alongou bastante muito mais por questões comerciais do que questões técnicas, e foi ótimo finalmente colocá-lo no ar.

    O projeto de migração de e-mail foi provavelmente o mais crítico que já trabalhei, pois estávamos lidando com uma grande massa de usuários e uma gigantesca massa de e-mails, o que trouxe alguns desafios interessantes. A parte do projeto que era a minha principal responsabilidade era a integração das nossas aplicações com os serviços do novo provedor de e-mails.

    Nesta integração, usamos REST na comunicação entre aplicações desenvolvidas por nós e também para comunicação entre a Globo.com e o novo provedor de e-mail. Todos gostamos bastante dos resultados dessa forma de comunicação e cada vez mais nossas aplicações estão seguindo por esse caminho. Por questões de priorização do Product Owner, é claro que as melhorias técnicas muitas vezes têm que ser adiadas, mas estamos progressivamente refinando nossa arquitetura e usando cada vez menos as comunicações EJB legadas e cada vez mais os serviços REST.

    Bom, entre as lições aprendidas neste projeto, está a de desconfiar de todos os componentes, e tratar minuciosamente de possíveis situações de contingência, até as que pareciam improváveis. Vou confessar que fomos um pouco ingênuos em alguns aspectos. Devido ao enorme gabarito da empresa com a qual estávamos nos integrando, tínhamos aquela idéia de que os servidores deles seriam “quase invulneráveis” e que a API deles seria infalível.

    Bom, continuo tendo um enorme respeito pela empresa, mas vi que eles também falham, e não é tão pouco como pensávamos. Alguns tratamentos de contingência que fizemos tiveram que ser revistos e acabamos aprendendo bastante com esse processo.

    Foi interessante que no domingo depois termos colocado a aplicação no ar eu li um post do Dan Pritchett sobre disponibilidade de 99,999%. Talvez se eu tivesse lido esse post uns 6 meses atrás eu acabaria só lendo rapidamente sem tanta atenção. Mas como vivenciei bem algumas questões que ele levantou, isso acabou realimentando um pouco as minhas idéias sobre o assunto.

    Bom, para quem já está usando o novo e-mail da Globo, espero que a experiência esteja sendo a melhor possível. Para mim esta virada foi uma experiência muito proveitosa e torço para que venham mais e mais projetos desafiadores como esse.


    Projetando APIs e protocolos

    June 14th, 2008

    O Bill de hÓra publicou um post sobre um assunto que me interessa enormemente. Ele comentou sobre a dificuldade de se projetar boas APIs e protocolos.

    Para quem não o conhece, o Bill de hÓra foi o co-editor da RFC do AtomPub, o protocolo de publicação do formato Atom. No post ele comentou sobre a dificuldade de elaborar um bom protocolo de comunicação (no caso o AtomPub). O trabalho demorou mais de 2 anos para ser concluído, e neste 2 anos não contam o tempo no qual o Joe Gregorio (o outro editor da RFC) já estava trabalhando no protocolo antes.

    Uma observação que ele faz é que é difícil encontrar indivíduos capazes de projetar boas APIs, e bem mais difícil é encontrar indivíduos capazes de projetar bons protocolos de comunicação. Algumas pessoas dizem que essas habilidades (projetar APIs e projetar protocolos) são de certa forma opostas, o que implica que seria especialmente difícil encontrar pessoas com habilidade nas 2 coisas.

    Ler esse post foi motivante e inspirador para mim.  Neste exato momento eu estou fazendo as duas coisas simultaneamente. Meu time é responsável pelo sistema de cadastro de usuários e autenticação da Globo.com, entre outras coisas. Esse sistema é provavelmente o que possui mais clientes internos na empresa. A implementação original utilizava EJBs para comunicação remota entre clientes e o servidor, e permitia apenas clientes Java.

    Estamos progressivamente saindo dessa estrutura. Estamos implementando novas interfaces e clientes que usam serviços REST na comunicação, em vez dos EJBs. Isto está sendo feito de forma progressiva porque nenhum Product Owner daria alto valor de negócio para uma migração dessas, exceto em situações extremas (que não são nosso caso).

    Pois bem, nesta migração eu estou atuando nas 2 frentes que o Bill de hÓra classificou como desafiadoras. Estamos modelando os serviços REST e o novo protocolo de comunicação. E estamos também implementando uma API Java para realizar as operações através deste novo protocolo.

    Sem dúvida esta migração é desafiadora. De fato não é fácil elaborar um bom protocolo e uma boa API. Porém, isto também motiva demais. Quem acompanha o meu blog já sabe do meu apreço por serviços REST. Assim, este trabalho atual tem sido ótimo para conseguir explorar inúmeras situações envolvidas neste tipo de comunicação.

    Para minha sorte, pude contar com alguns pontos facilitadores. Na elaboração do protocolo, o conhecimento do AtomPub ajuda muito. Eu já conheço bem esse protocolo e tinha desenvolvido serviços REST em alguns projetos, então essa parte da empreitada ficou muito facilitada.

    Além disso, o conhecimento da API Java anterior do projeto traz várias idéias que podemos explorar. Algumas decisões na API anterior foram muito boas, e outras trouxeram alguns problemas. Eu não participei da implementação original do projeto (isso foi em 2004), mas após trabalhar no projeto por bastante tempo, consegui vivenciar bem os problemas dela. O principal era o alto acoplamento entre o servidor e os clientes, então isso é o principal ganho que pretendemos ter com essa nova implementação baseada em REST.

    O outro ponto facilitador é estar no mesmo time que o Silvano, certamente um dos melhores caras que já conheci tecnicamente. Nós temos visões complementares sobre a arquitetura e a implementação. As idéias que colocamos na prática após as freqüentes discussões são muito superiores às que eu ou ele seríamos capazes de desenvolver individualmente. Com a liberdade de decisões técnicas que temos na Globo (principalmente após a adoção do Scrum), conseguimos evoluir nossas aplicações progressivamente, sempre avaliando pontos positivos e negativos das decisões anteriores.

    Após ler esse post do Bill, tive uma dimensão melhor da grandeza do desafio que estamos tendo agora. Isto traz ainda mais motivação, e não abala a confiança. Tenho a mesma sensação que Isaac Newton teve ao dizer que “se ele pôde enxergar mais longe foi porque se apoiou nos ombros de gigantes”.

    Quando estamos trabalhando freqüentemente com padrões e tecnologias abertas, temos sempre essa vantagem. Viver no mundo open source é se apoiar sempre nos ombros de gigantes, e então qualquer desafio fica muito mais suave e a nossa confiança aumenta. É por isso que eu amo o que faço ;)


    Bruno Pereira is Digg proof thanks to caching by WP Super Cache!