Archive

Archive for January, 2010

Installing Liferay with MySQL, CAS and openLDAP on Ubuntu (part 2)

January 23, 2010 4 comments

This is second part of of article “Installing Liferay with MySQL, CAS and openLDAP on Ubuntu”.

2. Installing and configuring MySQL

To install MySQL you simply run command:

sudo apt­ get install mysql­-server

Now that we have MySQL installed we can download sql script (that generates schema) and unzip it:

wget http://downloads.sourceforge.net/lportal/liferay-portal-sql-5.2.3.zip

unzip ./liferay-portal-sql-5.2.3.zip

Next you need to enter MySQL shell

mysql -u root -p

and create new database for Liferay

create database lportal character set utf8;
create user ‘lportal’@’localhost’ identified by ‘lportal123’;
grant all privileges on lportal.* to ‘lportal’@’localhost’;
flush privileges;

After entering portal database:

use lportal;

we can generate basic schema:

source liferay-portal-sql-5.2.3/portal-minimal/portal-minimal-mysql.sql

Now we have MySQL installed with database configured for Liferay portal.

3. Installing Liferay portal

Before we move on you need to first download Liferay 5.2.3 zip archive and unpack it somewhere in your file system (for example /home/user/liferay/). We will refer to this folder (or to the path of this folder) as LIFERAY_ROOT further in this tutorial.

Add rights to make tomcat runable:

chmod ­R +x LIFERAY_ROOT/tomcat/bin

Then you need to delete sample data. Liferay (since version 5.2) comes with so-called “sample data”, which must be removed before we move on. Delete :

  • folder LIFERAY_ROOT/tomcat/webapps/sevencogs­hook
  • folder LIFERAY_ROOT/tomcat/webapps/sevencogs­theme
  • folder LIFERAY_ROOT/tomcat/webapps/wol­portlet
  • file LIFERAY_ROOT/data/hsql/lportal.properties
  • file LIFERAY_ROOT/data/hsql/lportal.script

Now you need to only bind your Liferay portal with MySQL database your created earlier. To do that open file LIFERAY_ROOT\tomcat\webapps\ROOT\WEB­-INF\classes\portal­ext.properties for edition and enter lines below:

jdbc.default.driverClassName=com.mysql.jdbc.Driver
jdbc.default.url=jdbc:mysql://localhost/lportal?
useUnicode=true&characterEncoding=UTF-8&useFastDateParsing=false
jdbc.default.username=lportal
jdbc.default.password=lportal123

Now you have properly installed and configured Liferay portal.

4. Configuring SSL

Authentication to your portal should be done using secure connection. That’s why you need to enable SSL in your tomcat. First you need to generate certificate for your server. To do that run JDK tool called keytool:

keytool -­genkey ­-alias tomcat -­keypass asdfgh ­-keyalg RSA

notice that for this tutorial keypass (in other words password) will be ‘asdfgh’. Keytool will ask you few questions, but only one is really important. When asked “What is your first and last name?” you must answer with the DNS name of your server. If you are following this tutorial on your private computer (that do not have DNS name) then provide ‘localhost’ answer. Other questions are irrelevant and you can answer with default values (just keep pressing ENTER).

Now that you have your certificate generated, you can export it to .cert file. Run keytool again:

keytool ­-export ­-alias tomcat ­-keypass asdfgh ­-file server.cert

At the end you need to add your certificate to JDK’s keystore:

keytool ­-import ­-alias tomcat ­-file server.cert ­-keypass asdfgh ­-keystore $JAVA_HOME/jre/lib/security/cacerts

You will be asked for JDK’s keystore pass. By default this password is ‘changeit’.

Now all you need to do is simply enable SSL in your tomcat. In LIFERAY_ROOT/tomcat/conf/sertver.xml add new connector:

<Connector port=”8443″ protocol=”HTTP/1.1″ SSLEnabled=”true”
maxThreads=”150″ scheme=”https” secure=”true”
clientAuth=”false” sslProtocol=”TLS” keystorePass=”asdfgh”/>

Congratulations. You have now enabled SSL in your tomcat.

Go to Part 3 of this tutorial

Reference:

[1] – Liferay portal page

[2] – Tomcat SSL configuration How-to

Installing Liferay with MySQL, CAS and openLDAP on Ubuntu (part 1)

January 19, 2010 4 comments

Recently I’ve been asked to deploy a portal infrastructure into one of the Polish corporations. The task was to bind together Liferay (portal with MySQL as internal database) with CAS (single sign-on authentication) and openLDAP (directory for holding user specific data like login, password, email etc.).

The general idea was that every user’s information should be  held inside openLDAP. Liferay portal would delegate authentication to CAS web application where user’s login action would be authenticated against data from openLDAP. Because Liferay keeps its internal database, portal needs to periodically check openLDAP to see whether any data changed and update if needed.

Because the whole idea was kind of new for me, I had to do a small research before I got my hands dirty. On Internet I found many tutorials how to integrate Liferay with CAS, CAS with openLDAP and Liferay with openLDAP. Some of them worked, some not, some were simply obsolete. Moreover there was not one single tutorial to show how to bind all these technologies together. This post tries to fills this gap.

This post will be divided into four parts. Liferay version was 5.2.3 used with CAS 3.3. Installation and deployment was done on Linux Debian and on Ubuntu Linux (9.04).

1. Installing openLDAP

Warning: This will not run on Ubuntu 9.10! There were some changes done in Ubuntu that made installation of openLDAP really hard task. Ubuntu 9.04 is recommended.

To run installation you should simply run command below:

sudo apt­-get install slapd ldap­-utils

During installation you will be asked for administrator password. For purpose of this document this password will be ‘asdfgh’.

After installation ends, you should run configuration program:

sudo dpkg­-reconfigure slapd

You will then need to answer few questions:

a) If you enable this option, no initial configuration or database will be created for you. Omit
OpenLDAP server configuration?

Choose: No

b) The DNS domain name is used to construct the base DN of the LDAP directory. For example,
‘foo.example.org’ will create the directory with ‘dc=foo, dc=example, dc=org’ as base DN.

You need to enter name base DN, which normally is just simply the DNS domain name.
For  it.mycompany.com DN would be dc=it,dc=mycompany,dc=com

c) Please enter the name of the organization to use in the base DN of your LDAP directory.

Simply your organisation name. Can be anything.
d) The HDB backend is recommended. HDB and BDB use similar storage formats, but HDB adds
support for subtree enames. Both support the same configuration options.
In either case, you should review the resulting database configuration for your needs.
See/usr/share/doc/slapd/README.DB_CONFIG.gz for more details.

Choose: No

e) Do you want the database to be removed when slapd is purged?

Choose: No

f) Please enter the password for the admin entry in your LDAP directory.

Any, for this document it’s ‘asdfgh’
g) The obsolete LDAPv2 protocol is disabled by default in slapd. Programs and users should
upgrade to LDAPv3. If you have old programs which can’t use LDAPv3, you should select this
option and ‘olcAllows: bind_v2’ will be added to your cn=config directory.

Choose: No

Now to create simple structure that holds users and their groups, we run command:

ldapadd ­x ­D cn=admin,dc=it,dc=mycompany,dc=com ­W ­f ldap_data_set.ldif

where ldap_data_set.ldif looks like this:

——————- ldap_data_set.ldif ——————–

dn: ou=groups,dc=it,dc=mycompany,dc=com
objectClass: organizationalUnit
objectClass: top
description: grupy
ou: groups

dn: ou=people,dc=it,dc=mycompany,dc=com
objectClass: organizationalUnit
objectClass: top
ou: people

dn: cn=admins,ou=groups,dc=it,dc=mycompany,dc=com
objectClass: extensibleObject
objectClass: groupOfNames
objectClass: top
cn: admins
description: admins group
member: uid=jdoe,ou=people,dc=it,dc=mycompany,dc=com

dn: cn=programmers,ou=groups,dc=it,dc=mycompany,dc=com
objectClass: extensibleObject
objectClass: groupOfNames
objectClass: top
cn: programmers
description: programisci hudsona
member: uid=kmoe,ou=people,dc=it,dc=mycompany,dc=com
member: uid=jhudson,ou=people,dc=it,dc=mycompany,dc=com

dn: uid=jdoe,ou=people,dc=it,dc=mycompany,dc=com
objectClass: account
objectClass: extensibleObject
objectClass: uidObject
objectClass: userSecurityInformation
objectClass: top
email: jdoe@mycompany.com
member: cn=admins,ou=groups,dc=it,dc=mycompany,dc=com
name: John
sn: Doe
uid: jdoe
userPassword: {MD5}ICy5YqxZB1uWSwcVLSNLcA==

dn: uid=kmoe,ou=people,dc=it,dc=mycompany,dc=com
objectClass: account
objectClass: extensibleObject
objectClass: uidObject
objectClass: userSecurityInformation
objectClass: top
email: kmoe@mycompany.com
member: cn=programmers,ou=groups,dc=it,dc=mycompany,dc=com
name: Kate
sn: Moe
uid: kmoe
userPassword: {MD5}ICy5YqxZB1uWSwcVLSNLcA==

dn: uid=jhudson,ou=people,dc=it,dc=mycompany,dc=com
objectClass: account
objectClass: extensibleObject
objectClass: uidObject
objectClass: userSecurityInformation
objectClass: top
email: jhudson@mycompany.com
member: cn=programmers,ou=groups,dc=it,dc=mycompany,dc=com
name: Jane
sn: Hudson
uid: jhudson
userPassword: {MD5}ICy5YqxZB1uWSwcVLSNLcA==

—————-end of ldap_data_set.ldif ——————

This will create structure described below:

it.mycompany.com
|
|­­­ groups

|       |    admins

|       |    programmers
|
|­­­ people

|       |   jdoe

|       |   kmoe

|       |   jhudson

Every user has password: ‘123’.

And that’s simply it. We now have openLDAP installed with some user data in it.

Go to Part 2 of this tutorial

Reference:

[ldap1] – https://help.ubuntu.com/9.04/serverguide/C/openldap-server.html -> official Ubuntu tutorial
[ldap2] – https://help.ubuntu.com/community/OpenLDAPServer -> older version of [ldap1]
[ldap3] – http://docs.sun.com/source/816-6400-10/lmodify.html –  SUN’s documentation –  ldapmodify
[ldap4] – http://docs.sun.com/source/816-6400-10/lsearch.html – SUN’s documentation –
ldapsearch


Java Killers #003 – ? is the question

January 13, 2010 Leave a comment
Categories: Java Killers Tags:

JPA 2.0 and Spring 3.0 with Maven

January 9, 2010 27 comments

I’m currently updating WicketCool to use Spring 3.0, JPA2.0 and latest Wicket. Here is a short summary of my research, a quick tutorial showing how to jump into Spring3.0 + JPA2.0 development using Maven.

1. Dependencies

a) Spring

To use 3.0 release of the Spring framework you can’t no longer add one dependency as you used to do it

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring</artifactId>
   <version>2.5.6</version>
</dependency>

This will no longer work. Spring framework is divided into 20 modules:

If you create web appliactions, you will probably need modules listed below:

  1. all from Core Container: Beans, Core, Context and Expression Language
  2. AOP
  3. from Data Access/Integration: Transactions, ORM
  4. from Web: Web (even if you don’t use SpringMVC, you still might consider OpenEntityManagerInViewFilter which is inside Web module
  5. Test

Thus set of dependencies that you need to include in your pom.xml are:

<properties>
 <spring.version>3.0.0.RELEASE</spring.version>
</properties>

<dependencies>
 <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>${spring.version}</version>
 </dependency>
 <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-web</artifactId>
   <version>${spring.version}</version>
 </dependency>
 <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-beans</artifactId>
   <version>${spring.version}</version>
 </dependency>
 <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>${spring.version}</version>
 </dependency>
 <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-aop</artifactId>
   <version>${spring.version}</version>
 </dependency>
 <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context-support</artifactId>
   <version>${spring.version}</version>
 </dependency>
 <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-tx</artifactId>
   <version>${spring.version}</version>
 </dependency>
 <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-orm</artifactId>
   <version>${spring.version}</version>
 </dependency>
 <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jdbc</artifactId>
   <version>${spring.version}</version>
 </dependency>
 <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-test</artifactId>
   <version>${spring.version}</version>
 </dependency>
</dependecies>

b) JPA 2.0

Now that we have Spring dependencies sorted out, we can look at the JPA2.0.  We must remember that JPA itself is only standard, thus when setting dependencies we are really choosing the provider. I could go with Hibernate or EclipseLink. Hibernate is still in beta state and EclispeLink is a reference implementation of the standard, so I thought that EclipseLink is a good way to go. However after recent discoveries (which took me quite some to figure out by the way), I thought I will stick with the Hibernate’s beta.

What is new in Hibernate’s recent release is that you no longer need to define dependencies to core, annotations, commons-annotations ect. It is now only one, single dependency.  Second dependency is the API of the standard.

<dependencies>
  <dependency>
    <groupId>org.hibernate.java-persistence</groupId>
    <artifactId>jpa-api</artifactId>
    <version>2.0-cr-1</version>
  </dependency>
  <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>3.5.0-Beta-2</version>
  </dependency>
</dependencies>

You might also need to add JBoss repository:

<repositories>
 <repository>
   <id>JBoss Repo</id>
   <url>http://repository.jboss.com/maven2</url>
 </repository>
</repositories>

2. Configuration

The simples application context configuration file can look like this:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-3.0.xsd  http://www.springframework.org/schema/tx  http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

 <!-- holding properties for database connectivity /-->
   <context:property-placeholder location="classpath:jdbc.properties"/>
   <!-- enabling annotation driven configuration /-->
<context:annotation-config/>
<context:component-scan base-package="wcpackage"/>
   <tx:annotation-driven transaction-manager="transactionManager"/>

    <bean
       class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>

    <bean id="dataSource"
       class="org.springframework.jdbc.datasource.DriverManagerDataSource"
       p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}"/>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
       p:entityManagerFactory-ref="entityManagerFactory"/>

    <bean id="entityManagerFactory"
       class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
       p:dataSource-ref="dataSource"
       p:jpaVendorAdapter-ref="jpaAdapter">
       <property name="loadTimeWeaver">
          <bean
             class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
        </property>
        <property name="persistenceUnitName" value="wctemplatePU"></property>
    </bean>

    <bean id="jpaAdapter"
         class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
         p:database="${jpa.database}"
         p:showSql="${jpa.showSql}"/>
</beans>

Given that wcpackage is a root package for component scan and wctemplatePU is name of the persistent unit.
Now all we need to do is to define persistence unit in META-INF/persistence.xml

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/persistence">

	<persistence-unit name="wctemplatePU" transaction-type="RESOURCE_LOCAL">
		<properties>
			<property name="hibernate.hbm2ddl.auto" value="validate" />
		</properties>
	</persistence-unit>
</persistence>

And that is basically it. You have Spring configuration and now can use EntityManager in your services classes.

@Repository(value = "userDAO")
public class UserDefaultDAO implements UserDAO {

    @PersistenceContext
    private EntityManager entityManager;

Injected EntityManager will be with transaction-scoped persistence context, resource_local transaction type (meaning transactions used from database not JTA). Hope everything is comprehensive. If you have any questions, please let me know.

See also:

  1. A proper way for JPA entities instantiation
ale macie fajnie
Categories: Other Tags: , , ,

JPA2.0 banned in Poland!

January 7, 2010 6 comments

Yeah really! So I thought it’s time to play a little bit with the brand new JPA2.0 specification. I tried the Hibernate vendor, but since its implementation is still in beta and was throwing more exceptions then I thought a beta should throw, I thought I would give an EclipseLink a try.

Eclipse Link is a former Toplink and now (ever since given back to the community) a reference implementation of JPA standard. Reading this site I learned that to get started with the EclipseLink using Maven, you need to add one dependency:

<dependency>
  <groupId>org.eclipse.persistence</groupId>
  <artifactId>eclipselink</artifactId>
  <version>2.0.0</version>
  <scope>runtime</scope>
</dependency>

But Eclipse Link is still not in the main repo1 repository, so you have to add Eclipse repo information to your pom.xml.

<repository>
   <id>EclipseLink Repo</id>
   <url>http://www.eclipse.org/downloads/download.php?r=1&nf=1&file=/rt/eclipselink/maven.repo</url>
</repository>

And here where the fun begins. If you open repository link (http://www.eclipse.org/downloads/download.php?r=1&nf=1&file=/rt/eclipselink/maven.repo) in your browser  it will redirect you to a nearest mirror near you. Well, for people living in Poland this mirror is http://ftp.man.poznan.pl/eclipse/rt/eclipselink/maven.repo/. The problem is that polish mirror not only lacks the 2.0.0 final implementation, but also you can find eclipse link in 2.0.0-SNAPSHOT version catalogue, but the content of the catalogue will be empty (it has metadata but no jars!). All that is there is just milestonses, nothing else.

So dear readers, EclipseLink JPA2.0 is banned in Poland. It’s official :).

Thanks to the Wicket User Group we can work around this ban, using Belgium mirror repository http://eclipse.a3-system.be/rt/eclipselink/maven.repo. So this should work in your pom.xml:

<repository>
   <id>EclipseLink Repo</id>
   <url>http://eclipse.a3-system.be/rt/eclipselink/maven.repo</url>
</repository>

Funny, isn’t it? 🙂

Categories: News Tags: , ,

A proper way for JPA entities instantiation

January 4, 2010 6 comments

If you read Misko Hevery’s blog you should be pretty much familiar with term testable code (and if you don’t know Misko’s blog then I strongly encourage you to visit his site). Misko divides objects into two main types: service objects and value objects. Each service object provides some set functionalities defined in application logic. Value objects are leafs of the objects’ collaboration graph. They usually encapsulate the data, that is manipulated by services. In other words, in most cases they are the model objects, the nouns that you use to describe the application logic. If you use any ORM technology (like Hibernate or Toplink) value objects will most likely be the entities of your application. And on creating the entities I would like to focus in this post. All examples will be for JPA2.0 entities, since this is standard, but the rules can be easily applied to any other ORM solution. Before we move on to the main topic, which is entities instantiation, lets take a look on how service objects are created.

Most of you probably know that for service instantiation we use dependency injection, which makes code maintainable, testable and more declarative. I suspect that most of you guys know about it, but for all non-believers, I’ve created this very simple example for consideration:

public class UserService implements IUserService {
 @Inject
 private IUserDao dao;

 @Inject
 private IFacebookWS facebook;

 public User logIn(String login, String password) {

   User user = dao.findByLoginAndPassword(login,password);
   if(user == null) {
     return User.GUEST;
   }
   return user;
 }

}

We have those three service classes (and equivalent interfaces): UserDAO for database connection, FacebookWS for communication with facebook webservice and finally UserService that binds the application logic. I use dependency injection so I don’t create any instances of my service classes explicitly. This separation of concerns (separation of usage and instantiation of given class) makes my code more declarative. You, as a other programmer of my team, see that UserService uses UserDAO and FacebookWS, but don’t know how those dependencies are instantiated. And you shouldn’t really care, all that is important is that UserService depends on dao and webservice object.

Thanks to Dependency Injection my tests are now easy to write and easy to read:


@Test
public void shouldReturnGuestUserForIncorrectPassword() {

 // given
 IUserService service = new UserService();

 IUserDAO dao = mock(IUserDAO.class);
 when(dao.findByLogin("someLogin").thenReturn(null));
 inject(service, "dao", dao);

 // when
 User returnedUser = service.logIn("someLogin",
                                   "wrongPassword");

 // then
 assertEquals(User.GUEST, returnedUser);

}

Why (beside the fact that I’m using BDD template given-when-then) tests are easy to read? Important thing is that you (as some other developer of my development team) when looking just at my test, see that to perform logIn action, only IUserDAO dependency is mocked and injected to tested UserService class.

 inject(service, "dao", dao);

This way test is documenting the class its testing. You clearly see that to perform logIn action, facebook web service is not needed. In general to understand how some method works, you can first look at created tests for given class and then (if still needed) check out the implementation. I guarantee that reading tests and implementation is far more comprehensive then just reading implementation.

You might say that to understand how logIn works you wouldn’t need really tests. Remember however that this example is trivial. Imagine class with larger set of dependencies. Self-documenting, easy to read tests, might be really really helpful for maintaining code (especially if the code is one year old and it was developed by someone who is no longer hired in your company).

Secondly, why tests are easy to write? Imagine for example what would happen if I didn’t use DI and I was just instantiating dao and service object in a constructor?


public class UserService implements IUserService {

 private IUserDAO dao;
 private IFacebookWS facebook;

 public UserService() {
   dao = new UserDAO();
   facebook = new FacebookWS();
 }

How I could then mock any of those dependencies? One could say, that I would just simply inject the mock object after constructor. But what if for example when instantiating UserDAO, the dao object is connecting to data base? How would you prevent it from happening in your tests? I believe you couldn’t do it.

Ok, so we use DI for service objects, but what about the value objects? And more importantly what about entities? For the given example, how do we create User objects? The rule of thumb is to just simply use constructors when instantiating value objects. This should not be really a suprise. Value objects are fundamentals of your application, as they mostly just gather domain specific information. They are leafs in the objects relation graph, thus they will most likely be never mocked.

So (following this rule) in our example, User class should looked more or less something like this:

@Entity
public class User {

 @Id
 private String login;
 @Column(nullable = false)
 private String password;
 private String facebookLogin;
 private String facebookPassoword;

 public User(String login,
             String password,
             String facebookLogin,
             String facebookPassword) {
   this.login = login;
   this.password = password;
   this.facebookLogin = facebookLogin;
   this.facebookPassword = facebookPassword;
  }
 }

Everything works fine, even despite the fact in my personal opinion calling new User(“someName”,”somePassowrd”, “someOtherName”, “someOtherPassword”) becomes hardly readable and maintainable. However implementation is still valid. But what shall we do if we get a new requirement for our application:

@Test
public void shouldDefaultFacebookValuesEqualsEquvalentNormalValues() {
 // given
 String login = "a";
 String password = "b";

 // when
 User user = User(login,password);

 // then
 assertEquals(user.getLogin(), user.getFacebookLogin());
 assertEquals(user.getPassowrd(), user.getFacebookPassword());
}

In other words we say that login and password are obligatory in object instantiation, but facebook login and password are not – if not present during initialization, facebook login and password are same as normal login and password.
So what should we do to implement those requirements? Well I hope non of you think to do it like this:

@Entity
public class User {
 @Id
 private String login;
 @Column(nullable = false)
 private String password;
 private String facebookLogin;
 private String facebookPassoword;

 public User(String login,
             String password,
             String facebookLogin,
             String facebookPassword) {
   this.login = login;
   this.password = password;
   this.facebookLogin = facebookLogin;
   this.facebookPassword = facebookPassword;
  }

 public User(String login,
             String password) {
   this.login = login;
   this.password = password;
   this.facebookLogin = login;
   this.facebookPassword = password;
  }
}

You can clearly see the code duplication. Maintaining this code would turn into a nightmare in no time. A rather well-known solution is to implement something that some programmers call “telescoping constructor pattern” (name I first encountered in Joshua Bloch “Effective Java”) . For our scenario this patter would look like this:

@Entity
public class User {
 @Id
 private String login;
 @Column(nullable = false)
 private String password;
 private String facebookLogin;
 private String facebookPassoword;

 public User(String login,
             String password) {
   this(login, password, login);
 }
 public User(String login,
             String password,
             String facebookLogin) {
   this(login, password, facebookLogin, password);
 }
 public User(String login,
            String password,
            String facebookLogin,
            String facebookPassword) {
   this.login = login;
   this.password = password;
   this.facebookLogin = facebookLogin;
   this.facebookPassword = facebookPassword;
 }
}

You define constructor with minimal set of parameters (meaning parameters obligatory to object initialization). Then you continue on extending other constructors with parameters until you reach the constructor that defines them all. This works fine for small set of parameters, but can quickly turn into horror when number of parameters grows and so the vast number of possible constructors.

Another solution would be to go with the JavaBeans pattern.

@Entity
public class User {
 @Id
 private String login;
 @Column(nullable = false)
 private String password;
 private String facebookLogin;
 private String facebookPassoword;

 public User() {
 }

 public void setLogin(String login) {
   this.login = login;
 }

 public void setPassword(String password) {
   this.password = password;
 }

 public void setFacebookLogin(String facebookLogin) {
   this.facebookLogin = facebookLogin;
 }

 public void setFacebookPassword(String facebookPassword) {
   this.facebookPassword = facebookPassword;
 }
}

You create object without any parameters and use set methods to define appropriate values. Solution works fine with any number of parameters and is wildly use by many developers. In fact I’ve seen it almost in every second project I ever worked on. Since every single IDE gives automatic setter and getter generation, most developers follow this simple pattern:

1. create entity class in they favourite IDE (e.g User )
2. define all needed attributes as private fields (e.g login, password, facebookLogin, facebookPassword)
3. auto-generate getters and setters

This pattern is quick when creating entity classes, but it has its flaws. The fact that it generates a lot of code that you might never really need (from time to time check your code on how many getters you have that are never really use, you might get surprised), already makes it a no-no. But it has one more and a lot bigger disadvantage: it allows you to create entity object, that does not have all the obligatory fields set. Example:

User user = new User();
user.setLogin("john");
user.setFacebookLogin("jhawk");
user.setFacebookPassword("12345");

userDao.persist(user);
}

Assuming that userDao.persist(User) calls EntitManager’s persist method, running the code above will throw an exception by the JPA provider, since not-nullable password field was never set.

Ok, so what can we do about it? Joshua Blooch gives fine example of builder pattern.

Instead of making the desired object directly, the client calls a constructor (or static factory) with all of the required parameters and gets a builder object. Then the client calls setter-like methods on the builder object to set each optional parameter of interest. Finally, the client calls a parameterless build method to generate the object, which is immutable. The builder is a static member class of the class it builds.

This works fine for value objects that are immutable (meaning once set, their state is never changed). Consider the example below:

public class Coffee {
 private final CoffeType type;
 private final int cupSize;
 private final boolean hasMilk;

 public static class Builder {
   public CoffeeType type;
   public int cupSize;
   public boolean hasMilk;

   public Builder(CoffeeType type, int cupSize) {
      this.type = type;
      this.cupSize = cupSize;
      hasMilk = false;
   }

   public Builder withMilk() {
      hasMilk = true;
      return this;
   }

   public Coffee build() {
     return new Coffee(this);
   }
 }

 private Coffee(Builder builder) {
   this.type = builder.type;
   this.cupSize = builder.cupSize;
   this.hasMilk = builder.hasMilk;
 }
}

Reading the code above you can clearly see that coffee type and cup size are obligatory and whether coffee should or shouldn’t have milk is not mandatory field. Creating Coffee could look more or less like this:

Coffee coffee = new Coffee.Builder(CoffeeType.Expresso, 3).withMilk().build();
}

Of course using this pattern for value object that has two parameters would be an exaggeration. J. Blooch says:

In summary, the Builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters, especially if most of those parameters are optional.

The problem is that entities are not immutable by nature. So the question still remains, how can we construct entity classes? What I really like to do is combine JavaBeans pattern and Builder pattern when creating entities. For all entity attributes I create private fields, those that are obligatory become parameters for the public constructor. Since JPA requires that each entity has a parameter-less constructor, I create one, but I give him protected access level, so in most cases it won’t be accessible from client code. I create setter methods for all fields that require them at the moment and incrementally add them whenever needed. So our User example would look more or less like this:

@Entity
public class User {
 @Id
 private String login;
 @Column(nullable = false)
 private String password;
 private String facebookLogin;
 private String facebookPassoword;

 protected User() { }

 public User(String login, String password) {
   this.login = login;
   this.password = password;
 }

 public void setFacebookLogin(String facebookLogin) {
   this.facebookLogin = facebookLogin;
 }

 public void setFacebookPassword(String facebookPassword) {
   this.facebookPassword = facebookPassword;
 }
}

And if I would like to stick with all previously mentioned in this posts requirements, we could slightly enhance the constructor to look like this:

 public User(String login, String password) {
   this.login = login;
   this.password = password;
   this.facebookLogin = login;
   this.facebookPassword = password;
 }

Now instantiating User class requires two parameters (login and password). You gain flexibility of JavaBeans, with security of the Builder pattern. Of course this is only hybrid of this two solutions, so it is still possible to create malformed entity (instantiated with obligatory values and then set them again to nulls with setter methods), but this is less likely to happen. You gain on readability, since quick look on constructor parameters gives you notion of all obligatory attributes.

You can also combine this solution with JSR-303 validation and unit testes, solution that can shield you from creating malformed entities… But this is probably topic for another post.

But I wonder how you create your entity classes. Do you know any other ways to create entity classes so their instantiation is safe, readable and maintainable?

Categories: Articles Tags: , ,