bookmark_borderCoupling: The factory method

One of the challenges we face with coding is dealing with coupling. Coupling is an important aspect of programming, it tells us how much our code is tangled. When coupling is too high, we can’t easily re-use code. When the coupling is too low it does little. You can measure coupling, there are several metrics for it even (for instance “Coupling between Objects, CBO”).

In this blog post I’d like to talk about a subtle introduction of coupling: when you introduce a factory method.

Consider you have an interesting piece of code, and this piece of code has quite a lot of properties:

class Person {
	private String firstName;
	private String lastName;
	// .. more properties here

	public void subcribeTo(Subscription subscription) {
		// do something interesting here
	}

}

The problem is, because of the amount of properties and other dependencies, we’d like to simplify its creation by introducing a Factory method. In this case we are building a web application, so we take the Request as input to read the parameters:

class Person {
	private String firstName;
	private String lastName;
	// .. more properties here

	public static Person create(HttpServletRequest request, .. more arguments here .. ) {
		this.firstName = request.getParameter("firstName");
		// .. read more properties
		// .. set up dependencies, etc.
	}

	public void subcribeTo(Subscription subscription) {
		// do something interesting here
	}

}

In the code that uses Person, it becomes easier to construct the Person and we’re happy with that. However, we have introduced coupling on several levels:

  • We construct the object with specific parameters in the create method. If we want to create from different parameters, we cannot use it. There is a coupling between the parameters and the properties.
  • The object is constructed using a Request object. We cannot now move the class to an application that does not use the web. A person has nothing to do with a request, it is just convenience that we put the factory method in the Person class. There is a coupling between the code of Person and the dependency delivering the Request object.

There are several ways to deal with this. But lets start with the last reason of coupling. It is easy to fix this coupling by creating a Factory class within your web application. From there you can generate the Person object out of a request. The Person class has no create method anymore, and thus is not tightly coupled to a Request class. The newly created Factory however is coupled to the Request, which is fine as it is meant to convert Requests into Person objects. Hence we could even name it that way:

class Person {
	private String firstName;
	private String lastName;
	// .. more properties here

	Person(String firstName, String lastName, ...) {
		this.firstName = firstName;
		this.lastName = lastName;
		// ...
	}


	public void subcribeTo(Subscription subscription) {
		// do something interesting here
	}

}

class PersonFromRequestFactory {

	// .. dependencies here 

	public Person create(HttpServletRequest request) {
		Person person = new Person(request.getParameter("firstName"), )		
		// .. read more properties
		// .. set up dependencies in Person, etc.
	}

}

Once we have this Factory, you can take it a step further:
If you have different kind of request parameters to create the same object you could create different methods in the new Factory:

class PersonFromRequestFactory {

	// .. dependencies here 

	public Person createFromRegistrationForm(HttpServletRequest request) {
		Person person = new Person(request.getParameter("firstName"), )		
		// .. read more properties
		// .. set up dependencies in Person, etc.
	}


	public Person createFromSubscriptionForm(HttpServletRequest request) {
		Person person = new Person(request.getParameter("givenName"), )		
		// .. read more properties
		// .. set up dependencies in Person, etc.
	}


}

You could also create a Parameter object and go from there. For instance, if your web application uses Spring, you could wire your request parameters to an object (called “Form binding“) automagically and use that object as input in your Factory. This way it is type safe:

class PersonFromRequestFactory {

	// .. dependencies here 

	public Person create(RegistrationForm form) {
		Person person = new Person(form.getFirstName(), ...)		
		// .. read more properties
		// .. set up dependencies in Person, etc.
	}


	public Person createFromSubscriptionForm(SubscriptionForm form) {
		Person person = new Person(form.getGivenName(), )		
		// .. read more properties
		// .. set up dependencies in Person, etc.
	}


}

But how do you test all this?
Did you notice the Person has private fields, and no get/set methods? The only way to set the fields is using the Person constructor. How do you test the correct construction of this Person class from the request? Since we are not able to read the properties, we have to use other ways to test that code. I’ll cover that in the next blog post.

bookmark_borderGotcha’s showing error messages with Spring forms (form:errors)

(I have recently encountered this with Spring 3.1)

Want to validate your forms using Spring? Are you using the form tag and bind it with an object? Got the validator working? But still you just can’t seem to get these error messages showing up? Here is a gotcha that might help you out!

Consider this controller:

@Controller
public class FormController {

    @RequestMapping("/form")
    public ModelAndView handleGet(@Valid TellAFriendForm backingForm, BindingResult bindingResult) {
        ModelAndView modelAndView = new ModelAndView("backingForm");
        modelAndView.addObject("backingForm", backingForm);
        modelAndView.addObject("result", bindingResult);
        return modelAndView;
    }

}

With this jsp:

<form:form method="POST" commandName="myForm" action="?">
    <div>
        <label for="name">Name*</label>
        <form:input path="name" id="name"/>
        <form:errors path="name"/>
    </div>
    <div>
        <input type="submit" value="Send"/>
    </div>
</form:form>

When the user submits this form, the form should be validated. Whenever a field does not validate, it should inform the user about this.

This is done by using:

        <form:errors path="name"/>

Where ‘path’ refers to a field in the bound form object, in this case myForm. In this example, I have named my form “myForm”. The theory is that when the form is being validated, the BindingResult (put as “result” on the model), contains all fields that have validation errors. Using the form:errors tag you can make use of that and show error messages.

Although this works often, sometimes it does not and you spend some time figuring out why. A common gotcha is that you forget to put the bindingResult on your model (as “result”).

But there is another less intuitive gotcha.

When your given commandName in the form:form tag does not represent the camelcased, name of the type of the form, the form:errors tag will *not* work. So don’t make up your own name. Make sure it is the same as the type, and make sure it is camelcased correctly. I figured this out the hard way.

Solution: The form object is of type: BackingForm, the expected name would then be backingForm. Change the commandName into backingForm and you will see the form error messages showing up.

bookmark_borderRetrospective : JFall 2011

I’ve visited JFall, a conference held by the NLJUG (Dutch Java User Group), at 2 november 2011. In this blog I’d like to share my experiences of this conference. This was my first time at this conference and I pretty much had no expectations.

My pass for JFall 2011

There was a lot to go to; I have visited the following seemingly interesting topics:

Keynote – Java 7 Directors Cut
Overthere – Design and implementation of a Java Remote File and Execution framework
Hands on lab – Clojure – A gentle introduction to a brilliant language
Keynote – Building Highly Scalable Java Applications on Windows Azure
Migrating Spring to Java EE 6
Hands on lab – Whats that smell? – Refactor away that nasy odor

Its completely personal
For each topic I will write down my personal experiences. They are by no means complete. In fact they are completely biased. If you also have visited the JFall conference and you feel different about one of the topics; let me know in the comments below.

Keynote – Java 7 Directors Cut
The keynote consisted of two parts: The first part was about Oracle; how they are not that bad and how they had a rough year in 2010. All I was thinking was : “get on with it“. The second part was about Java 7. It took quite some time before Java 7 was released. (yes Java 7 is released already). In this part it was explained why it took so long and how Oracle played a role in getting it released.

Overthere – Design and implementation of a Java Remote File and Execution framework
This one was actually quite interesting. The talk was about a remote execution framework. Roughly said you could connect to a remote machine via this API, and then execute commands there. Its main goal is to make automated deployment easier. What I missed is they “why” part. Why is this framework built in the first place? What kind of trouble was this framework meant to solve primarily?

Hands on lab – Clojure – A gentle introduction to a brilliant language
Although the start of this session was a bit clumsy; it was really hands on. We did a lot of practice stuff, but also here I did not get any answer to why and when I should use Clojure in the first place. Someone asked if it was used within webapplications. But it seems it is not used that much at all within webapps. (is this so?) The language itself is something to get used to, and 50 minutes was really too short for this. It did spark interest a bit. What I found most intriguing is that using Clojure it forces you to think differently about solving problems. I found that very valuable.

Keynote – Building Highly Scalable Java Applications on Windows Azure
Microsoft presenting at a Java conference, who would have thought that? I think this actually was a great way for Microsoft to show how their attitude towards the Java community has changed. And for good reason. There are tons of Java powered (web) applications and Windows Azure is a platform capable of running them.

The keynote was given at a high speed; and it had (very daring) a live demo. Of course something went wrong, but in the end things did work. Also everybody could get a 30 day free trial of Windows Azure. The presentation concentrated about the effort needed to run Java based applications into Windows Azure. Also, it showed what configuration was needed to actually deploy an application. Aside the Java ‘support’ at Windows Azure, some architect schema’s where shown of well known websites (Flickr, Twitter, etc) and the match with Windows Azure was made. (Like: Yes you can do all these things with Windows Azure).

Migrating Spring to Java EE 6
This show starts with a big disclaimer, in the form of 3 slides and lots of talking about that “this presentation is not a shoot out”. I was wondering why, but the reason became clear after a few slides after that. In short, it was all the way “Spring Bashing” all the time. The use-case was that there was an old Spring application (what is old anyway?). And that you somehow must migrate. You have two options:
A) Migrate to a new Spring version.
B) migrate to Java EE 6.

Since we both know the subject of this presentation we are *not* choosing option A. Then the ‘fun’ part begins. The reasons given to use Java EE is mostly “because it is the standard”. I always get the chills of such comments. What is the standard anyway?

Its a pitty, because the reason that Spring is propriety software is actually valid. However, it just won’t cut it when yelling “its the standard“.

Then it begins, the migration path. And guess what the first step is: Update to the latest spring version. The reason is that Spring has a great backwards compatibility. One would wonder why to migrate further away from Spring from that point. Basically migrating to the latest Spring version would be easier, painless and won’t cost your business that much.

Something different that struck me was an example of how Spring is unable to render objects given by a (JDBCTemplate) DAO as you will be presented with a LazyInitializationException. So the solution in Java EE is that you put an anotation that says the bean scope is “Request”. Apart from the fact that Spring can do this too, it is also in my opinion (in Java EE and in Spring) a bad practice. I think that objects returned by DAO’s should *never* be used in the view. They are not the same thing, so don’t even try it. If you do you’re being lazy.

I think the presentation would be much better if the starting point would be an assignment like “build a web application”. Then you could argue if you would need Spring and why not (since it would be about Java EE 6). Then, you could show everybody how Java EE 6 is capable of doing things Spring can do and how much it has been improved. This would probably be much better than bashing into an existing (older) Spring application and telling everybody to migrate just for the sake of standards. I don’t think any customer would be willing to pay that bill.

Hands on lab – Whats that smell? – Refactor away that nasy odor
I love refactoring, so this one was more of a nice way to close the day. To me it was more like a rehearsal and getting the vocabulary right. I actually found that quite a positive side. Too bad it only lasted 50 minutes, which was way too short. The introduction was also a bit too long so the actual development time was not that long.

In overall
It was big. It was busy. It was very nice to experience. Often I wanted more, more in depth, more time. I see that as a good thing :). On the other hand, I think the NLJug should consider to spread JFall over two days. This way people can choose between several sessions, and the sessions given can be longer and allowed to be more in depth. Especially if the program has some repitition in it, I could choose to visit some workshops on day one, and then watch the presentations at day two which I would have missed at day one.

bookmark_borderPrevent cross-site scripting when using JSON objects using ESAPI and Jackson framework 1.7.x

Recently I have had the opportunity to fix a cross-site-scripting problem.

The problem: a lot of JSON objects are being sent over the wire and the data is not being html escaped. This means that anyone who would put html data IN would get it out and make any user vulnerable for XSS attacks.

In this case, JSON objects are being created by using the MappingJacksonHttpMessageConverter. This is deliverd by the Spring framework. Normally it is instantiated when you use spring-mvc (using the mvc-annotation tag). This allowed us to just return an object and the MappingJacksonHttpMessageConverter would take care of translating it into a JSON object.

In order to influence the creation of the JSON object and make it encode HTML for String values we need to do a few things:

  1. Create a Custom Object Mapper and wire into Spring
  2. Create a JsonSerializer that encodes HTML (using ESAPI)
  3. Register the JsonSerializer in the CustomObjectMapper

Create a Custom Object Mapper and wire into Spring

However, now we want to change the value serialized by the MappingJacksonHttpMessageConverter. So how do we do that? The MappingJacksonHttpMessageConverter uses an ObjectMapper. So in order to get the ObjectMapper map the values to an encoded one we need to create a custom Object mapper.

public class CustomObjectMapper extends org.codehaus.jackson.map.ObjectMapper {
}

At first we leave it empty. We want to make Spring make use of our CustomObjectMapper first. In order to do that you need to write out the mvc-annotation tag, because we need to inject our CustomObjectMapper in the the MappingJacksonHttpMessageConverter. This is a bit difficult to figure out at first, but for your convinience I have proveded the configuration you need.

<bean id="CustomObjectMapper" class="your custom object mapper"/>

<bean id="MappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
	<property name="objectMapper" ref="CustomObjectMapper"/>
</bean>

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
	<property name="order" value="1" />
	<property name="customArgumentResolver" ref="sessionParamResolver"/>
	<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>
			<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
			<bean class="org.springframework.http.converter.StringHttpMessageConverter" />
			<bean class="org.springframework.http.converter.ResourceHttpMessageConverter" />
			<bean class="org.springframework.http.converter.FormHttpMessageConverter" />
			<ref bean="MappingJacksonHttpMessageConverter"/>
		</list>
	</property>
</bean>

As you can see, the AnnotationMethodHandlerAdapter is the bean where everything is getting wired into. The messageConverters property contains a list of converters. The last entry is where the MappingJacksonHttpMessageConverter is referenced. Normally it is defined like the beans above it. But since we want to inject our own CustomObjectMapper it is done this way.

Create a JsonSerializer that encodes HTML (using ESAPI)

Now we know our CustomObjectMapper is used, we can start the part where we want to influence the way the jackson framework serializes our objects to JSON. In order to do that we create our own JsonSerializer. Then, we override the serialize method and make sure the provided jsonGenerator is writing our encoded value.

Code:

public class JsonHtmlXssSerializer extends JsonSerializer {

   public void serialize(String value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
      if (value != null) {
         String encodedValue = encodeHtml(value);
         jsonGenerator.writeString(encodedValue);
      }
   }

}

So this class extends from org.codehaus.jackson.map.JsonSerializer, and implements its own serialize method. The method encodeHtml will use the ESAPI encoding functions to escape HTML.

 

Implementing this is very easy:

   protected String encodeHtml(String html) {
      DefaultEncoder encoder = new DefaultEncoder();
      return encoder.encodeForHTML(html);
   }

The defaultEncoder is from ESAPI allowing us to encode the HTML.

 

Register the JsonSerializer in the CustomObjectMapper

The final step is to register the JsonSerializer within the ObjectMapper used by Spring. Doing that using Jackson 1.7.0 is very easy. Using the provided SimpleModule class we can easily add our own Serializer to the ObjectMapper. We do that by creating our own default constructor, which will register our serializer. Like so:

@Component
public class CustomObjectMapper extends org.codehaus.jackson.map.ObjectMapper {

   public CustomObjectMapper() {
      SimpleModule module = new SimpleModule("HTML XSS Serializer", new Version(1, 0, 0, "FINAL"));
      module.addSerializer(new JsonHtmlXssSerializer());
      this.registerModule(module);
   }
}