Archive

Archive for the ‘Articles’ Category

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

April 8, 2010 2 comments

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

5. Installing and configuring CAS

The easiest way to integrate CAS with openLDAP is to build CAS using Maven.  Created war file will contain all needed dependencies and all properties will be set inside configuration files.  Before we move on you need to first download CAS sources and unpack it somewhere in your file system (for example /home/user/Downloads/cas). We will refer to this folder (or to the path of this folder) as CAS_SOURCE further in this tutorial.

5.1 Configuration of dependencies and properties

1. Go to folder $CAS_SOURCE/cas-server-webapp and in file pom.xml add

<dependency>
     <groupId>${project.groupId}</groupId>
     <artifactId>cas-server-support-ldap</artifactId>
     <version>${project.version}</version>
</dependency>

2. Go to folder $CAS_SOURCE/cas-server-webapp/src/main/webapp/WEB-INF and open file deployerConfigContext.xml

3. In file deployerConfigContext.xml inside bean authenticationManager comment out SimpleTestUsernamePasswordAuthenticationHandler

<!--
<bean
class="org.jasig.cas.authentication.handler.support.SimpleTestUsernamePasswordAuthenticationHandler" />
-->

4. Add FastBindLdapAuthenticationHandler inside authenticationManager bean (where SimpleTestUsernamePasswordAuthenticationHandler used to be)

<bean
class="org.jasig.cas.adaptors.ldap.FastBindLdapAuthenticationHandler">
  <property name="filter" value="uid=%u,ou=people,dc=it,dc=mycompany,dc=com" />
  <property name="contextSource" ref="contextSource" />
</bean>

5. Add new bean called contextSource

<bean id="contextSource" class="org.springframework.ldap.core.support.LdapContextSource">
        <property name="pooled" value="true"/>
        <property name="urls">
            <list>
                <value>ldap://localhost/</value>
            </list>
        </property>
        <property name="userDn" value="cn=admin,dc=it,dc=mycompany,dc=com"/>
        <property name="password" value="asdfgh"/>
        <property name="baseEnvironmentProperties">
            <map>
                <entry>
                    <key>
                        <value>java.naming.security.authentication</value>
                    </key>
                    <value>simple</value>
                </entry>
            </map>
        </property>
</bean>

5.2 Building CAS war file

Building CAS war file actually requires only modules cas-server-core, cas-server-webapp and cas-server-support-ldap, however you can always build all components (somemodules simply won’t be used). For me personally, this is much quicker way. So all you really need to do now is to open your command line, go to $CAS_SOURCE folder and type

mvn -Dmaven.test.skip=true clean install

Created war file (called cas.war) can be found inside folder  $CAS_SOURCE/cas-server-webapp/target.  Now all you need to do is to deploy this file in tomcat. Just copy it to folder LIFERAY_ROOT/tomcat/webapps/ .

6. Integrating Liferay with CAS and with openLDAP

6.1 Integrating Liferay with CAS

1. Start Liferay

2. Log into admin account (at this point Liferay is not integrated with CAS yet)
login: test@liferay.com
haslo: test

3. Go to Control Panel -> Settings -> Authentication -> CAS

4. Select values ‘Enabled’ and  ‘Import from LDAP’
[x] Enabled
[x] Import from LDAP

5. In default values change cas-web into cas and localhost into your server’s DNS name (for this tutorial it will be it.mycompany.com) – or leave it localhost if you don’thave DNS name for your server.

6. In field  “Server Name” enter DNS name – it.mycompany.com:443

7. In field “Service URL” enter path to the service – https://it.mycompany.com:443/c/portal/login

6.2 Integrating Liferay with openLDAP

1. Go to Control Panel -> Settings -> Authentication -> LDAP
2. Select ‘Enabled’ option
3. Select openLDAP
4. Values

Connection:
base provider: ldap://localhost:389
base dn: dc=it,dc=mycompany,dc=com
principal: cn=admin,dc=it,dc=mycompany,dc=com
password: asdfgh
(test connection)

Users:
Authentication Search Filter: (uid=@screen_name@)
Import Search Filter: (objectClass=uidObject)
Screen Name: uid
Password: userPassword
Email Address: email
Full Name:
First Name: name
Last Name: sn
Job Title: — leave it empty
Group: member

Groups:
Import Search Filter: (objectClass=groupOfNames)
Group Name: cn
Description: description
User: member
(test connection)

5. In Import/Export:

Import Enabled: [x]
Import on Startup Enabled: [x]
Import Interval: any value e.g. 5 minutes
Export Enabled: [ ]

6. Go to Control Panel -> Settings -> Authentication → General and change “How do users authenticate?” to “By Screen Name”

7. Accept changes by clicking “Save” button

After importing users and groups you need to give  group “admins” a role “Administrator”. Go to Control Panel → Roles → Administrator → Assign Members → User Groups. Select group „admins” and click “Update Associations”.

Part 4 is coming soon….

Reference:

[CAS1] http://www.jasig.org/cas/ – CAS official site
[CAS2] http://en.wikipedia.org/wiki/Central_Authentication_Service – what wikipedia knows
[CAS3] http://www.ja-sig.org/wiki/display/CAS/Home – CAS official wiki

Categories: Articles

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


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