6/6/11

Enumerated Types Java and Databases

Enumerated types is one of the best thing in Java as in any programming language in general.
The problem is that is not supported by all databases. PostgreSQL and MySQL has support Oracle and a few others don't.
This creates a problem especially for those who want to build portable systems.
(Even though many are against portability in RDBMS)

The solution is to define the type as Enumerated Type in the Java part of your system but as VARCHAR or CHARACTER VARYING etc. That is saved in db as string/text and you can enforce control through type checking in the Java side of your system. If the Java side is not the only entry point of your system, then one solution is to add CHECK CONSTRAINT on the field in question and even use exclusively Stored Procedures where you make sure no illegal values found their way into the db.

Now if you are using JPA and especially if you e.g. are using NetBeans which automatically generates classes for all tables then just replace the type String with the ENUM_TYPE you have already defined.

One example: In my schema I have a principal table with a PRINCIPAL_STATUS
the generated code for the field was
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 20)
    @Column(name = "principal_status")
    private String principalStatus;

I changed the above code to the following

    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 20)
    @Column(name = "principal_status")
    @Enumerated(EnumType.STRING)
    private PRINCIPAL_STATUS principalStatus;

don't forget to import
import eu.minipay.entities.types.PRINCIPAL_STATUS;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;

Of course you must change accordingly the get and set methods.

6/5/11

WARNING: PWC4011: Unable to set request character encoding to UTF-8 from context , because request parameters have already been read, or ServletRequest.getReader() has already been called

While using Glassfish v3.1 with JSF 2.0 I ended up getting this very annoying warning.
WARNING: PWC4011: Unable to set request character encoding to UTF-8 from context /, because request parameters have already been read, or ServletRequest.getReader() has already been called


This seems to be very common with a very hard to find solution on google.
Finnally after a lot of search I found this link which had the solution.

http://mpashworth.wordpress.com/2011/06/01/glassfish-3-1-pwc4011-warning-with-jsf-applications/

I hope by placing the link here it will come up in google's answers


Place the following in the glassfish-web.xml of the web application.
<parameter-encoding default-charset="UTF-8"/>


<!DOCTYPE glassfish-web-app PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Servlet 3.0//EN" "http://glassfish.org/dtds/glassfish-web-app_3_0-1.dtd">
<glassfish-web-app error-url="">
 <parameter-encoding default-charset="UTF-8"/>
...
</glassfish-web-app>

3/10/11

javamail session on Glassfish and how to send an email

javamail session on Glassfish and how to send an email

In order to be able to send an email from a web application using Glassfish you must first setup a javamail session.

Go to glassfish administration console that is usually on port 4848. E.g. if you have installed glassfish locally then you may access it:
http://localhost:4848/

log in and go to Resources/ JavaMail Sessions.Create a new javamail session. Fill the fields accordingly.
mail/yoursessionnamehere  (the JNDI name for a javamail session must always start with "mail/"
Mail Host: smtp.googlemail.com ( I am using google services so my SMTP server is smtp.googlemail.com)
Default User: someuser@yourdomain.com
Default Sender Address: someuser@yourdomain.com
Description:  mail session to send support emails (write something to rememeber what this is for)
Store Protocol:  imap
Store Protocol Class:com.sun.mail.imap.IMAPStore
Transport Protocol:  SMTP
Transport Protocol Class: com.sun.mail.smtp.SMTPTransport
Debug: disabled

Additional Properties (9)
mail-smtp-host smtp.googlemail.com
mail-smtp-user someuser@yourdomain.com
mail-smtp-password yourpassword
mail-smtp-auth true
mail-smtp-port 465
mail-smtp-socketFactory-port 465
mail-smtp-socketFactory-class javax.net.ssl.SSLSocketFactory
mail-smtp-starttls-enable true
mail-smtp-socketFactory-fallback false

I have created a bean to send emails. This is the finally combination of code that worked for me after several tries



/*
 * EmailUtil.java
 *
 * Copyright 1988 MINIpay.
 * All Rights Reserved. Patents pending.
 *
 * This software is the proprietary information of MINIpay
 * Use is subject to license terms.
 *
 */


package eu.minipay.common;


import java.util.Date;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


/**
 *
 * @author minipay.eu
 */
@Stateless
public class EmailBean {


    @Resource(name = "mail/supportMINIpay")
    private Session mailSession;


    public void sendMessage(String email, String subject, String bodyMessage) throws MessagingException {        
        
        Message message = new MimeMessage(mailSession);
        try {
            message.setSubject(subject);
            message.setRecipient(RecipientType.TO, new InternetAddress(email)); 
            // this is if you want message body as text
//            message.setText(bodyMessage); 
            
            // use this is if you want to send html based message
            message.setContent(bodyMessage, "text/html; charset=utf-8");


            // This is not mandatory, however, it is a good
            // practice to indicate the software which
            // constructed the message.
            message.setHeader("X-Mailer", "MINIpay mailer www.minipay.eu");


            // Adjust the date of sending the message
            Date timeStamp = new Date();
            message.setSentDate(timeStamp);


            Transport.send(message);
        } catch (MessagingException ex) {
            throw ex;
        }
    }
}
To send an email just call the method inside a  bean method. E.g. in my case when a user requests a new password first get the bean
@EJB
    private eu.minipay.common.EmailBean emailUtil;
then just
emailUtil.sendMessage("email@domain", "subject", "message");
This works for me and I hope it will save you hours of searching and testing.

How to build a web based application

Hello,

recently I took over a project and was puzzled with all available technologies for several weeks.
I am concentrating on java and free open source technologies and after reading and testing all available frameworks and tools I finally decided to use the following.
Please note that the versions are important as these the versions that work. This means that previous versions had problems or didn't provide full support for some of the technologies I am about to use.

  • IDE
  • GUI framework
  • Application Server
  • RDBMS
  • Authentication
IDE
I compared two IDEs Eclise and NetBeans. Even though both are very mature products with many plugins, I found Eclipse much more complicated and error prone in combination with application servers. NetBeans is the perfect IDE tool and the only thing missing is a WEB GUI builder similar the one it had in previous releases before Oracle bought SUN and removed this functionality from NetBeans, probably in order to promote their JDeveloper which works though only with their commercial application server.
So, IDE NetBeans 7.0 (currently in beta but works perfect with Glassfish 3.1)

GUI Framework
Here I had to choose between the obsolete JSP with some combination of struts etc. or JSF with facelets. The choice is straightforward JSF 2.0 with facelets it is.

Application Server
Glassfish vs Tomcat. After doing several tests I decide to go with glassfish. Both products have suport for cluster load balancing etc but Glassfish supports beans and was less error prone. The only problem is the lack of proper documentation. You have to do extensive search on the web for every single configuration and code examples, most of which are outdated.
Glassfish 3.1 it is.

RDBMS
The choise here was easier to make as I have been using all three for many years and have extensive experience as developer on Oracle, MySQL and PostgreSQL. Oracle is certainly a RDBMS which has everything but it is so expensive that you need the BNP of a small country to buy licenses. MySQL has certainly been evolving alot the last years, but I found PosgreSQL to have most of the features that Oracle has for free.
PostgrSQL 9.x

Authentication
Initially I was planning to use my own db schema for authentication but Glassfish requires its own schema so I finally decided to go for an LDAP solution. Even though it is still unclear to me how I can setup roles and groups on LDAP but no worries, I will post everything as I find solutions.