# Reversing Groovy Switch Statement

Recently I’ve been working on a Groovy code that had many methods with long multibranch conditionals like this:

def parse(message, options) {
if (options.contains('A')) {
parseARule message
} else if (options.contains(2)) {
parseSmallDigitRule message
...
} else if (options.contains(something)) {
parseSomeRule message
} else {
parseSomeOtherRule message
}
}


Although this code is working, it is hard to see which branch is called under which condition. It would be much better if we could replace this code with something like Lisp cond macro. The best candidate for such a task in Groovy would be a switch statement. If we could only refactor the code above to something like following, it would significantly improve readability:

def parse(message, options) {
switch (options) {
case 'A' : return parseARule(message)
case 2   : return parseSmallDigitRule(message)
...
case ... : return parseSomeRule(message)
default  : return parseSomeOtherRule(message)
}
}


Unfortunately, this code doesn’t work out of the box in Groovy, but it works if we do some metaprogramming.

The way switch statement works in Groovy is a bit different than in Java. Instead of equals() it uses isCase() method to match case-value and switch-value. The default implementation of isCase() method falls back to equals() method, but some classes, including Collection, override this behaviour. That’s why in Groovy you can do things like this:

switch (value) {
case ['A','E','I','O','U'] : return 'vowel'
case 0..9                  : return 'digit'
case Date                  : return 'date'
default                    : return 'something else'
}


For our purposes we need some sort of reverse switch, where collection is used as a switch-value, and String and Integer are used as a case-value. To do this we need to override default implementation of isCase() method on String and Integer classes. It’s not possible in Java, but is very easy in Groovy. You can change method implementation globally by replacing it in corresponding meta class, or locally with the help of categories. Let’s create a category that swaps object and subject of isCase() method:

class CaseCategory {
static boolean isCase(String string, Collection col) {
reverseCase(string, col)
}
static boolean isCase(Integer integer, Collection col) {
reverseCase(integer, col)
}

private static boolean reverseCase(left, right) {
right.isCase(left)
}
}


Now we can use this category to achieve the goal we stated at the beginning of this post:

def parse(message, options) {
use (CaseCategory) {
switch (options) {
case 'A' : return parseARule(message)
case 2   : return parseSmallDigitRule(message)
...
case ... : return parseSomeRule(message)
default  : return parseSomeOtherRule(message)
}
}
}


If you are comfortable with global method replacement, you can amend String and Integer meta classes. In this case you don’t need to wrap switch statement with use keyword.

# Lazy Lists in Groovy

I like lazy evaluation, and it’s one of the reasons I like Haskell and Clojure. Although from engineering perspective lazy evaluation is probably not the most needed feature, it’s definitely very useful for solving some mathematical problems.

Most languages don’t have lazy evaluation out of the box, but you can implement it using some other language features. This is an interesting task, and I use it as a code kata which I practice every time I learn a new strict language.

So, how to implement lazy lists in a strict language? Very simple, if the language is functional. Namely, you build lazy list recursively by wrapping strict list within a function. Here is, for example, the strict empty list in Groovy:

If we wrap it with a closure, it becomes lazy empty list:

If we need a list with one element, we prepend (or speaking Lisp terminology cons) an element to lazy empty list, and make the result lazy again:

To add more elements we continue the same process until all elements are lazily consed. Here is, for example, a lazy list with three elements a, b and c:

Now, when you have an idea how to build lazy lists, let’s build them Groovy way. We start by creating a class:

The variable list encapsulates the closure wrapper of the list. We need to expose some methods that allow constructing lists using procedure described above:

Now we can construct lists by consing elements to empty list:

To access elements of the list we implement two standard functions, car and cdr, that return head and tail of the list respectively.

Here is how you use these functions to get first and second elements of the list constructed above

In Lisp there are built-in functions for various car and cdr compositions. For example, the previous assertion would be equivalent to function cadr. Instead of implementing all possible permutations, let’s use Groovy metaprogramming to achieve the same goal.

It might look complicated, but in reality it’s pretty simple if you are familiar with Groovy regex and functional programming. It’s easier to explain by example. If we pass “caddr” as a value of name parameter, the method will create a chain on method calls .cdr().cdr().car() which will be applied to delegate of the operation which is our LazyList object.

With this method in place we can call car/cdr functions with arbitrary depth.

If you create nested lazy lists, you can access any element of any nested list with this dynamic method.

With so many cons methods it’s hard to see the structure of the list. Let’s implement lazy method on ArrayList class that converts strict list to lazy. Again, we will use metaprogramming and functional techniques.

Now we can rewrite the previous example as follows

What have we accomplished so far? We learned how to build lazy lists from scratch and from strict lists. We know how to add elements to lazy lists, and how to access them. The next step is to implement fold function. fold is the fundamental operation in functional languages, so our lazy lists must provide it.

The only difference between this fold function and the standard one is the additional parameter n. We will need it later when we implement infinite lists. foldAll function to lazy lists is the same as standard fold to strict lists.

First example calculates the sum of all elements of the list, second calculates the product of first three elements.

If you have fold functions you can easily implement take functions

take is an inverse operation to lazy

Our next goal is map function on lazy lists. Ideally I want the implementation look like this

For some reason it doesn’t work lazy way in Groovy — it’s still strictly evaluated. Therefore I have to implement it directly with closure syntax

Unlike fold, lazy map is identical to strict map

The following example shows one of the benefits of laziness

map didn’t evaluate the entire list, hence there was no exception. If you evaluate the expression for all the elements, the exception will be thrown

For strict lists this is a default behaviour of map function.

The last function I want to implement is filter

In the following example we find first two elements greater than 2

With the help of car/cdr, fold, map and filter you can implement any other function on lazy lists yourself. Here is, for example, the implementation of zipWith function

Now, after we implemented all lazy functions we need, let’s define infinite lists

Infinite lists, from my point of view, is the most useful application of lazy lists

At this point you have all basic functionality implemented, and you should be able to extend this model to whatever you need in regards to lazy (infinite) lists. Happy lazy programming!

# Counting Modifications in Git Repository

Michael Feathers wrote a blog about Open-Closed Principle, where he described simple technique that measures the closure of the code. I created a Groovy script which implements this algorithm for Git repositories. If you run it from the root of your Git project, it produces a CSV file with the statistics of how many times the files have been modified.

As an example, here is the top 10 files from rabbitmq-server repository

845  src/rabbit_amqqueue_process.erl
711  src/rabbit_channel.erl
650  src/rabbit_tests.erl
588  src/rabbit_variable_queue.erl
457  src/rabbit_amqqueue.erl
448  src/rabbit_mnesia.erl
405  src/rabbit.erl
360  src/rabbit_msg_store.erl
356  src/rabbit_exchange.erl


# Maven and Git

More and more Maven projects are switching from Subversion to Git, and the majority of those projects make the same mistake: They configure scm section of POM to point to remote repository, the same way they did it in Subversion

By doing this they lose the main benefit of Git. They become dependent on the remote machine. And when their release depends on the remote machine, that’s what happens: They need to release the project but the remote machine is down

The right way of configuring Git in Maven is following

This configuration is universal, and it separates two orthogonal concerns: releases and remote copies.

### Resources

• Screencast that shows how to work with Git in Maven projects.

# Joe Armstrong on Optimization

A quote from Erlang and OTP in Action book

Make it work, then make it beautiful, then if you really, really have to, make it fast. 90 percent of the time, if you make it beautiful, it will already be fast. So really, just make it beautiful!

A quote from InfoQ interview

I think that people first of all write a problem, they solve the problem and then they sort of optimize this code, work on it and the code becomes very efficient but unreadable. What I think they should doing is specifying it with a domain specific language or some higher thing and then writing a compiler and then changing the compiler because it’s not efficient. Because then they would have the benefits of a clear specification and a fast implementation. What they do is they don’t keep these things separated and the language doesn’t support them separating it like that.

If you worked with Erlang you’ve probably heard about selective receive. In this article I want to demonstrate what selective receive is and how it works. Let me start with an excerpt from Joe Armstrong’s book Programming Erlang (Section 8.6, p.155):

1. When we enter a receive statement, we start a timer (but only if an after section is present in the expression).
2. Take the first message in the mailbox and try to match it against Pattern1, Pattern2, and so on. If the match succeeds, the message is removed from the mailbox, and the expressions following the pattern are evaluated.
3. If none of the patterns in the receive statement matches the first message in the mailbox, then the first message is removed from the mailbox and put into a “save queue.” The second message in the mailbox is then tried. This procedure is repeated until a matching message is found or until all the messages in the mailbox have been examined.
4. If none of the messages in the mailbox matches, then the process is suspended and will be rescheduled for execution the next time a new message is put in the mailbox. Note that when a new message arrives, the messages in the save queue are not rematched; only the new message is matched.
5. As soon as a message has been matched, then all messages that have been put into the save queue are reentered into the mailbox in the order in which they arrived at the process. If a timer was set, it is cleared.
6. If the timer elapses when we are waiting for a message, then evaluate the expressions ExpressionsTimeout and put any saved messages back into the mailbox in the order in which they arrived at the process.

# Book Review: Erlang and OTP in Action

Title: Erlang and OTP in Action
Author: Martin Logan, Eric Merritt, and Richard Carlsson
Paperback: 432 pages
Publisher: Manning Publications; November 2010
Language: English
ISBN-10: 1933988789
ISBN-13: 978-1933988788
$38.99 (amazon.com) ### Overview Even though this book has Erlang in its title, it’s only about 15% of the content dedicated to Erlang language itself — the biggest portion of the book is about OTP. Nowadays, when more and more developers get familiar with Erlang, they need a new book that can boost them to the next level of proficiency, where they can produce industry standard code leveraging all the power of Erlang platform. This book is supposed to fill this gap! # SpringOne2GX 2010 Last week I attended SpringOne2GX conference in Chicago, the main event in Spring/Groovy/Grails community. Here I want to post my brief review of this conference. ### First impressions The hotel (Westin Lombard) was nice and clean. Internet: there were 2 wireless networks and one cable — everything was free and worked pretty well, signal was good in almost all rooms. The conference reception was well organized — every participant received bunch of souvenirs and special edition of NFJS magazine. I saw hundreds of smiling and happy people of different ages and different outfits. Most of them with Macs. Most of them know each other. The food was fantastic, especially dinner with wine and beer. ## Day 1 The first day was mostly introduction and orientation. There was only one talk on the schedule. ### Rod Johnson — Keynote (video) I thought Spring was initially created 7 years ago but the oldest class in the source tree is dated by January 17, 2001, so Spring is actually almost 10 years old. Because of the anniversary the main theme of the presentation was: Where Spring goes in the next decade. Since the core framework is well crafted already, the focus will be on the integration and making Spring portfolio as a platform for applications. There are three key values in Spring — portability, productivity, and innovation — and the platform will be built along those dimensions. #### Portability In the past SpringSource made a good job by providing a framework that makes Java applications easily portable across different application servers. The goal for the next decade is to expand the same portability to the cloud — Google AppEngine, vFabric, vmforce, etc. #### Productivity As we all know the ultimate reason of the Spring existence is to make the life of application developer easier, our work is more productive. The framework hides the low-level boilerplate, and provides well defined abstractions. In the next year there will be several features added to the Spring portfolio. Rod mentioned some of them: • Seamless GWT integration • Database reverse engineering with roundtripping support in Spring Roo 1.1. You will be able to generate the domain object tree based on your database schema, and it will be updated every time you change the database. • Spring Payment Services project with Visa integration. Another aspect of productivity is a tool suite, where Spring provides STS. Rod invited Christian Dupuis on the stage, where he demoed how to developed Grails applications in STS. If you are a Grails developer you should definitely take a look at the latest version of STS — it will increase your productivity significantly. #### Innovation There will be several new projects released in the Spring portfolio soon: • Spring Social — application abstraction for social networks. • Spring Mobile — platform for multi-device applications. • Spring-AMQP — API for integration with RabbitMQ. • Spring Data — API to work with NoSQL databases, in particular Neo4J support in Spring Roo. Keith Donald demoed GreenHouse project and corresponding iPhone app. This is a reference implementation of Spring Mobile and Spring Social, and this app was really really useful during the conference when I needed to check the schedule and find the room. At the end of the presentation Rod introduced, and Mik Kersten demoed, the next big thing — Code2Cloud. It’s basically a tool that allows you to keep and manage your entire development environment in the cloud: the running app, the source code, the issue tracker, and the build server. Everything is in the cloud and configured by mouse click. It looks cool, and it definitely will be a buzz word in the next year, but I’m not sure if many people will use it. We’ll see. ## Day 2 I’m going to write only about technical sessions I attended. ### Jürgen Höller — What’s new in Spring Framework 3.1? (video) That was one of the best talks of this conference: technical, right to the point, with well-wrtten slides, and personal charm of the presenter. Despite the number 3.1 in the title, Jürgen actually covered three versions of Spring framework: 3.0, 3.1, and 3.2. I’m going to briefly mention the interesting features, and if you want more details you can check the excellent on-line documentation. #### Spring 3.0 • Custom annotations. You can create your own annotation by combining multiple existing annotations in one group. Spring automatically detects your annotation during the application context startup, and no special configuration is required. This is a very handy feature, especially when you copy-paste the same annotation group over and over again. • Configuration classes and annotated factory methods. If you annotate a method with @Bean annotation Spring framework will make the output of the method a Spring bean. There are some other annotations supported, e.g. @Lazy. • Standardized annotations. Spring now supports JSR-330 @Inject, JSR-250 @ManagedBean, and EJB 3.x @TransactionAnnotation. • EL++. Expression language can be used now in bean definitions inside appcontext XML, and also in component annotations. Very powerful feature. • REST support. Spring provides RestTemplate for client code, @PathVariable annotation, and special view resolvers on the server side. It’s very interesting topic — check the documentation for details. • Declarative model validation. You can specify data constraints right in your code by using annotations — very similar to what you have in GORM. • Improved scheduling. New namespace, and @Scheduled and @Async annotations makes your appcontext smaller and more readable. If you follow Spring releases, you probably use some or most of these features already. Now let’s see what Spring 3.1 brings to us. #### Spring 3.1 • Environment profiles for beans. Similar to Maven profiles but works in runtime. The idea here is to create a single deployment unit for all environments and enable certain Spring beans for specific environment. I can’t wait to try this feature in our enterprise project. • Cache abstraction. After 5 years of hibernation this feature is finally implemented. Spring provides an API to work with distributed cache, in particular in cloud environments. There will be adapters for most popular cache implementations, such as EhCache, GemFire, Coherence. • Conversation management, or how Jürgen calls it HttpSession++. It’s basically an extension of HttpSession shared across multiple browsers and window tabs. Looks very interesting. • Enhanced Groovy support. • c: namespace, which is a shortcut for <constructor-arg>, analogous to p: namespace for properties. Small feature that makes your appcontext consistent and more readable. #### Spring 3.2 Java SE 7 support, JDBC 4.1, support for fork-join framework, general focus on concurrent programming. ### Jeff Brown — GORM inside and out This talk was also good. I worked a bit with GORM before, and had an idea how it’s implemented, but it was useful to hear more details from one of its developers. Jeff started with the background of GORM, the complexity of Hibernate and JPA, and how GORM solves this problem following convention-over-configuration and sensible defaults strategies. He showed how to model the domain objects, what happens behind the scene when you link objects together, how to specify uni- and bi-directional relationships, and how to change default collection implementation in case of one-to-many relationship. During the presentation he was switching back and forth between sides and terminal, so it was easy to follow and understand the evolution of the sample application. He explained how to introduce various constraints into the model and how Grails would validate them. One of the interesting features I didn’t know about was how to test internationalized error messages. You don’t need to change your locale for that, simply add lang=your_language parameter to the URL, and Grails will switch to that language for all subsequent requests. Pretty handy. He concluded the talk by showing how dynamic finders are implemented in GORM using Groovy metaprogramming feature. Interesting part here is that you can implement similar things in your Groovy code using the same technique, basically having custom mini-GORM in your Groovy project! ### Venkat Subramaniam — Improving your Groovy code quality The title of this presentation was little bit misleading for me. I expected Venkat to show some Groovy specific mistakes and how to avoid them. Instead, he was talking about the errors that in most cases are equally applied to any programming language. He mentioned various code smells and explained how to fix them. If you are interested, you can download the slides from Venkat’s web site. He also gave an advise how to maintain the high code quality: • Have a respectable colleague review your code. • Use code analysis tools like CodeNarc and Sonar Groovy plugin. One of the topics he covered was the usage of the return keyword in Groovy. That was interesting. Compare the following two functions, guess what they return, and check your answer in the console ### Paul King, Guillaume Laforge — Groovy.DSLs (from: beginner, to: expert) (video) This would be very nice presentation if the speakers didn’t try to cover too much. This talk could be easily split into two: one is an overview of Groovy language and another one is DSL. Unfortunately they spent lot of time on theoretical DSL part and Groovy overview, so the practical DSL part was too short from my perspective. The good thing though is that I have slides now, so I can dig deeper into this subject at my spare time. In the second part of the talk Paul and Guillaume explained which features of Groovy language make it so simple to create DSLs. Here are some of them: • Static imports and import aliases. • Simplified collection syntax. • Small or no language noise. • Aggregating multiple method calls using ‘with’ construct. • Closures. • Operator overloading. • Metaprogramming. In the last part speakers talked about different patterns and techniques of DSL implementations. They provided a comprehensive list of books you might want to read if you are interested in building DSLs. ### Adrian Colyer — Technical keynote (video) Adrian’s talk was mostly a reiteration of Rod’s keynote from the previous day with some technical details. He mentioned Spring Payment and Spring Data projects, bean profiles and cache support in the Spring core. He showed Spring portability in action by providing links to Spring applications deployed on Google AppEngine and vmForce. Another interesting part was 20 minutes dedicated to RabbitMQ and Spring-AMQP. He even mentioned Spring-Erlang project which is supposed to be a convenient abstraction on top of standard Jinterface library. As a continuation of innovation theme Graeme Rocher demoed GORM support for NoSQL databases. That was cool. He simply uninstalled Hibernate plugin and installed Redis plugin, without touching data model. Everything worked perfect. Right now Spring works with Redis and GemFire, but soon they are going to add support for CouchDB, Cassandra, Riak, Neo4j, and MongoDB. Another interesting thing Graeme showed was grails-console. It’s a pretty nice tool, you should check it out. It allows you to interact with the Grails data storage using GORM features. Very handy. Another co-presenter was Keith Donald who demoed Spring Social and Spring Mobile. He explained how OAuth works, and how interoperability with social networks was implemented in GreenHouse. The keynote was concluded by Jon Travis who demoed SpringInsight. ## Day 3 ### Venkat Subramaniam — Functional programming in Groovy That was an excellent talk and nice start of the new conference day. Venkat explained main concepts and values of functional programming, and illustrated the theory with comprehensible examples. He compared imperative and functional style of programming by showing how to implement for-loop using inject function in Groovy. I think it was one of the best explanations of functional folding I’ve ever heard. He also demonstrated map and filter operations using collect and findAll methods. He clarified the difference between function value and closure, and between iterative procedure and iterative process. He gave an example on how to pass closure as a parameter to simulate function object in Groovy. He also showed how to replace tail-recursion, which Groovy doesn’t support, with inject method call. The presentation was concluded with an example of how to use functional techniques to build DSLs in Groovy. ### Matthias Radestock, Mark Pollack, Mark Fisher — RabbitMQ and Spring-AMQP (video) If you read my blog, you know that RabbitMQ is one of my latest interests. I decided to go to this talk just to see how the creators would present their projects. It turned out to be a nice introduction to both RabbitMQ and Spring-AMQP. They explained main concepts of AMQP and how it is different from JMS. Here I want to give you some ideas which were not obvious for me when I started working with RabbitMQ. • Messaging is all about decoupling, and AMQP is much more flexible than JMS in terms of publisher-consumer decomposition. • All resources are dynamically created and destroyed by clients — the static pre-configuration is optional. • Exchanges are stateless, they don’t keep messages, they only copy and dispatch them. Queues hold the messages and deliver one message to a single client. They neither do routing nor message copying. • Queue never receives the same message twice. • If the message doesn’t match routing key it’s dropped. • Because of the open protocol, you can use all available TCP tools to monitor your message traffic. Besides AMQP implementation RabbitMQ also provides some other useful features like custom exchanges, exchange-to-exchange routing, different protocol adaptors, etc. Spring, as usual, gives you a consistent API on top of the RabbitMQ client which hides all low-level boilerplate and makes your application code more readable. ### Craig Walls — Developing social-ready web applications (video) This presentation was about integrating your Java code with different social networks. There are three types of such integration: widgets, embedded code, REST API. Craig briefly explained first two, and then dived into REST. All popular social networks provide REST API which allows you to communicate with them. For simple operations, like search, you can just use standard Spring RestTemplate class to retrieve the data. Try for example the following URLs: This basic approach fails though if you try to post a new message, because you have to be authorized for update operations. That’s where OAuth comes in. The idea behind OAuth is pretty simple: instead of sharing your user-password with different clients, it uses generated tokens. This model is more flexible because if you want to revoke the permission from particular client you don’t need to change your password and notify rest of the clients — you just remove that client’s token from the list of authorized clients and that’s it. The only problem with OAuth and social networks is that they support different versions of OAuth. This problem is solved by Spring Social project. Spring Social offers consistent template-based API across different social providers. It basically gives you an OAuth aware RestTemplate, so you can do something like this: If you are in a social network business, definitely take a look at Spring Social. ### Mark Pollack, Chris Richardson — Using Spring with non-relational databases (video) Relational databases are great, right? They’ve been with us for ages. Everybody knows how to work with them, how to build SQL statements. Every language provides ODBC library. There are bunch of frameworks that make developer’s life easier. So why is so much buzz around NoSQL? Mark and Chris started their talk highlighting some problems that exist in relational database world: • Object-relational impedance mismatch. Complicated mapping of rich domain model to relational schema. Relational schema rigidity. • Extremely difficult/impossible to scale write operations. • Suboptimal performance in some cases. All these issues are addressed in NoSQL databases. Although keep in mind that it’s not coming for free — you have to trade off ACID semantics, transactions and some other features of RDBMS. But if scalability is more important for you than consistency then NoSQL is your way to go. There are tons of NoSQL databases available for you, but they all can be split into 4 categories based on their data model: • Key-Value: Amazon Dynamo, Redis, Riak, Voldemort. • Column: Google Bigtable, HBase, Cassandra. • Document: CouchDB, MongoDB. • Graph: Neo4j, Sones, InfiniteGraph. Mark and Chris talked about each type, what their typical use cases are, and how their APIs look like. They showed examples for Redis, Cassandra, MongoDB, CouchDB and Neo4j. Then they introduced Spring Data project which, as everything from SpringSource, simplifies the application development and hides low-level code. Right now they support most of the popular NoSQL databases, and they plan to add more in the future. The project is in active development phase, and the new contributors are welcome. So if it sounds interesting for you, go and check it out. ## Day 4 ### Hans Dockter — Gradle — a better way to build I never played with Gradle, so I was very curious to see how it looks like. According to Hans, who is the creator of this tool, Gradle is a general purpose build system with Groovy DSL interface. It’s written in Java and provides build-in support for Java, Groovy, Scala, web and OSGi projects. It’s a build language, so you can extend it for your own purposes if needed. If you compare it with Ant, Gradle is definitely much better because it’s more compact and flexible. It offers dependency resolution with integration with Maven and Ivy repositories. It also has some advanced features like incremental builds for custom tasks and parallel testing. The only problem I had with this presentation was that Hans kept comparing Gradle with Maven. In my opinion they are not comparable. They have different philosophy if you want. All Maven “constraints” are imposed by design, so it makes no sense to blame Maven for them. I think Ant-Gradle comparison is more appropriate and that’s what Hans should have emphasized. Other than that the session was pretty informative, and I have a better picture of Gradle now. ### Brian Sletten — Groovy + The Semantic Web I had no idea what Semantic Web was. I saw this term first time on the conference schedule, so I decided to go to this talk just to educate myself. I cannot even briefly describe all the discoveries I made during this presentation because I still feel little bit overwhelmed. I just want to provide some links from Brian’s slides that can guide you if you want to learn this concept. ### Conclusion Whew! This happened to be longer review than I planned initially. If you are still with me, congratulations! There were much more presentations at this conference but because of the tight schedule I had to sacrifice 80% of them. My overall impression from this conference is very positive. If you are a Spring/Groovy/Grails developer I encourage you to go to this event next year. The biggest benefit of it: You start seeing the Spring as a universe, not as a bunch of separate projects. You cannot get this feeling from the documentation, even if it’s perfect as the Spring one. # Integrating RabbitMQ With Ejabberd ejabberd is integrated with RabbitMQ by means of mod_rabbitmq gateway. If you followed my ejabberd installation instructions, you should already have mod_rabbitmq installed. ## Configure mod_rabbitmq Open /opt/ejabberd/ejabberd/etc/ejabberd/ejabberd.cfg file, find modules section, and add mod_rabbitmq stanza to the list You need to replace RABBIT_NODE with the real value, which you can find from the RabbitMQ process information $ ps -ef | grep beam
rabbitmq  8525  8142  0 16:37 pts/0    ... -sname rabbit@ubuntu ...


You can see my RabbitMQ node name is rabbit@ubuntu.

To make RabbitMQ and ejabberd work together, they have to run in the same Erlang cluster. That means they have to use the same cookie file. If you installed RabbitMQ from binary distribution, it uses the user’s cookie ~/.erlang.cookie. ejabberd, on the other hand, uses its own cookie. Let’s replace it with the user’s

$cd /opt/ejabberd/ejabberd/var/lib/ejabberd$ rm -f .erlang.cookie
$ln -s ~/.erlang.cookie  Restart ejabberd server $ /opt/ejabberd/ejabberd/sbin/ejabberdctl restart


## Add rabbit buddy to roster

The rabbit’s JID consists of two parts: exchange name and routing domain. The routing domain is a string rabbitmq.EJABBERD_HOST where EJABBERD_HOST is the host you registered in ejabberd.cfg. In my case the routing domain is rabbitmq.jabber.ndpar.com.

For the name you can use any exchange name available in the RabbitMQ server. I use amq.fanout exchange which exists in every RabbitMQ server. So I go to my IM client (Adium) and add this user to the buddies list amq.fanout@rabbitmq.jabber.ndpar.com.

## Rabbit’s greetings

To publish a message to RabbitMQ I use the same Groovy script as in the previous post

\$ ./publisher.groovy


# Get Started With RabbitMQ

RabbitMQ is an open-source implementation of AMQP. If you don’t know what AMQP is, I encourage you to read about it on the official web site or the reference page. What I personally like in RabbitMQ/AMQP is

• AMQP is a free alternative to expensive TIBCO Randezvous.
• Functionality-wise AMQP is a superset of JMS.
• RabbitMQ is written in Erlang, which means fault-tolerance and reliability.

In this short blog entry I show how to install RabbitMQ on a *nix box, and verify that it’s working with a simple Groovy client.