Andrew Maddison

Flowerchild.

Java Generic Type Class Arguments and Generic Methods Syntax

I always have trouble finding the syntax for writing a method that takes and returns a generic type, and even more frequently the syntax for passing generic types to a generic method (eg, passing a List<Something>). This is a common pattern when deserializing JSON from http responses back into objects. So for my own easy retieval in future, here it is.

First the simple case – a generic method (just wrapping a call to a Javax Response.readEntity)

1
2
3
4
5
6
7
public <T> T genericMethod(Class<T> type) {
    Response response = someMethodThatGetsDataAndReturnsTheResponseObject();
    return response.readEntity(type);
}

//calling code:
SomeType result = genericMethod(SomeType.class);

And here’s the syntax of a method that takes a GenericType object as argument (ie, which can take the class of a generic type as an argument), and for the calling that generic method.

1
2
3
4
5
6
7
8
9
10
import javax.ws.rs.core.GenericType;
...

public <T> T genericMethod(GenericType<T> type) {
    Response response = someMethodThatGetsDataAndReturnsTheResponseObject();
    return response.readEntity(type);
}

//calling code:
List<SomeType> results = genericMethod(new GenericType<List<MrdArticleCitationDto>>(){});

One of the trickier aspects of this whole game, is what to name the identifier of the type parameter. You cant call it “class” as that’s a reserved keyword and opinion seems to be divided between “clazz” and “klass”. In this example I’ve opted out and called it “type”.

comments

Overloaded Methods, Varargs, Single Arguments and Recursion in Java

This is another “documenting my own stupidity” post. I’m hoping the public self-ridicule will help stop me from being so short sighted in the first place.

I’m sure lots of people use the following pattern. You write a method that takes a heap of arguments, but which can have some defaults. You then introduce one or more overloads, with progressively fewer arguments, and sensible defaults filled in.

To avoid duplication of your actual logic, the overloads only add the defaults, and then call the original, many argumented method. For example:

Original pattern:

1
2
3
4
5
6
7
8
9
public String doSomething(){
    //No logic here, just a call to the next method down with a default.
    return doSomething("default-value");
}

public String doSomething(String argument) {
    //does something - very complicated, you don't want to duplicate this.
    return argument + " or summat";
}

So that was fine, But then things moved on, and I needed to introduce a little more complexity in the form of an unknown number of arguments using varargs. So I simply added a new method, migrated the logic and refactored to something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//we refactor the other methods - still don't want duplication
public String doSomething(){
    //No logic here, just a call to the next method down with a default.
    return doSomething("default-value");
}

public String doSomething(String argument) {
    //want to call the varargs based method below:
    return doSomething(argument);
    //Hmm - that's not going to work - it's just going to recurse.
}

public String doSomething(String ... lotsOfArguments) {
    //does something - even more very extremely complicated, and you still don't want duplication
    return StringUtils.join(authors, ",") + " or summat";
}

The middle method in the above snippet doesn’t work (and throws infinite recursion warnings) as it simply calls itself, rather than the varargs method with a single argument.

What confused me is that I googled about a bit, and couldn’t find any discussion of what to do in this case, so I tried the following, and felt pretty pleased with myself.

1
2
3
4
5
public String doSomething(String argument) {
    //want to call the varargs based method with the logic in:
    return doSomething(new String[]{argument});
    //take that Java
}

But of course – I was completely missing the point. I didn’t need the single argument overload as calls with a single argument already call the varargs overload! So it just needs deleting – and happy days.

1
2
3
4
5
6
7
8
9
10
//Delete the single string argument - it was a rudundant fossil anyway.
    public String doSomething(){
        //No logic here, just a call to the next method down with a default.
        return doSomething("default-value");
    }

    public String doSomething(String ... lotsOfArguments) {
        //does something - even more very extremely complicated, and you still don't want duplication
        return StringUtils.join(authors, ",") + " or summat";
    }
1
2
//calling code: works fine
String resut = doSomething("single string");

Works fine if you delete the single argument method. Of course. Face palm.

comments

NVM Node Version Manager .nvmrc File So You Don’t Need to Install or Use Every Time

I installed NVM to manage node installation, but was irritated, because I had to run “nvm install” or “nvm use” every time I opened a new bash session.

It turns out there is a poorly documented feature, the .nvmrc file. Simply drop one into your project folder, and in it just put the version number of node (or one of NVM’s aliases, such as ‘stable’).

1
   stable

As simple as that! Then open a new bash session and browse to your folder, node should be up and running.

comments

TFL Live Bus Departures a Little Usability

TL:DR If you’re at an unfamiliar bus stop in London and don’t know when the next bus is arriving, visit this little page that I’ve written to help find bus stop departures pages. Just type the number into the box and hit ‘Go’!

Any bus Stop on Chrome's iPhone 4 simulated display size

Longer: All this does is provide a light, mobile optimised (ish – see below) page that redirects you to TFL’s existing mobile departures pages. It’s pointless, and TFL do have such a page of their own now. But most of my pet projects are more about having fun and solving a problem.

So, for this project I’ve used some things, and learnt some things:

  • It’s static html, javascript and CSS
  • My first attempt (outside work) using Media Queries to create a not-awfull small screen experience.
  • I’m using SASS
  • Compiled with Gulp
  • Which required the grokking of NVM to install Node to get NPM working to install Gulp (it’s package managers all the way down).

It’s also my first (fairly unsuccessful) attempt at a mobile first design. It’s already looking better than it did thanks to some of my awesome colleages helping me out a bit.

It’s all on github here (unusual for me, as I usually use bitbucket). Pull requests welcome.

PS – I think this would be awesome on a .London domain name, but they cost about £30, so that’s not happening unless someone want’s to sponsor me!

comments

Making a Custom Brio Compatible South West Trains Class 444 Desiro

This is a writeup of how I made a custom toy South West Trains class 444 for my 2 year old niece. Or at least, a writeup of the bits I can remember.

The first thing I did was lookup a photo of the relevant train (google images) and doodle a sort of caricature of it onto a post-it note one lunchtime at work. The gist was to simplify the look so that it would look reminiscent of the real thing but sufficiently “toy like” that it doesn’t look over detailed and fussy on a model only 11cm long.

For example – 10 windows becomes 4, or even 3 on the driving ends, the driver’s door vanishes, as do the corridor’s between coaches and lots of little outline details etc etc.

My Custom Brio style toy SouthWest Trains Desiro Class 444

I formulated a plan to find an existing Brio compatible train, cannibalize the wheels and bogies, knock up a new wooden body, and join it all back together. Then I discovered that BigJigs sell a wagon that is simply a rectangular block already.

BigJigs Wagon, unmodifed and modified. With Gordon for scale!

I bought six of these, sanded off all the paint, unscrewed the bogies and wheels, and sprayed them with a toy-safe aerosol white primer/undercoat. I then carved the ends into a simple approximation of the driving ends of the class 444 trains.

Carving a wooden toy train

Next I learnt how to use Inkscape (this was actually a bit of a joy to learn and use) and drew up a design as an SVG. I drew the side view first, which I then extended to span the roof and opposite side. The full drawings are available to download from bitbucket here. They’re free for your own use, legal bit follows:

This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/4.0/.

The simplified side-only view is shown below.

My Custom Brio style toy SouthWest Trains Desiro Class 444

The first attempt at getting the design from computer to toy was not successful. I read that you can use iron-on inkjet t-shirt transfers on wood. The short answer is you can’t. The longer answer is that when you heat it with an iron, the transfer melts and becomes very slimy and slippy, at which point it slips and smears all over the place. Your mileage may vary, but I gave up.

The second plan was to try getting some inkjet water-transfer paper. But because I was up against a deadline (Christmas) I ran out of time to order some off the internet. I’d still like to try this, but at the time I fell through to plan C.

My final attempt was simply to print the design out on paper, and glue it onto the model. I painted the ends black and yellow by hand. The end result actually looks OK. I then lacquered the whole thing with a toy-safe semi-gloss aerosol varnish/lacquer. When it was all dry, I simply screwed the bogies back on (making sure to check the magnetic couplings were in north/south matched pairs, and that the two driving cabs had the opposite polarity, so they would join together) and I was done.

A quick note on toy safety. There are lots of European standards on things like toxicity of paints, and more importantly – small parts that could be a choking hazard. This model probably doesn’t meet them, and you should treat these as novelty/models not toys for tiny children (at least not children so tiny that they still chew on everything they see). For toy safe paint and Varnish, check out the Painter’s craft range from Rust-Oleum (check the label to make sure, as not all Rust-Oleum products are safe). Or look for any paint that conforms to the EN-71 standard.

And that is how I arrived at the final result. Let me know if you like it, or if you try it for yourself. My Custom Brio style toy SouthWest Trains Desiro Class 444

comments

AngularJS Pipe in Expression Is a Filter Not Bitwise Or

If you come across a pipe (or bar) symbol in an angularJS expression, and don’t know what it means, it’s a Filter (effectively formatting options).

I had remarkable trouble googling for this problem, hence this keyword laden post. Basically if you come across a single pipe (or bar) symbol inside double curly brackets then you might think that this is a mistyped OR symbol, or if you’re a bit more JS savvy, a bitwise shift operator. In fact you have to remember that angular expressions are not vanilla javascript – they are parsed by angular itself and have their own syntax. The single pipe is in fact a filter operator which slightly confusingly is often used to format numbers, for example with localised decimal seperators.

I had to go on quite a google treasure hunt to find that out, so hopefully this can act as a bit of a signpost for the curious in future.

comments

Custom Brio SouthWest Trains Class 444 Toy Train

My Brother is a bit of a train geek, a few years ago I made him a tiny railway as a Christmas present.

So this year I’ve made him and my 2 year old niece a joint Christmas present of a custom, one of a kind Brio style train, which is an accurate (ish) caricature of a SouthWest trains class 444 Desiro. These little wooden trains are awesome, I’ve never met a toddler who didn’t like them. There are a bunch of different manufacturers, of which Brio is just the most famous.

Some of the models are just generic “toy trains” but others are models of real trains past and present, but they’re mostly based on either German and American trains. So I made some that look like the trains you can see at my brother’s local station in Petersfield, specifically, a SouthWest Trains Class 444.

Here’s the end result: My Custom Brio style toy SouthWest Trains Desiro Class 444

Full details of how I built it, and the designs for the sides and top to follow in another blog post (if I get around to it).

I got around to it! I’ve written up how I made the trains in another blog post.

comments

Babylon JS Experiment

Very quickly – I’ve been playing with Babylon JS to do some WebGL animations. I’ve got a scene to draw but am having trouble with animations. Here are the results so far:

Spiky BabylonJS experiment

You can fly around with the cursor keys and mouse (Babylon default behaviour). Then hit the ‘a’ key to trigger an animation (and an error – after which you can’t fly around any more!) [Edit – fixed thanks to the peeps over at the HTML5 game devs forum]

The whole reason I wanted to do this was for fun, and to try and provide a visualisation for this 3d dogfight Code puzzle, but someone beat me to it, so now it’s just for fun.

comments

Chronhorama Project Idea

I suffer from a surfeit of ideas and not enough time and willpower to get them all finished (coughany finished). Most never leave the confines of my head. I’ve mulled over giving a lightning talk called “Ideas I’ve had but will never get round to”, so that if anyone else thought they were good ideas, maybe they could implement it.

I thought I ought to tell people about them. So here’s one of them:

Introducing Chronhorama

From the Greek: Chronos (time) and horan/horama (see/view). (Name only recently made up and liable to change at any moment)

The gist of it is: a sort of time traveling google streetview of my own garden.

What?

I’m currently working on a bit of hardware (because that’s fun). A motorised turntable, controlled by an Arduino, that can position a camera quickly and consistently. The x-axis turntable is almost ready to be sent away for laser cutting. The Y axis is going to be phase two and will be a bit trickier. It’, still in the mulling-over phase. My progress so far is now public and open source on bitbucket.

Phase three will be to get a raspberry pi to control both the turntable (via the Arduino) and the camera (via usb) to take a whole panorama automatically. Coincidentally, the same setup could probably serve as a gigapixel rig or a time-lapse setup.

Finally, once I’ve got a few panoramas, I plan to shove it all up on a website so you can pan and scroll around a virtual view of my garden (or anywhere else). The nifty thing is, there will also be a control to travel back in time to see the same panorama on a previous date.

Why?

I’ve got a new garden I don’t know very well and I often find myself trying to remember what was growing in a spot months earlier so that I know if I’m about to hide/enhance/kill it. If I can take seasonal panoramas, I can simply refer back to the website and see that nondiscript bush (A) was covered in flowers last summer, while non-descript bush (B) is a sucker that can get hacked, hoicked and composted with appropriate malice.

Yeah, but…Why? It all seems a bit overcomplicated.

I’m not re-inventing the wheel, I’m merely re-implementing it. How else do you learn to be a wheelwright?

More accurately, it’s fun, it’s blog fodder and I want to.

comments