Fancy UI

All About Crazy IT Stuff

Secure REST services using Spring Security

with 5 comments

Overview :

Recently, I was working on a project which uses a REST services layer to communicate with the client application (GWT application). So I have spent a lot of to time to figure out how to secure the REST services with Spring Security. This article describe the solution I found, and I have implemented. I hope that this solution will be helpful to someone and will save a much valuable time.

The solution :

In a normal web application, whenever a secured resource is accessed Spring Security check the security context for the current user and will decide either to forward him to login page (if the user is not authenticated), or to forward him to the resource not authorised page (if he doesn’t have the required permissions).

In our scenario this is different, because we don’t have pages to forward to, we need to adapt and override Spring Security to communicate using HTTP protocols status only, below I liste the things to do to make Spring Security works best :

  • The authentication is going to be managed by the normal form login, the only difference is that the response will be on JSON along with an HTTP status which can either code 200 (if the autentication passed) or code 401 (if the authentication failed) ;
  • Override the AuthenticationFailureHandler to return the code 401 UNAUTHORIZED ;
  • Override the AuthenticationSuccessHandler to return the code 20 OK, the body of the HTTP response contain the JSON data of the current authenticated user ;
  • Override the AuthenticationEntryPoint to always return the code 401 UNAUTHORIZED. This will override the default behavior of Spring Security which is forwarding the user to the login page if he don’t meet the security requirements, because on REST we don’t have any login page ;
  • Override the LogoutSuccessHandler to return the code 20 OK ;

Like a normal web application secured by Spring Security, before accessing a protected service, it is mandatory to first authenticate by submitting the password and username to the Login URL.

Note: The following solution requires Spring Security in version minimum 3.2.

Overriding the AuthenticationEntryPoint :

Class extends, and implements only one method, which sends response error (with 401 status code) in cause of unauthorized attempt.

public class HttpAuthenticationEntryPoint implements AuthenticationEntryPoint {
    public void commence(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException authException) throws IOException {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());

Overriding the AuthenticationSuccessHandler :

The AuthenticationSuccessHandler is responsible of what to do after a successful authentication, by default it will redirect to an URL, but in our case we want it to send an HTTP response with data.

public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(AuthSuccessHandler.class);

    private final ObjectMapper mapper;

    AuthSuccessHandler(MappingJackson2HttpMessageConverter messageConverter) {
        this.mapper = messageConverter.getObjectMapper();

    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws IOException, ServletException {

        NuvolaUserDetails userDetails = (NuvolaUserDetails) authentication.getPrincipal();
        User user = userDetails.getUser();
        userDetails.setUser(user); + " got is connected ");

        PrintWriter writer = response.getWriter();
        mapper.writeValue(writer, user);

Overriding the AuthenticationFailureHandler :

The AuthenticationFaillureHandler is responsible of what to after a failed authentication, by default it will redirect to the login page URL, but in our case we just want it to send an HTTP response with the 401 UNAUTHORIZED code.

public class AuthFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException exception) throws IOException, ServletException {

        PrintWriter writer = response.getWriter();

Overriding the LogoutSuccessHandler :

The LogoutSuccessHandler decide what to do if the user logged out successfully, by default it will redirect to the login page URL, because we don’t have that I did override it to return an HTTP response with the 20 OK code.

public class HttpLogoutSuccessHandler implements LogoutSuccessHandler {
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException {

Spring security configuration :

This is the final step, to put all what we did together, I prefer using the new way to configure Spring Security which is with Java no XML, but you can easily adapt this configuration to XML.

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    private static final String LOGIN_PATH = ApiPaths.ROOT + ApiPaths.User.ROOT + ApiPaths.User.LOGIN;

    private NuvolaUserDetailsService userDetailsService;
    private HttpAuthenticationEntryPoint authenticationEntryPoint;
    private AuthSuccessHandler authSuccessHandler;
    private AuthFailureHandler authFailureHandler;
    private HttpLogoutSuccessHandler logoutSuccessHandler;

    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();

    public UserDetailsService userDetailsServiceBean() throws Exception {
        return super.userDetailsServiceBean();

    public AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setPasswordEncoder(new ShaPasswordEncoder());

        return authenticationProvider;

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();

    protected void configure(HttpSecurity http) throws Exception {
                .logoutRequestMatcher(new AntPathRequestMatcher(LOGIN_PATH, "DELETE"))


This was a sneak peak at the overall configuration, I attached in this article a Github repository containing a sample project

I hope this will help some of you developers struggling to figure out a solution, please feel free to ask any questions, or post any enhancements that can make this solution better.


Written by imrabti

August 29, 2014 at 8:24 am

Posted in GWT, REST, Spring

Tagged with , , ,

JSR 303 loading messages from an I18N property file

leave a comment »

Overview :

This article will illustrate how to adapt the JSR 303 validation API to load messages from an I18n property file, and this by conserving all benefits of internationalisation and support for multiple languages.

To achieve this we are going to implement a custom MessageInterpolator which will be based upon Spring API for managing I18N messages.

Dependencies :

Below the required maven dependencies to make this work, the Javax validation and Hibernate validation are not listed in here :


Configuration of MessageSource :

The first step is the configuration of the MessageSource bean which is responsible of scanning and indexing the content of properties files.

    <bean id="messageSource" class="">
        <property name="defaultEncoding" value="UTF-8"/>
        <property name="basenames">

MyMessages and ErrorMessages are the properties files we wanted to scan, the name of the files support the conventions for multiple language.

For example if our application must support english and french then we should have : and

Custom MessageInterpolator :

In this custom MessageInterpolator we redefine the way JSR 303 resolve messages to display, we provide a custom implementation which uses Spring MessagesSource and the MessageBuild to search and prepare for the message to be displayed.

import java.util.Locale;

import javax.validation.MessageInterpolator;

import org.springframework.binding.message.MessageBuilder;
import org.springframework.context.MessageSource;

public class SpringMessageInterpolator implements MessageInterpolator {
    private MessageSource messageSource, 

    public String interpolate(String messageTemplate, Context context) {
        String[] params = (String[]) context.getConstraintDescriptor().getAttributes().get("params");

        MessageBuilder builder = new MessageBuilder().code(messageTemplate);
        if (params != null) {
            for (String param : params) {
                builder = builder.arg(param);

        return, Locale.FRANCE).getText();

    public String interpolate(String messageTemplate, Context context, Locale locale) {
        String[] params = (String[]) context.getConstraintDescriptor().getAttributes().get("params");

        MessageBuilder builder = new MessageBuilder().code(messageTemplate);
        if (params != null) {
            builder = builder.args(params);

        return, local).getText();

Usage on a custom JSR 303 :

Let say that we create a new JSR 303 validation annotation, which validate will check if a field is not blank. To use the custom Spring message interpolator, we need to declare a message on one of the properties files loaded by the Spring Message source, lets declare that on the :

{com.myproject.validation.NotBlank}    Mandatory field

Best practice is to name the key of the message like the complete classe name of our validation annotation, you are free to choose any key name you want but it must be between the brackets {} to work.

Our custom annotation will look like below :

@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Constraint(validatedBy = NotBlankValidator.class)
public @interface NotBlank {
    String message() default "{com.myproject.validation.NotBlank";

    Class<?>[] groups() default {};

    String[] params() default {};

    Class<? extends Payload>[] payload() default {};

Please verify that the default value of the message attribute is the same as the one you put on the property file.

Thats it, now you can use the annotation normally like you do, and if you don’t provide a hardcoded message it will get loaded from the property file if is declared there.

Written by imrabti

July 27, 2014 at 10:32 am

Writing Custom CellRenderer using the Declarative new GWT 2.5 UiRenderer

with 18 comments

Before GWT 2.5, writing a custom CellRenderer to present data in a certain manner was very complicated and very difficult to achieve.

All the custom UI code had to be written inside a Java class that inherits from the AbstractCell class, using HTML strings concatenation, which is a pretty clunky solution. If you want something cleaner you could choose to use the @Template class, but still it is very difficult to write and to maintain.

I always said, if only Google would add in GWT the ability to define the UI of a custom CellRenderer using XML, just like they did with the introduction of UiBinder, and to have the possibility to bind the UI components using the @UiField and to hook event processing using @UiHandler ==> Hooraaahhhh !!!! This dream came true with GWT 2.5, and it is called the UiRenderer.

In this article I’ll show some snippets of codes of a real use case example to explore most of the features brought to us with UiRender. First let’s describe the custom CellRenderer we will implement.


As you can see in the schema, the cell item renderer is composed of a picture, a text and two buttons, one to remove the item and the other one to open a popup for editing data.

To create a custom CellRenderer using UiRenderer we have to create two files, one containing the XML declarative UI code (think of the MyView.ui.xml files), and the other one holds the associated Java view (think of the The two files must have the same name.

Declarative UI code of MyCellRenderer.ui.xml :

One thing to remember, the difference between the UiRenderer and UiBinder is that in UiRenderer you can only use HTML tags. All GWT custom components will not work in here. I hope Google will add this feature in a future release.

<ui:UiBinder xmlns:ui=''>
    <ui:with field='name' type='java.lang.String'/>
    <ui:with field='image' type='java.lang.String'/>

        .imageWrapper {
            float: left;
            margin-right: 10px;
        .imageWrapper img {
            width: 64px;
            height: 64px;
        .infoWrapper {
            float: left;
        .infoWrapper div span {
            display: inline-block;
            marin-right: 5px;
            text-decoration: underline;
            cursor: pointer;

        <div class="imageWrapper">
            <img alt="{name}" src="{image}" />

        <div class="infoWrapper">
            <h3><ui:text from="{name}"/></h3>
                <span ui:field="remove">Remove</span>
                <span ui:field="update">Update</span>

        <div style="clear: both;"/>

Custom CellRenderer Java file :

This file will manage the UI logic, like for example passing the data to be displayed, formatting data (Date conversion, number conversion…), handling events…

In this example, we have two events to handle (the click on Remove and Update buttons). Thanks to UiRenderer, we can use ui:fields and the @UiHandler annotation. There is some other boilerplate code to add, like the onBrowse event handler to make it work (everything is well described in the snippet of code below).

public class MyCellRenderer extends AbstractCell {
    // This can be compared to UiBinder --> here where all magic is done
    public interface Renderer extends UiRenderer {
        void render(SafeHtmlBuilder sb, String name, String image);

        void onBrowserEvent(MyCellRenderer o, NativeEvent e, Element p, Person n);

    private final Renderer uiRenderer;

    public MyCellRenderer(final Renderer uiRenderer) {
        this.uiRenderer = uiRenderer;

    public void onBrowserEvent(Context context, Element parent, Person value, 
            NativeEvent event, ValueUpdater<Person> valueUpdater) {
        uiRenderer.onBrowserEvent(this, event, parent, value);

    public void render(Context context, Person value, SafeHtmlBuilder safeHtmlBuilder) {
        // All data extraction, transformation should be done in here
        String name = value.getFirstName() + value.getLastName();
        String image = value.getImage();

        // We directly the uiRenderer and we pass the HtmlBuilder
        uiRenderer.render(safeHtmlBuilder, name, image);

    void onRemovePersonClicked(ClickEvent event, Element parent, Person value) {
        Window.alert("Do you want to remove : " + value.getFirstName());

    void onUpdatePersonClicked(ClickEvent event, Element parent, Person value) {
        //Maybe use the ActionCell.Delegate to process the action elsewhere...
        Window.alert("Do you want to update : " + value.getFirstName());

Using the new Renderer in a CellList :

Now that we are done writing our custom, sophisticated and good looking CellRenderer (:D), we can use it the same way we used the old legacy Renderer. I added below a small snippet to show you how in case you forget:

public class MyView extends Composite {
    public interface Binder extends UiBinder<Widget, WebCartView> {

    @UiField(provided = true)
    CellList personList;

    public MyView(final Binder uiBinder, final MyCellRenderer myCellRenderer) {
        personList = new CellList(myCellRenderer); // Same way as using old Renderers
        ....  // Continue what you always do...

That’s it for this article, I hope this was useful and will help you build more awesome sophisticated apps without having to write a lot of complicated code. PS: this new UiRenderer can be used with any Cell based GWT widget.

For more details check the following links : (GWT 2.5 UiRenderer official docs ), (Cell widget docs).

Written by imrabti

November 26, 2012 at 8:39 pm

Posted in GWT

Tagged with , ,

Cross site requests with GWT, RestyGWT and HTML5 CORS

with 4 comments

I’m working on a GWT project that can be added to any web site to load a banner and to do that, I had to make some requests to a REST service deployed on another server.

We all know that this is impossible because Cross Site requests are forbidden, but with the introduction of CORS in HTML5 this can be done (check for more details), on this article I’m going to show how to make CORS requests to a REST services with RestyGWT and GWTP for testing I used Jersey as REST service provider (this can be any other framework : RestEasy, Rails…).

First of all, in all modern browsers today, when you execute a Cross Site request they automatically send a CORS request (or a Preflight request with the value OPTION in the header), your backend service should respond to this with an empty response containing some required headers to allow the CORS (we can compare this step to the Handshake in TCP), after receiving the correct response the browser will execute the actual request you want to send.

Enabling CORS on the back end :

To enable CORS on my JAX-RS REST service, I added a preflight response for each REST method, the response contain the required headers to authorize the request, I also added the same headers to the final response.


public class MyRestService {
  private HttpServletResponse response;

  private final MyDao myDao;

  @Path("/{id}") //The response for the preflight request made implicitly by the bowser
  public Response getByIdPreflight() {
    return Response.ok()
      .header("Access-Control-Allow-Origin", "*")
      .header("Access-Control-Allow-Methods", "POST, GET, UPDATE, OPTIONS")
      .header("Access-Control-Allow-Headers", "x-http-method-override").build();

  public MyData getById(@PathParam("id") long id) {
    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Allow-Methods", "POST, GET, UPDATE, OPTIONS");
    response.addHeader("Access-Control-Allow-Headers", "x-http-method-override");

    MyData data = myDao.get(id);
    return data;

You can also use a third party library to enable CORS on your java back end like for example :

Doing a CORS request from RestyGWT :

RestyGWT is a rich REST client API for GWT, it is based upon the JAX-RS annotation, for the given service in the back end, we have to write an interface containing all method we want to call on server (if you are not familiar with RestyGWT please visit :

public interface MyDataService extends RestService {
  public void getById(@PathParam("id") long id, MethodCallback<MyData> callback);

To bind and configure this interface service to the actual service on the back end, I register it as a Singleton bean on my GIN module.

public class ClientModule extends AbstractPresenterModule {
  protected void configure() {
    install(new DefaultModule(ClientPlaceManager.class));

  public MyDataService provideMyDataService(@Named("rest") String url) {
    MyDataService myDataService = GWT.create(MyDataService.class);
    Resource resource = new Resource(url);
    ((RestServiceProxy) myDataService).setResource(resource);
    return myDataService;

And finally, to use this service you just need to inject it in your presenter and use it normally. That’s it for this article 😀

Written by imrabti

August 8, 2012 at 7:33 am

Posted in GWT

Tagged with , , , ,

Spring / GWT Software Architecture for scalable applications – Part 2

with 7 comments

During this article you will learn how to build efficiently and quickly the backend (based upon the solution described on part one : that is going to be used later by any kind of clients (GWT, Android,…). My aim is to guide step by step on building an example application and gives you all the best practices on each step to achieve high quality code.

Specifically, you will do the following in this article:

  • Methodology based on UI prototyping to define the service layer of the application (how many services, what functionality’s they must offer…)
  • Setting up the infrastructure of the project : libraries, configuration files, logger…
  • Setting up the persistence layer : business entities, persistence related configuration files…
  • Setting up the DAO layer using Spring Data API : bind queries to DAO methods, conventional DAO method naming.
  • Setting up the service layer : transaction configuration, security configuration.
  • Setting up Test classes using JUnit and Spring Test.

Extracting services

From my experience the best way to determine the required services is by establishing first all the UI prototype for your web application, the next step is to analyze all prototypes carefully and try to form groups of coherent and consistent features which are our services.

Below UI prototype of the application we are going to build during this prototype :

From this annotated UI prototype you can clearly see that we have tow services, one for managing Transactions and the other for Accounts. Each services contain the following methods :

  • Transaction service contain a reference to TransactionRepo and AccountRepoand have the following methods :
    • add(Transaction new) : for adding a new transaction, it should also update the account balance.
    • loadTransactionByAccountId(accountId, period, type) : load transactions of the selected account and selected period (this month, this quarter, this year…) and type filter (income, expense, all).
    • loadTotalAmountByAccountId(accountId, period, type) : calculate the total amount of transactions of the selected account and selected period and type filter.
  • Account service contain a reference to AccountRepo and TransactionRepo have the following methods :
    • loadAll() : load all accounts.
    • add(Account new) : for adding a new account, if the initial balance is specified should create a new Income transaction attached to this account.

Back end infrastructure

In order to speed up the project setup (libraries, log4j setting, applicationContext…) I choose to use Spring Roo which will prepare all required infrastructure code for a spring based project. On this project I’m going to use the following  libraries and tools :

  • MongoDB : I choose to use a NoSQL database instead of the old relational one (Just a personal preference). For more information about how to setup the latest version of MongoDB on Ubuntu  see
  • Spring ROO 1.2 the first version that support MongoDB code generation and service oriented architecture see for more information.
  • I’ll be using SpringSource Tool Suite 2.8.1 as IDE which is the best environment to build Spring powered applications, see

To prepare our project, in STS create a new ROO project, give it a name and the topLevelPackage, then ROO generate automatically all required files (Log4j, applicationsContext, pom.xml,…) for a Spring project, normally this project works out of the box.

Business entities setup

From the ROO shell we are going to setup mongo database and create our tow business entities (Account and Transaction) :

//Setting up mongo add-on
mongo setup

//Creating the Account entity
entity mongo --class ~.domain.Account
field string --fieldName name --notNull
field number --fieldName balance --type double

//Creating the Transaction entity
entity mongo --class ~.domain.Transaction
field string --fieldName payee
field other --fieldName accountId --type org.bson.types.ObjectId
field date --fieldName dateTransaction --type java.util.Date --notNull
field string --fieldName tags
field string --fieldName type --notNull
field number --fieldName amount --type double

You did notice that the Transaction entity hold the ObjectID of the Account (because there is a one to many relation between the tow entities), to simplify things I prefer to manage this association manually without using advanced concept like DBRef or embedded lists.

Repository layer setup

Beginning from Spring ROO 1.2, there is support for generating Spring Data repositories (service oriented architecture).

The generated DAO’s offer simple database access methods (create, update, findAll…), we can add our own custom methods by following naming convention no implementation code need (see for more details) or if we have complexes queries with some business logic we declare them in the Repository interface and write theirs implementation (see

From ROO shell I’m going to create tow empty DAO one to manage Account and the other for Transaction :

//Account Repository
repository mongo --interface ~.repository.AccountRepo --entity ~.domain.Account

//Transaction Repository
repository mongo --interface ~.repository.TransactionRepo --entity ~.domain.Transaction

Theses repositories contain only standard methods offered by MongoRepository abstract class (more detail we still need to add our custom methods for both AccountRepository and TransactionRepository manually.

Account repository

From the list of methods extracted (loadAll, add) in the Account service we see that they already exists on the MongoRepository, except that when adding a new transaction we need to update the current balance of the account attached to the transaction, this can’t be done with just a conventional naming DAO method.

//DAO methods without implementation code : conventional naming
@RooMongoRepository(domainType = Account.class)
public interface AccountRepo extends AccountRepoAdvance {
    List<Account> findAll();

    Account findByName(String name);

//Advanced DAO methods which required implementation code
public interface AccountRepoAdvance {
    void updateAccountBalance(BigInteger accountId, Double transactionAmount, String type);

public class AccountRepoImpl implements AccountRepoAdvance {
    MongoOperations mongoOps;

    public void updateAccountBalance(BigInteger accountId, Double transactionAmount, String type) {
        //Implementation code Here...

Transaction repository

On this repository we need a conventional method to load transactions by accountId, period and type (no need for code implementation), this method have to be called findByAccountIdAndDateBetweenAndTypeLike this name will be parsed by Spring Data in order to generate the query on the fly.

Spring Data conventional naming

The last required DAO method is totalAmountByAccountId, this one is an aggregation query and will use the group feature of MongoDB. This method can’t be implemented using the conventional naming way because we have to use the MongoOperations object to execute this kind of more advanced queries.

Below a snippet of code source for TransactionRepository :

//DAO methods without implementation code : conventional naming
@RooMongoRepository(domainType = Transaction.class)
public interface TransactionRepo extends TransactionAdvancedRepo {
    List<Transaction> findByAccountIdAndDateBetweenAndTypeLike(ObjectId accountId,
            Date start, Date end, String type);

//Advanced DAO methods which required implementation code
public interface TransactionAdvancedRepo {
    Double totalAmountByAccountId(ObjectId accountId, Date start,Date end, String type);

class TransactionAdvancedImpl implements TransactionAdvancedRepo {
    MongoOperations mongoOps;

    public Double totalAmountByAccountId(.....) {
        //Implementation code Here...

Check out this great cheat sheet if you are an experienced SQL programmer and want to learn how to write MongoDB queries.

Service layer setup

The final step on this tutorial is to setup the service layer, this layer use services offered by the repository (plain simple CRUD and querying methods)  and add to them the business logic. For example when adding a new transaction we are going to use the method save of the repository TransactionRepo but also we need to assure that the balance of the account attached to this transaction is updated (this is the business logic to control).

I’m going  also to use ROO to generate the service layer, by typing the following commands :

//Account Service
service --entity ~.domain.Account --interface ~.service.AccountService

//Transaction Service
service --entity ~.domain.Transaction --interface ~.service.TransactionService
ROO will generate nice and clean services holding a reference for the required repository (all this code is hidden in generated aspects, it is just an infrastructure code). Below the source code of the generated interfaces along with extracted methods described earlier :
@RooService(domainTypes = { Account.class })
public interface AccountService {
    void addNewAccount(Account account);
    List<Account> loadAllAccounts();

//The TransactionService require both Transaction and Account repositories
@RooService(domainTypes = { Transaction.class, Account.class })
public interface TransactionService {
    void addNewTransaction(Transaction transaction);
    List<Transaction> loadTransactionsByAccountId(BigInteger accountId, Integer period,
            String type);
    Double loadTotalAmountByAccountId(BigInteger accountId, Integer period, String type);
I’m not going to describe in here the implementation code of the service, at the end of this article there is an archive containing the whole project.

Testing Services and repositories

The last step on this article, is to test if everything works the way we want, this is a very crucial step on building a great and organized service layer, and generally on this step sometimes we intend to tweak a little bit the repositories, entities and services if we forgot something in step 1.

Because we are working on a little example, all what I’m going to show is how to test services and see if they works correctly using JUnit and Spring Test (for more details visit, for more details see the code below  :

public class TestServices {
    @Autowired AccountRepo accountRepository;
    @Autowired TransactionRepo transactionRepository;
    @Autowired AccountService accountService;
    @Autowired TransactionService transactionService;

    public void cleaningOldData() {

    public void testCreatingAccount() {
        //Test creating new Account here...

    //... More Test Methods here, check attached source code for more details

That’s it for this article, I hop that you have a big picture of the back end part, this is just a little example but I think it will help some of you to build easily high quality application very quickly. I’m open to any suggestion or enhancement.

Full Project source code can be downloaded from here : Project source.

Written by imrabti

January 2, 2012 at 11:35 am

Configure LogBack Logging with Spring

with 5 comments

LogBack is a new API for logging created by the same author of Log4j(a newer implementation, it is like a new version), during this article I’m going to show how to integrate it and use it on a Spring project. On this tutorial I assume you are using a simple Spring ROO project which will prepare all the structure of the project for you, for more information see :

First of all you need to create the logback.xml (hold the configuration appenders like log4j.properprties) file in src/main/resources :

<?xml version="1.0" encoding="UTF-8"?>
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
            <pattern>%d %5p | %t | %-55logger{55} | %m %n</pattern>

    <logger name="test.myapp.repos">
        <level value="INFO" />

    <logger name="org.springframework">
        <level value="INFO" />

        <level value="INFO" />
        <appender-ref ref="CONSOLE" />

The second step is to configure Maven dependencies and add LogBack required libraries:

<-- Properties Settings -->

<-- Dependencies Settings -->

You need to get rid of all Log4j dependencies in the Maven pom.xml generated by Spring ROO, clean every single dependency related to logging before you add the code provided to set up LogBack.

For using the logger on a  class you are developing, you need to create a static instance of it and use normally as you use the Log4J, the only difference is the implementation and configuration code of LogBack Vs Log4j. On Logback.xml your class must be scanned for the logger to work.

package test.myapp.repos; /*This package figures on LogBack.xml*/
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MyTestClass {
    static Logger logger = LoggerFactory.getLogger(ItemController.class);

    public void create(String args) {
        logger.debug("My Args Is => " + args);

There is another sophisticated way of injecting the logger on a Spring bean, this can be achieved by developing a custom BeanPostProcessor which will automatically inject the Logger on fields annotated with @Log (this is a custom annotation we created) instead of instantiating the manually the logger as described earlier.

/** Custom @Logger annotation **/
public @interface Log { }

/** LoggerPostProcessor => Custom Spring BeanPostProcessor **/
public class LoggerPostProcessor implements BeanPostProcessor {

    public Object postProcessAfterInitialization(Object bean, String beanName) throws
        BeansException {
        return bean;

    public Object postProcessBeforeInitialization(final Object bean, String beanName)
          throws BeansException {
        ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {
                public void doWith(Field field) throws IllegalArgumentException,
                    IllegalAccessException {

                    //Check if the field is annoted with @Log
                    if (field.getAnnotation(Log.class) != null) {
                        Log logAnnotation = field.getAnnotation(Log.class);
                        Logger logger = LoggerFactory.getLogger(bean.class);
                        field.set(bean, logger);

        return bean;

/** Usage on a Spring Bean **/
public class MyBeanImpl implements MyBean {
    /** Not manual set up code **/
    @Log Logger myLogger;

The last thing to do is to declare this new BeanPostProcessor on you applicationContext.xml file :

<!-- The Logger Injector -->
 <bean id="LogginInjector" class="org.test.utils.LoggerPostProcessor" />

For more information about why to switch to LogBack, see : Why switch to LogBack.

Written by imrabti

December 12, 2011 at 2:36 pm

Posted in Logging, Spring

Tagged with , ,

Spring / GWT Software Architecture for scalable applications – Part 1

with 18 comments

During this article I’m willing to share with you a clean software architecture to build high scalable enterprise application based upon GWT (on the front end) and Spring (on the back end).

I’m going to start by showing the overall software architecture and describing all technologies and best practices I use, then on the next articles we will build a little application from scratch step by step, on each article we are going to concentrate on a precise part of the solution.

GWT/Spring Software architecture

The solution is composed from tow parts, the client side (GWT) and the server side (Spring/JEE).

Client side (GWT)

On GWT I use the MVP design pattern along with activities, and RequestFactory. On this solution the MVP is just an abstraction and it is implemented using activities, the presenter and RequestFactory.

On the table below I describe each letter of MVP and how is implemented in the solution :

MVP Model

On this architecture the objects creation and injection (this include views, remote interfaces, event bus…) is managed by an IoC framework (like Spring) called GIN and is based upon Google Guice. I’ll show you on the next article how to configure it and how I use it on this approach.

  • View is a singleton configured using GIN (GWT IoC framework), most of the time a view is used by just one activity.
  • Presenter is an interface implemented by a given view, to give a lightweight object which will be manipulated later by the activity to interact with the view.
  • Activity It contains no Widgets or UI code and have a lifecycle. All the code about the UI business logic is written here. Activities manipulate both the view (by the intermediate of the presenter) and models (by calling the RequestFactory) and are started and stopped by an ActivityManager that is associated with a container Widget (a certain display area on the screen).
  • Event Bus is a singleton configured using GIN and can be injected on activities and views, its function is to dispatch events to interested parties. An event bus eases decoupling by allowing objects to interact without having direct dependencies upon one another.
  • RequestFactory is a factory exposing all your RequestContext. Each spring service you want to expose to the client must have its clone interface on GWT which extends the interface RequestContext.
  • Proxy are the clones of the objects (business objects or VO’s) used on the spring services in the server side they are manipulated by the remotes interfaces (interfaces which extends RequestContext), activities and views on GWT.

Server side (Spring/JEE)

On the server side I use a simple service oriented architecture composed from DAO (data access object managed by Spring Data for JPA), services (transactional and secured service layer exposed to GWT through the RequestFactory API),  and finally persistent entities or value objects (theses are manipulated by services and DAO).

  • Spring Data JPA repositories : Interfaces that extends the Spring Data generic repository, this interface offer elementary DAO methods (save, update, find all…), we can also put here our simple DAO methods (only methods definitions no implementation required) see Spring Data documentation for more informations :
  • Custom repositories : Here we put advanced DAO methods that needs some business logic code not just simple queries like JPA repositories (the implementation of the custom interfaces is required).
  • NamedQueries XML File : Both Spring Data Repositories and Custom repositories loads queries from XML files instead of hard coding them in java classes.
  • Spring services : Here we have all the functionality that our server side expose to the client. In order to manipulate data a service is composed from one or many DAO’s, also all the methods of the service must be transactional (so we can rollback if there is an accident) and secure.

Project structure

Now that we know some foundations about the solution, I’m going to show you how is the project structured :

The project is divided in tow big packages, the server side and client side.

Structure of the server side

On the server side we have the following sub packages :

  • repos: composed from tow other packages ‘simple’ which contain spring data DAO’s interfaces and ‘advanced’ which contain advanced DAO’s (this type of DAO’s uses the EntityManager and they perform some business logic on data).
  • services: here we found the interfaces and implementation of services exposed to GWT client.
  • rest: here we put REST controller to expose a REST API to build for example native iOS or Android application.
  • business: here we have persistent entities and custom types (like enumerations or abstract classes).
  • security: all classes related with security like authentication service, security filters… (I use spring security to manage the security of the application).

Structure of the client side

On the client side we have the following sub packages :

  • activity: holds all activities, in each activity there is an inner interfaces which is the presenter implemented by the view.
  • place: here we find the places, a place is used by the ActivityManaged defined for each display region on the GWT shell (or layout) to decided which activity to load. I’m going to talk about places on the following articles.
  • UI: holds all the declarative XML files or java code to describe the UI (UI Binder). I also put in here the application layout (I called the shell). Every other files except layout related files are grouped on sub packages each one contain the UI’s that concern a certain module of the application.
  • event: contain all the custom event we use on the EventBus. The event on here are used for example to update the content of a view when we receive some data, when another display managed by another activity trigger an event. Check this article to learn more about how to use events on a MVP architecture.
  • request: here we find RequestContext interfaces in relation with Spring services on the back end, the communication is done using a RequestFactory servlet, for more information about how to integrate Spring and GWT check the following article The sub package proxy holds the value object exchanged between the client GWT and server Spring, they are a representation of the remote objects (entities or VO’s) managed by Spring on the client side.
  • ioc: holds infrastructure code to set up the IoC container on the client (configuration for GIN). The ‘MyAppModule’ file configure the beans managed by GIN container and theirs scope (Singleton, Provider…) this file is like the applicationContext.xml on Spring.  The ‘MyAppInjector’ indicate which of the defined beans we want to get to explicitly (anywhere even if it is not a GIN bean) it is like a factory of beans. A given application can have multiples ‘Modules’ and ‘Injectors’ files.
  • resource: here we host the custom style files and images, I use heavily the ClientBundle GWT API to learn more check

That’s it for this article, on the following article I’ll describe the example we are going to build step by step using this architecture.

Written by imrabti

December 6, 2011 at 9:52 am

How to skin a GWT CellTable

with 20 comments

In this article I’m going to show you how to customize the look and feel of a CellTable using CSS and ClientBundle API of GWT. I assume that you already familiar with CSS and ClientBundle, if not visit :

Below the final look and feel of the table :

First you need to create a CSS file on you resources package, this file will override the default CSS classes used by GWT, here you put your custom CSS code to change the L&F of your table, visit to get the list of all classes used to skin the CellTable.

@def selectionBorderWidth 2px;
.cellTableWidget {}
.cellTableFirstColumn {}
.cellTableLastColumn {}
.cellTableFooter {}
.cellTableHeader {}
.cellTableCell {}
.cellTableFirstColumnFooter {}
.cellTableFirstColumnHeader {}
.cellTableLastColumnFooter {}
.cellTableLastColumnHeader {}
.cellTableSortableHeader {}
.cellTableSortableHeader:hover {}
.cellTableSortedHeaderAscending {}
.cellTableSortedHeaderDescending {}
.cellTableEvenRow {}
.cellTableEvenRowCell {}
.cellTableOddRow {}
.cellTableOddRowCell {}
.cellTableHoveredRow {}
.cellTableHoveredRowCell {}
.cellTableKeyboardSelectedRow {}
.cellTableKeyboardSelectedRowCell {}
.cellTableSelectedRow {}
.cellTableSelectedRowCell {}
.cellTableKeyboardSelectedCell {}
@sprite .cellTableLoading {}

Now that you know all CSS classes, all you have to do is to put your custom CSS code, if you don’t redefine a certain CSS class it will use its default L&F.

Below the CSS code I wrote to achieve the L&F shown earlier :

.cellTableHeader {
padding: 0px;
color: #545454;
text-align: center;
font-size: 13px;
background-image: none;
background-color: #cfcfcf;
height: 25px;
vertical-align: middle;
font-weight: bold;
text-shadow: 0 1px 1px rgba(255,255,255,.7);
.cellTableFirstColumnHeader {
-moz-border-radius-topleft: 5px;
-webkit-border-top-left-radius: 5px;
.cellTableLastColumnHeader {
-moz-border-radius-topright: 5px;
-webkit-border-top-right-radius: 5px;
.cellTableCell {
padding: 4px;
overflow: hidden;
font-size: 12px;
color: #454545;
.cellTableEvenRow {
background: #ffffff;
.cellTableOddRow {
background: #ECECEC;
.cellTableSelectedRow {
background: #628cd5;
.cellTableSelectedRowCell {
border: none;
.cellTableHoveredRow {
background: transparent;
.cellTableHoveredRowCell {
border: none;
.cellTableKeyboardSelectedRow {
background: #ffc;
.cellTableKeyboardSelectedRowCell {
border: none;
.cellTableKeyboardSelectedCell {
border: none;

After this we need to write our ClientBundle class that will use our custom CSS file and inject it to a given CellTable. This class must extend CellTable.Resources.

public interface TableRes extends CellTable.Resources {
@Source({CellTable.Style.DEFAULT_CSS, "org/test/resources/table.css"})
TableStyle cellTableStyle();

interface TableStyle extends CellTable.Style {}

Finally all we need to do now is to use this new L&F on a CellTable, on your UiBinder java class you need to write this :

public class TestUI extends Composite implements {

interface TestUIUiBinder extends UiBinder<Widget, TestUI> { }


//CellTable custom UI resource
private CellTable.Resources tableRes = GWT.create(TableRes.class);

//Create the CellTable with a custom L&F
CellTable<Test> testTable = new CellTable<Test>(10, tableRes);


That’s all, you have now a fancy CellTable :-).

Written by imrabti

November 1, 2011 at 7:52 am

Posted in CSS, GWT

Tagged with , , , ,

Installing MongoDB 2.0 on Ubuntu 11.10

with 13 comments

Ubuntu 11.10 ships with an older version of MongoDB, in this article I’m going to show how to install properly the latest version MongoDB which the 2.0.1.

First you have to download the 32bit or 64bit Linux binaries from here and unzip the contents to /usr/local.

cd /tmp
sudo tar -zxf /tmp/mongodb-linux-i686-2.0.1.tgz -C /usr/local

Then you need to configure some symbolic links.

sudo ln -s /usr/local/mongodb-linux-i686-2.0.1 /usr/local/mongodb
sudo ln -s /usr/local/mongodb/bin/bsondump /usr/local/bin/bsondump
sudo ln -s /usr/local/mongodb/bin/mongo /usr/local/bin/mongo
sudo ln -s /usr/local/mongodb/bin/mongod /usr/local/bin/mongod
sudo ln -s /usr/local/mongodb/bin/mongodump /usr/local/bin/mongodump
sudo ln -s /usr/local/mongodb/bin/mongoexport /usr/local/bin/mongoexport
sudo ln -s /usr/local/mongodb/bin/mongofiles /usr/local/bin/mongofiles
sudo ln -s /usr/local/mongodb/bin/mongoimport /usr/local/bin/mongoimport
sudo ln -s /usr/local/mongodb/bin/mongorestore /usr/local/bin/mongorestore
sudo ln -s /usr/local/mongodb/bin/mongos /usr/local/bin/mongos
sudo ln -s /usr/local/mongodb/bin/mongosniff /usr/local/bin/mongosniff
sudo ln -s /usr/local/mongodb/bin/mongostat /usr/local/bin/mongostat

All you need to do now is to setup the Linux service which will be used to start MongoDB server, to do so download this script from here.

sudo mv mongod /etc/init.d/mongod
sudo chmod +x /etc/init.d/mongod

After this, you’ll need to create a new system user ‘mongodb’ and prepare some folders.

sudo useradd mongodb
sudo mkdir -p /var/lib/mongodb
sudo mkdir -p /var/log/mongodb
sudo chown mongodb.mongodb /var/lib/mongodb
sudo chown mongodb.mongodb /var/log/mongodb

And finally you need to activate you MongoDB service’s by adding it to your system’s run-level. That way the service will startup during the boot sequence and stop nicely during the OS shutdown procedure.

sudo update-rc.d mongod defaults

That’s all, now you have a cleanly installed MongoDB on your server.

Written by imrabti

October 31, 2011 at 8:23 pm

Posted in MongoDB, Ubuntu

Tagged with , ,

Get to Spring ApplicationContext from everywhere (The clean way)

with 18 comments

In this article I’ll show you a tip on how to get to your spring Application from any place on your application.

Let say that you are writing a Fat client java application (using Swing for example) and you use Spring in it and want a clean way to retrieve a certain bean from the loaded ApplicationContext how can you do that ???

First create a class named ApplicationContextProvider, this class must implement the ApplicationContextAware interface. A bean which implements this interface, will be called back on creation using the interface’s setApplicationContext(ctx) method, and provided with a reference of the whole context. I’m going to declare the ApplicationContextClass as a singleton and store the value for the context to be reused.

public class ApplicationContextProvider implements ApplicationContextAware {
    private static ApplicationContext context;

    public ApplicationContext getApplicationContext() {
        return context;

    public void setApplicationContext(ApplicationContext ctx) {
        context = ctx;

This bean must be declared on you ApplicationContext configuration file :

<bean id="applicationContextProvder" class="org.myApp.ApplicationContextProvider"/>

To load a certain bean, all you need to write is this :

MyBean c = ApplicationContextProvider.getApplicationContext.getBean("BeanId", MyBean.class);

Written by imrabti

September 28, 2011 at 7:50 am

Posted in Spring

Tagged with ,