SimpleUrlAuthenticationFailureHandler Locale based

by GarciaPL on Saturday, 26 September 2015

Some of you may use Spring Security in your application. Let's assume that your application is localized for many different languages. In this post I would like to give you some solution for case when user loggs into your application and should be redirected to specified address with appropriate locale for that user. I think, because I am not sure that in this case LocaleResolver would not work because before user loggs in, you will receive for instance English locale which depends on what configuration is on your server. In this case you need to use CookieLocaleResolver. Another assumption - I hope that your app uses cookies.


import org.springframework.web.servlet.i18n.CookieLocaleResolver;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

public class AuthenticationFailureImpl extends SimpleUrlAuthenticationFailureHandler implements AuthenticationFailureHandler {

    private String defaultFailureUrl;
    private String langToken = "?lang=";
    private CookieLocaleResolver localeResolver;

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

        Locale requestLocale = localeResolver.resolveLocale(request);
        saveException(request, exception);
        if (requestLocale != null) {
            new DefaultRedirectStrategy().sendRedirect(request, response, defaultFailureUrl + langToken + requestLocale.getLanguage());
        } else {
            new DefaultRedirectStrategy().sendRedirect(request, response, defaultFailureUrl + langToken + Locale.ENGLISH.getLanguage());

    public void setDefaultFailureUrl(String defaultFailureUrl) {
        this.defaultFailureUrl = defaultFailureUrl;

    public void setLocaleResolver(CookieLocaleResolver localeResolver) {
        this.localeResolver = localeResolver;

Of course there is a bean configuration for this class :


Gson Timestamp deserialization

by GarciaPL

Google Gson [1] is very useful library for parsing JSON to our domain object. It supports mapping JSON to such formats as Long, String, Integer, Boolean etc. The problem is when you have Timestamp [2] in your domain object. You are forced to write Adapter [3] which will help you to make it happen.

package com.garciapl.parser;

import com.garciapl.model.dto.ExampleDTO;

import java.lang.reflect.Type;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TimestampAdapter implements JsonDeserializer {

    private final DateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    public ExampleDTO deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) {
        if (json.isJsonObject()) {
            JsonObject jsonObject = (JsonObject) json;
            String startDate = jsonObject.has("startDate") ? jsonObject.get("startDate").getAsString() : null;
            String endDate = jsonObject.has("endDate") ? jsonObject.get("endDate").getAsString() : null;

            Timestamp startDateStamp = null;
            Timestamp endDateStamp = null;
            if (startDate != null && endDate != null) {
                startDateStamp = createTimestamp(startDate);
                endDateStamp = createTimestamp(endDate);

            return new ExampleDTO(startDateStamp, endDateStamp);
        return new ExampleDTO();

    private Timestamp createTimestamp(String json) {
        try {
            Date date = format.parse(json);
            return new Timestamp(date.getTime());
        } catch (ParseException e) {
            throw new JsonParseException(e);

Below you can find how to use this above adapter in GsonBuilder :

package com.garciapl.parser;

import com.garciapl.model.dto.ExampleDTO;
import com.garciapl.util.Localization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Modifier;
import java.lang.reflect.Type;

public class JsonParser {

    private final static Logger logger = LoggerFactory.getLogger(JsonParser.class);

    private Gson gson;

    public JsonParser() {
        gson = new GsonBuilder()
                .registerTypeAdapter(ExampleDTO.class, new TimestampAdapter())

    public  T fromJson(String json, Class destinationClass) {
        if (json == null || json.isEmpty()) {
            try {
                return destinationClass.newInstance();
            } catch (InstantiationException e) {
                logger.error("JsonParser exception : ", e);
                return null;
            } catch (IllegalAccessException e) {
                logger.error("JsonParser exception : ", e);
                return null;
        } else {
            return gson.fromJson(json, destinationClass);

Reference: [1] [2] Timestamp Java Doc [3] Gson TypeAdapter

Font for developers - Hermit

by GarciaPL on Wednesday, 16 September 2015

A few days ago I was looking for some new, not widely available, curios and eye-catching font for documenting my stuff. And of course I found! It's called Hermit [1]. This font is as the author said is focused on programming. It has medium, light and bold versions. Font comes from Monospace family. This font also supports complete Latin-0 character set also known as a ISO 8859-15. Below you can find screenshot when this font was used by me.

Hermit font

Reference : [1]


by GarciaPL on Monday, 7 September 2015

At this moment I am looking for some Java library for SQL-DSL. I have two requirements for this library. First of all it must be able to build queries using Builder pattern. Second requirement is that it should be available in Maven central repository. I must to add that I am not looking for some bigger framework to do it, but some small tool to build those queries dynamically. I found very good library called jOOQ. Unfortunately it will apply overhead in my project. I found library called sql-dsl from kantega [2]. Unfortunately it is not available in Maven repository. Additionally I found that this library does not support distinct statement (maybe owner forgot about this...). Nevertheless there was perfect time and place for me to make pull request with hotfix on GitHub [1]. I hope that owner of this library will apply those changes and put this library in Maven repository that it will be more accessible for me and other developers.

Reference :

ROME Parsing RSS

by GarciaPL on Sunday, 30 August 2015

A few days I was looking for some library to parsing RSS feeds in Java mainly for Android purpose. For me it was quite obvious that I will pick up library called ROME because of I have still a pretty good feeling about it from previous projects. Below you can find my piece of code which is very similar to this one on ROME website.

URL url = new URL("");
SyndFeedInput input = new SyndFeedInput();
SyndFeed feed = XmlReader(url));
List entries = feed.getEntries();"Size : " + entries.size());
Iterator iterator = entries.iterator();
while (iterator.hasNext()) {
      SyndEntry entry = (SyndEntry);"Entry : " + entry.getTitle() + " " + entry.getAuthor() + " " + entry.getLink());

If you will use official ROME library [1] on Android you will be faced with this error :
ERROR/AndroidRuntime(263): java.lang.NoClassDefFoundError: [Ljava.beans.PropertyDescriptor;
This error occurred due to lack of libraries on Android platform related to java.beans package. Fortunately there is a way to parse this RSS on Android platform properly. Only what you need to do is download fork of ROME library called AndroidROMEFeedReader [2] and apply jdom-1.1.1-android-fork.jar and android-rome-feed-reader-1.0.0.jar to your project in Android Studio. From this moment you will be able to fetch and parse RSS without including java.beans package to your project.

Reference: [1] ROME [2] GitHub AndroidROMEFeedReader [3] Docs Oracle Java Beans

Recruitment Tech Test #2

by GarciaPL on Saturday, 15 August 2015

Some time ago I have solved another technical test for one company. As the same before this test was performed for recruitment process.

This application is dedicated for tellers which provides functionalities like :

  1. Create account(s) - a user can create an account, associate a name with it, give it a unique account number, add a starting balance etc.
  2. Make lodgement - a user can lodge an amount into an account (balance increase)
  3. Make transfer - a user can transfer an amount from one account to another (balance transfer)
  4. View transactions - a user can view recent, or all, transactions for an account (statement)
Application was developed using Java 7 and Spring Framework 4.0.1. Below you can find out what libraries were used in application :

  • Spring Beans – 4.0.1.RELEASE
  • Spring Tx – 4.0.1.RELEASE
  • Spring Context – 4.0.1.RELEASE
  • Spring Context Support – 4.0.1.RELEASE
  • Spring Orm – 4.0.1.RELEASE
  • Spring Jdbc – 4.0.1.RELEASE
  • Spring Web – 4.0.1.RELEASE
  • Spring Web MVC – 4.0.1.RELEASE
  • Spring Test - 4.0.1.RELEASE
  • Joda Money - 0.10.0
  • Jackson Core - 2.5.0
  • Jackson Databind - 2.5.0
  • Jackson Annotations - 2.5.0
  • Javax Servlet API – 3.1.0
  • JSTL – 1.2
  • Hibernate Core - 4.3.5.Final
  • Hibernate Entitymanager - 4.3.5.Final
  • HSQLDB - 2.3.3
  • SLF4J - 1.7.8
  • Commons Logging - 1.2
  • JUnit - 4.10
  • Mockito - 1.9.5
  • Hamcrest - 1.3
  • Twitter Bootstrap - 3.3.4
  • DataTables - 1.10.7
  • jqBootstrapValidation - 1.3.6

Home screen

Create new account

Deposit money

Transfer money


Application for tellers has also built-in Jetty web sever container which allows you run it very quickly using command mvn jetty:run in directory of project. After that application should be accessible under context http://localhost:9090/banknow/.
You can also build own WAR file using command mvn war:war in directory of project. War will be accessible under directory /target and called banknow.war.
Reference :
[1] GarciaPL BankNow
[2] Jetty
[4] jQuery DataTables
[5] jQuery jqBootstrapValidation