Tuesday Apr 08, 2014

JavaOne 2014 na faixa, 0800, grátis!

Existem muitas coisas interessantes sobre o JavaOne, a maior conferência de Java deste planeta. Talvez a oportunidade de ficar sabendo em primeira mão sobre grandes lançamentos, ou ouvir sobre novas formas de utilizar a tecnologia, ou ainda conversar com desenvolvedores de todo o mundo, ou melhor: conhecer pessoalmente aqueles com quem conversamos somente por redes sociais e mailing lists. E é claro, a oportunidade de conhecer San Francisco, e o Vale do Silício: os escritórios da Oracle, do Google, da Apple, ou até da Microsoft. :D


Se você nunca foi ao JavaOne, mas tem muito interesse, curiosidade, e muita disposição (são várias sessões, e muitos eventos pós-sessões como happy hours, shows musicais, hackathons, etc!), e quer uma ajudinha para ir no evento, um bom patrocínio, existem duas formas de você fazer isso. A melhor opção é participar do JavaOne 2014 IoT Developer Challenge!.

Continue lendo o post...

Saturday Mar 29, 2014

Get all countries using Java SE 8 Locale

I saw this blog post "Get all the country using Java Locale List" and then I thought about posting something similar, but using Lambda and the Stream API of Java SE 8. Here's my "fork", including a call to sort the locales based on "display country" property.

Continue reading...

Friday Jan 24, 2014

Hackathon de Java e Raspberry Pi na CPBr14


Você que é desenvolvedor Java e vai para a Campus Party na semana que vem de 27 de Janeiro a 2 de Fevereiro de 2014, não pode perder o Hackathon de Java e RaspberryPipromovido pelo SOUJava, com apoio da Oracle, trazendo kits, premiação, e mentoring! O objetivo é aprender, praticar e inovar, e todos os participantes ainda vão ganhar uma camiseta. Um dos projetos será selecionado para apresentação no palco principal!

Presença de grandes nomes da comunidade Java brasileira como:

Para maiores informações, consulte o site do SOUJava Hackathon de Java e Raspberry Pi na Campus Party.

Monday Jan 13, 2014

Nova versão do Java para Janeiro 2014

À partir do dia 15 de Janeiro, estará disponível para os usuários a nova atualização do Java. O aviso já havia sido feito no ano passado, mas hoje saiu o anúncio pré-release do Critical Patch Update de Janeiro de 2014 com maiores detalhes. Os produtos relacionados ao Java (Java SE, Embedded, JavaFX, e JRockit) receberão 36 correções de segurança, das quais 34 podem permitir execução remota sem autenticação. Devido à ameaça representada por um ataque, a Oracle recomenda que os clientes apliquem correções Critical Patch Update assim que possível. Para usuários desktop que necessitam de Java para acessar sites que requerem a tecnologia, como Internet Banking, a atualização do Java é extremamente importante.

Esta atualização do Java é chamada de "Java SE 7u51" ou "Java SE 7 update 51" e vem com uma importante novidade. Usuários podem agora indicar manualmente quais sites são confiáveis. Desta forma, os avisos de segurança não serão exibidos, pois fica entendido que o usuário confia no site. Para saber mais sobre esta funcionalidade, leia o documento Como posso configurar a Lista de Sites de Exceção? na Central de Ajuda do Java em português. Ou veja também aqui no meu blog um post sobre esta nova feature. Outra mudança importante nesta nova versão do Java é que todos os aplicativos Java que precisam ser executados no navegador, à partir de uma página Web, deverão ser assinados digitalmente com um certificado válido. Para saber mais, veja este outro post Mudanças no Java SE 7u51 para Applets e Web Start.

Além do Java, outros produtos da Oracle receberão diversas atualizações e correções de segurança neste lançamento, como Oracle VM VirtualBox, Oracle MySQL, Oracle Database, Oracle Fusion Middleware, e muitos outros. Para maiores informações, consulte o pre-release do anúncio do Critical Patch Update de Janeiro de 2014

Friday Jan 10, 2014

Novo Java 7u51 e os Internet Banks no Brasil

Science Duke

UPDATE: Novo post com detalhes sobre a nova atualização do Java. Clique aqui.

O ano de 2013 foi conturbado para o Java, mas a Oracle resolveu e corrigiu uma série de falhas de segurança. Muitas destas correções foram relacionadas ao funcionamento do Java Browser Plugin, que integra com os navegadores Web e permite a execução de aplicativos Java a partir de páginas HTML.

Agora, 3 meses após a última atualização Java 7u45, na próxima semana teremos o lançamento do update 51. Esta nova atualização virá com mais algumas correções e uma série de novidades, mas talvez a mais importante delas chama-se Exception Site List (documentação em Português), destinada para os usuários finais.

Na atualização 40, incluimos a feature Deployment Rule Set, destinada a administradores de estações de trabalho corporativas para oferecer esta funcionalidade com facilidade de implantação. Para usuários finais, a feature Exception Site List permite uma configuração por interface gráfica bem simples. Assim como no DRS, esta funcionalidade permitirá que usuários configurem em seus computadores os domínios Web nos quais eles confiam. Por exemplo, um usuário pode digitar https://www.sitedomeubanco.com.br e o Java irá confiar nos Applets (e também aplicativos Java Web Start) hospedados nestes sites.

Comparação do Exception Site List com Deployment Rule Set

A introdução da Exception Site List cria um segundo caminho para confiar (whitelist) em RIAs (Applets e JWS) e diminui as exigências para administradores de sistema.

 Exception Site List
Deployment Rule Set
 Desde quando?  Java 7 update 51 (Janeiro 2014)
 Java 7 update 40 (Setembro 2013)
 Destinado a
 Usuário final  Administrador de Sistemas
 Forma da configuração
 Interface gráfica  Arquivo JAR assinado
 Se os dois conflitarem
 Perde

 Ganha 


 Para aplicação de políticas padrão de segurança, alguns administradores de sistema podem bloquear o uso da Exception Site List como fariam com qualquer outra configuração do painel de controle.

Adicionando um site à Lista de Exceção

Usuários finais podem acessar esta funcionalidade à partir do painel de controle do Java.

  1. Abra o painel de controle do Java
    1. Windows/Mac - abra o painel de controle do sistema ou as Prefeências do Sistema, e escolha Java
    2. Linux/Solaris - Execute o comando jcontrol
  2. Clique na aba Segurança
  3. Clique em "Gerenciar Lista de Sites" / 
  4. Uma nova janela aparecerá

  5. Clique no botão Adicionar / Incluir

  6. O endereço não deve conter nome de arquivo no final:
    • Correto: https://www.meubanco.com.br/ib/
    • Errado: https://www.meubanco.com.br/ib/pagina.html
  7. Clique em OK. A janela irá fechar. Talvez você veja uma janela de confirmação caso utilize um canal de comunicação não-criptografado como http://. Prefira sempre o procolo https//.
  8. De volta ao painel de controle do Java, clique em OK para fechar.
  9. Recarregue a página onde está a aplicação Java, no seu navegador.

Distribuição da Exception Site List

Apesar de esta funcionalidade ser voltada a usuários finais controlando sua própria lista de exceções, quase todas as configurações de software podem ser automatizadas.

O arquivo que controla esta lista é armazenado no diretório do usuário descrito na configuração de deployment. Por exemplo, no Windows 7 este local é
C:\Users\%USER%\AppData\LocalLow\Sun\Java\Deployment\security\exception.sites

O formato do arquivo é puro texto, uma URL por linha.

Veja também maiores informações sobre o uso de Deployment Rule Sets. Para manter-se informado sobre as mudanças no Java, acompanhe o blog (em inglês) Java Platform Group

<origem>

Monday Nov 18, 2013

Você Está Pronto Para O Próximo Update do Java?

Oracle criou dois novos recursos, o 
Java RIA Security Checklist e o Java Security Resource Center para ajudar você a se preparar para a próxima atualização do Java SE, Java SE 7 update 51 (agendado para Janeiro de 2014). Esta versão modifica os requisitos de deployment para aplicações em Applet & Web Start com dois novos requisitos: 

  1. Uso do atributo Manifest, chamado Permissions
  2. Assinaturas de código válidas

Estas mudanças não afetarão desenvolvedores de aplicações back-end, ou cliente standalone; o escopo é limitado somente para Java Applets & Java Web Start (RIAs). Leia alguns destes detalhes no meu post anterior Mudanças no Java SE 7u51 para Applets e Web Start.

Java RIA Security Checklist


A mudança agendada para o Java SE 7u51 irá fazer com que o controle de segurança "default" (security slider) requererá o atributo Permissions no Manifest, e que o código esteja assinado devidamente com um certificado de código válido. O Java RIA Security Checklist
 provê as melhores práticas para ajudar os times de desenvolvimento a identificarem as tarefas necessárias para atender a estes novos requisitos.

Security Resource Center


A Oracle lançou o novo Java Security Resource Center para agrupar informações relacionadas a segurança para a comunidade Java, de acordo com o perfil de cada profissional: desenvolvedor, administrador de sistemas, usuário doméstico, ou especialista em segurança.

Recursos Adicionais

 

Nota:
 Para garantir que sistemas de usuários finais (end users) estejam protegidos quando usando conteúdo baseado em Java, a Oracle recomenda que você esteja sempre atualizado para a mais recente versão. Você pode remover versões antigas do Java seja durante o processo de atualização, ou com usando a ferramenta Java Uninstall Tool em Java.com.

Tuesday Sep 10, 2013

Java SE 7 update 40 e o Mission Control 5.2

Java SE Downloads
Chegou uma nova atualização do Java SE 7: update 40. Esta versão inclui várias novas funcionalidades como o Java Mission Control, Deployment Rule Set, suporta para o Retina display no Mac, e suporte a Hard Float ABI no Linux ARM v7. Também inclui diversas correções de bugs. Para quem desenvolve Applets e aplicações Java Web Start, este release, fica a atenção para conhecer e enteder as mudanças.

Deployment Rule Sets

Esta funcionalidade permite um administrador de desktops a controlar o nivel de compatibilidade para clientes Java assim como níveis de segurança para a empresa. Para maiores detalhes, veja a documentação do Deployment Rule Set.

Java Mission Control

O Mission Control era até então uma ferramenta disponível para clientes Oracle, e que foi lançada há muito tempo atrás junto com o JRockit (JRMC). Mas a Oracle agora disponibilizou a ferramenta junto com a JRE HotSpot 7u40. 

Esta ferramenta permite monitorar, gerenciar, introspectar, e detectar memory leaks nas suas aplicações Java, sem ter que introduzir códigos para isso, que normalmente degradam a performance da aplicação. Hoje esta ferramenta está agora disponível no download do Oracle HotSpot JDK 7u40!

Flight Recorder

Mas a principal e mais importante característica é o Flight Recorder. Este recurso funciona através da leitura de eventos produzidos pela JVM. Mesmo ativando a geração destes eventos, a sobrecarga total  para as suas aplicações ainda fica abaixo de 2%, que considerando o tipo e o valor de informação que você recebe, é quase nada. Um exemplo de evento é a chamada de um método de uma classe Java.

Com o profile de chamadas de métodos você pode descobrir onde o aplicativo está gastando a maior parte do tempo executando seu código Java. Este é, por exemplo, útil para otimizar a aplicação onde as otimizações realmente terão impacto. Isto sem precisar introspectar seu código manualmente!

Alem disso, você tem também uma visão de otimização para alocação de objetos. Você pode ver por exemplo, a alocação em tempo real de objetos na Old Gen da memória heap. diretamente no espaço de idade, além de outras abas que oferecem diversas informações importantes sobre o processamento de informações na sua aplicação Java. Leituras de arquivos I/O, Socket I/O e muito mais.

Se você precisa de mais informações sobre o Mission Control, entre na página da ferramenta em www.oracle.com/missioncontrol.

E obrigado ao Markus Eisele por ter cedido parte deste post! :-)

Monday Sep 09, 2013

Mudanças no Java SE 7u51 para Applets e Web Start

Science DukeA atualização do Java 7 update 51 (prevista para Janeiro, 2014) pretende incluir duas alterações de segurança desenhadas para melhorar a autenticação e autorização de aplicações Applets e Web Start. O controle de segurança slider do painel do Java está sendo atualizado para bloquear aplicações RIAs (Applets e Web Start) que não atenderem a estes novos requisitos. Importante: estas mudanças só se aplicam para RIAs, e não para Java no servidor ou em aplicações desktop fora do browser.

Sumário:

  • Você deve assinar todas as RIAs (Applets e aplicações Web Start)
  • Você deve definir o atributo "Permissions" dentro do Manifest
  • Sua aplicação será afetada se é inicializada a partir de um web browser. Sua aplicação não será afetada se ela é executada fora de um navegador web.

Informação completa poderá ser encontrada no release notes do Java 7 update 51, assim que for lançado em 2014.

Desenvolvedores:

A partir do Java 7u51 (Janeiro, 2014), RIAs devem ser atualizadas. As mudanças necessárias são no processo de empacotamento e distribuição; nenhuma mudança em código Java ou API é necessária. O estímulo para essas mudanças se refere à potencial abordagem de re-purposing de aplicações sandboxed, em que colocando permissões em um JAR assinado previne a modificação do seu nível de permissão definido. RIAs devem conter duas coisas:

  1. Assinatura de códigos de uma entidade verificadora confiável Trusted Authority. Todo o código para Applets e aplicações Web Start deve ser assinado, independente dos atributos de permissões.
  2. Atributos no Manifest
    1. Permissions - introduzido no Java 7u25, e obrigatório a partir do Java 7u51. Indica que uma aplicação RIA deve ser executada em modo sandboxed ou requerer todas as permissões.
    2. Codebase - introduzido no Java 7u25 e extremamente recomendável a partir do Java 7u51. Aponta para o local conhecido que hospeda o código (por exemplo: intranet.example.com)

Exemplo de META-INF/MANIFEST.MF

Manifest-Version: 1.0
Created-By: 1.7.0_51
Permissions: sandbox 
Codebase: www.java.com java.com 

Este arquivo manifest é criado quando o JAR  é empacotado, seja através do comando JAR, sua ferramenta de build, ou a sua IDE. 

Exemplo JNLP para apps Web Start

<?xml version="1.0" encoding="UTF-8"?>
<jnlp href="JavaDetection_applet.jnlp">
    <information>
        <title>Java Detection</title>
        <vendor>Oracle Inc.</vendor>
    </information>
    <resources>
        <jar href="JavaDetection.jar" />
    </resources>
    <applet-desc
          name="Java Detection Applet"
         main-class="JavaDetection"
         width="1"
         height="1">
     </applet-desc>
     <update check="background"/>
</jnlp>

Veja o documento Development and Deployment of RIAs para maiores detalhes no formato do arquivo JNLP e o deployment toolkit. Para instruções sobre como assinar seu código, veja o tutorial Lesson: Signing Code and Granting It Permissions.

Administradores de Desktops

Se você é um administrador de desktops que gerencia instalações de softwares como o Java, em diversos computadores, considere o uso dos Rule Sets para cadastrar aplicações Java na whitelist. Deployment Rule Sets permite que você certifique que uma aplicação é conhecida como segura e confiável, mesmo que você não possa atualizar esta aplicação para atender a estes novos requerimentos.

Nota: este artigo foi publicado originalmente no blog do Java SE Product Management Team.

Thursday Sep 05, 2013

Install Fusion Middleware Infrastructure on Oracle DB 12c

This week I had the opportunity to play a little with the new and recently released Oracle DB 12c. This version brings a new approach for databases, calledPluggable Databases. There are plenty of articles and YouTube videos already explaining this and I will not focus this article on it. Instead, I want to help you on How to Install Oracle Fusion Middleware Infrastructure on Oracle DB 12c.
There are a couple of steps and commands to be followed, and some very important observations. Starting with a simple one:

Do NOT execute the RCU installer on top of a CDB.
One more time: do NOT execute RCU on top of a CDB. 


If you do point the RCU tool to install over a CDB, you might get this message:

ORA-65096: invalid common user or role name


Now with this in mind, I believe you have understood that the first step is, obviously, to create a PDB. There are some options, but I will use pure SQL commands.

Step 0 - Use the correct encoding for your Database install

Make sure you have installed your DB with the AL32UTF8 encoding. 
This is recommended, but it might work in case you are using something else.

Step 1 - Create a PDB to hold the FMW Infrastructure Data

The following command will create a PDB called PDBFMW with a user "fmw" and password "welcome1".

SQL> CREATE PLUGGABLE DATABASE PDBFMW ADMIN USER fmw IDENTIFIED BY welcome1
 FILE_NAME_CONVERT=(
  '/u01/app/oracle/oradata/orcl/pdbseed/system01.dbf', 
  '/u01/app/oracle/oradata/orcl/pdbfmw/system01.dbf',
  '/u01/app/oracle/oradata/orcl/pdbseed/sysaux01.dbf', 
  '/u01/app/oracle/oradata/orcl/pdbfmw/sysaux01.dbf',
  '/u01/app/oracle/oradata/orcl/pdbseed/pdbseed_temp01.dbf', 
  '/u01/app/oracle/oradata/orcl/pdbfmw/pdbfmw_temp01.dbf'
  )
 STORAGE UNLIMITED


Please make sure to adjust the values to your installation. 

Step 2 - Open the PDB for changes

After you have the PDB created, make sure you change its state to READ_WRITE

SQL> ALTER PLUGGABLE DATABASE PDBFMW OPEN READ WRITE

Step 3 - Fix user privileges

Now you must make sure the user "fmw" has all required privileges. As this is for Development, I will just give everything.

SQL> GRANT ALL PRIVILEGES TO fmw WITH ADMIN OPTION
SQL> GRANT SYS TO fmw

* Important note: I'm not a DBA expert and these might not be the correct privileges for production environment. So please make sure to give only the necessary privileges following the documentation.

Step 4 - Run the RCU tool

This step considers that you have correctly installed Fusion Middleware Infrastructure into your Middleware Home / WebLogic installation folder. In my case, I'm using the full WebLogic + JDeveloper installation package, which brings the FMW Infra bundled. Now go to your $MW_HOME folder and run the RCU tool:

$ cd $MW_HOME
$ cd oracle_common/bin
$ ./rcu

Make sure to use the correct properties to connect to your recently created Pluggable Database:
Database Type: Oracle Database
Host Name: db12c (change to your DB IP address)
Port: 1521
Service Name: pdbfmw (here you use the PDB name)
Username: fmw
Password: welcome1 (or whatever you defined)
Role: SYSDBA
Click "Next" and see if it worked. If you are not using AL32UTF8, it will ask you to Ignore. Just do it, but remember: it might not work properly.

Step 5 - Select components and create new prefix

I like to select everything, and use the "FMW" prefix. Click "Next", "Next", "Next", etc, etc, etc... Until it finishes.

FINISHED!

You have successfuly created the right database structure for your Fusion Middleware Infrastructure, and now you can create a WebLogic domain with ADF and everything else, pointing to this PDB.

If you have any question, post a comment!

Friday Aug 23, 2013

Java EE 7 OTN Tour 2013 Trip Report - Part 1/2

OTN Tour 2013 is over, and after 7 countries, all I have to tell you is this: #JavaEE7 rocks and people loved it! It is quite coincidence that at the end, I went to 7 cities in Latin America to give my "What's new in Java EE 7" talk plus the Hands-on Lab and other talks like the one about WebLogic 12c and another about GlassFish 4.

In reality, I had also planned to go to Panama City, and San José in Costa Rica. Well, things sometimes don't always go as planned, and I couldn't go to Panama. And when I got to Costa Rica, I was sent back to Mexico because I was not with my Yellow Fever card. But I'm looking forward to Java EE 9, if you know what I mean. :-) In the end, I visited 7 cities:
  • Mexico City, Mexico
  • Guadalajara, Mexico
  • Santiago, Chile
  • Lima, Peru
  • Montevideo, Uruguay
  • Buenos Aires, Argentina
  • São Paulo, Brazil
Now, before I talk about each city, let me explain something to you really important: OTN Tour is organized by LAOUC, the Latin America Oracle Users Community. And at each participant city, local OUGs help to organize, set a venue, local partners as sponsors, and also work with the speakers' agenda. Oracle does sponsor these events, both by supporting the local event,  as well by sponsoring Oracle ACEDs to travel with the tour. If you want to become an Oracle ACE, all you need to do is to learn about the Oracle ACE program.

We all know how Database-driven Oracle has been for the past decades, and we understand that most off the Oracle User Groups are more interested on Database stuff. But this is changing. There was a lot of interest during the whole tour on Middleware and Development technologies such as Java EE, ADF, WebLogic, and GlassFish. Dana Singleterry joined me in this tour and brought with him a lot of information on ADF 12c and ADF Mobile. Don't forget to follow him on Twitter.

By the way, this tour was great to improve my Spanish. Yeah, you read it: Spaaaanish. I'm from Brazil, and we speak Portuguese there. And Brazil is the only country in Latin America that speaks Portuguese. To improve my learning, at every country I visited I tried to learn local slangs. So for each city, I did a special slide for Java EE 7. Really, you gotta learn local slangs to be cool with a 2nd/3rd language :-P Anyway, it all started on July 21st in the morning...


Mexico City (DF), Mexico - July 26th

Like I told before, I could not go to Panama nor Costa Rica, so I stayed in Mexico the first week, and worked with Oracle folks there, did customer meetings, worked from hotel, etc. On Friday I finally started. Great venue at Egade Business School as well a very nice setup with coffeebreaks and lunch for everyone. Kudos to ORAMEX, the local OUG. In Mexico, I gave my Java EE talk, and did the Hands-on.
Spanish Lesson Part 1
By the way, chingar is a word in Mexican Spanish that means a lot of things, both for good or bad contexts. It can be used so widely that there is even a "chingonary", or a dictionary on how to use it, that I had to buy one for me in a local bookstore. In this case, it means "Java EE 7 has so many new technologies inside", but of course using a slang, almost a swearing word :P

Pictures: Facebook or Google+

Guadalajara, Mexico - July 27th

Guadalajara was not part of the official OTN Tour. Actually, it was an Oracle Java Day organized by the local Oracle office, with people from the Oracle Curriculum Development Team and where some of the great content of Oracle Learning Library is coming from. This conference was led by Edgar Martinez and I can't say how thankful I am. Edgar and his team did a great job. Everything was perfect: the great staff team, pizza for lunch, the office, the setup, the trail, and last but not least, the happy hour! Edgar blogged about this as a guest at Java blog, so you may want to read more about this there. Here I gave my Java EE 7 talk, and the hands-on. A lot of people showed up!

More pictures of the event on Flicker, my Facebook, and my Google+
Also, all the registration fee for this event was donated to a local orphans institute. Later, perhaps the best moment of it all: when we were walking on the street after the event looking for a place to dinner, we met with the supporters of this institute.


">


Santiago, Chile - August 1st


Santiago is an incredible city. It holds about 30% of the entire population of Chile, and I would guess perhaps more than 50% of the entire economy there. It is one of the most modern city, with great infrastructure and easy access to several touristic places. It was where I could enjoy a tourist-like day, so expect to see regular pictures. :P

Spanish Lesson Part 2
The term bacán in Chilean Spanish means "cool". I had to change my slide here.
The conference here happened at a very nice university, close to a subway station, and here I gave my Java EE 7 talk the hands-on again, and then the GlassFish in Production Environments. I met with great people here both from Oracle User Groups as well some people from the local Java community. It was also where I first met and talked to Tim Hall, really great guy, Oracle ACED, an expert on Oracle Database. If you have any questions about OraDB, follow him on Twitter and check his website, oracle-base.com.

Pictures: Facebook or Google+

Lima, Peru - August 3rd

One day after Santiago, I was flying to Lima for the third country of my list. Lima has really nice areas, like Miraflores so if you plan to visit Peru one day, make sure you stay there to enjoy the best view of the Pacific Ocean. For night life, visit Barranco, full of bars, restaurants, and nightclubs.

Here I gave my traditional Java EE 7 session, catch up with local Oracle people, and had perhaps one of the crowdest room in the whole tour. The question I made to the attendees in the picture below was: "Did you like the new stuff in Java EE 7? Raise your hand if yes!!!"

Pictures: Facebook or Google+

Spanish Lesson Part 3
The term chévere in Peruvian Spanish means "awesome". It is similar to bacán from Santiago, Chile. But people here prefer to be different. :-) So I had to change my slide again.

More next week
I still have to talk about was this tour in Argentina, Montevideo, and finally Brazil. But I will leave that for the next post.

By the way, to keep posted on this, follow me on Twitter! Or Google+... Or Facebook... :-)

Thursday Jul 25, 2013

Como instalar o GlassFish 4.0 (ZIP) [pt_BR]

O jeito mais rápido e fácil de instalar o GlassFish 4 em servidores é utilizando a versão ZIP do instalador. O ZIP já vem com um domínio (domain1) configurado, e por isso o tamanho do arquivo é maior que o instalador nativo (onde um domínio será configurado durante a instalação).

Passo-a-passo

  1. Entre em http://www.glassfish.org/downloads e clique no link abaixo de Zip (quick start). No momento deste post, a versão disponível é a 4.0.
  2. Descompacte o ZIP em um diretório de trabalho:
    $ mkdir ~/Work
    $ cd ~/Work
    $ unzip ~/Downloads/glassfish-4.0.zip
  3. Entre no diretório bin do GlassFish:
    $ cd glassfish4/bin
  4. Execute o seguinte comando para inicializar o domínio domain1
    $ bash asadmin start-domain domain1
  5. Abra o seu navegador e vá para o endereço http://localhost:4848

Pronto! Servidor up and running!

Sunday Jul 21, 2013

OTN Tour 2013 in Latin America

The Oracle Technology Network Tour 2013 has already started, bringing several Oracle and non-Oracle speakers to OUGs (Oracle User Groups) to countries across Latin America. You can check the official OTN Tour 2013 page of the tour to follow up with agenda, dates, speakers and other information. Last year I participated giving talks in Uruguay and Argentina about Oracle WebLogic 12c. That time, I had recently joined Oracle and didn't know much about it. But this year though, I wanted to do more.

Some facts about Latin America
Latin America includes all countries between Mexico and Argentina, most of them who speak Spanish, and where Brazil the only country that speaks Portuguese (not exactly like the one from Portugal, and definitely not like Spanish), and there are other languages too, like French (in French Guiana). These are also know as Romance languages, derived from latin. Spanish is the predominant language and that's why one of the challenges for me as a Product Manager and Java Evangelist here is to communicate with these countries, and taking Spanish classes is just part of the solution. Knowing details about each country and Spanish variations is the "advanced" step. In Mexico for example, chingar is one of these advanced things :-) But it must be used carefuly, for obvious reasons

En Java EE 7, hay un chingo de nuevas APIs.

OUGs+JUGs = Bigger community working together
This tour is slightly different from previous years. There will be much more Java content than before, specially because of the Java EE 7 launch. And local JUGs were invited to join the OUGs that usually organize and coordinate each country. If you want to help, go to this post and provide contact information, for future events. OUGs and JUGs working together is quite a new thing, and I see it as a great thing!! 

Countries for OTN Tour 2013
Here is the full agenda , and in bold where I start.

  • Colombia, 07/12
  • Ecuador, 07/15
  • Guatemala, 07/17
  • Panama, 07/22
  • Costa Rica, 07/24
  • Mexico, 07/26
  • Chile,  08/01
  • Peru, 08/03
  • Uruguay, 08/05 - 08/06
  • Argentina, 08/07 - 08/08
  • Brazil, 08/10

Due to agenda and other conferences, I could not come to the first 3 countries, but I am already on the road to cover the rest, starting with Panama next Monday.

Talks
I proposed a few abstracts to OUGs/JUGs choose which could work best for each country, and here are the topics:

  • GlassFish in Production Environments
  • What WebLogic 12c Has To Offer to Boost Your Productivity
  • What's new in Java EE 7
  • Hands-on for Java EE 7

Photos and videos
I don't have a plan yet on how, when, or if even I will produce videos. But I brought my camera! Let's see how it goes.

Social 
If you want to follow my jorney, connect with my Twitter profile and/or the #OTNTour hashtag.

Join the Tour!!

PS: I will try to write a blog post per country, with pictures, and in the local language. :-) 

 

Tuesday Jun 04, 2013

Promote Java EE 7 and GlassFish on your Twitter

The launch of Java EE 7 is right ahead. On June 12th we will hear from Oracle executives and evangelists what's all about the new version of the platform. The Live Webcast "Introducing Java EE 7" will have two sessions, and all you need to do to join us and watch Arun Gupta and others, is to go to this webpage and sign up. Also, don't forget to check GlassFish's blog, you know, because it's the reference implementation of Java EE! :-)

But if you really, really love Java EE and really, really want people to join us, why don't you also promote the launch on your Twitter account? Use this background image that fits very nice on your profile, and also don't forget to set the background color to #517E9C.

Let's Make The Future Java... Together!

Friday May 10, 2013

Líderes de JUG de Latinoamérica, Oracle quiere ponerse en contacto


Hola Comunidad Java de América Latina! Dentro de un par de meses, voy a empezar una gira por América Latina para llevar a usted las nuevas características de la plataforma Java EE 7.

Esta gira comenzará en julio en Brasil, en el TDC - The Developers Conference, en São Paulo. Luego, después de eso, voy a empezar mi viaje a través de varios países. Pero para ayudar a terminar mi agenda, necesito tu ayuda!

Todo lo que necesitas hacer es compartir este artículo con alguien que usted conoce o en su red social. , y por supuesto, proporcionar la información que pido aquí. Esto me ayudará a ponerme en contacto con los líderes JUG locales en su país, y planear las reuniones.s.

Su ayuda es muy apreciada!

¡Gracias!

Thursday May 02, 2013

Integrating WebSockets and JMS with CDI Events in Java EE 7

UPDATE July 15th, 2013
I've updated this blog entry to clarify the issue of integration between WebSockets API 1.0 and other Java EE technologies, and also to link you to the bugs submitted in the WebSockets, JMS, and specially the CDI specification. I want to talk all spec leaders involved in this, specially JJ Snyder, Danny Coward, and Nigel Deakin.

This is a great reminder of how important is your participation during the specification definition process. Please read, test and report any issue you find in a specification before it becomes final. Join the Adopt a JSR program and work with us!

------------------ 

WebSocket is the new kid on the block when you think about Web Development these days. And it is expected that you want to integrate it with whatever is available in your hands. Java EE 7 is coming with cool things beyond this, for example JMS 2.0. And then you wonder: how can I send asynchronous messages to all WebSocket sessions connected to my website? Server push; no polling: for real!

The answer is quite simple: CDI. Also know as the Java EE magic glue. CDI enables a developer to build inter-communication between, apparently, distinct parts of your application. Let's go through all the steps to enable your WebSocket application to send and receive messages through JMS.

1 - Creating the WebSocket Server Endpoint

First we need to build the WebSocket server endpoint that will receive messages from clients, and to also notify clients asynchronously with a server push, with incoming JMS message payloads:

@Named
@ServerEndpoint("/websocket") public class WebSocketEndpoint implements Serializable { // this object will hold all WebSocket sessions connected to this WebSocket // server endpoint (per JVM) private static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>()); 

Now you must also add three key methods to this WebSocket: 

@OnOpen public void onOpen(final Session session) { sessions.add(session); } @OnMessage public void onMessage(final String message, final Session client) { ... } @OnClose public void onClose(final Session session) { sessions.remove(session); }

Notice that on onOpen and onClose, we manage all user sessions connected to this endpoint. We will see later how sessions will be used inside onMessage. For now, let's create a SessionBean to send messages to a JMS Queue.

2 - Creating the SessionBean to send JMS messages

Due to missing parts from the specifications, we cannot use @Inject JMSContext inside a @ServerEndpoint WebSocket, and we can't also set a server endpoint as a MessageListener to receive JMS messages. Simply put, integration between JMS and WebSockets (and probably other Java EE APIs) is not straightforward. You can follow the discussion in the following issues:

 

But fortunately, there are two ways to do this: 

  1. Create a stateless SessionBean that sends messages to a JMS queue
  2. Inject JMS resources inside WebSocket Server Endpoint, and create a JMSContext from the ConnectionFactory

 

Solution #2 can be achieved using the following snippet, thanks to Nigel Deakin, spec leader of JMS who helped me discovering this issue.

@Resource(lookup="java:comp/DefaultJMSConnectionFactory") ConnectionFactory cf;
@Resource(lookup = "jms/myQueue") Queue myQueue;
 
@OnMessage
public void onMessage(final String message, final Session client) {
try (JMSContext context = cf.createContext();){
context.createProducer().send(myQueue, message);
}
}

We are going to use solution #1 and create a SessionBean to forward incoming WebSocket messages to a JMS queue. Create a class named QueueSenderSessionBean as it follows:

@Stateless
public class QueueSenderSessionBean { ... }

This is a simple @Stateless SessionBean. Now, let's add a business method to it, called sendMessage:

public void sendMessage(String message) { ... } 

Quite straight-forward, isn't? One of the great things about JMS 2.0 is its simplicity to send messages to a destination. To do that, we need to inject two objects:

@Resource(mappedName = "jms/myQueue")
private Queue myQueue;
@Inject private JMSContext jmsContext; 

JMSContext is one of the new classes added to JMS API, and is documented here. It encapsulates a Connection and a Session, and makes use of a default ConnectionFactory, now a required resource to be provided by all Java EE 7 certified application servers. Next, all you need is to add the logic to the previously added method:

jmsContext.createProducer().send(myQueue, message);

And you are done with the SessionBean. Next we will add some glue between the SessionBean and the WebSocket to send messages to the JMS destination.

3 - Forwarding an incoming WebSocket message to a JMS destination

All you need to do here is to inject the SessionBean into your WebSocket, and call the sendMessage method inside onMessage of your endpoint. Let's start with the injection first, but due to a bug, we must do constructor injection. Open your WebSocket server endpoint class WebSocketEndpoint, and add the following field:

private QueueSenderSessionBean senderBean;

Now add the following constructor to it:
  @Inject
  public WebSocketEndpoint(QueueSenderSessionBean sb) {
     this.senderBean = sb;
  }

Next step is to simply call the method inside onMessage
senderBean.sendMessage(message);

We have finished the first part of this application. With this code, you are now able to send a message from a WebSocket client, to a JMS destination. Next, we will do the opposite. Let's push some data from a JMS queue to all WebSocket clients!

4 - Listening to a JMS Destination with a MessageDriven Bean

Funny fact: some developers have not realized yet, but the MessageDriven annotation is not specified by the JMS API. Instead, it is part of the EJB specification, and it can be used not only for JMS, but for many other things. David Blevins from the awesome Apache TomEE realized that, and proposed a small change to the EJB spec, where resource adapters required connectors to provide a messagelistener-type. His proposal though, suggests that you should be able to use an MDB to listen to different things, and the listener interface should be optional. One example is to listen to Telnet commands. Pretty awesome! But let's focus on our use case here, which is specific to JMS.

Now that we can publish messages into a Queue destination from a WebSocket client, we must process them to later forward to somewhere else. Let's start coding our JMS MDB (remember, not all MDBs are implicitly JMS-related!), implementing the MessageListener interface, required by JMS ResourceAdapter connectors:

  @Named
  @MessageDriven(mappedName = "jms/myQueue")
  public class WebSocketMDB implements MessageListener {
    @Override
    public void onMessage(Message msg) { ... }
  }

This is the basic code to any JMS MDB. Now let's do some magic... 

5 - Firing CDI events with the JMS Message payload

Remember when I told that we cannot listen to JMS destinations directly from the WebSocket server endpoint due to specification restrictions? Well. We can actually, but using a different technique. If you haven't heard about CDI Events, you should read about it before continuing this tutorial. Done? Ok, let's go. First thing we need is an Event qualifier. Create the WSJMSMessage annotation inside your project:

  @Qualifier
  @Retention(RetentionPolicy.RUNTIME)
  @Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE})
  public @interface WSJMSMessage {}

 With a defined qualifier, CDI will be able to connect the firing event with the observer object. Go back to the WebSocketMDB and add an Event dispatcher to it, with the qualifier we created above:

    @Inject
    @WSJMSMessage     Event<Message> jmsEvent; 

 Now let's add the logic to the onMessage method:

jmsEvent.fire(msg);

6 - Listening to CDI events within the WebSocket server endpoint

This is the last server-side part of this article, then next you will see how to code Javascript on the client-side. Let's listen to CDI events fired by the MDB, with the Message payload. Open again your WebSocketEndpoint class, and add the following method to it:

public void onJMSMessage(@Observes @WSJMSMessage Message msg) {
        try {
            for (Session s : sessions) {
                s.getBasicRemote().sendText("message from JMS: " + msg.getBody(String.class));
            }
        } catch (IOException | JMSException ex) {
            Logger.getLogger(WebSocketEndpoint.class.getName()).log(Level.SEVERE, null, ex);
        }     } 

Observe the @Observes and the qualifier @WSJMSMessage we defined previously. This is what tells CDI to listen to the fired events by the MDB.

7 - Client-side Javascript to connect with the WebSocket server endpoint

This has been floating around the Internet for a while as it is not Java nor Java EE specific, but anyway it is basically this:

// note the final path is the same defined inside WebSocketEndpoint class at @ServerEndpoint websocketSession = new WebSocket('ws://' + document.location.host + '/your-app-context-root/websocket');

Here is the final Javascript used by this example, as well the HTML interface.

Conclusion

I hope you have found this article useful to begin your development with Java EE 7, and what are the possibilities of integrating CDI, WebSockets, JMS, and EJB. These are the main points about this article:

  • ability to asynchronously communicate with WebSocket clients (although you can also use session.getAsyncRemote() to send messages asynchronously)
  • ability to do a server push to WebSocket clients at any point in your application
  • ability to scale server-pushed communication to WebSocket client sessions across a cluster using JMS Topics
    This is perhaps one of the most interesting thing about this setup. If you use a Topic instead of a Queue, you will be able to push data to all WebSocket sessions connected to your application across a cluster. There's a know limit of roughly 64k client sessions per web server, and in this example we use a static synchronized Set to hold a reference to them. Imagine now a cluster. We change this to a Topic clustered subscriber, and we are able to scale up server pushed data :-)
The source code of this project is available at my GitHub repository javaee7-jms-websocket-example. I hope you liked the article!

About


Bruno has been having fun working with Java since 2000 and now helps Oracle on sharing the technology accross all Latin America. Also plays videogames, does trekking and loves beer.

Follow me on Twitter! @brunoborges

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today