Monday, 2 December 2013

Importing a libgdx project into Intellij

I've started getting into Intellij.  I must admit, I'm much more comfortable with Eclipse so it was a bit of a learning curve.  On top of that, I'd never used the libGDX gaming framework for Android.  I found documentation a little sparse online so I thought I'd record a YouTube video just to give a simple step-by-step tutorial on importing the demo projects into IntelliJ and playing them on a device.  This was the first time I'd ever made a YouTube video, so apologies for the audio quality.

Friday, 15 November 2013

Strategy Pattern ain't meant for Spring!

Right, so lets say you're writing a Spring MVC app and you decide, "I want to do seperate encapsulated algorithms that can be swapped to carry out a specific behaviour".

The classic response to this would be "you need the Strategy Pattern ma' boy!".  So, that's what I did, consider the code below...

public interface MealStrategy {
    cook(Meat meat);
First strategy
public class BurgerStrategy  implements
MealStrategy {
  @Autowired CookerDao cookeryDao;

  public void cook(Meat meat) {
Next strategy...
public class SausageStrategy  implements
MealStrategy {
  @Autowired CookerDao cookeryDao;

  public cook(Meat meat) {
      return cookeryDao.getSausage(meat);
public class MealContext {
    private MealStrategy mealStrategy;

    public void setMealStrategy(MealStrategy strategy) {
        this.strategy = strategy;

    public void cookMeal(Meat meat) {
Now say this context was being accessed through an mvc controller, like...
private MealContext mealContext;

@RequestMapping(method = RequestMethod.POST)
public @ResponseBody Something makeMeal(Meat meat) {
    mealContext.setMealStrategy(new BurgerStrategy());

Normally, this would make perfect sense for use with the strategy pattern.  However, the one line that makes it all come crashing down is the line in the controller...

mealContext.setMealStrategy(new BurgerStrategy())

This will cause the new instance of the bean to be created outside Spring's application context.  This is curious, so how should you go about implementing a pattern within Spring if you can't use new to create a new instance?  After asking this question on StackOverflow, the conclusion I came to was to use the Dependency Injection pattern (as per the standard autowiring in Spring) and make individual injections of strategies.  Firstly, I'd need to amend the strategies so they have named components.

public class BurgerStrategy implements MealStrategy { ... }

public class SausageStrategy implements SausageStrategy { ... }
Now in the controller, I have individual strategies to use, so rather than setting a strategy, I just pick the appropriate one that's injected.
@Resource(name = "burger")
MealStrategy burger;

@Resource(name = "sausage")
MealStrategy sausage;

@RequestMapping(method = RequestMethod.POST)
public @ResponseBody Something makeMeal(Meat meat) {

Wednesday, 12 June 2013

Java testing with Selenium and dynamic ids in html

One of the cool aspects of Selenium, is that not only can you record yourself using a site, you can actually run this as a junit test.
Firstly, I'll install Selenium in Firefox (as this is the official version) and record a quick test.  It's important to note that Selenium will give you a number of different ways to remember which html tag you invoked.  For instance, it can just invoke a specific id on a page.
However, when using a portal system like say JSF under Liferay, the id values are generated on the fly, so you'd record one test, then never be able to run it successfully again.
One really nice feature of Selenium is you can invoke a HTML xpath so in the Liferay example, your code would still find the tag it needed to click.  Lets say I record myself logging into the page below...

Now because this page is generated with liferay, I can see the input text id for the form is...
As JSF under Liferay will create a new id quite regularly for this textbox (each time the server is restarted I believe, although it may be even more frequent), this means we can't just get the id and hook into that, as the tests will only ever run once. 

What we can do however is hook into liferay by using the html tag directly as this won't be different each time Liferay loads the JSF.  I noticed I had to use this same technique for every page in Liferay as the id for nearly all the html rendered through JSF had a different id each time the page was accessed.

We can then export this to a junit class from the file menu File | Export Test Case As... | Java / JUnit 4 / Web Driver which would give us the following class to run and test.

Sunday, 12 May 2013

Tomcat deployment script

So this weekend I deployed (shameless attempt at self promotion!).  I've spent a lot of time with EC2 on Sonar / Jenkins boxes, but never deployed over Tomcat on it in production other than small tests.

One thing I found during the inital deployment that really started to be a constant theme...

stop tomcat, download war, delete old war folder, move war, start tomcat.

This started to become a pain, so I ended up just using a shell script.

So the maven process in my pom is to move my war to a directory, that then gets uploaded to and my shell script does the rest.
There are probably much nicer ways to do this such as using ant to ftp the script to the location for the shell script to download it, but it's not really that important.
Also - all the code from player viewer is available open source here

Thursday, 9 May 2013

Is private encapsulation always secure?

Suppose you make a method private in Java, experience tells us this is bread and butter stuff and only methods inside this class can access the private methods.  However, in the following example I'll show how setting methods as private isn't always safe.

From here, we can see if we had an instantiated User object, we could just call user.getFirstName(); However - what if we wanted to get the password?  We can use reflection to access this private method.

This is where the Method object in the Java.lang.reflect package is useful.  If I was to reflect this method back into an object, I'm able to set the accessibility of this object.

The accessibility method call is important as it will turn off any encapsulation checks on this method invocation.  We can then simply invoke this method as shown below to result in the password being printed out.

This is one of the many reasons why storing your passwords in plain text in a compiled object, even if you make the methods private, is dangerous.

Tuesday, 16 April 2013

Hibernate exception timings vs SELECT COUNT(*) to check entity existance

This is something that I've been curious about for some time.  How much faster really is it to throw an exception rather than doing a SELECT COUNT(*) to check if an entity exists?

My initial suspicions are that the SELECT COUNT(*) would in fact be slower due to the database transactions.  However, the time to build up the exception stack for the NoEntityFound is no small fate either.  It's also worth considering if the numbers fluctuate based on the amount of data within the table at that point?

Obviously, the analysis could get much more complicated and it's not my intention to go into the realms of indexes / partitioning / whether the entity is presenting a view of two tables / hibernate caching.  It's more a general curiosity.

So lets begin, here's my entity..

Now I'm going to use an extremely simple HibernateUtil class to get me the session, shown below.

To fire the exception, I'm going to use the .load() method from org.hibernate.Session. I'll also run the following code to see how checking the SELECT COUNT(*) would take...

Here are the results! Using the load method, with the given entity above this takes 1328 milliseconds. SELECT COUNT(*) came in last with 1454 milliseconds, all hail load!
Now something that does seem important is as both methods were pretty dam close, which one is more readable? To be honest, the load does just seem to make sense and catch the exception but you could easily argue exceptions shouldn't control the flow of your application if you're checking existence of an object. Currently, I have 608 entries in the table that the Player entity is hooked up to. Below are the results for the different times.
.load()SELECT COUNT(*)number of values in table
What we can see from the results above, interestingly is the amount of data in the table, has pretty much no resemblance to the time either query takes to run.

Sunday, 7 April 2013

Parsing ESPN API using Java and Google GSON

For my first post, I'll explain how to parse the ESPN API.  The API documentation can be found at

Firstly, you'll need to request an API key, then you can start querying the REST API to retrieve the JSON response.  In the following example, I'm going to query simply for all the players in the sport of "Soccer" (dam that Americanism )  that play in the Premier League in England.

From reading the documentation, this is the URL that I need to send requests to (with [apiKey] replaced with the correct value).[apiKey]

Something to bear in mind first of all, there's an offset value that forces you to make multiple queries if you want more than just the 50 results, this is set with a parameter known as offset.  So for instance, to get the results from 51-101 the following query would pull these back.  We'll come back to this later as this can cause some slight issues.[apiKey]&offset=51

Now I've got the description out the way, I'll start the code, it should be noted I'm using GSON to parse the JSON so you'll need to add the following Maven dependency.

Once this has been done and you've ran the maven:install to get the jars downloaded, you can start querying. The code below is simply required to download the JSON from the ESPN API

Now we can start parsing this JSON, because the JSON produced has a lot of redundant data, I decided against parsing it into objects and just queried it raw. This will give us a JsonArray of Athletes and the associated data that can be pulled about them. It should be noted as this point, the response here varies based on your API allowance (free, partner, paid etc). I'll leave the relevant ESPN API page here
Now, as we've got the relevant JsonArray we want, we can just loop through it to return the data about each player. It should be noted a couple of things that may look odd about this code. Firstly, the reason for the sleep is because the API has a limit of how many times a second you can call it, currently as I write this for free you're limited to once every 3 seconds. Secondly, the reason it's in a loop of 650 is to do with the offset I referenced earlier in this post. This means you need to query each 50 players, this seems a little computationally expensive as I'd have thought it'd be easier just to return the 602 players rather than having to do the heavy loading of receiving 12 RESTful calls.
Then, when we put this all together you get the class below, this will loop through every player giving you their first name.
You can download the full project on github