Showing posts with label groovy. Show all posts
Showing posts with label groovy. Show all posts

Friday, June 29, 2012

Groovy 2.0 is there - but useless...

As much as I waited for the 2.0 release of my favorite programming language I'm grumpy about the quality of the release - or rather the lack of it. Here's why:

One of the most important (for me) things that have been added to 1.8 (I guess it was), the annotations to decoratively add logging facilities to classes is broken.

https://jira.codehaus.org/browse/GROOVY-5557
@groovy.util.logging.Slf4j
class Test {
    Test() { log.debug "Here" }
}
But the best thing is the error message:
Caught: BUG!
Until that's fixed I recommend sticking to the stable version.

Not a nice day,... unfortunately...

Wednesday, May 16, 2012

Making Groovy scripts maintainable

Writing Groovy code is cool. Fixing them some time later can be hard as they tend to grow out off control pretty soon. Finding an install.gsh that has 100+ lines is not hard. And since Groovy is a very expressive language those 100 lines are not making the compiler happy - it's actually stuff to be done.

I have a bad feeling about this

In Java we're pretty much used to either creation of big, ugly, monolithic classes or going the completely opposite direction with Spring or some other dependency injection framework. In scripts we tend to rather go the first way which makes them unmaintainable and hard to understand. Why? Because historically shell scripts were created this way and we tend to think in this way. It's a script, isn't it?

These are not the droids you're looking for...

In fact Groovy scripts are not scripts at all. They are classes, that will have a main method. The only difference is that they are automatically compiled when needed. This means we can use all the good Java stuff when writing Groovy scripts: classes, external libraries through @Grab annotation and so on.

Here's an example:

Configuration.groovy:
class Configuration {
    String path
}
install.gsh:
#!/usr/bin/groovy

println new Configuration(path: "/tmp")

Since all the classes are in the default package (inaccessible from pure Java!) you don't need to import them manually. Should it make sense to split them into folders you can always do that:

org/example/Configuration.groovy:
package org.example

class Configuration {
    String path
}
install.gsh:
#!/usr/bin/groovy

import org.example.Configuration

println new Configuration(path: "/tmp")

Further more you can write tests for your classes, make sure they always work even if some mad cow enters the arena and goes Hulk on your code :)

May all your scripts be maintainable forever and for always!

Saturday, March 31, 2012

Spring, MVC and Groovy

If you'd ever find yourself choosing the whole Grails stack only because it is sooo much easier to setup a project by comparison to pure Spring MVC I strongly recommend you try out the new Spring MVC on Groovy Maven archetype. That sucker punches in Spring in an easily selectable version, Groovy (1.8.6) and the groovy-eclipse compiler (also 1.8.6), JUnit and Spock, JavaMelody for monitoring - basically all you need to create a web application using Groovy, some IoC container, an MVC framework and test all that in a reasonable fashion.

http://www.testdriven.org/spring-groovy-web-archetype

Give it a shoot. If there's something you'd like to add to it then by all means - drop a note on GitHub.

Have a nice day!

Sunday, September 18, 2011

Java 6 has a web server inside!

The what

I'm into miniaturization - anyone who knows me also knows as much. Probably because I'm not very tall for today's standards but mostly due to the sole nature of small things: they are easy to figure out. For example getting to understand every bit and piece of the whole car (whatever brand) is impossible. In many cases no one would even allow you to go that far. But having a deep understanding how manual shift gear box works shouldn't be a problem for moderately intelligent person... The exact same principle adheres to software development as far as I am concerned. I like small parts I can grasp in short amount of time and have it used right after the learning process knowing what the hell I'm doing. You might think about it in terms of components of a desktop application, a JavaScript library for dynamic web pages or (as I've found out today) in terms of a small set of classes that do exactly what they are supposed to do and you can have them do their thing in a matter of minutes. I'm obviously (as the title suggests) talking here about the embedded web server found in the com.sun.net.httpserver package.

The how

Besides being fixated on miniaturization I'm also a Groovy freak as I thing this is the best language for JVM ever created and there's nobody to convince me otherwise :D For that very reason the following example showing a miniature web application with embedded web server is a Groovy script:
import com.sun.net.httpserver.*

class ExampleHandler implements HttpHandler {
	void handle(HttpExchange exchange) throws IOException {
		def response = "Hello, world!"

		exchange.sendResponseHeaders(200, response.length());
		def outout = exchange.responseBody
		outout.write(response.bytes);
		outout.close();
	}
}

public class ExampleAuthenticator extends BasicAuthenticator {
	static users = [ "john": "john123" ]
 
	public ExampleAuthenticator(String realm) {
		super(realm);
	}

	@Override
	public boolean checkCredentials(String username, String password) {
		return users[username] == password;
	}
}

def server = HttpServer.create(new InetSocketAddress(8000), 0);
def context = server.createContext("/example", new ExampleHandler());
context.authenticator = new ExampleAuthenticator("Example application")
server.executor = null
server.start();
Let's start from the beginning...

The ExampleHandler class

This particular class is responsible for generating all the output sent later on to the server. As you can see it's a very minimalistic thing here, even to the point where the body needs to know how big it actually is. The line Exchange.sendResponseHeaders(...) shows that. The rest is pretty self explanatory so I'm not going to drill into it.

The ExampleAuthenticator class

This class provides basic authentication for our small application. It's so damn easy anyone will understand it right away but for the sake of clarity here's the bottom line:
  • Every credential is stored in the static users=[:] map

The meat

Now we have finally come to the good part! The actual use of HttpServer. Here you see how the server is created using a factory method (HttpServer.create) that takes an InetSocketAddress and some other argument I didn't drill down to just yet and gives you back an HttpServer instance ready to work. That instance does pretty much nothing so far other than a response 404 for everything you ask. To change that we create a new application context (very similar to the one found in a Servlet container) and register it under a specific path on that server. In the next line we tell the context that it is guarded by basic authentication - that's my favorite :) - and we're almost all set. The last thing is to (for whatever reason) assign an empty executor that in turn is supposed to have a side effect in the sense that a default executor will be assigned instead. That's weird...

The outcome

In 32 lines we've created a dynamic web application with authentication - ready to conquer the world! That's maybe a lot more than Sinatra or Spark but still - it's something worth knowing about. If you'd like you can utilize it directly from Java and it is still not a lot more code than what's seen here!

Have fun!

Thursday, May 26, 2011

String + String = Problems

This is just a quick note to everyone not knowing it.

If for whatever reason you do have in your code something that concatenates strings using the + (plus) operator and it's going on in any form of loop or other that means executing this part regularly you might want to rethink what you've become over the years.

Man I never thought I'll see this thing again but I did! One of the developers was (again) producing a CVS line using a + b + c + d + shit load of other stuff. I mean come on! There have been books written about it already! :)

So if you're a Java developer choose one of either String.format, StringBuilder or StringBuffer classes to do the concatenation for you. If you're a .NET use either String.Format or StringBuilder to do it efficiently.

If you're a lucky Groovy developer your string concatenation will not be efficient anyway so you're free to use string interpolation - you can't get any worse than that :) At least it's damn good readable!

Sure thing is that depending on which platform you use concatenating might be more efficient if you use (for example in C#) the String.Concat method. But overall if you're concatenating a large number of strings (say in a loop or so) use the builder things at your disposal - they're a safe bet.

Sunday, April 10, 2011

Quicksort - the groovy way

I must confess: I didn't write quicksort by myself ever. I always felt it's one of those things that I don't really have to do. Well, Dierk Koenig showed that it might be useful to write your own implementation of quicksort. Not for regular use but for training purposes.

You all know the Collections.sort method, right? We all know it's damn fast, well tested and all that stuff. Let's see what does it take in Groovy to implement quicksort ourselves:
def qs(list) {
if (list.size() < 2) return list
def pivot = list[0]
def items = list.groupBy { it <=> pivot }.withDefault { [] }
qs(items[-1]) + items[0] + qs(items[1])
}

WTF? 4 lines plus function definition? And it can easily be shrunk to 3 lines by inlining the pivot variable:
def qs(list) {
if (list.size() < 2) return list
def items = list.groupBy { it <=> list[0] }.withDefault { [] }
qs(items[-1]) + items[0] + qs(items[1])
}


One of my colleges told me that before he saw the implementation of quicksort in Groovy he didn't quite get the idea, what it does and all. Same here :) I never tried to dig into the details, I just accepted that it works. But with this implementation I just see what's going on! There's nothing to understand, just 3 lines to read :D
By comparison an implementation of bubble sort is around 10 lines long and is about 100 times slower :D
If you're wondering how does this implementation perform by comparison to the Collections.sort() method here are the results (sort a 100 elements list 1000 times):

def qs(list)Collections.sort()
1938ms19ms

The actual timing varies but the ratio more/less 100:1 sticks.

It's interesting to note that there's a 10 times difference in timing when invoking list.sort() and Collections.sort(list) in favor for the latter one. That's probably due to the dynamic stuff going on in between.

Monday, January 10, 2011

camelCase for human beings

Reading lots of characters glued together is a very good thing for the compiler. Human beings tend to prefer spaces rather than a set of lowercase characters separated with uppercase characters to distinguish words. It's just how we were taught since we were very young...

In case of unit test in Groovy we can actually name our tests with spaces! Here's an example:
import org.junit.Test

class ExampleTests {
@Test void 'This test verifies nothing but is a good example'() {
assert 1 == 1
}
}
When later on you're reading the name of the test that failed it's a whole lot easier than to read the same in camelCase.

Converting camelCase to human text

I thought I'll give a string an additional method so that whenever I have a camelCase string I can convert it easily to something that's easier to read:
String.metaClass.humanify = {
def r = ""

delegate.eachWithIndex { c, i ->
if (i == 0) r += c.toUpperCase()
else if (c in 'A'..'Z') r += ' ' + c.toLowerCase()
else r += c
}

return r
}

From now on it's easy to read camelCase when it's humanized :D

Friday, January 7, 2011

Groovy/Grails DSL testing

Today I faced a usual task of testing a controller action that utilizes the withCriteria call to fetch some data from the database. Usually what I do in situation like this is I write an integration test, have the database mocked using in-memory instance of HSQLDb and all is nice and dandy.

This time I didn't have the luxury to have the database in place. I will not bore you why that is the case - it simply is. What I didn't want to do was to just let the thing be untested so I've decided to create a ultra-minimalistic framework for testing such DSLs in Groovy.

First of all, it all bases on the assumption that you don't care about the actual results the DSL brings. What you do care about is the fact that certain parts of the DSL have been called in a particular order and with proper arguments. To put this in context: you don't care that the withCriteria DSL will be in reality transformed into SQL but you do care that what you wrote will be as you expect it to be.

So the following class has emerged:
package groovy.test

class DSLTester {
static mock(clazz, method, result) {
def tester = new DSLTester()
clazz.metaClass.static."${method}" = { Closure dsl ->
dsl.delegate = tester
dsl.resolveStrategy = Closure.DELEGATE_FIRST
dsl()
return result
}
return tester
}

def result = []

def methodMissing(String name, args) {
result << [ name: name, args: args.toList() ]
}
}

What it does is it executes the closure passed on as the DSL to whatever static method we decide to test and catches all the missing calls as if they were proper DSL calls. You might find the args.toList() part to be a little bit strange. This is to allow use simple comparison in tests - read on to find how.

To give you an example first let's define the Person class:
class Person {
String firstName
String lastName
}

With that in hand let's create a home controller that will just print all the people ordered by firstName:
class HomeController {
def index = {
def people = Person.withCriteria {
order "lastName"
}

[ people: people ]
}
}

To test the withCriteria closure let's utilize the DSLTester class:
import groovy.test.DSLTester
import grails.test.ControllerUnitTestCase
import org.junit.Test

class HomeControllerTests extends ControllerUnitTestCase {
void testExecuteDSL() {
def mock = DSLTester.mock(Person, 'withCriteria', [])
def actual = controller.index()
assert mock.result == [ [ name: 'order', args: [ 'lastName' ] ] ]
}
}

As you can see the only assertion that I make here is that the order will be properly set to 'lastName' which is what we wanted in the first place.

There's tons of ways you could improve this. You could for example come up with a nice way to verify expected methods have been called with the proper arguments instead of declaring a huge list with hashes containing everything. Sky is the limit :)

The main motivation behind this sort of test is to provide means to test only your code and to test it in complete isolation. It might be perfectly understandable that since the code that uses withCriteria has such a strong dependency on the database that testing it in isolation makes no sense. I however like to keep things isolated :)

Thursday, December 30, 2010

Compiling Groovy 1.7.6 with IKVM

If you'd like to see how to compile Groovy 1.7.6 under IKVM.NET take a look at this archive. It contains everything you need to be able to turn the groovy-all-1.7.6.jar (and its dependencies) into both an executable (that runs the console) and a library that can then be embedded into a .NET application.

Beware: This is a 27MB download so it's not a small thing.

groovy-1.7.6-net.zip

A note about the compilation process

Please note that there are some issues during 2 phases of the compilation:
1. The first one occurs when compiling commons-logging-1.1.1.jar as it also requires LogKit which I was to lazy to collect and compile
2. The second one occurs while compiling Groovy itself as there are still some dependencies missing. They aren't however important enough to block the usage of compiled library and executable.

Let me know if you'll find this interesting and/or useful :)

Groovy scripting from C#

Well, after the last finding that the Groovy Console executes on IKVM.NET what must have followed was embedding of Groovy scripting capabilities in a C# application.



Here you can snatch the project along with everything needed to compile and run it (besides the .NET framework of course). Beware, it's a 19MB download (50MB+ after unzipping). I've created it using Visual C# Express 2010.

Have fun!

Groovy 1.7.6 under .NET

Well, I finally did it! It did require a huge leap of fate but it finally turned out possible: Groovy running on .NET using IKVM 0.44.0.5!



And not only running but also interoperating with .NET classes!



It's running extremely slow but stable enough to play around a bit with it.

Next step: using Groovy classes from .NET!

Saturday, December 26, 2009

Grails - a decomposed application project

Hi there,

I've been looking around for ways to nicely decompose a large application (an Enterprise Application so to speak) using Grails. It turns out this platform has such a capability already build-in! Interested? Read on...

The basic building blocks of Grails are plugins. There's a plugin for everything: the ORM layer, IoC container, security, twitter access - you name it! So how is this going to help us decompose a large enterprise-grade application? Well, we're going to compose it from... plugins!

Here's a step-by-step instruction on how to create the main application along with one additional pluging. Other plugins can be added exactly the same way as the single one mentioned here.
  1. Create a grails application (we're going to name it "myapp" here) using standard Grails command grails create-app myapp
  2. Do not change the folder just yet to myapp - instead issue the following Grails command: grails create-plugin myapp-plugin
  3. cd to myapp
  4. Add the line plugins.myapp-plugin=0.1 to application.properties (that's in the main application, not in the plugin!)
  5. cd to grails-app/conf
  6. Add the following line to BuildConfig.groovy: grails.plugin.location.'myapp-plugin' = '../myapp-plugin'
  7. cd out of the application and into the myapp-plugin folder
  8. Issue grails package-plugin command to create plugin.xml
  9. cd back to your application and run it as usual using grails run-app
That's it! Whenever you make changes to your plugin they will be automatically picked up just as if they were a part of your main application which is the greatest feature ever!

Have fun!

Friday, December 25, 2009

Groovy - dumping object's properties

Marry Christmas! This is the Christmas Eve and what follows is a Christmas Present for you!

Have you ever used BeanUtils from Apache to query the properties of an object? Was that easy? Well I did that and what I ended up was completely unreadable and chaotic. But there's good news! Here's how it's doable in Groovy:
object.properties
That's it! Groovy exposes the map of properties as a predefined property called "properties". Ain't that cool? Let's see how we would go about printing all the values of object's properties along with their names:
println object.properties.collect{it}.join('\n')
Here's what it's doing: it gets the map of properties, turns it into a list (collect{it}) and joins them with a new line character.

Did you notice that "class" is also one of the properties? That's nasty! How about filtering it out?
println object.properties.findAll{it.key != 'class'}.join('\n')
Now that's much better, but good only for one or two names to filter. How about a more general solution?
def filtered = ['class', 'active']
println object.properties
.collect{it}
.findAll{!filtered.contains(it.key)}
.join('\n')

That's much much better but still, if the object has like 15 properties looking them up is a pain if they are not sorted. Let's do something about it:
def filtered = ['class', 'active']

println object.properties
.sort{it.key}
.collect{it}
.findAll{!filtered.contains(it.key)}
.join('\n')

And there it is! A list of key=value (value taken from object's toString()) separated by a new-line character for easier browsing :)

I hope this will help you out with your Groovy adventures!

Have a nice holiday!

Friday, December 18, 2009

Grails - the search is over

Recently I've been crushed with the simplicity of Grails framework. For those of you who don't know what's this thing is all about please check the Grails web site - it's well worth your while!

Here are some highlights I've checked out during the evaluation process:
  • Grails combines the best open source technologies into one easy to use framework (Spring IoC, Hibernate, Spring MVC, Spring WebFlow)
  • Additional integrations are as easy as one-line plugin installation (Jabber integration, JMS integration, additional view capabilities, JavaMelody monitoring - just to name a few)
  • ActiveRecord pattern as well as dynamic finders rock!

Stay tuned for some working examples. I'll post them during the weekend.