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 →
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 →
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 →
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 →
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 →
We can use the integrateWith
command with Grails to generate for example IDE project files and build system files. We specify via an extra argument the type of files to be generated. We can use this command also to create a .gitignore
file with some default settings for files to be ignored in Grails projects.
$ grails integrate-with --git
Continue reading →
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 →
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 →
The Groovy API has the interface Writable. Classes that implement this interface are capable of writing their selves to a java.io.Writer
object. The interface has one method writeTo()
where the code is that writes the contents to a given Writer
instance. Most implementations will also use the implementation of the writeTo()
method in their toString()
implementation.
The GString implementation in Groovy also implements the Writable
interface. This means we can redirect the GString contents to some Writer
instance if we want to. In the following code we use a FileWriter
to write the contents of a GString to a file:
Continue reading →
To convert a byte[]
array to a String
we can simply use the new String(byte[])
constructor. But if the array contains non-printable bytes we don't get a good representation. In Groovy we can use the method encodeHex()
to transform a byte[]
array to a hex String
value. The byte
elements are converted to their hexadecimal equivalents.
final byte[] printable = [109, 114, 104, 97, 107, 105]
// array with non-printable bytes 6, 27 (ACK, ESC)
final byte[] nonprintable = [109, 114, 6, 27, 104, 97, 107, 105]
assert new String(printable) == 'mrhaki'
assert new String(nonprintable) != 'mr haki'
// encodeHex() returns a Writable
final Writable printableHex = printable.encodeHex()
assert printableHex.toString() == '6d7268616b69'
final nonprintableHex = nonprintable.encodeHex().toString()
assert nonprintableHex == '6d72061b68616b69'
// Convert back
assert nonprintableHex.decodeHex() == nonprintable
Continue reading →