GHads mind

developers thoughts & finds

Posts Tagged ‘groovy

Disable Gaelyk reloading routes on every Request in DEV mode

leave a comment »

I’m working on a little client/server app with C# WPF 4.5 as frontend and Gaelyk on Google App Engine (GAE) as server backend. While testing the load of my app on development server, I discovered a high single core load on my server and a very bad response time once the requests per second was higher than around 10.

After some testing hours I found that Gaelyk reloades the routes.config file on every request to check for changes as I didn’t have timestamps on my filesystem or I did not start with admin rights. Anyway instead of checking if the file has changed, the RoutesFilter always creates a new GroovyShell and runs the routes.config as script, thus compiling it which in turn resulted in a high single core load and a bad request time. As you can imagine constant recompiling stresses the server and I observed a delay of 150ms per request just for reevaluating the routes.config file on every request. Wow, that sums up quickly.

Well, in production mode this will not be done and on deveploment mode this is normaly not a problem but in my case I have many users that query the server once a second and the check for file modification is not working.

But as I do not change the routes often (and if I will just have to restart Gaelyk) I looked around how to disable this behaviour and discovered you can configure your own route filter in web.xml

    <!-- Use custom routes filter to disable reloading of routes.config for every request for development server -->

Then just extend the RouteFilter class:

package utils

import groovyx.gaelyk.routes.RoutesFilter;

class NoReloadRoutesFilter extends RoutesFilter 
	private boolean init = false
	synchronized void loadRoutes() {
		if (!init) 
			 init = true

That’s it. It may be an uncommen problem but it was a problem for me 🙂


Written by ghads

November 15, 2013 at 6:50 pm

Posted in Uncategorized

Tagged with , , , ,

HTML5 <time> microformat with Grails (UTC dates…)

with 2 comments

As I mentioned last post I’m doing a little pet project with Grails, HTML5 and MongoDB. Now I wanted to include the rendering of dates in StackOverflow style, something like: 5 minutes ago, about an hour ago and such. As HTML5 defines a <time> microformat I naturally wanted to use this one today and also found a nice jQuery plugin to convert times into the format I like: timeago. This one also includes support for the <time> tag by default.

But there’s a catch (as always…). The <time> tag and the plugin depend on ISO8601 UTC dates, which MongoDB stores nicely. But by getting data from MongoDB, you have your java.util.Date class and trouble starts, as there is no default way of formatting and recalculating dates to UTC with one call. Else I could have used the Grails included formatDate tag.

So I first searched for an easy way to format a Date instance to ISO8601 UTC format. Luckily I found the following post that shows how to set UTC for a formatter and the right format string for ISO8601. As this is a two line call and I didn’t want to make a Utils-Class for representation only to call it from the controller and having a String for rendering instead of a Date. And I didn’t want to include the formatter code on every page, I came up with a Grails Filter solution.

By including this class in grails-app/conf:

class MyFilters {
	def filters = {
		addUtils(controller:'*', action:'*') {
			after = {
				// add formatter for UTC dates in ISO8601 format
				SimpleDateFormat ISO8601UTC = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
				params["_UTC"] = ISO8601UTC

I have a new formatter instance inside the params ready to use for formating dates to UTC in the correct way for the tag:

<time class="timeago" datetime="${params._UTC.format(created)}">${created}</time>

I used an underscore to seperate the utils from regular paramaters used to render the site. For now I don’t care about a new instance for every call, but if you care, just make the formatter static and reduce the scope of the addUtils Filter to only the pages that need it.


Written by ghads

January 26, 2011 at 3:10 pm

Grails + HTML5 = Works

with 6 comments

Today while building a project to test MongoDB integration with Grails, I was curious whether Grails can emit HTML5. So I just tried to apply to great HTML5 Boilerplate ( template and it worked out wonderful. I just changed the default main.gsp, main.css and application.js and added some more files…

Of course some things need adaption:

– Using jQuery 1.4.4 instead of 1.4.2
– All hardcoded path replaced with ${resource(dir:’images’,file:’favicon.ico’)} for example
– Javascript libs can be embedded with <g:javascript library=”…” /> instead of a hard coded path, when you place your lib file into the web-app/js folder
– For JQuery Fallback loading the src can be exchanged with ${resource(dir:’js’,file:’jQuery-1.4.4.js’)} to avoid hard path coding
– Because of the templating/layout nature of Grails view, JavaScript loading of jQuery and the additional plugins.js and application.js (also via <g:javascript …>) cannot be pushed to the very end of the page, but must be loaded before any part of a page is been decoreted by the template (except for belatedpng)
– I reused the default spinner div, but cleared the default grails code in application.js and introduced two simple functions for showing and hiding the spinner
– For flexible layout I used the following construct plus two additional GSPs header.gsp and footer.gsp

<div id="container">
  <g:applyLayout name="header" >
   <content tag="header">
    <g:pageProperty name="page.header" />
 <div id="main">
  <g:layoutBody />
  <g:applyLayout name="footer">
   <content tag="footer">
    <g:pageProperty name="page.footer" />

This enables the header.gsp and footer.gsp to include portions of the GSP page to show while being modular. The header/footer.gsp looks like:

<%@ page contentType="text/html;charset=UTF-8" %>
<b>Footer begin...</b>
<g:pageProperty name="page.footer" />
<b>Footer end...</b>

While a GSP page may looks like:

<%@ page contentType="text/html;charset=UTF-8" %>
  <title>my title</title>
  <meta name="layout" content="main">
  <content tag="header">
   … draw the header here…
  <h1>Hello ${name}!</h1>
  <content tag="footer">
   … draw the footer here…

This allows for dynamic customizing of header/footer portions per page if desired, e.g. to render a status per page, which has its position and styling defined via the layout.

The rendered result of this looks like:

Header begin… … draw the header here… Header end…
Hello World!
Footer begin… … draw the footer here… Footer end…

The HTML5 Validator only complaints about the chrome frame but validates my rendered test page sourcecode without any moaning.

For CSS3, the integration was a nobrainer, I just added everything to main.css, removed all grails styles and used a @import url(styles.css); for a clear seperation of predefined and own styles at styles.css. The W3C Validator for CSS3 doen’t really like the main.css file, but as it comes directly from the boilerplate template I don’t really care. I can now start writing my pet project with HTML5 and CSS3 and can be sure to have maximum compatibility with yesterdays, todays and tomorrows browser and will update my code when a new version of the fantastic boilerplate template comes out.

Oh, for your own integration before going productive don’t forget to add expires to external resources, minify .css and .js files to one and enably GZIP transfer at your server. That should be all for a snappy cool HTML5/CSS3 site done with grails.

Have fun and greetings,

Written by ghads

January 21, 2011 at 9:43 am

Filter Collections via “Double Brace Initialization”

with 3 comments

Hi again,

here’s another little code I did recently while trying to answer a Stackoverflow-Question.

The author of the question (here) asks for a smarter way to filter collections/lists in Java like it is done in Python/Scala/Groovy, as one-liner.

I immediatly thought of JDK7 closures, but as it is widly known Oracle shifted the featurelists for JDK7 and 8 not long ago and it seems, closures will come not earlier than 2012. But even with closures the accepted answers shows that in its current state event closures would be an akward and over-complicated solution compared to groovy for example (quoted from the seanizers answer):

JDK7 sample code:

findItemsLargerThan(List l, int what){
  return filter(boolean(Integer x) { x > what }, l);
findItemsLargerThan(Arrays.asList(1,2,5,6,9), 5)

Groovy sample code:

  Arrays.asList(1,2,5,6,9).findAll{it > 5}

You see…

So I started to experiment with pure Java to find a solution that is easy to read and easy to program while not beein too verbose. After some hours I came up with the following code

List<Integer> filtered = new Filter<Integer>(Arrays.asList(1,2,5,6,9)) {
    findAll(it > 5);

I thinks it’s quite elegant, because it’s readable pure Java code and fits one line sans code-formating. How does it work? Obvisually one needs a class Filter. The abstract Filter class implements the List interface (delegates all methods to an internal List variable) and takes the collection to filter (assigned to the internal List variable) as argument for its constructor and throws a RuntimeException when the collection is null or empty. Then we have the double brace initialization pattern which allows to dynamicly and anonymously subclass the filter class while providing an instance initalizer which will be executed after the constructor of the Filter class is done. Inside the instance initializer all we do now is a method call to findAll(), which takesa boolean argument. But where does “it” come from and how will “it” be mapped to each element of the collection?

“it” is a variable inside the Filter class. As the instance initializer is executed after the constructor, we can set “it” to the first element of the collection to filter. The instance initializer is then executed and the boolean condition it > 5 is evaluated. So at the time findAll() is executed, the condition whether to include the first element in the filtered result is already done. So the magic to repeat the evaluation for each element must be inside the findAll() method:

protected void findAll(boolean b) {
  // exit condition for future calls
  if (values.size() > 1) {
    // only repeat for each entry, if values has multiple entries
    Constructor constructor = this.getClass()
    Iterator iterator = values.iterator();
    boolean first = true;
    while (iterator.hasNext()) {
      T element =;
      // don't evalute again for the first entry
      if (first) {
        if (!b) {
        first = false;
      } else {
        // else repeat Filter invocation for all elements
        Filter filtered = null;
        try {
          // invoked constructor for the element
          filtered = (Filter) constructor.newInstance(
            new Object[] { null, Arrays.asList(element) });
        } catch (Exception e) {
        // if values is empty, the condition didn't match and the
        // element can be removed
        if (filtered != null && filtered.isEmpty()) {
  } else {
    // one element can be checked directly
    if (!b) {

(a little bit more polished than my answer at Stackoverflow)

First thing is to define an exit condition as the findAll() method will be executed multiple times eventually. The condition says, if there is more than one element in the list, we must iterate, else we can look at the evaluted boolean condition directly. In the last case “false” will just clear the internal List, whereas “true” does not change it.

When iteration is needed we get the constructor of this class once (there is only one) and take the next element. If it is the first one, we already know the evaluated condition and thus remove or keep the first item. For all other items we will create a new instance of the anonymous class that extended Filter via instance initalizer in the first place. By creating a new instance and providing a list as argument with a single element, the instance initializer is called again after the constructer set “it”. So the evaluation of the boolean condition starts again, but for the next element this time. After instance creation it’s a simple check whether the boolean condition had matched or not. If the internal List is empty, the condition was “false” and the element can be removed from the Filter instance that iterates the elements and creates new instances.

So the only catch is that there are n-1 additional instances created for a collection n to filter, when n is the number of elements. But as Instance creation is quite cheap these days and every additional instance does not need to iterate again, this runs quite fast. I’m sure there is still potential to optimize the Filter class as new ArrayLists are created here and there but im very satisfied with the result so far.

The filter class can be used for each kind of object, for example checking if people are 18 would be “findAll(it.getAge() >= 18);”, if there is a People Class with a getAge() method.

So long this time, hope you enjoyed this blogpost (feedback is appriciated).

Written by ghads

September 22, 2010 at 3:49 pm

Short update

with one comment

Hi @all and a happy new year 🙂

Yeah, I know, it’s little bit late already, but I simply had no time to blog earlier. Too much to do with testing out Win7 and hacking java and vbscript…

Anyway, here are some new cool findings to check out: – Grid-based computing of fractal mantras as screensaver

Consider GlassFish ESB v2 for SOA Tooling ( for a good tutorial about GlassFish, NetBeans, ESB and BPEL – Where you can learn about many aspects of Java developing technologies (with passion 🙂 – Get quick and easy groovelets to work at your favourite (application) server and why those groovy servlets rock – A generic proxy approch to the builder pattern – A portable ISO mounting/creating solution for Windows

So long and many greetz,

Written by ghads

February 2, 2009 at 12:38 pm

Bringing together .NET and Java

leave a comment »

I just researched some bridging technologies for calling Win DLL/Com objects from Java. I stumpled upon those two very usefull sites:

The first one shows how to write a COM DLL with VisualBasic, using other Com-Objects and accessing this new DLL from within Groovy and/or Java. This is something for making my Optimus Mini Three really usable from groovy/java I hope. The second one provides native functions via APIs to Java for creating IE, floating windows and retrieving system informations. Bringing this all together into an usefull application I will try 🙂

Greetz, GHad

Written by ghads

November 18, 2008 at 1:50 pm

Play! Java Server/Services development

leave a comment »

Just a quick link again:

Quote from the page:

Discover a clean alternative to bloated enterprise Java stacks. Play! focuses on developers productivity and targets RESTfull Architectures

I just read the examples and it looks really cool for use at home, building some simple home services, for example a media album for all family members and such things. I’ll take a look when I’m finally done with my hardware…

Greetz, GHad

Written by ghads

November 18, 2008 at 12:10 pm