Blog

15 May 2012

Classloader leak prevention library

As every Java web developer knows hot deployment doesn't usually work multiple times in a row. Usually the deployment fails due to memory issues (read: memory leaks).

Mattias Jidderhamn has also experienced this and got fed up with it, so he wrote a library that tries to mitigate the memory leaks.

His classloader leak prevention library is available from his blog and from GitHub. It's licensed under Apache 2 license and it's pretty easy to integrate with your project, you only need to add one listener class to you web.xml.

I suggest that you give it a try!


11 April 2012

How to enable GPU acceleration in Android emulator

Everybody who's developed Android applications with the Android emulator has probably noticed that the emulator could be a little bit faster. As the name implies, the emulator emulates the ARM hardware on x86 which makes it quite slow. Fortunately Google has invested some time and resource to make the emulator faster and more pleasant to use. With the lastest update, the emulator can utilize the GPU of the host machine to accelerate drawing operations. This makes the emulator a lot faster. Unfortunately this works only from Android 4.0.3 emulator onwards, but that's a start. Here's how to enable this feature:

First make sure you have the latest SDK and the latest system image for Android 4.0.3 (API 15) installed.

SDK manager

You need to have Android 4.0.3 system image revision 2 installed in order to have GPU acceleration support.

After checking and/or installing the missing updates, open the AVD manager and create a new Android 4.0.3 emulator. You can also update an old emulator instance if you have one already.

New emulator

Set Target to Android 4.0.3 - API level 15. Then add a new hardware property by pressing the New button. Select GPU emulation from the list and press OK. And then set the GPU emulation value to yes. That's all there is to it, press the Create AVD button and start the emulator.

Once the emulator boots up, swipe to different screens and open menus and you'll notice how smooth the animations are. GPU acceleration is a welcomed update to the Android emulator. This feature makes development with the emulator much more pleasant. It also makes the emulator feel more like a real device.


23 February 2012

Calling Android application code from WebView

My earlier blog post showed how an application can call WebView's javascript functions from Java code. This time I'm going to show you how to call Java code from the WebView.

In order to call Java code from a WebView, you need to create a WebViewClient implementation. Basicly this means that you need to create a class that extends WebViewClient class and you need to set your WebView to use it. Below is a simple example of a custom WebViewClient implementation:

private class CustomWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {

        if(url.startsWith("korri://")) {

            Toast.makeText(JSTestActivity.this, "Custom protocol found", Toast.LENGTH_LONG).show();

            return true;
        }

        return false;
    }
}

and this is how you set your WebView to use it:

WebView webView = (WebView) findViewById(R.id.webview);
webView.setWebViewClient(new CustomWebViewClient());

The CustomWebViewClient class overrides on method from WebViewClient, the shouldOverrideUrlLoading method. This method is where communication from WebView is interpreted. The method checks if an url starts with a custom protocol (korri://) and if does, it shows a Toast to the user. The custom protocol is used to distinct communication to the application from normal page navigation. In order to show the Toast, you need to add a link to the html file which is loaded to the WebView. This link has to start with the special protocol, for example like this:

<a href="korri://toast">Show toast!</a>

The example above is very simple and also easily extendable. You could for example create a link to korri://toast/Hello_World and show all text that follows after korri://toast/ in a Toast. This way you can modify the text shown to the user in the WebView.

Calling application methods from WebView doesn't require anything else than this, it's really this easy.

Word of warning though, calling Java code from WebView is always a slow operation. The reason for this is that the browser running in the WebView is native program and the application is running in a VM. So everytime you make a call, the operating system needs route the call from native code to VM. If you make a call here and there, you probably won't notice any performance problems, but if you're doing a lot of them, like ten or more every second, you will notice some slowness.


19 January 2012

Post a form with the Android virtual keyboard

Android form screenshot

The usual way of implementing any kind of an input form, is it on a web page or in an mobile application, is first to add some fields and then some buttons to handle the form submission. So in the basic case, the user first fills the fields and then use the buttons to submit the form.

For ages the web browsers have contained a little shorcut to streamline the process, the enter which submits the form without the need of using the a button for the submission. This is also available in Android with the help of TextView.OnEditorActionListener class.

You can add a OnEditorActionListener to a field or fields and execute methods based on input clicks. For example, if you have login form like the one depicted in the picture, you can easily submit it with the following lines of code:

passwordField.setOnEditorActionListener(new TextView.OnEditorActionListener() {
           
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            handleLogin();
        }
        return false;
    }
});

So now when the user presses the Done button after he/she has written text to the password field, the login is automatically submitted withou the need for pressing a separate Login button.


17 January 2012

First impressions of Nokia Lumia 800

Nokia Lumia 800

In the last days of 2011 I read an review about the Nokia Lumia 800 from a respected blog. The writer wasn't very thrilled about the device and kept saying how his BlackBerry, iPhone and iPad were way better devices than the Lumia 800. In my opinion the review was poorly written and it was obvious that the writer had made his mind about the device even before picking it up for the first time. After reading the review, I knew that I had to test the device myself. So about five minutes after reading the review I ordered myself a Lumia 800 from Amazon and three days later the device arrived.

I've now used the device for two weeks and I like it a lot. Before the Lumia 800, I used Samsung Galaxy S as my primary phone. The Galaxy S is quite decent device, not very spectacular in any way, but quite ok. The Lumia 800 on the other hand is very beautiful device with an operating systems that doesn't try to copy everything from others. If I had to describe Windows Phone 7.5 to an Android or iOS user, I would describe it as different. All the gestures and interactions with the screen components are familiar but the layout and the UI flow is new. I really like that it's different, the last thing we need is another grid based OS which does the same thing as all others. The main menu with the tiles is nice, althought it is a bit of a gimmick, but still it's a fresh idea.

In the two weeks that I've used, I haven't noticed any major issues with the phone or the operating system that would have made me switch back to the Galaxy S. There's a lot more apps available to the device than I initially thought and the bundled Nokia software are a nice addition. I did have some issues when synchronizing GMail contacts to the phone, i.e. the phone couldn't handle invalid data, but I sorted it out by going through the contacts one by one. Some small things I miss from Android, for example turning the volume down doesn't turn the vibration off, but these are small things that hopefully Microsoft fixes with the Tango or Apollo updates.

+ Design
+ WP7.5
+ Nokia Maps and Nokia Drive

- Battery could last a little bit longer
- Contact synchronization from GMail

Overall it's a good phone and an accomplishment from Nokia to get it out so quickly.


06 January 2012

SimpleModal with JQWicket

I was recently asked to implement a modal dialog to a web page that uses Wicket as the presentation framework.

I knew that Wicket contains a ModalWindow class, which creates a modal dialog panel to the screen. This implementation, though, has some drawbacks, for example I couldn't find a way to modify the borders easily and also I didn't find a way to disable dragging of the window.So I tried to look for other out-of-the-box implementations, but I couldn't find any that would have suited my needs.

So in the end, I found a SimpleModal plugin for JQuery by Eric Martin. SimpleModal was just the thing I needed, it was simple implementation and it was easy to modify. Although it did require JQuery, so I decided to implement it on top of JQWicket, which makes it easy to use JQuery with Wicket.

Adding SimpleModal on top of JQWicket was surprisingly easy thing to do. The only things I needed to do were download the SimpleModal Javascript file, attach it to the page header, add proper html and attach a JQBehavior which opens the dialog when a link is clicked.

Source code for the page is simple:

package net.korri.www.example;

import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.markup.html.TransparentWebMarkupContainer;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.request.resource.PackageResourceReference;

import com.google.code.jqwicket.JQBehaviors;

public class ModalPage extends WebPage {

    public ModalPage() {
       
        WebMarkupContainer dialog = new TransparentWebMarkupContainer("dialog");
        dialog.setOutputMarkupId(true);
        add(dialog);
       
        WebMarkupContainer link = new WebMarkupContainer("modal_link");
        link.add(JQBehaviors.mouseClick("$('#"+dialog.getMarkupId()+"').modal();"));
        add(link);
    }

    @Override
    public void renderHead(IHeaderResponse response) {
        response.renderJavaScriptReference(new PackageResourceReference(getClass(), "jquery.simplemodal.1.4.2.min.js"));
    }
}

And the corresponding html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:wicket="http://wicket.apache.org/dtds.data/wicket-xhtml1.4-strict.dtd"
    xml:lang="en" lang="en">
<head>
    <title>ModalPage</title>
    <style type="text/css">
    #simplemodal-overlay {
        background-color: #000;
    }
    #simplemodal-container {
        background-color: #333;
        border: 8px solid #444;
        padding: 12px;
    }
    </style>
</head>
<body>
    <h1>Modal dialog</h1>
    <a href="#" wicket:id="modal_link">Open dialog</a>

    <div wicket:id="dialog" style="display: none">
        <h2>Modal Dialog</h2>
        <p>This is sample modal dialog</p>
        <p>
            You can click <a href="#" class="simplemodal-close">close</a> to close this dialog.
        </p>
    </div>
</body>
</html>

The html page contains some initial css styles for the dialog so that you can see it when it's open.


10 September 2011

Quartz and the update checker

Every programmer has probably at some point used a timer to run a piece of code at some exact time or after some exact interval. If you've used java, you've probably heard about Quartz scheduler.

I've used Quartz in couple of my own projects, but I haven't followed the project recently. Today I decided to rewrite some of my old code and update Quartz to the latest version. Ealier I've used Quartz version 1.6.1 and today when I checked the current stable version is 2.0.2.

I update the quartz jar and refactored the old scheduler code. All in all, everything went quite easily, although at one point I had to look at the example source code to figure out how the new builders are used. Eventually the code compiled and the jobs fired as they should.

One really surprising thing is that TerraCotta has added and update checker feature to the library and it's turned on by default. The update checker contacts the TerraCotta servers and asks for the newest version of Quartz. If you're running an older version, the checker prints a message to the log. It's not obtrusive at all but it's still wholly unnecessary thing to do.

Fortunately the update checker can be turned of but it isn't as easy as it could be. You can add a

-Dorg.terracotta.quartz.skipUpdateCheck=true

startup parameter or you can add

org.terracotta.quartz.skipUpdateCheck=true

to quartz.properties file to disable the update checker. Though both of these methods are unusable in my case.

I don't want to add custom startup parameters and having only the update checker line in quartz.properties doesn't work since you're then missing the default settings. The only usable way disable the update checker was to add

System.setProperty("org.terracotta.quartz.skipUpdateCheck", "true");

call to the initialization code. This is basicly the same thing as adding the startup parameter, but this way you don't have to fiddle with application server startup parameters.


27 May 2011

How to fix Eclipse Helios crashes on Fedora 15

Fedora 15 was released on tuesday 24.5.2011 and it contains the new flashy Gnome 3 desktop and loads of other new stuff. As usual, the new Fedora distribution contains also new versions of the system libraries, including version 2 of the XULRunner. Unfortunately the unmodified Eclipse Helios only support versions 1.8.x - 1.9.2.x of XULRunner and doesn't play nice with version 2.

Eclipse starts ok and most of the features work without problems, but the content-assist is something that crashes the program every time. You don't actually need to press Ctrl+Space to init the crash, hovering the mouse cursor over a variable in the source code is enough.

Fortunately the crashing can be avoided by doing two things:

  1. In Gnome3 the webkit library name changed to libwebkitgtk so you need to create one missing symbolic link: ln -s /usr/lib/libwebkitgtk-1.0.so.0 /usr/lib/libwebkit-1.0.so.2
  2. Add -Dorg.eclipse.swt.browser.UseWebKitGTK=true to eclipse.ini

After doing these two things, the content-assist and the internal browser work once again and they won't crash the whole development environment.


03 March 2011

Android browser and basic authentication

The one thing I like about the Android platform compared to the other platforms is the ability to install software from anywhere you like. The platform isn't locked down to one application source like some of the competing platforms. This ability to install software from multiple sources enables some nice possibilities to the development and testing process. One particularly helpful ability is that when you are developing a custom application, you can send a testing apk to the customer and he or she can install and test it without a major hassle. To take this even further, you can even host the apk on your own web server and the customer can install it from there with the Android browser.

Building an apk and serving it with a web server is a piece cake, but what is astonishing is the fact that if you want to be secure and use basic authentication when serving the apk, Android fails miserably. The built-in Android download manager doesn't support basic authentication at all, something that the desktop browsers have supported for ages. And what's more troubling is the fact this defect has been reported to Google over two years ago and no visible progress on this issue has been made.

Luckily there are a ways to overcome this problem. One solution suggested in the comments of the original bug report was to allow access to all who identify themselves as Android download managers. I'm not a fan of this approach since anybody who knows the url can download the apk without giving any password. My solution to this problem is to server the files through a server side script, php for example, that requires a valid password before any data will be sent. That way the client doesn't need to support basic authentication but the apk will still be password protected.

 


27 February 2011

UrlRewriteFilter with Wicket

Some of you have probably tried using UrlRewriteFilter with a framework that's installed as a filter and noticed that it doesn't work properly. The redirections work correctly but the transparent forwarding doesn't. I've been trying to get it to work with Wicket and I finally figured out what's wrong with my configuration.

I have configured UrlRewriteFilter and Wicket in my web.xml like this:

<filter>
    <filter-name>UrlRewriteFilter</filter-name>
    <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>UrlRewriteFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
    <filter-name>WebApplication</filter-name>
    <filter-class>
        org.apache.wicket.protocol.http.WicketFilter
    </filter-class>
    <init-param>
        <param-name>applicationClassName</param-name>
        <param-value>net.korri.www.wicket.WicketApplication</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>WebApplication</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

But the problem with this configuration is that when the UrlRewriteFilter forwards an url, the other filters will be skipped. So I need to change my filter mapping configutation for Wicket a little bit:

<filter-mapping>
    <filter-name>WebApplication</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>  
    <dispatcher>FORWARD</dispatcher>  
</filter-mapping>

Now all requests and forwards will always be filter by the Wicket filter and so the url forwarding will work. One thing to notice is that the dispacther tag was added in 2.4 servlet specification so you need to be using at least that version. More info about the dispatcher tag is available here.


22 January 2011

Calling Android WebView javascript from Java

Few days ago I stumbled into a javascript problem with Android WebView. I needed to call a javascript method after the a webpage had been loaded. I skimmed through the WebView documentation, but unfortunately I couldn't find any support for javascript calling from WebView, WebViewClient or ChromeViewClient. I even found a bug in the Android bug tracker realted to this, but it hadn't been fixed yet.

Fortunately the solution turned out to be easier than I expected. In order to call WebView javascript from Java, you need to use WebView.loadUrl just as you do when you load an url. So for example if you want to call a javascript function called myTestFunction() you would write it like this:

webview.loadUrl("javascript:(function() { myTestFunction();})()");

You can call multiple functions and insert multiple lines of javascript at the same time. Remember that if you want to use alert() and confirm() functions, you need to create a WebChromeClient class that implements the onJsAlert and onJsConfirm methods.

Update 23.2.2012:

I added a blog post which explains on how to do this the other way around, i.e. how to call Java methods from a WebView. It's available here http://www.korri.net/blog/2012/2/11-calling-android-application-code-from-webview.html


16 January 2011

Spotify links in Linux

When using Spotify in Linux there's one thing that doesn't work out of the box, the spotify links to songs and playlists. Fortunately getting them to work is actually very simple, at least in Gnome. You just need to issue these three commands as the superuser:

gconftool-2 -t string -s /desktop/gnome/url-handlers/spotify/command "/usr/bin/spotify -uri %s"
gconftool-2 -t bool -s /desktop/gnome/url-handlers/spotify/needs_terminal false
gconftool-2 -t bool -s /desktop/gnome/url-handlers/spotify/enabled true

After issuing these commands the links should work everywhere.

Update 23.2.2012:

In Gnome3 you need to modify the /usr/share/applications/spotify.desktop file.

Change Exec to:

Exec=spotify -uri %u ""

and add MimeType to the file:

MimeType=x-scheme-handler/spotify;

After making the changes, run "update-desktop-database -q" as root and the spotify links work once again.


19 December 2010

From server side to Android

Initially published at Qvik - Blog, Behind the BS

I've been building web applications professionally for over five years. I've worked on various platforms with different programming languages, platforms like .Net, PHP, Ruby on Rails and J2EE. In the recent years I've mainly worked on server side Java applications, mostly because there are a lot of this kind of work available and because I enjoy working on something where the development efforts are quickly visible.

Recently I was given an opportunity to develop an application to the Android platform and, since I'm keen to try out new things, I took it. I thought that since Android application are developed with Java, it should be fairly easy thing to do. So now few weeks into development, I'm writing this blog post about my initial impression about the Android platform and development.

The Good

One of the positive things about Android, for me at least, is that the development is done with Java. So there's no need to learn a new language or a new syntax to be able to write code. This also means that you can get an Android project to full speed rather quickly with experienced Java programmers, the only thing they need to learn is the Android way of doing things.

I've also been surprised about how close the Android development is to server side development. Of course there are differences in things like threading, but I never expected to able to use advanced features like Dependency Injection in Android until I stumbled in to RoboGuice. Also the fact that Android projects can be built with Ant means that the dependencies can be sorted with Ivy and builds can be managed with Jenkins.

The Bad

In server side development it's common that projects are divided into smaller pieces called modules. Modules are easier to develop and test since they only focus one or two things. I've tried the same approach with the Android project I'm working on and I found out that it's not that easy to achieve. Everything behaves the same if your modules contain only code, but once you have layouts and assets in them, everything goes to sour. The problem is caused by the Android compiler, which cannot find assets compiled into modules. Although this can be easily avoided by keeping all assets in the same project, it makes sharing code between projects more difficult.

In addition there are couple of things that bother me with the Android development tools. All in all the tools are pretty good and do the job they were meant to do, though the Android emulator could be a little bit faster and why oh why doesn't the emulator log scroll automatically? These are small but irritating things, at least when you run into them multiple times every day.

Summary

Although I only have a few weeks experience with the Android platform and despite those small irritating things, I can honestly say that I like the Android platform. The language is familiar, the development tools are pretty good and the whole programming mindset doesn't differ that much from the server side. With a few weeks under my belt, I'm not wondering the success of the Android platform, it's a pleasure to work with.

Update (7.1.2012)

Lot of things have changed since 2010. One of them being the whole Hudson / Jenkins debacle. Since my preferred CI server is nowadays Jenkins, I updated the links to point to it.