Java SE 7 Programmer I (1Z0-803)

by GarciaPL on Saturday 5 December 2015

I just wanna say that I managed to pass the certificate exam of Java SE 7 Programmer I (1Z0-803). Exam is not easy and it is not hard to pass even you have experience as a Java Developer. You need to spend some time to go through certification exam issues. At this point I can recommend one book despite of Oracle Documentation which was written by Mala Gupta. This book has a title : "OCA Java SE 7 Programmer I Certification Guide" [2].






Reference :
[1] Oracle University Java SE 7 Programmer I 1Z0-803
[2] Mala Gupta - OCA Java SE 7 Programmer I Certification Guide

Cross Site Scripting - XSSRequestWrapper

by GarciaPL

We all know what Cross Site Scripting (XSS) [1] means. In short the idea is that input parameters in our application should be checked for containing characters with special meaning in HTML for instance <, >, /. Those signs should be escaped by application into &amp;, &lt;, &gt;, &#x27;, &quot;, &#x2F before they will be processed by backend.

First of all you need implement Filter [7][2] which will intercept incoming requests to backend for further processing.

package pl.garciapl.xss;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import java.io.IOException;

public class RequestFilter implements Filter {

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

    public void init(FilterConfig fConfig) throws ServletException {
        logger.debug("RequestFilter initialized");
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        chain.doFilter(new XSSRequestWrapper((HttpServletRequest) request), response);
    }

    public void destroy() {
    }
}

Then you need define XSSRequestWrapper [3] used to filter every request. You can also find test class XSSRequestWrapperTest [4] which might give you preview what kind of malicious HTML might occur and what might be desirable output.

package pl.garciapl.xss;

import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;
import org.owasp.esapi.ESAPI;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class XSSRequestWrapper extends HttpServletRequestWrapper {

    public XSSRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    @Override
    public String[] getParameterValues(String parameter) {
        String[] values = super.getParameterValues(parameter);

        if (values == null) {
            return null;
        }

        int count = values.length;
        String[] encodedValues = new String[count];
        for (int i = 0; i < count; i++) {
            encodedValues[i] = stripXSS(values[i]);
        }

        return encodedValues;
    }

    @Override
    public String getParameter(String parameter) {
        String value = super.getParameter(parameter);
        return stripXSS(value);
    }

    @Override
    public String getHeader(String name) {
        String value = super.getHeader(name);
        return stripXSS(value);
    }

    private String stripXSS(String value) {
        if (value != null) {
            // It's highly recommended to use the ESAPI to avoid encoded attacks.
            value = ESAPI.encoder().canonicalize(value);
            // Avoid null characters
            value = value.replaceAll("", "");

            value = Jsoup.clean(value, Whitelist.none());
        }
        return value;
    }

}

Above class filters also headers and content of requests. As you can see method stripXSS uses ESAPI [6] library. The ESAPI (Enterprise Security API) is an OWASP project to create simple strong security controls for every web platform. I also use library called Jsoup [5] to clean once again suspect HTML [8].



Reference : [1] Cross Site Scripting Wikipedia [2] RequestFilter Pastebin [3] XSSRequestWrapper Pastebin [4] XSSRequestWrapperTest Pastebin [5] Jsoup 1.8.3 Maven [6] ESAPI 2.1.0 Maven [7] Servlet Filters and Event Listeners Doc [8] Jsoup Sanitize untrusted HTML (to prevent XSS)

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() {
        @Override
        public void run() {
            //execute here method with given delay
            handler.postDelayed(networkReceiverTask, 15000);
        }
    };


Reference:
[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>
</style>

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


ProgressDialog progressDialog = new ProgressDialog(MainActivity.this, R.style.LoadingDialogTheme);
progressDialog.setMessage(getString(R.string.dialog_loading_content));
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(true);
progressDialog.show();


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.


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

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("https://www.centralbank.ie/Pages/RSSFeedDisplay.aspx?FeedID=20");
SyndFeedInput input = new SyndFeedInput();
SyndFeed feed = input.build(new XmlReader(url));
List entries = feed.getEntries();

logger.info("Size : " + entries.size());
Iterator iterator = entries.iterator();
while (iterator.hasNext()) {
      SyndEntry entry = (SyndEntry) iterator.next();
      logger.info("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

Transactions


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 Github.com BankNow
[2] Jetty
[3] HSQLDB
[4] jQuery DataTables
[5] jQuery jqBootstrapValidation

Recruitment Tech Test

by GarciaPL on Tuesday 23 June 2015

Some of you might have a knowledge that one of the IT company has created a technical test. For recruitment process of course. I decided to take up this challenge. Below you can find a solution of it. I posted this only for educational purposes.

The projects is splited into two modules : currencyfair-gateway and currencyfair-consumer.

The first module currencyfair-gateway is responsible for exposing endpoint used for retriving from user request in JSON format. Request is validated due to it's fields. If request is not valid user will receive detailed information about which fields are incorrect. Otherwise request will be forwarded to message broker RabbitMQ.

The second module currencyfair-consumer fetches messages from message broker RabbitMQ to process it via Data Processor. Once it's done the processed data are broadcasted to frontend.
Application was developed using of course Java and Spring Framework. Those above two modules were connected via message broker RabbitMQ. Below you can see what is the overall architecture of this application. Other used libraries :

  • 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 Aop – 4.0.1.RELEASE
  • Spring Aspects - 4.0.1.RELEASE
  • Spring Web – 4.0.1.RELEASE
  • Spring Web MVC – 4.0.1.RELEASE
  • Spring AMQP - 1.4.5.RELEASE
  • Spring Erlang - 1.4.5.RELEASE
  • Spring Rabbit - 1.4.5.RELEASE
  • Spring WebSocket - 4.0.1.RELEASE
  • Spring Messaging - 4.0.1.RELEASE
  • Spring Integration - 4.1.0.RELEASE
  • Spring Integration AMQP - 4.1.0.RELEASE
  • Spring Integration Stream - 4.1.0.RELEASE
  • Spring Test - 4.0.1.RELEASE
  • Jackson Core - 2.5.0
  • Jackson Databind - 2.5.0
  • Jackson Annotations - 2.5.0
  • Jackson Mapper ASL – 1.9.10
  • Gson – 2.2.4
  • Guava - 18.0
  • Unirest - 1.4.5
  • Javax Servlet API – 3.1.0
  • JSTL – 1.2
  • SLF4J - 1.7.8
  • Commons Logging - 1.2
  • JUnit - 4.10
  • Mockito - 1.9.5
  • Hamcrest - 1.3
  • Highcharts - 4.1.5
  • Twitter Bootstrap - 3.3.4
  • SockJS - 0.3.4
I also used external resource like ECB Currency Rates (European Central Bank) for calculating income financial data from various currencies to one based EUR currency.

Architecture

Endpoint

Endpoint consumes JSON data on context /currencyfair-gateway/endpoint like below :


{ 
    "userId": "12345",
    "currencyFrom": "EUR",
    "currencyTo": "GBP",
    "amountSell": 1000,
    "amountBuy": 747.10,
    "rate": 0.7471,
    "timePlaced" : "24-JAN-15 10:27:44",
    "originatingCountry" : "FR"
}

Message is validated under empty of above fields, timePlaced format (dd-MMM-yy hh:mm:ss), existing of currencyFrom and currencyTo in ISO 4217, existing of originatinCountry in ISO 3166-1 and by calculations of amountSell, amountBuy and rate.


Data processor

Module is reponsible for calculating all data required by frontend to display it on charts.

GraphBroker

Module sends data supplied by Data processor to specific Stomp endpoints.

Frontend

Each graph subscribes data via Stomp over WebSocket from specific context. At this moment there are implemented some graphs which can be found on GitHub repository. 


References :  [1] https://github.com/GarciaPL/CurrencyFair

Portfolio

by GarciaPL

I recently uploaded my portfolio on GitHub Pages. If you are interested in projects which was developed just visit below website :

GarciaPL.github.io




Could not Autowire. No beans of 'SimpMessagingTemplate' type found

by GarciaPL on Saturday 6 June 2015

My main IDE which is used at this time to develop for example Spring application is IntelliJ IDEA 13.1. My last project is built on Spring Framework 4. There is no so much problems with it, but there is one with Spring WebSocket. When you are going to autowire SimpMessagingTemplate object there is an error :

"Could not Autowire. No beans of 'SimpMessagingTemplate' type found"

The solution is very simple. Just add in your bean xml, in my case it's dispatcher-servlet.xml this line :

<context:component-scan base-package="org.springframework.web.socket.config"/>

As far as I know this problem is fixed in Intellij IDEA 14.0. Below you can read about ticket which is strictly related with this issue.

If this solution above did not work perhaps you need to move bean definition of your class which contains Autowired field of SimpMessagingTemplate to dispatcher-servlet.xml, I mean context which is pointed in your web.xml by org.springframework.web.servlet.DispatcherServlet.


Reference :
[1] Jetbrains IDEA-123964

Maven Fetch JSON during building Jar

by GarciaPL on Monday 25 May 2015

My recent project was aimed to develop standalone application written in Swing with embedded database which was in form of JSON file. During building my Jar using Maven, I was faced with problem to replace this JSON file before final application will be produced. Before you will prepare such solution you should get familiar with Maven Build Lifecycle [1]. Below I listed those LifeCycle's :


  1. validate
  2. generate-sources
  3. process-sources
  4. generate-resources
  5. process-resources
  6. compile
  7. process-classes
  8. generate-test-sources
  9. process-test-sources
  10. generate-test-resources
  11. process-test-resources
  12. test-compile
  13. test
  14. prepare-package (maven 2.1+)
  15. package
  16. pre-integration-test
  17. integration-test
  18. post-integration-test
  19. verify
  20. install
  21. deploy
After you will decide in which phase you are going to run your custom Java class, which in my case was fetching JSON from server, you are going to use plugin called exec-maven-plugin developed by Codehaus [2].

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2</version>
                <executions>
                    <execution>
                        <id>fetchJSON</id>
                        <phase>prepare-package</phase>
                        <inherited>false</inherited>
                        <goals>
                            <goal>java</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <mainClass>pl.avantis.iom.rest.DrupalQueriesImpl</mainClass>
                    <cleanupDaemonThreads>true</cleanupDaemonThreads>
                    <daemonThreadJoinTimeout>30000</daemonThreadJoinTimeout>
                </configuration>
            </plugin>

This plugin will run pl.avantis.iom.rest.DrupalQueriesImpl in phase prepare-package, this is a step just before package phase, so your Jar will contain the newest JSON file without downloading it manually .

Reference : [1] Maven Build Lifecycle [2] Codehaus - Exec Maven Plugin

TrafficCity BIHAPI Orange

by GarciaPL on Saturday 14 March 2015

Today I have released on GitHub two repositories which contain one of my recent project called TrafficCity. It was developed on hackathon called BIHAPI (Business Intelligence Hackathon API) organized by Orange Poland.

Briefly describing what's it's about in this app - on the mobile app you can place your markers (waypoints) on Google Maps which describes your daily route to work/school. After that you can send those waypoints to server to further processing.

In Backend you can see what's routes are defined by users. Additionally you can upload OSM file which is strongly related with OpenStreetMap and after that you can see on particular area what's is the chance to appear traffic jam.

An application consists of Backend app written in Spring and mobile app written in Android. Application was mainly deployed on JBoss AS 7.1. Backend part is also using interfaces provided by Orange - SIM GeoLocalization API, SMS API, USSD API and by Warsaw City - Transport POI Maps.

Unfortunately, I think that application which is in alpha phase, probably would remain so. There a few things to do/fix on the Backend and Mobile part, but not at this moment. I hope that more appropriate time will come.

Below I allowed myself to post some screenshots from backend and mobile part of this application.

Dashboard

Markers
OSM Upload
OSM Projects
HeatMap


Home
Settings
Transport Type
First marker
Multiple markers
Daily route
Settings


Reference :
[1] GitHub TrafficCity Backend
[2] GitHub TrafficCity Android
[3] BIHAPI

Swing Shuffle JTable rows

by GarciaPL

Swing in my opinion is quite great framework or library whatever you prefer to create Java application on desktop. But after using it some time, I noticed that one of the disadvantage of Swing is that when you make some heavy calculation, that almost always your GUI is going to freeze. Of course you can not leave this in that way, so you must create some workaround. To make it happen you can use for instance Timer from javax.swing package of course.


        final Timer timer = new Timer(200, null);
        ActionListener actionListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (isRandomizeRows()) {
                    ContestTableModel contest = getContestTableModel();
                    Vector data = contest.getData();
                    Collections.shuffle(data);
                    contest.setData(data);
                    getTablePlayers().setModel(contest);
                    getContestTableModel().fireTableDataChanged();
                }
            }
        };

As you can see method isRandomizeRows() only blocks execution of this Timer. I do not know why method .stop() which is implemented in this Timer simply does not work. Nevertheless there is a line where AbstractTableModel from our JTable is acquired (getContestTableModel()). After that you get data in Vector collection. Shuffle it's contents using Collections.shuffle(data) method. After that set data, set model and let to know JTable that it's data has changed.

Unirest - HTTP Client

by GarciaPL

I am currently developing some application in Swing which does a lot of crazy things, but it also connects to backend system via REST interfaces to retrieve or send some XML's. At this moment I must to admit that one of the most powerful libraries used by me to serialize and deserialize XML is nothing else that XStream [1]. It is really worth of using. Very powerful and configurable. It deserves to be described in separate post.

Back to the topic, I was looking for some HTTP client request library which can help me to make some requests to server in approachable way. On the one hand we have HttpClient supplied by Apache in httpcomponents package [2]. We have also RestTemplate supplied by Spring team [3] and so on. But this time I found library called Unirest! [4].

You can make GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS requests in synchronous or asynchronous way, supports form parameters, file uploads, gzip, Basic Authentication, timeouts, proxy, responses in String or JSON.

In this post I would like to present two mainly used at this moment in previously mentioned application, approaches to REST interfaces using of course GET and POST methods. There also be used Basic Authentication.

Firstly let's create interface for those methods :

public interface mQubeQueries {
        List getPlayers(Integer serviceId, Date from, Date to) throws UnirestException, XStreamException;
        void sendResults(Integer serviceId, Integer stageId, List results) throws UnirestException, XStreamException;
}
GET

public class mQubeQueriesImpl implements mQubeQueries {
    private XStream xStream;

    public mQubeQueriesImpl() {
        this.xStream = new XStream();
        this.xStream.setMode(XStream.ID_REFERENCES);
    }

    @Override
    public List getPlayers(Integer serviceId, Date from, Date to) throws UnirestException, XStreamException {
        GetRequest response = Unirest.get("http://server.com/" + "get-players" + "/" + serviceId +
                "/" + new DateFormatter().formatQubeDateTimezone(from) +
                "/" + new DateFormatter().formatQubeDateTimezone(to)).basicAuth("login", "password");

        if (response.asString().getStatus() == 403) {
            throw new UnirestException("No authorized");
        }

        if (response.asString().getStatus() != 200) {
            throw new UnirestException("Unexpected response with code : " + response.asString().getStatus());
        }

        String body = response.asString().getBody();
        if (body == null) {
            throw new UnirestException("Response from server is null");
        } else {
            try {
                return (List) xStream.fromXML(body);
            } catch (Exception e) {
                throw new XStreamException(e.getMessage());
            }
        }
    }
}


POST

    @Override
    public void sendResults(Integer serviceId, Integer stageId, List results) throws UnirestException, XStreamException {
        List results = new ArrayList();
        for (Entrant entrant : results) {
            ResultDTO record = new ResultDTO();
            record.setDateCreated(new Date());
            results.add(record);
        }

        String xml = xStream.toXML(results);

        HttpResponse response = Unirest.post("http://server.com/" + "send-drawing-results" +
                "/" + serviceId + "/" + stageId).basicAuth("login", "password").
                header("Content-Type", "application/xml").body(xml).asString();

        if (response.getStatus() == 403) {
            throw new UnirestException("No authorized");
        }

        if (response.getStatus() != 204) {
            throw new UnirestException("Unexpected response with code " + response.getStatus());
        }
    }
References :
[1] XStream
[2] HC Apache
[3] Spring RestTemplate
[4] Unirest
[5] Pastebin Interface Source Code
[6] Pastebin GET Method Source Code
[7] Pastebin POST Method Source Code

Load image from resources in Maven

by GarciaPL

I would like to share a very useful snippet of code which allows you to load image located in resources folder (we talk about project in Maven). I assume that you know how looks project in Maven. For the record it is something like this :

Maven project structure

In one of my projects there was a need to store images inside in Swing application in .png and .gif format in resources directory (/src/main/resources/). At this moment I place those images manually, but in some near future I will use some library for instance JarPlug or MyJarExplorer to manipulate content of this jar file to automate this process.


Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/resources/dvlogo.png"));
if (image != null) {
   ImageIcon icon = new ImageIcon(image);
   getMainLogo().setIcon(icon);
}
Above code retrieves image using Toolkit class from Maven's resources directory and create ImageIcon object which is used next in some JFrame to display it. Reference :  [1] Pastebin Source Code

Swing Repainting JButton

by GarciaPL on Monday 2 March 2015

At my currently project written mainly in Swing, I had an issue where there was a need to show some text on JButton before some calculations. Unfortunately after setting some custom text on this component using .setText method, I was invoking some quite heavy operations which blocks UI. I tried using .repaint and .revalidate methods (once on component, once on RootPane) before those operations, but they did not work. Finally, I managed to obtain how to force change this text using method paintImmediately.

getButtonLogin().paintImmediately(0, 0, 600, 600)

Finance Currency Convert

by GarciaPL on Tuesday 17 February 2015

After my last trip do Budapest with my wife (I really recommend going to this town! It's wonderful! not only building, but also people are very very nice to tourists), I had a little forints. There is not such much of them, but recently I was checking what is the current currency rate of forint to exchange those money. It was no such difficult to do it, I just did request to Google like '9000 HUF to PLN'. Then idea came to me, that I can wrote some script in Perl which can do it for me and additionally inform via email when there is a good opportunity to exchange those money.

For sending emails I used very nice API called Mandrill [2]. For currency convert from HUF to PLN I used module called Finance::Currency::Convert::Yahoo [3].

#!/usr/bin/perl -w
use strict;
use POSIX;
use WebService::Mandrill;
use Finance::Currency::Convert::Yahoo;
 
$Finance::Currency::Convert::Yahoo::CHAT = 1;
$_ = Finance::Currency::Convert::Yahoo::convert(9430,'HUF','PLN');
 
if (defined($_)) {
   if (floor($_) gt 135) {
      print "Sell HUF : ".floor($_)."\n";
      send_email('receiver@gmail.com', 'Sell HUF', 'Right now there is the time to sell HUF');
   } else {
      print "Keep HUF\n";
   }
} else {
   print "Error\n";  
}
 
sub send_email {
 
        (my $to, my $subject, my $body) = @_;
 
        my $mandrill = WebService::Mandrill->new(
                debug   => 1,
                api_key => 'YOUR_API_TO_MANDRILL',
        );
 
        my $response = $mandrill->send(
                subject      => $subject,
                from_email   => "sender\@gmail.com",
                text         => $body,
                track_opens  => 1,
                track_clicks => 1,
                to => [
                    { email => $to }
                ],
        );
}




Reference : [1] Pastebin Source Code Finance Current Convert [2] Mandrill.com [3] CPAN Finance::Currency::Convert::Yahoo

Launch4j - Generate exe from jar

by GarciaPL on Saturday 7 February 2015

Sometimes there is a some particular need that your program (of course mainly written in Java, that's obvious) must also be able to work under Windows environment (sic!). There is no such problem if you program will have still .jar extension, but recently business in my company demanded to create such program with .exe extension. I was convinced that it's not really possible. I was thinking how to mix different approaches to create applications under Windows and Linux environment.

But I finally found a very helpful and customizable tool called Launch4j [1]. This tool is mainly used by Graphical User Interface (GUI) where you define all configuration for instance Input (jar) and Output file (exe), some classpath, header, JRE version required by application to work, some custom environment variables, splash and of course information about version, copyright, product and company name etc.

Regarding to my case in company I must transform .jar to .exe file without using GUI. There was a need to create some REST interface which will receive some parameters like .jar file, .icon and other specified information to generate generic .exe file using of course launch4j.

To do so, you must include launch4j.jar to your project and use below Java code to generate .exe.

    public static void main(String[] args) {
        try {
            File file = new File("/home/lciesluk/configuration.xml");
            try {
                ConfigPersister.getInstance().load(file);
            } catch (ConfigPersisterException ex) {
                System.out.println("ConfigPersisterException " + ex.getMessage());
            }

            Config config = ConfigPersister.getInstance().getConfig();
            System.out.println("Input : " + config.getJar().getAbsolutePath());
            System.out.println("Output : " + config.getOutfile().getAbsolutePath());

            File baseDir = new File("/home/lciesluk/launch4j"); //extracted launch4j
            Builder b = new Builder(Log.getAntLog(), baseDir);
            File build = b.build();
            System.out.println("EXE location : " + build.getAbsolutePath());
        } catch (BuilderException ex) {
            System.out.println("BuilderException " + ex.getMessage());
        }
    }

I added also an additional sample of configuration file used by launch4j [2].
<launch4jconfig>
  <dontwrapjar>false</dontwrapjar>
  <headertype>gui</headertype>
  <jar>/home/lukasz/Motohurt.jar</jar>
  <outfile>/home/lukasz/Motohurt.exe</outfile>
  <errtitle>Please download and install Java</errtitle>
  <cmdline></cmdline>
  <chdir>.</chdir>
  <priority>normal</priority>
  <downloadurl>http://java.com/download</downloadurl>
  <supporturl></supporturl>
  <stayalive>false</stayalive>
  <restartoncrash>false</restartoncrash>
  <manifest></manifest>
  <icon>/home/lukasz/icon.ico</icon>
  <jre>
    <path></path>
    <bundledjre64bit>false</bundledjre64bit>
    <bundledjreasfallback>false</bundledjreasfallback>
    <minversion>1.7.0</minversion>
    <maxversion></maxversion>
    <jdkpreference>preferJre</jdkpreference>
    <runtimebits>64/32</runtimebits>
  </jre>
  <versioninfo>
    <fileversion>1.0.0.0</fileversion>
    <txtfileversion>1.0</txtfileversion>
    <filedescription>App</filedescription>
    <copyright>GarciaPL</copyright>
    <productversion>1.0.0.0</productversion>
    <txtproductversion>1.0</txtproductversion>
    <productname>App</productname>
    <companyname>GarciaPL</companyname>
    <internalname>GarciaPL</internalname>
    <originalfilename>App.exe</originalfilename>
  </versioninfo>
</launch4jconfig>

Reference : [1] Launch4j Home Page [2] Launch4j Configuration XML

Grand Prix BIHAPI

by GarciaPL

On 29th January in European Center of Solidarność in Gdańsk were announced results of BIHAPI competition. First winner of competition was "CoSieStao" which allows users access to various types of information related with town/district where they live. Application was created by Paweł Konieczny and Piotr Martyniak. There were also awarded such applications like "Via CRM the first passenger relationship management in the world", "Poczytaj mi", "Stacz kolejkowy" and "IfCity". More information about competition and awarded applications can be found under www.bihapi.pl.

Competition partners :

Oracle Communication (technology partner), Capital City Warsaw, Gdańsk, Poznań, Poznańskie Centrum Superkomputerowo-Sieciowe, IQ Partners, Black Pearls, SpeedUp Group, Investin, Fundacja TechSoup, Orange Foundation, Fundacja Pracownia badań i innowacji społecznych Stocznia, Centrum Cyfrowe Fundacja Projekt: Polska, geecon.org, Gdański Park Naukowo-Techniczny, Uniwersytet Ekonomiczny w Poznaniu, Warsaw University of Technology, Międzynarodowe Targi Poznańskie.



 BIHAPI Grand Prix

Atom RSS Parser Android

by GarciaPL on Wednesday 21 January 2015

One of my Android applications requires to fetch and process external RSS resource. My first thought was that I should use very useful and well documented library called ROME [1]. Unfortunately I had some difficulties using this library because of there is a lack of java.beans package in Android's Java API implementation [2]. Of course you can fix this issue by installing some missing packages, but I was looking for some out-of-box solution. Finally, I found library called Simple Feed Parser [3]. It may for some of you be quite outdated (last commit was 4 years ago) and I found that there is a some issue with accessing date of single RSS entry, but it has very simple implementation, it is compatible with Android SDKs and it does not require any further library dependencies! Below you can find some example usage of this library in Java.

import com.ernieyu.feedparser.Feed;
import com.ernieyu.feedparser.FeedException;
import com.ernieyu.feedparser.FeedParser;
import com.ernieyu.feedparser.FeedParserFactory;
import com.ernieyu.feedparser.Item;

try {
                InputStream inputstream = new URL("http://rss.android.com/rss).openStream();
                FeedParser parser = FeedParserFactory.newParser();
                Feed feed = parser.parse(inputstream);
                List itemList = feed.getItemList();
                for (Item item : itemList) {
                    logger.info("Title : " + item.getTitle());
                    logger.info("Item : " + item.getLink());
                    logger.info("Description : " + item.getDescription());
                    logger.info("Date : " + item.getPubDate()); //might be null
                }
            } catch (IOException e) {
                logger.info("IOException : " + e.getMessage());
            } catch (FeedException e) {
                logger.info("FeedException : " + e.getMessage());
            }

References :  [1] ROME - All feeds lead to Rome! [2] Java.Beans on Android [3] Simple Feed Parser