Category Archives: java

JSF Seam Validation + Custom Messages + Annotations + Internationalization

Validation is one of the first things you test out when evaluating a web framework and its often one of the most time consuming to wrap your head around. In this post I’ll talk about three types of validation mechanisms present in JBoss’ Seam which will get you on your way towards validating web forms without too much pain:

I’m going to cover three cases:

  1. Validating required fields without using annotations
  2. Validating manually and displaying custom messages
  3. Validating fields using Hibernate annotations in Seam beans

We’ll also display messages using a simple resource bundle (java.util.ResourceBundle) which will allow us to internationalize our forms and messages. Let’s dive into the examples:

Validating required fields without using annotations

This is the most general case, you want to force the user to input something in your text fields and if they don’t, you want to display a message telling them just that.

Here’s a JSF form which asks for a username and password:

<h:messages/>
<h:form id="LoginForm">
    <table>
	<tr>
	    <td><h:outputText value="#{messages&#91;'login.username'&#93;}"/></td>
	    <td>
		<h:inputText required="true" value="#{user.username}" label="#{messages&#91;'login.username'&#93;}"/>
	    </td>
	</tr>
	<tr>
	    <td><h:outputText value="#{messages&#91;'login.password'&#93;}"/></td>
	    <td>
		<h:inputSecret required="true" value="#{user.password}" label="#{messages&#91;'login.password'&#93;}"/>
	    </td>
	</tr>
	<tr>
	    <td></td>
	    <td>
		<h:commandButton action="#{loginAction.login}"
				 value="#{messages&#91;'button.login'&#93;}"/>
	    </td>
	</tr>
    </table>
</h:form>

Specifying required=”true” is all you need to validate required fields. The matter of displaying messages is left to the <h:messages/> tag which iterates through the list of messages generated by the validation phase and displays them sequentially.

By default validation messages are displayed in a format that is not very intuitive, in order to change the format you must override a property in your messages.properties file located at the root of your classpath:

javax.faces.component.UIInput.REQUIRED={0} is a required field.

The placeholder is {0} is automatically filled by the label attribute of the <h:inputText> tag. So in the above case if login.username is defined to be “Username” in the resource bundle, the messages that will be printed will be: Username is a required field.

If validation passes, then the login() method on the bean referenced by loginAction will be called (as specified by the <h:commandButton> tag.

Validating manually and displaying custom messages

This is probably the most powerful way of validating user input – programmatically. Let’s face it, the built-in validators can only do so much, at some point you end up writing java code to validate input by checking it against a database or queue etc. Going back to the login example, say we need to check the values supplied by the user against a database and if they match, let them into the system and if they don’t, kick them back to the login page with a message. The login page does not change, let’s get to the LoginAction class:

@Name( "loginAction" )
public class LoginAction {

    @In
    private User user;

    @In(create=true)
    private FacesMessages facesMessages;

    public String login() {
        if (user.getUsername().equals( "Arsenalist" ) && user.getPassword().equals( "Raptors" )) {
            return "success";
        } else {
            facesMessages.addFromResourceBundle("login.failed");
            return "failure";
        }
    }
}

It’s very obvious what’s happening here. The injected instance of FacesMessages allows you to use its addFromResourceBundle() method to specify a message that will be displayed in the view resulting from returning “failure”. Just for completeness sakes, here’s the faces-config.xml navigation rule:

    
    <navigation-rule>
        <from-view-id>/pages/login.xhtml</from-view-id>
        <navigation-case>
            <from-action>#{loginAction.login}</from-action>
            <from-outcome>success</from-outcome>
            <to-view-id>/pages/home.xhtml</to-view-id>
        </navigation-case>
        <navigation-case>
            <from-action>#{loginAction.login}</from-action>
            <from-outcome>failure</from-outcome>
            <to-view-id>/pages/login.xhtml</to-view-id>
        </navigation-case>
    </navigation-rule>

Validating fields using Hibernate annotations in Seam beans

The next step is to apply more complex validation without resorting to writing Java code and for that Seam relies on Hibernate’s validation framework. As an aside, this dependency is probably the most annoying thing about Seam at this point but it works well enough to look past.

Let’s say we need to force the value of username to be atleast 5 characters. In order to do this we need to annotate two things:

  1. The injected user variable in LoginAction so Seam knows to validate it
  2. The User objects properties to specify what to validate.
    1. Here’s the relevant piece in LoginAction.java:

      @Name( "loginAction" )
      public class LoginAction {
          @In @Valid
          private User user;
          public String login() {
              . . . .
          }
      
      

      Here’s the relevant piece in User.java:

      @Name( "user" )
      public class User {
      
          private String username;
          private String password;
      
          @Length(min=5, message= "#{messages['login.username.length']}" )
          public String getUsername() {
              return username;
          }
          . . . .
      

      Notice how we’re using a resource key inside an annotation to print the message. This will look for a resource bundle called messages and inside it for the login.username.length property to retrieve the message. You could alternately just write the message in plain old English inside the annotation but why would you want to when you can internationalize.

      The last thing we need to do is tell the JSF page that it will need validation (I think this is a somewhat redundant step since the bean is already annotated but nonetheless it is required). You must wrap the fields of the login form around the <s:validateAll> tag like so:

      <h:messages/>
      <h:form id="LoginForm">
          <s:validateAll>
                  . . . .
      	    <h:outputText value="#{messages&#91;'login.username'&#93;}"/></td>
                  . . . .
          </s:validateAll>
      </h:form>
      

      Note: Be sure to specify required=”true” for the fields you want to apply annotation validations to. Otherwise, you’ll see some very weird results such as only non-blank fields getting the annotation validations applied to while the blank fields get considered valid.

      Here’s a list of annotations that you can use to validate java beans:

      • @Length(min=, max=) Checks whether the string length matches the range
      • @Max(value=) Checks that the value is less than or equal to the max
      • @Min(value=) Checks that the value is greater than or equal to the min
      • @NotNull Checks that the value is not null
      • @Past For a date object, checks that the date is in the past
      • @Future For a date object, checks that the date is in the future
      • @Pattern(regex=”regexp”, flag=) For a string, checks that the string matches this pattern
      • @Range(min=, max=) Checks whether the value is between the min and the max
      • @Size(min=, max=) For collections, checks that the size is between the two
      • @AssertFalse Asserts that the evaluation of the method is false
      • @AssertTrue Asserts that the evaluation of the method is true
      • @Valid For a collection or a map, checks that all the objects they contain are valid
      • @Email Checks whether the string conforms to the email address specification

      That’s all there is to it.

Performing a LEFT OUTER JOIN using JPQL and JPA

Haven’t made a tutorial-type post in a while so here’s an installment of documenting something that should be already documented. The problem at hand is a very common one: how do you do a LEFT OUTER JOIN on two tables (entities) when you’re using the Java Persistence API.

Let’s go with the sports theme and model basketball shoe sponsorship. An NBA player may or may not have a shoe deal, for example Lebron James has a shoe deal with Nike while Juan Dixon doesn’t. We have two tables and entities to work with: Player and ShoeCompany. Now the task at hand is to retrieve all information about all players. Given that many of them don’t have shoe deals we want to be careful of not ignoring them in our query, that’s where the OUTER JOIN kicks in. In other words, retrieve the set of entities where matching values in the join condition may be absent. Here’s what the entities and tables look like:

@Entity
@Table( name="nba_player" )
public class Player {

    @Id @Column
    private Long id;

    @Column
    private String name;

    @OneToOne
    @JoinColumn( name="shoecompany_id" )
    private ShoeCompany shoeCompany;

    // getters and setters
}
@Entity
@Table( name="shoe_company" )
public class ShoeCompany {

    @Id @Column
    private Long id;

    @Column
    private String name;

    // getters and setters
}

Here’s what the tables look like:

nba_player(id, name, shoecompany_id)
shoe_company(id, name)

Doing this query without an OUTER JOIN is also possible, it’s quite simple actually, we just add an additional WHERE clause where we check for the foreign key being NULL.

SELECT *
FROM nba_player p, shoe_company s
WHERE p.shoecompany_id = s.id or p.shoecompany_id IS NULL

The same SQL query using an OUTER JOIN would look like:

SELECT *
FROM nba_player p LEFT OUTER JOIN  shoe_company s
                                       ON (p.shoecompany_id = s.id)

To generate the OUTER JOIN query using JPQL, you’ll have to write this:

SELECT p FROM Player p LEFT JOIN p.shoeCompany sc

That’s it, now you’re free to use and abuse LEFT OUTER JOINs all you want. I’m using TopLink Essentials as the JPA implementation but that shouldn’t come into play. Grab the techy part of the blog’s feed.

IIS messes with the application lifecycle in a way Tomcat wouldn’t dare

How would you dig it if someone randomly restarted your application every few minutes or so for absolutely no reason? Would you be upset, angry or plain confused on why an application server would bother recycling an application at seemingly random intervals without being prompted. See, just like the Servlet specification defines the ServletContextListener interface, it’s .NET counterpart happens to be Global.asax which defines application lifecycle methods like Application_End, Application_Start and such. A pretty sensible idea when you look at the surface of things but what’s horribly, horribly wrong is that .NET applications shut themselves down every 20 minutes if they detect that no requests have been made to IIS. This is all done in the hopes of preserving IIS resources which makes me wonder just exactly how resource intensive running an IIS app really is.

Now think about this, this means that any context loading or application initialization that you do on startup might be happening a few times an hour just because traffic to your application might be slow. Any static variables that you declare get dumped, any kron processes you’re running get killed, database connection pools get emptied, application scope data is erased, worker threads are stopped, everything is gone! If you’re running a plain old website which doesn’t do much, this might be borderline acceptable, but if you perchance happen to do some medium to heavy initialization, you’re bound to run into big time trouble that will leave you scratching your head and adjusting your crotch. And no, it doesn’t matter what you change in Web.config, nothing can save you.

If this isn’t appalling enough, try checking out some of the work-arounds to this problem. If you’re running a kron job in your application, you’ll realize that you’ll be doing some serious work just to keep it running. One of the arguments you hear is that since it’s a kron job, it really doesn’t belong in a .NET application and that you should really be writing a windows service to do the job for you. Now that’s just plain see-through bullshit, you can’t suggest writing a desktop application and call running a kron job in a web application a bad design The .NET gurus also suggest simulating a call to the web server to keep your application alive, something like the following:

void Application_End(Object sender, EventArgs e) {
   WebRequest request = WebRequest.Create ("http://myapp.com/SomePage.aspx");
   HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
   log.Info("Status: " + response.StatusDescription);
   response.Close ();
}

So pretty much, resuscitate it just before it’s about to croak. Truly a pathetic, pathetic piece of code which only exists because of a deep flaw in .NET”s application lifecycle philosophy. Compare this with the old and sturdy ServletContextListener which wouldn’t have the cahones to call contextDestroyed() even if the app was running for 10 years straight.

Another similar problem in .NET is the tendency for threads to store data in the HttpContext.Current object (kinda like ThreadLocal in Java), except that HttpContext is dependent on the Request object actually existing. If the Request is gone away (which only make sense since it’s an atomic event), any variables tied to it are also gone. I never comprehended why simple static space isn’t used instead.

Now someone might argue that you might be able to tweak settings in Machine.config or go to IIS Manager and drill down to Application Pools (new in IIS 6) and change your DefaultAppPool properties to alter the behavior of worker processes, which might do the trick. But the problem is that the default behavior of ALL IIS hosting companies is to leave this crucial setting at it’s default value and the worst part is that it can’t be altered at an application level but only in IIS. Something which just flat out sucks.

Logging abstraction is utterly pointless

I had always thought so but in the last week I’ve concluded with dynamite determination that logging abstraction is completely pointless. No. Benefit. Whatsoever. Could I be mistaken? No, if anything you’re probably still hanging on to Commons Logging because somebody told you how great it was, I don’t think anyone in their right mind would, after taking a step back and looking at the circumstances say, Hmmm, I really need to be careful and not commit myself to Log4J because God knows when Mark Womack and his team might pack it in and leave me hangin’. The same people who name their first born after Commons Logging classes commit themselves to products like IText, JFreeChart and GodKnowsWhat without ever thinking about abstraction. Raise your hand if you’re ever used IText and considered what happens if you want to switch your PDF generation tool? Nobody? So why the hell do we care so much about logging?

Luckily the answer is as simple as it is stupid: making a logging tool is so freaking easy that everybody’s got a homegrown one which they swear by and would never ditch even if they were offered ass in return (this just in, Logger just won the most used classname ever, it beat out Tester). So instead they use Commons Logging which gives them the feeling of not being such a big idiot with the added bonus of sleeping well at night knowing that they could eaaaasily switch to Log4J if they wanted to. What these poor saps don’t know is that switching between logging tools isn’t even that easy regardless of the abstraction, you still have to worry about configuring your tool which is a major pain in the ass if you want to actually stick to the proper log levels. Besides, nobody’s switching to anything, once you pick a logging framework you stick with it until the application is dead. Period. No exceptions. And if you happen to be switching your logging implementation so frequently that you need abstraction you suck at design and product evaluation.

Do you really care which of the two following imports you’d rather have shit on your code: org.apache.commons.logging or org.apache.log4j. Unless you have a thing for using commons packages (and some people do) you probably don’t give a rats ass. So with that in mind why don’t we save ourselves some trouble and just use Log4J, and as a bonus I’ll throw in the pro of Tomcat not barfing every time it sees two commons logging jars in its classpath, God forbid if they’re two different versions because then it starts giving you errors that make you regret ever even getting into Java.

The only way to beat Log4J is to have something out of the ever so trustworthy java.* packages do the logging for you. Luckily there’s JULI which is really great but unfortunately it’s documented about as poorly as Guice and isn’t marketed nearly as aggressively as that retard Duke (I really hate that son of a bitch, looks like a tooth with a big cavity). Besides, anytime anyone asks you to modify something in the JAVA_HOME directory to configure something red flags go up. Somebody please document how to load a config file from your classpath without specifying a -D option in JAVA_OPTS. I mean I’m configuring logging, not optimizing my garbage collection, yeeeesh.

Subscribe to Arsenalist's tech feed

Career not going anywhere? Just change your title

So you’ve been working away at your development job for God knows how long and there’s no end in sight to your misery. There’s no chance of moving up in the company and although your bosses like you, they don’t think much of you. They’re happy with what you’re doing as long as you do it quietly, deliver in the whereabouts of your deadlines, show up to the company picnic and stay out of any real decision making. You’re taking up more and more responsibilities over the years but your pay is only being raised by a paltry 2% while the cost of living is going up by 5. You know you’re being fucked but are too lazy or incapable of doing anything. So what do you do? You change your title of course.

Continue reading

Indian outsourcing is killing IT

The mailing lists were never easy to read through but if a man put his mind to it and used the delete button swiftly enough you could actually get something out of them and maybe even find a reason to stay on. But ever since everybody in North America cheaped out and started sending all the work to India the mailing lists of every major product have been polluted with the Sanjays and Prashants of this world asking questions that make me wonder why the hell we’re sending out our prized projects to these seemingly incompetent people.

Granted they come cheap but even so judging from their posts and having worked with them on a couple projects I still haven’t found a singular reason why I should trust them to write a simple POJO. Their unaccountability on their mailing list is appalling, I wouldn’t want my company being represented by some dude who’s asking the struts-user list questions like these and putting their company name and his title at the bottom. This just tells me you’re an idiot and have no clue what you’re doing.

I realize that I’m generalizing and that there are always exceptions, but if you Nabble through the Maven, IBatis, Struts etc user lists you’ll encounter posts which make it apparent that the author has the most rudimentary knowledge of the product and of software design and is just hoping to get by. This theme is prevalent across most mailing lists leading me to believe that this is a widespread disease which effects the outsourcing industry. Given the apparently skill level of the people working on these projects, one can only surmise that the quality of work being done in those countries is subpar. Also, posting your resumes and asking for H1 visas on peoples blogs does not help your credibility nor does it showcase your skills. Again, it just makes you look like an idiot.

Here’s an exercise: try posting an ad for a development project on Craiglist and ask for a quote. What you’ll end up getting is tin-canned emails from India that list Gupta Inc. as knowing EVERY SINGLE LANGUAGE AND DATABASE PLATFORM EVER MADE. Then follow up with a random one and actually talk to their “Project Manager” and you’ll notice that the email was just a bunch of bullshit and you’re dealing with a two-man operation run out of a basement on a Pentium II.

Lately I’ve met an increasing number of people who are “managing a team in India” and work for a company with an accent in it’s name. These are the new managers the IT industry is producing, usually they’re in their mid-20’s and consider their new “manager” role a promotion. But when you’re managing narrow-minded developers getting paid the minimum wage and communicating 95% of the time over MSN, the work that’ll get done will reflect the circumstances and talent of the people involved. Software development is an industry where geographic location hardly seems to matter but when we’re communicating requirements, design and expectations entirely over chat, things are bound to get lost in translation. My point? You can’t oversee a project if you’re thousands of miles away, especially if you’re dealing with a guy who’s trying to scrape by. This whole system is flawed and annoying, both from the manager’s and developer’s perspective.

As long as you can tolerate their nerdiness and smell you can generally have a conversation with another North American developer and talk about a wide range of languages and tools without too many awkward moments. Not the case with slave labor. I visited India a couple years ago and had a chance to speak with some developers working at India’s second richest bank. The first think you notice about these people is how specialized they are. If they have a Java job, that’s all they know. Nothing more. Java. Java. Java. If they have a Perl job, it’s all about Perl and they’ll write everything in Perl and not even consider anything else for any reason. The mentality seems to be to get the job done as the lowest price and as fast as possible, nothing else matters. Fair enough, but I just don’t see the price of the work making up for the lack of quality and the general fuckedupness of the process.

And yes, I’m an Indian.

 Get the feed

CXF WS-Security using JSR 181 + Interceptor Annotations (XFire Migration)

I had blogged about how to setup XFire with WS-Security a while ago and since then the XFire 1.x series as we know it is dead, instead Apache’s CXF can be considered XFire 2.0. CXF improves over XFire in many areas including better architecture and more importantly easier message handling and manipulation. In this entry, we’ll setup a CXF application that secures its services using CXF’s WS-Security features.

Before I get to the example I want to mention some of the major changes that I noticed in CXF:

  • Interceptors instead of handlers: Handlers are out and are replaced with a much more common concept of interceptors (if you’re from the Struts2/Webwork world you know what they are). Interceptors are created by extending the AbstractPhaseInterceptor class which forces you to implement handleMessage(Message). Note that you must specify the phase where you want each interceptor executed.
  • Access to MessageContext: In XFire, the MessageContext was always available in your handlers. In CXF you don’t have access to it in the interceptor but you can get contextual properties using the message.getContextualProperty(String) methods. Access to the MessageContext is also available using the @Resource annotation as described here but this only works in service implementations.
  • JAXWS Endpoints: Spring service classes must be exposed using the <jaxws:endpoint> tag. You can also do this programmatically but why would you.
  • Message and Exchange: The Message and Exchange objects have changed dramatically from XFire. CXF’s Message and Exchange objects are devoid of all those helpful methods that were present in XFire but they make up for it by having get(Class) and get(String) methods which can be used to retrieve valuable information. It’s probably a good idea to look through Exchange.keySet() and Message.keySet() and see whats available to you in your interceptors. For example when a Fault occurs, the message.get(Exception.class) returns the exception that was thrown to cause the fault. Also note that the information present in these maps varies depending on what Phase you’re in.

Now to the WS-Security example. CXF just added support for configuring interceptors using annotations which means configuring WS-Security for our web services just got easier.

Here’s the service interface and implementation.

@WebService
public interface SportsService {
    public String getTeam();
        return "Arsenal";
    }
}

@WebService(
    serviceName="SportsService",
    endpointInterface="ca.utoronto.sis.cxfapp.SportsService")
@InInterceptors(interceptors={
        "com.arsenalist.cxfapp.WSSecurityInterceptor"
})
public class SportsServiceImpl implements SportsService {

    public String getTeam() {
        return "Arsenal";
    }
}

I’ve added a single in interceptor called WSSecurityInterceptor which is a class that we’ll write. In XFire we also needed a DomInHandler and a DomOutHandler for each service implementation, none of that is required here. WSSecurityInterceptor will just wrap the WSS4JInInterceptor class, the reason we can’t just specify WSS4JInInterceptor as an annotation is because we need to set custom properties on it such as using UsernameToken authentication.

The other thing WSSecurityInterceptor does is add a ValidateUserTokenInterceptor which is similar to ValidateUserTokenHandler in the XFire examples. Since WSS4J validates a UsernameToken only if it finds a security header we need to cover the case where no security header is specified. ValidateUserTokenInterceptor just makes sure the username, password, nonce and timestamp are specified before even considering it a valid request. Here’s the WSSecurityInterceptor and the PasswordHandler class:

public class WSSecurityInterceptor extends AbstractPhaseInterceptor {

    public WSSecurityInterceptor() {
        super(Phase.PRE_PROTOCOL);
    }
    public WSSecurityInterceptor(String s) {
        super(Phase.PRE_PROTOCOL);
    }

    public void handleMessage(SoapMessage message) throws Fault {

        Map props = new HashMap();
        props.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
        props.put(WSHandlerConstants.PW_CALLBACK_REF, new PasswordHandler());

        WSS4JInInterceptor wss4jInHandler = new WSS4JInInterceptor(props);
        ValidateUserTokenInterceptor userTokenInterceptor = new ValidateUserTokenInterceptor(Phase.POST_PROTOCOL);

        message.getInterceptorChain().add(wss4jInHandler);
        message.getInterceptorChain().add(new SAAJInInterceptor());
        message.getInterceptorChain().add(userTokenInterceptor);
    }
}

public class PasswordHandler implements CallbackHandler {
    public void handle(Callback[] callbacks) throws IOException,
            UnsupportedCallbackException {
        WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];
        if (pc.getIdentifer().equals("arsenal")) {
            pc.setPassword("gunners");
        }
    }
}

Note that the ValidateUserTokenInterceptor is invoked in a later phase than WSS4JInterceptor. Here’s the ValidateUsertokenInterceptor class:

public class ValidateUserTokenInterceptor extends AbstractPhaseInterceptor {

    public ValidateUserTokenInterceptor(String s) {
        super(s);
    }

    public void handleMessage(SoapMessage message) throws Fault {
        boolean userTokenValidated = false;
        Vector result = (Vector) message.getContextualProperty(WSHandlerConstants.RECV_RESULTS);
        for (int i = 0; i &lt; result.size(); i++) {
            WSHandlerResult res = (WSHandlerResult) result.get(i);
            for (int j = 0; j &lt; res.getResults().size(); j++) {
                   WSSecurityEngineResult secRes = (WSSecurityEngineResult) res.getResults().get(j);
                    WSUsernameTokenPrincipal principal = (WSUsernameTokenPrincipal) secRes
                            .getPrincipal();

                    if (!principal.isPasswordDigest() ||
                            principal.getNonce() == null ||
                            principal.getPassword() == null ||
                            principal.getCreatedTime() == null) {
                        throw new RuntimeException("Invalid Security Header");
                    } else {
                        userTokenValidated = true;
                    }
                }
            }
        }
        if (!userTokenValidated) {
            throw new RuntimeException("Security processing failed");
        }
    }
}

Now we have a service implementation annotated in a way where it is WS-Security enabled and is also registered as a web service. The final step remaining is to expose it as a consumable endpoint. That can be achieved by either of the following ways:

Using the fully qualified class name:

<jaxws:endpoint
   id="helloWorld"
   implementor="com.arsenalist.cfxapp.SportsServiceImpl"
   address="/SportsService" />

Or by referring to a Spring bean corresponding to the @WebService annotated class. This would be more prudent if you’re using Dependency Injection in your service implementations.

<bean id="sportsServiceImpl" class="com.arsenalist.cfxapp.SportsServiceImpl"/>

<jaxws:endpoint
   id="sportsService"
   implementor="#sportsServiceImpl"
   address="/SportsService" />

Finally you could also just use good ‘ol fashioned Spring beans. This comes in handy if you wan to specify a different binding like Aegis:

<bean id="aegisBean" class="org.apache.cxf.aegis.databinding.AegisDatabinding"/>
<bean class="org.apache.cxf.frontend.ServerFactoryBean" init-method="create">
	<property name="serviceBean" ref="registrationSoapService"/>
	<property name="address" value="/services/1_0_0/Registration"/>
	<property name="dataBinding" ref="aegisBean"/>
</bean>

The CXF documentation which shows how to configure the web.xml is pretty straightforward.

If you’re using Maven, the dependencies section of the pom.xml might look something like this. Remember that support for configuring interceptors via annotations was just added so you have to access the SNAPSHOT repositories instead of the main one.

<repositories>
    <repository>
        <id>apache-snapshots</id>
        <name>Apache SNAPSHOT Repository</name>
        <url>http://people.apache.org/repo/m2-snapshot-repository/</url>
        <snapshots>
        <enabled>true</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>apache-incubating</id>
        <name>Apache Incubating Repository</name>
        <url>http://people.apache.org/repo/m2-incubating-repository/</url>
    </repository>
</repositories>
<dependencies>
    ...
    <!-- spring beans, core, context, web 2.0.6 -->
    ...
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-transports-http</artifactId>
        <version>2.1-incubator-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-core</artifactId>
        <version>2.1-incubator-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-frontend-jaxws</artifactId>
        <version>2.1-incubator-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-ws-security</artifactId>
        <version>2.1-incubator-SNAPSHOT</version>
    </dependency>
    ...
<dependencies>

Thanks for reading.

Spring’s AOP support can’t be ignored

You see I’ve never actually written many (any?) AOP classes but there’s enough talk about it splashed all over the internet that even though it might be a worthless concept that you’ve never used or cared about, you’re bound to encounter it at some point. A fellow GO Train rider once told me it was the thing to know if you want to have a Java job in five years. That made me read the AspectJ in Action book which makes you feel guilty about not using AOP. I don’t talk to that guy anymore. Then there’s Adrian Colyer who will have you believe that AOP is the glue that ties every enterprise application together and without it you might be writing code that is hanging on by threads.

Now I realize for some of you this might bring flashbacks to 2004 but bear with me. A few days ago I had to catch an Exception in the DAO layer and translate it to something else, now normally this very simple problem is solved by 95% of the monkeys by using a try/catch on the Exception and throwing something more worthy of being bubbled up. But if the same DAO method is being executed in different places in your application you might have to do separate try/catch blocks for each, something which is totally acceptable, clear, concise and happening for ages. There’s nothing wrong with it.

But there is an AOP way of doing this outlined pretty clearly in the docs where you write a pointcut and provide advice on the execution of the event. No try/catch blocks, the client code is devoid of any knowledge about exceptions. Spring’s AOP support makes doing this the AOP way very easy, but is it overkill? I don’t know, I guess it depends on your style of development.

So to replace the generic try/catch mechanism with the AOP way, first declare a pointcut:

package com.arsenalist.aop;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class SystemArchitecture {

    @Pointcut("execution(* com.arsenalist.dao.*.*(..))")
    public void daoOperation() {}
}

Once we’ve specified what methods to monitor using pointcuts, give advice on what should happen when the pointcut is executed.

package com.arsenalist.aop;

import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class DaoExceptionTranslator {

    @AfterThrowing(
      pointcut="com.arsenalist.aop.SystemArchitecture.daoOperation()",
      throwing="ex")
    public void translateException(Exception ex) {
        throw new RuntimeException("Generic message");
    }
}

With the above setup any method executed in the com.arsenalist.dao.*.* packages will be translated into a RuntimeException. I’m assuming that the interfaces reside in com.arsenalist.dao package and the implementations in a package underneath that. Here’s the Spring configuration needed:

<bean id="daoExceptionTranslator" class="com.arsenalist.aop.DaoExceptionTranslator"/>
<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" />

Most importanly the Maven POM should look something like this:

<dependency>
    <groupId>aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.5.3</version>
</dependency>
<dependency>
    <groupId>aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.5.3</version>
</dependency>
<dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib-nodep</artifactId>
    <version>2.1_3</version>
</dependency>
<dependency>
    <groupId>asm</groupId>
    <artifactId>asm-all</artifactId>
    <version>2.2</version>
</dependency>

Although there is a newer version of ASM available, it doesn’t seem to be compatible with Spring AOP.

There can be many arguments against this setup, the main one being that you’re unable to handle the same Exception differently depending on where it’s being called from. To do that you’d have to specify another pointcut and another advice on how to handle it. You also lose all call-context information because you’re assuming that everthing you need to handle the exception is in the Exception object.

But in the general sense it does seem to be an improved method of executing baseline operations when a particular event occurs. The docs get you thinking about other places where you can use AOP proxies instead of the “normal” way of doing things and it’s pretty easy to get sucked into “convert everything to AOP mode”.

If you’re afraid of proxies, this is not for you. Every call to the DAO layer happens via a proxy which is necessary to achieve the intended effect. I’m not sure what the performance penalites of using proxys on every single call to the DAO layer are but if you go this route, CGLIB proxies are apparently much faster than their JDK counterparts. Either way, if you haven’t tried out AOP but are sick of hearing the sound of it, give Spring AOP a shot. It’s probably worth it.

Unit Testing Struts 2 Actions wired with Spring using JUnit

Hopefully this entry serves as some search engine friendly documentation on how one might unit test Struts 2 actions configured using Spring, something I would think many, many people want to do. This used to be done using StrutsTestCase in the Struts 1.x days but Webwork/Struts provides enough flexibility in its architecture to accommodate unit testing fairly easily. I’m not going to go over how the Spring configuration is setup. I’m assuming you have a struts.xml file which has actions configured like this:

<struts>
 <package namespace="/site" extends="struts-default">
  <action name="deletePerson" class="personAction"
                  method="deletePerson">
   <result name="success">/WEB-INF/pages/person.jsp</result>
  </action>
 </package>
 ...
</struts>

You also might have an applicationContext.xml file where you might define your Spring beans like this.

<beans>
 <bean id="personAction"
  class="com.arsenalist.action.PersonAction"/>
 ...
</beans>

Then of course you also need to have an action which you want to test which might look something like:

public class PersonAction extend ActionSupport {

  private int id;

  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String deletePerson() {
    ....
    return SUCCESS;
  }
}

Remember than in Struts 2, an action is usually called before and after various other interceptors are invoked. Interceptor configuration is usually specified in the struts.xml file. At this point we need to cover three different methods of how you might want to call your actions.

  1. Specify request parameters which are translated and mapped to the actions domain objects (id in the PersonAction class) and then execute the action while also executing all configured interceptors.
  2. Instead of specifying request parameters, directly specify the values of the domain objects and then execute the action while also executing all configured interceptors.
  3. Finally, you just might want to execute the action and not worry about executing the interceptors. Here you’ll specify the values of the actions domain objects and then execute the action.

Depending on what you’re testing and what scenario you want to reproduce, you should pick the one that suits the case. There’s an example of all three cases below. The best way I find to test all your action classes is to have one base class which sets up the Struts 2 environment and then your action test classes can extend it. Here’s a class that could be used as one of those base classes.

See the comments for a little more detail about whats going on. One point to note is that the class being extended here is junit.framework.TestCase and not org.apache.struts2.StrutsTestCase as one might expect. The reason for this is that StrutsTestCase is not really a well written class and does not provide enough flexibility in how we want the very core Dispatcher object to be created. Also, the interceptor example shown in the Struts documentation does not compile as there seems to have been some sort of API change. It’s been fixed in this example.

import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.ActionProxyFactory;
import junit.framework.TestCase;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.Dispatcher;
import org.apache.struts2.views.JspSupportServlet;
import org.springframework.context.ApplicationContext;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletConfig;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.ContextLoader;

import java.util.HashMap;

/**
 * @author Zarar Siddiqi
 */
public abstract class BaseStrutsTestCase extends TestCase {
    private static final String CONFIG_LOCATIONS = "META-INF/applicationContext-app.xml," +
                "META-INF/applicationContext-security.xml";
    private static ApplicationContext applicationContext;
    private Dispatcher dispatcher;
    protected ActionProxy proxy;
    protected static MockServletContext servletContext;
    protected static MockServletConfig servletConfig;
    protected MockHttpServletRequest request;
    protected MockHttpServletResponse response;

    public BaseStrutsTestCase(String name) {
        super(name);
    }

    /**
     * Created action class based on namespace and name
     * @param clazz Class for which to create Action
     * @param namespace Namespace of action
     * @param name Action name
     * @return Action class
     * @throws Exception Catch-all exception
     */
    @SuppressWarnings("unchecked")
    protected <t> T createAction(Class<t> clazz, String namespace, String name)
            throws Exception {

        // create a proxy class which is just a wrapper around the action call.
        // The proxy is created by checking the namespace and name against the
        // struts.xml configuration
        proxy = dispatcher.getContainer().getInstance(ActionProxyFactory.class).
                createActionProxy(
                namespace, name, null, true, false);

        // by default, don't pass in any request parameters
        proxy.getInvocation().getInvocationContext().
                setParameters(new HashMap());

        // do not execute the result after executing the action
        proxy.setExecuteResult(true);

        // set the actions context to the one which the proxy is using
        ServletActionContext.setContext(
                proxy.getInvocation().getInvocationContext());
        request = new MockHttpServletRequest();
        response = new MockHttpServletResponse();
        ServletActionContext.setRequest(request);
        ServletActionContext.setResponse(response);
        ServletActionContext.setServletContext(servletContext);
        return (T) proxy.getAction();
    }

    protected void setUp() throws Exception {
        if( applicationContext == null ) {
            // this is the first time so initialize Spring context
            servletContext = new MockServletContext();
            servletContext.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
                    CONFIG_LOCATIONS);
            applicationContext = (new ContextLoader()).initWebApplicationContext(servletContext);

            // Struts JSP support servlet (for Freemarker)
            new JspSupportServlet().init(new MockServletConfig(servletContext));
        }
        // Dispatcher is the guy that actually handles all requests.  Pass in
        // an empty. Map as the parameters but if you want to change stuff like
        // what config files to read, you need to specify them here.  Here's how to
        // scan packages for actions (thanks to Hardy Ferentschik - Comment 66)
        // (see Dispatcher's source code)
        HashMap params = new HashMap();
        params.put("actionPackages", "com.arsenalist.action");
        dispatcher = new Dispatcher(servletContext, params);
        dispatcher.init();
        Dispatcher.setInstance(dispatcher);
    }
}

By extending the above class for our action test classes we can easily simulate any of the three scenarios listed above. I’ve added three methods to PersonActionTest which illustrate how to test the above three cases: testInterceptorsBySettingRequestParameters, testInterceptorsBySettingDomainObjects() and testActionAndSkipInterceptors(), respectively.

public class PersonActionTest extends BaseStrutsTestCase {

 /**
  * Invoke all interceptors and specify value of the action
  * class' domain objects directly.
  * @throws Exception Exception
  */
 public void testInterceptorsBySettingDomainObjects()
         throws Exception {
  PersonAction action = createAction(PersonAction.class,
                "/site", "deletePerson");
  action.setId(123);
  String result = proxy.execute();
  assertEquals(result, "success");
 }

 /**
  * Invoke all interceptors and specify value of action class'
  * domain objects through request parameters.
  * @throws Exception Exception
  */
 public void testInterceptorsBySettingRequestParameters()
                     throws Exception {
  createAction(PersonAction.class, "/site", "deletePerson");
  request.addParameter("id", "123");
  String result = proxy.execute();
  assertEquals(result, "success");
 }

 /**
  * Skip interceptors and specify value of action class'
  * domain objects by setting them directly.
  * @throws Exception Exception
  */
 public void testActionAndSkipInterceptors() throws Exception {
  PersonAction action = createAction(PersonAction.class,
                  "/site", "deletePerson");
  action.setId(123);
  String result = action.deletePerson();
  assertEquals(result, "success");
 }
}

The source code for Dispatcher is probably a good thing to look at if you want to configure your actions more specifically. There are options to specify zero-configuration, alternate XML files and others. Ideally the StrutsTestCaseHelper should be doing a lot more than what it does right now (creating a badly configured Dispatcher) and should allow creation of custom dispatchers and object factories. That’s the reason why I’m not using StrutsTestCase since all that does is make a couple calls using StrutsTestCaseHelper.

If you want to test your validation, its pretty easy. Here’s a snippet of code that might do that:

 public void testValidation() throws Exception {
  SomeAction action = createAction(SomeAction.class,
                  "/site", "someAction");
  // lets forget to set a required field: action.setId(123);
  String result = proxy.execute();
  assertEquals(result, "input");
  assertTrue("Must have one field error",
                  action.getFieldErrors().size() == 1);
 }
 

This example uses Struts 2.0.11 and Spring 2.0.6. That about sums things up.

Updated on November 4th, 2007 to make it a little simpler and compatible for newer versions of Struts and Spring. Thanks to Haroon Rafique.

When Web 2.0 goes wrong – Part 2

Here’s the second part of my rundown of Webware’s “best web apps“. Check out the first installment if you haven’t already. Here are the offenders:

Windows Live Hotmail: In other words, Hotmail. All the power to the guy who invented Hotmail and blew open the doors to internet communication, its just too bad Microsoft has since ruined Hotmail by first a) not improving it for the first five years after acquiring it and b) by handing the renovation project over to a bunch of monkeys who insist on making it look more like Windows, only slower. Just like anything else webby, Microsoft was late in pumping out a proper email platform and when it finally did, it forgot to copy Gmail properly. Instead it took the approach of copying Gmail and at the same time keeping components of the already crappy Hotmail intact. Bad move. I don’t want to right click to select multiple messages, we do that with checkboxes on the web. The Spam filtering is still brutal and the emails that you actually want to receive end up in the Junk folder (something that has NEVER happened to me with Gmail) or you’re forced to click pointless buttons like “Show Content” and “Mark as Safe” even for emails sent by your Mom. The interface shifts more often than Alberto Gonzales and 20% of the screen is taken up by an ad. The concept of tags still hasn’t caught on and you’re forced into segregating content into folders. If you have any integrity you should stop using Hotmail.

Windows Live Messenger: In other words, MSN. I still have a copy of 4.1 on my machine, see that’s where the product stopped being chatting software and turned into a slow and bloated commercial about other Microsoft services. Throw in links to date.com, some trashy horoscope sites, an MSN Today popup that should never have seen the light of day and you end up with Windows Live Messenger – the crappiest chatting software in the world. It must’ve been a slow year for Webware to select this piece of trash in their top 500. The problem with this thing is that it doesn’t know who its catering to so it tries to please everyone: huge emoticons, whiteboards, limits on how much an be typed, multiple contact groups, bulky user interface, games, celebrity gossip, all send mixes messages to someone who’s just trying to tell his wife to pick up some bread when coming back from work. Death to Messenger.

Flickr: OK, you have to understand that unless you have a pro account Flickr is about as useless as an appendix. Here are some of the restrictions: only three albums allowed, 100MB upload per month and here’s the kicker: You can only display 200 images at any given point! The last restriction pretty much encapsulates the first two rendering the entire product worthless for anyone who takes say 10 pictures a month. So much for the “Flickr loves you” slogan, a more appropriate one would be “Buy the pro account!”. Sure there’s some nice stuff, RSS feeds and of the sort but if you’re going to spend your money, don’t give it to Yahoo, they’re rich enough. Try SmugMug which is vastly superior and run by people who genuinely care about your user experience (use vz6dRtcdUp91g as the coupon code to help a brother out). If you’re too cheap to spend money on photography storage, PhotoBucket is still better than Flickr. They don’t have a great uploader but thanks to the people at Flock, that’s been taken care of.

MyPunchBowl: Again with the modal boxes. Go there, sign up, and try to add an event, then tell me what you think of the site. The love affair with Lightbox continues as it seems every alternate form is using it regardless of whether the usage is justified. Maybe its something about the screen dimming after you click on a button that gets developers and marketing folks all wet in the pants, either way it’s getting to the point where usability is being sacrificed for the sake of using a gimmick. Also, since when did it become so cumbersome to click “Edit” and then start typing that people have resorted to making multiple text boxes and textareas disabled only to bring them to life after an unintuitive click, thereby wasting away any sort of tacit knowledge the user might’ve had. Where and when did this design principle pop out? A site that is dead simple in the functionality it offers is made to look like a 70 year old whore in 5 inch heels.

Wink: This sight is a little scary. It’s a people search that searches social networks such as MySpace, Bebo, LinkedIn and Friendster to suck any information about the unfortunate soul whose name was typed. Apparently the privacy agreements you sign on some of these sites allow third party apps to search their databases, pull up personal info including photographs and display it to ANYONE, something that might not be apparent at first glance. Remember the times when it was cool to use an image for a button? Well that practice is still acceptable as long as the result is somewhat pleasing to the eye. Don’t tell that to the designers at Wink, they love to use buttons with gradients that bring you all the way back to 1998 making you wonder where the colored scrollbars which would make the experience complete are. The app doesn’t search Facebook so it’s pretty much pointless.