Pages

Wednesday, 14 May 2014

Jax-RS custom exception handling

One of the nice things about working with JEE is the components available really are pretty standard.  While using JAX-RS, sometimes you need to control how exceptions get processed and fed back to the user.  If an exception is thrown, by default, you'll get some horrible HTTP 500 internal server exception, exposing the internal failings of your web service.

Consider the following gist, this endpoint would be used to view a user based on the Id.

Now, the implementation of this interface would look something like the following, to do the donkey work of actually retrieving the user.

This looks fine, but consider if the userDao was doing some entity business logic, using Query.getSingleResult and the user with this ID didn't exist?

According to the JEE6 API documentation, you'd receive a NoResultException, which would cause an HTTP 500 error exposing your internal server exception, which is definitely something end users shouldn't see. We need to leverage the exception handling of Jax-RS!

First, we need a dumb exception object, appropriately named, which will be what we'll actually throw, consider the code below..

Next, we need to modify our original code to take into account this exception, I've modified the original UserWebService and associated implementation appropriately below.

This will now throw an appropriate exception when a user cannot be found. However, we still need to create a Handler object to convert this exception into an actual JSON response so we get a nice friendly error message. The class below handles this exception and will convert the error message in the exception into a JSON response. The important annotation you'll see on this class is the @Provider annotation.

You'll notice we create an ErrorMessage object to respond to from the web service. This is just a simple dumb object to hold the details of the actual error that'll be marshalled into JSON.

The final step in mapping our exception handler provider to the web-app is to add the following into our web.xml for our webapp.

Now when we call this REST endpoint with a user ID that doesn't exist (let's say "DAG"), we'll happily receive the following JSON response rather than a stacktrace.

Friday, 17 January 2014

Stripping Java string SQL statements automatically

Do you ever get sick of typing out an SQL statement in Java with all the String syntax?

Then, when the statement doesn't work, you have to copy it back into pure SQL to run it to check it works?

This was a pretty common problem for me, so I made a simple syntax stripper http://idavid.co.uk/sqlstripper/ so I could quickly covert from SQL into a Java string and back again.  Consider the following Java String...

String query = "SELECT * " +
"   FROM USERS u" +

"INNER JOIN CODE cd ON cd.userid = u.id " +
"WHERE u.id in ('1','2') ";

This would parse fine if it was being sent into stmt.executeQuery(query)

But it I wanted to run this on SQL server just to see what it produced, I'd have to manually remove all the syntax etc to make it run and generate the following SQL.

SELECT *
FROM USERS u
INNER JOIN CODE cd ON cd.userid = u.id
WHERE u.id in ('1','2')

This is exactly what my SQL stripper does.  It also gives you the ability to paste in an SQL statement into the right hand textbox and convert it into a nicely formatted Java String, so converting the SQL statement above would give...

"SELECT *"
+ " FROM USERS u"
+ " INNER JOIN CODE cd ON cd.userid = u.id"
+ " WHERE u.id in ('1','2')";

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...

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

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

  @Override
  public cook(Meat meat) {
      return cookeryDao.getSausage(meat);
  }
}
Context...
@Component
@Scope("prototype")
public class MealContext {
    private MealStrategy mealStrategy;

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

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

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

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.

@Component("burger")
public class BurgerStrategy implements MealStrategy { ... }

@Component("sausage")
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) {
    burger.cookMeal(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 http://www.playerviewer.com (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 http://www.mysite.com/deploy/ROOT.war 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.