Tuesday, November 25, 2014

Java 7 resources management

 Did you know that there is a really better way to close resources in Java 7? Yes, before Java 7, you should always explicity close connections, files, datasources or others resources after using them.

This used to be done like this:

     FileOutputStream fos = null;  
     try {  
       fos = new FileOutputStream("test.txt");  
       // do something cool with fos  
     } catch (FileNotFoundException e) {  
       // catch code  
     } catch (IOException e) {  
       // catch code  
     } finally {  
       try {  
         fos.close();  
       } catch (Exception ex) {  
         // log the exception  
       }  
     }  


Now, if you are using Java 7, you just would have to write this code:
  
  try (FileOutputStream fos = new FileOutputStream("test.txt")) {  
     // do something cool with fos  
  } catch (FileNotFoundException e) {  
     e.printStackTrace();  
  } catch (IOException e) {  
     e.printStackTrace();  
  }  


Realize that the recource declaration have to be written on the new try() and that you have to use a resource that implements java.lang.AutoClosable interface.

Best regards!

Tuesday, August 13, 2013

Integration tests with Selenium

Recently, I've been trying to figure out how to improve the quality of my projects decreasing its bug amount. I know that for most of us programmers, the first think that came in mind is unit tests with JUnit. I agree that they are necessary. No doubt that we can get a lot of benefits testing the application business logic, however we do know that implement these kind of tests nowadays on JEE platform is increasingly difficult. This happens not only because of environment dependent JEE features(JPA, CDI, EJBs) but also because of the huge amount of bad coding projects we face every day.

I do agree unit testing still gonna be the most efficient way to garantee the correctness of our algorithms, but to reach this out we have to write test driven programs, decoupling business and infrastructure layers or using some refactoring technics when talking about legacy systems.

Having this scenario in mind, integration tests became even more important in JEE projects. With this kind of tests we can ensure the entire application life cycle of each request the user may dispatch on a real runnable environment without necessity of mocks.

One really nice free tool that can be used to implement automatic integrated tests is Selenium. This tool is capable of automate web browsers interactions. The solutions is composed by Selenium IDE and Selenium Web Browser.

Selenium IDE is is a Firefox plugin where you can not only record browser interactions in order to create tests scripts but also run these scripts.

Selenium Web Driver is a collection of language specific bindings that can be used through an API to run tests scripts with a unit test program. In java we are talking about JUnit test classes that can ben automatic exported from the Selenium IDE original scripts.

At http://docs.seleniumhq.org/ you can find all resources you need to start creating your own integration tests.

Thursday, February 28, 2013

Testing Java Applications with Arquilian

For quite some time i want to try Arquilian test framework. 

Arquilian is a Commutity JBoss Open Source project that intend to make it easy to create a Java web application where tests can be naturally created during all the programming life cycle.

One of the things that makes programmers avoid testing nowadays is the fact that java web applications are writen using several resources offered by the application containers like Data Sources for persistence, Context and Dependence Inversion, Transaction mechanisms and so on.

Now you can avoid the use of mocks and test your applications with the real resources implementations offered by application servers in a easy way.

I tested and worked like a charm.

I started reading and implementing the steps of this guide to create the project structure with the necessary dependencies. This could be done with JBoss Forge, but i choose Maven and it was very simple. By the end of this guide, i could get my first green-bar testing a simple CDI Bean.

On the second guide, i could see Arquilian using a remote JBoss AS 7 to run and debug my tests.

And finally, on the third guide  i followed the steps to test an application using JPA to store and retrieve some data from database.



Tuesday, January 22, 2013

Falácias da Computação Distribuída

Atualmente, nosso maior desafio enquanto desenvolvedores de software não é Java, JEE, .Net., JavaScript, HTML5, JBoss Seam, NoSql etc.
   Desenvolver software capaz de realizar transações ACID(atômicas, consistentes, isoladas e duráveis) em ambientes com dezenas de acessos simultâneos já permite que alguns problemas complexos da computação sejam para nós percebidos.
   E isto torna-se muito mais impactante em programas executados em vários servidores de aplicação em cluster.
   Ou seja, nosso maior desafio é a computação distribuída associada ao grande número de acessos simultâneos.
   Encontrei este artigo que descreve as "Falácias da Computação Distribuída". As autorias destas falácias são atribuídas à mentes como Peter Deutsch e James Goslin.
 
Falácias da computação distribuída:
    1. A rede é confiável
    2. A latência é zero
    3. A banda é infinita
    4. A rede é segura
    5. A topologia é imutável
    6. Existe apenas um administrador
    7. Não há custo para transporte de dados
    8. A rede é homogênea

    No texto do artigo, estão descritas algumas das consequências destes pensamentos que muitas vezes, por impulso, tomamos como verdade. Seguindo tais falsas verdades, acabamos construindo aplicações inseguras, com baixo desempenho e que não garantem a integridade da informação.
   Eu gostaria de reforçar os itens 2, 3 e 7. Quando nossa mente nos trás um falso sentimento de que as conexões têm latência zero, banda infinita e que não há custo para transporte de dados esquecemos de nos preocupar com o o alto consumo de recursos que nossos códigos podem gerar.
   Decisões arquiteturais de projetos devem levar em consideração os trade-offs impostos pelo mundo da computação distribuída em relação às regras de negócio envolvidas. É por isso que não existe e nunca existirá uma solução arquitetural única para qualquer sistema de informação.
   O nosso papel como programadores é descobrir como combinar soluções para minimizar os efeitos destas limitações de forma que as exigências das regras de negócio sejam satisfeitas com o resultado mais eficiente possível. Tenho redescoberto JEE à cada dia. E ela tem se mostrado uma tecnologia fantástica para atingir tal objetivo.