Android Cron Service

by GarciaPL on Thursday, 12 November 2015

I would like to publish a very useful snipper of code to create cron service in your Android app. Of course you might use some libraries created by other developers. A lot of them might be found on site called Android Arsenal [1] which also I would like to recommend for developers who are looking for libraries.

So, First of all you need to create Handler [2] object which allows you to send and process Runnable objects. This object has a lot of methods which might help you to define expected behavior of your code. This time I will use method postDelayed which allows to execute some Runnable with delay.

private Handler handler = new Handler();

And then we can define Runnable with task in it which should be executed with given delay

Runnable networkReceiverTask = new Runnable() {
        public void run() {
            //execute here method with given delay
            handler.postDelayed(networkReceiverTask, 15000);

[1] Android Arsenal Job Schedulers
[2] Android Handler

Android Progress Loading Dialog

by GarciaPL on Monday, 9 November 2015

Some of you might be looking for some solution to display progress loading dialog. I have used below example it in one of my Android application compiled against API 23 (Android 6.0). That's why on first glance you might think that style theme which I used in this case is overloaded. You need just to adjust it to your own purposes.

<style name="LoadingDialogTheme">
    <item name="colorAccent">#1976D2</item>
    <item name="android:textColor">#1976D2</item>
    <item name="android:textColorPrimary">#1976D2</item>
    <item name="android:textColorSecondary">#1976D2</item>
    <item name="android:windowFrame">@null</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowTitleStyle">@null</item>
    <item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
    <item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
    <item name="android:backgroundDimEnabled">false</item>
    <item name="android:background">@android:color/transparent</item>

Above style should be added in styles.xml. Then you can use this style with ProgressDialog as below.

ProgressDialog progressDialog = new ProgressDialog(MainActivity.this,;

And the final result is as this one :

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 :