Lova – Java 8 functional interface for AsyncTask on Android

I call the class Lova – in Swedish “to promise something” is “att lova något” .

This assumes you have converted your Android project to compile with Jack.

Warning: Lambdas do not currently work with multidex! See issue 226867.

This implementation only supports a single input parameter to the background task, but it the doInBackground method could easily be changed to send the full array instead.

If you need to report progress or handle cancellation of the AsyncTask, this implementation is too simple.

 

 

Limitations of Apple iOS captive portal web browser

At my employer Softhouse  (the best IT consultancy in Karlskrona, and we’re hiring!) I recently got the requirement to make an AngularJS web application work properly in the captive portal window on Apple iOS.

These requests are made with HTTP header:

User-Agent: CaptiveNetworkSupport-325.10.1 wispr

A captive portal is the login screen you get when you connect to many wifi access points at hotels, airports, and similar. The application works fine in a normal Safari browser on iOS, but not in the captive portal web browser.

The captive portal web browser is almost a complete web browser, but while normal Safari session on iOS can be debugged over USB, it is not possible to debug the captive portal web browser! (If you figure it out, please comment below!)

When I could not access the JavaScript console, I had to resort to debug by displaying application state on the web page.

Finally I discovered that the JavaScript application stopped working after calling Windows.sessionStorage.setItem().

Yes, for reasons hidden in the annals of history the AngularJS application depends on Windows.sessionStorage. The original developers probably had a good reason. Or at least some reason.

The session storage service in the application looked something like this:

return {
   get: function(key) {
      return sessionStorage.getItem(key);
   },
   set: function(key, val) {
      sessionStorage.setItem(key, val);
   },
   unset: function(key) {
      sessionStorage.removeItem(key);
   }
};

So maybe sessionStorage is not defined? I tried a simple:

if (sessionStorage) {
    return {
        get: function (key) {
            return sessionStorage.getItem(key);
        },
        set: function (key, val) {
            sessionStorage.setItem(key, val);
        },
        unset: function (key) {
            sessionStorage.removeItem(key);
        }
    };
} else {
    var session = {};
    return {
        get: function (key) {
            return session[key];
        },
        set: function (key, val) {
            session[key] = String(val);
        },
        unset: function (key) {
            delete session[key];
        }
    };
}

But, same error!

According to Apple’s own documentation on Key-Value Storage, Safari can throw an exception from sessionStorage.setItem() and a Stack Overflow comment states:

I found the same behaviour on Safari to be caused by private mode browsing. It seems that while on private browsing Safari does not allow local storage to be used at all.

Maybe the captive portal works like the private mode  browsing…?

So, let’s try this code:

var hasSessionStorage = !!sessionStorage;

if (hasSessionStorage) {
    try {
        sessionStorage.setItem("hasSessionStorage", true);
    }
    catch (e) {
        hasSessionStorage = false;
    }
}

if (hasSessionStorage) {
    return {
        get: function (key) {
            return sessionStorage.getItem(key);
        },
        set: function (key, val) {
            sessionStorage.setItem(key, val);
        },
        unset: function (key) {
            sessionStorage.removeItem(key);
        }
    };
} else {
    var session = {};
    return {
        get: function (key) {
            return session[key];
        },
        set: function (key, val) {
            session[key] = String(val);
        },
        unset: function (key) {
            delete session[key];
        }
    };
}

Finally, it works!

David’s technology radar

Inspired by ThoughtWorks Technology Radar, here is an attempt to write down my current world view:

Adopt

Trial

  • Mozilla Persona – use the same e-mail address and password to login to many web sites (not so many yet though)
  • OpenShift – cloud application platform
  • “Private cloud” – run your own “cloud” server
  • Raspberry Pi – small and cheap computer
  • Server Sent Events
  • WebSockets

Assess

  • Chef or Puppet
  • Docker
  • Gearman
  • Vagrant

The Inner-platform API anti-pattern

I learned the term Inner-platform effect the other day and it perfectly describes an API that I have touched upon.

First of all, what is the Inner-platform effect? It basically means that in attempt to make an application as flexible as possible it is implemented so that it creates a new platform that abstracts the original platform. I immediately associated to the API described below.

Let’s see if you can spot the Inner-platform effect in this URL, heavily anonymized but if you have been exposed to it you will probably recognize it immediately.

http://server/execute/clientSystemConnector
?service=createUser&key=id&value=97580
&key=name&value=David%20Eriksson&key=city&value=Ronneby

There are actually three examples of the Inner-platform effect in the above URL. The first is example is the “service” parameter. Instead of having separate URLs for separate services, the service name is a parameter. This means that the server platform first figures out what to about the /execute/clientSystemConnector path component of the URL, then the Inner Platform need to figure out how to handle the different possible values of the service parameter. (Anyone thinking about a giant “switch” statement?)  To avoid the Inner-platform effect, each service should have its own path in the URL.

The second example is blatantly obvious: having key and value parameters that specifies the names and values of the actual parameters. The impact of this “feature” is that the platform  provides a list of keys and a list of values to the inner platform, which must extract the actual parameters for use in the application. Without the Inner-platform effect the application could have received the parameters directly from the original platform.

It is probably not so easy to spot the third example, but it concerns authentication. Authentication (if it could be called that) for the services in this API is based on using different paths for different clients. So the above URL is used by the “clientSystem”. If “anotherClientSystem” need to execute the same service, the URL would be:

http://server/execute/anotherClientSystemConnector
?service=createUser&key=id&value=97580&...

So instead of using the built-in authentication mechanism (HTTP Basic Auth) in the platform, the Inner platform goes its own way.

How would I build an API to avoid the Inner platform? Except addressing the above issues I would also make it a POST (or PUT) request, as it handles the creation of a resource.

POST http://server/user/create HTTP/1.1
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Content-Type: application/x-www-form-urlencoded

id=97580&name=David%20Eriksson&city=Ronneby

Goodbye, Inner Platform!

PS. The origins of the API is probably 8-10 years old by now, and maybe it was a good idea at the time.

PPS. See the Inner-platform effect article on wikipedia for more examples.

No application without a library, no web site without an API?

When I wrote the first versions of Dynamite and Unshield (eight and nine years ago!) I decided from the start that each project had to be implemented in two parts: a library (hopefully reusable) and a command line tool using the library. I believe I learned this from cURL and libcurl, and I still consider it a best practice. For the purposes of this article, let’s call it the tool-library pattern.

I don’t do much C/C++ coding these days, even though I have been ogling Spindly – the C89 implementation of SPDY forked from libspdy by cURL author Daniel Stenberg.

For my current clients at work, I do Java coding or webMethods Integration Server development.

When I can spare some and energy for coding at home, it’s mostly web development in PHP, which brings me back to the tool-library pattern: Unfortunately I have not yet started using a smilar practice for my web development.

So what is the web site equivalence to the tool-library pattern? For a web site I mean that the “library” is a web service API that is consumed by the actual web site.  This is called First-Class APIs by Helgi Þormar Þorbjörnsson.

The API does not have to be public, but if it is, any other consumers of the API (for example a Smartphone app) will share the same API (or parts of it).

I’m currently rewriting my Swedish site for colloquial words and expressions from a hack (!) to a proper layered architecture. The next step will be to add new features and I hope to move these into an API.

Pebble – more injection and less dependencies in PHP

Dependency Injection (DI) is hardly anything new. I see it as a must for Test Driven Development (TDD). The thing I like most about DI in Java is Autowired in Spring or javax.annotation.Resource, they way member variables are set “magically” and the exact details about creation and implementation is located elsewhere.

For PHP there are at least the following implementations related to Dependency Injection:

PHP-Dependency (Pd) works with @ annotation in the constructor comment, but why involve the constructor? And is a whole framework needed? PHP is not Java.

Pimple is very much a Dependency Injection Container, not so much about the injection. Simple, yes.

When it comes to Zend Framework 2 Dependency Injection I just can’t grasp how it simplifies anything. It seems to require a lot of boilerplate.

Unsatisfied with the above and a given a dose of NIH Syndrome, I decided to create my own DI system for PHP. After a bit of coding yesterday evening and night I named it Pebble and it is already on github! 🙂

My current requirements on Pebble are as follows:

  1. It must be possible to inject values of specific properties on class construction
  2. It must work nicely in Zend Framework 1.x
  3. It must not require any configuration files (and especially no XML)
  4. It must be a single .php file for the core implementation
  5. It must provide an open interface for extension and customization
  6. It must work nicely with PHPUnit (especially with the getMock method)
  7. It must work with autoloading of classes in PHP
  8. It is allowed to use PHP 5.3 features
  9. It is allowed to use @-based annotations in docComment, e.g. /** @something */

However, I have not yet used Pebble with PHPUnit, so I don’t know yet if that requirement holds!

Now is a good time for you to examine example1.php! The README is currently plain-text, I’ll format it later!

Blogging, sharing, status updates, everywhere?

I’ve realized a long time ago that my personal web diary in in Swedish – 2good.nu – has been obsoleted by my Facebook account. Same with the diary for our first-born child. I didn’t even start a blog for our second child.

This is quite OK, as my home-made web diary software – even rewritten in Zend Framework – will never have the same features as Facebook. There are no comments, photo uploads, likes, mentions of friends, etc, that the existing social networks already implement.

Of course I also have a Twitter account, @davideriksson, that complements this blog with mostly English-language updates regarding software development and related topics. I actually use Google Buzz for sharing some stuff with friends, and it is also connected to my Twitter account.

I never use my Orkut account so let’s ignore that. Should I mention my LinkedIn account? By its nature it is almost purely for my professional relations.

Now comes Google+ and I will give it a try as soon as they accept the invitation I have. Should I spend/waste my time on yet another social network, connected to more or less the same people?

What I want is to publish stuff (blog posts, links, photos, videos, status updates) in one place, and have it reach the desired target group (or Social Cicle, in Google+ speak). Something like Diaspora sounds like a good idea, but it is not click-and-play and does it integrate with the other social networks mentioned previously? I’m not so sure.

Ideally I publish something on Facebook and it ends up in the corresponding social circles in Google+, and the other way around.

Another solution would to be that I publish everything from my personal site, and it pushes it to the corresponding systems. Maybe I have to implement photo upload after all? And build an Android client? No, I should not have to.

A better solution would be that a single social network is my “main” one and it provides an API that I can use to share data to other social networks. Maybe Google+ is that social network, but it does not have a public API yet. I still have to build stuff, but integrating systems is much more fun than implementing photo upload… 🙂

To see what others publish I realize that I still need to connect to each social network, but I’m probably curious enough!

The Book Of JOSH is back online!

A little more than a year ago I wrote Recommended reading: “The Book Of JOSH: Scala In The Enterprise”. Since then, the original article was removed from the author’s blog and I didn’t know of any copies.

The other day I was browsing already read articles in Google Reader, and found the article in Google Reader!

As I like the article very much and still would like to recommend it to others, I have decided to host it myself: The Book Of JOSH. Enjoy!