Spring MVC 3.2.2 – Include within include.

I’m an intern at Solutions Medias 360. This small Montreal startup is building website for car dealers.

It did an amazing job and have more than a 100 websites running my now. It his looking to expand in the United States very soon and is looking big. If you are either a front end developer working with HTML, CSS, JavaScript or a back end Java developer, they are looking for more staff and feel free to email them.

The most recent websites are lightweight Tomcat applications that works with RESTful APIs to fetch the appropriate data. The websites’ webbapps are working with the Spring MVC 3.2.2 framework. As the name says, it is working with an Model-View-Controller pattern. Here is the graph included in the docs :

Spring MVC diagram

From what you can see here, any incoming requests goes through a controller that fetch the data and then pick the view to render. That is straightforward and it’s not a problem for a simple page. But I have a problem figuring how turns out the whole process when an include tag is rendered inside one of the views. Let me explain.

When you write a JSP page, you can use the <jsp:include page="/path/to/the/page" /> tag. In a Spring MVC application, such a tag sends the request back into the controller loop. For example you open up your application on page /home, then the request X go through the /home controller which does his job and then returns the view to be used, if the view to be rendered has an include tag to page /ad then the request X goes into the controller that handles the /ad path.

My problem shows up here. You see the include tag allows the use of the param tag which is used to pass param into the request. If two parameters has the same name, the default behavior is that the old parameter value is appended to the new value with a comma. For example :


<jsp:include page="/example/fragments/findById">
	<jsp:param name="example-id" value"26" />
	<jsp:param name="view" value"example-id-view" />
<jsp:include>

At this point, the request contains at least two parameters one “view” that has a value of “example-id-view” and one “example-id” which has the value of “26″. If the page has this other include tag :


<jsp:include page="/ad/fragments/example">
	<jsp:param name="view" value"example-ad-view" />
<jsp:include>

Now the request still contains the two parameters. The value of “example-id” has not changed but the “view” parameter value will be “example-ad-view,example-id-view”.

We could have easily updated our controllers so it picks the first part before the comma but the solutions was too generic and couldn’t works in our way of doing things for two reasons :

  • Spring can handle list parameters, so “1,2,3″ could be transformed into a List filled with the values. Appending new data with a comma would confuse the framework
  • An unintended could be happening at anytime in the rendering of complex views

Our solutions was too implements our own “include” tag so we could override how the parameters of this specific are added to the request. Luckily for us, the the Apache (org.apache.taglibs) jstl source code is open so we could have an insight of how such a thing is implemented.


To create a JSTL tag with a Java class, you have to create a class and make it extends the BodyTagSupport. This class does the basic of a JSTL tag. You can redefine the methods you want, in our case doEndTag(). You can see more in the doc.

We wanted our tag to look like this :


<sm360:mytag page="/example/fragments/findById">
	<sm360:param name="example-id" value"26" />
	<sm360:param name="view" value"example-id-view" />
<sm360:mytag>

The tag would need to place these sm360:param inside a Map and place it in a Stack in the request. If the Stack doesn’t exist, you create it, otherwise you push stuff into it. The method would look like this :


    @Override
    public int doEndTag() throws JspException {
        ServletRequest request = pageContext.getRequest();

        addStackedMap(request);

        try {
            pageContext.include(url);
        } catch (ServletException | IOException ex) {
            ex.printStackTrace();
        }

        return EVAL_PAGE;
    }

My sm30:param tag is responsible from adding itself to the parent tag parameter Map. In our case my sm30:mytag tag, implements an interface like ParamParent and the sm30:param must look for their parent and use the preferred interface to add their values to the Map.

The doEndTag() of the sm30:param tag is executed prior to the sm30:mytag tag. That way once the map is added to the Stack inside the request, it is already filled with all the given params.

The last step is to create annotations for our Spring controllers and to define your own HandlerMethodArgumentResolver to find the stack, extract the Map and find the values your controller is looking for.

First Foray

Well it’s been more than a week that I haven’t posted anything here. It is far from my goal of posting daily. I think I gave up on this as I just don’t have anything interesting to share with the internet at this rate. I think I’ll only post when I have something nice to say or something cool to show off.

A couple of weeks ago, I decided I would dig into the Go language to see how it works and to satisfy my curiosity. I landed on a simple blog engine written in Go that works with MongoDb and the Revel web framework. So after finishing my set up and trying some tutorials online I cloned the IronZebra repository and decided I would dive in first to see how it is all connected.

I don’t know anything about MongoDb so this is not the kind of stuff I’ll show you here. I’ll leave it on the side and maybe try to implement an IronZebra version of the engine that works with MySQL. With the first look in the code, I can say that the engine is based on a MVC pattern. All the files that define the engine itself can be found in the app folder.

All the website resources are found in the public directory. At the moment there are CSS and Javascript files and an image folder. I’ve opened a couple of files in the app folder to see how things were working behind the curtains. To be honest I did understand the code that I saw in there. What I didn’t understand is maybe the clue that ties all of theses pieces together.

Maybe this is because I don’t understand how a Revel application is built for the moment, but the way everything worked appeared as magic to me!

I’ll keep digging and I’ll post my findings as I understand how this thing works!

Third conversion

Last week was very busy and I had no time to write about the conversion of my friend’s bike to a fixed gear bicycle. Unfortunately, we couldn’t finish it because we ran into all sorts of problem.

Before I elaborate on what were those problems, I’ll give a little history of the bike. That bike is an old 14-speed Raleigh that my mother got in a garage sale for 10$. When she first bought it, my friend used it as it was. Sonn enough, it became clear that this bike had not received any maintenance in a couple of years and it was destroying itself during usage.

One day, I told my friend that it would be a nice experiment to get rid of that rusty derailleur and that ugly/heavy crankset. The process spanned on multiple weeks. One night my friend’s brother was at my place and we couldn’t find something to do so we disassembled the bike. Everything, from top to the bottom. The bike was naked.

A couple of months later, my friend came by and picked up the bike to bring it back to his place where he painted it. He chose to have it painted white with a red crankset (chainring + chain arm) with black pedals and a black chain.

It brings us to last week where we began to assemble his bike. We ran into several problems and it took us something like two hours to get very few things done. In this time lapse, we managed to install the bottom bracket, the crank set with the pedals on it. We also installed a replacement fork with a new headset. Let me explain the problems and provide you with a few tips:

  1. Get all the parts you need prior to assembly and try a first fit to make sure everything is all right for the bike.
  2. Paint the bike after you’ve tried the parts for the first time.

The first one seems obvious, but it is hard to do when you are new to the game. First, you don’t know everything you will need or you might forget something and you some of the parts may not fit. What happened to my friend and I can also happen to you. You reuse an old parts but it is not fitting with a new part that you bought, but the new part is standard as your old part should be.

The second one is more aesthetic than practical. Nevertheless, it’s very disappointing to ruin your painting trying to install a part that is giving you a hard time. You move the bike around on the stand, you are working with various tool on and around the bike. It becomes very easy to scratch that finish you worked very hard to get. Be careful, and try the parts first before the painting, chances are that the installation will be much easier if you tried it before.

Busy week

Well this week has been one hell of a week. A pleasant week, but a busy one.

I’ll do a one line resume of the past week, day by day.

  • Monday: I rode to my girlfriend’s house for a dinner before she leaves to her apartment in QC city.
  • Tuesday: My friend came to Montreal and we started building his bike, which will be red and white.
  • Wednesday: I rode to St-Lambert, first by the Victoria bridge, which was closed, and finally by the Jacques-Cartier bridge. Once there, my girlfriend picked me up to go to a dinner at my parent’s place.
  • Thursday: I took a bus back to my parent’s place (I left my bike there) and I went on a 25k ride with my buddy and his 2M2B bike.
  • Friday: I rode from my parent’s place to my apartment, to get cleaned, eat and rode to the job right after that.

I don’t know what is up for tonight, but chances are that I’ll jump off a plane on Saturday and I’m headed to the “Fête des bières et saveurs” of Chambly.

It will be a sweet weekend.

iPhone 4 WiFi greyed out

A couple of months ago, my friend went for a ride with his iPhone4 in the waterproof back pocket of his cycling shirt. Turned out the waterproof part of the short was more a marketing story.

Long story short, water went in and destroyed the phone. So he asked one of his friend if he could use her old broken front glass iPhone 4, she said yes and he used it for the past six months or so. Last week I get my hands on to the broken iPhone and starts to wonder why the back panel is popping out so much if it was a power issue.

Next thing you know, I bought a new battery and replace it and the phone is working. The iPhone4 battery is pretty easy to replace and with the good tools is only a matter of minutes. When I first started the phone, everything seemed to be working perfectly, but there was a problem.

The phone couldn’t find any WiFi. After a little investigation, I discovered that the phone has no more WiFi Address and that means the WiFi chip on the main board is supposedly out. Since the chip is soldered on the board, I wouldn’t try to fix it, simply replacing it. But looking over the internet I found that the water could have deteriorated the connection between the chip and the antenna. In this thread at iFixIt, the guy seems to have disassambled the iPhone and cleaning all of the screws made it work again.

This is what I try as soon as I can get my hands back on the device.

IronZebra

A couple of weeks ago, I landed upon a blog post on HN (Hacker News). This post was about a new blog engine built on Go. This is the single project that led to my sudden interest in Go. Today, I decided to take the steps to run the application both on my computer and on Heroku as the original developer did.

First I had no experience with Heroku prior to today’s experiment. Of course the experience wasn’t a straight path from the beginning to the end, but overall it was very satisfying and I learnt a lot. For those who doesn’t know, Heroku is an online cloud environment for your apps. Basically, you sign-up, you register an app, and using git, you push your code on a remote git hosted at Heroku. When you push, everything is done so that the changes you’ve made go live.

Building IronZebra should be a process relatively easy. You checkout the code, get the Go requirements and install the requirements and then you launch your browser. Doing it on Heroku should be even more easy according to the doc! Unfortunately for me, I didn’t know Heroku, I didn’t know most of what IronZebra need and nothing but the least, I’ve had to do it on Windows first.

The very first thing to do is too checkout the project’s code, so far, nothing very complicated. Using git, you do a clone of the IronZebra repo:

git clone https://github.com/hermanschaaf/ironzebra.git

Once you’ve got the code, you’ll need to install all of the dependencies that you don’t have. To store the data, IronZebra uses MongoDB, so you need it installed. On Windows, I’ve downloaded the zip, extracted it, made 2 directories and launched mongod.exe:

mkdir c:\data
mkdir c:\data\db
bin\mongod.exe
...

So you have the code, you have the data system ready. What else? Bazaar, I can’t tell exactly why it is needed, I think it is due to some of the IronZebra’s dependencies, but I’m not sure. Anyway it’s pretty easy to install with a msi on Windows. Now you’ll have to install the Go packages that IronZebra needs: Revel, revMgo (Mongo module for Revel). Go provides the get command to fetch and install the required packages to your workspace.

go get github.com/robfig/revel/revel
go get github.com/hermanschaaf/revmgo

When I ran those commands, I experienced a problem with Revel. Revel uses more than git to fetch the code, it does use Mercurial for some parts of the code. So in order to successfully install Revel, I had to install Mercurial on the side. Be sure to shutdown your command window after the installation to ensure the new %PATH% is taken into consideration. It looks like you can also install all of the project’s dependencies by running this command from the project directory:

go get ./...

Once your done, revel should be installed in your workspace so you can start IronZebra with the following command (if you added %GOPATH%\bin to your %PATH% environment variable) :

revel run github.com/hermanschaaf/ironzebra

Be sure you have Mongo running and then you can access the IronZebra blog engine at http://localhost:9000/

Now that you have it running locally, it would be nice to have it hosted somewhere, let’s say Heroku. First, you need the Heroku Toolbelt for Windows and a Heroku Account. After installation, open the command line and log into your Heroku account, instruction for this are provided on the download page.

Once you are logged in, navigate to your project directory and create your Heroku application:

heroku create

Now that your application is created, you must tell Heroku what to do with a Go application since it doesn’t know by default yet. With the following command, you will set the configuration of your Heroku application according to the IronZebra buildpack :

heroku config:set BUILDPACK_URL=https://github.com/hermanschaaf/heroku-buildpack-go-revel.git

Now Heroku knows what to do with a Go Revel web application, so you can push the code to the Heroku repository and it will be compiled and deployed to your Heroku application :

git push heroku master

If you try to reach the web application, you’ll have an error message. This is because the IronZebra has no Mongo installation to use. Luckily, Heroku provides a free add-on to add a Mongo database to your web application, you can add it from your app settings page on Heroku or with the command line like this:

heroku addons:add mongohq:sandbox

If you have an error, it is because you must add a credit card to your Heroku account for further billing, but don’t worry it won’t cost you a penny.

Enjoy!

 

 

Wheel Truing

A week ago, I went back in my home town because I was leaving for camping and I had some things to pick up. That day, my best friend came at my parents’ place with the fixed gear bicycle we built him a couple of months ago. He was going for a ride and expected me to go with him. I told him I couldn’t at the moment.

He told me that on his way to my home, about 1.5k, he was already having a bad time with the handle bar and his seat that was too high for his short legs (haha). I told him to ride my back as I had to drive to get my girlfriend. He left riding my single speed, but I had one thing in mind: it’s going to be dark in like 30 minutes.

After the week-end, I take the bus back to my parents’ house to ride my bike back to my apartment to notice something very strange about it. When the front wheel spins, it makes a sqwik-sqwik sound that I’ve never heard. After a little inspection, I realize that the sound comes from my the spokes. The wheelset is new and freshly installed as you can recall. The spokes are loose and the sound happens when pressure is applied on the wheel and the spoke rub against each other.

Continue reading

Go Fibonacci

As my first little test with the Go language, I’ll try to calculate the 100th Fibonacci number. For those who don’t know, the Fibonacci sequence is a very popular integer sequence and it is easy to calculate. The first two numbers of the sequence are 0 and 1, and any other number is the sum of the previous two. Learn more here : http://en.wikipedia.org/wiki/Fibonacci_number

The sequence looks like this:

0, 1, 1, 2, 3, 5, 8, 13…

This exercise should be very easy, but is intended to teach me the basics of the Go language.

After a while, I come up with this:

package main

import (
	"fmt"
)

func main() {
	i:= 10;
	fmt.Printf("Iterative Fibonacci : %d. \n", iteraFibonacci(i));
	fmt.Printf("Recursive Fibonacci : %d. \n", recurFibonacci(i));
}

func recurFibonacci(n int) int {
	if n == 0{
		return 0;
	}
	if n == 1 {
		return 1;
	}
	return recurFibonacci(n-1)+recurFibonacci(n-2);
}

func iteraFibonacci(n int) int {
	secondPrevious := 0;
	firstPrevious := 1;
	if n == 0{
		return secondPrevious;
	}
	if n == 1 {
		return firstPrevious;
	}

	fibo := firstPrevious + secondPrevious;
	for i := 2; i < n; i++ {
		secondPrevious = firstPrevious;
		firstPrevious = fibo;
		fibo = firstPrevious + secondPrevious;
	}
	return fibo;

}

This code calculates the tenth Fibonacci number with an iterative technique and a recursive method. There is nothing worth nothing here. This is pretty straightforward. This is the result in the console:

fibonacci
Iterative Fibonacci : 55.
Recursive Fibonacci : 55.

There are a couple of things that came across when I was trying to write this. The first thing that I noted is that you can’t pass an incremental operator in method name. Here is an example of a little recursive call that increment x until it has reached the limit and produced output of go install:

package main

import (
	"fmt"
)

func main() {
	fmt.Println(add(20, 0));
}

func add(limit int, x int) int {

	if x >= limit{
		return x;
	}

	x++;
	return add(limit, x);//works

	//return add(limit, x++);//doesn't work
}
//# david/incremental
//incremental.go:17: syntax error: unexpected ++, expecting )

I’ll dig onto this and try to find why this is something I can’t do or if there’s another of doing this. There is another thing I noticed while doing this experiment. The goal of the exercise was to calculate the 100th Fibonacci number, there was unexpected result when I tried to do so:

fibonacci
Iterative Fibonacci : -980107325.

Two interesing things here. The result is negative, it shows and when going over the maximum integer limit, it wraps around. This wrap-around has very bad effect on my recursive call as it never returns.

The week-end

This week-end I’m going out for camping with my girlfriend.

I’ll be leaving tonight on my bike for my parents’ house and from there I’ll use my brother’s car to pick up my girlfriend. This will be the only camping experience I’ve had in the past five years, minimum.

Once I have reached CEGEP, I have had no real opportunities to go camping. I’ve been kind of busy and I sold my car when I moved in Montréal. I’m lucky enough that my girlfriend has almost always access to her parents Honda or Nissan so we can go pretty much everywhere we want.

This week-end we are going to camp in the Mont-Orford. The site where we will mount our tent is 4k into the mountain and it is not accessible with a car. We will be trying the new three places tent my brother bought for our winter trip in Europe next year.

I wish the weather will be all fine!

Mathieu Dupuis | © Sépaq

Golang

Today, I’m thinking about building a Go application. The problem is: I never used C or C++ or even Go itself.

I’ve looked at some videos and read about the language and it seems like a solid new language to adopt. I’ll start by looking at the IronZebra blog platform. It is a simple blog system that is written in Go. I hope to be able to help out the guy who started the project as well as using it to host my own blog instead of this easy WordPress!

I went to http://tour.golang.org to see what I could do and learn about the basics of the language. I tried a couple of things and finally got the hang of a little function to concatenate strings. This looks like it:

package main

import (
    "fmt";
)

func concat(list ... string) string{

   		if len(list) == 0 {
   			return "";
   		}

   		if len(list) == 1 {
   			return list[0];
   		}

   		str := "";
   		for _, s := range list {
   			str += s;
   		}

   		return str;
}

func main() {
    fmt.Println(concat("this", "should", "be", "sticked", "together"));
}

I’ll explain in my next post how this all works, but it’s not that hard if you have a little developer background.