Interesting use of Java 8 interface default method

Intro

I was in the middle of trying to implement a type of validation on my current project at work. Said project uses Java 7, and the problem had to do with an interface extending another interface. I was literally in the middle of implementing it, and I said to myself, “I wonder how I could handle this same problem using Java 8!”. So I hopped over to my personal development machine, and gave it a try. First, let me see if I can set forth the problem.

The Problem

Here is the problem we are trying to solve:*
We need the program to behave such that, when we invoke a specific type of validator, we invoke it with the signature specific to that validator. Let me elaborate.

We had an interface like such:

public interface Validator {
  public boolean validate(Thing thingToValidate);
}

We then had 2 other interfaces that extend the Validator interface. (these may look like they have no purpose since they don’t contain any method signatures, but they are marker interfaces used specifically in other parts of the code):

public interface PreProcessingValidator extends Validator {
}
public interface PostProcessingValidator extends Validator {
}

Obviously, we also had the code where the validators get invoked.

/// code removed for brevity...
for(Validator v : validators) {
  v.validate(aThing);
}

This is all great, except we find out that we need the PostProcessingValiator objects to be able to validate also against the ProcessingResult. What can we do? I know one thing! We can just add a method to do that in the PostProcessingValidator:

public interface PostProcessingValidator extends Validator {
  public boolean validatePostProcessing(Thing thing, ProcessingResult result);
}

The problem is now any class that implements the PostProcessingValidator interface needs to implement both the validate(Thing) method and the validatePostProcessing(Thing, ProcessingResult) methods. There are some tricky ways to get around this in Java 7 and below, but I wanted to see what I could do with Java 8. And that’s when interface default methods came to mind. I have no idea if it will actually work or not, but I give it a shot.

The Solution

Java 8 provides for adding default methods to interfaces. This allows you to have interfaces that contain functionality as well as method headers.Let’s take a look at how we can use them to do what we want.

The Validator interface is alright as-is; nothing really needs to change. But we need to allow for classes that implement the PostProcessingValidator interface to not need to implement both methods. here is how I was able to do it:

public interface PostProcessingValidator extends Validator {
  @Override
  public default boolean validate(Thing thing) {
      throw new UnsupportedOperationException("validate(Thing) not supported; call validatePostProcessing(Thing, ProcessingResult");
  }

  public boolean validatePostProcessing(Thing thing, ProcessingResult result);
}

Say what?! I had no idea that this was possible until I tried.

A default method in a sub-interface can ‘override’ that method from a super-interface.

I don’t know all the implications of this behaviors, but I’m not even sure why the designers of Java allowed this sort of override to happen, as it seems like it could be pretty hazardous if not used correctly. I can also think of one gotcha with this approach. A caller can still attempt to invoke validate(Thing), so you need to return to the caller what they need to know what was gone wrong.

The only other code we need to change is the code where we invoke the validators:

/// code removed for brevity...
for(Validator v : validators) {
  if(v instanceof PostProcessingValidator) {  
    v.validatePostProcessing(aThing, aResult);
  } else {
    v.valdiate(aThing);
  }
}

So my conclusion is, you can feel free to use this pattern in your code if you want, although I’m not sure it provides for the best code clarity, or even a good approach to solving the problem. But it does solve this particular problem.

* – all identities in this article have been altered to protect the innocent :-)

Posted in Java, Java 8, Uncategorized | Tagged , , , , | 1 Comment

Get the IP address for a host name in Groovy

I was playing around with some Groovy scripts and looking at some neat tip and tricks on how Groovy can simplify what would have taken a lot more code in Java. Here is one that came up with: print out the IP address in dot notation of a given host.

def hostname = 'google.com'
println InetAddress.getByName(hostname).address.collect { it & 0xFF }.join('.')
Posted in Groovy | Tagged , , , , | Leave a comment

Using Grails REST for authentication in an AngularJS SPA

Introduction

I have played around with AngularJS for a few weeks now. I like how it provides for separation of concerns on the client-side that us server-side programmers prefer. I have built a couple of controllers that are retrieving data via REST from a Grails back-end domain. That is all well and good, but I want to protect access to the data, and most web applications have authentication so it is something good to figure out anyways.

I have made a few assumptions about Grails:

  • You are using Grails 2.3.x
  • You are using the asset-pipeline plugin
  • You are using Bower to manage AngularJS modules
  • You already have some AngularJS controllers defined which access data that you would like to protect

Configure Grails for authentication

For Grails, I am familiar with the Spring Security plugin, so I want to find a plugin along those lines. I found a nice plugin which provides “… authentication for REST APIs based on Spring Security …” using “… a token-based workflow.” Sounds exactly like what I need! It is a pretty easy plugin to set up.

  1. Install the plugin via a BuildConfig.groovy dependency
  2. Run grails s2-quickstart com.asoftwareguy.example.auth User Role to create the domain classes for authentication
  3. Create a class to hold the authentication tokens in the database:
    package com.asoftwareguy.example.auth
    
    class AuthenticationToken {
    
        String username
        String token
    }
    
    
  4. Add the proper configurations to Config.groovy:
    // Added by the Spring Security Core plugin:
    grails.plugin.springsecurity.userLookup.userDomainClassName = 'com.asoftwareguy.example.auth.User'
    grails.plugin.springsecurity.userLookup.authorityJoinClassName = 'com.asoftwareguy.example.auth.UserRole'
    grails.plugin.springsecurity.authority.className = 'com.asoftwareguy.example.auth.Role'
    grails.plugin.springsecurity.securityConfigType = 'InterceptUrlMap'
    grails.plugin.springsecurity.interceptUrlMap = [
            '/':                    ['permitAll'],
            '/assets/**':           ['permitAll'],
            '/partials/**':         ['permitAll'],
            '/**':                  ['isFullyAuthenticated()']
    ]
    
    grails.plugin.springsecurity.rememberMe.persistent = false
    grails.plugin.springsecurity.rest.login.useJsonCredentials = true
    grails.plugin.springsecurity.rest.login.failureStatusCode = 401
    grails.plugin.springsecurity.rest.token.storage.useGorm = true
    grails.plugin.springsecurity.rest.token.storage.gorm.tokenDomainClassName = 'com.asoftwareguy.example.auth.AuthenticationToken'
    grails.plugin.springsecurity.rest.token.storage.gorm.tokenValuePropertyName = 'token'
    grails.plugin.springsecurity.rest.token.storage.gorm.usernamePropertyName = 'username'
    

    Notice that access to /partials and /assets is fully permitted; all other access requires authentication. Access to /api is allowed via the plugin itself.
    Also note the entry for grails.plugin.springsecurity.rest.login.failureStatusCode = 401. This is necessary because the AngularJS module uses HTTP status code 403 to verify that authentication is required to access a resource, which is different from an authentication error when attempting to authenticate. We override in Grails to use HTTP status code 401 to indicate that.

  5. Add a user entry or two into Bootstrap.groovy, so you have some credentials set up.
    class BootStrap {
    
        def init = { servletContext ->
    
            User user = new User(username: "test", password: "test123")
            user.save()
    
            Role roleUser = new Role(authority: "ROLE_USER")
            roleUser.save()
    
            new UserRole(user: user, role: roleUser).save()
        }
        def destroy = {
        }
    }
    
  6. Run a few tests against the server to check that when provided a JSON object with username and password to /api/login, the server returns a token that is used to later retrieve data.

Configure AngularJS for authentication

Now that I have a back-end server accepting REST authentication requests and responding with a token I can use for later API calls, I need to set up my AngularJS application to use authentication. I settled on using the HTTP Auth Interceptor Module that is an AngularJS module.

    1. Change directory to grails-app/assets
    2. Run bower install angular-http-auth
    3. Add the require directive to your application manifest:
      //= require angular-http-auth/src/http-auth-interceptor
      
    4. Add the module declaration to your application:
      var exampleApp = angular.module('exampleApp', [
          'http-auth-interceptor',
          'ngRoute',
          'ui.bootstrap',
          'login',
          // others
      ]);
      
    5. Add a directive to your application to show the login form when required:
      exampleApp.directive('showLogin', function() {
          return {
              restrict: 'C',
              link: function(scope, element, attrs) {
                  var login = element.find('#login-holder');
                  var loginError = element.find('#login-error');
                  var main = element.find('#content');
                  var username = element.find('#username');
                  var password = element.find('#password');
      
                  login.hide();
                  loginError.hide();
      
                  scope.$on('event:auth-loginRequired', function() {
                      console.log('showing login form');
                      main.hide();
                      username.val('');
                      password.val('');
                      login.show();
                  });
                  scope.$on('event:auth-loginFailed', function() {
                      console.log('showing login error message');
                      username.val('');
                      password.val('');
                      loginError.show();
                  });
                  scope.$on('event:auth-loginConfirmed', function() {
                      console.log('hiding login form');
                      main.show();
                      login.hide();
                      username.val('');
                      password.val('');
                  });
              }
          }
      });
      function getLocalToken() {
         return localStorage["authToken"];
      }
      
      function getHttpConfig() {
          return {
              headers: {
                  'X-Auth-Token': getLocalToken()
              }
          };
      }
      
      function getAuthenticateHttpConfig() {
          return {
              ignoreAuthModule: true
          };
      }
      

      Notice a couple of other functions defined here as well. These are used later by the login controller(s) to set and retrieve the authentication request header/token combination. Here is the example HTML markup:

      <!DOCTYPE html>
      <html ng-app="exampleApp" lang="en">
      <!--[if lt IE 7 ]> <html lang="en" class="no-js ie6"> <![endif]-->
      <!--[if IE 7 ]>    <html lang="en" class="no-js ie7"> <![endif]-->
      <!--[if IE 8 ]>    <html lang="en" class="no-js ie8"> <![endif]-->
      <!--[if IE 9 ]>    <html lang="en" class="no-js ie9"> <![endif]-->
      <!--[if (gt IE 9)|!(IE)]><!--> <html lang="en" class="no-js"><!--<![endif]-->
      	<head>
      		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
      		<title><g:layoutTitle default="Example App"/></title>
              <meta name="viewport" content="width=device-width, initial-scale=1">
              <asset:link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/>
              <asset:stylesheet href="font-awesome/css/font-awesome.css" />
              <asset:stylesheet href="bootstrap-css/css/bootstrap.css" />
              <asset:javascript src="application.js"/>
      		<g:layoutHead/>
      	</head>
      	<body class="show-login">
              <div class="page-header container">
                  <div class="row">
                      <div class="span6">
                          Welcome to Example App!
                      </div>
                      <div class="span6" style="text-align: right;" ng-controller="logoutController">
                          Welcome, username.
                          <a href="" ng-click="logOut()">(Log out)</a>
                      </div>
                  </div>
                  <div class="row" style="text-align: right;">
      
                  </div>
              </div>
      
              <div id="login-holder" class="container" style="width: 300px;">
                  <div id="login-error" class="alert alert-error">
                      <button type="button" class="close" onclick="$('#login-error').hide();">&times;</button>
                      Username and/or password incorrect.
                  </div>
                  <div id="loginbox">
                      <div id="login-inner" ng-controller="loginController">
                          <form name="loginForm" role="form" ng-submit="logIn()" autocomplete="off">
                              <div class="form-group">
                                  <label for="username">Username</label>
                                  <input id="username" class="form-control" type="text" ng-model="authData.username"/>
                              </div>
                              <div class="form-group">
                                  <label for="password">Password</label>
                                  <input id="password" class="form-control" type="password" ng-model="authData.password"/>
                              </div>
                              <input type="submit" class="btn btn-primary" value="Login"/>
                          </form>
                      </div>
                      <div class="clear"></div>
                  </div>
              </div>
              <div id="content" class="container">
      		    <g:layoutBody/>
              </div>
      	</body>
      </html>
      
    6. Define your login controller(s):
      var login = angular.module('login', []);
      
      login.controller('loginController',
          function ($rootScope, $scope, $http, authService) {
              console.log('loginController called');
      
              $scope.logIn = function() {
                  console.log('logIn called')
      
                  $http.post('api/login', { username: $scope.authData.username, password: $scope.authData.password }, getAuthenticateHttpConfig).
                      success(function(data) {
                          console.log('authentication token: ' + data.token);
                          localStorage["authToken"] = data.token;
                          authService.loginConfirmed({}, function(config) {
                              if(!config.headers["X-Auth-Token"]) {
                                  console.log('X-Auth-Token not on original request; adding it');
                                  config.headers["X-Auth-Token"] = getLocalToken();
                              }
                              return config;
                          });
                      }).
                      error(function(data) {
                          console.log('login error: ' + data);
                          $rootScope.$broadcast('event:auth-loginFailed', data);
                      });
              }
          }
      );
      
      login.controller('logoutController',
          function ($scope, $http, $location) {
              console.log('logoutController called');
      
              $scope.logOut = function() {
                  console.log('logOut called');
      
                  $http.post('api/logout', {}, getHttpConfig()).
                      success(function() {
                          console.log('logout success');
                          localStorage.clear();
                          $location.path("/")
                      }).
                      error(function(data) {
                          console.log('logout error: ' + data);
                      });
              }
          }
      );
      
      console.log('login controllers load complete');
      

Fire up the application and try to navigate to one of your existing AngularJS controllers which requests protected data from the back-end server. If you have not already authenticated, the authentication module broadcasts a login required event, the directive we defined traps that event and overlays the screen with the login form. The login form stays active until you successfully authenticate, at which point the authentication module broadcasts a login confirmed event, and our directive traps that event and hides the login form, and the original data request is replayed with the authentication token as a request header.

Conclusion

The combination of AngularJS for a client with Grails REST APIs on the server is a powerful one with a lot of promise. Hopefully this will help you out if you are trying your hand at building an application along these lines. I have provided an example application using this approach on GitHub.

Posted in AngularJS, Grails | Tagged , , , , , | 22 Comments

Grails 2.3 Maven dependency caching issues

tl;dr version:
Change BuildConfig.groovy to reference your local mavenRepo repository as:

mavenRepo ("http://my.server/repos/my-grails-plugins") {
    updatePolicy 'always'
}

Long version:
If you have played around with Grails 2.3, you know that the project has switched to Maven (Aether, actually) as default for dependency resolution, as opposed to Ivy. However, on my current project, we have run into a few issues with the semantics of dependency caching with Aether as opposed to Ivy.

In Ivy, when you updated a snapshot dependency, it would detect that and immediately go download it from the repository. Aether’s default update policy on snapshots is to update at most once per day. This doesn’t work well when a Grails plugin is under active development and you are constantly publishing new versions to your own hosted artifact repository, such as Artifactory.

The fix listed above instructs Aether to always update the dependencies in that particular repository. You can read more about it in the Grails docs.

Here are the possible values for updatePolicy:

  • never – Never check for new snapshots
  • always – Always check for new snapshots
  • daily – Check once a day for new snapshots (the default)
  • interval:x – Check once every x minutes for new snapshots

Once you set a more frequent update policy, you should see something similar in the logs when you refresh-dependencies. This lets you know that Grails is checking the repository for new artifacts:

| Downloading: org/grails/plugins/xyz/1.0-SNAPSHOT/maven-metadata.xml
| Downloading: org/grails/plugins/abc/1.0-SNAPSHOT/maven-metadata.xml

Posted in Grails, Maven | Tagged , , , , | 2 Comments

SpringOne 2GX Wrap-up

(I have been meaning to post this for a while, but life has caught up with me, including my company’s tech conference, where I was a speaker in one session and a panelist in another.)

On September 9-12, I had the privilege of attending SpringOne 2GX 2013 in the beautiful Santa Clara, California. It was my first time to visit California, let alone Silicon Valley (I don’t count my layover at LAX a couple of years ago).

Pre-Conference

My co-worker Brian and I flew into San Jose on Monday, and decided to take a tour around a few of the geek sites in the area. We took our rental car and meandered our way up to Mountain View, where we stopped for a quick visit to the Googleplex, and back down to Cupertino where we stopped to visit the Apple campus. It was a fun few hours before we headed to the Santa Clara Convention Center for the conference registration.

The Conference

The conference ran 9 concurrent sessions along two main tracks: 5 sessions in the SpringOne track, pertaining to the Spring ecosystem; and 4 sessions in the 2GX track, focusing on the Groovy/Grails ecosystem. Being as I am in the position in my company for leading a Grails-focused project, I chose to stay solely in the 2GX track. The sessions I attended were:

  • Lift-off with Groovy 2.1 – Guillaume LaForge
  • Advanced Web Development Techniques With Grails 2 – Jeff Scott Brown
  • Road to Grails 3.0 – Graeme Rocher
  • Type checking your DSLs – Cedric Champeau
  • Making Spring Groovy – Kenneth Kousen
  • Creating Groovy DSLs that Developers can Actually Use – Guillaume LaForge and Paul King
  • Leveraging Groovy for Capturing Business Rules – Paul King
  • Application Architecture in Groovy – Daniel Woods
  • RESTful Groovy – Kenneth Kousen
  • A Groovy Mullet: JavaScript in the front, Groovy in the back – Kenneth Kousen
  • Testing Grails: Experiencies from the field – Colin Harrington
  • Case Study – Using Grails in the Real World – Greg Turnquist
  • Becoming Productive Groovy/Grails and Spring Developer with IntelliJ IDEA – Andrey Cheptsov
  • My Top Takeaways

    • Groovy is now first-class in the Spring ecosystem
    • Grails 2.3 makes big leaps in functionality
    • DSLs are a powerful toolthat you can use to bridge the gap between users and developers
    • REST, REST, REST, REST
    • Spring Boot is cool, but not sure how it fits in the scheme of the whole ecosystem
    • IntelliJ is awesome for Groovy/Grails development (I already knew this, as I am a convert from STS)
Posted in Grails, Groovy, Spring | Tagged , , , , , , , , , | Leave a comment

Grails cascade validation for POGOs

Recently, I have been working on some code that does not use any of the GORM capabilities in Grails, but instead controllers call to a service layer which interacts with web services hosted on an ESB. The domain classes that are in use are not understood by Grails to be the domain artefact type and as such, do not inherit certain traits. One of the traits that is missing is the ability to cascade validation from the object being validated down to any child objects. Let me illustrate.

Let’s say that we have a class Person which has some properties. One of these is a residential address, which is of type Address.

import grails.validation.Validateable

@Validateable
class Person {
    String firstName
    String lastName
    Address residenceAddress

    static constraints = {
        firstName  blank: false //other constraints
        lastName   blank: false //other constraints
    }
}

@Validateable
class Address {
    String line1
    String line2
    String city
    String state
    String postalCode

    static constraints = {
        line1       blank: false //other constraints
        city        blank: false //other constraints
        state       blank: false //other constraints
        postalCode  blank: false //other constraints
    }
}

Since the Person class is a POGO and not a Grails domain artefact, the first thing we need to do to make this class capable of being validated during Grails controller binding is to mark the class with @Validateable. Then we can add the static constraints block and it will be used to evaluate/validate the properties during binding.

Issues arise when we need to validate the residenceAddress property of Person. How can we accomplish this? One way to do this is to manually validate the properties, and report any errors.

class MyController {
    // ...
    def personSubmit(Person p) {
        // ...
        // p is already validated, except for residenceAddress
        def anyErrors = p.hasErrors() || 
                        !p.residenceAddress.validate()
        if(anyErrors) {
            // report errors ...
        }
    }
}

The problem with the above approach is two-fold. First, it doesn’t scale. We shouldn’t be validating the parent object and then again validating a child property. Imagine if this class had multiple child properties that were themselves object that again contained properties that were objects. What a nightmare to validate. Second, since you are manually invoking the validate method out of sequence with what is in the constraints block, any errors are reported back within their own object and there is no way to know what the original sequence was for the errors. This is particularly annoying when you need to display errors to a user that were part of a form submission and they are listed out in an order inconsistent with the layout of the form.

So, I decided that I would write some code that would would provide the functionality that is missing with POGOs.

import org.codehaus.groovy.grails.validation.*
import org.springframework.validation.*

class CascadeValidationConstraint extends AbstractVetoingConstraint {

    public static final String NAME = "cascadeValidation"

    @Override
    String getName() {
        NAME
    }

    @Override
    boolean supports(Class type) {
        true
    }

    @Override
    public void setParameter(Object constraintParameter) {
        if (!(constraintParameter instanceof Boolean)) {
            throw new IllegalArgumentException(
                """Parameter for constraint [$name] of 
                   property [$constraintPropertyName] 
                   of class [$constraintOwningClass] 
                   must be a Boolean
                """
            )
        }
        super.setParameter(constraintParameter)
    }

    @Override
    protected boolean skipNullValues() {
        return true
    }

    @Override
    protected boolean processValidateWithVetoing(
            Object target, Object propertyValue, 
            Errors errors) {
        if (!propertyValue.validate()) {
            propertyValue.errors.fieldErrors.each {
                String field = "${propertyName}.${it.field}"
                def fieldError = new FieldError(
                    target.errors.objectName, 
                    field, 
                    it.rejectedValue, 
                    it.bindingFailure, 
                    it.codes, 
                    it.arguments, 
                    it.defaultMessage
                )
                errors.addError(fieldError)
            }
            return false
        }
        return true
    }
}

What the above constraint does is validate the given property, and if it doesn’t pass validation according to the constraints block defined on that class, adds each error as a FieldError to the property’s parent object at the correct field location. Then you just need to register your custom constraint. You can do this in Config.groovy, Bootstrap.groovy, or during plug-in initialization if you build this into a plug-in.

import org.codehaus.groovy.grails.validation

ConstrainedProperty.registerNewConstraint(
    CascadeValdiationConstraint .NAME, 
    CascadeValdiationConstraint .class
)

Now our Person class can be defined as follows and all validations are handled as expected (note the highlighted line below).

import grails.validation.Validateable

@Validateable
class Person {
    String firstName
    String lastName
    Address residenceAddress

    static constraints = {
        firstName        blank: false //other constraints
        lastName         blank: false //other constraints
        residenceAddress cascadeValidation: true
    }
}

@Validateable
class Address {
    String line1
    String line2
    String city
    String state
    String postalCode

    static constraints = {
        line1       blank: false //other constraints
        city        blank: false //other constraints
        state       blank: false //other constraints
        postalCode  blank: false //other constraints
    }
}
Posted in Grails | Tagged , , , | 3 Comments

The Agile Mindset

I was thinking back on an interaction I had with one of my co-workers last week, and how that made me realize that I have personally had a shift with how I identify myself at work.

This co-worker is relatively new to the company, only having been here for a few weeks, and I hadn’t had opportunity to introduce myself. The other piece of background here is to know that only part of our organization has operated under an Agile framework; the rest is still using a “traditional” system. We had the usual exchange of names. But when they asked me who I worked for, my first response is what made me have the epiphany. I didn’t say my manager’s name, I didn’t say “development” or even the project I am working on. I said “the Honey Badgers”, which is the name we have given to our Scrum team that started together back in 02/2012.

If asked that question before 02/2012, I can almost guarantee you I would have said “development” or “I’m a developer” or something to that effect. This is the change in mindset I am referring to. If you are like me, you will no longer find yourself identifying solely with your “silo” department; you will identify with the team you have been a part of and built a relationship with over the course of time. This is to take nothing away from my fellow developers or my respect for them. I actually think it is a good thing for the team and the organization when you start to identify yourself this way. It shows that you have invested yourself in your team and have dedicated yourself to the success of what your team produces.

What do you think? If you haven transitioned towards an Agile team from some other sort of management, have you also have this same shift in your mindset?

Posted in Agile, Scrum | Tagged , , , , | Leave a comment