Lime MVC : simple and extensible

May 29th, 2012

Being a complete fan of google Guice, I look around to find some equivalent of Spring MVC that I could plug with Guice injection instead of Spring’s.

 

After a few month using various features of Lime-MVC, I can say this is the kind of tool I like : simple, easy to use, productive, and at the same time quite configurable and extensible. Several times I thought “well, maybe this is where it’s going to be a bit more difficult”, and very quickly I found the perfect API in Lime to do exactly what I wanted in an elegant way.

 

Lime MVC is simple

The initial idea of Lime MVC is to provide a lightweight tool similar to Spring MVC, but with Guice injection.

Your controllers look like :

 

@Controller
public class BookStoreController {

@Path(”/books”) @Model(”books”) @View(”view.jsp”)

public List getBooks(

@RequestParameter(”author”) String author) {

//fill a list of books

return booksList;

}

} 

 

and your webapp use a Lime Servlet initialized with :

 

public class MVCConf extends GuiceServletContextListener {

@Override

protected Injector getInjector() {

Injector injector = Guice.createInjector(

new MvcModule() {

@Override

protected void configureControllers() {

control(”/bookstorecontroller/*”)

.withController(BookStoreController.class);

}

});

return injector;

}

}  

It provides sensible basic features out of the box

Of course, your controllers methods can take arguments corresponding to request params, to params extracted from rest-like URLs, etc, based on java annotations. You can define regexp to specify which parts of the URL might be used as parameters.

It also has some default converters for Dates, numeric types, etc.

 

It gives you low level access and can be extended when required

When you need to do so, it is dead easy to work directly with  HttpServletRequest/HttpServletResponse objects.

 

Also, Lime MVC is quite modular and its design is easy to understand. It provides APIs where you can plug your own way of resolving views, converting parameters, handling exceptions, etc.

 

To illustrate this, Lime MVC works with JSP views, and you can easily switch to other template engines. Lime MVC has out of the box extensions for JSilver, Velocity and Freemarker, but it is really easy to add your own extension to create other view types, for example to return JSON object using google’s GSON or any other JSON converter you like.

The framework does not force you to use specific implementations, yet makes it easy to plug your own preferred tools in it.

 

All in all, I found Lime MVC to be non-intrusive, lightweight and easy to customize.

JDK8 Lambdas in Action

April 21st, 2012

Les lambdas sont une nouvelle fonctionnalité très attendue du JDK 8 (version finale prévue pour septembre 2013).

Cet article reprend une présentation faite à Devoxx Paris 2012 dans laquelle j’ai fait une démonstration de code utilisant les lambdas dans la preview du JDK8.

Ces exemples mettent aussi en évidence certains choix importants dans la facon dont les lambdas sont implémentés dans le JDK 8.

Tout d’abord les binaires du JDK 8 Preview sont disponibles (avec des release régulières suivant l’avancement d’implémentation) ici : http://openjdk.java.net/projects/lambda.

Une fois le JDK installé, on peut écrire un premier exemple affichant tous les éléments d’une liste de String :

public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add(”Guillaume”);
names.add(”Eric”);
names.add(”David”);

names.forEach(s->System.out.println(s));

}}

Les collections du JDK 8 proposent une méthode forEach(Block) qui peut prendre une expression Lambda en paramètre.

Cette expression lambda s->System.out.println(s) pourrait aussi s’écrire (String s)->{ System.out.println(s); }.

Une expression lambda plus complexe avec plusieurs paramètres en entrée, executant plusieurs instructions  et retournant une valeur s’écrira

(String s, Object o)->{ System.out.println(s); return s + o ;}

L’inférence de type permet d’omettre le type des paramètres dans les cas ou ce type peut être déduit du contexte :

(s)->{ System.out.println(s); }

Dans le cas ou l’on a une seule instruction dans le block de l’expression, on peut ommettre les accolades:

(s)->System.out.println(s)

Si l’expression a un seul paramètre en entrée, on peut supprimer les parenthèses :

s->System.out.println(s)

Et enfin on peut aussi utiliser une syntaxe pour faire directement un alias vers une méthode existante :

System.out::println

Cette syntaxe permet de créer des alias vers des méthodes statiques, des méthodes d’instance ou des constructeurs

De la même facon qu’on a utilisé la méthode forEach, on peut aussi utiliser la méthode filter(Predicate).

Les expressions lambdas passées en paramètre de forEach ou filter peuvent être extraite sous forme de variable locales :

Predicate<String> longName= s->s.length()>4;

Block<String> display = s->System.out.println(s);

names.filter(longName).forEach(display);

Les interfaces Predicates et Block sont des “Functional Interfaces” : interfaces comportant une seule méthode abstraite.

On peut affecter une expression lambda à toute Functional Interface dont l’unique méthode a une signature qui correspond à celle de l’expression lambda.

Ceci permet d’utiliser des expressions lambdas avec de nombreuses librairies existantes, sans aucune modification de ces librairies : on peut par exemple utiliser une expression lambda dans tout API utilisant un Runnable ou Callable, ou un ActionListener.

Si l’on regarde plus en détail le contenu des interfaces Predicate ou Block, on voit dans l’interface Predicate qu’en plus de la méthode

boolean eval(T t);

On a d’autres méthodes non abstraites : ces méthodes on une implémentation précédée du mot clef default!

Predicate<T> and(Predicate<? super T> p) default {

return Predicates.and(this, p);

}

Le jDK 8 introduit cette notion appelée Virtual Extension Method, qui permet d’ajouter dans une interface des méthodes non abstraites avec une implémentation par defaut.

Les classes qui implémentent l’interface bénéficient automatiquement de ces définition, et peuvent éventuellement redéfinir cette implémentation.

Cette notion de VEM est introduite en partie à cause de l’introduction des lambdas.

En effet, pour bénéficier complétemet des lambdas il est nécessaire de faire évoluer les librairies de collections afin d’y ajouter des méthodes très attendues : filter(), map(), reduce(), etc.

Si on ajoute ces méthodes aux interfaces Collection ou List, cela casse toute implémentation de ces interface qui aurait été écrite avant le JDK8, ce qui n’est pas envisageable avec la base de code java existante aujourd’hui.

Il n’est pas non plus envisageable de créer de nouvelles interfaces List2, Collection2, uniquement pour éviter de casser la compatibilité avec les collections existantes.

les VEMs permettent donc de faire évoluer les librairies existantes tout en assurant la compatibilité avec le code existant.

On peut bien sur utiliser des lambdas avec ses propres interfaces (pourvu qu’elles aient une seule méthode abstraite), ce qui va permettre de créer des librairies acceptant des expressions lambdas comme paramètres.

L’utilisation des VEM permet de plus d’améliorer facilment les APIs vues par le client et de créer des API “fluent” avec du chainage de méthodes, etc.

Enfin, d’un point de vue outilage, il reste encore aujourd’hui beaucoup de progrès à faire. Les IDEs ne proposent pas encore de support permettant de coder confortablement avec ces nouveautés du JDK8 (ni les expressions lambdas ni les VEMs).

Maven par contre se contente de déléguer la compilation et l’exécution aux binaires javac et java, et l’utilisation du JDK8 avec maven est très transparente.

The basics of reliable Delivery : Mary Poppendieck session at Agile 2009

August 28th, 2009

At last I can take some time to blog a little about the Agile 2009 conference.
I started this week with a session by Mary Poppendieck : “Workflow is othrogonal to schedule - the basics of reliable delivery“. 
A lot of this session was derived from the example of building skycrapers in the first half of the 19th century. In this context, one of the bigest constraint was to be fully finishedand do the tower opening by May 1st, because rents started on a yearly basis on may 1st. So pretty tough schedule constraint, and usually these towers could be build within 18 months, quite reliably.
The main difficulty was to manage logistics and make sure all the materials were available onsite at the right time and the right place, with the people to use them right away.Building skyscrapers
The different lines on this diagram show timings for definition of required materials, materials ordering, detailed design,and eventually materials delivery and the actual building, all done by chunks of 2 storeys. One can notice that the detailed design is performed throughout the construction, right before starting to build each floor.
One thing Mary insisted on is that the schedule is not derived from the design of he building, it is rather the other way around : the design is defined to meet the constraints, especially being able to deliver the building within less than 18 months. What is important to meet this is the workflow (gloal design, ordering, detailed design, material delivery, construction) and the pace it gives to the project.
Major points that were mentionned were :

  1. Experience cannot be replaced. People will be able to decide if the project is viable, and how things should be done in which order if they have already experienced 5 or 10 different building projects.
  2. The overall complexity (of the building) can be reduced through wise decoupling in 2 ways : reduce architecture dependencies, and reduce schedule dependencies.
  3. Team work should be based on respect and trust. All major deciders should be fully involved in the project and feel responsible for its success or failure as a team. This is opposed to contract-based thinking where one part is trying to impose the other part to do more and more stuff regardless of the viability or risks.

Agile 2009 conference

August 27th, 2009

We’ve now moved to the second half of the Agile 2009 conference. As I was told, this is quite a huge conference, lots of people, lots of different sessions, some space for additional unscheduled sessions, … Just too many things for one mind. Two ideas that keep coming again and again are :

  1. Experience cannot be replaced by anything else.
  2. Regarding code writing : Expressiveness has been mentionned several times as one of the top-3 keys to quality code.

Monday was a big day four Eric Lefevre and myself, as we were animating a coding dojo session on the theme “adding functionality to lecgacy code”.
We had planned to ask for a dozen volunteers to participate and take turns coding on our Monopoly example.It turned out we were about ten people in the room, so we didn’t need to ask for volunteers, we had the perfect size crowd for the exercise.We used Test Driven Development (of course!) during the session. This is also a good mean for measuring what we can archieve during one hour of coding, and to have a garantee that we end up with working software.
The session went with quite passionnate discusions about what we should do next, the scope of tests, etc. Eventually, one of the major take away from this session was that pair programming is not easy. This is probably even more true in this context were people didn’t know each other before the session, they didn’t know each other way of thinking, coding habits, etc. 
We did actually run the same exercise with people doing weekly dojo session in Paris and managed to get more functionality implemented, probably because people were a little bit used to coding with each other.programing with the stars 
Eric also managed to perform at the “Programing with the stars” contest during lunchtime,  where there were fantastic teams, jury and a great presenter, who managed to make this event look like a TV show with suspense, loud music, applause and all. 

All in all, a pretty good day to begin this conference. 
I’ll add more about sessions I attended in other articles.

XPDays Paris 2009

May 29th, 2009

Highlight of this week : XPDay Paris on monday/tuesday. I liked the agileFairyTales games with snow white and the 7 dwarfs (see http://www.agilefairytales.com/mirror.html), Arnaud Bailly’s presentation on how a test solution typically progresses to become over-complex (great presentation especially in this 30 mins not-so-easy format, dense and still easy to follow).

Unfortunately I had to leave the presentation by Regis Medina and Antoine Contal regarding XP + Lean before the end (and I missed Regis’ presentation about Théorie des centres). But take a look there… interesting stuff.

Eric Lefevre and I presented a discussion session “Scrum est-il dangereux?” (not so good translation of “Is Scrum Evil?”). Notes from the session are available on pictures here.

Also, this was the opportunity to meet people (the usual suspects but also some good surprises, people I hadn’t seen in years). All this in the really cool site La porte Jaune, very nice.

Upcoming conferences

May 22nd, 2009

I’ll be at XPDay Paris conference next week,where I’ll present with Eric Lefèvre-Ardant “Scrum est-il dangereux?” (Is Scrum Evil?). This is a re-edition of a session that took place at CITCON Amsterdam last year, facilitated by Jeffrey Frederic.agile2009_webbadges.png

I’ll also be at Agile 2009 in Chicago this summer,   presenting a coding dojo “working on legacy code” with Eric again, and at CITCON in september. This year CITCON takes place in Paris, at ISEP (where I did 5 years of studies).CITCON

And I’m sure I’ll be at ValtechDays as well, program not defined yet for the 2009 edition…


Redmine 0.8.0 RC is out!

December 8th, 2008

More details and download available here

Amongst other things, it includes cross project search, calendar and gant with issue filtering, editable watchers list, and many more…

Agile Edge à Londres mardi 28 octobre 2008

November 2nd, 2008

J’étais mardi dernier à la conférence Agile Edge organisée par Valtech Londres, au sein de Lord’s Cricket Ground.
Après une introduction où Phill Hall, grand amateur de cricket, s’est dit “proud to perform professionnnaly at Lord’s Ground”, David Anderson a ouvert la journée avec une keynote faisant ressortir principalement Lean comme une suite logique des méthodes agiles, ainsi que Real Options.
L’agilité fait aujourd’hui est passée aujourd’hui dans le domaine “grand public”, Lean insiste plus sur l’aspect “flux tendu” sur la chaine de développement et la limitation des gaspillages, tandis que Real Options met l’accent sur le fait de garder la possibilité de décider le plus tard possible, se gardant ainsi un maximum d’options ouvertes au cours du projet.
Les conférences se sont ensuite déroulées dans deux tracs différents, “agile for the team” portant principalement sur les pratiques agiles au jour le jour, et “agile for the organisation, plus orientée sur la stratégie.
J’ai assisté notemment dans la partie “agile for the team” à la présentation “Agile Requirements” d’Akbar Zamir, (avec qui j’avais travaillé en 2001 sur un projet où nous mettions déjà en œuvre un certain nombre de principes agiles).  Dans la section “Agile for the organisation”, j’ai été impressionné par la présentation d’Al Goerner sur l’utilisation de métriques pour le pilotage de projet. L’utilisation d’un burn-down chart enrichi de différentes façons permet de détecter au plus tôt un certain nombre de risques de dérapages au plus tôt dans la vie du projet.
L’assistance a été mise à contribution en fin d’après midi pour partager différentes expériences agiles, au cours de la présentation de Jeff Mc Kena, de Serena. (Jeff Mc Kena était présent une semaine plus tôt pour présenter la Key note des Valtech Days à Paris).

Phill Hall présente Jeff Mc Kena au début de la session

Ci-dessus : Phill Hall présente Jeff Mc Kena au début de la session “Agile War Stories”.

Deux mots clefs qui ressortent de cette journée : Lean et Trust (l’agilité a besoin de confiance entre les différents acteurs d’un projets, et aide à renforcer cette confiance)

Mylin Generic Web Connector used for Redmine

May 5th, 2008

Mylin (Previously an eclipse plugin called Mylar) is a part of eclipse that allows developers to define and use tasks inside eclipse, and link those tasks to code, code changes, etc.
Mylin tasks can be localy defined in Eclispe, but the main interest of Mylin is that it can be integrated with issue-tracking systems. You can then get your lists of bugs from your issue tracking tool in an eclipse view, and change your ticket statuses from eclipse.

Several connector already exist (Jira, bugzilla, Trac, Mantis), but I was looking for an integration with Redmine. Fortunately, Mylin also provides a Generic Web Repository Connector, allowing the integration with any web issue tracking tool (given some constraints on how issue pages can be accessed).
Basically, you customize it for the tool of your choice by specifying URLs displaying your issue query results, issue details, and also a pattern (defined as a regular expression) that Mylin will use to parse the result web page and deduce the issues to display in eclipse. The connector also provides customization options to manage login into the issue trakcing system.

After maybe half an hour to figure out the right URL patterns and regular expression (I definitely need some practice with regexp…), I had my Redmine tasks in eclipse and I could display several groups of tasks (for V1.2 and V2.0) :

From there, I can right-click on a task to open the details in eclipse and modify a task :

The good news is that this can be used with any issue tracking system that has a simple enough web interface to allow Mylin to query urls and parse the resulting page to get ticket descriptions.

Redmine rocks!

May 4th, 2008

Last summer I took a look at Redmine, an open source collaborative tool written in Ruby on Rails (cf article on Valtech Blog). I’m currently starting to use Redmine for one project I’m involved in, and I’m promoting it on several other projects at my client.

I was previously a great fan of Trac, and Redmine does now provide real advantages. It provides most of Trac features (issue tracking, wiki, roadmap, code repository browser and links between these modules), plus additional modules : News, discussion forum, basic time tracking associated with issue tracking, generation of changelog, calendar view.

In addition to completely new modules, Redmine also provides a very slick interface. For example tickets can be updated in batch mode. This is really useful for instance when allocating tickets to milestones of the project (in agile jargon, you would use this for your sprint backlog definition). Code changes related to issues appear on the issue page, as well as related issues. Moreover, you can specify keywords like “fixes” or “closes” so that tickets get closed automatically when you check-in code with a comment including “fixes #123″.

Redmine is inherently multi-project (projects and one level of sub projects) and provides all its administration configuration in a web interface.
The administration interface includes custom field definition, custom workflow, permissions, integration with 6 code repositories, LDAP, etc. It provides quite advanced features : for example, when defining a custom field, you can just tick a checkbox to make this field searchable, mandatory, or make it appear in query criteria. You can even define a regular expression that the field must conform to.
Redmine modules (wiki, ticket tracking, news, forum, etc.) can be activated or de-activated per project. Each project can also choose whether to use custom fields or specific issue trackers with custom workflow.
Also, Redmine can be installed in minutes, it just requires Ruby on rails and a database (mySQL by default).

Redmine architecture allows the definition of plugins. A generic Continuous Integration plugin to obtain build results from RSS feeds already exist, as well as a plugin to display a google calendar as one tab in Redmine projects.
The product is already integrated with 6 version management systems : SVN, CVS (Not available in Trac), Mercurial, Bazaar, Darcs, Git.

And the cherry on top of the cake : even if there is no Mylin integration available specifically for Redmine, you can use Mylin’s Generic Web Repository Connector to get your Redmine tickets in Eclipse.

In terms of references, Redmine is used for building the next version of Typo3 (a Major open source CMS).