Archive: 2014

Groovy Goodness: More Efficient Tail Recursion With TailRecursive Annotation

Posted on by  
Hubert Klein Ikkink

Since Groovy 1.8 we can use the trampoline method for a closure to get better recursive behavior for tail recursion. All closure invocations are then invoked sequentially instead of stacked, so there is no StackOverFlowError. As from Groovy 2.3 we can use this for recursive methods as well with the @TailRecursive AST transformation. If we apply the annotation to our method with tail recursion the method invocations will be sequential and not stacked, like with the closure's trampoline method.

import groovy.transform.TailRecursive

@TailRecursive
long sizeOfList(list, counter = 0) {
    if (list.size() == 0) {
        counter
    } else {
       sizeOfList(list.tail(), counter + 1)
    }
}

// Without @TailRecursive a StackOverFlowError
// is thrown.
assert sizeOfList(1..10000) == 10000

Continue reading →

Awesome Asciidoc: Explain Code with Callouts

Posted on by  
Hubert Klein Ikkink

Writing documentation with Asciidoc is such a treat. We can add markers to our code where we want to explain something in our code. The markers have numbers and are enclosed in < and > brackets. The explanation for the markers follows a code listing in a callout list. Here we use the same marker and add extra text to explain the code. We can put the markers in comments in our code so we can use the markers in existing code.

Suppose we have the following piece of documentation where we add two markers (in comments) to some Groovy source code:

Continue reading →

Grails Goodness: Using Aliases as Command Shortcuts

Posted on by  
Hubert Klein Ikkink

In Grails we can add aliases for standard Grails commands with the alias command. For example we want to use another name for a command or combine a command with arguments to a single alias. With the following command we create a start-app alias for the standard run-app command:

$ grails alias start-app run-app
Alias start-app with value run-app configured
$

Continue reading →

Awesome Asciidoc: Include Partial Parts from Code Samples

Posted on by  
Hubert Klein Ikkink

Writing technical documentation with Asciidoc and Asciidoctor is so much fun. Especially the include macro makes inserting changing content, like source files, a breeze. We only need to maintain the original source file and changes will automatically appear in the generated documentation. We can include only a part of source file using tags. In the source file we add a comment with the following format tag::_tagName_[] to start the section. We end the section with end::_tagName_[]. Now in our Asciidoc document we can indicatie the tags we want to include with include::_sourceFile_[tags=_tagName_].

Suppose we have the following Groovy source file Sample.groovy. We want to include the method hello() in our technical documentation:

Continue reading →

Groovy Goodness: Define Compilation Customizers With Builder Syntax

Posted on by  
Hubert Klein Ikkink

Since Groovy 2.1 we can use a nice builder syntax to define customizers for a CompileConfiguration instance. We must use the static withConfig method of the class CompilerCustomizationBuilder in the package org.codehaus.groovy.control.customizers.builder. We pass a closure with the code to define and register the customizers. For all the different customizers like ImportCustomizer, SecureASTCustomizers and ASTTransformationCustomizer there is a nice compact syntax.

In the following sample we use this builder syntax to define different customizers for a CompileConfiguration instance:

Continue reading →

Groovy Goodness: Restricting Script Syntax With SecureASTCustomizer

Posted on by  
Hubert Klein Ikkink

Running Groovy scripts with GroovyShell is easy. We can for example incorporate a Domain Specific Language (DSL) in our application where the DSL is expressed in Groovy code and executed by GroovyShell. To limit the constructs that can be used in the DSL (which is Groovy code) we can apply a SecureASTCustomizer to the GroovyShell configuration. With the SecureASTCustomizer the Abstract Syntax Tree (AST) is inspected, we cannot define runtime checks here. We can for example disallow the definition of closures and methods in the DSL script. Or we can limit the tokens to be used to just a plus or minus token. To have even more control we can implement the StatementChecker and ExpressionChecker interface to determine if a specific statement or expression is allowed or not.

In the following sample we first use the properties of the SecureASTCustomizer class to define what is possible and not within the script:

Continue reading →

Groovy Goodness: Customize ToString Creation

Posted on by  
Hubert Klein Ikkink

The @ToString AST transformation has several parameters we can define to customize the generated code for the toString method. We have already seen some of the parameters in an earlier blog post, but in new Groovy releases some extra parameters were added.

For example we can leave out the package name of the class with the parameter includePackage. If we set the value to false the package name is not included:

Continue reading →

An exploration on locking and atomicity in Redis

Posted on by  
Robbert van Waveren

Lately I've been doing some development of a turn based browser game using node.js and Redis. Being intended to run on multiple node.js instances and each instance also being able to "autoplay" for afk users, it was clearly lacking a semaphore of some sort to make sure only one action at the time would be processed per game across all nodes. With Redis being my central persistence component I figured this was a good time to dive a bit deeper in the capabilities of Redis when it comes to locking. As it turns out locking makes a great use-case to learn about the true power of some of the most basic Redis commands. So while this blog post is definitely about locking with Redis, its actually more about how common Redis commands can be used to solve some pretty complex issues. Generally locking patterns can be divided into pessimistic and optimistic. In this blog I'm focusing on the creation of a general purpose (pessimistic) lock/semaphore that could be used for anything that requires limiting access to a resource or piece of code really. The third example also uses the build-in optimistic locking capabilities of Redis to solve to a race condition issue. Keep in mind though, that in either case it is the client that is responsible for maintaining the relation between "the lock" and "the resource". Lets start with the oldest and most common locking pattern and work our way through from there.   1. SETNX/GETSET based locking The commands of choice for the first example (works on all Redis versions): SETNX only sets a key to a value if it does Not eXists yet. GETSET gets an old value and sets it to a new value atomically!

var redis = require('redis');
var nameOfKeyToLock = 'the_lock';
var timeout = 10000;
var retry_time = 500;

var doLocked = function(client, nameOfKeyToLock, callback){
  var lock = function() {

    var newLockValue = Date.now() + timeout;

    //SETNX command
    client.setnx(nameOfKeyToLock, newLockValue, function(err, result){
      if(result === 0){
        client.get(nameOfKeyToLock, function(err, currentValue){
          currentValue = parseFloat(currentValue);
          if(currentValue > Date.now()){
            //lock still valid, retry later
            return retry();
          }

          newLockValue = Date.now() + timeout;
          //GETSET command
          client.getset(nameOfKeyToLock, newLockValue, function(err, check){
            if(currentValue == check){
              //old value was still the same, so now the lock is ours
              return callback(unlock);
            }
            retry();
          });
        });
      } else {
        //no lock was present, we now got it
        callback(unlock);
      }
    });

    var unlock = function(after){
      if(newLockValue > Date.now()){
        client.del(nameOfKeyToLock, function(){
          console.log('released lock');
          after();
        });
      } else {
        after();
      }
    };
  };
  var retry = function() {
    console.log('scheduling retry');
    setTimeout(lock, retry_time);
  }
  lock();
};

Continue reading →

Grails Goodness: Extending IntegrateWith Command

Posted on by  
Hubert Klein Ikkink

We can extend the integrate-with command in Grails to generate files for a custom IDE or build system. We must add a _Events.groovy file to our Grails projects and then write an implementation for the eventIntegrateWithStart event. Inside the event we must define a new closure with our code to generate files. The name of the closure must have the following pattern: binding.integrate_CustomIdentifier_. The value for CustomIdentifier can be used as an argument for the integrate-with command.

Suppose we want to extend integrate-with to generate a simple Sublime Text project file. First we create a template Sublime Text project file where we define folders for a Grails application. We create the folder src/ide-support/sublimetext and add the file grailsProject.sublimetext-project with the following contents:

Continue reading →

Coloring Different Data Sources in IntelliJ IDEA

Posted on by  
Hubert Klein Ikkink

The database plugin in IntelliJ IDEA is a useful tool to work with data in databases. As long as we got a JDBC driver to connect to the database we can configure a data source. And then we can run queries, inspect the contents of tables and change data with the database tool window. It is not uncommon to have multiple data sources, for example development and test environment databases, which will have the same tables. When we open the tables or run queries we don't have a visual feedback to see to which data source such a table belongs. To have a visual feedback we can colorize our data source. This means we assign a color to a data source and when we open a table from that data source the tab color in the editor window will have a different color than other tabs or the background color of the data source objects have a color.

To add a color to a data source we must open the database tool window and right click on a data source. We select the option Color Settings... from the popup window:

Continue reading →

Groovy Goodness: Closure as Writable

Posted on by  
Hubert Klein Ikkink

In a previous post we learned about the Writable interface and how the GString implementation implements this interface. In Groovy we can also use a closure as an implementation of the Writable interface. The Closure class has the method asWritable() that will return a version of the closure with an implementation of the writeTo() method. The Writer object that is used as an argument for the writeTo() method will be passed as argument to the closure. The asWritable() method also adds a toString() implementation for the closure to return the result of a closure as a String.

In the following code we write a sample make() method. The make() method return a Writable closure. The closure is only executed when the writeTo() or toString() method is invoked.

Continue reading →

shadow-left