Since Groovy 1.8.7 we can create a list and use the withDefault()
method to define a default value for elements that are not yet in the list. We use a closure as argument of the method, which returns the default value. We can even access the index of the element in the closure as an argument.
Besides the withDefault()
method we can use the withLazyDefault()
which is just another name for the same functionality. If we request a value for an index that is greater or equal to the size of the list, the list will automatically grow up to the specified index. Any gaps are filled with the value null
.
Continue reading →
Most people working in professional IT-driven companies, have heard about Agile, most people in professional companies have heard about Lean. Those who are interested in the subject, have found out that these two very popular phrases are actually closely related. So what is the relation between lean and agile? I'll try to briefly answer this question and will start with a little history.
Contrary to popular belief, the origins of Lean aren't in Japan, but derive from the Ford company in America and the work of the American statistician W. Edwards Deming. The following excerpt states the heart of his philosophy:
Continue reading →
Since Groovy 1.8.7 we can use the first()
and last()
methods on Iterable
objects. With the first()
method we get the first element and with the last()
method we get the last element:
def list = 0..100
assert list.first() == 0
assert list.last() == 100
def abc = 'abc' as Character[]
assert abc.first() == 'a'
assert abc.last() == 'c'
def s = ['Groovy', 'Gradle', 'Grails', 'Rocks'] as Set
assert s.first() == 'Groovy'
assert s.last() == 'Rocks'
Continue reading →
Git supports hooks, which are scripts that are fired when certain events happens. The scripts are simply shell scripts and we can use Groovy to run those scripts. We must make Groovy the script language with the hash-bang (#!
) header in the Git hook script file. And then we are ready to go and use Groovy as the script language for the Git hooks.
Git hooks are placed in the .git/hooks
directory of our project. We create an example script that will use growlnotify
to create a notification message with information from the Git commit action. growlnotify
is a command-line tool for Mac OSX to send out messages to Growl. Other operating systems also have tools to create notification message from the command-line.
Continue reading →
We can use the Gradle announce
plugin to send announcements from the build process. We can send data to Twitter (I don't know if our followers are waiting for this, but if you want to you can), but also to notification applications on our local computers. For Mac OSX Growl is supported, for Linux notify-send and for Windows Snarl.
The plugin adds an announce
object with the announce()
method. The method accepts two arguments. The first argument is the message and the second argument is either twitter
or local
to indicate where to send the announcement.
Continue reading →
Like most Java developers I used to have a serious aversion to JavaScript. I was quite happy to delegate any 'scripting' stuff to fellow developers. At my current project, we initially decided to use the Vaadin web framework. It seemed the perfect choice for creating Rich Internet Application (RIA) user-interfaces without writing a single line of JavaScript. However what originally seemed to be a sensible choice, turned out to be a dead-end:
- Vaadin is highly dependent on http sessions and as it turns out doesn't play well when being clustered.
- No default support for server push; also the 'most stable' Vaadin add-on turned out to be quite unstable and incompatible with clustering.
- No wrapper existed for v3 of Google Maps; as an alternative we used the OpenLayers Add-on instead. However this add-on turned out to be not so stable either and lacked the user experience of Google Maps to which users are accustomed to (like dragging the 'pegman' on the map in order to show street view).
Continue reading →
Sometimes we are working on an application where we have no control over specific Spring bean implementations. Nevertheless we want to check for the existence (or duplication) of these bean implementations during start-up of the application server. Since Spring version 3.0 it is possible to use Spring's ApplicationListener. This interface is based on the EventListener and uses the standard Observer design pattern. In 3 steps we can easily check for the existence of a specific Spring bean.
We create an ApplicationListener<ContextRefreshedEvent> implementation. The method onApplicationEvent will be called when a refresh of the ApplicationContext occurs.
package com.jdriven.blog.applicationlistener;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
public class BeanContextStartupListener
implements ApplicationListener<ContextRefreshedEvent>
{
public void onApplicationEvent( ContextRefreshedEvent event )
{
...
}
}
We need to register the BeanContextStartupListener as a Spring Component. In this sample we just simply enable component scanning in the spring xml configuration as follows.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.jdriven.blog.applicationlistener" />
</beans>
We also add the @Component
to the class definition:
import org.springframework.stereotype.Component;
@Component
public class BeanContextStartupListener
implements ApplicationListener<ContextRefreshedEvent>
We implement the onApplicationEvent method of the BeanContextStartupListener and throw an Exception when no bean exists within the current ApplicationContext.
public void onApplicationEvent( ContextRefreshedEvent event )
{
Map serviceImplementations = event.getApplicationContext().getBeansOfType( JDrivenService.class );
if ( serviceImplementations.isEmpty() ) {
throw new IllegalStateException("JDrivenService was not instantiated during startup.");
}
}
Continue reading →
Groovy closures are powerful. A closure can be passed to methods as argument or defined as a variable. We can even return closures from methods or other closures. We can use the returned closure to execute the logic from the closure with the explicit call()
method or the implicit syntax with just the closure object followed by opening and closing parentheses (()
).
// Method returns a closure. Method could
// also have been another closure to return
// the closure.
def repeater(times) {
{ value -> value * times }
}
// Use explicit call() method on the return closure
// object from the repeater() method.
assert repeater(2).call('mrhaki') == 'mrhakimrhaki'
// Use implicit call() method on the return closure
// object from the repeater() method. This
// might looks strange at first...
assert repeater(2)('mrhaki') == 'mrhakimrhaki'
Continue reading →
Two of the most famous mocking frameworks EasyMock and Mockito, don't offer out of the box support for mocking final and static methods. It is often said on forums that "you don't want that" or "your code is badly designed" etc. Well this might be true some of the time, but not all of the time. So let's suppose you do have a valid reason to want to mock final or static methods, PowerMock allows you to do it. Here's how (example with Mockito):
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.4.12</version>
<scope>test</scope>
</dependency>
Continue reading →
Since Groovy 2 we can use a subset of the Project Coin features from Java 7. But we don't have to run Java 7 to use them in Groovy code. We can use the new features even if we run our Groovy code on older Java versions.
Groovy didn't have to add all Project Coin features, because some are already supported in Groovy, like the switch
statement on String
objects or diamond operator. A feature that is added is a syntax enhancement to define binary literals. We can now use binary integral literals by prefixing the value with 0b
:
Continue reading →
In Groovy we can use the drop()
and take()
methods to get elements from a collection or String
object. Since Groovy 1.8.7 we also can use the dropWhile()
and takeWhile()
methods and use a closure to define a condition to stop dropping or taking elements. With the dropWhile()
method we drop elements or characters until the condition in the closure is true
. And the takeWhile()
method returns elements from a collection or characters from a String
until the condition of the closure is true
. In the following example we see how we can use the methods:
def s = "Groovy Rocks!"
assert s.takeWhile { it != 'R' } == 'Groovy '
assert s.dropWhile { it != 'R' } == 'Rocks!'
def list = 0..10
assert 0..4 == list.takeWhile { it < 5 }
assert 5..10 == list.dropWhile { it < 5 }
def m = [name: 'mrhaki', loves: 'Groovy', worksAt: 'JDriven']
assert [name: 'mrhaki'] == m.takeWhile { key, value -> key.length() == 4 }
assert [loves: 'Groovy', worksAt: 'JDriven'] == m.dropWhile { it.key == 'name' }
Continue reading →
Mockito has a very nice feature that allows you to verify what parameters were used when a method was executed. For example:
ArgumentCaptor argument = ArgumentCaptor.forClass(Person.class);
verify(mock).doSomething(argument.capture());
assertEquals("John", argument.getValue().getName());
Continue reading →