Showing posts with label spring. Show all posts
Showing posts with label spring. Show all posts

Monday, April 4, 2016

Spring Boot with JSPs using Undertow

This is a follow-up to my previous post Spring Boot with JSPs in Executable Jars.

Undertow is another alternative for using an embedded container with Spring Boot. You can find general information in the Spring Boot reference guide chapter Use Undertow instead of Tomcat. While I was working on updating the Spring Boot documentation regarding the JSP support for Tomcat, I noticed the following line in the reference guide for Spring Boot 1.3.3:

"Undertow does not support JSPs."

Being a good citizen, I dug a little deeper and discovered the Undertow JSP sample application by Chris Grieger. It turns out that Undertow has indeed JSP support by using jastow, which is a Jasper fork for Undertow. The key was to adapt the Undertow JSP sample application for Spring Boot. Doing so was actually fairly straightforward. The actual Undertow configuration uses Spring Boot`s EmbeddedServletContainerCustomizer:


final UndertowDeploymentInfoCustomizer customizer = new UndertowDeploymentInfoCustomizer() {

  @Override
  public void customize(DeploymentInfo deploymentInfo) {
    deploymentInfo.setClassLoader(JspDemoApplication.class.getClassLoader())
    .setContextPath("/")
    .setDeploymentName("servletContext.war")
    .setResourceManager(new DefaultResourceLoader(JspDemoApplication.class))
    .addServlet(JspServletBuilder.createServlet("Default Jsp Servlet", "*.jsp"));

    final HashMap<String, TagLibraryInfo> tagLibraryInfo = TldLocator.createTldInfos();

    JspServletBuilder.setupDeployment(deploymentInfo, new HashMap<String, JspPropertyGroup>(), tagLibraryInfo, new HackInstanceManager());

  }
};

The full source is available in the JspDemoApplication class. The main issue is more or less the retrieval and configuration of the used Taglibraries. The Undertow JSP sample provides the TldLocator class, which does the heavy lifting. For our example, I am adapting that class so that it works in the context of Spring Boot. In Spring Boot we are dealing with über-Jars, meaning the resulting executable jar file will contain other jar files representing its dependencies.

Spring provides some nifty helpers to retrieve the needed Tag Library Descriptors (TLD) files. In TldLocator#createTldInfos I use a ResourcePatternResolver, specifically a PathMatchingResourcePatternResolver with a location pattern of classpath*:**/*.tld.


final URLClassLoader loader = (URLClassLoader) Thread.currentThread().getContextClassLoader();

final ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(loader);
final Resource[] resources;
final String locationPattern = "classpath*:**/*.tld";

try {
 resources = resolver.getResources(locationPattern);
}
catch (IOException e) {
 throw new IllegalStateException(String.format("Error while retrieving resources"
   + "for location pattern '%s'.", locationPattern, e));
}


Important

Don’t forget the asterix right after classpath. The classpath*: allows you to retrieve multiple class path resources with the same name. It will also retrieve resources across multiple jar files. This is an extremely useful feature. For more information please see the relevant JavaDocs for PathMatchingResourcePatternResolver.

Once we have the TLD resources, they will be parsed and ultimately used to create a collection of org.apache.jasper.deploy.TagLibraryInfo. With those at hand, we create a JSP deployment for Undertow using the DeploymentInfo and the TagLibraryInfo collection.


final HashMap<String, TagLibraryInfo> tagLibraryInfo = TldLocator.createTldInfos();
JspServletBuilder.setupDeployment(deploymentInfo, new HashMap<String, JspPropertyGroup>(), tagLibraryInfo, new HackInstanceManager());

And that’s it. Simply build and run the application and you should have a working JSP-based application.


$ mvn clean package
$ java -jar jsp-demo-undertow/target/jsp-demo-undertow-1.0.0-BUILD-SNAPSHOT.jar

In your console you should start seeing how the application starts up.



Once started, open your browser and go to the following Url http://localhost:8080/.


You can find the full source-code for this sample at https://github.com/ghillert/spring-boot-jsp-demo

Monday, October 6, 2014

Java Template Engines Revisited Part 1

Over the past week, I spent some time looking at Java based template engines. Typically I need templating support for two areas:

  • View Templates (For rendering views in your browser)
  • Email Templates - with support for both HTML and Text emails

For email templates I had used the usual suspects such as Velocity and Freemarker in the past but both feel a tad heavy and old these days - Velocity's last release was in 2010! Eventually I settled for a simpler option a while back: StringTemplate, which as a library worked fairly okay.

As I had done some client-side templating using Mustache and Handlebars, I was intrigued in seeing Java implementations for both:


The nice thing about Mustache is that implementations are available for almost any programming language imaginable, which could be nice in case you have the need to maintain browser-bound and backend (Java) templates or in case you have multiple Java and non-Java application with templating needs.

For now I have chosen mustache.java. Looks like it is heavily used at Twitter. Depending on how willing you are towards enduring any type of logic in your templates, you may also want to check out Handlebars and the corresponding Java implementation. It is basically a super-set of Mustache, providing additional built-in helpers.

Lastly, for both Mustache and Handlebars there is support available for Spring MVC.


I have not used either support for Spring MVC, yet, though. In case you have used any of the mentioned options, please leave feedback to this blog.


Monday, September 15, 2014

Secure your AngularJS Apps with Spring Security and Spring Session


A few days ago I was in the middle of preparing for my Spring One 2GX 2014 talk Creating Modular Test-Driven SPAs (Slideshare) with Spring and AngularJS. Part of the presentation is a demo application I created called botanic-ng. This application uses AngularJS on the client side and Spring (Boot) on the server-side. As I wanted to not merely create a simplistic toy app, I also intended to add authentication and (simple) authorization to the application.

I did not want to go too crazy with this (e.g. implementing full-fledged OAuth 2.0 integration). Nevertheless, I wanted to add (I hope) some meaningful security features inside my AngularJS application.

Disclaimer: I am not a security expert. Proceed with caution as this solution may not provide enough security for your application needs.

By chance I came across a demo application that Josh Long created a while back. That application, while using Spring Security, did not integrate with Spring Security to the fullest extends, and I felt that I could improve upon that implementation using Spring Session which is new project created by Spring Security lead Rob Winch.

Spring Session

The Servlet 3.0 Specification (JSR 315) introduced several ways to customize the handling of session cookies, for instance changing the name of the cookie (from the default JSESSIONID) and providing additional security relevant settings:


However, you're still pretty much bound to using cookies in order to store your Session IDs. For cases where you need more comprehensive flexibility for handling your sessions, Spring Session comes in quite handy and provides numerous advantages.

By default Spring Session stores session information in Redis using the RedisOperationsSessionRepository. Sessions expire by default after 30 minutes but this can be customized using the setDefaultMaxInactiveInterval property. Beyond Redis a MapSessionRepository is also provided to allow for easy integration with e.g. Hazelcast.

For my use-case, I wanted to expose the Session ID not via a standard cookies but via an HTTP header. Luckily, Spring Session provides various pluggable strategies to customize that behavior. As Spring Session works as a Filter you have to configure a SessionRepositoryFilter. On this filter you can set the used HttpSessionStrategy. By default it uses the CookieHttpSessionStrategy. For my use-case, though, I am using the HeaderHttpSessionStrategy, which by default stores the Session ID in an HTTP header called x-auth-token (This is customizable though).

On the client-side in my AngularJS application, I am adding a HTTP header via $http to every request.

$http.defaults.headers.common['x-auth-token'] = user.token;

This is configured upon successful login through the LoginController. Botanic-ng submits the login credentials to the server, which in turn uses them to authenticate the user using Spring Security (AuthenticationController) and if successful, the AuthenticationToken containing the Session ID and user roles will be send back to the client.

The Session ID on the client is stored in memory only and if you refresh the client, the user must re-authenticate.

For the full source code, please see: 




Saturday, September 13, 2014

Spring One 2GX 2014 - My session slides

Have not blogged in a while. Need to make a mental note to revive that. Just came back from Spring One 2GX 2014 in Dallas, TX. It's been a wonderful event and I learned a lot - From microservices to reactive streams. I also gave 2 presentations which I think were well received. For my AngularJS with Spring (Boot) talk I had 140 attendees, yeah :-)

Creating Modular Test-Driven SPAs with Spring and AngularJS



Spring Batch Performance Tuning


Thursday, August 8, 2013

SpringOne2GX 2013 - Early-bird registration

Just a quick note to point out that SpringOne2GX is coming up next month in Santa Clara (Sept 9-12) and the early bird registration (save $200) expires tomorrow, Aug 9th.

Therefore, please join us and register at: http://www.springone2gx.com/conference/santa_clara/2013/09/register

In case you haven't been following the massive amount of activity that has been happening in the Spring community such as Spring 4.0, Spring XD, Spring Reactor, Spring Boot, and much, much more (Please check http://blog.springsource.org for some of the latest), I think it is fairly safe to say there will be a LOT of announcements and news this year!

If you are involved with, or work with the Spring framework, Grails, Groovy - This will be a big one and it would be very worthwhile to be there!

Furthermore, if you are interested in cloud/PaaS, the first ever Cloud Foundry conference, Platform, is co-hosted at the same venue on Sept 8-9 and registration for SpringOne means you get to go to that too, if you want. http://www.platformcf.com

Just FYI - there is some crazy massive Cloud Foundry usage going on in China right now: http://www.wired.com/wiredenterprise/2013/07/cloudfoundry/

I will see you there!

Friday, October 5, 2012

What's New in Spring Integration 2.2 - JPA Support

I have just published a new blog posting, which introduces the new Java Persistence API (JPA) support that is provided with Spring Integration 2.2. This is the third part in a series of blog posts highlighting some of the new features available in Spring Integration 2.2 following the recent release of Release Candidate 1. Please head over to the SpringSource blog to get the details:

http://blog.springsource.org/2012/10/05/whats-new-in-spring-integration-2-2-part-3-jpa-support/

Monday, April 9, 2012

Create Spring Integration Projects using STS

I finally published my blog post on how to create Spring Integration projects using Spring Templates in STS. You can find the post over at:

http://blog.springsource.org/2012/04/09/create-spring-integration-projects-using-sts/

I also created a corresponding screencast, which was posted to the SpringSourceDev YouTube channel.

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!

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.

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

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...

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.

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...

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. 



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.

Tuesday, January 25, 2011

Marshal Json data using Jackson in Spring MVC with Jaxb Annotations

The title is quite a mouthful but let me explain...For the DevNexus.com website I want to provide the website's data not only via XML but also via JSON in order to provide maximum flexibility for other consuming services. E.g. Pratik Patel pinged me the other day that he intends building an IPad client and Charlie Collins is planning to update his DevNexus Android client, which he originally created for the 2010 conference (The pressure is on gentleman ;-).

The DevNexus website is based on Spring MVC 3.0 and provides RESTful Urls that render Html views of the data (Targeting traditional browser clients as well as mobile client using Spring Mobile and jQuery Mobile).

Thus, I configured Restful endpoints as described in my last blog post. The easiest way to marshal JSON in Spring MVC is via the Jackson Java JSON-processor. Spring has a few documentation pointers regarding that. Theoretically, the setup is fairly simple and in its simplest forms means to just put the Jackson jar file onto your class path and adding mvc:annotation-driven to your Spring Xml Context file (See Chapter 15.12.1 of the Spring documentation). No sweat.

To get started more specifically with Jackson, here are some blog entries that I came accross while diving deeper into it:
While the tutorials may make you think that serializing JSON is happening defacto automatically, it turned out, that I had to fine-tune my domain model for Jackson. My domain model objects have bi-directional relationships and and I was getting a ton of errors of type:

java.lang.StackOverflowError - org.codehaus.jackson.map.JsonMappingException: Infinite recursion (StackOverflowError)

You can configure Jackson's marshalling behavior by annotating your domain model objects. However, those annotations are Jackson specific and I already was annotating my obejects with Jaxb annotations for the Xml marshalling of data.

Well - cool beans - , it turns out, Jackson can indeed use Jaxb annotations to renders Json data (added with version 1.1 of Jackson).

But how do I configure Jackson? How do I make it work in my Spring environment? I came across 2 blogs, that combined, provided the necessary solution.

The first example I found here, which provides a really nice example.

Furthermore, I not only wanted to configure Jackson to use Jaxb annotations, but I also needed to make it work for my Spring environment. For that Kyrill Alyoshin has some good information on his blog (
He also details how to make Jackson work better with Hibernate, which sounds interesting and I may return to his blog entry more specifically for that.).

Basically the best way to integrate Jackson and Spring is to create a custom ObjectMapper class that enables Jaxb support and which can then be injected into Spring's MappingJacksonJsonView.

Here are the things that were needed to get things going for my project -

First, add the following Maven Dependencies (jackson-xc provides the additional Jaxb support):
<!-- Jackson JSON Mapper -->
 <dependency>
     <groupId>org.codehaus.jackson</groupId>
     <artifactId>jackson-core-lgpl</artifactId>
     <version>1.6.4</version>
 </dependency>
 <dependency>
     <groupId>org.codehaus.jackson</groupId>
     <artifactId>jackson-mapper-lgpl</artifactId>
     <version>1.6.4</version>
 </dependency>
 <dependency>
     <groupId>org.codehaus.jackson</groupId>
     <artifactId>jackson-xc</artifactId>
     <version>1.6.4</version>
 </dependency>

The custom ObjectMapper:
import org.codehaus.jackson.map.AnnotationIntrospector;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.xc.JaxbAnnotationIntrospector;

public class JaxbJacksonObjectMapper extends ObjectMapper {

 public JaxbJacksonObjectMapper() {
  final AnnotationIntrospector introspector
      = new JaxbAnnotationIntrospector();
  super.getDeserializationConfig()
       .setAnnotationIntrospector(introspector);
  super.getSerializationConfig()
       .setAnnotationIntrospector(introspector);
    }

} 

The SpringContext configuration that wires everything together:
    <bean class="org.springframework.web.servlet.view
        .ContentNegotiatingViewResolver">
        <property name="order" value="1" />
        <property name="ignoreAcceptHeader" value="true" />
        <property name="mediaTypes">
            <map>
                <entry key="xml"  value="application/xml"/>
                <entry key="json" value="application/json"/>
            </map>
        </property>
        <property name="defaultViews">
            <list>
                <bean class="org.springframework.web.servlet.view
          .xml.MarshallingView">
                    <property name="marshaller" 
                      ref="jaxbMarshaller"/>
                </bean>
                <bean
                    class="org.springframework.web
.servlet.view.json.MappingJacksonJsonView">
                    <property name="objectMapper"
 ref="jaxbJacksonObjectMapper"/>
                </bean> 
            </list>
        </property>
    </bean>

Friday, January 21, 2011

REST with Spring - ContentNegotiatingViewResolver vs. HttpMessageConverter+ResponseBody Annotation

Disclaimer: This blog posting reflects experiences while learning to implement RESTful services. Thus, certain elements of my blog posting may turn our to be not correct. Therefore, if you encounter errors, please let me know and I will post corrections as soon as possible. Please proceed with caution...

As I posted in my previous blog "Making DevNexus.com more Restful", I am in the process of making more of the data from DevNexus.com consumable by other services, by exposing JSon and XML based endpoints. The website/application is implemented using Spring MVC 3.0 in the view layer using Spring's REST support.

Here are a few good reads that I came across that provide some helpful information:
  1. http://blog.springsource.com/2009/03/08/rest-in-spring-3-mvc/
  2. http://blog.springsource.com/2009/03/16/adding-an-atom-view-to-an-application-using-springs-rest-support/
  3. http://rwehner.wordpress.com/2010/06/09/2-ways-to-create-json-response-for-ajax-request-in-spring3/
  4. http://www.ibm.com/developerworks/web/library/wa-restful/
  5. http://forum.springframework.org/showthread.php?p=337206
  6. http://static.springsource.org/spring/docs/3.0.x/reference/mvc.html
As it turns out, there are 2 ways of implementing REST endpoints:
Using a ContentNegotiatingViewResolver

When you use a ContentNegotiatingViewResolver your web controllers return ModelAndViews or view names and the ContentNegotiatingViewResolver will, based on various criteria, choose the right data representation strategy.

The highest priority hereby has the file extension which is used if available in the request. Next, the ViewResolver will look for a (definable) request parameter that identifies the view. If that does not help, the ViewResolver uses the Java Activation Framework to determine the Content-Type. If all fails, use the the HTTP Accept header. Of course the steps can be individually disabled.

A key takeaway though is, that your controllers will return a single ModelAndView/Viewname that will resolve into a specific view such as:
  • org.springframework.web.servlet.view.json.MappingJacksonJsonView
  • org.springframework.web.servlet.view.xml.MarshallingView 
  • org.springframework.web.servlet.view.documentClass.AbstractPdfView
  • etc...
However, this may feel a little unnatural for certain data representations such as XML (using Jaxb annotations) or Json (using Jackson), where a dedicated view may not be necessary. Luckily, you can configure the ContentNegotiatingViewResolver to use default views which kind of solves the issue.

Using HttpMessageConverters

This is where HttpMessageConverters potentially could help. Whenever you use the @ResponseBody annotation you will be using a HttpMessageConverter (See also the Spring reference documentation, chapter "15.3.2.5 Mapping the request body with the @RequestBody annotation" and "18.3.2 HTTP Message Conversion").

What this means is, that instead of returning a ModelAndView or view name, you will actually return data, e.g. a Collection of Objects.

If you use the Spring Context  <mvc:annotation-driven/> then support for XML and JSON marshalling is activated by default, provided the respective class libraries (Jaxb and/or Jackson) are present in your class-path (See the Spring documentation for details at chapter "15.12.1 mvc:annotation-driven")

Here is the interesting problem, if you use <mvc:annotation-driven/> you can set additional conversion services but you cannot set additional HttpMessageConverters. Consequently, if you want to do that then you have to use explicit bean declarations and remove the <mvc:annotation-driven/> tag from your context. This was something not too well covered in article [6] http://www.ibm.com/developerworks/web/library/wa-restful/

Ultimately, I am using the following bean declaration instead of the <mvc:annotation-driven/>  tag:

     <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="webBindingInitializer">
            <bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
                <property name="conversionService" ref="conversionService"/>
                <property name="validator" ref="validator"/>
            </bean>
        </property>
       <property name="messageConverters">
           <list>
               <ref bean="jsonConverter" />
               <ref bean="marshallingConverter" />
               <ref bean="atomConverter" />
           </list>
       </property>
    </bean>

My choice

This was a bit tricky. Both approaches are somewhat overlapping and I wish the documentation would give you better guidance on which approach to use under which cicumstances. Certainly the ContentNegotiatingViewResolver option seems to be the better documented solution. On the other side, you don't need to configure explicit views when using HttpMessageConverters and the ResponseBody annotation and therefore, that setup looks a bit more streamlined.

One issue I was running into was, that for my application I can return both pure data views (Json, XML) and also Html/Jsp responses. Somehow I was not able to configure my controller easily+cleanly, to respond to the same Url with multiple controller methods (one using @ResponseBody and the other returning a JSP view)

Secondly, I wanted to also support file extensions to use the correct view or converter.  As it turns out though, HttpMessageConverters don't support that - Although there was an example somewhere for using request parameters. But that approach would require me creating additional custom classes...

Anyway, I went ahead chose the ContentNegotiatingViewResolver approach to implement my Restful services.

Further issues

Once I made my decision, everything seemed to go smoothly. I got my services implemented quickly and they worked perfectly in Firefox. Here is an example of the intended Url structure:

http://www.devnexus.com/s/speakers
http://www.devnexus.com/s/speakers.html
http://www.devnexus.com/s/speakers.xml
http://www.devnexus.com/s/speakers.json

With that I thought to have covered all bases: Support file extensions, but also allow clients to connect to http://www.devnexus.com/s/speakers and retrieve all data representations using the respective Http Accept header.

I deployed the app into production, but then the next day at the monthly Atlanta Users Group meeting - people informed me that the DevNexus site were down. That was odd, as I had accessed the site just minutes prior to the meeting.

Well, as it turned out, Google Chrome, Safari and Internet Explorer transmit a wild mixture of Http Accept headers. Consequently, when users accessed http://www.devnexus.com/s/index then the server would try to return an Xml view because Chrome and Safari requested Xml data rather than Html data.

For more details on Accept headers, please see the following fascinating:

http://www.gethifi.com/blog/browser-rest-http-accept-headers

What also threw me off, was that quite a few sources, incl. the Spring documentation imply that using the Http Accept header might be a actually a viable way of determining the correct view to return to clients.

To illustrate the chaos -Here is an interesting posting from the webkit mailing list:

https://lists.webkit.org/pipermail/webkit-dev/2010-January/011188.html

Ultimately, I got my servlet context configured in a way I think works best for me, though. The extension-less Url will always return Html now and for other data representations the file extension is mandatory. I also configured the ContentNegotiatingViewResolver to ignore Http Accept header by setting:
<property name="ignoreAcceptHeader" value="true" />
Many thanks to this blog posting by Rick Herrick. Thus, now my servlet-context.xml file contains:

    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="order" value="1" />
        <property name="ignoreAcceptHeader" value="true" />
        <property name="mediaTypes">
            <map>
                <entry key="xml"  value="application/xml"/>
                <entry key="json" value="application/json"/>
            </map>
        </property>
        <property name="defaultViews">
            <list>
                <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
                    <property name="marshaller" ref="jaxbMarshaller"/>
                </bean>
                <bean
                    class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
                    <property name="objectMapper" ref="jaxbJacksonObjectMapper"/>
                </bean>
            </list>
        </property>
    </bean>

    <bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
        <property name="order" value="2"/>
    </bean> 
 
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
        <property name="order"  value="3"/>
    </bean>

That was a rather long day to get things working as intended but a good learning experience nonetheless. There is certainly something intriguing about having clean Urls.

Tuesday, January 4, 2011

Spring Mobile, jQuery Mobile and SiteMesh

I just realized that I haven't published a blog entry in a while. Time just flies by. Anyway, I am in the midst with several other volunteers to prepare for the Atlanta-based DevNexus developer conference which will take place March 21-22.

For this year's conference I reworked the conference website application using Spring (MVC) 3.0, JPA 2.0 etc. In addition to standard clients, I started looking into supporting mobile clients as well.

My requirement was to provide a decent looking mobile interface in a reasonable amount of time (heck, it is all done during my spare-time afterall). Plus, I wanted to support multiple mobile devices at once. Out of that reason I ruled out a native client implementation (at least for now).

Another option, would have been to look at other development frameworks such as PhoneGap and Appcelerator, something I may still have to do down the road.

As I have been using jQuery quite a bit, I started exploring it using either jQTouch or jQuery Mobile. I opted into looking at jQuery Mobile as it is the official jQuery sanctioned project.

As it turns out, you can easily create create some nice looking UIs using jQuery Mobile. As an example, just point, your mobile browser, e.g. Android to http://www.devnexus.com/. This is pretty impressive considering that I have been using an Alpha 2 version with just standard theming and functionality.

I still have to work on the detail pages, but the main landing page looks fairly nice out of the box using minimal amounts of code.

On the server-side, I am using Spring Mobile, which currently is available as a M2 release. What Spring Mobile allows you to do is to detect from within your Spring MVC controllers, whether the incoming request originates from a mobile device or not.

If you need to detect specific device capabilities, you can even use a WurflDeviceResolver, but for my use case I simply need to know whether a mobile device request is coming in or not. If so, forward to a mobile version of the respective controller's jsp page.

One, question I had to solve was how to make everything work with SiteMesh, which I use for templating purposes. As I use the same Urls for mobile and standard clients (No site-switching), I ended up needing to create a custom SiteMesh DecoratorMapper extending AbstractDecoratorMapper.



public class SpringMobileParameterDecoratorMapper extends AbstractDecoratorMapper {
    private String decoratorName = null;

    public void init(Config config, Properties properties, DecoratorMapper parent) throws InstantiationException {
        super.init(config, properties, parent);
        decoratorName = properties.getProperty("decorator.name", "mobile");
    }

    public Decorator getDecorator(final HttpServletRequest request, final Page page) {

        final Device device = DeviceResolverHandlerInterceptor.getCurrentDevice(request);

        if (device != null && device.isMobile()) {
         return getNamedDecorator(request, decoratorName);
        } else {
         return super.getDecorator(request, page);
        }

    }
} 

It may not be the bestapproach to have a hard dependency onto Spring Mobile in my SiteMesh DecoratorMapper...but it works nicely so far.

Wednesday, January 27, 2010

Automating User Registrations with OpenID and Spring Security 3.0 - Part 3

Preparing heavily for DevNexus 2010, I did not have as much time as I hoped for in order to continue my series on using OpenID with the new SpringSecurity 3.0 (See Part 2 for details) Thus, today I would just like to cut and paste some of the code from my little 'home-POC'. In the coming weeks I still hope to incorporate it properly into jRecruiter.

Here is the JSP snippet for the OpenID login form:
<div id="openid-registration">
  <form name='oidf' action='/jrecruiter-web/j_spring_openid_security_check' method='POST'>
    <fieldset id="openIdLoginSection">
          <legend>Login with OpenID Identity</legend>
          <div class="required">
            <label for="openid_identifier">Identity</label>
            <s:textfield id="openid_identifier" name="openid_identifier" required="true" maxlength="80" tabindex="1" size="30"/>
          </div>
          <div class="submit">
            <input type="submit" value="Login"/>
          </div>
    </fieldset>
  </form>              
</div>


Here is the relevant piece of my Spring context file:

<security:http  auto-config="true" access-decision-manager-ref="accessDecisionManager" >
  <security:intercept-url pattern="/s/admin/**" access="ADMIN"                        requires-channel="https"/>
  <security:intercept-url pattern="/**"         access="IS_AUTHENTICATED_ANONYMOUSLY" requires-channel="any" />

  <security:form-login login-page="/login.html" default-target-url="/admin/index.html"
                       authentication-failure-url="/login.html?status=error" />
  <security:logout logout-url="/logout.html" invalidate-session="true" logout-success-url="/show.jobs.html"/>
  <security:session-management>
     <security:concurrency-control max-sessions="1" error-if-maximum-exceeded="false"/>
  </security:session-management>
  <security:custom-filter ref="openIDFilter"                   position="OPENID_FILTER" />
</security:http>

<bean id="openIDFilter" class="org.jrecruiter.web.security.RegistrationAwareOpenIDAuthenticationFilter">
  <property name="authenticationManager" ref="authenticationManager"/>
  <property name="consumer" ref="attributeAwareOpenIDConsumer"/>
  <property name="authenticationSuccessHandler"        ref="openIDFilterSuccess"/>
  <property name="authenticationFailureHandler"        ref="openIDFilterFailure"/>
  <property name="registrationTargetUrlRequestHandler" ref="openIDFilterRedirectToRegistration"/>
</bean>

<bean id="openIDFilterRedirectToRegistration" class="org.jrecruiter.web.security.RegistrationTargetUrlRequestHandler">
  <property name="defaultTargetUrl" value="/registration/signup.html"/>
</bean>
<bean id="openIDFilterSuccess" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler">
  <property name="defaultTargetUrl" value="/admin/index.html"/>
</bean>
 
<bean id="openIDFilterFailure" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
  <property name="defaultFailureUrl" value="/login.html?status=error"/>
</bean>

<bean id="attributeAwareOpenIDProvider" class="org.jrecruiter.web.security.AttributeAwareOpenIDProvider" scope="prototype">
  <constructor-arg ref="userService"/>
</bean>

<bean id="attributeAwareOpenIDConsumer" class="org.jrecruiter.web.security.AttributeAwareOpenIDConsumer"/>


I did some customization: public class AttributeAwareOpenIDConsumer extends OpenID4JavaConsumer {
  public AttributeAwareOpenIDConsumer() throws ConsumerException {
         super(Arrays.asList(UsedOpenIdAttribute.FIRST_NAME.getOpenIdAttribute(),
                                     UsedOpenIdAttribute.LAST_NAME.getOpenIdAttribute(),
                                     UsedOpenIdAttribute.EMAIL.getOpenIdAttribute(),
                                     UsedOpenIdAttribute.AX_FIRST_NAME.getOpenIdAttribute(),
                                     UsedOpenIdAttribute.AX_LAST_NAME.getOpenIdAttribute(),
                                     UsedOpenIdAttribute.NAME_PERSON.getOpenIdAttribute()));
  }
}
I also created a custom class AttributeAwareOpenIDProvider which extends org.springframework.security.openid.OpenIDAuthenticationProvider. It overrides public Authentication authenticate(Authentication authentication) Thus, I can hook into the actual authentication process and inject my own logic.

For example,  if the OpenID authentication succeeds it does not necessarily mean that your account exists, yet. Therefore, if OpenID authentication succeeds (if (status == OpenIDAuthenticationStatus.SUCCESS)), I try loading the user from my application's database (userDetailsService). If then a UsernameNotFoundException is thrown I collect a series of OpenID attributes from the org.springframework.security.openid.OpenIDAuthenticationToken. Once finished, I am throwing a custom AuthenticationSucessButMissingRegistrationException. I use it to redirect to the registration page and pre-populate the registration form with some of the collected OpenID attributes.

I hope this gives you some ideas of how you can integrate OpenID into your SpringSecurity infrastructure. I am myself still in the early learning phase regarding OpenID and I still need to figure out how to best manage multiple authentication realms within my application. But that may be a reason for another blog post.