Friday, December 30, 2011

Method Validation With Spring 3.1 and Hibernate Validator 4.2

JSR 303 and Hibernate Validator have been some awesome additions to the Java ecosystem, giving you a standard way to validate your domain model across application layers. Combined with the annotations of the Java Persistence API (JPA) you have some very nice tools at your disposal to ensure that only valid data enters your database.

However, one piece of missing functionality was the ability to also validate method calls. For example, wouldn't it be nice if you could use normal JSR 303 annotations to safeguard business layer calls as well?

Of course you can enforce constraints programmatically, e.g. prevent the passing of Null parameters. Spring for instance provides the org.springframework.util.Assert class. However, it would be desirable, if constraints placed on input parameters as well as return values were part of the method contract.

Enter Hibernate Validator 4.2, which was released in June of 2011. It provides now method validation and Gunnar Morling, one of the committers, has an excellent write-up on this on his blog at:
Also, check out the Hibernate validator documentation regarding method validation. Gunnar Morling also provides some preliminary Spring support available at GitHub:
But the news for Spring aficionados is getting even better - Direct support for Method Validation With Hibernate Validator is now available in the lastest Spring 3.1 release that went GA just two weeks ago.

Specifically Spring 3.1 provides the following support in regards to method validation:
In order to get started, make sure that you are using Spring 3.1.0.RELEASE and that you have Hibernate Validator 4.2 in your classpath. That's all what you need to begin using JSR 303 annotations on the method level. For example, now you can annotate your methods using e.g.:

@Validated
public interface BusinessService {
    @NotNull String convertToUpperCase(@NotEmpty String input);
}
The @Validated Annotation indicates that the methods in the class are to be included for method validation. Keep in mind that you can specify your own annotation that will be enabling method level validation for the annotated class. Specify your own annotation by calling setValidatedAnnotationType on the MethodValidationPostProcessor.

However, placing the annotations themselves will not enforce the constraints 'automagically'. In fact Spring will be using AOP (Aspect Oriented Programming) Advices under the covers that delegate to Hibernate Validator. The easiest way to enable these advices is to declare a MethodValidationPostProcessor bean in your Spring application context as shown below.
 
<?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"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

 <context:component-scan base-package="com.hillert.spring.validation" />

    <bean id="validator"
      class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
      
    <bean class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor"/>
    
</beans>
 
For more details, I have published a small project over at GitHub that illustrates method level validation using Hibernate Validator:
In order to get get started:
  1. Clone the repository using $ git clone git://github.com/ghillert/spring-hibernate-validator-sample.git 
  2. $ cd spring-hibernate-validator-sample
  3. Build the sample using Maven $ mvn clean package
  4. Run it with $ mvn exec:java 
The command-line based sample provides a simple String conversion service, that converts Strings to upper-case. You can insert those Strings from the command line. The Service layer will enforce the following constraints using method level Hibernate Validator annotations:
  • The input String must not be empty (not null and not an empty String)
  • The conversion service will never return null
In order to trigger validation exceptions you can enter some special strings:
  • Pressing just enter (no string entered) will cause an empty String parameter to be set
  • Submitting "null" (The String), will cause a null parameter to be set
  • When entering "returnnull", the underlying business method will return Null
The Main method will catch the occurring MethodConstraintViolationExceptions and print some details to the command prompt.

Lastly, the current method validator support via Spring is specifically targetting Hibernate Validator. However, there are standardization efforts underway as part of the Bean Validation 1.1 specification (JSR-349). In order to follow the progress, please follow also http://beanvalidation.org/.

Spring will provide support for JSR-349 as soon as the official standard has been ratified. In order to track inclusion into the Spring framework, please follow also Spring Framework Jira ticket SPR-8199 . As of today this feature should be available in the next Spring 3.2 release.

I hope this blog entry and the accompanying sample have showed you how easy it is to get started with  method level validation using Spring and Hibernate Validator. Please let me know if you have further questions or run into issues.

Tuesday, December 27, 2011

Java Print Service Frustrations

This is probably not the most exciting "toy" to play with for the holidays, but I wanted to explore some use-cases that involve printing through Java back-end services. Basically, in an enterprise environment you may run into requirements, where the documents you receive or generate also are required to be printed out for whatever reasons. In all honesty, I never had to deal with Java's print Apis and thus started from scratch.

It turns out, that there are 2 approaches (reminds me of the multitude of Date implementations...). One approach dates back to the 1990s and is called the Java 2 Print API and is tied more to User Interfaces (UI) triggering the printing process. With Java 1.4, the Java Print Service API (JPS) was introduced (JSR 6) which serves as a super-set of the the Java 2 Print Api.

The JPS Api is certainly workable but I ran into some serious trouble. For my initial use-case, I may receive simple text documents, e.g. XML that I want to send to a definable printer as plain text.

I was unable to get that to work on my Mac using Mac OS X 10.6.8. However, on my Windows JVM it worked flawlessly and my text files were printed out without any complaints. On my Mac, though, my little Java test application finishes without any errors but my printer queue states:

Error: pstopdffilter/pstocupsraster failed with err number -31000

Googling did not help much either. There seemed to be some anecdotal evidence that other people might have had trouble with text printing as well but I was unable to uncover definite answers (Many of the information is years old). The question I have is whether this is an issue with:
  • My Printer, which is a Brother HL-4070CDW
  • The Mac JVM (Mine is: build 1.6.0_29-b11-402-10M3527)
  • CUPS
  • something else
If any of the readers has encountered similar issues or is able to shed some more light into this issue, please let me know (THANKS!).

While searching for explanations, I stumbled across the following thread on stackoverflow.comhttp://stackoverflow.com/questions/1655297/print-to-specific-printer-ipp-uri-in-java. There they mentioned the following CUPS specific libraries:
Jipsi aparently changed names and moved to Google code:
As I need a generic solution that works not only on Mac using CUPS but also on Windows I have not experimented with any of the libraries above. Nevertheless I wanted to mention them.

I have also tried various other DocFlavors and settings but to no avail. What is interesting, though, is that the printing of PDF files works fine. Printing image files such as PNG or JPG fails as well.

Here is the trivial application that I am using:

import java.io.FileInputStream;
import java.io.FileNotFoundException;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.Sides;

public class PrintPS {

  public static void main(String args[]) throws FileNotFoundException, PrintException {
    FileInputStream textStream = new FileInputStream(args[0]); 
    DocFlavor myFormat = DocFlavor.INPUT_STREAM.AUTOSENSE;
    Doc myDoc = new SimpleDoc(textStream, myFormat, null); 
  
    PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet(); 
  
    aset.add(new Copies(1)); 
    aset.add(Sides.ONE_SIDED); 
  
    PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
  
    System.out.println("Printing to default printer: " + printService.getName());
  
    DocPrintJob job = printService.createPrintJob(); 
    job.print(myDoc, aset); 

  }
}

Furthermore, I looked at the follwing Java-based Text editors to see how they accomplish printing (Which works fine on my Mac as well):
RTEXT uses the DocFlavor: DocFlavor.SERVICE_FORMATTED.PRINTABLE which in turn uses a component that implements the java.awt.print.Printable Interface. 

I guess, as a next step I have two options...go down into the trenches of Java2D or have some fun generating PDF files...And all I wanted was to print some simple text that works across Operating Systems. 

Wednesday, December 7, 2011

DevNexus 2012 - Registration is Open

The Atlanta Java Users Group is delighted to announce that registration for DevNexus 2012 is now open. In order to reserve your ticket, please go to:
DevNexus 2012 will be held on Wednesday, March 21st and Thursday, March 22nd at the Cobb Galleria Centre in Atlanta, GA. We already confirmed many amazing presenters covering a wide array of crucial technology topics.

In addition to providing great content for Java developers, DevNexus is a very valuable networking opportunity. This event attracts Java/JVM talent from diverse backgrounds, be it large corporations, consulting organizations or independent technology connoisseurs. You will have an opportunity to discover what other development teams are using as their favorite tools and practices.

Why should you attend DevNexus 2012:
  • Best Value: $185 Early Bird price (until Feb 1) for two full days of technology immersion and comaraderie.
  • Ask questions to world-class experts and fellow developers
  • Learn how to move your applications into the cloud (covering Cloud Foundry, Heroku, Google App Engine, OpenShift)
  • Learn Agile Best Practices & Tools
  • Learn more about core Java topics as well as other languages on the JVM
  • Learn more about building rich (mobile) web-application applications, e.g. using HTML5
  • Hear about the latest developments from JBoss and SpringSource
We have already lined-up some impressive speakers, with many more to be announced in the upcoming weeks:
  • Tim Berglund - Covering NoSQL topics
  • Patrick Curran - Chairman of the JCP, keynote speaker
  • Hans Dockter  - Founder of Gradle
  • Ben Evans - Covering various core Java topics including Java 8
  • Mark Fisher - Spring Integration Lead, covering Enterprise Integration Patterns (EIP) and Cloud Foundry
  • Barry Hawkins - Covering Agile Methodologies
  • Josh Long - Spring Developer Advocate
  • Pratik Patel - Mobile/Web, Java
  • Rossen Stoyanchev - Spring MVC Lead
  • James Ward - Covering Heroku and Play framework
Fore more details on speakers please visit:

http://www.devnexus.com/s/speakers

We also would like to thank our sponsors for their support in making DevNexus a success:

Gold Sponsors
Silver Sponsor
We hope to see you all at DevNexus, and please register for this incredibly valuable event at:


Thursday, December 1, 2011

Cloud Foundry for Spring Developers - Slides

Yesterday, I presented "Cloud Foundry for Spring Developers", at the Atlanta Spring User Group. I finally got around to upload the presentation slides to Slideshare:

http://www.slideshare.net/hillert/cloud-foundry-for-spring-developers

I would like to thank everyone for coming to the presentation! Cloud Foundry rocks!