Saturday, February 27, 2010

Sending E-mails with JavaMail on Glassfish V3

One of the main advantages of using an application server like Glassfish is to keep your application free of complex code, such as 1) manual control of database transactions; 2) database access configuration; 3) security authentication and authorization; 4) sending and receiving e-mail messages, among many other complexities that are non-functional requirements, consuming the time we would be spending on functional requirements.

In my opinion, an important differential of Glassfish V3 is its very rich and complete administration console. It is easy to use and to learn, which is, in my opinion, one of the most important competitive advantages, since it contributes to reduce the maintenance cost, a constant headache for system administrators. We have used the administrative console in a previous post to configure a database connection to PostgreSQL. Now, we are going to use it again in order to configure a JavaMail resource for applications that aim to send emails.

Follow the steps below:
  1. enter in the administrative console (http://[server-name]:4848/).
  2. go to Resources / JavaMail Sessions.
  3. create a new JavaMail session and set the following mandatory properties:
    JNDI Name: mail/[email-account-name]
    Mail Host: [smtp-server-address]
    Default User: the username to authenticate on the smtp server
    Default Return Address: the address used by recipients to reply the message. Some servers require that this address should be the one used by the authenticated user to access his mailbox.
If the server doesn't request secure authentication, then the three steps above are enough to start using the new JavaMail session, but a server without secure authentication is a very rare case nowadays. You will certainly need to inform a password to login on the smtp server. In most cases, the server administrator also changes the default port of the smtp server, which forces us to explicitly inform the correct port. For these special needs we can use additional properties in the JavaMail session. Follow the steps below:
  1. Still on the JavaMail session form, go to the Additional Properties section and add 3 more properties, which are:
    mail.smtp.port: [port-number]
    mail.smtp.auth: true
    mail.smtp.password: ****** ;)
  2. Click on Save to create the JavaMail session.
The last step is how to use this new JavaMail session in our applications to send emails. Using the JNDI name, we are going to inject the JavaMail session in a Java class, which could be a POJO of a pure web application, an EJB Session Bean, or any other type of class. See the code below for details:

public class UserAccountBsn {
  @Resource(name = "mail/[email-account-name]")
  private Session mailSession;

  public void sendMessage(UserAccount userAccount) {
    Message msg = new MimeMessage(mailSession);
    try {
      msg.setSubject("[app] Email Alert");
      msg.setRecipient(RecipientType.TO,
        new InternetAddress(userAccount.getEmail(),
        userAccount.toString()));
      msg.setText("Hello "+ userAccount.getName());
      Transport.send(msg);
    }
    catch(MessagingException me) {
      // manage exception
    }
    catch(UnsupportedEncodingException uee) {
      // manage exception
    }
  }
}

The @Resource annotation receives the JNDI name of the JavaMail session and injects an instance of the session in the variable mailSession. This variable is used within the sendMessage method to create a new MimeMessage. The content of the message is built and finally sent to the recipient by the method Transport.send. The method receives as parameter an entity class representing an user registered on the application. It is so simple, isn't it? ;)

Using this feature, we avoid any additional implementation to add those parameters hardcoded or parameterized, saving a lot of time, simplifying the maintenance of the applications, and reusing existing resources naturally shared by the container.

Friday, February 26, 2010

Creating a Connection Pool to PostgreSQL on Glassfish V3

I recently created a new connection pool to PostgreSQL on Glassfish and I would like to share the steps I followed with you. Obviously, you need PostgreSQL and Glassfish installed on your machine and a database already created in PostgreSQL. If you didn't configure your new PostgreSQL installation yet, follow the steps I described at this previous post and come back here to continue with the connection pool. The necessary steps are:
  1. We need the PostgreSQL JDBC Driver, since Glassfish and its deployed applications are writen in Java. Drivers are available for download at http://jdbc.postgresql.org. For this experiment choose the JDBC4 driver.
  2. Download the driver file postgresql-<version>.jdbc4.jar and copy it to the diretory [glassfish_home]/glassfish/domains/domain1/lib/.
  3. Restart Glassfish in order to make it load the new database driver. I thought that adopting an OSGI architecture Glassfish would never need restarts again, but I was wrong. At least, the restarting process is faster than V2.
  4. Enter in the administration console and go to Resources/JDBC/Connection Pools.
  5. Create a new connection pool with the name [database_name]Pool, select the resource type javax.sql.ConnectionPoolDataSource, select the database vendor PostgreSQL and click next.
  6. Select the datasource classname org.postgresql.ds.PGConnectionPoolDataSource and inform the following additional properties:
    DatabaseName=[database-name]
    Password=******* ;)
    PortNumber=5432 (this is the default port but make sure that you are using the correct one)
    ServerName=[server-name|ip]
    User=<database-username>
  7. Click Finish to save the new connection pool.
  8. Go to the list of connection pools again and select the new one that you just created.
  9. Click on Ping to check if the connection was correctly configured. The message "Ping Succeeded" means that the connection is working fine.
  10. In order to be able to use this connection pool in JEE applications, we have to create a JNDI name for it. Go to Resources/JDBC/JDBC Resources.
  11. Click on New and set the JNDI Name jdbc/[database_name], select the connection pool created above and click Ok to finish. This JNDI name will be used by applications to access the PostgreSQL database.
These instructions may work with Glassfish V2 as well, since its database configuration is quite similar.

I'm being very specific in terms of chosen technologies, but if you have a slightly different configuration and these steps are not working yet, please comment your issues below, describing also your current configuration/context. Maybe, we can figure it out.

Monday, February 22, 2010

Jamie Oliver for the Peace Nobel Prize

Last year Mr. Obama won the Peace Nobel Prize. There was a lot of controversy about this prize because the president of the United States didn't do anything concrete to bring peace to the world. I, particularly, didn't like the Nobel commission's choice for this prize. So, in order to fix this hasty decision, I would like to suggest a name for 2010: Jamie Oliver, the famous British chef! What???

Jamie figured out that he can actually change the world by changing people's eating habits. His mission statement seems really touching, inspiring and reachable actually.
“I wish for your help to create a strong, sustainable movement to educate every child about food, inspire families to cook again and empower people everywhere to fight obesity.”

Doing this, Jamie could save millions of lives all over the world reducing the obesity statistics and, consequently, making people feel really happy for doing something definitively useful, which is: feed people. Watch his message in this video below. It is more than convincing, it's touching.



You may think I'm exaggerating, but I'm not. I'm 31 years old and I started to cook at 30, less than 1 year ago. I know by a matter of fact what Jamie is trying to say. I know how good cooking means for mental health :D. If you have a family to care about and you go to the kitchen with the mission to feed them, you see exactly your importance in other people's life cycle in the simplest way possible. That's why cooking is worth experiencing.

These two pictures below show two of Jamie's recipes that we have made at home and they are simply amazing.
Poulet et Poireaux Stroganoff

Côtelettes D'Agneau Grillées Avec Une Riche Salsa

Look at the details about Jamie's plan here and start helping him to accomplish this by just spreading the wonderful art of cooking. If somehow you are not motivated enough, watch the movie Julie & Julia and you will be sufficiently motivated. Trust me! ;)

Tuesday, February 9, 2010

Did Oracle Regret about Kenai Ultimatum?

All Kenai Project Leaders received a message from Oracle trying to explain a possible misunderstanding about the message they transmitted before. From my understanding there is no misunderstanding, but a change of plans due to the community reaction. Take a look at the open letter below:

Gentlepeople,

In an effort to get information out to the Kenai community quickly, while trying to manage the integration of our two companies, I think we did a poor job at communicating our plans for Kenai.com to you. I would like to remedy that now. Our strategy is simple. We don't believe it makes sense to continue investing in multiple hosted development sites that are basically doing the same thing. Our plan is to shut down kenai.com and focus our efforts on java.net as the hosted development community. We are in the process of migrating java.net to the kenai technology. This means that any project currently hosted on kenai.com will be able to continue as you are on java.net. We are still working out the technical details, but the goal is to make this migration as seamless as possible for the current kenai.com projects. So in the meantime I suggest that you stay put on kenai.com and let us work through the details and get back to you later this month.

Thanks for your feedback and patience.

Ted Farrell
Oracle Corporation
Reference: http://blogs.sun.com/projectkenai/entry/the_future_of_kenai_com

That's pretty good! It is the first signal that Oracle is willing to listen to the community. I'm happy with that because it was a constructive decision, good for both sides. However, a question remains: Will current java.net projects migrate to Kenai infrastructure or will Kenai projects migrate to java.net infrastructure? I'm asking that because the Kenai infrastructure is far better. A migration to java.net infrastructure is actually a downgrade.

It seems we have to wait until the end of February to finally get an answer. I can't wait for that! ;)

Sunday, February 7, 2010

Good Ideas for Kenai That Somebody Else Should be Doing Instead

As you already know, Oracle is planning to deactivate Kenai for community developers. Yes, it is sad but let's move on and spread our code before it is destroyed. It is also time to make public some ideas I've been sharing with Sun's folks last year. I have criticized Oracle for some decisions they have made, that's true, but I don't want to criticize and shut up. I have to propose something better and realistic to show that they are lazy thinkers, growing by buying other people's innovation, not actually doing their own.

I want to discuss 2 ideas. Each one solves a particular need of entrepreneur developers.
  1. I need integrated services to manage my software project and also to deploy it: It would be a mix of SourceForge with Amazon EC2, or Assembla with Google App Engine. Once my code is committed to the server and an integration test is performed, then my application would be automatically deployed in a server. Today, we need at least two different service providers to make it happen and it means more bureaucracy and waste of time. If Oracle or RedHat adopts something like this, the payment for such services would financially support their open-source projects, such as OpenSolaris, Glassfish, JBoss and MySQL.
  2. I'm an expert in my own open-source product, but I need help with its infrastructure: I have a complex and large JEE5 application and my expertise allows me to provide good support in terms of application features and bug fixing. As a matter of fact, my application is using Glassfish as application server and MySQL as database. However, all I know about these technologies are enough to develop and deploy the application. If a critical error occurs, avoiding the application to run because of an external and unexpected problem, probably my own knowledge is not enough. In order to solve that, Oracle or RedHat would make a partnership with developers, providing services that complements developer's services. Considering RedHat, the customer would pay directly to them for the services and RedHat would transfer part of the payment to the developer, who provided part of the service too. With this deal, every developer becomes a potential retailer of RedHat's services. That's one more solution to increase investments on open-source projects.
Both ideas above were explained to Sun engineers some months ago (At the time I was thinking that IBM would by Sun :D).  To sell open source products, companies should innovate, however Sun was good when innovating their products, but not their selling and services processes. These parts of their business were always traditional. RedHat, on the other hand, has far better selling and services processes for their open source products than Sun because they are agile, have simple procedures and minimal distance between the customer and the specialist. That's why they are one of the only companies to get profit from open-source.

Companies that already offer software project management (track system, version control, wiki, etc.), such as AtlassianCollabnetGoogle or even Oracle with Kenai, have strategic advantage because they already have something done, with large experience on it. I only wish that people out there get this idea and make it happen. This is not what I love to do, so I won't appropriately exploit it. But I'm confident that these are good ideas and I hope to blog about any future service that provides such features and I'm probably going to be one of the first customers of the pioneer.

Wednesday, February 3, 2010

The End of Kenai: Oracle (1) x (0) Community

I'm very disappointed with Oracle about Kenai's discontinuation. SUN was working to provide a better service for the community, besides solving their own internal development management. But now, Oracle changes the rules, saying implicitly that the community doesn't deserve that, but a simpler, less integrated, difficult to manage platform, which is java.net.

The beginning Oracle's relationship with the Java Community was not that easy. To celebrate the transition, they started giving us more work to do (move our projects as soon as possible from Kenai to anywhere else) besides the work we already have to perform in our open-source projects.

Using a bit of intelligence, Oracle would propose to keep the Kenai platform with the community, because the trademark is already well known among us, and creating an internal instance of Kenai, with a sub-domain or even with another name, since the name "Kenai" doesn't make any difference internally. Also, it's easier for a database company to divide internal projects from community projects than forcing thousands of people to leave Kenai. The cost to keep Kenai working for the community is ridiculous for Oracle.

Oracle should remember, or even learn, that we spend a considerable time of our lives convincing people to use their, now new, products. We even teach people how to use those products. You know, without people with expertise around a product, it cannot be consolidated in a certain geographic region. We also generate a lot of knowledge around our groups that influence local software companies to choose the technologies we have been struggling to learn. So, we have generated a lot of business for those who work with us and give us a good support and recognition.

So far, just words coming from Oracle. Words just saying that nothing worse is going to happen besides some projects they already have eliminated. Some positive words full of promises and empty of actions. I'm not willing to keep listening to excuses or explanations. I'm willing to continue promoting new Oracle's products. But, what can Oracle do to make it happen in the best way possible, even better than before?