Compiling Cascading: FAILURE: Build failed with an exception.

Today I ran into a really stupid error message when I tried to recompile cascading-jdbc:

Evaluating root project ‘cascading-jdbc’ using build file ‘/home/…/cascading-jdbc/build.gradle’.

FAILURE: Build failed with an exception.

* Where:
Build file ‘/home/…/cascading-jdbc/build.gradle’ line: 68

* What went wrong:
A problem occurred evaluating root project ‘cascading-jdbc’.
> Could not find method create() for arguments [fatJarPrepareFiles, class eu.appsatori.gradle.fatjar.tasks.PrepareFiles] on task set.

* Try:
Run with –stacktrace option to get the stack trace. Run with –debug option to get more log output.

BUILD FAILED

Total time: 5.355 secs

Solution

Check your gradle version … I ran a brand new Ubuntu with the shipped gradle version 1.4. Well the cascading readme states that gradle 1.8 is required … and it really is.

RaspberryPi Weatherstation – The TV Station (Part III)

The third and last post of this series describes the RasperryPi that is connected to the TV and displays the sensor data in a visually appealing way.


Part 1Part 2Part 3


In the past blog post, the first Raspberry Pi was connected to several sensors. Tiny Python scripts poll the data from the sensors regularly and save them to simple text files that can be copied via SSH/SCP. Current data can be obtained from the sensors by directly connecting to the Brick Daemon which runs on this RasPi.

The main focus of this post is the visualization of the data via a JavaFX application and how to control the FX application by using the regular remote control of the TV. But – before we’re divig into the details, I want to teas you with a screen shot of the final result 😉

Wetterstation blue edition

Nice isn’t it? So let’s get started

Things to discuss

The most important question first: What do I want to see and do?
I had a pretty clear intention already: I want to see the current values of all sensors in a small overview and I want to be able to toggle through time series of the past days.

Toggling should be done by the TV’s remote control as I would have the remote at hand already when I switch to the Weather data display. I’ve seen several guides where an IR-receiver and an additional remote were used to control the RasPi. Yet I simply do not like the idea of having another remote control on the table – right next to the other ones. Also controlling the app via mobile phone wasn’t what I wanted as we usually still simply use the TV’s own remote to control the TV. – Also I know from Raspbmc that it is possible to accomplish this by using libCEC – somehow.

Next question to clarify: How should the data be visualized on the TV. This was easy: JavaFX.
Colleagues asked me why I chose FX instead of HTML5. Well mainly there were three reasons:

  • I simply wanted to do something in JavaFX
  • I’m not a fan of fizzling around with JavaScript and CSS. And the standard way to displaying webapps on the RasPi seems to be using Midori. A browser I never worked with before – and even thinking about possible CSS/JS incompatibilities totally turned me off.
  • I wanted to control the UI with the TV’s remote control. That has to be done somehow using the CEC-commands that are sent through HDMI. I’ve never done that before and anticipated my chances to accomplish this in pure Java ways higher than somehow creating input events that I had to redirect to the browser.

Checking the Hardware

Prior to coding, I did some research if and how the CEC commands are sent through HDMI. And – unfortunately – besides all software problems, a lot of people reported problems to even get the signal to the RasPi! Possible problems mentioned throughout several posts included the TV software having disabled the CEC functionality or HDMI cables that were blocking / not forwarding the CEC signals.

What I found the easiest way to test the CEC compatibility of the setup was Raspbmc. Raspbmc is a mediacenter for Raspberry Pis, which is easy to install and supports CEC. So: download the image, flash it to an SD card, connect the Pi to your TV with the HDMI cable that you want to use later as well and start the Pi. If you see your TV’s remote working: Great! Otherwise: you have my sympathy. Good luck in finding out what is wrong with your technical setup.

Install libCEC

So the CEC signals are technically consumable by the Pi. Let’s istall libCEC.
DO NOT install the packages from the pulse-eight website. And also DO NOT simply recompile and install libCEC following the guide on the GitHub page. It’s important to compile the lib for the Pi! Just follow one of the step by step guides to compile and install:

$ cd /tmp
$ sudo apt-get install build-essential autoconf liblockdev1-dev libudev-dev git  libtool pkg-config
$ git clone git://github.com/Pulse-Eight/libcec.git
$ cd libcec
$ sudo ./bootstrap
$ sudo ./configure --with-rpi-include-path=/opt/vc/include --with-rpi-lib-path=/opt/vc/lib --enable-rpi
$ sudo make
$ sudo make install
$ sudo ldconfig
$ cec-client -l

LibCEC is now installed including cec-client (seen in the last call). Play around a bit with cec-client. Up to now everything was fine on our Samsung TV. But beware, I’ve seen posts where people with TVs from other vendors faced serious problems … If you want to play around with cec-client, CEC-O-MATIC might also be a reference you should have a look at.

Install Java 8

At the time of writing, Java 8 is already released. At the time I was writing the code, it was still an EA release (Early Access). I read several posts that recommended installing the ARM version of Java 8. So I simply followed the OpenJDK guide to install OpenJDK 8:

  1. download Java 8 ARM from Oracle
  2. unpack the file: sudo tar zxvf jdk-8-linux-arm-vfp-hflt.gz -C /opt
  3. and check if Java 8 got installed: /opt/jdk1.8.0/bin/java -version
  4. Set default java and javac to JDK 8:
    $ sudo update-alternatives --install /usr/bin/javac javac /opt/jdk1.8.0/bin/javac 1
    $ sudo update-alternatives --install /usr/bin/java java /opt/jdk1.8.0/bin/java 1
    
    $ sudo update-alternatives --config javac
    $ sudo update-alternatives --config java
    
    $ java -version
    $ javac -version

    java and javac should link to 1.8.0 now.

Next adjust the memory split option as also mentioned on the page to 256mb (gpu_mem=256 in /boot/config.txt). It’s useful to read the page. The page also gives a note which is pretty important to avoid frustration:

Note that the default configuration of JavaFX on the Raspberry Pi does not use X11. Instead JavaFX works directly with the display framebuffer and input devices. So you should not have the X11 desktop running when starting JavaFX.

JDK 8 EA builds for the Raspberry Pi include full support for hardware accelerated graphics, with everything from the base, graphics, controls and FXML modules. Media and Web modules are not included.

So configure the Pi to boot just to the shell (via sudo raspi-config) and do not try to see the JavaFX output via VNC!

Building the GUI

Designing the UI (or: how I started to love JavaFX)

Before I even started to code, I wanted to set up the layout. Coming from a Java-Swing background I was really excited to try this JavaFX thingy that was said to be so much cooler than Swing.

After setting up the project in NetBeans and installing JavaFX Scene Builder I was very positively surprised! By the way, I was only working with Scene Builder 1.1, the current Version 2 is said to be even better. After initializing the project, my focus quickly went into the src/main/resources folder. At this location you can find fxml/FXMLDocument.fxml and styles/base.css (later renamed to metro.fxml/.css). Designing the Gui was about 90% done just in Scene Builder (for the .fxml) and Netbeans (for the.css). The really really nice thing is that it is a true WYSIWYG editor. Also whenever the css file is being edited, the effect is immediately visible in Scene Builder. Simply great compared to what I was used to from my Swing experience.

After the main layouting was done, I started to write some Java code in FXMLDocumentController.java. Accessing UI components is simply done by annotating the according fields. The fields themselves are injected automatically. A nice decoupling of view and controller. Also I was able to compare two very different layouts by just switching one single line (the one referencing the fxml file) without further refactoring.

Time for some user tests! Honestly, I was a bit afraid what others would say. But I wanted to make a NICE UI, so I asked my wife and friends on Facebook and Google+ for feedback. And this decision turned out to be damn right! I got very valuable feedback about colors and layout. I definately recommend asking users – and value their feedback!

Afterwards I implemented the logic for reading the CSV files including filling the model classes. These model classes were then rendered into the graphs. So I also had some test data and continued styling the graph lines via CSS. At this stage I remembered the talks of Gerrit Grunwald. Gerrit is pretty experienced in JavaFX on the Pi and mentioned in some talks that animations on the Pi can be really really slow in the beginning until everything gets hot spot compiled. – I can definitely confirm this! The trick was to simply set animated="false" on the line chart that would only be animated at the beginning (which I didn’t really need or want anyways).

Show the UI on the TV

Time for a first test on the TV! At this point, remember the last part from “Install Java8” above: We do not need an X-server as JavaFX on the Pi paints directly to the framebuffer! So just compile and build the Jar, copy it over to the Pi and start it with java -jar ./ Weatherstation-1.0-SNAPSHOT.jar.

I made the experience that my regular monitor is not the same as the display of the TV. So I spent some time with adjusting css font sizes until I was content with the way everything was displayed on the TV. It feels a bit like webdesign and testing with different browsers – just a bit less painful.

Connecting the sensors

With the gui being done so far, the next step had to be done. When the program is started, archived data is read from files. Current data should be fetched directly from the remote sensors. This was actually plain easy. With the API provided by tinkerforge, everything I had to do was starting a thread off the Event dispatching thread that polled new sensor values periodically and pushed the data to the models. the models then simply updated their UI elements.

Remote control Java

The key strokes should be used to toggle through the values of humidity, temperature, ambient light and air pressure.

Everything that was left now was the remote control part. Unfortunately, libcec is a C-binary only. So I had the choices to try some JNI and talk to the lib directly or to start a Java Thread wrapping a process that just called the cec-client program:
/usr/local/bin/cec-client -d 8 -t prta -o Wetter. The d parameter defines the verbosity of the output, t defines the type of device the cec-client simulates (recorder, …), and o finally defines the string that is shown in the On Screen Display of the TV when brwosing through the HDMI input devices. When a cec-client listens with this command, just switch the TV to the according “device” and press some buttons on the remote control. The key presses are shown on the console.

The console output again is parsed directly from the Java process and calls the appropriate methods in the controller. This works brilliant in my case. Yet PulseEight do not recommend using cec-client in a production environment as it is intended for tests only. But well – I didn’t want to invest even more time into coding a perfect cec-java-bridge. Especially as my C-knowledge is very basic. So chances are high that my implementation would be far from “production ready”, too.

WE ARE DONE

That’s it! And of course, you can fork the complete project on GitHub!


Part 1Part 2Part 3


Take care when logging Exceptions!

Today I was facing some weird nullpointer exceptions (NPEs) in my Android App (Beta phase, luckily). Usually I catch exceptions like

try{ .. }catch(SomeException e){ 
   logger.info("A SomeException occured, but i got it.", e) 
}

Well in this part of the code I broke with my habit and wrote:

try{ .. }catch(SomeException e){ 
   logger.info("A SomeException occured, but i got it: "+e.getMessage(), e) 
}

And guess what. I experienced the expected exception, caught it (great) – and got a NPE somewhere in the Loggin framework. WTF?
After having a quick look at the Throwable API, I realized that getMessage() can indeed return null. And String+null produces null. So I nulled my logging message and passed this null reference right into the logging call – which produced the NPE in there. This was very annoying as I successfully caught the first exception – just to produce a susbsequent error during handling the first one.

Well, I immediately grepped my whole project for any strings like .getMessage() and checked for any other NPE traps.
Lesson learned today: carefully check the Api docs and be even more paranoid for NPEs.
Yet one question remains unanswered: Why on earth would one like to return null references in exceptions instead of empty strings?!

IllegalStateException: Content has been consumed

When working with Android or (to be more general) Apache HttpComponents, one should keep in mind that it depends on the HttpResponses (Api: Apache, Android) if they can be consumed multiple times or not. And if the response is not, then better triple check your code, what you’re doing.

I experiences the (very ugly) issue during the apparently simple task of reading the content of the response. )For ease of simplicity, I also use Apache commons-io, to read buffers etc.)

HttpResponse response = ...;
String content = IOUtils.toString(response.getEntity().entity.getContent());

Okay, how many possible Nullpointer Exceptions do you see? I didn’t care until I experienced the first one, so I made the code NPE safe:

HttpEntity entity = response.getEntity();
// entity can be null according to the docs!
if (entity != null) { 
    // The interface doesn't say that getContent() MUST return non-null
    InputStream stream = entity.getContent(); 
        if (stream != null) {
            tempContent = IOUtils.toString(entity.getContent());
        }
}

And suddenly I was faced with IllegalStateException: Content has been consumed. As I also did changes somewhere else, I assumed the error in some toString()-Methods that would read the content of the response during debugging. But as the error also showed up without debugging, I had a closer look to my “improvement”.

Well, the error was the call IOUtils.toString(entity.getContent()); which tried to re-aquire the Input Stream. But as I just aquired it two lines above for the null check, the content was already marked as consumed. So the (now hopefully) correct and robust code is:

HttpEntity entity = response.getEntity();
// entity can be null according to the docs!
if (entity != null) { 
    // The interface doesn't say that getContent() MUST return non-null
    InputStream stream = entity.getContent(); 
        if (stream != null) {
            tempContent = IOUtils.toString(<strong>stream</strong>);
        }
}

And the moral of the story

Be very carefull when reading HttpResponses! Also avoid pretty-printing the content in toString() – this might suddenly also consume your content. And good luck finding the point where you consume the content in such cases.

But .. why?! Please avoid returning null!

Yet I still wonder, why so many methods are allowed to return null instead of just an empty stream or something. All the Null-checks don’t make the code more readable. Some programmers might even be tempted to simply put an catch(NullPointerException e) around the part of

response.getEntity().entity.getContent()

. Nothing I’d really recommend but I could also understand if I’d see something in other code.

Tomcat MongoDB Authentication Realm

Tomcat MongoDB Authentication Realm

Tomcat provides a nice and powerful mechanism for authentication by the so called Tomcat Authentication Realms.
In the Tomcat Docs, Realms are explained as:

A Realm is a “database” of usernames and passwords that identify valid users of a web application (or set of web applications), plus an enumeration of the list of roles associated with each valid user. You can think of roles as similar to groups in Unix-like operating systems, because access to specific web application resources is granted to all users possessing a particular role (rather than enumerating the list of associated usernames). A particular user can have any number of roles associated with their username.

Continue reading Tomcat MongoDB Authentication Realm

A basic Java WebApp example project supporting an xml free Jersey REST config

RESTful Webservices are an essential and convenient part in current web applications when Information should be exchanged. Additionally the main exchange formats in current webservices are either JSON or XML.

So when we want to implement the serverside of a web application using Java and especially REST services, we might end up serializing and deserializing objects to and from XML and JSON. Honestly not a very desirable task. But fortunately there is the Jersey project which can help us in this task.

Continue reading A basic Java WebApp example project supporting an xml free Jersey REST config

An introduction to the Logging framework (a.k.a. System.out.println is evil)

Motivation

One of the first lines a programmer will write in a new language is surely “Hello World”. In Java you can write to the console or to the error stream quite easy with a simple System.out.println("Hello World") or System.err.println("Hello Error"). Great! When the code grows, bugs creep into the code and make live a bit harder. At this point programmers should definately start a deep and loving relationship with the debugger that is delivered with the IDE instead of using System.out/err.println() as debug method. Nevertheless – there are at cases, where a Debugger cannot (or hardly) be applied:

  1. The code runs in the IDE but not if startet directly. – What the hell’s going wrong?
  2. Handling of exceptions. An exception indicates a state that should not have happened and therefore it might be considered to be logged.
  3. The code is deployed to someone else and you cannot attach the debugger to his/her machine.

At either point, beginners tend to use System.out/err.println() to trace the execution path. While this might be okay if the onlyone that is using the code is the programmer alone, this can be very annoying if you are working in a team: If you forget to remove the debug messages, you’re polluting someone elses console output. Even worse: if the code is deployed to a client which reports an error, you cannot raise/lower debug levels or just enable/disable debugging. Do you really want to send a “debug version”? (No you wouldn’t.)

Continue reading An introduction to the Logging framework (a.k.a. System.out.println is evil)

Rooting and upgrading my HTC Tattoo to CyanogenMod 7

Yesterday I decided that the days of my HTC Tattoo running original HTC-Android-1.6 were numbered – finally. Actually the thought about updating was in my mind for QUITE some time. But with all the different how-to-update guides and “oh my god I broke my phone”-posts, I was really frustrated and unsure if I should really risk to “brick” my phone (a.k.a.: turn it totally unusable).

Well okay – so I crawled the web once more for an up-to-date update guide. Well – to make a (rather) long story short: I achieved my goal!

Continue reading Rooting and upgrading my HTC Tattoo to CyanogenMod 7

Research Idea: Evaluation of Traffic Lane Detection with OpenStreetMap GPS Data

I am soon leaving University and thus the time for pure research will soon be over. Unfortunately I still have some ideas for possible research. I’ve tried getting them out of my head as this has not yet worked out, I’ll try to write them down – maybe somewone finds them interesting enough for a Bachelor-/Masterthesis or something like that …

Introduction

OpenStreetMap creates and provides free geographic data such as street maps to anyone who wants them. The project was started because most maps you think of as free actually have legal or technical restrictions on their use, holding back people from using them in creative, productive, or unexpected ways. The OpenStreetMap approach is comparable to Wikipedia where everyone can contribute content. In openStreetMap, registered users can edit the map directly by using different editors or indirectly by providing ground truth data in terms of GPS tracks following pathes or roads. A recent study shows, that the difference between OpenStreetMap’s street network coverage for car navigation in Germany and a comparable proprietary dataset was only 9% in June 2011.

In 2010, Yihua Chen and John Krumm have published a paper at ACM GIS about “Probabilistic Modeling of Traffic Lanes from GPS Traces“. Chen and Krum apply Gaussian micture Models (GMM) on a data set of 55 shuttle vehicles driving between the Microsoft corporate buildings in the Seattle area. The vehicles were tracked for an average of 12.7 days resulting in about 20 million GPS points. By applying their algorithm to this data, they were able to infer lane structures from the given GPS tracks.

Adding and validating lane attributes completely manually is a rather tedious task for humans – especially in cases of data sets like OpenStreetMap. Therefore it should be evaluated if the proposed algorithm could be applied to OpenStreetMap data in order to infer and/or validate lane attributes on existing data in an automatic or semiautomatic way.

Continue reading Research Idea: Evaluation of Traffic Lane Detection with OpenStreetMap GPS Data

TrafficMining Project goes open source

Quite some time ago I wrote about a little demo that was published at SIGMOD 2010 and SSTD 2011 (see post1 and post2).

The TrafficMining project could be described shortly as:

An academic framework for routing algorithms based on OpenStreetMapdata. Actually this framework is not intended to replace current routing applications but to provide an easy to use GUI for testing and developing new routing algorithms on real OpenStreetMap data.

Well, what makes this worth a post is the fact that we finally switched development over to GoogleCode with a discussion group at Google Groups.
GoogleCode has the major advantage of a Mercurial repository, an issue tracker, easy code reviews and an miproved possibility to contribute code. If you just want to follow the development, just join the google group or keep a bookmark to the project’s update feed.

By the way: the PAROS and MARiO downloads can be found there in the downloads section.