ICE09 . playing with java, scala, groovy and spring .

Playing with Spring

Archive for the ‘Groovy’ Category

Proxying your Web Service Requests with Gradle and Groovy

Posted by ice09 on October 13, 2012


Sometimes you have to mock a Web Service request, eg. to ensure that a client works well with a new interface.
Usually, this can be done easily with soapUI in mocking Web Servide mode:

However, in this special case several Web Services had to be called, but only some of them should be intercepted, others should just be just forwarded to the actually running Web Services.

Groovy Solution

As so often, Groovy is the perfect solution for this. There are just three files involved, with these three files, together with the Gradle Quickstart plugin of the Springsource Tool Suite Grale plugin.

So, just three steps to your Groovy Proxy Server solution:

  1. Download Springsource Too Suite and the Gradle Plugin, create a Gradle Quckstart Plugin Gradle project
  2. Create the ProxyServer Groovy script and the sample response file in src/main/resources
  3. Add the application plugin as well as the groovy plugin to the Gradle build … that’s it. I’d like to say: Gradle rocks!

The main ProxyServer Groovy script


import static*
import org.apache.http.client.ResponseHandler
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.BasicResponseHandler
import org.apache.http.impl.client.DefaultHttpClient

class ProxyHttpHandler implements HttpHandler {
        def answers = []

        ProxyHttpHandler(def answers) {
                this.answers = answers
				println "prepared answers: $answers"

        void handle(HttpExchange exchange) throws IOException {
                def reqText = exchange.requestBody.getText()
                def fileName = answers.find{ reqText.contains(it) }
                def response
                if (fileName != null) {
					println "...sending prepared answer: $fileName"
                    response = new File("${fileName}.xml").getText()
                } else {
                    println ">>> redirect >>>"

                    HttpPost builder = new HttpPost( "http://localhost:8088/mockGetCodeDecodeSoap12" )
                    StringEntity strent= new StringEntity(reqText);
                    strent.setContentType("application/soap+xml; charset=utf-8");

                    DefaultHttpClient client = new DefaultHttpClient();
                    ResponseHandler<String> responseh = new BasicResponseHandler();
                    String responseBody = client.execute(builder, responseh);
                    response = responseBody
                exchange.sendResponseHeaders(200, response.length());
                def outout = exchange.responseBody

def server = HttpServer.create(new InetSocketAddress(8080), 0);
def answers = []
def files = new File(".").eachFile {
	if ("xml")) {
		answers << - ".xml"
def context = server.createContext("/", new ProxyHttpHandler(answers));
server.executor = null
println "######################\nstarted proxyserver...\n######################"

This script scans the local directory for all XML files and stores the filenames. If a requestbody is retrieved with the Java Web Server, which has somehow the filename in it’s text (this is very fuzzy, however, it worked for our problem), the prepared text file is sent back.
If no corresponding file is found, the request is forwarded to the real service and the response is “tunneled”.

So, only the build.gradle is missing, it is the original Quickstart gradle build file, extended just with the application plugin, the groovy plugin and their configurations.

So, the application can be build with gradle installApp, which creates the complete application, which should be started in the root directory with bin/gradleapp.bat. Voila!

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'application'
apply plugin: 'groovy'

mainClassName = ""

sourceCompatibility = 1.5
version = '1.0'
jar {
    manifest {
        attributes 'Implementation-Title': 'Gradle Quickstart', 'Implementation-Version': version

repositories {

installApp {
	from 'src/main/resources'

dependencies {
	groovy group: 'org.codehaus.groovy.modules.http-builder', name: 'http-builder', version: '0.5.2'
    testCompile group: 'junit', name: 'junit', version: '4.+'

test {
    systemProperties 'property': 'value'

Posted in Groovy | Leave a Comment »

Groovy vs. Ruby – the CSV shootout (7L7W day 3)

Posted by ice09 on October 18, 2011

Nope, there is no rant here. Even more, there is no CSV shootout. However, a little CSV is here, it’s even Meta-CSV somehow.

Ok, let’s clarify this: I just started reading the book “Seven Languages in Seven Weeks” and I already like it. It’s exactly written for someone on my language-knowledge level, ie. someone who tried and used several languages and is pretty good at getting the differences between OO and functional languages, but has difficulties to explain what differentiates Clojure from Scala from Haskell from Io besides the different kinds of typing (static vs. dynamic). Someone who has heard of but never knew what prototypes are about and what specialities each language defines (the movie comparison also helps a lot. But be aware that Prolog developers have to relax a little and accept to be compared to Rain Man).

So, the first day is about Ruby. I know Groovy pretty well, so I thought that would be easy. It was. But, I realize that the subtile differences matter a lot. In short, I feel that Ruby is much more consistent (you will see by the sample). However, I like Groovy more – after all, for a Java developer it’s the much better fit. But also, I like the even more magic – which I’d hate in big production systems but really love for scripting.

So, the sample is a CSV reader – the Ruby part is much longer than it has to be, but it should show the Metaprogramming mechanisms. And I like them a lot, even more than the Groovy ones (though Categories are really cool for scoping the Metaprogramming).

class CsvRow
  attr_accessor :values, :keys
  def initialize( keys, values )
    @keys = keys
    @values = values 
  def method_missing(id, *args)
    if (id==:to_ary) 
      then return @values 
      else return @values[@keys.index(id.to_s)]

module ActsAsCsv
  def self.included(base)
    base.extend ClassMethods
  module ClassMethods
    def acts_as_csv
      include InstanceMethods
      include Enumerable
  module InstanceMethods   
    attr_accessor :headers, :csv_contents
    def each &block
    def read
      @csv_contents = []
      filename = self.class.to_s.downcase + '.txt'
      file =
      @headers = file.gets.chomp.split(';').collect{|s| s.delete("\"")}
      file.each do |row|
        values = row.chomp.split(';').collect{|s| s.delete("\"")}
        @csv_contents <<, values)
    def initialize

class RubyCsv  # no inheritance! You can mix it in
  include ActsAsCsv

m =
m.each { |it| puts it.Kontonummer }

I will not explain how this works here, there are bazillions of resources of people really knowing Ruby. The most important fact is how the Metaprogramming works – and it does it exactly as expected. Even more, it does it right. The best fact to me is that upon including the module (which unfolds itself into the base class very nicely), the include method is called automatically. There is no dependency of the RubyCsv on it’s Mixin (and there shouldn’t be!).

So, this is pretty cool. How do I achieve this in Groovy? This is diffficult, there are no modules in Groovy. Of course, Metaprogramming is easy in Groovy, but I want it to mimick the Ruby script.

The most I can get is by using the Groovy 1.6 @Mixin annotation like this:

class CsvRow {
    def keys = []
    def values = []
    def propertyMissing(String name) { 

class ActAsCsv {
    public headers = []
    public csvRows = []
    def read(def instance) {
        new File("rubycsv.txt").eachLine {
            if (instance.headers.isEmpty()) {
                instance.headers = it.trim().split(';').collect{it.replaceAll("\"", "")}
            } else {
                def values = it.trim().split(';').collect{it.replaceAll("\"", "")}
                instance.csvRows << new CsvRow(keys:instance.headers, values:values)

    def iterator() {

class GroovyCsv {
    GroovyCsv() {
    //@Delegate ActAsCsv acter = new ActAsCsv()

def act = new GroovyCsv()
println act.collect { it.Buchungstext.reverse() }
act.each { println it.Kontonummer }

So, this is nice as well, but compared to Ruby it’s more clumsy. The worst thing is the trick with calling the Mixin in the constructor with the this reference. It does not work otherwise, since the fields cannot be set on the Mixin-GroovyCsv-instance itself. This is weird and costs time to debug. It is not a real dependency upon the Mixin itself, but it’s just superfluous.
Also, the nice template method style of including modules in Ruby is not the same. It fells better in Ruby (look up the Enumerable inclusion, it’s really nice). On the other hand, just having to declare iterator() the right way to get rid of all Metaprogamming to implement the Collection methods correctly is cool as well. Also, I found it cleaner to use the @Delegate possibility, which works exactly as expected (no this weirdness here).

It’s as always, there is no best way, I like both versions a lot. I still feel that Ruby feels cleaner, but I can achieve everything in Groovy with the same “expressiveness”. But I can use all Java and all it’s environment and tools as well – so jep, to me it’s the better choice. But I see where a lot of the good stuff in Groovy comes from.

Posted in Groovy, Ruby | Leave a Comment »

DSLs made easy – with Groovy’s chain method calls (GEP 3)

Posted by ice09 on October 7, 2011

As you probably know, the creation of DSLs is quite easy these days. Take Groovy or Scala and the creation of internal DSLs is a day’s work. Take Xtext 2.0 and the creation of an external DSL is a two days’s work.

However, let’s assume you do not have a day, but two hours left – still possible? Yes, indeed. With Groovy 1.8 and its new chained method calls (contributed by GEP 3).

So, chained method calls have always be possible in Groovy, but the new “conventions” of GEP 3 make the creation of a DSL really straightforward, since with a little effort you can design a DSL which has no brackets and dots at all!

.use case.

A sample use case for a simple DSL is the evaluation of account data. I wanted to have

  • the possibility to parse downloaded CSV files
  • enrich the items with certain categories
  • store them in a local (file based) database
  • be able to evaluate the items for certain time spans and categories

Having thought about the GUI which I would have to create for this use case, I felt overwhelmed immediately, given that my design capabilities are … debatable. But also, I would like to be able to use the data in several ways, transform it, check and validate it and so on. For this I do not want to create my own command set, but I want to use Groovy commands for this. Namely, I want to create an internal DSL.


The following commands I can think of. However, this is not complete

load savingsfile     scans a predefined directory for the newest CSV file with a certain pattern and reads this file into memory 
                     (as a list of string arrays)
filter database      filter the data in memory against a predefined database file and remove all items from memory which are in the 
                     database already (depends on load step)
categorize data      use a certain rule set (external configuration) to automatically categorize the items according to different properties
                     (like sender/receiver of money)
show data            show the actual data in memory
save database        store the actual data in database file (filter step must be executed first)

Moreover, the DSL should allow for evaluating the data in memory, with the following syntax

evaluation of date september, 2011 category "Clubbing" with display           evaluate the database and display evaluation for 
                                                                              september, 2011 in category "Clubbing"
evaluation of date always category "Clubbing" without display                 same as above, but for no specified time span
evaluation of date always category all with display                           same as above, but for no specified time span and no specified category
evaluation of date always category all without display                        same as above, but without display of data (yes, it might not make sense -
                                                                              but it's possible :))

Now, the thing is that I would like to be able to execute all these commands several times, for different data and – since the data is available as a list of string arrays – I know I can do whatever I want with it within Groovy.
So, if I do not have a GUI, what about a shell? Of course, Groovy has one. What about TAB completion on my shiny new DSL – sure, why not? (ok, honestly, due to type inferencing difficulties, this does not work completely, but it’s a help definitely – just try it!)

So, let’s go. Just start the Groovy shell (GROOVY_HOME/bin/groovysh) and copy & paste this code. Yes, that’s just the skeleton to show the important parts – but there is a working version here, which works if you are customer of the German Sparkasse (shouldn’t they pay me for this?). If you really want to use this “real”, working version, you will need a rule file, which must be named and has key/value pairs of regular expressions for the sender field like PAYPAL=Paypal or ^GA=Geldautomat.

class Savings {
    def read = false
    def filtered = false
    def datenbank
    Savings(datenbank) {
        this.datenbank = datenbank
    def load(sfile) {
        read = true
        println "file loaded."
    def display(dummy) {
        if (!read) println "no data available."
        else println "display called."
    def filter(sfile) {
        filtered = true
        println "data is filtered."
    def categorize(cat) {
        println "categorize called with category ${cat}."
    def save(sfile) {
        if (!filtered) println "data is not filtered, aborting storing."
        else println "data is stored in file $datenbank"; read = false

class Evaluation {
    def month
    def year
    def display = false
    def category
    def date(Integer month, Integer year) {
        this.month = month
        this.year = year
    def date(all) {
        this.month = null
        this.year = null
    def without(display) {
        this.display = false
    def with(ausgabe) {
        this.display = true
    def category(category) {
        if (category.toString() != "all")
            this.category = category
    def evaluate() {
        println "evaluate ${(month != null) ? "month ${month+1} year $year" : "all"} in category $category ${display ? "with":"without"} display"

enum words { savingsfile, category, of, data, database, all, always, with, without, display }
(january, february, march, april, may, june, july, august, september, october, november, december) = (0..11)
datenbank = "db.csv"
import static words.*

savings = new Savings(datenbank)

read = { file -> savings.load(file) }
showit = { speicher -> savings.display()}
filter = { file -> savings.filter(file)}
categorize = { speicher -> savings.categorize(speicher)}
store = { file ->}
evaluation = { of -> new Evaluation() }

//sample commands

read savingsfile
filter database
categorize data
showit data
store database

evaluation of date september, 2011 category "Clubbing" with display
evaluation of date always category "Clubbing" without display
evaluation of date always category all with display
evaluation of date always category all without display

The last lines (from //sample commands) are actual commands of the DSL. Try these with TAB completion in the shell and see what’s possible and what’s not. I will not explain the functionality in detail, because there are several resources which can be used for clarification.


I wanted to show that two hours can be enough to create your own DSL, together with the Groovy shell this is a really powerful way to let people with limited technical abilities use the power of the complete Java/Groovy platform in interactive mode! Imagine the possibilities – your business analysts will love you.

Obviously, I had to fit the DSL to the conventions of GEP 3 (and moreover, I had to rename “load”, “show” and “save”, since these are reserved keywords in the Groovy shell…), but still I think it’s worth it. But if you take care of DSL design and do not want the language to be restricted by the command chain conventions, look for a cleaner approach. For quick & dirty API usage easing, this works as a charm.

If this blog post was useful to you, you can tip me. Maybe you do not want to tip, but please inform yourself about Bitcoin and applications of Bitcoin like Youttipit.

Posted in DSL, Groovy | Leave a Comment »

QuickTip: SCP with Groovy, Maven and Eclipse

Posted by ice09 on December 20, 2010


It’s easy to use SCP with Java, Groovy and even with Maven. However, it gets more complicated if you want to use all of them simultaneously.

It should work this way: An (key-file-based) SCP-connection should take place in a Groovy, so the transferred file can be manipulated straight away. All this should be triggered by a Maven build process and alternatively, using Eclipse with the Groovy plugin, it should be possible to directly start the Groovy script.


Either Eclipse with the Groovy plugin and the Maven plugin or the SpringSource Tool Suite (which includes both plugins) should be installed.

Maven config

The Maven config consists of two dependencies:

  1. The Ant-SCP-Plugin, which is based on JSch
  2. Embedded Groovy (groovy-all.jar)

And two Maven Plugins:

  1. GMaven
  2. The Exec Maven Plugin

<project xmlns="" xmlns:xsi=""


Here comes the Groovy part, in fact it’s quite short, since it focuses on the file transfer part. Obviously, it would be easy to manipulate the transferred files after the SCP-transfer, since we are inside a Groovy script and we can use whatever Java library we want since we are inside a Maven project. The universe is ours!

package de.ice09.scp

new AntBuilder()

The file must go to src/main/groovy for GMaven to work. The key must be OpenSSH-compliant. If you use PuTTY, you can export this format. Alternatively, you can use username/password instead.


After creating a new Maven project with the pom.xml listed above, more than half of the work is done. With or without an IDE this can be tested. Just run

maven clean install exec:java

GMaven should generate the Java stubs, the Execution Plugin should execute the generated Java class file. The dependencies for JSch, Antbuilder etc. are handled by Maven or Groovy itself.

Eclipse config

The final step is to enable the Groovy nature in Eclipse. This leads us to a faster development cycle, since the Groovy script can be run “natively”, without having Maven to generate the Java stub before. There is no problem running the two options (Groovy with Maven and Eclipse) side-by-side, so it is really easy to develop and deploy, since there is no big difference. You always have a completely runnable version available, given that Maven is installed on the target system.

Convert to Groovy project


Add Groovy sources (from src/main/groovy) to classpath


The deployable way: start process using GMaven and Execution Plugin

2010-12-20_23-36_Run Configurations

Start in development mode using the Groovy Eclipse Plugin


Posted in Groovy, Maven | 1 Comment »

File monitoring with Groovy, JMX and Vaadin

Posted by ice09 on December 1, 2009

Note: The complete sourcecode is available on github here. For just downloading, unzipping and importing the project into Eclipse, press on the github site (detailed instructions below).

Besides the Google Web Toolkit (GWT), there is a nice web application framework for Java-only users called Vaadin.
Out-of-the-box, it has a more polished interface and prettier components than GWT.
I used it in a small application, my experience was very positive, even though I used Vaadin in a non-standard way (periodic asynchronous updating of a component by a infinitely running process), it works very well and there was really good support by the Vaadin team.
Note: This post is not an introduction to Vaadin, I hardly know it myself. A great developer-friendly entry are the sample applications. For more info, there is a step-by-step tutorial and a book for deeper understanding.


Automated testing of a web application is used in a Continuous Integration Environment. Furthermore, load/stress testing of the web application takes place in a Performance Test setting. A process should monitor logfiles in these test environments and report errors in a web-based report.

Technically, a thread must monitor several logfiles, aggregate these errors in a managed component which must be analyzed by a visualizing component (eg. a automatically refreshing table), which must be accessible from several clients.

So, now with technological annotations…

Technically, a thread must monitor several logfiles (Groovy), aggregate these errors in a managed component (Groovy, JMX) which must be analyzed by a visualizing component (eg. a automatically refreshing table), which must be accessible from several clients (web based, Vaadin).

Ok, lets go.

The “server side components”

The server side just consists of a simple Groovy script:

import groovy.jmx.builder.*
import java.rmi.registry.LocateRegistry

class ServerState implements Serializable {
    def list=[]
def jmxbean = new ServerState()

Thread.start {
    def jmx = new JmxBuilder()
    def beans = jmx.export {
        bean(name: "jmx.builder:type=ExportedObject", jmxbean)
    jmx.connectorServer(port: 9000).start()

def worker = { logfile ->
    println "analyzing ${logfile}"
    logfile.withReader { reader -> 
        while (true) {
            def line = reader.readLine();
            if (!line) { 
            } else {
                def inner = [:]
                inner["server"] =
                inner["ts"]= new Date().toString()
                inner["error"] = line

new File("c:/temp/").eachFileMatch(~/^log.txt.*/) { file ->
    Thread.start worker.curry(file)

First, a thread is started that exports the aggregating bean via JMX (it’s so easy in Groovy).
After calling jmx.connectorServer(port: 9000).start(), the bean is available under the JNDI-Name service:jmx:rmi:///jndi/rmi://localhost:9000/jmxrmi to client processes (using the name jmx.builder:type=ExportedObject).
Afterwards, a worker closure is created. Nothing special in there, just the reader.skip(logfile.length()) makes sure the end of the file is used at the beginning (before the monitoring process starts).
The last three lines are quite dense, though. Here, all files matching the pattern (eg, log.txt, log.txt1, log.txt2) are used to create threads which monitor these files. This is easily achieved by using currying, which is described in detail here.
In this case, file is applied and the rest (the partially applicated closure) is submitted to Thread.start, which takes a closure (now with an already defined logfile) as the argument.

Tip: Using the Groovy script

All information necessary to run Groovy in any environment is stated here.
However, there is a really cool way of testing Groovy scripts without any settings, etc. Just JAVA_HOME must be set correctly.

  1. Download Groovy, unzip or install to some directory (eg. c:\dev\groovy)
  2. Set your JAVA_HOME environment variable to your Java installation (eg. set JAVA_HOME=c:\java\jdk1.6.0_17).
  3. Start groovyConsole.exe (in \$GROOVY_HOME\bin). Paste the script there. Run it.

Located in GROOVY_HOME\bin: groovyConsole

groovyConsole in action

The “client side”

Testing with jconsole

jconsole is included in the Java SDK (JAVA_HOME\bin)

The JMX-URL is determined by the Groovy script

Result of calling the exported operation getList()

Creating a web app client with Vaadin

  1. Download the Vaadin Eclipse plugin.
  2. Download the zipped files (click on ). It’s subproject Vaadin.
  3. Create new Vaadin project, choose Vaadin jar (cmp. image) – this post was tested with vaadin-6.2.nightly-20091016-c9216.jar.
  4. Delete generated src and Webcontent (!! except WEB-INF/lib !!) directores and copy from downloaded zip.

Structure and Functioning

The JMX-component to connect to Groovy-JMX-server

public class JmxService {

	private JMXServiceURL url;
	private JMXConnector jmxc;
	private MBeanServerConnection mbsc;
	private ObjectName mbeanName;
	private static JmxService INSTANCE;
	private JmxService() {
		try {
			url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9000/jmxrmi");
			jmxc = JMXConnectorFactory.connect(url, null);
			mbsc = jmxc.getMBeanServerConnection();
			mbeanName = new ObjectName("jmx.builder:type=ExportedObject");
		} catch (MalformedURLException e) {
		} catch (IOException e) {
		} catch (MalformedObjectNameException e) {
		} catch (NullPointerException e) {
	public static JmxService getInstance() {
		if (INSTANCE == null) {
			INSTANCE = new JmxService(); 
		return INSTANCE; 
	public ServerState getServerState() {
		return JMX.newMBeanProxy(mbsc, mbeanName, ServerState.class, true);


The table with its on-click-listener is created in pure Java

	private Table initTable(final IndexedContainer container) {
		final Table table = new Table();
		table.setColumnExpandRatio("error", 1);
		final Application self = this;
		table.addListener(new Table.ValueChangeListener() {
            public void valueChange(ValueChangeEvent event) {
				Object o = table.getValue();
                if (o != null) {
                	preformattedText = new Label("Here can be sources");
            	} else {
		return table;

The Refresher”pattern” is explained here, the sources are in the repository. All necessary sources are also included in the github sources to this post.

Running the project

You can just start the server-side Groovy script (after configuring the file matching loop at the end of the script corresponding to your system). Afterwards, just start the Vaadin project with “Run on Server”.
Now, you have to change a monitored file (eg. add a line and save the file). If you have chosen “Aktualisierung starten” (ie. start polling for new JMX events) the changed line should appear in the table. You can choose the line (details view is not implemented yet) to display more information. The table scrolls accordingly (the last item is always displayed at the bottom of the table).
The refresh mechanism necessary for polling the JMX state is copied from here.
Note: for real usage, it would be much better to use JMX notification for this use case.

Posted in Groovy, Vaadin | Leave a Comment »

Groovy, JMX and MBeans

Posted by ice09 on August 31, 2009

It’s really easy to create a MBean, export it with the platform MBean server and access the bean with Groovy.
Here’s how (it’s more or less an extended rewrite of this post).

The main trick is to implement ApplicationContextAware, which let Spring call the setApplicationContext method with the prepared application context (not tried, could be even shorter: is autowiring with the type “ApplicationContext” possible as well?)

Java part

The ManagementFactory lets you register your MBean in the platform MBean server (used to serve the application context).
Important: The easiest way to access the MBean remotely is by providing as System parameters (VM arguments in Eclipse) – obviously, this is not very secure.


import java.util.logging.Level;
import java.util.logging.Logger;


import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class AppCtxGlobalExporter implements AppCtxGlobalExporterMBean, ApplicationContextAware {

	private ApplicationContext appCtx;
    public AppCtxGlobalExporter() {}

	public void setApplicationContext(ApplicationContext appCtx) throws BeansException {
		this.appCtx = appCtx;

	private void initMBeanServer() {
		try {
				registerMBean(this, new ObjectName("jmxsample:type=AppCtxGlobalMBeanExporter"));
		} catch (InstanceAlreadyExistsException e) {
            Logger.getLogger(AppCtxGlobalExporter.class.getName()).log(Level.SEVERE, null, e);
		} catch (MBeanRegistrationException e) {
            Logger.getLogger(AppCtxGlobalExporter.class.getName()).log(Level.SEVERE, null, e);
		} catch (NotCompliantMBeanException e) {
            Logger.getLogger(AppCtxGlobalExporter.class.getName()).log(Level.SEVERE, null, e);
		} catch (MalformedObjectNameException e) {
            Logger.getLogger(AppCtxGlobalExporter.class.getName()).log(Level.SEVERE, null, e);
		} catch (NullPointerException e) {
            Logger.getLogger(AppCtxGlobalExporter.class.getName()).log(Level.SEVERE, null, e);

    public String[] getBeanNames() {
    	return appCtx.getBeanDefinitionNames();


with the interface:


public interface AppCtxGlobalExporterMBean {
    String[] getBeanNames();


Here the main class:


import org.springframework.context.ApplicationContext;

public class AppCtxRegistry {
	public static void main(String[] args) {
		ApplicationContext app = new ClassPathXmlApplicationContext("beans.xml");
		SampleBean sample = (SampleBean) app.getBean("sample");
		while(true) {
			try {
			} catch (InterruptedException e) {


the sample bean is left out, it’s not important and could even be empty.
The important part is the applicationContext.xml, the bean which implements ApplicationContextAware must just be instantiated, the Method setApplicationContext is called with the appropriate appcontext on startup.

<?xml version="1.0" encoding="UTF-8"?>

  <bean class=""/>

  <bean id="sample" class=""/>

Now comes the fun (Groovy!) part:

import as JmxFactory
import as JmxUrl

class JmxClient {

    def jmx() {
        def serverUrl = 'service:jmx:rmi:///jndi/rmi://localhost:6666/jmxrmi'
        def server = JmxFactory.connect(new JmxUrl(serverUrl)).MBeanServerConnection
        def mbean = new GroovyMBean(server, "jmxsample:type=AppCtxGlobalMBeanExporter")
       	mbean.BeanNames.each {
        	println it

    public static void main(String[] args) {
        new JmxClient().jmx()


Posted in Groovy | Leave a Comment »

Spring and Groovy, again…

Posted by ice09 on August 9, 2009

No real news here, just another example for Spring and Groovy in a simple web project.

Github for server version is here.
Github for client version is here.

What does it do?

We needed a simple Request/Response Mock for SOAP Web Services. Since the real sending component uses EJB and Weblogic t3-protocol specific stuff, I wanted to decorate this component.
The simplest way seemed to create an own endpoint, which accepts the SOAP web service requests, searches for templates based on the payload-root-element and evaluates the determined template (which itself is a Groovy template).

How does it work?

Quite straightforward. If a directory with the file template.groovy and the name of the root element of the payload exists, the template is loaded and evaluated with the input data and finally returned by the DispatcherServlet.
Spring MVC is used, however it was not necessary for this little sample.
The most interesting part is the injection (with @Autowired) of the Groovy script (which resides in src/main/resources/, which is not really correct).

<!-- this is really important to start the annotation processing in Spring -->

<!-- the controller is instantiated, via @Autowired the Groovy Script is set -->
<bean id="RequestMockController" class="com.mock.sample.RequestMockController"/>

<!-- local repository (must be changed most likely) -->
<bean id="localRepo" class="java.lang.String">
   <constructor-arg value="c:/temp/repo/"/>

<!-- instantiate Groovy as a Spring bean -->
<lang:groovy id="xml" script-source="classpath:XmlToolImpl.groovy"/>

IMPORTANT: to be able to use Groovy-Spring beans, the Groovy object should implement a Java interface (which is then used in the Java code).

How do I test it?

Use the client code with the parameters supplied in the README.
The request could look like this:

<soapenv:Envelope xmlns:soapenv="" xmlns:wss="">

For this request to succeed, the file REPO/getString/template.groovy must exist (see resources).


In the sample, there is one special behaviour, which requires two passes – if the template returns something like “>redirect”, the request is redirected to the new file (this works one time only and is just included to easy the “dispatching or controller pattern”)

Posted in Groovy, Maven | 1 Comment »

Groovy Spring

Posted by ice09 on June 6, 2008

Though the not really persuading (Open Source) IDE support, Groovy is my favorite script language for the Java VM. To have at least simplest support for Groovy, the Eclipse Plugin can be used. However, do not expect too much of it – it seems to be quite unstable (there are some suspicious OOME under Linux), but the Syntax Highlighting is ok. It is said that IntelliJ has the best Groovy IDE support by far, but I didn’t test it.
There exists nice Spring support for Groovy – you can transparently use Java- and Groovybeans. Combining this with Maven makes it really easy to make Spring even groovier.



This post will focus on the Groovy usage within Spring, therefore the use case is quite simple.

  • A central Java bean has a list of several beans (ie. resembles a workflow)
  • The injected beans must implement an interface ITestStep which is very generic (Object execute(Object))
  • Implementing an interface seems the only way to inject Groovybeans transparently


The Maven POM:

<?xml version="1.0" encoding="UTF-8"?>

The Spring config:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="" xmlns:xsi=""

	<lang:groovy id="groovyTestStep"

	<bean id="testFlow" class="de.groovysample.JavaGroovyTest">
<property name="testSteps">
				<ref bean="groovyTestStep" />


The Beans (ie. workflowsteps) interface:

package de.groovysample;

public interface ITestStep {

	Object execute(Object arg);


The Groovybean (NOTE: this gose to src/main/resources as SimpleGroovyClass.groovy):

import de.groovysample.ITestStep

class SimpleGroovyClass implements ITestStep {

	Object execute(Object arg) {
		println "groovy called with arg: $arg"


The Workflow Javaclass the Groovybean is injected to:

package de.groovysample;

import java.util.ArrayList;
import java.util.List;

public class JavaGroovyTest {

	private List<ITestStep> testSteps = new ArrayList<ITestStep>();

	public void setTestSteps(List<ITestStep> testSteps) {
		this.testSteps = testSteps;

	public Object execute(Object arg) {
		for (ITestStep testStep : testSteps) {
		return null;


and the Main class:

package de.groovysample;

import org.springframework.context.ApplicationContext;

public class Main {

	public static void main(String[] args) {
		ApplicationContext app = new ClassPathXmlApplicationContext("beans.xml");
		JavaGroovyTest test = (JavaGroovyTest) app.getBean("testFlow");
		System.out.println(test.execute("called from Java"));


Resulting in the overall project setup

That’s all, this way you can easily combine Java and Groovy beans (which must implement an interface).

Posted in Groovy, Maven | Tagged: , | 1 Comment »