Archive for the ‘spring’ Category

An Honest Look at Seam – Part 1: How Seam builds on Spring

Thursday, March 4th, 2010

I have been spending a lot of time with JBoss Seam, and I must say, I am very excited about what I have seen. My goal in these next few posts is to talk about why I think these features of Seam are game changers and what they are saying about the direction the JEE Spec is going.

Before I dive into the topic for this post, one of my coworkers gave a brief introduction to Seam a few weeks ago. I would recommend reading it first if you are completely unfamiliar with Seam. If you are looking for a more thorough introduction (other than the reference docs), I give my recommendation goes to Seam in Action by Dan Allen. It has been my guide in my own exploration of Seam and, in spite of it’s Seam 2.0/2.1 focus, it is extremely relevant to working with Seam 2.2 today. With that out of the way, let us begin with some background.

I am a big fan of the Spring Framework. The many “glue code” utility classes and the Spring IoC Container have been staples in my applications since I started working with the Java Platform. Spring provided a way to do POJO programming in a world that was under the tyranny of the ugly EJB 2 programming model. They created an alternative to a broken standard that was very welcome. But this post is about Seam, so what’s all the Spring talk for? One of the key features, or rather the key feature, of Seam is what the Seam guys like to call Contextual Components. For those of you with a Spring background like me, a Seam Component is analogous to a Spring Bean. The contextual piece is what makes it interesting.

In Spring, you usually assume that a bean is going to be a singleton and that it is going to be stateless. That is the way of things with Spring. The common case is that everything is constructed at startup and all wired together before your application services it’s first request. You get all that glue code and DI goodness right up front. There is another way to handle your beans that is not as widely used. You can declare the scope of a bean to be Prototype, which means Spring will construct a new instance of that bean for you each time you ask your ApplicationContext for it.

Seam has taken this a step further. Instead of beans being limited to being either Stateless application singletons or construction prototypes, Seam let’s you scope components to rich set of contexts. See here for the complete list. This makes the Seam context not just a repository of pre-built service objects, but a scoped application state manager that is managed as a central concern of the framework (which is a fancy way of saying Seam takes care of the plumbing so you don’t have to). Now, instead of having a DAO object that encapsulates your data access methods, you can have a Data Mediator that not only knows how to get at an entity instance and save changes back to the database, but it also tracks the instance in the proper scope for you, so you only have to read it once from the database, even across multiple http requests. It is extremely powerful.

The other piece that Seam adds is called Outjection. No, that isn’t a typo. As part of an operation invoked on a Seam component, it not only gets all it’s dependencies injected, scoped as appropriate for the context of the components involved, but it also can send new components back to the context to be used by other parts of the application, managing the scope all the way.

What does this mean practically? No more leaky Http Sessions!

Now, if you are wondering if this is relevant to where JEE is going, take a look at JSR 299. CDI, or “Web Beans” as it has been called, is largely based on what I just explained to you. This JSR is part of JEE 6 and will available in the next update to your favorite application server. You can get this functionality now with Seam 2.2, or if you are required to “stick with the specs” when you do things, go ahead and download Weld, the JSR 299 reference implementation. Weld is what JBoss AS 6 is using to implement CDI and what Seam 3.0 will be built on.

In my next post, I’ll talk about the power of the new Conversation Context that Seam and JSR 299 introduce.

Bookmark and Share

Refactoring with Spring – Spring Security

Thursday, November 20th, 2008

I have been doing a lot of thinking about Spring lately, and given that Rod is back in my good graces, I wanted to do a few posts on ways spring has made my life easier. In this first post, I’m going to talk about Spring Security, specifically using it to bring a consistent security model to a legacy web app with “home grown” security.

So let’s set the stage. First is our legacy web app with it’s homegrown security. It will have a common header jsp that checks to see if the user’s id is in the session. Remember, this is really old, so I’ll even use scriptlets so you all can feel like it’s 2001 again.


<%
HttpSession mySession = request.getSession(true);
if( mySession.getAttribute("USERID")== null) {
%>
<jsp:forward page="login.jsp" />
<%
}
%>

If you application really has it bad, you’ll have the above block at the top of every jsp instead of a <jsp:include/>.

Now, the problem with this is that if you forget to put this at the top of one of your jsps, that page can now be accessed even if the user isn’t logged in. This technique also is open to a number of session attacks.

Enter Spring Security. We are going to use Spring Security to do a few things. First, we are going to get the security concerns out of the jsp pages and add some session protection. Second, we are going to enable some role_based access control to the different sections of our app.

The only piece of custom code spring security requires you to provide is a implementor of org.springframework.security.userdetails.UserDetailsService. This class is responsible for fetching your user data from wherever it lives. They provide a jdbc implementation (if you use their schema) and an ldap implementation that you can use if you want. Since this is a legacy app we are refactoring, we are going to have to write our own UserDetailsService to get the user data out of the existing tables in the database.

The UserDetailsService returns instances of org.springframework.security.userdetails.UserDetails, which you can implement yourself or used the provided implementations.

When I was implementing spring security in my legacy project, I got this far, put the basic config into my application context as detailed in the Spring Security Reference Manual and I was able to start restricting access to my pages. However, the application I was working with set a bunch of session variables after a successful login that were used by the jsps, so I had to figure out how to handle that. The trick was to implement my own AuthenticationProcessFilter` that would now have the job of setting these session variables. I chose to extend org.springframework.security.ui.webapp.AuthenticationProcessingFilter, overriding the successfulAuthentication() method and I added that to my application context so that it would get picked up by spring security’s filter chain.

What I didn’t realize is that if you want to override that particular filter, you can’t use the <security:form-login/> schema element. That meant I needed to also provide my own authentication entry point. I just used the out of the box one as I had no need of customizing it.

With that taken care of, it was as easy as adding another <security:intercept-url/> to my <security:http> to restrict certain sections of the app to certain roles. See the details in the application context below.

Overall, this took about 9 hours worth of work to get going and that was starting from having never used spring security before. So, if you need to replace your “home grown” webapp security and you need to do it quick, Spring Security is a great way to go.


<?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:security="http://www.springframework.org/schema/security" xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.4.xsd ">

        <!-- Our application's datasource -->
        <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
                <property name="expectedType" value="javax.sql.DataSource" />
                <property name="jndiName" value="jdbc/MyDataSource" />
                <property name="resourceRef" value="true" />
                <property name="lookupOnStartup" value="false" />
        </bean>

        <!-- The JDBC Template for use in legacy code -->
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
                <property name="dataSource" ref="dataSource" />
        </bean>

        <!-- Our UserDetailsService Implementation -->
        <bean id="userDetailsServiceDao" class="com.citytechinc.springsecurity.custom.CustomUserDetailsServiceDaoImpl">
                <property name="jdbcTemplate" ref="jdbcTemplate" />
        </bean>

        <!--
                Custom AuthenticationProcessFilter that sets all the session varibles needed by legacy jsps after successful login. We
                autowire by type to pick up the parts of spring security that are loaded by <security:http/>
        -->
        <bean id="formAuthenticationProcessingFilter" class="com.citytechinc.springsecurity.custom.CustomAuthenticationProcessingFilter"
                autowire="byType">
                <security:custom-filter position="AUTHENTICATION_PROCESSING_FILTER" />
                <property name="defaultTargetUrl" value="/default.jsp" />
                <property name="alwaysUseDefaultTargetUrl" value="true" />
                <property name="authenticationFailureUrl" value="/security/login.jsp?submitType=1" />
                <property name="filterProcessesUrl" value="/security/login_action" />
                <property name="invalidateSessionOnSuccessfulAuthentication" value="true" />
                <property name="migrateInvalidatedSessionAttributes" value="false" />
        </bean>

        <!-- Our authentication entry point, we need this since we are using a custom AuthenticationProcessFilter -->
        <bean id="authenticationEntryPoint" class="org.springframework.security.ui.webapp.AuthenticationProcessingFilterEntryPoint">
                <property name="loginFormUrl" value="/security/login.jsp?submitType=0" />
        </bean>

        <!-- Load our user details service into spring security -->
        <security:authentication-provider user-service-ref ="userDetailsServiceDao" />

        <!-- The bulk of the security config -->
        <security:http session-fixation-protection="newSession" entry-point-ref="authenticationEntryPoint">
                <security:logout invalidate-session="true" logout-success-url="/default.jsp" logout-url="/security/logout_action" />
                <security:anonymous />
                <security:intercept-url pattern="/error*.jsp" access="ROLE_ANONYMOUS,ROLE_USER" />
                <security:intercept-url pattern="/security/log*" access="ROLE_ANONYMOUS,ROLE_USER" />
                <security:intercept-url pattern="/maint/*.jsp" access="ROLE_ADMIN" />
                <security:intercept-url pattern="/**/*.jsp" access="ROLE_USER" />
                <security:intercept-url pattern="/*.jsp" access="ROLE_USER" />
        </security:http>
</beans>


Update!


Here’s a link to the source code for my custom classes. Note: I use the SimpleJDBCTemplate, so you’ll need spring-jdbc from 2.5 or later if you are using maven.

Update: fixed broken link to Spring Security Reference Manual

Update: I had to turn off comments on this post since I was getting tons of spam and I don’t want to have to filter through it anymore.

Bookmark and Share

Reaction to the Spring Source Maintenance Policy

Thursday, November 6th, 2008

I love Spring Framework and I use it in almost every java application I write, big or small. However, my mirth over spring was greatly dampened when they announced their new maintenance policy a few weeks ago. I was horrified that they would stop maintenance on the current community version of spring after 3 months! As a consultant, this was going to have the potential to spell the end of my use of spring in many of my client projects as I doubt I was going to get them to shell out the cash for support from another vendor. Plus in most cases, spring doesn’t provide direct visible benefit to my clients. The benefit of using spring is enablement of testable code through dependency injection and not have to reinvent the wheel on all that boiler plate code for JNDI, JMS, Hibernate, JDBC, Web Services, the list goes on and on.

Being rather behind in my news reader, I was relieved to read Rod Johnson’s post detailing an updated maintenance policy. The biggest deal to me is that the current version of spring will see maintenance releases until the next release reaches release candidate status. I have had very good experience with release candidates of both spring 2.0 and 2.5, so this policy seems great to me. Rod Johnson is officially back in my good graces. :)

Bookmark and Share

SpringSource, JBoss and the Modular Application Server

Friday, July 25th, 2008

I read Rod Johnson’s post on Oracle raising the price of Weblogic a few weeks ago and have been thinking a lot about his recent comments about the SpringSource Application Platform and his predictions for the future of JEE.  The impression I have gotten is that Rod thinks the JEE Application Server is dying.  Perhaps I am naive in disagreeing, but I just don’t see it.  I would agree that the Spring + Hibernate + Tomcat + Web Framework of the Month stack that is very popular meets the need in many cases, but there are instances where a full container is going to fit the bill much better.

My support for this opinoin lies in my deep love of distributed transactions and message-driven applications, where a full JEE container provides nice integration points as part of the spec. Some of you might assert that you can do message driven apps outside of JEE App Server just fine, but only if you want to give up easy integration with a JTA transaction manager.

Back to the SpringSource Application Platform. I respect Rod and SpringSource a ton and I love how the Spring Framework has changed the way I write software, but I have to wonder if part of this is marketing cruft related to the fact that Spring Source is now touting their own application server.  My biggest complaint is against all the talk about how the SpringSource Application Platform is so modular with all of it’s OSGI-loaded goodness. JBoss had a modular application server in 2002!

My other complaint is that I don’t think that OSGI Bundles are going to actually solve the complaints about how complex the packaging of JEE applications is.  Does it have nice dynamic features and slick ways to handle classloading and dependency managemant with hot replacement at runtime?  Absolutely!  Will Average Joe Developer be able to make his own OSGI bundles all work together with a miriad of 3rd party bundles with differing dependency requirement without running into strange classloading issues and dependecy conflits with greater ease than he can right now in JEE?  My guess is no.  By the way, JBoss has been letting you break the rules about how to deploy you JEE application for a long time, allowing for much simpler packaging if that is what you are interested in.

Bookmark and Share

Welcome to the blog of:

Matt Campbell

You are currently browsing the archives for the spring category.

Archives

  • Categories