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.

Labels: , ,

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. 

Labels: , , ,

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:


Labels: , , , ,

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!

Labels: , , , ,

Tuesday, November 29, 2011

Cloud Foundry for Spring Developers


I will be presenting at the Atlanta Spring User Group tonight (Nov 29, 2011) at 6:30pm. For more details, including directions, please visit:

http://www.meetup.com/AtlantaSpring/


Title: Cloud Foundry for Spring Developers

Session abstract:

This session provides an overview of how to build and deploy Spring-based applications to the Cloud Foundry platform.
The session will cover application configuration parameters, binding services to your application, deployment options using using STS, the vmc command tool, as well as the new Apache Maven plugin for Cloud Foundry. Gunnar will demonstrate how to deploy applications to both micro and public Cloud Foundry and will also show how debugging works with Cloud Foundry and how you can inspect services remotely using Caldecott.

Gunnar will also show various options to keep your War-files deployable to both Cloud Foundry and stand-alone Servlet Containers using Auto-Reconfiguration, the Cloud namespace, and Spring 3.1 profiles.

Lastly, he will give a high-level overview how you can use Cloud Foundry together with Spring Integration in order to create scalable Spring applications.

Labels: , ,

Wednesday, November 2, 2011

DevNexus 2012 - Call For Papers Now Open


The DevNexus™ 2012 developer conference is taking place March 21-22. We are delighted to announce the Call for Papers is now open. We are looking forward to receiving your amazing proposals covering one of the following topics:
  • Java and JVM Languages
  • Cloud
  • NoSQL
  • Web (incl. Mobile Development, HTML5, JavaScript)
  • Methodologies and Tools
We do not encourage overt marketing pitches. Sessions are 75 minutes long and we encourage breakout sessions, work-shops and case studies. Please include the following information:
  • Name
  • Job Title
  • Email
  • Twiter id
  • Company
  • Presentation Title
  • Audience Level (General, Beginner, Intermediate, Advanced)
  • Presentation Abstract
  • Your Bio
Please submit your proposals as soon as possible to info at ajug.org. The Call for Papers closes January 15, 2012.
The planning committee will carefully review your proposals, and you will get a confirmation whether your talks are selected or not for the DevNexus™ conference.
For more information, please visit: http://www.devnexus.com/

Labels: , , , ,

Thursday, September 22, 2011

Maven and Cloud Foundry - The plugin is here!

It has been an amazing time so far for me working at SpringSource for the past couple of months and today I have finally published my first blog post for the official SpringSource blog. The blog post also marks the Milestone 1 (M1) release of the Cloud Foundry Maven Plugin which will make it much easier for Maven users to deploy their applications to Cloud Foundry.

Thus, checkout the blog post, use the plugin and follow the project over at GitHub. Please provide plenty of feedback - it is highly appreciated!

Labels: , , , ,

Friday, July 29, 2011

OSCON 2011 - Mission Accomplished


OSCON 2011 - Mission Accomplished and a week of amazing learning and networking is finally coming to an end. I had flown in not only for OSCON Java but also for the Community Leadership Summit, that took place last Saturday and Sunday (but Sunday, I attended the JVM languages day instead, which was wonderful as well).

I was super-impressed with the variety of people from all over the planet, not only the US but also Europe and the Americas. E.g. if you saw somebody wrapped in a flag…that was Bruno Souza, the man that has put Brazil on the map for Java developers. Furthermore, all the cool open-source companies that you could ever think of were present as well. Just an awesome level of energy there.

Also, I was able to connect with a ton of VMware/SpringSource folks at the event that I hadn’t met personally before, yet. Just to give you an idea of how awesome the open-source community is: On Tuesday we went out for some great food at McMenamins Kennedy School. It is housed in an old school with everything left intact/restored (incl. the showers in the rest rooms). That place has 5 bars, restaurant and excellent outdoor seating.

Anyway, our group included Dan Allen from JBoss (member of the Seam, Weld and Arquillian projects), Peter Neubauer from Neo4J (Founder, good chance for me to speak some German ;-), William  Rowe from SpringSource (Apache Foundation Vice President, HTTP Server), David Blevins from IBM (Co-founder of Geronimo and OpenEJB), Mark Johnson from SpringSource  (President of NEJUG),  Bruce Snyder from SpringSource (ActiveMQ comitter), Josh Long from SpringSource (Developer advocate and author), Steve Mayzak from SpringSource (Author). Seriously, to me, this was like being backstage! Thanks for having the chance to meet you all!

Back to OSCON here are the sessions I was able to attend:

Monday

  • Theory of Caching (Greg Luck)
  • Java Puzzlers – Scraping the Bottom of the Barrel (Josh Bloch, Bob Lee)
  • The Ghost in the VM: A Reference to References (Bob Lee)

Tuesday

  • Everything You Wanted to Know about Open Source that Nobody Told You (Jeff Genender)
  • Managing Thousands of Cloud Instances with Java (Patrick Lightbody)
  • ActiveMQ in Action – Common Problems and Solutions (Bruce Snyder)
  • The Evolution of Java: Past, Present, and Future (Josh Bloch)
  • From Ruby on Rails to Java: The Gory Details (Steve Jenson) 
  • A Giant Hop Forward with Spring Roo (Steve Mayzak and Josh Long

Labels: , ,

Thursday, July 21, 2011

Priority Channels in Spring Integration

As somebody was asking about a Priority Channel example for Spring Integration in the forums today, I went ahead and created a simple example. You can grab the source code over at GitHub:

https://github.com/ghillert/spring-integration-examples/tree/master/priority-channel-example

For some additional information check out the related forum entry:

http://forum.springsource.org/showthread.php?112368-PriorityQueue-example-needed

Labels: , ,

Monday, July 4, 2011

HTML5 WebSockets for JVM Developers

Anything related around HTML5 seems to be a hot button topic these days and lucky for me that I got an opportunity to take a deep dive into WebSockets. Thus, I will use this blog to post my findings over the next few days and I will present some simple code examples as well.

Anyway, WebSockets allow Servers to basically "push" data back to subscribed Browser clients in an effective manner instead of using workarounds such as long-polling. The WebSockets API is being standardized by the W3C (http://dev.w3.org/html5/websockets/) and the actual protocol is being defined by the Hypertext-Bidirectional (HyBi) working group (Part of IETF) - http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-09.

For further reading and to learn more about WebSockets in general, please also check out the following resources:
It turns out, though, that the only browsers, that support WebSockets out of the box right now, are Safari and Chrome. Wait - Firefox is not supported? Well, Firefox does support WebSockets but it is disabled by default due to security issues with the implemented draft version of the WebSocket protocol (Firefox 4+5). You can find more information about this here:
Nonetheless, if you're interested, you can re-activate WebSockets in Firefox 4 and 5 quite easily. Take a look at the following link for more information on how to do this:
Firefox 6 is supposed to bring back websockets support, albeit using a newer draft of the websocket protocol (hybi-07), which is not backwards compatible.

What about Web Servers?

Okay, so WebSockets look cool, yet with limited browser support. Furthermore, different webservers have varying stages of support for asynchronous messaging, with Jetty and Glassfish being the best options currently a provide native websocket support. It looks like Resin also has direct websocket support. See also:
Tomcat 7 currently does not support WebSockets, yet. Check out the following issue tracker entry to learn more about the current state of affairs in Tomcat 7:
What's next?

So, essentially what we want is some kind of framework that supports "graceful degradation": when available a suitable framework shall use websockets, but if not available, the framework should fall back to more traditional push work-arounds such as long-polling.

On the server-side, I am running Java, and therefore, I need a respective implementation on that platform. Choices, though, seem to be rather limited and I came up with the following list of options:
Just for reference, there seems to be quite some activity going on outside of Java:
My choice for now

Socket.IO looks like it has quite some traction but the default implementation is for Node.JS. There are Java implementations available but they did not seem to have much traction. jWebSocket actually looks promising but its licensing (LGPL) is too restrictive to me (My choice needs to be Apache license compatible ;-).

Out of the list above, I chose Atmosphere (http://atmosphere.java.net/). Atmosphere has pretty much all the features you would like to have incl. detecting server-side capabilities and using the best possible approach transparently. Atmosphere comes with a jQuery plugin that abstracts away the implementation details (same Api for using long-polling vs. websockets)

While Atmosphere comes with quite a few examples, they are interestingly mostly for JAX-RS and there are no examples for Spring MVC. Also, the documentations is rather limited but luckily you get very swift and helpful responses from Atmosphere mailing list.

In my next posting, I will provide a little example integrating Spring MVC and Atmosphere. So stay tuned.

Nevertheless, if you have other WebSocket recommendations and/or thoughts, please leave comments!

PS:

A funny thing, I just realized that Burr Sutter, a friend of mine and fellow AJUG board member wrote down his WebSockets research experiences as well. It is a small world. Go check it out at:

Labels: , ,

Tuesday, May 24, 2011

Testing Email Notifications with Apache James 3.0

On windows machines I have been using Mailster for testing email notifications. Unfortunately, I had issues with Mailster in the past running on non-Windows machines. Thus, on Mac I have been using a local Postfix instance, which forwarded email to dedicated (real) mailboxes. But, it involved a bit of customization and ultimately I had to "know" to which mailboxes I wanted to send notifications to.

However, ideally I don't really care about email addresses. Instead I typically want to verify that the format and layout of the generated emails are good, be it text emails ort Html emails. Ultimately, it would be nice, if for testing, all notification sent ended up in ONE mailbox for development testing purposes.

Enter Apache James. Not long ago I came across this wonderful blog posting below about using Apache James 2.x in order to test application email notifications:


http://livingtao.blogspot.com/2007/05/testing-application-generated-emails.html

IT is amazing to see that this is pretty much the only dedicated blog posting on the internet regarding a seemingly very common issue. You would think that almost every serious enterprise application has to sent out email notifications, and be it solely for the "forgot password" feature. What is so fantastic about using Apache James, is that it allows you to test Email notifications, while sitting on a plane with no internet in sight. Just run everything locally.

Anyway, the steps illustrated in the blog above also work nicely for James 3.0 (currently milestone 2). What is pretty cool about Apache James is that it is now Spring-based :-)

Here are the simple steps to get things set up for Apache James 3.0:
  • Download Apache James 3.0
  • Unzip the downloaded archive
  • Edit mailetcontainer.xml in directory /conf/
  • Search for "<processor name="transport">"
  • Replace the entire element that starts with "<mailet match="All" class="RemoteDelivery">" with: "<mailet match="All" class="Forward">    <forwardto>test@localhost</forwardto></mailet>"
  • Startup Apache James 3.0 using sudo /bin/run.sh (Sudo is needed for local permissions)
  • Connect via Telnet to Apache James using:  telnet localhost 4555 (User: root password: root)
  • Type: adduser test test <return>
  • ./james-cli.sh -h localhost adddomain localhost
  • ./james-cli.sh -h localhost adduser test@localhost test
  • Setup Thunderbird (or your favority email application)




I hope this gives you enough starting points for setting up email notification testing. Please leave comments  if you see areas I can improve upon. Onward...

Labels: , ,

Saturday, April 30, 2011

Spring 3.1 Bean Definition Profiles - Use Case

As I am diving deeper into VMware's Cloud Foundry, I decided to make the DevNexus conference web-application fit for Cloud Foundry. However, instead of creating an explicit version of the application for Cloud Foundry, my goal is to have one War file that can be deployed without modifications to either CloudFoundry or a stand-alone servlet container.

Here one new Spring 3.1 feature comes in handy: Bean definition profiles. Bean definition profiles allow you to conditionally load Spring beans. There are some great resources already out there on how to use Bean definition profile, and thus I won't go into the details here:
How am I using Bean Definition Profiles for the DevNexus web-application? 

Personally, I like to develop web applications that can run in a wide variety of environments with as little configuration as necessary. For my use-case, I want to create a single war file that can be deployed to the cloud,  but which can also be deployed into your locally running Tomcat, Jetty, etc.

Furthermore, I believe that bean definition profiles can also be very useful for demo/integration testing purposes. For web applications, I like the concept of "application home directories". They contain configuration files (e.g. DB connectivity parameters), data files such as for Hibernate Search etc.) and the web application will reference the home directory either through a system property, environment variable or looks in a default directory in your user directory. But what if the home directory does not exist?

If the home directory does not exist, then the application runs in demo mode (or embedded mode), which means, the application use an embedded database for persistence and to also loads a set of seed+demo data at application startup-up.

Summarizing, I can think of the following Web application "modes" aka profiles:
  • Embedded mode (Integration testing and Demo mode)
  • Cloud Foundry mode (e.g. reference the MySql service, don't use file-system properties)
  • Stand-alone deployment mode (Uses home directory)
Thus, I can create a dedicated Bean definition profile in my Spring application context for each mode. Here is an example I have:

 <beans profile="default">
        <bean id="propertyConfigurer"
            class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="searchSystemEnvironment" value="true" />
            <property name="locations">
                <list>
                    <value>file:${TING_HOME}/ting.properties</value>
                </list>
            </property>
        </bean>
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
            destroy-method="close">
            <property name="driverClassName" value="${database.jdbc.driverClassName}" />
            <property name="url" value="${database.jdbc.url}" />
            <property name="username" value="${database.jdbc.username}" />
            <property name="password" value="${database.jdbc.password}" />
            <property name="maxActive" value="100" />
            <property name="maxIdle" value="30" />
            <property name="maxWait" value="1000" />
            <property name="poolPreparedStatements" value="true" />
            <property name="defaultAutoCommit" value="true" />
        </bean>
        <bean id="entityManagerFactory"
            class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter" />
            <property name="persistenceUnitName" value="base" />
            <property name="jpaProperties">
                <props>
                    <prop key="hibernate.dialect">${database.hibernate.dialect}</prop>
                    <prop key="hibernate.query.substitutions">true '1', false '0'</prop>
                    <prop key="hibernate.generate_statistics">true</prop>
                    <prop key="hibernate.cache.use_second_level_cache">true</prop>
                    <prop key="hibernate.cache.use_query_cache">true</prop>
                    <prop key="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</prop>
                    <prop key="hibernate.show_sql">${database.hibernate.show_sql}</prop>
                    <prop key="hibernate.format_sql">true</prop>
                </props>
            </property>
        </bean>
    </beans>
    <beans profile="cloud">
        <cloud:data-source id="devnexus-db"/>
        <bean id="entityManagerFactory"
            class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
            <property name="dataSource" ref="devnexus-db" />
            <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter" />
            <property name="persistenceUnitName" value="base" />
            <property name="jpaProperties">
                <props>
                    <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                    <prop key="hibernate.query.substitutions">true '1', false '0'</prop>
                    <prop key="hibernate.generate_statistics">true</prop>
                    <prop key="hibernate.cache.use_second_level_cache">true</prop>
                    <prop key="hibernate.cache.use_query_cache">true</prop>
                    <prop key="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</prop>
                    <prop key="hibernate.show_sql">false</prop>
                    <prop key="hibernate.format_sql">true</prop>
                    <prop key="hibernate.hbm2ddl.auto">create-drop</prop>
                </props>
            </property>
        </bean>
    </beans>
    <beans profile="embedded">
        <jdbc:embedded-database type="H2" id="dataSource"/>
        <bean id="entityManagerFactory"
            class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter" />
            <property name="persistenceUnitName" value="base" />
            <property name="jpaProperties">
                <props>
                    <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
                    <prop key="hibernate.query.substitutions">true '1', false '0'</prop>
                    <prop key="hibernate.generate_statistics">true</prop>
                    <prop key="hibernate.cache.use_second_level_cache">true</prop>
                    <prop key="hibernate.cache.use_query_cache">true</prop>
                    <prop key="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</prop>
                    <prop key="hibernate.show_sql">false</prop>
                    <prop key="hibernate.format_sql">false</prop>
                </props>
            </property>
        </bean>
    </beans>

What about integration testing? 

As of writing this blog posting the latest Spring 3.1 release is: 3.1.0.M1 and there is no explicit support for selecting profiles in your test declaratively. There is, though, the following new feature request Jira:

https://jira.springsource.org/browse/SPR-7960 - "TestContext framework should support declarative configuration of bean definition profiles"

This feature is scheduled for Spring 3.1 M2, but in the meantime, I use a static block which does the trick:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
        locations={
          "classpath:spring/applicationContext-core-data.xml",
          "classpath:spring/mainApplicationContext.xml"
                 })
public abstract class BaseDaoIntegrationTest {
 
static {
  System.setProperty("spring.profiles.active", "embedded");
 }
 
    protected @PersistenceContext(unitName="base") EntityManager entityManager;

}

Over the next few days I hope to deploy an updated DevNexus application to Cloud Foundry, so stay tuned for updates.

Labels: , ,

Thursday, April 14, 2011

First explorations into SpringSource's CloudFoundry

I received my credentials last night for SpringSource's CloudFoundry and I am now in the process of going through the examples. Next, I plan to make some of my applications (home-projects) work on the cloud. The general documentation so far seems to be a still a bit scattered. Therefore, below I summarize all the documentation and resources I have used so far to immerse myself into the services provided by the CloudFoundry. Hopefully it provides a good starting point for you as well.

Background information
There are quite a few examples posted on GitHub, that are a tremendous help in getting started:
Deploy Applications to the cloud from within Eclipse (STS)
Deploy Applications to the cloud using the command line tool vmc
Spring Roo Support
Groovy/Grails 
Further reading
Mark Fisher published a great general article covering both, the vmc command line tool and Eclipse:
Make also sure you hit the forums:
And when you really want to look under the hood, take a look at the source code for CloudFoundry at:
It seems like that when checking out CloudFoundry, it is also a great opportunity to familiarize yourself with Spring 3.1 (see this Spring blog post detailing some of the new features). While I think it is not strictly required it provides functionality that is quite useful for cloud deployment scenarios such as:
More details on that in my next blog post. Back to the cloud...

Labels: , ,

Monday, April 4, 2011

Spring Integration - Camellos Continued

We had a great DevNexus conference this year and we were extremely blessed, that the project leads of both, Apache Camel (Claus Ibsen) and Spring Integration (Mark Fisher), spoke at the conference. In my opinion both frameworks are probably the best integration frameworks on the JVM!

Back in late 2009 I had written a blog post, where I presented some results from my Apache Camel learning experience. Now in 2011 it is time to do the same for Spring Integration. I am in the process of creating a few examples for Spring Integration that I create while learning it. So my hope is to create a little series of blog posts covering Spring Integration and Enterprise Integration Patterns (EIP) in general.

Nevertheless, don't forget to check out the wonderful examples that are provided via the Spring Integration Git repo at: http://git.springsource.org/spring-integration/samples/. It contains a sophisticated list of examples and is the best place to get started.

Well, let's get started - The source code for my example is available via GitHub, and will be successively expanded with additional examples in the coming weeks:
For right now the implemented core Spring Integration functionality in Camellos si is the following:

 
  1. A user drops a file in a local directory (/camellos-si/data/inbox/), that is continuously polled by Spring Integration.
  2. The file is picked up by Spring Integration and converted to a byte array with the original file being deleted.
  3. The resulting byte array is sent to an in-memory channel.
  4. A custom transformer will pick up the data array and compress the data using a ZipOutputStream
  5. The resulting byte array is yet again being sent to another channel.
  6. Finally an Outbound Channel Adapter will grab the data from the channel and send it via Ftp to an embedded Ftp server (stored under: /camellos-si/data/ftp/).
In order to try it out - just download camellos-si-distribution-1.0.zip from the downloads section at https://github.com/ghillert/camellos-spring-integration. Unzip it and start the application by executing:

java -jar camellos-si.jar

That's it. Spring Integration should boot up and you can drop files you want to zip up into '/camellos-si/data/inbox/'.

* * *

Some interesting additional features covered by my example:


Maven Shade Plugin (http://maven.apache.org/plugins/maven-shade-plugin/)

The Maven Shade Plugin can be a nice simplifier in stand-alone deployment scenarios. Let's say you have a project with multiple jar dependencies, then you can use this plugin to merge all jar dependencies into one single jar. You can also configure the Maven Shade Plugin so that it generates the Main-Class property in META-INF/MANIFEST.MF and consequently, you can deliver a single jar (No class-path hell) and execute the application like my simple example:

java -jar camellos-si.jar

Maven Assembly Plugin (http://maven.apache.org/plugins/maven-assembly-plugin/)

The Maven Assembly plugin helps with creating distributable packages. For instance for my example I need not only the compiled jar file but I also need a few directories in the right place, e.g. Apache FtpServer requires the users.properties file to be an actual file (having it as a class path resource embedded in your jar won't work).

Basically, you can use the Maven Assembly Plugin to move things around and to mold your resulting distributable package (a Zip file in my case).

Embedded Ftp Server using Apache FtpServer (http://mina.apache.org/ftpserver/)

Something I always find intriguing with Spring is the simple embedability of additional services such as running ActiveMQ embedded in your Spring context by just adding a single line of Xml, or in this case embedding Apache FtpServer. I know it is a blurry line where you start building your own application server but mentally I still find it easier to do it in Spring than using an app server, particularly when you only want to do it for testing, showcasing etc. and move on to use external ActiveMQ, Ftp Server instances for production etc.

I hope this example has been enlightening for your own Spring Integration discoveries - stay tuned for more. 



Labels: , , , ,

Tuesday, March 8, 2011

DevNexus 2011 - Tools to Get Stuff Delivered

Dear fellow developers,

DevNexus 2011 is only 2 weeks away (March 21-22) and if you haven't registered, yet, please seize the moment and register at http://www.devnexus.com/. Please hurry as registration is closing in one week.
Already, we are pleased to note that we surpassed the number of attendees compared to last year's conference. A big THANK YOU to all of you that registered so far!!


We will be having several raffles: an iPod Nano provided by JBoss, a Flash Builder 4 Premium license provided by Adobe and we will raffle a selection of books. Zero Turnaround is giving to every attendee a JRebel + Enterprise Add-on licenses (for 4 months).

And that is not all! We will have a cocktail hour on March 21st, which is an awesome opportunity to network, talk to speakers and enjoy free drinks.

DevNexus 2011 is your chance to learn about the latest trends in mobile application development, UI frameworks, NoSQL, core Java technologies and the latest from JBoss, Springsource and much more.

This year we also have a focus on Tools and Best Practices that make you more productive as a developer which encompasses an exciting set of sessions such as:

Git Foundations and Advanced Git Tricks
http://www.devnexus.com/s/presentations#1119
http://www.devnexus.com/s/presentations#1120

Gradle
http://www.devnexus.com/s/presentations#1115

Arquillian
http://www.devnexus.com/s/presentations#1152

Selenium RC
http://www.devnexus.com/s/presentations#1158

There are many more sessions to choose from - a total of 35 sessions (incl. 3 keynotes) across 4 parallel tracks. Our schedule is now finalized - Take a look at: http://www.devnexus.com/s/schedule

We would also like to thank our sponsors, who help us tremendously by off-setting much of the substantial costs associated with this event:

Gold Sponsors
  • Terracotta
  • The Intersect Group
  • Automated Logic Corporation
Silver Sponsors
  • Blackberry
  • Anteo Group
  • 4t Networks
  • ICE
  • JBoss
Cocktail Hour Sponsor
  • MATRIX
Please join us for this amazing event and register athttp://www.devnexus.com/

Thank you all and we will be delighted to see you in 2 weeks!

Cheers,


Gunnar

Labels: , ,

Thursday, March 3, 2011

Advanced Java, JRuby, Spring, Google, JBoss and DevNexus 2011

DevNexus 2011 - March 21st & 22nd (www.devnexus.com) - Registration will be closing soon.

Several large teams have already registered and this is the best event to have your team attend - the injection of new technologies, techniques and ideas from some of the world's best technologists as well has having other professional software developers to mingle with. We will soon hit max capacity for the event so please complete your registrations today.

The DevNexus organizing committee looks for the best speakers and hottest topics in the software development industry and this year we have had a tremendous response from notable presenters. The following are just a few of the DevNexus speakers:

  • Jevgeni Kabanov - the founder and CTO of ZeroTurnaround (JRebel) will be addressing JVM memory management and classloading - these are excellent sessions for your most hardcore Java coders
  • Dick Wall - of the JavaPosse will dive into functional languages and overall best practices for software practitioners
  • Bob McWhirter - the prolific founder of open source solutions such as Codehaus.org, Drools and Groovy will address Ruby/JRuby on his new project TorqueBox - the power of Ruby raised to the power of JBoss
  • Claus Ibsen - the project lead for Camel and co-auther of the "Camel in Action" book will focus on enterprise integration
  • Mark Fisher - the project lead for Spring Integration will address AMQP and the "Cloudy Future of Integration"
  • Hans Dockter - the founder and project lead for Gradle will focus on automated build systems
And many more notable speakers discussing great topics...http://www.devnexus.com/s/speakers
  • Hadoop 
  • Git 
  • Scala 
  • Arquillian 
  • Flex
  • jQuery 
  • Sproutcore
  • Selenium 
  • Gradle 
  • Apache Camel 
  • Spring Integration, Mobile, Social 
  • JBoss
  • TorqueBox 
  • Apache Shiro 
  • GWT 
  • Google App Engine 
  • NoSQL 
  • The Future of Java
  • ...
If you wish to subscribe to future Atlanta Java Users Group Announcements, please visit
http://www.ajug.org/confluence/display/AJUG/MailingLists

We look forward to seeing you at future AJUG Events and DevNexus 2011.

Sincerely,
Burr
770-714-3292

Labels: , , ,

Tuesday, February 22, 2011

DevNexus 2011 - Craft Rich (Mobile) Internet Applications

Dear fellow developers,

DevNexus 2011, the south-east's premiere developer conference is only a few weeks away and will take place March 21-22 in Atlanta, GA - Come join us and learn the techniques and technologies that will boost your corporate projects and personal skills to the next stage of excellence. 

We are currently living in an age of massive changes that are transforming our industry. No longer is it acceptable to release static web applications as we did back in the Struts 1.x days. Our customers demand more - rich, interactive and responsive applications that also need to be available across multiple devices - not only desktops but also smart phones and tablets. It is becoming the new reality - Prepare yourself!

DevNexus will help you discover the possibilities and techniques to master this exciting world of Rich Internet Applications (RIA). And thus, we dedicated an entire track to cover:
  • GWT - David Chandler from Google will show you the latest developments around GWT 2.1
  • PhoneGap - Josh Marinacci from HP/Palm will show you how to develop mobile web applications using GWT and PhoneGap
  • jQuery - Learn from Pratik Patel how you can use jQuery 1.5 to built great UIs and how it helps you to loose the fear of JavaScript. Also learn how jQuery Mobile can help you createHTML5 based cross-device compatible mobile web applications. (The mobile web version of DevNexus.com is powered by jQuery Mobile - http://www.devnexus.com/s/index?site_preference=mobile)
  • SproutCore - Did you know that both Apple's MobileMe and iWork.com are powered by SproutCore? Yehuda Katz will show you the possibilities that this exciting JavaScript framework offers.
  • Flex - James Ward covers the new features in the upcoming Flex 4.5 release that will allow you to develop mobile applications across multiple devices (Android, RIM's Playbook, iPhone)
  • Spring Mobile - Need to serve mobile and desktop content from the same domain and or even the same Urls? Come and listen to Roy Clarkson's and Keith Donald's presentation on  Spring Mobile
  • Spring Social - SpringSource co-founder Keith Donald will show you how to add "social features" to your applications using a common Api to integrate Twitter, Facebook and LinkedIn
Furthermore, we will have a keynote by Yehuda Katz, member of the jQuery and Ruby on Rails core team. Yehuda will show us how to build web applications in a multi-device world covering among other things HTML5

This is an incredible line-up of sessions covering (mobile) web application development. What is even better - This is just one track. There are 3 more tracks covering core Java topics, NoSQL and many more crucial topics. 
Take a look at our schedule at: http://www.devnexus.com/s/schedule

This is AJUG's biggest DevNexus event ever! 

Don't hesitate, take the plunge and please register at http://www.devnexus.com/

Labels: , ,

Monday, February 7, 2011

Spring Mobile M3 - Site Preference

A few weeks ago I started playing with Spring Mobile. For my app I want to use existing Spring MVC controllers to render different views depending on whether the client is a mobile device or a classic browser.

For that purpose Spring Mobile is really a very helpful asset (See my last Spring Mobile related blog post for more details). Back then I investigated a feature that allows you to manage a user's site preference. For example, the normal use case is that a user with a mobile device only sees the mobile version of your website.

Wouldn't it be desirable, though, to allow the user to switch to the full version of the website as well?  While hopefully not a regular use-case, your site's visitor may be for instance interested in some additional content that is unavailable in the mobile version. A good example for me is Wikipedia. For normal use, the mobile web version of Wikipedia is certainly quite functional. However, I am also bi-lingual (plus aspiring to learn Spanish), so I often use Wikipedia to look up articles, let's say in German, but then I want to switch over to the Spanish version of the same article in order to find certain translations. Because I can't do the language switch in the mobile web version, I at least have the option to change back to the full Wikipedia version and switch the article's language there.  

Well, Spring Mobile has a feature for site preference but unfortunately that feature (when I checked in the M2 release) had some limitations. It only worked with the SiteSwitcherHandlerInterceptor. This interceptor assumes you want to redirect the user to a dedicated mobile sub-domain that is hosting your application's mobile version.

In my simple use-case, however, I want to keep the mobile and non-mobile content on one domain (same urls) but let mobile users change to the full version of the website and stay on that full version for the duration of their session (or set via cookie for the duration of multiple visits).


Unfortunately, the "site preference" feature back then was somewhat embedded in the M2 release and you could not use it stand-alone easily. Well, I headed over to the Spring forums and posted my issue there and within 3 days, Keith had implemented and commited improvements for my requirements (I was truly impressed with the feedback!)

Well, only a month later, I finally found the time to look at the latest changes regarding the site preference feature. This has coincided also with the Spring Mobile M3 release 1 day later, which contains all the latest features. 

Checking out and building Spring Mobile

But in case you want to anyway, you can check out and build the Spring Mobile project easily yourself using Git and Gradle. You will find the sources here: http://git.springsource.org/spring-mobile

Just FYI, I was unable to check out the Spring Mobile project using Eclipse's EGit. It looks like Egit does not support (??) Git submodules, a feature used by Spring Mobile. However, checking out the project from the command line using worked well:

git clone --recursive git://git.springsource.org/spring-mobile/spring-mobile.git

Building project using Gradle is trivial. Under the spring-mobile directory execute either ./gradlew build or gradlew.bat. You don''t even have to have Gradle installed locally - it downloads Gradle for you. I am Maven fan but that was impressive!! I really owe it to myself to look at Gradle more closely very soon.

Spring Mobile M3 Changes regarding Site Preference

Anyway, the changes regarding the site preference feature in the M3 release are satisfying my needs perfectly. The site-preference functionality has been refactored out into its own feature and Spring Mobile now provides the following separate features:
  1. Device Resolution
  2. Site Preference Management
  3. Site Switching
The documentation has also been updated and is reflecting the feature changes and is quite helpful in that regard. Here is the configuration necessary to configure site-preference for my use-case:

I updated my Maven dependencies to:

     <dependency>
         <groupId>org.springframework.mobile</groupId>
         <artifactId>spring-mobile-device</artifactId>
         <version>1.0.0.M3</version>
     </dependency>

I updated my spring web context xml file:

  <mvc:interceptors>
       <bean class="org.springframework.mobile.device.DeviceResolverHandlerInterceptor" />
       <bean class="org.springframework.mobile.device.site.SitePreferenceHandlerInterceptor" />
  </mvc:interceptors>

In order to dependency inject:
  • org.springframework.mobile.device.site.SitePreference
  • org.springframework.mobile.device.Device
into your Spring MVC controllers, you need to add custom argument resolvers:

<bean class="org.springframework.mobile.device.DeviceWebArgumentResolver" />
<bean class="org.springframework.mobile.device.site.SitePreferenceWebArgumentResolver" /> 


See Chapter 2.4.4 of the Spring Mobile documentation for details. An interesting observation: If you're using the site preference feature, you probably only need to inject: org.springframework.mobile.device.site.SitePreference 
into your controllers. For example if users don't explicitly set the site preference through the request parameter ('currentSitePreference'), SitePreference will fall back to what Device would tell you.

I like the documentation change that instead of using a CustomWebArgumentResolverInstaller, the documentation now configures the resolvers directly in the context, which makes things easier to understand. I am impressed that with the M3 release the documentation looks very good.

Oh and in case you wondered how it works in practice - Check out http://www.devnexus.com/

It is admittedly (volunteer-) work in progress but I think the site preference feature is working nicely for my project now. Next, I need to beef up my jQuery Mobile skills to mobile-web-enable the entire site.

Labels: , ,