26 maio 2014

Java FAQ Brasil - Tudo o que você precisa saber


Com frequência recebo e-mails de clientes com dúvidas sobre "quando sairá a próxima versão do Java?", ou então "quando vai expirar o Java?" ou ainda "quais as mudanças da próxima versão?".

Por isso resolvi escrever o Java FAQ Brasil, respondendo estas dúvidas e muitas outras.

Para continuar lendo o FAQ, siga para o meu Oracle blog.

15 maio 2014

Oracle no TDC2014 Florianópolis

Este ano a presença da Oracle no The Developers Conference 2014 - Edição Florianópolis vai fazer a diferença! Sem contar que fomos até mencionados pelo Cacau Menezes, grande figura da região da Ilha da Magia. Vejam só o que ele disse em seu blog:
"Já pensou em controlar uma torneira de chopp via dispositivos móveis e ser avisado pelo Twitter quando você já tomou todas? Pois é, essa ideia se tornou realidade pelos profissionais da gigante tecnológica Oracle Bruno Borges (@brunoborges) e Marco Antonio Maciel (@marcomaciel)." - Cacau Menezes
Enfim, estaremos presente no evento com as seguintes palestras e trilhas:

Trilha Games - Quinta
15:40 - Como criar o game 2048 em JavaFX

Trilha Javascript - Quinta
17:40 - Nashorn: novo motor Javascript no Java

Trilha Java EE - Sexta
10:10 - Criando uma aplicação HTML5 com Java EE 7 e WebSockets

Trilha SOA & BPM - Sexta
15:40 - Integrando Oracle BPM com Java EE e WebSockets

Trilha Java - Sábado
10:10 - Migrando de Applets para JavaFX, e novos modelos de distribuição de aplicativos Java

Trilha Internet das Coisas - Domingo
15:40 - Controle de Eventos em Tempo Real através de Java Embarcado
17:40 - Tweet para cerveja! Torneira de chopp controlada por Java, JavaFX, e IoT!

Se você quiser saber mais sobre os palestrantes da Oracle que estarão presentes no evento, acompanhe o Giovani Bassan, o Marco Maciel, e o Bruno Borges (eu) no LinkedIn :-) E acompanhe no Twitter com a hashtag #TDC2014!



13 maio 2014

Test your website on JavaFX WebView

If you are building (or considering to build) a two-tier Java application that loads remote content from your webserver into a WebView component inside JavaFX, here's a quick and dirty Javascript code that you can use to test your website and make sure it is compatible.

To invoke, download the file browser.js and execute it on your command-line like the following example:
$ jjs -fx browser.js -- http://www.twitter.com/brunoborges


And if you liked this, you may want to check out the WebFX project as well. :-)

28 abril 2014

Git SSH over HTTP Proxy

If you are like me and you are using Linux behind an HTTP proxy, you will probably want to access GitHub and other Git remote repositories through SSH. For that to work, you will likely need to use some sort of utility that will enable you to connect to an SSH server through an HTTP proxy server.

To do that, you can use the connect-proxy command. The repository has no binary, so you will have to compile it on your own. But it is not hard if you are a good Linux user . If you run the install.sh script, you will end up with the binary at /usr/local/bin.

The last thing to do is to setup your SSH config file accordingly:

$ cat ~/.ssh/config

Host *
  ServerAliveInterval 30
Host *.amazonaws.com
  ProxyCommand connect-proxy -H proxy.myserver.com:80 %h %p
Host github.com 
  ProxyCommand connect-proxy -H proxy.myserver.com:80 %h %p 

Extra bonus: access to Amazon EC2 with SSH over HTTP Proxy.

If you know a better way to do this, please comment!

12 abril 2014

Had Heartbleed showed us a new business model for Open Source?

This is what I wrote on my Twitter the day I heard about Heartbleed:

Some say this bug is the worse bug ever found, affecting the Internet as a whole, since most servers have OpenSSL. With paid and closed source software, it is easy to blame someone. At some point, there are companies who prefer paid and closed source just because of that. But what about a Free and Open Source? Who is to be blamed about the issue? I would say there are three entities to be blamed for the Heartbleed bug, each with different weights:
  1. The developer who introduced the bug is the least to be blamed. Developers make mistakes, some big, some small. This one just happened to be a small bug but with a big consequence.
  2. The QA developer who didn't see the bug is the least to be blamed. A developer reviewing code. In the end, continues to be a developer mistake like in (1).
  3. The whole IT industry (companies and developers of all kind; FOSS or not) who uses OpenSSL for free but does not pay anything for it, and although being Open Source, don't look at it, don't review commits. Just expect it to work without bugs. These are the most to be blamed. (including myself)
As the article in my tweet above says:
Jackson also says a lesson to be drawn from the Heartbleed Bug is that "we as an industry have dramatically underinvested in software integrity and generally ignored, for a security perspective, the open source building blocks on which the Internet functions. Open source is everywhere. It is the foundation of all modern software applications."
So my question to you now is: if we, the IT industry, had put more investment into the OpenSSL development team, would the chances had been higher for the Heartbleed bug to be found? Being Open Source helps, of course, but if there is no incentive (or obligation) for people to look at it, to review the code, then most people won't look at it and instead, just use it for free. This is what happened. All companies and developers are to be blamed.

Should we consider  a different business model for Open Source software? What about a model where a company (not individual) willing to use an Open Source software has to either:

  • pay for a license and/or subscription support;
  • provide resources (developers and/or QA) dedicated to the software itself;
  • discount on license/support based on contributions;
Is it time for a new business model for Open Source?
What are your thoughts?

UPDATE #1 13/04/2014
A headline on Slashdot shows that Apple is far from supporting Open Source. The news says:

Apple bundles software from the Apache Software Foundation with its OS X operating system, but does not financially support the Apache Software Foundation (ASF) in any way.

Isn't time for Open Source foundations such as Apache or Eclipse, charge for the use of their Open Source projects by companies who profit from these projects? Consider "charge" as either through money, contribution, or developers paid by these companies to work on these Open Source projects.

UPDATE #2 13/04/2014
Here is another blog post titled "Heartbleed, an ASL business model failure?" by Bruno Lowagie, original author of iText, covering similar ideas I wrote above.

UPDATE #3 14/04/2014
Interesting article aobut the weakenesses of Open Source: "Heartbleed and the misconceptions about Open Source". Here's a quote:

As Heartbleed showed, even mission critical software used by a large portion of the Internet does not necessarily have the resources to be professionally maintained. The OpenSSL team receives only about $2000 yearly in donations.

08 abril 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!.

O que você precisa fazer para concorrer no IoT Developer Challenge?
Tudo o que você precisa fazer é criar um projeto, bolar um vídeo e publicar o código-fonte deste projeto utilizando a tecnologia Java Embedded da Oracle, com foco em IoT: Internet of Things, com placas de embarcados como Raspberry Pi e similares, dispositivos, sensores, etc.

Quais os prêmios?
Na categoria profissional:
3 times ganharão uma viagem para o JavaOne. Três membros de cada time vencedor ganhará a entrada para o JavaOne 2014, e mais US$ 2.000,00 para custear até 4 noites de hotel e também as passagens de avião. (outras despesas como alimentação e transporte não serão custeadas).
Na categoria estudante: 

  • 1º lugar: 3 membros do time vencedor ganharão cada, a entrada para o JavaOne e mais US$ 2.000,00 para custear passagens e (até) 4 noites em hotel.
  • 2º lugar: 3 membros do time vencedor ganharão cada, um laptop e um voucher para certificação Oracle com valor total de até US$ 1.500,00
  • 3º lugar: 3 membros do time vencedor ganharão cada, um laptop e um voucher para certificação Oracle com valor total de até US$ 1.300,00



Data Limite para Enviar
O período para enviar a sua criação termina no dia 30 de Maio de 2014.

Quer saber mais?
Se você quiser saber mais, não deixe de ler o FAQ do IoT Developer Challenge.

Precisa de ajuda?
Se precisar de uma ajudinha para criar um projeto legal, confira a página do IoT Developer Challenge. Vários webinars foram publicados. E tem até alguns exemplos de códigos!

JavaOne 2014 de graça? Com viagem e hotel pagos! :-D
Assim fica fácil ir no JavaOne e curtir toda a experiência desta grande conferência! Se você precisar de ajuda, seguem alguns videos e tutoriais para ajudar neste desafio!


Outra forma de gastar menos para ir ao JavaOne: seja um palestrante!
E se você achar que dá muito trabalho criar um projeto tão maneiro, com tecnologias tão recentes, sobre um tópico tão quente como Internet of Things, tudo bem! Outra forma de economizar, pelo menos no preço da entrada para o JavaOne 2014, é sendo um palestrante. Estes seres iguais a nós desenvolvedores, que apenas querem apresentar algo interessante e legal, e que pode ser muito útil para muitos outros desenvolvedores, ganham acesso para a conferência (passagem e hotel não incluídos).

Você tem exatamente uma semana para enviar uma palestra, pois o Call for Papers encerra no dia 15 de Abril. Bola rápido um tema bacana, e proponha sua palestra!

31 março 2014

JavaFX version of the 2048 game

I've been "busy" this weekend doing several things. But nothing more important than playing the addictive game 2048 (web javascript version). After several hours few minutes playing with it on my phone, I decided to write a JavaFX version called Fx2048. Gabriele Cirulli has published the source code on GitHub in his repository, so you can learn how to code a game like this in any platform!



Now why a JavaFX version? Well, why not? But I will give you a few reasons for you to look into Fx2048:

  • opportunity to learn Java SE 8
  • learn Lambda expressions
  • learn Stream API
  • learn JavaFX 8
  • learn JavaFX CSS basics
  • learn JavaFX animations
There you go! A simple project that will teach you all that :-)

Have fun!

PS: a few bugs to solve and features to implement, but feel free to pull request!

29 março 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.



And if you want to collect all that to a list instead of printing to standard output, replace the last forEach call with collect(Collectors.toList()); and assign a variable.

26 março 2014

Migrating JDBC Resources from GlassFish to WebLogic

Following up with my series of articles about Migrating from GlassFish to WebLogic, this time I want to cover the migration of a very common resource used by every Java EE developer: JDBC resources, or simply, DataSources. And in case you haven't read yet the first article, here it is: Migrating a Java EE App from GlassFish to WebLogic. That one will walk you through redeploying a simple yet almost complete Java EE 6 application on WebLogic, without any code change nor specific deployment descriptors, and still taking advantage of the enhanced Maven Plugin in WebLogic 12c.

It is easy to migrate resources by using the Web consoles of both WebLogic and GlassFish. Just open one browser window for each server, put them side-by-side, and follow the UI menus. Most of the properties are the same. But if you walkthrough the full article below, you will not only learn the concepts and what is required to migrate JDBC resources, but also how to migrate things using Command-line Interface (asadmin from GlassFish; wlst from WebLogic). So in order to understand what I'm doing here, I strongly recommend you to read, at least the introduction of, these two docs below in case you are not familiar with asadmin or wlst:


Oracle WebLogic Types of JDBC Data Sources

WebLogic offers three types of DataSources. For this migration, the type we will use will be "Generic". To know more about each type, click on the links below:

  • Generic Data Source
    • the type you are most familiar with; we will focus on this one
  • GridLink Data Source
    • in case you have an Oracle RAC Database, this is an optimal data source with HA and Failover features
  • Multi Data Source
    • abstracts two or more Generic Data Sources; works like a 'pool of data sources' so you can use it for either failover or load balancing


JDBC Resources: DataSources and Connection Pools

In the first article this was sort of covered from a Java EE Standard point of view. I simply took advantage of the @DataSourceDefinition annotation type, which allows developers to define JDBC DataSources directly from the Java source code, and requires no vendor-specific deployment descriptors nor manual previous configuration of the application server.

Now in case you have a legacy application or you are not using @DataSourceDefinition, you will be required to migrate these resources by hand. This will require three (plus one optional) simple steps:

  1. List JDBC resources from a GlassFish domain
  2. (optional; see below) Install 3rd-party JDBC drivers in WebLogic
  3. Extract and convert relevant and required information by WebLogic
  4. Create datasources inside WebLogic
Oracle WebLogic 12c already comes with JDBC drivers for Oracle DB 11g, MySQL 5.1.x, and Derby DB, so you won't need to do anything for these databases. For more information, read the docs JDBC Drivers Installed with WebLogic Server. In this doc you will also learn how to update the versions already provided by WebLogic, for example if you want to take advantage of the new features in Oracle DB 12c

If you are using Microsoft SQL Server, PostgreSQL, or any other database, check the Setting the Environment for a Thirdy-Party JDBC Driver for more information on how to install these drivers.

Concepts of JDBC Resources

We should also learn one difference between the concept of JDBC Resources in GlassFish 3 versus WebLogic 12c. In GlassFish, there are two types of JDBC Resources:
  • JDBC Connection Pools
  • JDBC Resources (aka DataSources)
On the other hand, WebLogic treats JDBC Resources as one single thing: Data Sources. The connection pool is part of the data source definition where in GlassFish, the Data Source is a separate artifact, which allows enabling/disabling the object, and also provides the JNDI name to a specific Connection Pool. In few words, when migrating a data source from GlassFish to WebLogic, you will only care about the JDBC Connection Pool and the JNDI name given at the JDBC Resource item.

Listing JDBC Resources from a GlassFish domain

First, let's list all JDBC Resources (datasources) in our GlassFish server. Connect with asadmin and execute the list-jdbc-resources command:

asadmin> list-jdbc-resources
jdbc/__TimerPool
jdbc/__default
jdbc/gf2wls
Command list-jdbc-resources executed successfully.

Let's focus on our example: the jdbc/gf2wls datasource. This will be the DataSource we will migrate from GlassFish to WebLogic. Now let's list all Connection Pools in this GlassFish domain by using asadmin list-jdbc-connection-pools:

asadmin> list-jdbc-connection-pools
__TimerPool
DerbyPool
mysql_gf2wls_gf2wlsPool
Command list-jdbc-connection-pools executed successfully.

Now of course in case you have dozens of connection pools created in your GlassFish domain, it would be easier to issue a command that shows you which connection pool is associated to the Data Source you want to migrate. To do this, let's use the asadmin get command:

asadmin> get resources.jdbc-resource.jdbc/gf2wls.*
resources.jdbc-resource.jdbc/gf2wls.enabled=true
resources.jdbc-resource.jdbc/gf2wls.jndi-name=jdbc/gf2wls
resources.jdbc-resource.jdbc/gf2wls.object-type=user
resources.jdbc-resource.jdbc/gf2wls.pool-name=mysql_gf2wls_gf2wlsPool

We not only got which connection pool is associated to this data source but also its JNDI name, because the name of the resource may not be exactly the same as the JNDI name. 

Extracting GlassFish's JDBC Connection Pool data

Next step is to get all properties of your Connection Pool. Let's issue the asadmin get command again:

asadmin> get resources.jdbc-connection-pool.mysql_gf2wls_gf2wlsPool.*
resources.jdbc-connection-pool.mysql_gf2wls_gf2wlsPool.property.portNumber=3306
resources.jdbc-connection-pool.mysql_gf2wls_gf2wlsPool.property.serverName=localhost
resources.jdbc-connection-pool.mysql_gf2wls_gf2wlsPool.property.databaseName=gf2wls
resources.jdbc-connection-pool.mysql_gf2wls_gf2wlsPool.property.User=gf2wls
resources.jdbc-connection-pool.mysql_gf2wls_gf2wlsPool.property.URL=jdbc:mysql://localhost:3306/gf2wls?zeroDateTimeBehavior=convertToNull
resources.jdbc-connection-pool.mysql_gf2wls_gf2wlsPool.property.driverClass=com.mysql.jdbc.Driver
resources.jdbc-connection-pool.mysql_gf2wls_gf2wlsPool.property.Password=gf2wls
Command get executed successfully.

Easy, isn't? Now, let's focus on the minimum required properties we need to create this DataSource in WebLogic 12c. They are under resources.jdbc-connection-pool.mysql_gf2wls_gf2wlsPool.property.* , so if you want to list only these, change the asadmin method above to the following: asadmin get resources.jdbc-connection-pool.mysql_gf2wls_gf2wlsPool.property.*

Create the Data Source in WebLogic using WLST

To help you witht he final step, I've created a sample WLST script to create a Data Source in WebLogic. In this script, there are a few variables you must define. To call this script, go to your WebLogic installation directory and, if you are on Linux, call $ source setDomainEnv.sh (or the proper script for your environment). Then execute the WLST script: $ java weblogic.WLST ds_gf2wls.py

You should see the following output:

$ java weblogic.WLST ds_gf2wls.py
Initializing WebLogic Scripting Tool (WLST) ...

Welcome to WebLogic Server Administration Scripting Shell

Type help() for help on available commands

Connecting to t3://localhost:7001 with userid weblogic ...
...
Starting an edit session ...
Started edit session, please be sure to save and activate your 
changes once you are done.
Saving all your changes ...
Saved all your changes successfully.
Activating all your changes, this may take a while ... 
The edit lock associated with this edit session is released 
once the activation is completed.
Activation completed

That's it. Check your WebLogic Console, by going to the Data Sources page.

Extending and improving the migration process

Now you may be wondering how to improve the process by automating everything, right? Yes you can do that! Since we have been using CLI commands, it all depends now on you by tweaking and coding some bash scripts. For example, you can use asadmin to get the information of all Data Sources, generate a bunch of files, use sed to, you know, hack the output files, then loop through them and call a more dynamic WLST script. If you want to read files from WLST, here's a fragment you can use:

from java.io import FileInputStream

propIS = FileInputStream("MyGFDS.properties")
configDS = Properties()
configDS.load(propIS)

dsName=configDS.get("dsName")
dsFileName=configDS.get("dsFileName")
dsDatabaseName=configDS.get("dsDataBaseName")
datasourceTarget=configDS.get("datasourceTarget")
dsJNDIName=configDS.get("dsJNDIName")
dsDriverName=configDS.get("dsDriverName")
dsURL=configDS.get("dsURL")
dsUserName=configDS.get("dsUserName")
dsPassword=configDS.get("dsPassword")
dsTestQuery=configDS.get("dsTestQuery")

Migrating Advanced Settings

If you want to migrate advanced settings of the Connection Pool, take a look at the full list of properties I extracted from GlassFish in my sample Data Source. To change for example the Max Pool Size, tweak the WLST script and add the following:

dsMaxPoolSize=25

cd('/JDBCSystemResources/' + dsName + '/JDBCResource/' + dsName + '/JDBCConnectionPoolParams/' + dsName)
cmo.setMaxCapacity(dsMaxPoolSize)

Again, you can do whatever you want in WLST.

There you go! If you come up with a super awesome script to automate the whole process, let me know!

03 março 2014

Migrating a Java EE App from GlassFish to WebLogic

WebLogic is Oracle's strategic application server for the Java EE Platform. Since Oracle decided to focus on it for commercial support, and decided to leave GlassFish free of any ties with commercial decisions, I decided to bring this type of content to help GlassFish customers as well users to experiment, try, and evaluate Oracle WebLogic 12c (Java EE 6 certified).



But before getting down to the migration part, first thing you should learn is How to Install WebLogic 12c. For this migration tutorial in a developer environment, we will be using the Developer installation, but for production environments, we recommend the Full installation.

Full Installation
For full installation that can be used either in a production environment or in a developer environment, download the WebLogic Generic Installer and follow the steps descriped in the documentation for 12.1.2 on how to install WebLogic.

The difference between full and dev, is that full is targeted for any environment, and dev is well, for developers only. Oracle always recommend the full installation, but usually and specially for Java EE applications in a dev environment, the Development installation is enough. The good thing about it is the download size: less than 200Mb, and still you also get Oracle Coherence to play with. By the way, there is no licensing requirements for development purposes (either full or dev install), because WebLogic (and other Oracle products) are free for developers.

Required software

For this series of Migrating from GlassFish to WebLogic, I will be using NetBeans 8.0, GlassFish 3.1.2.2Oracle JDK 7, Oracle MySQL Community 5.6, and WebLogic 12.1.2. So make sure you have that software (except WLS for now) installed and configured in your system.

Developer Installation of WebLogic 12c

Let's get started by first installing WebLogic 12c for Developers. Instructions here are for Linux, but it is not that much different for Windows or Mac.
  1. Download WebLogic 12c ZIP Distribution for Developers (latest version: 12.1.2)
  2. Unzip it somewhere, for example:
    $ unzip wls1212_dev.zip -d /opt
  3. Go into the newly created directory
    $ cd /opt/wls12120
  4. Let's unpack the JAR files that were optimally compressed with pack200
    $ sh configure.sh    // for Windows, call configure.cmd
  5. After the uncompression, configure script will ask you if you want to create a new domain. Say "yes" by pressing 'y', then [enter]
  6. Provide a username, a password, and then confirm again the password
  7. Wait for the domain to be created and started
In just a few minutes you will have WebLogic installed, configured, and running!

Test your WebLogic 12c Developer Installation

At this point, you should have a WebLogic domain configured, up, and running. You can access the Admin Web Console at the following URL: http://localhost:7001/console. It will ask for username/password you typed during install. Take a moment to explore the Admin Console. You can find more information at the official documentation for 12.1.2.

You may also find very useful to know you can manipulate all domain settings through the WebLogic Scripting Tool, a command-line interface for you to code in Python, and issue commands to view and edit all settings. In an upcoming version of WebLogic we will also provide a REST interface.

I will use WLST in the next posts in this series, so maybe you want to read more later.

How to Start/Stop WebLogic 12c

In order to start and stop correctly your WebLogic domain, you can either do that from an IDE such as NetBeans, or by running specific scripts. These scripts are located under the following path location:

/opt/wls12120/user_projects/domains/mydomain/bin
  • $ sh startWebLogic.sh
  • $ sh stopWebLogic.sh

The Beauty of Java EE 6

Now, instead of going through the process of creating a Java EE application, I coded a small application that covers a large set of Java EE 6 APIs and pushed it to this GitHub repository. It is an application using the following APIs:
  • CDI 1.0
  • JSF 2.1
  • Bean Validation 1.0
  • EJB 3.1
  • JPA 2.0
  • JAX-WS 2.2
  • JAXB 2.2
  • JAX-RS 1.1
The beauty of Java EE is that you will learn from this migration how good it is when you follow standards, and also the value of the platform. Simply put: we will migrate this application without touching any code. At least not for now. Let's first set some infrastructure requirements. For now, we must have a database.

JPA and Database setup

To facilitate things, and before you can run this application, make sure you have MySQL installed and running on localhost, and with a database named gf2wls with username/password gf2wls with all privileges. The project comes with a drop-and-create configuration when JPA (through EclipseLink) is initialized.

To setup this, connect as root to your local MySQL server and issue the following two commands:
  1. $ mysql -u root -p
  2. mysql> create database gf2wls;
  3. mysql> grant all privileges on gf2wls.* to gf2wls@localhost identified by 'gf2wls';
And you are set!

Import project to NetBeans, setup MySQL driver, and run it on GlassFish 3.1.2.2

Since this is an article about migrating from GlassFish to WebLogic, I will assume you know how to get this application running on GlassFish 3.1.2.2 from NetBeans. But I will provide some highlights to make it work smoothless.



In order for the @DataSourceDefinition entry inside class InitializeSampleDataSessionBean work fine and connect to your MySQL database in GlassFish, make sure you have copied MySQL JDBC Driver into glassfish3/glassfish/domains/domain/domain1/lib/ext/ of course, before starting it up. In WebLogic, you don't need to do this since MySQL Connector/J is already part of the default installation.

Download the project 'bookmark-javaee6' to your local machine by either cloning the GitHub repository locally, or by downloading the zip and extracting somewhere. This is an Apache Maven project, so don't worry about environment. Just make sure you have this project up and running on a GlassFish domain.

Import the project bookmark-javaee6 into your NetBeans environment. Right click on bookmark-javaee6 project and select Run. Test the application by going to http://localhost:8080/bookmark-javaee6.

You should by now looking at the following screen:


Test the Bookmark WebService with a simple client

The sample Bookmark application comes with a JAX-WS WebService.

  1. You can test this WebService in many ways, but I will give you three main options: one is to try SoapUI
  2. Another option is to right click on the WebService in NetBeans, and select Test WebService
  3. Last option is to run the bookmark-javaee6-wsclient that comes with JUnit Test Cases. 
Make your choice, and see it working!

Running the sample Java EE 6 application in WebLogic 12c

Before we go to a pure Maven description on how to do this, let's give NetBeans a try. Now that you have everything ready (a Java EE 6 application running on GlassFish 3.1.2.2), with source code as a Maven project in NetBeans, let's add WebLogic as a Server to it.

  1. Go to the Services tab in NetBeans, and right click in Servers, then select Add Server....
  2. Select Oracle WebLogic Server
  3. Insert the path location of your recently installed WebLogic server. Remember to select the subfolder wlserver. If you installed as described in the beginning, you should try /opt/wls12120/wlserver
  4. Type your username and password of your WebLogic domain
  5. Finish this wizard
Now we must change from GlassFish to WebLogic in Project Properties. Select bookmark-javaee6 project and right click on it. Go to Run and select your newly created WebLogic 12.1.2 server. Press OK. See the picture below to understand what has to be done:



Start your project by right clicking in it, and select Run! Test your application running on WebLogic by going to the following location: http://localhost:7001/bookmark-javaee6


In case you had any problem, try these two articles:


Success! You have now the same application running on WebLogic 12c! Without any code change!

WebLogic understands GlassFish Deployment Descriptor

I haven't mentioned this before because I wanted you to see the sample application up and running on WebLogic, but what you can do in this application is to remove src/main/webapp/WEB-INF/weblogic.xml, and change the context-root inside glassfish-web.xml. What will happened if you redeploy this application without weblogic.xml, is that the application will start just fine, but in a different context-root: the one you typed inside glassfish-web.xml.

The reason for this is well documented on Support for GlassFish Deployment Descriptors. Give it a look in case you want to know what else does WebLogic understands from GlassFish's DD.

Now, let's try something different. Let's now use pure Apache Maven to compile and run the application on your WebLogic installation! For that, we will first need to configure the plugin.

Configuring the WebLogic Development Maven Plugin

Before you can use the plugin, you must install it in your local or remote Maven repository. Feel free to follow official instructions for WebLogic 12.1.2. But in case you want to just get it done, here's the short version:

  1. Go to your WLS installation. It is probably located here:
    /opt/wls12120
  2. Now change to the following directory:
    $ cd oracle_common/plugins/maven/com/oracle/maven/oracle-maven-sync/12.1.2 
  3. Issue the following command to sync WLS Maven Plugin into your local repository:
    $ mvn com.oracle.maven:oracle-maven-sync:push -Doracle-maven-sync.oracleHome=/opt/wls12120/oracle_home/.
You have now successfully installed WLS Maven Plugin. To validate the installation, type:
$ mvn help:describe -DgroupId=com.oracle.weblogic-DartifactId=weblogic-maven-plugin -Dversion=12.1.2-0-0

To continue, let's configure the plugin onto our bookmark-javaee6 sample application, and then deploy the package into WebLogic
  1. Open the POM file of bookmark-javaee6 project
  2. Uncomment the WebLogic Maven Plugin definition
  3. Make sure to enter the same username and password as your domain when you installed and configured WebLogic
  4. Make sure WebLogic is running
  5. Make sure there's no other bookmark-jaavaee6 project deployed on your WebLogic instance
  6. Execute the following command:
    $ mvn package pre-integration-test
  7. Check your logs and try http://localhost:7001/bookmark-javaee6!

Conclusion

As you could see, if you are working with a Java EE 6 project 100% standardized, and perhaps Maven, you will find no problems at migrating this project to WebLogic 12c. In fact, if you are using Maven it will be as simple as adding a new plugin just to facilitate deployment. But even this you won't have to do in case you have a binary only. Just open the Admin Web Console, and fire a deployment from there!

And by the way, WebLogic is not that heavyweight and unproductive application server developers thought it still is. For more information about Developer Productivity with WebLogic 12c, read my entry "WebLogic in Comparison: RebelLabs and the Java App Server Debate".

Caveats for Java EE projects, road ahead for migrations

In the next blog posts of this series, I will cover how to work around some common issues when your project is not exactly following, or taking advantage of all standards defined in the Java EE 6 platform, or simply using extra features, customizations of GlassFish.

Here's a sneak peek of what's coming next:
  • How to Migrate JDBC DataSources from GlassFish to WebLogic
  • How to Define, Deploy, and Use JMS resources
  • How to Migrate JMS resources from GlassFish to WebLogic
  • How to Add and Isolate (classpath of) 3rd-party libraries (for example PrimeFaces)
And many more things to come!
  • Applying a GlassFish Domain Topology to a WebLogic Domain (clustering, etc)
  • Migrating Security Realms
  • Migrating Custom Login Modules
If there's any other subject you'd like to see, please post a comment!

Cheers!

24 janeiro 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 RaspberryPi promovido 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.

15 janeiro 2014

Banco do Brasil e o Java SE 7u51

A nova atualização do Java está mais segura, e bloqueia por padrão os Applets que não estão devidamente assinados ou configurados. Todas as informações sobre como adequar os applets já foram fornecidas pela Oracle há alguns meses atrás. Mudanças no Java SE 7u51 para Applets e Web Start.

Para clientes do Banco do Brasil que atualizaram para o Java SE 7u51, existem duas soluções: 


- aguardar o Banco adequar seus Applets para funcionarem corretamente com a nova versão, ou... 

- configurar o endereço do Banco na nova funcionalidade de "Lista de Exceção de Sites".

IMPORTANTE

Não reduza o nível de segurança para "Médio". Este nível permitirá que Applets maliciosos possam ser executados no seu computador, e danificar o sistema, ou roubar dados. Dê preferência para o uso da função "Lista de Sites de Exceção".

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. 

O processo é simples. Siga estes passos para Windows, mas para Mac OS X o procedimento é o mesmo, exceto a parte de como abrir a tela de Configuração do Java:

  1. Vá ao Painel de Controle do Windows e clique 2 vezes no ícone Java
  2. Na janela que abrir, clique na aba Segurança
  3. Clique no botão Editar Lista de Sites
  4. Clique no botão Adicionar
  5. Agora digite no campo os seguintes sites (um por vez): 
    • Pessoa Física: https://www2.bancobrasil.com.br/  
    • Pessoa Jurídica: https://aapj.bb.com.br/ 
    • Verificador do Plugin do BB: https://cva.bb.com.br/
  6. Clique em OK até sair do painel de controle do Java
  7. Entre novamente no site do BB e tente novamente
PS: dica do Marcelo Breitenbach no Facebook

Para outros bancos e sites que requerem o uso do Java, o procedimento é o mesmo. O importante é saber qual o Endereço do Site para colocar na Lista de Exceção. Escrevi com maiores detalhes sobre este processo, e como configurar para outros sites, no meu Blog da Oracle: Novo Java 7u51 e os Internet Banks no Brasil

13 janeiro 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

08 janeiro 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 configure.sh (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 configure.sh 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 startWebLogic.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 netbeans.org 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 theOracle 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 withOracle 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 :-)
Contato

Email:bruno.borges(at)gmail.com

LinkedIn: www.linkedin.com/in/brunocborges
Twitter: www.twitter.com/brunoborges
Comprei e Não Vou
Rio de Janeiro, RJ Brasil
Oracle
São Paulo, SP Brasil