Wednesday Jan 08, 2014

WebLogic in Comparison: RebelLabs Java Servers Report

RebelLabs did a great job comparing the main Java servers out there, where some are pure Servlet/JSP containers, others are full Java EE compliant. But they didn't want to include in the list Oracle WebLogic nor IBM WebSphere apparently for no logical reason but "they are suited for large enterprise production environments", and because the report is focused on developers.

"The Great Java Application Servers Debate"

So, I decided to write this blog post to include detailed information about WebLogic, since WLS is free for developers, even if you are going to deploy GlassFish/JBoss/Whatever in production. Which is why I didn't get why RebelLabs didn't want to compare WebLogic.

Remember, I will detail WebLogic from a "developer point of view", using the same categories RebelLabs used in their report. Here we go:

Download & Installation

WebLogic 12c is certified for Java EE 6, and 12.1.1 was released on Dec 2011. The second release is 12.1.2 and is from July 2013, part of the full Cloud Application Foundation 12c release. For developers, there is a ZIP distribution sized at 184Mb.
  1. Accept Licence agreement
  2. Download installation package *
  3. Extract the archive
  4. Run (Linux/Mac) or configure.cmd (Windows)
  5. You are ready to go!
* you must have an OTN account, required for other things like access Oracle Forums

The script will ask you if you want to create a domain. Say "yes". Then you are asked to provide username/password for it, because we do care about default security. And right after the script finishes creating the domain, you can point to http://localhost:7001/console, because the script will automatically start WebLogic for you. To start WebLogic again, just call: 
$ cd user_projects/domains/mydomain; sh
Conclusion: License accepted only once. Bigger than others indeed but enhanced default security. Starts server automatically right after creating domain.

Tooling support

The RebelLabs report says WebLogic is only integrated with JDeveloper. But that's a big mistake. WebLogic is well integrated with NetBeans, Eclipse, IntelliJ, and can even be used with Apache Maven and Ant. For a "big fat bloated enterprise production-only app server", I would say WebLogic is in very good shape for development environments.

Eclipse: you can either download Oracle Enterprise Pack for Eclipse bundled with Eclipse, or just the update by either downloading the repository, or pointing to the repository URL.

NetBeans: support comes out of the box since version 7.1 (released in January 2012). Here's an article hosted on about NetBeans and WebLogic.

IntelliJ IDEA: Jetbrains comes with native support for WebLogic not only version 12, but also older versions. 

Apache Maven: in release 12.1.2, Oracle WebLogic has an enhanced Maven support with more goals and easier installation into Maven repositories. Check the documentation to learn more.

Apache Ant: for several versions WebLogic has been coming with Ant support. And continues to do so. Check the documentation for 12.1.2

If you are developing with Eclipse, NetBeans, or JDeveloper, you can even enable FastSwap, a feature that reloads changed classes on the fly. I've blogged about how to enable and use FastSwap with NetBeans a while ago.

Conclusion: has support for 99,9999% of tools used by developers. FastSwap for on-the-fly class update. IntelliJ and NetBeans with OOTB support. Eclipse plugin or full distribution with OOTB support.

Server Configuration

In the report, RebelLabs gave GlassFish a score of 3, which is weird because the way they described this section, seems like everything is perfect. The "Reason" line gives no negative reason at all! So I asked them on Twitter.

In WebLogic, you can basically do everything through the Web console available in the Admin Server. From there you can create clusters, create new managed servers, add Java EE resources like JMS queues, Data Sources. You can create Work Managers, do Security management. Anything. But for developers that don't want to follow steps documented in Word files full of screenshots of all these Web interfaces, they can simply write a Python script, and whenever they have to configure something [again], all they need to do is to run the script. The feature is calledWebLogic Scripting Tool, or simply WLST, and several companies have been using this for many years. It's great for configuration automation and also manageability. If you want to record the commands you type in the WLST shell for future executions, call startRecording(). If you don't want to write a script from scratch, the Adminstration Web console comes with a "Recording" feature that will record all your actions and create the script for future executions. And you can also connect through JMX.

If you are really into XML configuration, you can access the domain folder, then edit theconfig/config.xml file and do your magic. But they will only take effect after a restart.

And finally, most changes don't require a server restart.

Conclusion: Python scripts. JMX. Rich web console. Recording features. XML. Most changes go live without restart.

Documentation & Community

Documentation for WebLogic is very complete, and the new 12.1.2 documentation website has an updated Look & Feel. It is easy to navigate and comes with a search (basic and advanced) feature. The community is not as small as you may think. Oracle runs the Oracle ACE program and highlights outstanding professionals all around the world. The Oracle Partner Network is also big, with several folks running meetings, bootcamps, hackathons, etc. Take for example the last edition of UK OUG Tech 13, where attendees developed Puppet modules during a WebLogic Hackathon. And finally there's an Oracle Forum for WebLogic which is ran by the Oracle Technology Network team. 

Community is not related to only Open Source products. Doesn't matter if it's Open Source or not, if there's enough people working with a product, there's a chance for a community be born.

Conclusion: There is a community. Not as know as Open Source ones. Widespread around the world. Decentralized.

Features & Open Standards compliance

WebLogic 12c is Java EE 6 Full profile certified. Customers can also develop rich web applications with Oracle ADF, and they also get extra features/support for TopLink, like Oracle Coherence Integration. TopLink can be seen as an extension of EclipseLink, the Open Source JPA implementation, maintained at the Eclipse Foundation, but with great contribution from Oracle. WebLogic 12c has also support for OSGi bundles.

For administrators and devops, in addition licensed customers gain several other products and support. So for example, if you are comparing WebLogic Standard Edition with JBoss, don't forget that WLS SE comes bundled with support for: 
  • Oracle HTTP Server (enhanced Apache)
  • Oracle TopLink/ADF
  • Configuration Wizard / Upgrade Framework / OPatch
  • Oracle Java SE
  • Oracle WebLogic Management Framework
  • WebLogic JDBC Drivers, Server Clients, Apache Plugin
  • HTTP Pub-Sub Server
If you want more details about what you get by buying WebLogic, see this table. It will show also what other flavours of WebLogic (Enterprise/Suite) have to offer.

Conclusion: of course 1 apple will be cheaper than 4. :-)

Conclusion: Java EE 6 and OSGi. Extra features/products for licensed customers starting since WebLogic Standard Edition. Most complete application server, with support for all products involved in a basic infrastructure for running server-side Java applications.

Administration & Management/UI

As I pointed in the "Server Configuration", WebLogic has several ways for the developer to configure whatever the dev wants. But to give you an impression, here's a screenshot of the Admin Console, to create a JDBC Data Source:
Conclusion: Rich web console. Allows to control, from the Admin Server, all resources, as well monitor and manage servers in one or more clusters.

Cost $$$ / Licensing

The pricelist is available publicly and can be easily googled. No secrets, full transparency, from how much you pay (at maximum, since there's always a conversation with the sales rep), to what you get in exchange. Remember: when you license and contract support for WebLogic Standard Edition, you pay per processor socket (not per core), and you get support for Oracle Java SE (JVM), Oracle HTTP Server (Apache), and several other features/products. Other editions are priced differently but come with even more features.

But anyway, WebLogic comes with no charge for developers.

Conclusion:  When comparing cost to other application servers, remember that WebLogic comes with supported JVM (Oracle HotSpot), support of an enhanced Apache (Oracle HTTP Server), and other things that most application servers don't offer when you license or subscribe for support.

The Results

I've seen developers running Tomcat or JBoss or GlassFish, and going into production with WebSphere or WebLogic. But with the information above, I say that, overall,  WebLogic has evolved a lot especially in the new 12c version, with a smaller ZIP distribution, easy and secure installation, enhanced Maven support, great features for managing, awesome tooling support, and most important, free for developers. And don't forget the community! 

If a developer wants to develop pure Java EE applications, WebLogic is a very strong candidate. Even if the customer is running WebSphere in production :-)

Tuesday Jan 07, 2014

Demoiselle Framework no WebLogic 12c

Pra quem não sabe, o Demoiselle é um framework que roda sob a plataforma Java EE 6, desenvolvido e mantido pelo SERPRO para ser usado em projetos de todas as esferas do Governo.

No dia 1 de Novermbro do ano passado (2013), foi lançada a versão 2.4.0 conforme o Twitter dos mantenedores do framework. Decidi então saber qual seria a dificuldade de rodar um projeto Demoiselle no Oracle WebLogic 12c.

O WebLogic 12c (versão 12.1.1) foi lançado em Dezembro de 2011 e é compatível e certificado na plataforma Java EE 6, mas foi no ano passado em Julho que recebeu um update (a versão 12.1.2) com uma série de novas features e algumas correções, completando assim o release 12c do Cloud Application Foundation, que serve de infraestrutura para toda a tecnologiaFusion Middleware da Oracle.

Criando um projeto de exemplo e um pacote WAR

Uma grande vantagem do Demoiselle é que é um framework desenvolvido inteiramente com Apache Maven, e possui archetypes para facilitar a criação de novos projetos. Para este teste, vou usar o seguinte archetype:
O comando para criar um projeto a partir deste archetype pode ser este:
$ mvn archetype:generate \ \
 -DarchetypeArtifactId=demoiselle-jsf-jpa \
 -DarchetypeVersion=2.4.0 \ \
-DartifactId=demoiselle-sample-2.4.0 \
 -Dversion=1.0.0-SNAPSHOT \
O nome do projeto será demoiselle-sample-2.4.0

Ajuste a configuração JPA do projeto

O Demoiselle vem com um arquivo persistence.xml no diretório src/main/resources/META-INF e este arquivo deve ser editado da seguinte maneira: 
  1. Comente a configuração que está ativa logo no início do arquivo (específica para JBoss)
  2. Descomente a segunda configuração para GlassFish, chamada "GlassFish 3 with JTA transaction"
  3. Modifique o JNDI do Data Source para o seguinte valor: jdbc/demoiselle

Geração do pacote WAR

Agora para ter um arquivo WAR pronto para ser instalado no WebLogic, basta gerar o pacote: 
$ mvn -Pglassfish3 package
Repare que especifico o profile chamado glassfish3. Isto porque o Demoiselle possui uma série de profiles para cada servidor de aplicação (tomcat6, tomcat7, glassfish3, jboss6, jboss7). No momento em que escrevo este blog, meu pedido para acrescentar o profile do WebLogic 12c ainda não foi aceito. Acompanhe o pull request no GitHub para maiores detalhes e atualizações.

Mas não tem problema especificar o profile já existente glassfish3, pois este atende às especificações do Java EE 6, e o WAR resultante funciona perfeitamente no WebLogic 12c. 

Agora você deve ter no diretório target do projeto, um arquivo chamado demoiselle-sample-2.4.0-1.0.0-SNAPSHOT.war. Anote o local e o nome deste arquivo para depois fazermos deploy deste artefato.

Download, Instalação, Configuração e Deploy no WebLogic 12c

Sobre como fazer download e como instalar o WebLogic, já escrevi em 2012, How to Install WebLogic 12c ZIP on Linux (em inglês). Se tiver alguma dúvida, comente no post!

Quanto à configuração, a única coisa que precisamos fazer é criar um Data Source apontando para um banco de dados. Desde a versão 10.3.3 o WebLogic já vem com o Derby como parte da instalação, permitindo assim configurar um Data Source para um banco de dados em memória. No WebLogic 12c, o Derby já está ativo e para criar um Data Source é bem fácil.

Primeiro, acesse o diretório onde o domínio foi criado, e depois inicialize o servidor:
$ ./
Agora acesse a URL do console administrativo Web no endereço http://localhost:7001/console. Informe o usuário/senha que você definiu durante a instalação (geralmente, é weblogic/welcome1). O passo-a-passo da configuração é bem simples:
  1. No menu esquerdo, clique em Services, Data Sources
  2. Clique no botão New
  3. Selecione a opção Generic Data Source
  4. Informe o valor jdbc/demoiselle nos dois campos texto (Name e também JNDI Name)
  5. Selecione o tipo de banco de dados Derby na combobox
  6. Clique em Next
  7. Na tela seguinte não há o que fazer. Clique em Next
  8. Na tela seguinte também não há o que fazer. Clique em Next
  9. Na tela onde diz "Connection Properties", informe o valor demoiselle no campo Database Name
  10. Nesta tela, informe localhost como o Host Name
  11. Nesta tela, informe demoiselle nos campos Username, Password, Confirm Password
  12. Clique em Next
  13. Na tela seguinte verifique os dados, e experimente a configuração clicando no botão Test Configuration
  14. Clique em Next
  15. Selecione o AdminServer e finalmente, clique em Finish
Agora você deve ter um Data Source chamado jdbc/demoiselle, de acordo com a configuração feita anteriormente no persistence.xml do projeto.

WLST - WebLogic Scripting Tool

O WebLogic vem com uma feature muito legal chamada WLST, que permite você escrever scripts em Python para automatizar tarefas administrativas no servidor de aplicação. Se você achou o passo-a-passo acima complicado, experimente rodar este script especificamente para criar o Data Source jdbc/demoiselle usando o Derby. O procedimento é simples:
  1. Faça download do arquivo no Gist
  2. Acesse a pasta do domínio WebLogic
  3. Digite o seguinte comando para incorporar as variáveis de ambiente do domínio WebLogic na shell:

    $ source bin/

  4. Digite o seguinte comando para invocar o script:

    $ java weblogic.WLST <caminho para o arquivo>/

Deployment da aplicação Demoiselle

Aproveitando o ambiente do domínio na sua shell (após executar "source bin/"), é muito simples fazer o deploy da aplicação. Execute o seguinte comando:
$ java weblogic.Deployer \  -username weblogic \  -password welcome1 \  -deploy <caminho para o projeto>/demoiselle-sample-2.4.0/target/demoiselle-sample-2.4.0-1.0.0-SNAPSHOT.war
Lembre-se de ajustar o usuário e senha do seu domínio WebLogic tanto no comando acima, quanto no script WLST. Por conveniência, deixei já o comumente utilizado u:weblogic p:welcome1.

Caso queira usar a interface Web, o processo é simples. Clique no menu Deployments, depois no botão Install e basta seguir as instruções da tela.

Testando a aplicação Demoiselle

Agora que a aplicação está rodando, você pode testar acessando a URL da aplicação, que provavelmente é esta: http://localhost:7001/demoiselle-sample-2.4.0-1.0.0-SNAPSHOT/index.jsf

Qualquer dúvida, é só comentar! Ou me procurar no Twitter @brunoborges. :-)



Thursday Dec 05, 2013

WebLogic agora é grátis para desenvolvedores!

Uma ótima notícia, que não é mais tão notícia assim, para todas as empresas desenvolvedoras de software, ISVs, fábricas de software, parceiros e não-parceiros Oracle. O WebLogic, servidor de aplicação Java EE líder de mercado pode ser baixado gratuitamente e utilizado em ambientes de desenvolvimento sem qualquer custo, através da licença da OTN. Conforme licença publicada no site, o trecho mais importante é este:

"[...] deploy the programs only on your single developer desktop computer (of any type, including physical, virtual or remote virtual), to be used and accessed by only (1) named developer."

Até então era comum acreditar que para desenvolver para uma grande empresa que adquiriu o WebLogic, seria necessário a empresa prestadora de serviço adquirir também o produto. Um exemplo comum é de empresas que desenvolvem software para outras empresas em forma de projetos (fábricas de software); estas empresas podem utilizar o WebLogic nas máquinas dos desenvolvedores sem qualquer custo Outro trecho interessante na licença da OTN é este:

"You may continue to develop, test, prototype and demonstrate your application with the programs under this license after you have deployed the application for any internal data processing, commercial or production purposes"
Veja a licença OTN completa para maiores informações

Se a sua empresa está em São Paulo, e vocês desenvolvem software para outras empresas que utilizam o WebLogic em produção, entre em contato para conhecer mais sobre o novo Oracle WebLogic 12c: bruno dot borges at oracle dot com.

Se ainda restam dúvidas sobre a simplicidade de instalar o WebLogic em ambientes de desenvolvimento, veja este outro blog post (em inglês) sobre como configurar o WebLogic distribuído em formato ZIP: How To Install WebLogic Zip on Linux!

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


 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

Thursday Nov 14, 2013

O futuro do WebLogic 12c

Antes de falar do WebLogic 12c, uma informação importante é que prorrogamos o suporte do WebLogic 11g (versão 10.3.6) até 2018, e o suporte estendido até 2021. Isto dará maior tranquilidade aos clientes a planejarem suas migrações, reduzindo assim riscos e custos, principalmente aos clientes de Fusion Apps e SOA Suite/BPM. 

A versão atual do WebLogic 12c é a 12.1.2, lançada este ano em Junho, juntamente com todo o Cloud Application Foundation 12c (Coherence, Oracle HTTP Server, Tuxedo, etc). A versão anterior 12.1.1 já era certificada em Java EE 6, e agora esta nova versão traz uma série de recursos e funcionalidades para integrar suas aplicações com o banco de dados Oracle 12c, facilitar o operacional através de Dynamic Clustering e Elastic JMS, mais otimizações para Exalogic e JMS, administração do Oracle Coherence pelo console administrativo do WebLogic, plugins para desenvolvimento de projetos com Apache Maven, geração automática de serviços REST para seus projetos JPA com o TopLink RESTful Data Services, e muito mais.

O WebLogic 12.1.2 também substituiu o antigo instalador da BEA e os utilitários de patch BSU com o Oracle Universal Installer e o utilitário opatch para a aplicação de patches. Muitos clientes Oracle já conhecem estas ferramentas, que já eram utilizadas para outros produtos, como o próprio Banco de Dados.

Ou seja, uma série de novidades que justificam a liderança do WebLogic no mercado de Application Servers. Mas ao olhar os próximos passos e o roadmap para as versões do WebLogic 12.1.3 e 12.1.4, há motivo de sobra para se interessar na versão 12c.

A versão WebLogic 12.1.3 deverá ser a primeira homologada para diversos produtos 12c do FMW como SOA Suite 12c. Além disso, alguns novos recursos serão incluídos para melhorar ainda mais a experiência do administrador de infraestrutura para escalar ambientes com mais servidores. Por exemplo, a feature de Elastic JMS permitirá o uso do Server Migration sem perder mensagens durante esta execução. Estamos trabalhando para oferecer na versão 12.1.4 o suporte para auto-scaling de clusters dinâmicos, com base em limites e métricas definidas pelo usuário. O WebLogic 12.1.4 também deverá ter uma API para controlar os clusters dinâmicos. Desta forma, os usuários poderão facilmente programar a hora de parar, iniciar ou remover nós de um cluster dinâmico.

O WebLogic 12c conta com o driver JDBC 12c, oferecendo melhor integração com o Oracle DB 12c, e uma destas features é chamada de "Application Continuity". Esta feature permite que após uma falha de comunicação com um nó de um Oracle RAC, a transação com o banco de dados seja transferida sem qualquer efeito colateral para outro nó do cluster, garantindo disponibilidade. Na versão WebLogic 12.1.4, será introduzido também um novo recurso chamado de Multitenant Applications. Desta forma usuários poderão definir um modelo WebLogic para uma aplicação, para um ou mais clientes desta aplicação, que terá o seu próprio cluster, etc.

O conteúdo acima foi originalmente postado aqui.

AVISO LEGAL: O texto acima visa delinear nossa direção geral dos produtos. Destina-se apenas para fins informativos, e não pode ser incorporado em qualquer contrato. Não é um compromisso e não deve ser usado na tomada de decisões de compra. O desenvolvimento, lançamento e tempo dos recursos ou funcionalidades descritos para os produtos da Oracle permanecem a critério exclusivo da Oracle.

Wednesday Nov 06, 2013

6 Facts About GlassFish Announcement

Since Oracle announced the end of commercial support for future Oracle GlassFish Server versions, the Java EE world has started wondering what will happen to GlassFish Server Open Source Edition. Unfortunately, there's a lot of misleading information going around. So let me clarify some things with facts, not FUD.

Fact #1 - GlassFish Open Source Edition is not dead

GlassFish Server Open Source Edition will remain the reference implementation of Java EE. The current trunk is where an implementation for Java EE 8 will flourish, and this will become the future GlassFish 5.0. Calling "GlassFish is dead" does no good to the Java EE ecosystem. The GlassFish Community will remain strong towards the future of Java EE. Without revenue-focused mind, this might actually help the GlassFish community to shape the next version, and set free from any ties with commercial decisions.

Fact #2 - OGS support is not over

As I said before, GlassFish Server Open Source Edition will continue. Main change is that there will be no more future commercial releases of Oracle GlassFish Server. New and existing OGS 2.1.x and 3.1.x commercial customers will continue to be supported according to the Oracle Lifetime Support Policy. In parallel, I believe there's no other company in the Java EE business that offers commercial support to more than one build of a Java EE application server. This new direction can actually help customers and partners, simplifying decision through commercial negotiations.

Fact #3 - WebLogic is not always more expensive than OGS

Oracle GlassFish Server ("OGS") is a build of GlassFish Server Open Source Edition bundled with a set of commercial features called GlassFish Server Control and license bundles such as Java SE Support. OGS has at the moment of this writing the pricelist of U$ 5,000 / processor. One information that some bloggers are mentioning is that WebLogic is more expensive than this. Fact 3.1: it is not necessarily the case. The initial edition of WebLogic is called "Standard Edition" and falls into a policy where some “Standard Edition” products are licensed on a per socket basis. As of current pricelist, US$ 10,000 / socket. If you do the math, you will realize that WebLogic SE can actually be significantly more cost effective than OGS, and a customer can save money if running on a CPU with 4 cores or more for example. Quote from the price list:

“When licensing Oracle programs with Standard Edition One or Standard Edition in the product name (with the exception of Java SE Support, Java SE Advanced, and Java SE Suite), a processor is counted equivalent to an occupied socket; however, in the case of multi-chip modules, each chip in the multi-chip module is counted as one occupied socket.”

For more details speak to your Oracle sales representative - this is clearly at list price and every customer typically has a relationship with Oracle (like they do with other vendors) and different contractual details may apply.

And although OGS has always been production-ready for Java EE applications, it is no secret that WebLogic has always been more enterprise, mission critical application server than OGS since BEA. Different editions of WLS provide features and upgrade irons like the WebLogic Diagnostic Framework, Work Managers, Side by Side Deployment, ADF and TopLink bundled license, Web Tier (Oracle HTTP Server) bundled licensed, Fusion Middleware stack support, Oracle DB integration features, Oracle RAC features (such as GridLink), Coherence Management capabilities, Advanced HA (Whole Service Migration and Server Migration), Java Mission Control, Flight Recorder, Oracle JDK support, etc.

Update 24-11-2013:  clustering support is available on WebLogic Enterprise and Suite editions.

Fact #4 - There’s no major vendor supporting community builds of Java EE app servers

There are no major vendors providing support for community builds of any Open Source application server. For example, IBM used to provide community support for builds of Apache Geronimo, not anymore. Red Hat does not commercially support builds of WildFly and if I remember correctly, never supported community builds of former JBoss AS. Oracle has never commercially supported GlassFish Server Open Source Edition builds. Tomitribe appears to be the exception to the rule, offering commercial support for Apache TomEE.

Fact #5 - WebLogic and GlassFish share several Java EE implementations

It has been no secret that although GlassFish and WebLogic share some JSR implementations (as stated in the The Aquarium announcement: JPA, JSF, WebSockets, CDI, Bean Validation, JAX-WS, JAXB, and WS-AT) and WebLogic understands GlassFish deployment descriptors, they are not from the same codebase.

Fact #6 - WebLogic is not for GlassFish what JBoss EAP is for WildFly

WebLogic is closed-source offering. It is commercialized through a license-based plus support fee model. OGS although from an Open Source code, has had the same commercial model as WebLogic. Still, one cannot compare GlassFish/WebLogic to WildFly/JBoss EAP. It is simply not the same case, since Oracle has had two different products from different codebases. The comparison should be limited to GlassFish Open Source / Oracle GlassFish Server versus WildFly / JBoss EAP.

But the message now is much clear: Oracle will commercially support only the proprietary product WebLogic, and invest on GlassFish Server Open Source Edition as the reference implementation for the Java EE platform and future Java EE 8, as a developer-friendly community distribution, and encourages community participation through Adopt a JSR and contributions to GlassFish.

In comparison

Oracle's decision has pretty much the same goal as to when IBM killed support for Websphere Community Edition; and to when Red Hat decided to change the name of JBoss Community Edition to WildFly, simplifying and clarifying marketing message and leaving the commercial field wide open to JBoss EAP only. Oracle can now, as any other vendor has already been doing, focus on only one commercial offer.

Some users are saying they will now move to WildFly, but it is important to note that Red Hat does not offer commercial support for WildFly builds. Although the future JBoss EAP versions will come from the same codebase as WildFly, the builds will definitely not be the same, nor sharing 100% of their functionalities and bug fixes. This means there will be no company running a WildFly build in production with support from Red Hat.

This discussion has also raised an important and interesting information: Oracle offers a free for developers OTN License for WebLogic. For other environments this is different, but please note this is the same policy Red Hat applies to JBoss EAP, as stated in their download page and terms. Oracle had the same policy for OGS.


GlassFish Server Open Source Edition isn’t dead. Current and new OGS 2.x/3.x customers will continue to have support (respecting LSP). WebLogic is not necessarily more expensive than OGS. Oracle will focus on one commercially supported Java EE application server, like other vendors also limit themselves to support one build/product only. Community builds are hardly supported. Commercially supported builds of Open Source products are not exactly from the same codebase as community builds.

What's next for GlassFish and the Java EE community?

There are conversations in place to tackle some of the community desires, most of them stated by Markus Eisele in his blog post. We will keep you posted.

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

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.


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


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:


Manifest-Version: 1.0
Created-By: 1.7.0_51
Permissions: sandbox 

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">
        <title>Java Detection</title>
        <vendor>Oracle Inc.</vendor>
        <jar href="JavaDetection.jar" />
          name="Java Detection Applet"
     <update check="background"/>

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


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


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.


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


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,

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


  1. Entre em 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/
  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.

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.

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!


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:

@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;
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:

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:
  public WebSocketEndpoint(QueueSenderSessionBean sb) {
     this.senderBean = sb;

Next step is to simply call the method inside onMessage

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:

  @MessageDriven(mappedName = "jms/myQueue")
  public class WebSocketMDB implements MessageListener {
    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:

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

    @WSJMSMessage     Event<Message> jmsEvent; 

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

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://' + + '/your-app-context-root/websocket');

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


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!


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


« May 2015