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.


package com.garciapl.security;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;

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

public class AuthenticationFailureImpl extends SimpleUrlAuthenticationFailureHandler implements AuthenticationFailureHandler {

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

    @Override
    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.google.gson.*;
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");

    @Override
    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.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
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;

@Component
public class JsonParser {

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

    private Gson gson;

    public JsonParser() {
        gson = new GsonBuilder()
                .serializeNulls()
                .disableHtmlEscaping()
                .setDateFormat(Localization.BASE_DATE_FORMAT)
                .registerTypeAdapter(ExampleDTO.class, new TimestampAdapter())
                .excludeFieldsWithModifiers(Modifier.TRANSIENT)
                .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES)
                .setPrettyPrinting()
                .create();
    }

    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] https://github.com/google/gson [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] https://pcaro.es/p/hermit/
[2] https://github.com/pcaro90/hermit

SQL DSL

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 :
[1] https://github.com/GarciaPL/sql-dsl
[2] https://github.com/kantega/sql-dsl