The MetaSieve Blog

August 25, 2010

Using Cometd 2.x with Grails

Filed under: Uncategorized — Tags: , , , — Björn Wilmsmann @ 8:16 pm

I’ve been struggling quite a bit to get CometD (see this for more information on the Comet Pattern) working with Grails and the corresponding Grails CometD plugin, the documentation being sparse and the new version of the CometD API being somewhat confusing with lots of new interfaces and abstractions.

Anyway, I’ve got it working so I thought, I might share the experience (see code sections at the end of the article for copying source code):

Assuming that you would like a Grails service to communicate via CometD, this is how a basic implementation of a simple service that finds Account entities for search parameters would look like:

AccountService.groovy

AccountService.groovy

There are a few things to note here. The service implements the interface InitializingBean provided by Spring. This interface supplies an afterPropertiesSet() method that allows you to initialize additional properties after Spring has wrought its magic. This way you can initialize and handshake with the Bayeux server using the bayeux bean that’s injected by the CometD plugin.

The runAsync closure in findAccounts(def query, def params = [:]) is provided by the Grails Executor plugin, which allows you to run background threads in your application without losing the Hibernate session. This is exactly why runAsync is needed here. As findAccounts(def query, def params = [:]) will be called asynchronously we have to make sure everything that occurs inside this method is thread-safe.

Via the subscribe() method you can have a so-called SubscriberListener subscribe to a messaging channel:

MySubscriberListener.groovy

MySubscriberListener.groovy

Such a SubscriberListener has to extend the abstract class SessionChannel.SubscriberListener as provided by org.cometd.bayeux.client.SessionChannel. This class demands that its sub-classes provide an onMessage(SessionChannel channel, Message message) method, which will act as a callback method upon new messages on the channels the listener is subscribed to.

Apart from that, there’s some nice Groovy magic happening here that allows you to instantiate a MySubscriberListener which calls a service method without actually hard-coding that service method in the MySubscriberListener class. In this case, the listener will call the service’s findAccounts(def query, def params = [:]) method.

The client side of this little example would look something like this (assuming you’re using the jQuery version of the CometD client), with cometd-subscriptions.js being loaded first and init.js afterwards:

cometd-subscriptions.js

cometd-subscriptions.js

init.js

init.js

Once this is all set up, you can do something like this to nudge AccountService from your JavaScript client:

$.cometd.publish('/requests/search', { 'payload': { q: 'some query', params: { offset: 10 } } });

I hope this primer helps you to overcome initial problems with CometD and Grails. If you’ve got any questions or additional contributions, please feel free to leave a comment.

Source code for copy & paste:

AccountService.groovy:

package myapp

import grails.converters.JSON

import org.springframework.beans.factory.InitializingBean

class AccountService implements InitializingBean {

def bayeux
def bayeuxSession

static transactional = true

void afterPropertiesSet() {
bayeuxSession = bayeux.newLocalSession()
bayeuxSession.handshake()
bayeuxSession.getChannel('/requests/search').subscribe(new MySubscriberListener
(this, 'findAccountsToFollow', ['q', 'params']))
}

def findAccounts(def query, def params = [:]) {
runAsync {
def accounts = Account.findAllByName(query, params)

// publish to search results channel
bayeuxSession.getChannel('/results/search').publish(['payload':['accounts':accounts]] as JSON)
}
}
}

MySubscriberListener.groovy:

package myapp

import org.cometd.bayeux.Message
import org.cometd.bayeux.client.SessionChannel

class MySubscriberListener extends SessionChannel.SubscriberListener {
def callbackService
def callbackMethod
def callbackParams

public MySubscriberListener(def service, def methodName, def params = []) {
callbackService = service
callbackMethod = methodName
callbackParams = params
}

public void onMessage(SessionChannel channel, Message message) {
// callback
def callbackParamValues = []
callbackParams.each { param ->
callbackParamValues.add(message.data.payload."${param}")
}

callbackService."${callbackMethod}"(*callbackParamValues)
}
}

cometd-subscriptions.js:

var subscriptions = {};

function refreshCometSubscriptions(channels, callbackFunctions) {
for (var i in channels) {
if (typeof channels[i] == 'string') {
unsubscribeFromCometChannel(channels[i]);
subscribeToCometChannel(channels[i], callbackFunctions[channels[i]]);
}
}
}

function unsubscribeFromCometChannel(channel) {
if (subscriptions[channel]) {
$.cometd.unsubscribe(subscriptions[channel]);
}
subscriptions[channel] = null;
}

function subscribeToCometChannel(channel, callbackFunction) {
subscriptions[channel] = $.cometd.subscribe(channel, callbackFunction);
}

init.js:

// initialize cometd
var channels = ['/test', '/results', '/results/search'];

var testCallback = function() { };
var resultsCallback = function() { };
var searchResultsCallback = function(message) {
renderFollowerSearchResults(JSON.parse(message.data).payload.accounts, '#resultsContainer', 'resultList', '#box2');
};

var callbackFunctions = { '/test' : testCallback, '/results' : resultsCallback, '/results/search' : searchResultsCallback };

$.cometd.init('../../cometd');
$.cometd.addListener('/meta/connect', function(message) {
if ($.cometd.isDisconnected()){
return;
}
if (message.successful) {
$.cometd.publish('/test', { 'data': { 'message':'Connection with CometD server has been established.' } });
}
});
refreshCometSubscriptions(channels, callbackFunctions);

Advertisements

June 3, 2010

PlzFinder & GermanPostalCode Plugin veröffentlicht

Filed under: Deutsche Beiträge — Tags: , , , — Björn Wilmsmann @ 2:04 pm

Wir haben heute unter PlzFinder eine neue Web App online gestellt, mit der man deutsche Postleitzahlen finden und überprüfen kann.

Außerdem haben wir das GermanPostalCode Plugin für Grails veröffentlicht, das diesen Dienst nutzt, um auf einfache Weise deutsche Postleitzahlen in Grails Apps zu überprüfen.

April 2, 2010

Kameleoon: Morphing The Web (with Grails)

Filed under: Uncategorized — Tags: , , , , — Björn Wilmsmann @ 6:00 pm

The way we do web design more or less hasn’t changed for more than 10 years or so. Most new websites start from scratch design-wise, meaning that when you have a cool idea for a new website you hire a web designer for turning that idea into something that’s nice to look at.

Another option is using some blogging software or CMS like WordPress or Joomla alongside with predefined templates that are shipped with the software. While the latter option surely is satisfactory for many purposes (see this blog, for instance …), it doesn’t allow you a great deal of customization.

One final option is using one of those clunky homepage toolboxes which allow you to ‘design’ your own website with virtually no knowledge of HTML, CSS or graphic design. However, these most of the time impose rather narrow restrictions as to what can be done with them and what cannot. This goes as far as that most of the time you can tell right away which of those toolboxes has been used.

Enter Kameleoon. Kameleoon is a pretty new service that approaches web design rather differently.

It allows you to take any existing website (So, admittedly you’d have to do some initial web design before using Kameleoon, too.) and modify each and every CSS property in a nifty WYSIWYG editor. You can change colours, border styles, font types, upload background images and the changes will be applied right in place. You don’t even have to touch your server-side code anymore when applying design changes! Pretty cool, isn’t?

Technically, this is done by adding a JavaScript snippet to your website that loads the Kameleoon scripts, CSS files and renders any changes you’ve made so far. Kameleoon doesn’t care about the technology used on your website (well, apart from Flash, that is …). You can gain some more control about what can be changed by Kameleoon adding additional CSS classes to your HTML code though.

Kameleoon‘s user interface might admittedly be a bit overwhelming at first and needs some time to get used to. But, then again, so does Photoshop, doesn’t it?

The Kameleoon application runs on Grails 1.2.1. The rendering engine makes use of GIMP scripted via Python. One very cool thing about this is that the Python code is dynamically generated by Groovy.

Finally, the client side JavaScript code was written with Qooxdoo, a framework for creating rich Internet applications.

March 17, 2010

Continuous Testing with Grails

Filed under: Uncategorized — Tags: , , — Björn Wilmsmann @ 12:37 am

I’ve just released a new Grails plugin called AutoTest. AutoTest provides an automatic (or continuous) testing feature for Grails. After having installed AutoTest you will be able to run the following new Grails script:

grails auto-test

This will start a continuously running Grails test process. Once you modify and save a file within your Grails project unit and integration tests (and as a matter of fact any kind of tests added by plugins) will be run against the new version of the changed file.

This allows you to get continuous feedback on code changes without having to switch between editor and terminal.

For more information, please have a look at the plugin documentation

March 5, 2010

Does Grails have a problem?

Filed under: Uncategorized — Tags: , , , — Björn Wilmsmann @ 5:29 pm

Recently (or rather over the course of the last half year or so), there has been quite some discussion about how the Grails community responds to open source contributions, mainly with regard to Grails plugins.

The main issue Robert Fischer takes offence at is that the Grails community seems less appreciative of contributions, especially with regards to plugin development, than other open source communities like Rails.

According to Robert, Grails users are more demanding in terms of support for open source components. There seems to be a notion of ‘You built it so support it!’ within the Grails community whereas other communities nourish a more cooperative DIY style.

Now, when developing software for commercial purposes ‘You built it so support it!’ is perfectly fine but given that most open source developers don’t get compensated directly for their efforts this is problematic at least. Sure, open source work can gain you a decent job, marketing buzz or new customers for your company but this alone in most cases doesn’t justify doing extensive and often painful support.

I think the root of the matter is the cultural background of Grails in contrast to the background of projects like Rails:

While Rails has been born out of explicit disdain for ‘enterprise’ culture with all its complexities and often cumbersome nonsense, Grails tried to build upon a few positive aspects of enterprise software culture like reliability, scalability and security and do away with unproductive, complex boilerplate code at the same time.

So, while those two frameworks aren’t that different in terms of features and what can be achieved with them, each comes from and mainly caters for a distinctly different background.

Regarding the matter at hand, the problem with the enterprise background of Grails chiefly is that enterprise customers expect to pay often bizarre amounts of money for software allowing them to hold the creators of said software responsible and demand extensive support from them.

In a way this notion maybe shines through here as well. In the enterprise segment people are used to getting support for the software they use so they also demand this kind of support from open source developers, who mostly happen to create their stuff in their spare time.

While I’m perfectly fine with releasing my own plugins under the Apache license and support them whenever I have time to, I can completely comprehend Robert’s point of view and his desire to get a different kind of compensation for his open source work. In fact, there should be plenty of space for both approaches (and anything that lies in-between) within open source software development.

However, in my opinion the Grails community – especially those relying on Grails for commercial applications – does indeed have a problem if one of its most prolific plugin authors feels like he has to resort to such rather unusual measures to gain appreciation for the work he’s doing.

Moreover, although I consider a commercial market for Grails Plugins an interesting idea, I don’t think this is a viable alternative for plugin developers and users alike.
This would first of all require a much wider adoption of Grails to allow developers to get a decent amount of money from plugin development.
Secondly, this would most likely exclude smaller enterprises from adopting Grails at all.

Your thoughts?

List of related articles:

March 1, 2010

MagicNumbers: Dynamic Time and Byte Calculations for Grails – Using the Meta Object Protocol to add behaviour to Grails at runtime

Filed under: Uncategorized — Tags: , , — Björn Wilmsmann @ 1:00 pm

The March issue of GroovyMag, an online-only magazine for everything Groovy and Grails has been published today.

I’ve contributed an article about the Grails MagicNumbers plugin you might find interesting. Here’s a teaser:

Grails plugin development and Groovy‘s Meta Object Protocol are powerful tools for adding runtime modifications to standard Java classes. Introducing the new Grails MagicNumbers plugin, I’d like to show how metaprogramming in Groovy can be used to make code both more readable and easier to write. The MagicNumbers plugin allows you to write readable code like 3.days or 6.megabytes instead of having to manually calculate the equivalent number of seconds or bytes.

[ … ]

Code like this obviously has several advantages over manually calculating and writing the actual numbers:

  • It is written much more easily.
  • The code is much more readable. You can even show this code to someone who hasn’t any programming experience at all and she will immediately understand its purpose.
  • The code is less error-prone and thus more maintainable.

So, I wanted to have this kind of magic in Grails as well. Fortunately, due to Groovy’s Meta Object Protocol and the Grails plugin framework, this kind of functionality can be added quickly and elegantly.

[ … ]

Read the rest of this article at GroovyMag.

Related links:

January 8, 2010

Using Grails for creating UML diagrams

Filed under: Uncategorized — Tags: , — Björn Wilmsmann @ 7:59 pm

Back in the old days (like, 5 years ago …) when embarking upon a new software project you would (hopefully, that is …) usually start by sketching the underlying model using ER or UML diagrams.

No matter if you’re on the more enterprisey side of software development that requires more complex upfront documentation or if you’re going down the agile road, there had to be at least some sort of a model.

Problem is, once you’ve drawn that model in your favourite UML design tool or just with good ol’ pen & paper, you have to turn that model into code. Although the more expensive UML design tools allow for code creation and sometimes even feature round-trip abilities (that is code changes are reflected in the diagram), most of them are far from perfect in that they mostly produce fairly generic Java code that has to be heavily customised depending on the framework you’re using.

Even worse, if you use another language like Groovy or Ruby you likely have to start writing code from scratch.

However, fortunately for Grails there are two nifty plugins that offer an elegant way out (see http://railroad.rubyforge.org/ for a Rails solution):

Both automatically create UML diagrams for your app’s domain model. The main difference between those two is that the former draws upon yUML.me, a very promising web service that allows you to create UML diagrams with a Wiki-like syntax.

So, nowadays I don’t even bother firing up Visual Paradigm – the UML design tool I liked best before – anymore when I have to design a domain model. All I do is run ‘grails create-app’ and start writing actual domain class code! Thanks to GORM, Grails‘ object-relational mapping, writing actual code is easier and faster than drawing diagrams in a design tool.

Once I’m done I can use one of the plugins mentioned above to create a shiny UML diagram for impressing the customer and documenting the current state of the application.

Update: Sven Lange wrote a nice and more detailed blog post about Grails and UML diagrams, too: http://www.svenlange.co.za/?p=80

January 2, 2010

Grails MagicNumbers Plugin 0.2.2 released

Filed under: Uncategorized — Tags: , — Björn Wilmsmann @ 5:14 pm

I’ve been busy today working on some improvements of the new MagicNumbers plugin.

The new version mainly features new methods for byte calculation, some additional time calculation methods and a bug fix with regards to displaying large numbers. Moreover, the plugin now also adds its methods to the Long class in addition to the Integer class.

Please have a look at the plugin documentation, too:

http://grails.org/plugin/magic-numbers

Grails MagicNumbers Plugin 0.1 released

Filed under: Uncategorized — Tags: , — Björn Wilmsmann @ 4:35 am

Inspired by RailsActiveSupport library, we’ve just released the MagicNumbers plugin that adds several time calculation methods to the Integer class:

http://grails.org/plugin/magic-numbers

With this plugin you now can do cool things like the following with Grails as well:

2.minutes
1.hour
4.weeks
2.months.fromNow

December 31, 2009

Tired of updating your copyright notices each year?

Filed under: Uncategorized — Tags: , — Björn Wilmsmann @ 7:15 pm

If you have a website chances are you go through the same tedious process each January, 1st: Updating your copyright notice to the current year. If you happen to use Grails for your website you can have it handle that update automatically for you (other frameworks and languages are of course capable of this, too) by adding the following code to the footer of your layout:


&copy; <g:formatDate format="yyyy" date="${new Date()}"/>

Older Posts »

Create a free website or blog at WordPress.com.