Integrating Spring MVC with Hibernate Annotation-Based Validation

In this article, I would like to demonstrate how to integrate Spring MVC, Spring bean validation framework and hibernate validator using annotations. The Hibernate Validator project is implementation of JSR 303 – Bean Validation standard, which defines a metadata model and API for JavaBean validation. For the the purpose of this example, I used Spring Framework v3.0.5 and Hibernate Validator v4.1.0.

What I like about Spring + Hibernate validation, is that this combination eliminates the need to use validator classes in controllers for bean validation. In other words, less code, less classes, everything looks much cleaner.

I am not going to talk about how to build web application from scratch using Spring MVC. I assume that you already have something working in place. I am just going to show the important bits needed, in order to plug hibernate validation in to your code:

1. Define two following beans in your application context XML in your WEB-INF directory:

[xml]
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
[/xml]

The basic configuration above will trigger JSR-303 to initialize using its default bootstrap mechanism. A JSR-303 provider, such as Hibernate Validator, is expected to be present in the classpath and will be detected automatically.

[xml]
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/message-resources.bundle" />
</bean>
[/xml]

The bean above knows how to access resource bundles using specified basenames.

2. Create resource bundle (in this example it is “message-resources.bundle”) under WEB-INF. The resource bundle is where you should define your validation messages that the end user sees if his form submission fails validation. Please note that the bundle does not have to be at the root of WEB-INF, it can be placed also in a sub-directory of WEB-INF. The format for validation messages in your bundle should be as follows:

[java]Annotation.bean-variable-name.bean-propery=validation error message.[/java]

For example:

[java]
NotBlank.someFormName.name=Name must not be blank,
Size.someFormName.name=Name must be less than or equal to {1} characters.
NotBlank.someFormName.street=Street name should not be blank. Please enter a value
NotEmpty.someFormName.selectedItem=Item selection is required
[/java]

The example above describes four different validation messages for different validation rules. In case of a particular validation rule disobeyed, its respective validation message will be found based on the validation annotation, bean name and bean property name.

3. In your controller, in the method that validates bean from the POST request, annotate your bean with annotation @Valid. For example:

[java]
@RequestMapping(value = "/update.html", method = RequestMethod.POST)
public String update (    @ModelAttribute("someFormName")
@Valid SomeForm someFormName,
BindingResult result,
Model model)
{

if(result.hasErrors()) {
// Return view name
}

// Do stuff

// Return view name
}
[/java]

The @Valid annotation is part of the standard JSR 303 – Bean Validation API, and is not a Spring-specific construct. The Hibernate Validator instance invoked when a @Valid method argument is encountered.

Very important: your bean variable name in your controller method (in this case its “someFormName“) must match the bean variable name in your validation message resource bundle.

4. Annotate your bean member variables with annotations that tell Hibernate Validator what should be validated and what are the validation rules:

[java]
public final class SomeForm {

@NotBlank
@Size(min=0,max=20)
private String name;

@NotBlank
private String street;

@NotEmpty
private String selectedItem;

// Getters

// Setters
}
[/java]

As you can see from the above bean, the three fields that should be validated are annotated with @NotBlank, @NotEmpty and @Size. The validation rules are simple: the name property must not be blank nor longer than 20 characters, street property must not be blank, while selectedItem must not be empty.

By the way, you can have more complicated validation rules in place using annotations. It is possible to use expressions which decide whether validation rules should fire. Consider the following, which validate an email field:

[java]
@Email(applyIf="email is not blank")
@NotBlank
private String email;
[/java]

You don’t want to display invalid email format error message when the filed is blank. Therefore that above expression in @Email annotation will have the rule fired only when the property is not blank. Expression can be especially very convenient when validating password fields:

[java]
@NotBlank
private String password;

@NotBlank(applyIf = "password is not blank")
@Expression(value = "confirmedPassword= password", applyIf = "password is not blank")
private String confirmedPassword;
[/java]

Validation rules for confirmedPassword property will fire only when password field will not be blank.

That’s it :) If any rule(s) are disobeyed, the BindingResult result object will be populated with appropriate error messages, loaded from your message bundle. The error messages then can be displayed in your JSP using Spring tag:

[xml]
<spring:hasBindErrors name="someFormName">
<c:forEach items="${errors.allErrors}" var="error">
<spring:message message="${error}"/>
</c:forEach>
</spring:hasBindErrors>
[/xml]

And that is it! Feel free to post a comment if you run into problems and I iwll try to help you the best I can :)

Right Tool For the Right Job

I wanted to start a discussion what is the better choice for an application server when building an enterprise J2E application? Should one go for a Tomcat + Spring combination which provide light-weight simplified alternative to JEE container or should more heavy weight app server like JBoss be considered?

I have found some resources on Stackoverflow that provided me enough information to think about:

  1. What are benefits of JBoss AS-based application architecture?
  2. When to ditch a J2EE container (i.e. JBoss) for straight Tomcat
  3. Should I go with Tomcat or a full J2EE container?

Are There No Other Developing Platforms?

I came across a video called Java 4-Ever Trailer. Produced by guys at Java Zone.  Its a trailer about supposedly upcoming movie about an average family living in .NET world.  Their son grows up to be rebellious by starting to experiment with Java as a teenager. I think it is absolutely hilarious. I had to remove a link to the video on Youtube, because its no longer available there.

http://jz10.java.no/java-4-ever-trailer.html

My favorite moment is when father screams on his last breath “… They actually enable us to send XML messages through SOAP… Through SOAP!! … ”

Brilliant!

Brainteaser: Overridable methods

Consider the following case of inheritance:

[java]
public class Parent {
public Parent() {
getValue();
}
public void getValue() {

}
}

public class Child extends Parent {
private final Integer integer;
public Child() {
integer = new Integer(888);
}

@Override
public void getValue() {
System.out.println(integer);
}
}
[/java]

Question: What would the following program print, why?

[java]
public class Test {
public static void main(String[] args) {
Child child = new Child();
child.getValue();
}
}
[/java]

Lets assume that getValue() implementation in Child class was changed to:

[java]
@Override
public void getValue() {
System.out.println(integer.toString());
}
[/java]

Question: What would the output of the Test class be now, why?

Brainteaser: Broken Case of Inheritance

Consider the following case of inheritance:

[java]
public class ExtendingHashSet<E> extends HashSet<E> {
private int counter = 0;

public ExtendingHashSet() {

}

@Override
public boolean add(E e) {
counter++;
return super.add(e);
}

@Override
public boolean addAll(Collection&lt;? extends E&gt; c) {
counter += c.size();
return super.addAll(c);
}

public int getCounter() {
return counter;
}
}
[/java]

Created instance:

[java]
ExtendingHashSet<String> s = new ExtendingHashSet<String>();
s.addAll(Arrays.asList("one", "two", "three"));
[/java]

Question: What value would s.getCounter() method return at this point and why?

Looking forward for your answers dear readers

Brainteaser: Broken Comparator

Question: The following program returns result “1″, which indicates that first Integer value is greater than the second, why?

[java]
import java.util.*;

public class Example {

public static void main(String[] args) {
System.out.println(&amp;quot;Result: &amp;quot; +
naturalOrder.compare(new Integer(90),
new Integer(90)));
}

private static Comparator&amp;lt;Integer&amp;gt; naturalOrder =
new Comparator&amp;lt;Integer&amp;gt;() {
public int compare(Integer first, Integer second) {
return first &amp;lt; second ? -1 : (first == second ? 0 :1);
}
};
}

[/java]

Please note:
In this case, comparator for natural order on Integer is written for example only, and in practice there is no need to write it.

Looking forward for your answers dear readers

Resources:
Effective Java

Hack any Java class using reflection attack

Have you ever thought how secure your application is? Well reflection attack can demonstrate how vulnerable Java classes are. In this post, I will try to apply reflection attack on a simple Java class to demonstrate vulnerabilities and what can be done to prevent it (in most cases).

Consider a POJO class:

[java]
public final class VictimClass {

private String password = "default_password";
private static final int USER_ID = 3452678;
private String privateFiled = "default_value";

/**
* Private constructor that should
* not be invoked
*/
private VictimClass() {
System.out.println("Oops… " +
"This private constructor was not " +
" suppose to be invoked");
}

/**
* Private accessor
*/
private String getPassword() {
return password;
}

/**
* Private mutator
*/
private void setPassword(String password) {
this.password = password;
}

/**
* Private static method
*/
private static int getUsersId() {
return USER_ID;
}
}

[/java]

The POJO contains private constructor and several private methods and fields, which I will attempt to invoke and modify using reflection attack.

Now, I cannot say that reflection attacks are possible due to a Java bug. No, its simply how Java classes were designed. The core reflection facility was originally designed for component based application builder tools.

In java.lang.reflect, Constructor, Method and Field extend from parent AccessibleObject class. These objects provide access to the class’s methods and fields. By calling inherited parent method setAccessible(), private variables and methods including private constructors become accessible.

My tester class:

[java]
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.ClassNotFoundException;
import java.lang.InstantiationException;
import java.lang.IllegalAccessException;
import java.lang.reflect.InvocationTargetException;
import java.lang.NoSuchMethodException;

public class Tester {

private static String CLASS_NAME = "VictimClass";
private static Class victimClass = null;
private static Object victimClassObj = null;

public static void main(String[] args) {
victimClass = loadClass(victimClass, CLASS_NAME);
printClassStructure();
attack();
}

private static Class loadClass(Class clazzor, String className) {
Thread thread = Thread.currentThread();
ClassLoader classLoader =
thread.getContextClassLoader();

try {
clazzor = Class.forName(className, true, classLoader);
}
catch (ClassNotFoundException e) {
System.err.println("Error: could not find class: "
+ CLASS_NAME);
}

return clazzor;
}

private static void printClassStructure() {

Constructor[] constructors =
victimClass.getDeclaredConstructors();
for (Constructor c : constructors) {
int modifier = c.getModifiers();
System.out.println("Declared constructor name: " +
c.getName() + "ntis accessible: " +
c.isAccessible() + "ntis private: " +
Modifier.isPrivate(modifier) + "n");
}

Method[] methods = victimClass.getDeclaredMethods();
for (Method m : methods) {
int modifier = m.getModifiers();
System.out.println("Declared method name: " + m.getName() +
"ntis accessible: " +
m.isAccessible() +
"ntis private: " +
Modifier.isPrivate(modifier) +
"ntis static: " +
Modifier.isStatic(modifier) + "n");
}

Field[] fields = victimClass.getDeclaredFields();
for (Field f : fields) {
int modifier = f.getModifiers();
System.out.println("Declared field name: " + f.getName() +
"ntis accessible: " +
f.isAccessible() +
"ntis private: " +
Modifier.isPrivate(modifier) +
"ntis static: " +
Modifier.isStatic(modifier) +
"ntis final: " +
Modifier.isFinal(modifier) + "n");
}
}

private static void attack() {

Field[] fields = victimClass.getDeclaredFields();
Method[] methods = victimClass.getDeclaredMethods();
Constructor[] constructors =
victimClass.getDeclaredConstructors();
//make constructor accessible
constructors[0].setAccessible(true);

System.err.println("Initiating reflection attack:");
try {
//create new object by invoking private constructor
victimClassObj = constructors[0].newInstance(new Object[] {});

//make static method accessible and get its value
//please note: when invoking static method,
//object represented by this Method is null
methods[2].setAccessible(true);
Object o = methods[2].invoke(null, new Object[] {});
System.out.println("Got user ID from private static accessor: "
+ o.toString());

//make method accessible and get its value
methods[0].setAccessible(true);
o = methods[0].invoke(victimClassObj, new Object[] {});
System.out.println("Got original password from private accessor: "
+ o.toString());

//make method accessible and set to it new value
methods[1].setAccessible(true);
System.out.println("Injecting new password using private mutator");
methods[1].invoke(victimClassObj, new Object[] {"injected_password"});

//get method’s its new value
o = methods[0].invoke(victimClassObj, new Object[] {});
System.out.println("Got injected password from private accessor: "
+ o.toString());

//make field accessible and get its value
fields[2].setAccessible(true);
o = fields[2].get(victimClassObj);
System.out.println("Got private field: " + o);

//make field accessible and set to it new value
System.out.println("Injecting value to a private field:");
fields[2].set(victimClassObj, "new_default_value");

//get field’s its new value
o = fields[2].get(victimClassObj);
System.out.println("Got updated private field: " + o);

//make field accessible and get its value
fields[1].setAccessible(true);
o = fields[1].get(victimClassObj);
System.out.println("Got private static field: " + o);

//make field accessible and set to it new value
System.out.println("Injecting value to a private static final field:");
fields[1].set(null, new Integer(2));

//get field’s its new value
o = fields[1].get(victimClassObj);
System.out.println("Got updated private static final field: " + o);

}
catch (InstantiationException e) {
System.err.println("Error: could not instantiate: " + e);
}

catch (IllegalAccessException e) {
System.err.println("Error: could not access: " + e);
}

catch (InvocationTargetException e) {
System.err.println("Error: could not invoke the target: " + e);
}
}
}

[/java]

The call to setAccessible() can be restricted if SecurityManager is set, then any attempt to call the method above will result in exception. If required, it is possible to grant permission java.reflect.ReflectPermission “suppressAccessChecks” using external java.policy file or by applying security policy programmatically. This permission will allow invocation of setAccessible(). My other post How to set SecurityManager and Java security policy programmatically explains how this can be achieved. Please note: by doing so, you can allow malicious access to your classes.

This is what happens when program executes:
I am using reflection, to get a print out of declared constructors, methods and fields. Following that, I am invoking private static and non-static method and attempting to change the value of private declared fields.

The program produces the following output:

[java]
Declared constructor name: VictimClass
is accessible: false
is private: true

Declared method name: setPassword
is accessible: false
is private: true
is static: false

Declared method name: getUsersId
is accessible: false
is private: true
is static: true

Declared method name: getPassword
is accessible: false
is private: true
is static: false

Declared field name: password
is accessible: false
is private: true
is static: false
is final: false

Declared field name: USER_ID
is accessible: false
is private: true
is static: true
is final: true

Declared field name: privateFiled
is accessible: false
is private: true
is static: false
is final: false

Initiating reflection attack:
Oops… This private constructor was not suppose to be invoked
Got user ID from private static accessor: 3452678
Got original password from private accessor: default_password
Injecting new password using private mutator
Got injected password from private accessor: injected_password
Got private field: default_value
Injecting value to a private field:
Got updated private field: new_default_value
Got private static field: 3452678
Injecting value to a private static final field:
Error: could not access: java.lang.IllegalAccessException: Field is final
[/java]

As output shows above, it is not possible to set a value to the filed that is final. Therefore, it would be good idea to make fields final whenever possible. As it was shown before, it prevents reflection attack (when trying to set a new value), plus to that its good for performance optimization (memory allocation).

So what we got so far? When we have a POJO, it is possible to invoke private constructor, private static and non-static methods and change the value of private fields.

Enumerators on other hand do not allow invocation of their private constructors. An attempt to do so will result in IllegalArgumentException exception: “Cannot reflectively create enum objects”. Enums are safe against invocation of private constructors through reflection attacks.

Since enum object instances cannot be created through reflection, private non-static methods cannot be invoked. Having said that, it is still possible to invoke private static methods on enum using reflection, like on any other Java class.

Update: private non-static methods can be invoked on enum class, please refer to comments.

In conclusion, number of steps can be taken, in case someone really wants to prevent reflection attack on non-enum Java classes:

  1. Make fields final whenever possible
  2. Private constructor can throw an exception if there will be an attempt to invoke it.
  3. Applying security policy without ReflectPermission and setting security manager

I hope that I was descriptive enough here, I will appreciate your comments here.

The source code for this post was tested in my Eclipse and is attached.

Cheers

How to Set SecurityManager and Java Security Policy Programmatically

In this example I want to show how to use SecurityManager to prevent unauthorized access to private members of a Java class, for example using reflection to invoke private constructor. Besides that I also want to show how Java security policy can be set programmatically with permission allowing to invoke private constructor through reflection when security manager is in place.

Consider a POJO:

[java]
public final class VictimClass {
/**
* Private constructor that should
* not be invoked
*/
private VictimClass() {
System.out.println("Instance created");
System.out.println(
"Constructor was made accessible");
}
}
[/java]

I want to prevent invocation of private constructor, by setting security manager. After first invocation attempt, I do want to invoke private constructor by granting required permission by refreshing current security policy.

This is my tester class:

[java]
import java.lang.reflect.Constructor;
import java.lang.ClassNotFoundException;
import java.lang.InstantiationException;
import java.lang.IllegalAccessException;
import java.lang.reflect.InvocationTargetException;
import java.lang.NoSuchMethodException;
import java.security.AccessControlException;
import java.lang.reflect.ReflectPermission;
import java.security.SecurityPermission;

public class Tester {

private static String CLASS_NAME = "VictimClass";
private static Class victimClass = null;

public static void main(String[] args) {

loadClass(victimClass, CLASS_NAME);

//apply default policy with one permission
System.setProperty("java.security.policy","default.policy");

try {
//Setting security manager
SecurityManager sm = new SecurityManager();
System.setSecurityManager(sm);
} catch (SecurityException e) {
System.err.println("Error: could not set security manager: " + e);
}

//first attempt to make constructor accessible
try {
makeConstructorAccessible();
}
catch (AccessControlException e) {
System.err.println(
"Could not made constructor accessible: " + e.getMessage());
}

System.out.println("Applying ReflectPermission programmatically…");
SecurityPolicy.getPolicy().addPermission(
new ReflectPermission("suppressAccessChecks"));
SecurityPolicy.getPolicy().addPermission(
new SecurityPermission("setPolicy"));
SecurityPolicy.getPolicy().refresh();
makeConstructorAccessible();
}

private static void loadClass(Class clazzor, String className) {
Thread thread = Thread.currentThread();
ClassLoader classLoader =
thread.getContextClassLoader();

try {
victimClass = Class.forName(className, true, classLoader);
}
catch (ClassNotFoundException e) {
System.err.println("Error: could not find class: "
+ CLASS_NAME);
}
}

private static void makeConstructorAccessible() {
Constructor[] constructors =
victimClass.getDeclaredConstructors();
//make constructor accessible
constructors[0].setAccessible(true);

try {
System.out.println(
"Creating new instance by invoking private constructor");
constructors[0].newInstance(new Object[] {});
}
catch (InstantiationException e) {
System.err.println("Error: could not instantiate: " + e);
}
catch (IllegalAccessException e) {
System.err.println("Error: could not access: " + e);
}
catch (InvocationTargetException e) {
System.err.println("Error: could not invoke the target: " + e);
}
}
}
[/java]

This is what happens when program executes:

Before setting SecurityManager, I am applying default security policy from external file with security permission “setPolicy”, that will allow me to reset new security policy in the future.

My default security policy:

[java]
grant {
permission java.security.SecurityPermission "setPolicy";
};
[/java]

When SecurityManager is set, it restricts everything except whats permitted by security policy that was set previously. You can view list of Java permissions that can be set here.

By default, the private constructors,methods and fields are inaccessible. So if you want to use reflection, and invoke private constructor of this POJO, it will result in
IllegalAccessException since the constructor above has private modifier.

This restriction can be bypassed by calling parent method setAccessible(). To remind: java.lang.reflect.Constructor, java.lang.reflect.Method and java.lang.reflect.Field extend from parent java.lang.reflect.AccessibleObject class.

By calling inherited parent method setAccessible(), private variables and methods including private constructors become accessible.

With SecurityManager set, an attempt to invoke setAccessible() will result in AccessControlException. Following that, I am granting required ReflectPermission suppressAccessChecks by applying my own security policy. This will allow me to invoke private constructor in my POJO.

Now, having said that, I have to say that granting ReflectPermission with action suppressAccessChecks can be extremely dangerous as it allows private constructors to become accessible, as the example above shows. Not only constructors, but inaccessible fields and methods can become accessible, which can allow room for reflection attacks. In my other post Hack any Java class using reflection attack I explain how this can be achieved.

When I am applying my own security policy, please note that I am granting again security permission “setPolicy”. Because I am reseting default policy set previously, I have to grant “setPolicy” permission again if I want to keep applying new security policies in the future at run time of this program.

Below is my own implementation of java.security.Policy class, I tried to put enough comments to make things straight forward to you readers:

[java]
import java.security.Policy;
import java.security.CodeSource;
import java.lang.reflect.ReflectPermission;
import java.security.SecurityPermission;
import java.security.*;
import java.lang.RuntimePermission;
import java.util.*;

public class SecurityPolicy extends Policy {

private PermissionCollection perms = null;

//lazy initialization class holder
private static class SecurityPolicyHolder {
private static final SecurityPolicy policy = new SecurityPolicy();
}

private SecurityPolicy() {
perms = new Permissions();
}

public static SecurityPolicy getPolicy() {
return SecurityPolicyHolder.policy;
}

public PermissionCollection getPermissions(CodeSource codesource) {
return perms;
}

//invoked when new Permission is added to the current security Policy
public boolean implies(ProtectionDomain domain, Permission permission) {

//get permission collection from the domain
PermissionCollection domainPermissions = domain.getPermissions();

//get enumeration of permission elements
Enumeration<Permission> permissions = domainPermissions.elements();

//convert to array list (dont have to, i just dont like enumerations)
ArrayList<Permission> list = Collections.list(permissions);

//Checks to see if the specified permission is
//implied (subset of) by the collection of
//Permission objects held in this PermissionCollection
if (!domainPermissions.implies(permission)) {

//permission collection in the domain is read-only,
//Exception will be thrown if Permission object
//is added to read-only collection
if (domainPermissions.isReadOnly()) {

//Because collection is read-only,
//add Permission objects to the local
//permission collection instead
for (Permission p :list) {
if (!perms.implies(p)) {
perms.add(p);
}
}

//assign local permission collection as a
//domain permission collection
domainPermissions = perms;
}
else {
//if domain permission collection is not read only,
//just add new permission to it
domainPermissions.add(permission);
}

//check if now domain has the new Permission
return domainPermissions.implies(permission);
}

return false;
}

public void addPermission(Permission permission) {
perms.add(permission);
}
//you can write your own implementation
//of refresh method
@Override
public void refresh() {
Policy.setPolicy(this);
}
}
[/java]

The following shows program output. Please not that first attempt to make private constructor accessible resulted in exception. After required permission was granted, new object instance was succesfully created through reflection:

[java]
Could not made constructor accessible:
access denied (java.lang.reflect.ReflectPermission suppressAccessChecks)
Applying ReflectPermission programmatically…
Creating new instance by invoking private constructor
Constructor was made accessible
Instance created
[/java]

Please note:
I did test this code. But I am not sure whether my SecuriyPolicy class implemented efficiently. The source code for this post is attached.

set java security policy sourcecode

Brainteaser: ArrayList VS TreeSet

When I came across the following example I did not expect the results that the program has printed :) hehe…

Question: What does this program print? Why?

[java]
import java.util.*;

public class SetList {

public static void main(String[] args) {

Set<Integer> set =
new TreeSet<Integer>();
List<Integer> list =
new ArrayList<Integer>();

for (int i = -3; i < 3; i++) {
set.add(i);
list.add(i);
}

for (int i = 0; i < 3; i++) {
set.remove(i);
list.remove(i);
}

System.out.println(set + " " + list);
}
}
[/java]

Looking forward for your answers dear readers

Resources:
Effective Java

Patch For Flex Builder 3 Plugin to Work With Eclipse 3.4 (Ganymede)

I installed few days ago new version of Eclipse (Ganymede) and today I tried to install flex builder v3.

The installation went fine, but I got the following exception when trying to open Flex editor in Eclispe: “…org.eclipse.jface.util.Assert$AssertionFailedException: Assertion failed…”.

After Googling for some time I came across the following fix. So… there you go