How to remove execute bit from files in Git

Occasionally, files get committed to source control having the wrong file permissions. Either they don’t have execute when they should, or they have execute when they shouldn’t, just for example. I came across this a couple of weeks ago and came up with the following solution. It changes the file permissions recursively on files and also does the same to the Git index. Please refer to the Git documentation for config.fileMode for more information on why this might happen.

asoftwareguy@Intrepid:~/Projects/a$ find -executable -type f -exec git update-index --chmod=-x {} \;
asoftwareguy@Intrepid:~/Projects/a$ find -executable -type f -exec chmod -x {} \;
asoftwareguy@Intrepid:~/Projects/a$ git status
asoftwareguy@Intrepid:~/Projects/a$ git commit -m "Changing file permissions to remove execute bit"
asoftwareguy@Intrepid:~/Projects/a$ git push
Posted in bash, Git, Scripting, Source Control | Tagged , , , , , , | Leave a comment

Spring Security with Grails 3

I am a big user and advocate of Grails, and I was curious about working with Grails 3, so I started taking a look at it during the M2 release. Most of the applications I work on require authentication/authorization, and all of them that do so, use Spring Security to do it.

In the Grails 2.x applications I have worked on, I have always used the awesome Grails Spring Security plugin. I noticed that so far, it hasn’t been updated to support working with Grails 3, but I don’t see that as a huge issue. I had been a Spring developer long before I had come to Grails, so I figured I would just tackle the problem the “old-fashioned way” with Spring Beans and DI.

I won’t go over the demo here in this blog post. You can find the code out on GitHub, and the README explains how to run through the different scenarios for authentication/authorization. Hopefully my code can help you out, if you are looking to start integrating Spring Security with Grails 3, and need to do so before a plugin is available for use.

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

Interesting use of Java 8 interface default method


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) {

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

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 = ''
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


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 = true = 401 = true = 'com.asoftwareguy.example.auth.AuthenticationToken' = 'token' = '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 = 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")
            Role roleUser = new Role(authority: "ROLE_USER")
            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', [
          // 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');
                  scope.$on('event:auth-loginRequired', function() {
                      console.log('showing login form');
                  scope.$on('event:auth-loginFailed', function() {
                      console.log('showing login error message');
                  scope.$on('event:auth-loginConfirmed', function() {
                      console.log('hiding login form');
      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]-->
      		<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"/>
      	<body class="show-login">
              <div class="page-header container">
                  <div class="row">
                      <div class="span6">
                          Welcome to Example App!
                      <div class="span6" style="text-align: right;" ng-controller="logoutController">
                          Welcome, username.
                          <a href="" ng-click="logOut()">(Log out)</a>
                  <div class="row" style="text-align: right;">
              <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 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 class="form-group">
                                  <label for="password">Password</label>
                                  <input id="password" class="form-control" type="password" ng-model="authData.password"/>
                              <input type="submit" class="btn btn-primary" value="Login"/>
                      <div class="clear"></div>
              <div id="content" class="container">
    6. Define your login controller(s):
      var login = angular.module('login', []);
          function ($rootScope, $scope, $http, authService) {
              console.log('loginController called');
              $scope.logIn = function() {
                  console.log('logIn called')
                  $'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);
          function ($scope, $http, $location) {
              console.log('logoutController called');
              $scope.logOut = function() {
                  console.log('logOut called');
                  $'api/logout', {}, getHttpConfig()).
                      success(function() {
                          console.log('logout success');
                      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.


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 , , , , , | 35 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).


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