Tropical Software Observations

Showing posts with label groovy. Show all posts
Showing posts with label groovy. Show all posts
30 August 2010

Posted by Unknown

at 4:20 PM

0 comments

Labels: , ,

RabbitMQ: PubSub Messaging with Groovy

RabbitMQ typically send "direct" message between the queue and the listeners -- if you have 5 messages put on the queue with 3 listeners, then each of the listener will get one of these messages. However if you need to have all the listeners get the same message, you need to set the exchange to "fanout".

The explanation of using rabbitmq's fanout feature may be well described in the FAQ, but it's not clear in code. So I hope someone will find the below groovy code helpful to see how to use rabbitmq fanout for pubsub topology messaging.

The below code is a basic message publisher to send message to rabbitmq queue. Note the exchange declared as "fanout" exchange. The queue binding may not be useful in fanout use case as all the messages will be send out to all listening consumers.



import com.rabbitmq.client.*


def factory = new ConnectionFactory();
factory.setUsername(username);
factory.setPassword(password);
factory.setVirtualHost("/");
factory.setHost(rabbitmqhost)
factory.setPort(rabbitmqport)
Connection conn = factory.newConnection();
def channel = conn.createChannel()


String exchangeName = "foExchange"
String routingKey = "foo"
String queueName = "fooQueue"


channel.exchangeDeclare(exchangeName, "fanout", true)
channel.queueDeclare(queueName, true, false, false, null);


(1..3).each { n ->
    channel.basicPublish(exchangeName, routingKey,  MessageProperties.PERSISTENT_TEXT_PLAIN, 
                        " (${n}) test testing test [${new Date()}]".getBytes() );
}


channel.close()
conn.close()
System.exit(0)
println " Fin "




Now lets look at the consumer side to consume messages in fanout use case.In a fanout setup, the consumer doesn't have to do anything special. If you don't specify any particular queue name, it will get all messages from the exchange. You can however continue to received message from any particular queue if you bind to it.





String exchangeName = "fooExchange"
String routingKey = "foo"
//String queueName = "fooQueue"


String queueName = channel.queueDeclare().getQueue()
channel.queueBind(queueName, exchangeName, "#");
println " Queue: ${queueName} "


boolean noAck = false;
def consumer = new QueueingConsumer(channel);
channel.basicConsume(queueName, noAck, consumer);
boolean running = true


while(running) {


    QueueingConsumer.Delivery delivery;
    try {
        delivery = consumer.nextDelivery();
        println new String(delivery.body)
    } catch (InterruptedException ie) {
        continue;
    }
    channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
    
}


19 January 2010

Posted by Unknown

at 3:03 PM

0 comments

Labels: , , ,

GORM query by association (query properties of child object)

Let's say we have a Book object and it has an associated Author object. To query Books based on certain properties of the Author we have 2 common ways to it.

1. Using HQL query

def results = Book.findAll(" from Book as b where :title = b.author.name) ", [title:"Mr Author"])

2. Using criteria with createAlias()

def results = Book.withCriteria {
createAlias("author", "a")
eq("a.name", "Mr Author")
}

I hope this helps some of you out there. For some reason "createAlias" is not well documented in the Grails documentation, unless you cross reference the Hibernate docs.

04 August 2009

Posted by Irregular Zero

at 4:28 PM

0 comments

Labels: , ,

Groovy Tutorial for MongoDB

Java Tutorial (http://www.mongodb.org/display/DOCS/Java+Tutorial)

Since Groovy is based on Java, you can make use of the Java driver for MongoDB as well as go through the tutorial shown above. The code can be used as-is or modified to look more groovy.

Create a groovy file (mongo.groovy) and place the Java driver in the same directory. Edit it so the code looks like:

this.class.classLoader.rootLoader.addURL(new File("mongo-0.6.jar").toURL())

import com.mongodb.*

DBAddress address = new DBAddress("localhost", "mydb")
Mongo db = new Mongo(address)
db.authenticate('testUser', 'testPassword')

DBCollection coll = db.getCollection("testCollection")

BasicDBObject doc = new BasicDBObject()
doc.put("name", "MongoDB")
doc.put("type", "database")
doc.put("count", 1)

BasicDBObject info = new BasicDBObject()
info.put("x", 203)
info.put("y", 102)
doc.put("info", info)

coll.insert(doc)

for(i in 1..100) {
coll.insert(new BasicDBObject().append("i", i))
}

println coll.getCount()

DBCursor cursor = coll.find()
while(cursor.hasNext()) {
println cursor.next()
}

You can see it's just a rehash of part of the Java tutorial, the output will be a count of the number of inserted objects followed by the objects themselves.

The first line of code loads the jar file, this is useful if you're not looking to put the jar in a classpath or one of groovy's configured library paths like '~/.groovy/lib'.

Running the script is accomplished by 'groovy mongo.groovy' in the terminal. You can also type in 'groovyConsole' to load the console then opening the script and running inside it.

28 April 2009

Posted by Bacchus D

at 4:57 PM

0 comments

Labels: , ,

Grails and PartyTime Training in China


We've just returned from a trip to Guangzhou where we spent two days working with our partners, Well United, on Groovy, Grails, and PartyTime. It turned out to be a larger group than expected but the more the merrier!

It was a lot to cover in two days but even though the time allotted for the training session was rather short, it went very well and the Well United team picked everything up quickly.  The C#, PHP, and Java developers seemed enthusiastic about Grails and we hope to be working together on projects sometime soon.

Many thanks to our gracious hosts in Guangzhou and Hong Kong. We enjoyed the Macanese and Cantonese food and hope to be back soon!


18 April 2009

Posted by Unknown

at 11:23 AM

2 comments

Labels: ,

Install Groovy 1.6.1 on Windows -- A guide for the non-Java developer

* This is a quick guide on installing the latest Groovy 1.6.1 in Windows for non-Java developers.

1. Download and install Java SDK 1.6.x. Get the latest installer from Sun here. If this is your first time downloading Java, you are going to be confused with the various JDK 6 Updates packages -- JDK 6 Update with JavaFX SDK, JDK Update with Java EE, JDK Update with NetBeans 6.5.x. If unsure just look for the package without any of those extras -- Java 6 Update 13.

2. Download Groovy 1.6.1 installer from Groovy site. We will just use the Windows installer.

3. Double click on the Groovy installer and follow the wizard steps.


4. Use the defaults settings -- create GROOVY_HOME, add to PATH and add to System environment.


5. Make sure you have set JAVA_HOME environment. Right click on "My Computer", select "Properties". Click on the "Advance" tab and then click on the "Environment Variables" at the bottom of the window.



6. Add JAVA_HOME to User Variables. Click "Add" and enter the name as JAVA_HOME and value set to the full path to your Java JDK directory, e.g., C:\Program Files\Java\jdk1.6.0_13.


7. Continue with the Groovy installation wizard -- click next and use the defaults settings for native launcher and use all the Additional Modules.

8. Once finished, you should be able to see a new Groovy menu in Program list.


9. Lets give it a try. Select "Start GroovyConsole" to run GroovyConsole. If all goes well, you should be able to see the GroovyConsole up.

10. There are 2 useful keyboard shortcuts to know for GroovyConsole:

  • Cntrl+Enter = Run the groovy code
  • Ctrl+w = Clear console output

09 January 2009

Posted by Unknown

at 5:59 PM

0 comments

Labels: , , ,

Consume RSS Feeds easily with Groovy and Rome

This is what I did to start consuming RSS feeds with Groovy within 20 minutes!

1. Download Rome.
2. Download Rome Fetcher.
3. Download JDOM is you haven't done so.
4. Extract rome-x.jar, rom-fetcher-x.jar and jdom.jar to a tmp directory -- I placed them in lib/.
5. Start your Groovy console with the classpath set to the jar files, like this:
$ groovyConsole -cp lib/rome-1.0RC1.jar:lib/rome-fetcher-0.9.jar:lib/jdom.jar
6. Use the code below:


import com.sun.syndication.fetcher.*
import com.sun.syndication.fetcher.impl.*
import com.sun.syndication.feed.synd.SyndFeed


FeedFetcherCache feedInfoCache = HashMapFeedInfoCache.getInstance();
FeedFetcher feedFetcher = new HttpURLFeedFetcher(feedInfoCache);
SyndFeed feed = feedFetcher.retrieveFeed(new URL("http://feeds.digg.com/digg/topic/programming/popular.rss"));


feed.entries.each {
println " -> ${it} "
}

println " == ${feed.entries?.size()}"


7. Finally, start reading the below docs: