Containerizing the W3C Mobile Checker App

I had been looking for some type of tool that would be similar to what the Google Mobile-Friendly Test web app does. For internal enterprise apps, the Google tool doesn’t help too much as it can’t see them. Eventually, I came across the W3C Mobile-Checker. This does most of what I’d need to do, but it’s deployment is a bit of a challenge. To simplify things, I thought it might be a fine idea to package it up using Docker.

The first thing to note is that the W3C Mobile-Checker has a bunch of dependencies such as:

The number of processes violates the Docker best practice of running only a single-process per container and I am not a big fan of approaches like the ones advocated by the Phusion Baseimage-Docker container. But in the interest of simplifying deployment, I figured might be okay for this type of app. This of course means running something like supervisord.

The first big challenge was figuring out how to get XVFB running in Docker. Thankfully, Linuxmeerkat has an excellent post on running a GUI application in a Docker container, which was incredibly helpful in setting this up. One thing that was interesting was that it seems like Chrome has changed quite a bit as there was no need to run the container in privilaged mode. From there, the rest of the set was pretty straight forward and I hacked up supervisord config that looks a bit like this:

[supervisord]
nodaemon=true

[program:browsermob-proxy]
command=/opt/browsermob-proxy-2.1.0-beta-1/bin/browsermob-proxy --use-littleproxy true

[program:Xvfb]
command=/usr/bin/Xvfb :1 -screen 0 1920x1080x24

[program:node]
command=/usr/bin/node /opt/Mobile-Checker/app.js > /dev/stdout

The full code is up on GitHub here. It’s also published to Docker Hub and you can run it like so:

    docker run -p 3000:3000 damnhandy/mobile-checker-docker

I’m still figuring out how best to package the Node.js app itself. Right now, the build on Docker hub contains a snapshot of the Mobile-Checker version at the time it was built. The one upside of using supervisord here is that it respawns the Mobile-Checker app each it crashes, which is quite often. But at any rate, this type of set up gives you can idea how one could do automated browser testing using Docker.

On Describing Push Notifications in Web APIs

A few weeks back, I attended my first RESTFest “unconfernece””. This was a really great event put on by some fantastic folks. The “everyone talks” aspect of RESTFest is actually awesome idea for a conference this size. This format is great because if you’re like me, you had some things you wanted to get some feedback on and this provides the forum to do just that. Everyone gets a chance to do a quick 5-in-5 talk about anything. I was looking to get some feedback on some ideas I’ve been considering about push notifications in Web APIs.

I titled my talk “Real-Time Web APIs,” but I’m no so much interested in Web APIs that follow “real-time computing” constrains. Really, I’m looking to see if there’s a good way to describe a service that streams push notifications from a Web API that follows “RESTful” architectural constraints. There’s a lot of good ideas out there, but many of them either assume that the client either a web browser or running an HTTP server. Additionally, the mechanism to describe these services need some work.

The Goal

The core building blocks for push notifications are already available, but not so much the means that aid in discovery and the description of such resources. I’d like to be able to organize these pieces so that the following requirements can be met:

  1. Don’t assume that the subscriber is able to receive a callback using HTTP POST. If the subscriber is a web browser or a thick desktop client like a Swing or JavaFX application (yes, people still make these!), or even a nativ app on iOS, running a web server to receive and HTTP callback isn’t always practical or feasible.
  2. Advertise that a given link is exposing a stream of events via a link relation. This might be similar to the monitor link relation, but not necessarily bound to SIP.
  3. The link relation should be able to indicate the media type that event messages are described in, ideally via the type property.
  4. If there’s a sub protocol involved, it should also advertise what sub-protocol. If event stream is a media type that supports embedded content, it should also express that as well.
  5. Subscribing to a stream or feed should be simple

WebSockets and HTM5 Server-Sent Events (SSE) present some interesting opportunities for Web APIs that demand low-latency push notifications while also removing the need for a consumer to run an HTTP server. Keep in mind that I’m not talking about doing something like “REST over WebSockets (Shay does make some great points though!),” I’m simply looking for push notifications without the need for for the consumer to run a web server as well as describing the stream via link relations. I think it could be done, but there’s some missing bits.

PubSubHubub

PubSubHubub ticks a lot of check boxes for me, such as:

  • While the protocol is built around Atom and Atom concepts, it could support a variety of media types. It’s using the Content-Type header to express what is coming over the wire.
  • It sports a discovery model using the rel="hub" link relation either in a link header or a link within an Atom feed.
  • The subscriber subscribes to the Topic URL from the Topic URL’s declared Hub(s) using the PubSubHubbub subscription protocol.
  • Publishers ping the “Hub” to notify it of updates, aggregates the content, and sends it to the subscriber using an HTTP POST request to the call hub.callback URL.

What I like about it a lot is the use of hypermedia to do discovery and call backs. Additionally, it’s using standards means to describe what’s coming over the wire. The rel="hub" link relation combined with the script ion protocol is super easy an fit works. My challenge with PubSubHubub is the requirement of an HTTP callback on the part of the subscriber. As stated earlier, this isn’t always possible.

From my perspective, PubSubHubub has the right foundational model. It’s simply HTTP callbacks that are the sticking point. So can we do something similar with WebSockets or Server-Sent Events? I think so, but there’s some challenges with existing formats in order to make this work.

Server-Sent Events

I REALLY like HTML5 Server-Sent Events (SSE). A lot. I’m also really annoyed by the fact that Internet Explorer still isn’t supporting SSE in IE11. What I like about SSE is that it’s a media type (text/event-stream) so the subscriber will know that this URL represents an event stream. The event stream model is also dead simple:

event: change
data: 73857293

But it could be also like this:

event: change
data: {"@id" : "15628", "@type" : "ChangeEvent",  "value" : "73857293" }

Or even this:

event: change
data: {
data: "@id" : "15628", 
data: "@type" : "ChangeEvent",  
data: "value" : "73857293" 
data: }

Or like this (If you’re into this sort of thing):

event: change
data: <ChangeEvent><id>15628</id><value>73857293</value></ChangeEvent>

As you can see, the data field could contain nested media type like XML, JSON, or something else. The problem is that that there is no way to indicate that. How does one know that the data field contains structured content such as JSON? The browser gets around the issue by embedding JavaScript in an HTML document that references the stream:

var source = new EventSource(’/updates');
source.addEventListener('add',  changeHandler, false);

Obviously, the changeHandler function will parse and handle the embedded content. This works great where the subscriber is a web browser (or embedded browser), but for other environments it’s not so easy.

We could express this via a link, but it’d be missing some details. Let’s assume we have a link relation called stream that informs a client that this link represents a stream of events:

Link: <http://example.com/events>; rel="stream"; 
      type="text/event-stream";

It works and declares that the link is a stream of event and it exposes the events via SSE. But the subscriber has no hints that the data field contains JSON or XML content. In cases where the browser, or an embedded web browser, are not available, how does can a client get more information as to process a stream? For SSE, one option might be to include a media type parameter, call it data if you will, that would indicate that the nested type is something like JSON-LD:

Link: <http://example.com/events>; rel="stream"; 
      type="text/event-stream;data='application/ld+json'"

It’s just an idea, but it could be workable. I would love feedback on this and would REALLY like to see Microsoft add Server-Sent Events to IE at some point.

WebSockets

WebSockets are neat, but the majority of use cases for streaming notifications only really needs to go one way. The bi-directional nature of the WebSockets protocol is a nice to have but not entirely necessary for most applications. WebSockets by itself really isn’t that useful. A number of WebSocket examples you’ll see are effectively someone’s home-grown, JSON-based, socket protocol. It’s a bit too cowboy for my tastes, but it can get the job done.

Where I do find WebSockets more useful is being able to leverage a well-defined subprotocol over a WebSocket. At the moment, I’m quite of fond of STOMP, particularly STOMP over WebSockets. In a Java shop that is already heavily invested in JMS, STOMP over WebSockets is a reasonable leap given that tools such as ActiveMQ, RabbitMQ, and others are support STOMP over WebSockets now.

Building on the Server-Sent Event examples earlier, we have some similar problems such as:

  • We still don’t have a good way to indicating what might be coming over the wire
  • We have a new problem since we’re dealing with another protocol that supports subprotocols, we don’t have a means to identify the sub-protocol that the WebSocket will be using

At RESTFest, I crapped up a variation of link relation like so:

Link: <wss://example.com/events>;rel=”stream/v12.stomp";
       type=“application/ld+json";

Here, we’d overload the rel field to indicate that it’s a stream but that it’s also using STOMP as the sub-protocol, specifically STOMP v1.2 (note I’m using IANA WebSocket subprotocol IDs here). Because the URI begins with wss://, we know that we’re using WebSockets over SSL. The type property is indicating that the messages will be using application/ld+json. The problem with both approaches is that if I want to offer another alternate message formats (say JSON-LD or XML), then this solution does really work. But maybe that’s not a problem.

Constrained Application Protocol

One of the great things about attending a workshop like RESTFest is that you’re surrounded by people who are smarter or more experienced than you. After my 5-in-5, Mike Amudsen had a few good questions about what I was trying to do. He then asked if I had considered CoAP, or the Constrained Application Protocol. Having never heard of CoAP, I obviously hadn’t taken it into consideration. CoAP more than likely satisfies a number of my needs. Since it’s still in draft form, it’s not an easy sell yet. Without a doubt, CoAP is something to keep an eye one.

Wrapping Up

Right now, I’m going down the STOMP over WebSockets route. I’d REALLY prefer Server-Sent Events, but the fact that Microsoft isn’t supporting SSE in IE10 and IE11 is AND the corporate standard in most shops, it sadly makes SSE a non-starter. In the coming weeks, I’ll be slapping some code up on GitHub to test out some ideas. I’d love to get feedback on these ideas to see if I’m going off the rails or if these ideas have some merit.

Handy URI Templates 2.0.1 is out

After a months of not blogging and kind of working on my URI Template library, I finally managed to get out version 2.0.1. The new API makes a quite a bit of changes and it does break some things in version 1.x. Here’s a run down of what has changed:

  • Better error handling. The API can now be more specific about what the error was and more importantly, where it was.
  • The code was refractored to support and internal model, which will help support reverse matching.
  • A new UriTemplateBuilder API for programatically creating URI templates
  • Support for Jackson serializer/deserializers

Overall, it’s cleaner and easier on the eyes. Now to wrap up reverse matching.

Handy-URI-Templates 1.1.7 Released

Yesterday Handy URI Templates 1.1.7 was released which fixed a few uritemplate-test issues as well as some URI encoding fixes. Hat tip to tekener for those fixes.

With that out of the way, I’ll be focusing on 1.2 which will change the API a bit, but will finally add reverse mapping so that you can use it to match request URLs to a URI template pattern. It turns out that this is a bit more complicated than I first imagined. A number of folks have pointed to the excellent wo-furi project as this already does reverse mapping. However, it only handles level 1, and maybe level 2 templates. Things get hairy when you start reverse mapping level 3 and level 4 templates.

Handy Aspects Moved to GitHub

A few years back, I dabbled a bit with Aspect Oriented Programming and dorked around with JBoss AOP and AspectJ. I created a few aspects an threw them up on Java.net. Over the years, I never really kept up with maintaing the project. Since then, Java.net migrated projects and Handy Aspects was removed. Since then, I have received a few requests for the code and I planned on moving it to GitHub.

But rather than simply throwing the code up there “as-is”, I decided to bring the project up to date a bit. For example, I moved the build from Ant to Maven and brought the dependencies up to the latest versions. I also removed JBoss AOP version and everything is now based on AspectJ. With that said, you can follow and fork the new project Handy-Apsects project here.

I want to like SCXML, but executable XML is a bit of a two-bagger

Over the past few days I have been reading up on the State Chart XML spec. Ever since reading some of Stu Charltons ideas on a RESTful Hypermedia Agent and listening to his WS-REST keynote presentation, I’ve taken more of an interest in hierarchical state machines and began taking a more in-depth look into SCXML.

The design of SCXML is interesting. I like the ECMA Script functionality and XML structure feels clean at first. It all seems fine until you get to the section on executable content. There’s a bit of debate around “executable xml” and executable XML frameworks like Jelly. And even folks poking fun at the idea of an XML programming language. As a Java guy, I have grown to dislike build tools such as Ant due to the fact that one can express relatively complex conditional logic in XML. I like tools like Maven better since it’s XML model is more declarative rather than executable (profiles are conditional). When I need more complex build operations, I’d be looking at tools like Gradle. Don’t get me started on XSLT.

I really like the concept of SCXML, but I’m not sold on the design. I don’t really have issue with the use of XML in general, I get it. However, the executable XML content bit is really hard to get past. Expecially when a scripting evironment is available to the SCXML environment. I can debug JavaScript code with a number of tools. Executable XML content? Not so much. For me, the executable content bit is the technical equivalent of a two-bagger.

Handy URI Templates 1.1.2 Released

After a few weeks of tweaking, I put out a new release of Handy URI Templates. What’s important about version 1.1.2 is that it is now being tested against the uritemplate-test suite started by Mark Nottingham. Most importantly, it is also now passing all tests. Additionally, this release also marks the introduction of expression validation as well. If you’ve been using the 1.0.x versions, I’d highly recommend moving up to 1.1.2.

Fun with URI Templates and the Facebook Graph API

URI Templates can make interacting with the web APIs like the Facebook Graph API a little easier. Here, I’ll show you how you can use URI Templates to create request URIs into the Facebook Graph API using the Handy URI Templates library. The URI Template examples described should be usable by any RFC6570 URI Template processor, but I’ll be focusing on how to use the Handy URI Templates API in Java. If you’re using PHP, have a look at Michael Dowling’s excellent Guzzle Framework which has great URI template support.

URI Template Basics

We’ll assume you have some familiarity with URI templates. Basically, a URI template is expression where replacement variables are identified by the text between ‘{‘ and ‘}’, like so:

https://graph.facebook.com/{id}

Where {id} is the name of the variable. This is similar to how paths are expressed in JAX-RS, and OpenSearch URL template syntax . The RFC6570 spec provides a lot more details on the URI template standard syntax, so we’ll focus on how to use URI templates in conjunction with the Facebook Graph API.

Facebook Graph API Basics

For the most part, most URIs in the Graph API follow the basic pattern of hostname + id. In a URI template, this pattern can be expresed as:

https://graph.facebook.com/{id}

When the template variable is expanded, it will allow you to create URIs that can be used request resources like so:

And so on. Facebook also requires you to supply the access_token in a query parameter on the request URI, so now we end up with the expression:

https://graph.facebook.com/{id}{?access_token}

Please check the Facebook documenation on how to get the token.

Using the Handy URI Templates API, you can create a URI from an expression like so:

String expression = "https://graph.facebook.com/{id}{?access_token}";
String uri  = 
   UriTemplate.fromExpression(expression)
              .set("id", "bgolub")
              .set("access_token", System.getProperty("fb.access_token"))
              .expand();

This will give you the following URI:

https://graph.facebook.com/bgolub?access_token=your_fb_access_token

Because the {id} variable can contain sub paths, we need a way to express that. If we have want to express a URI template that gets a users information or the users photo albums, we need additional path segements. We could use multiple path segments with more variables, but this can make the template more complicated. One option is to modify the expression so that {id} can accomodate a single path segement or multiple path segments by rewriting the expression as:

https://graph.facebook.com{/id*}{?access_token}

This does a few things:

  • By putting the path ‘/’ operator in the variable expression, we’re stating that the values in this variable path segements. By default, if the variable values is an array, Collection or Map, the values will be ‘,’ delimited.
  • The * modifier means ‘explode’. With an array or Collection plus the explode modifier, the values will be delimited by the ‘/’ operator.

Now if we change the code a little bit:

String expression = "https://graph.facebook.com{/id*}{?access_token}";
String uri =  
    UriTemplate.fromExpression(expression)
               .set("id", new String[] {"bgolub","albums"})
               .set("access_token", System.getProperty("fb.access_token"))
               .expand();

You’ll note that the value we pass to the id variable is an array of strings and the processor will render valuse as two strings separated by a /.The resulting URI is now:

https://graph.facebook.com/bgolub/albums?access_token=your_fb_access_token

Now lets see how we can make more advanced types of requests.

More Advanced Requests

The Graph API has a number of query parameters that modifiy the request. All of these are defined in the Facebook Graph API documenation so I won’t detail them here. With all of the query parameters collected, you end up with the following URI template expression:

https://graph.facebook.com{/id*}{?q,ids,fields,type,center,distance,limit,offset,until,since,access_token}

You can pretty much use this template express for the majority, if not all, of the Facebook Graph API. We’ll use that expression for rest of the examples.

Search Request URIs

With the URI template, we can create URIs that map to Graph API search requests. Using the “coffe” example from the Facebook documenation:

String expression = "https://graph.facebook.com{/id*}{?q,ids,fields,type,center,distance,limit,offset,until,since,access_token}";

String uri = 
    UriTemplate.fromExpression(expression)
                .set("id","search")
                .set("q", "coffee")
                .set("type","place")
                .set("center", new float[] {37.76f,-122.427f})
                .set("distance", 1000)
                .set("limit", 5)
                .set("offset", 10)
                .set("access_token", System.getProperty("fb.access_token"))
                .expand();

This will give us the URI:

https://graph.facebook.com/search?q=coffee&type=place&center=37.76,-122.427&distance=1000&limit=5&offset=10&access_token=your_access_token

Note how the variables until and since are not included in the expanded URI.

FQL Request URIs

Even things URIs with FQL queries can be expressed in a template. Give our code:

String expression = "https://graph.facebook.com{/id*}{?q,ids,fields,type,center,distance,limit,offset,until,since,access_token}";

  String uri = 
    UriTemplate.fromExpression(expression)
               .set("id","fql")
               .set("q", "SELECT uid2 FROM friend WHERE uid1=me()")
               .set("access_token", System.getProperty("fb.access_token"))
               .expand();

Wrap Up

Hopefully this gives you a good idea on both how to use URI Templates in general, and a good insight into how you can use teh Handy URI Templates API. If you want more exmaples, have a look at the code on GitHub here. There are examples for Facebook, Twitter, and GitHub.

A URI Templates Implementation for Java

In my copious spare time, I have managed to cobble together an initial implementation of the URI Templates spec (RFC6570),  for Java. The project is up on GitHub here:

http://github.com/damnhandy/Handy-URI-Templates

The majority of the documentation is available in the README file, so have a gander at that for details on how to use it. It’s in the initial phases right now, but it’s a good time to kick the tires and provide feedback.