Stubbing void methods with Mockito

I’ve been meaning to post something about this topic for a while, but it seems to have been slipping my mind. This post is targeted at those of you who use Mockito for your testing(Mockito is brilliant btw, and I applaud the folks over at Mockito for making this library!)

One thing that I got in the habit of was typing the when(mockClass.methodCall(eq(arg1))).thenCallRealMethod() etc, you’ll soon notice that if you’re trying to mock a void method, intellisense in any of your IDE’s will probably fail to allow you to select the methodCall method. There is an answer, and its way better than what was suggested in earlier versions. There is now a suite of doAnswer, doCallRealMethod, doNothing, doReturn(object), doThrow(exception) and the list goes on.

If you’re struggling to mock a void method, this is how you should go about it. Assuming you have a class that you would like to mock:


public class SampleClass {
   private String defaultValue = "default";

   public String getDefaultValue() {
    return defaultValue;
   }

   public void setDefaultValue(String defaultValue) {
    this.defaultValue = defaultValue;
   }
}

Here is a test class, mocking the behaviour of SampleClass, and setting up the test so that calls to the void method setDefaultValue are actually called, and subsequently verified with mockito.


public class SampleClassTest {

  private SampleClass sampleClass = mock(SampleClass.class);
  private String newDefaultValue = "Changed";

  @Test
  public void testOldWayOfVoidMethodMock(){

//   This is the old approach to attempting to mock void methods. I suggest
//   you avoid this in favour of the new method which is much
//   cleaner and more readable.

     stubVoid(this.sampleClass).toAnswer(new Answer() {
       public Object answer(InvocationOnMock invocation) throws Throwable {
         invocation.callRealMethod();
         return null;
       }
     }).on().setDefaultValue(eq(newDefaultValue));

     sampleClass.setDefaultValue(newDefaultValue);

     verify(sampleClass).setDefaultValue(newDefaultValue);
  }

  @Test
  public void testNewWayOfVoidMethodMock(){
//    Previously you would have been tempted to write something like
//    this to test void methods...
//    when(sampleClass.setDefaultValue(eq(newDefaultValue))).thenCallRealMethod();

//    However, this is how you should treat mocking void methods with
//    Mockito. Works with or without methods that require arguments
//    of course.
   doCallRealMethod().when(sampleClass).setDefaultValue(eq(newDefaultValue));

   sampleClass.setDefaultValue(newDefaultValue);

   verify(sampleClass).setDefaultValue(newDefaultValue);
 }
}

I’ve included two test methods to demonstrate the old suggested way, and the newly much more readable way. If you need more help then I suggest heading over to the mockito documentation which is pretty useful.

Back from India

So I’m back from India, and that was a life experience! The trip has taken it out of me, but what an extraordinary country. India, for someone who is going there for the first time, not knowing what to expect, can only be described as a complete and utter assault on every sense you possess!

But now back to reality. Not too long ago I was talking about going contracting. This is the month I go about taking the actual plunge, before I jet off again on a quick trip around Italy soon – I know I’m taking advantage of the time off to do some much needed travelling. 🙂

I promise more technical posts will follow! Watch this space.

Escaping to the Himalayas

As some of you might know, I’m a bit of a biker, and also a little bit nuts sometimes. When you combine these two things, you will end up with a crazy idea like going to the Himalayas and riding around there on a Royal Enfield. So that’s exactly what I’m about to do! 🙂

I’ve decided to sign up with Blazing Trails and do one of their tours from Manali to Leh. I’ve never been to India before, and I’ve also never done a bike tour like this before – complete bike tour virgin! 🙂 Oh and did I mention I’m going on my own, not knowing a soul on tour!? Yeah I’m definitely nuts! I’ll more than likely be offline for the majority of the time, so this is a quick post to say “See you in +/-2 weeks!”

I suspect that by the time I return, I’ll be completely exhausted, but would have gained a life time experience. Here goes nothing….

Appfuse – The defined artifact is not an archetype

If ever you run into an issue with trying to create a project from an appfuse archetype template inside your favourite IDE and recieve the following error message:

Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:2.2:generate (default-cli) on project standalone-pom: The defined artifact is not an archetype -> [Help 1]

Then rather go here: http://static.appfuse.org/archetypes.html and run the command line version. It’ll save you the headache!

Taking the plunge, going contracting!

Recently I’ve been deliberating with a lot of energy mind you, about where I am in my current career as a software developer, and how that marries with where I’m at in my current position at my company. For reasons I won’t divulge here, suffice it to say I’m not completely happy I’m heading in the right direction, and have chosen to resign and move on.

With moving on there’s, always the choice between finding another permanent position, or to take the plunge and going contracting. I’ve had a few frank discussions with friends and ex-colleagues about the merits of both, and there was a definite positive bias of opinion towards contracting. Not only just the benefits of extra cash in your back pocket – provided you’re good enough – but also contracting is inherently associated with freedom.

Show me the money!

Everyone you speak to when it comes to contracting will at some point, if not the first point, mention that the money is better. You have the luxury of getting more cash in your back pocket – remember always do it above-board when it comes to taxation, it’s really not worth it! – but you take the risk for if ever there are quiet times in the industry. You’ll obviously be responsible for things like your own medical, pension, training, equipment etc. Which is why you can demand a higher rate, and what also works in your favour is that the higher rate is only subject to a finite amount of time – i.e contract duration. Believe it or not, this is quite an attractive thing for companies seeking sections of work to be completed, because they already know what it will cost them up front – I guess provided they know the scope etc. I’ve been in software development long enough to know that it is rare for someone to quote a fixed duration of time to deliver a product/feature, and it being delivered on time! :-p But the point I’m really trying to make here is that the company hiring the contractor, can cease the need for any further expenditure once the contract is up. When you’re permanently employed, the company can’t quite do that as easily.

Travelling

With contracting, you’re committed for a set period of time, to deliver a service. After the contract is finished, you can decide to either extend/find a new one. Or you could choose to do some things which you’ve always wanted to do. I love travelling, and especially travelling with my girlfriend. She’s a teacher and during the summer we’ve dreamed of taking weeks off to go travelling, which she’s more than capable of doing, but I unfortunately historically couldn’t. Most permanent employment have restrictions on the number of consecutive weeks you can take off, and also the number of days off that you can have in the year. This is completely negated when you contract. Travelling or even learning to play an instrument are totally within your control provided you do a little bit of planning, and save the extra cash you’re now getting while contracting. 🙂

Training

When contracting you would be in charge of your own progression. That really appealed to me. I decide what courses I want to attend, and what new technologies I want to experiment with. This is obviously not to say that I didn’t have those choices in a permanent position, but when contracting you’re free from the shackles of pay-back schemes, and lock-in, as well as avoiding situations where in quiet times the company can’t send you on training due to budget cuts. This is another reason why you can demand higher rates, so that you can keep up with the industry. Also, and possibly more valuable in my opinion, is that every new contract you work on, exposes you to new things, new technologies, new implementations of methodologies etc. This is an incredibly important asset to have.

So these are just my reasons and opinions for going contracting. It’s scary to take the plunge, but I’m sure when I finally do land my first contract, I’ll never look back. While doing incessant and relentless research on this topic, I was given a book by a dear friend of mine, and this was something like a bible to me. Its called the Contractors’ Handbook, and is more geared for UK individuals wanting to go contracting. Its written by Dave Chaplin, and he’s got a new version of this book coming out in June, so check it out here, I can’t recommend it enough if you’re becoming serious about contracting.

So, are you thinking about going contracting now? 🙂

Spring 3.1 RESTful Authentication

Lately I’ve been dabbling in trying to secure a REST service that I’ve built using Spring & Spring Security. I’ve been reading quite a bit about REST of late(and have been for quite some time), and the popular themes around security I’m noticing, is that HTTPS is a good thing, and persisting any sort of session state(even user authentication) is not the best practise. So I decided to take a look at what Spring have provided in the way of authentiction when using web apps, and decided that there wasn’t anything pre-configured that I could use that would require me to provide my security credentials on every request, and effectively re-authenticate, unless of course you were going to use Basic Authentication, or Digest authentication.

Looking around at how others in the industry implement security for their REST services, I came across a pretty neat implementation at Kayako, and thought I’d adopt the same principle. If you’ve not seen how Kayako secure their REST services, its quite simple. You, as a client, need to provide 3 things.

1. The API Key

Something that identifies you as a user. Preferably this should be some “Not so easily guessable” string. I would suggest perhaps some guid. Add this as an additional attribute against the user details you hold in your DB. Allow the user to request a new guid through your web app if they feel that their current one has been compromised.

2. A Salt

This should be a random string that should change on every request. You could calculate and MD5 hash of the content of your request, or you could send any other random string.

3. Signature

This is the Hash(preferably a HMAC SHA, see my previous post about hashing passwords in Spring). This hash is a combination of your password, with the Salt mentioned above. On the server side, it’ll lookup your user details via your API Key, and validate the authenticity of your credentials by performing the same hash against your salt/password in the hope that it’ll arrive at the same signature that you’ve provided in the request. Obviously the password that is stored in the database would be a hashed password anyway, just so that it’s not obviously “guessable”.

I couldn’t find anything in Spring which is provided out of the box support for stateless authentication for REST, where I could provide these credentials in the URL, so I decided it would be fun to try and roll my own, using Kayako as a source of authority on how to provide the details for the secured REST call. Feel free to check out the sample app I’ve put together over on Github.

Whats Involved

In order to embark on creating your own mechanism for authentication with Spring, you need to be familiar with how the Spring Security model works. If you’re not familiar with it, I’d suggest a quick read over their documentation.

The main java classes involved in order to make this happen are the following:

1. The Filter (RESTAuthenticationFilter)

I’ve chosen to insert this filter where Spring would have used a Forms Authentication Filter. Below is a snippet where I’ve pointed out where/how I did this.


<sec:http disable-url-rewriting="true" entry-point-ref="forbiddenEntryPoint" use-expressions="true" create-session="never">
 <sec:anonymous enabled="false"/>
 <sec:session-management session-fixation-protection="none"/>
 <sec:custom-filter ref="restAuthenticationFilter" position="FORM_LOGIN_FILTER"/>
 <sec:intercept-url pattern="/**" access="isFullyAuthenticated()"/>
 </sec:http>

Notice how I’ve chosen specifically to not create a session, disabled anonymous access, and replaced the Forms Login Filter with my own.

2. The Authentication Provider (RESTDaoAuthenticationProvider)

This is essentially responsible for looking up the user, and validating their credentials. I’ve tried to use as much of already existing functionliaty so I’ve extended from the AbstractUserDetailsAuthenticationProvider, and the most important method here is the additionalAuthenticationChecks(...). This method is actually where the check is done to see if the password the user has supplied is in fact correct.

So thats the guts of it! There are obviously a few other supporting classes, but if you can get your head around this, then you’re well on your way to customising your authentication for REST Services in Spring.

Hash based Message Authentication Code hashing in Spring MVC

Hash based Message Authentication Code(HMAC) is used in scenarios where you need to validate the validity and authenticity of a message. Recently I was implementing some security aspects for our REST service, and I noticed that Spring Security currently supports SHA hashing for password, but no HMAC SHA hashing.

Now firstly, this is really for informational sakes, and I’m in no position to advise which way is better, but instead, I’m providing what I think I’d rather have implemented, and its purely a personal preference – for me anyway.

So, now back to the point. Firstly, below is a sample of a security configuration(in xml) using one of the many Spring Security provided implementations of the PasswordEncoder interface – namely the ShaPasswordEncoder.

.....
<authentication-manager>
   <authentication-provider>
      <password-encoder hash="sha"/>
      <user-service>
         <user name="jimi" password="d7e6351eaa13189a5a3641bab846c8e8c69ba39f" authorities="ROLE_USER, ROLE_ADMIN" />
         <user name="bob" password="4e7421b1b8765d8f9406d87e7cc6aa784c4ab97f" authorities="ROLE_USER" />
      </user-service>
   </authentication-provider>
</authentication-manager>
.....

Now in this simple contrived sample config, we’re telling Spring Security to use their implementation of the ShaPasswordEncoder. Upon inspection of this implementation, you’re also able to specify the field responsible for holding the salt value if you so choose to provide one. In the REST service I have, I have defintely opted to provide a salt in which to further secure the hash.

In this ShaPasswordEncoder implementation provided by Spring, it performs a hash on the raw concatenated string in the format of “password{salt}” . This surprised me somewhat, because I had actually expected Spring to provide an implementation of HMacSHA when providing a salt, not just an implementation of SHA! And believe me theres a difference! So the purist in me came out, and I couldn’t let this rest (see what I did there? rest….REST?.. ok I know, perhaps a little lame, but I digress.)

The main difference between the two implementations, is that the way Spring have done it, they have just effectively hashed a string. With HMac, the salt actively plays a role in the encryption of the raw string. Some might argue that they arrive at the same end result, which is a hashed string based on the salt. I’d tend to agree, but the purist in me wanted to do it properly, so I wrote my own implementation of what the HMacSha should have been. Below is a simple snippet of what the code looks like when just using a normal SHA hash, and when using a HMacSHA. In these samples below I’ve only shown the code which actually does the hashing so you can see what the difference is. Also bear in mind, that my custom rolled hashing class extends the PasswordEncoder class so that I can include it in the security config xml.

SHA Implementation

public String encodePassword(String rawPass, Object salt) {
 String saltedPass = mergePasswordAndSalt(rawPass, salt, false);

MessageDigest messageDigest = getMessageDigest();

byte[] digest = messageDigest.digest(Utf8.encode(saltedPass));

// "stretch" the encoded value if configured to do so
 for (int i = 1; i < iterations; i++) {
 digest = messageDigest.digest(digest);
 }

if (getEncodeHashAsBase64()) {
 return Utf8.decode(Base64.encode(digest));
 } else {
 return new String(Hex.encode(digest));
 }
 }

protected final MessageDigest getMessageDigest() throws IllegalArgumentException {
 try {
 return MessageDigest.getInstance(algorithm);
 } catch (NoSuchAlgorithmException e) {
 throw new IllegalArgumentException("No such algorithm [" + algorithm + "]");
 }
 }

protected String mergePasswordAndSalt(String password, Object salt, boolean strict) {
 if (password == null) {
 password = "";
 }

if (strict && (salt != null)) {
 if ((salt.toString().lastIndexOf("{") != -1) || (salt.toString().lastIndexOf("}") != -1)) {
 throw new IllegalArgumentException("Cannot use { or } in salt.toString()");
 }
 }

if ((salt == null) || "".equals(salt)) {
 return password;
 } else {
 return password + "{" + salt.toString() + "}";
 }
 }

HMac Implementation

protected final Mac getMac() throws IllegalArgumentException {
 try {
 return Mac.getInstance(algorithm);
 } catch (NoSuchAlgorithmException e) {
 throw new IllegalArgumentException("No such algorithm [" + algorithm + "]");
 }
 }
 public String encodePassword(String rawDataToBeEncrypted, Object salt) {
 byte[] hmacData = null;
 if(rawDataToBeEncrypted != null){
 try {
 SecretKeySpec secretKey = new SecretKeySpec(rawDataToBeEncrypted.getBytes(ENCODING_FOR_ENCRYPTION), this.algorithm);
 Mac mac = getMac();
 mac.init(secretKey);
 hmacData = mac.doFinal(salt.toString().getBytes(ENCODING_FOR_ENCRYPTION));

if (isEncodeHashAsBas64()) {
 return new String(Base64.encode(hmacData), ENCODING_FOR_ENCRYPTION);
 } else {
 return new String(hmacData, ENCODING_FOR_ENCRYPTION);
 }

}
 catch(InvalidKeyException ike){
 throw new RuntimeException("Invalid Key while encrypting.", ike);
 }
 catch (UnsupportedEncodingException e) {
 throw new RuntimeException("Unsupported Encoding while encrypting.",e);
 }
 }
 return "";

}

I am using this version of the hashing algorithm for my sample REST service which I have up on Github. You can check out the java file itself here, but I’ll give a more detailed run down of the sample project in my next blog post, which is about supporting stateless authentication in a Spring REST application, and how I went about rolling my own security filter/mechanism to support this. Watch this space!

PhoneGap – Your answer to a multi-platform targeting mobile framework.

I recently attended a SpringOne and Cloud Foundry conference and Adrian Coyler, CTO of SpringSource was there giving a rather interesting keynote speech. What struck me as very interesting in his talk was how Ardian was sharing his experience about the growing trend that businesses are adopting these days. This trend he was talking about, had to do with how companies are beginning to favour mobile applications in order to get their idea/product out there in the wild. Obviously this isn’t new right? But what struck me is that in majority of these cases, companies would either start with a mobile app, or they would only build a mobile app.

Discussion carried on about the inevitable customer base, and the handful of different handset manufacturers you’d need to consider as your target audience. Obviously Android and iPhone handsets are way up there on the consideration list, but there are quite a few other often forgotten stragglers which you might not want to discount – namely Windows Phone, Blackberry, and maybe, just maybe Symbian.. OK, maybe Symbian is a bit of a stretch, I confess, I don’t think I even think my Gran owns a Symbian phone!

Anyway, my point is, that this topic reminded me of a mobile framework which I had stumbled across but never bothered to explore. And this ladies and gentlemen I present to you the blessed beauty that is PhoneGap.:) Firstly, if you think this is the one to rule them all, then you might be getting slightly ahead of yourself, but it does a pretty fine job of taking the platform specific backache out of the equation.

PhoneGap’s strength lies in its use of HTML 5. Think of PhoneGap as a native container, which executes/loads locally placed HTML 5 pages, that are driven by Javascript frameworks and styled with CSS goodness. Did I mention that you can choose which Javascript framework you want, so if you like JQuery, use it, like Sencha Touch? Use it. Awesome! You can get an application up and running in no time – I did my first ever sample app using PhoneGap which was capable of taking pictures in less that 2 hours! Not too shabby eh?

So for those of you who have only been deep underground working hard on specific native mobile applications, I urge you to come up for air and give this a go. Or even if you just have a new idea and you want to develop it for the mobile market, then I implore you to take a look at this framework. And just to be clear, I haven’t switched jobs to become a PhoneGap marketing pimp, I just think it’s a promising framework which is set to change how mobile apps will be built in the future.

Once you’ve given it a go, let me know what you think!

JQuery – Wait for multiple AJAX calls to return before continuing

I have to say, I love JQuery. Before 2 years ago, I was a complete and utter JavaScript noob, and quite frankly I feared it. But when I began getting to grips with this gem of a JavaScript framework, my eyes opened up to an entirely new world!

Ok, enough gushing and onto my discovery. I have a website that currently makes multiple ajax calls to retrieve a bunch of lookup lists etc. Before I can setup a grid I have on the page, which makes use of these lookup lists, I need to wait for all these calls to return before I can initialize my grid with the data. Enter JQuery’s when, then concept. This is only available from JQuery 1.5 onwards.


function getLookupListOne(){
    return $.get('lookup-list-one-url.json', function(data){
    for(var i = 0; i < data.length; i++){
        lookupListArrayOne[i] = "Some global array data you might want to initialize...";
    }
});

function getLookupListTwo(){
    // Content left out for brevity
});

function getLookupListThree(){
    // Content left out for brevity
});

$(document).ready(function() {
    $.when(
        getLookupListOne(),
        getLookupListTwo(),
        getLookupListThree()
    ).then(function(){
        alert('All AJAX Methods Have Completed!');
    )};
});

The remote end hung up unexpectedly – Git + IntelliJ + Mac OS X

So I thought I’d try out IntelliJ’s neat little feature to import my project into a Github repo. Now I always used to do the git repo setup manually at the command line, and then commit and push my changes from the terminal too! But to speed things up, I thought I’d give this a bash. Only to be prompted with the following error in the Version Control pane in IntelliJ:

java.io.IOException: There was a problem while connecting to github.com:22
at com.trilead.ssh2.Connection.connect(Connection.java:791)
at com.trilead.ssh2.Connection.connect(Connection.java:577)
at org.jetbrains.git4idea.ssh.SSHMain.start(SSHMain.java:154)
at org.jetbrains.git4idea.ssh.SSHMain.main(SSHMain.java:135)
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
at java.net.Socket.connect(Socket.java:529)
at com.trilead.ssh2.transport.TransportManager.establishConnection(TransportManager.java:341)
at com.trilead.ssh2.transport.TransportManager.initialize(TransportManager.java:449)
at com.trilead.ssh2.Connection.connect(Connection.java:731)
… 3 more
fatal: The remote end hung up unexpectedly

With a bit of searching and digging around on the net, I came across fatal: The remote end hung up unexpectedly and the obvious setup instructions on github. But the real gem that helped me out was Github (SSH) via public WIFI, port 22 blocked

I wouldn;t have originally thought that it would be because of the network I was connected to, but in desperation I resorted to looking around about ssh’ing on public networks, and eventually found this. For those who don’t feel like reading the StackOverflow question/answer, you basically just need to do the following:

Create the config

sudo nano ~/.ssh/config

Add the config

Host github.com
User YourEmail
Port 443
Hostname ssh.github.com

And Presto! When you push your changes from IntelliJ to Github, it’ll ask you if you trust this domain, and once you accept, all will be good with the world!