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)