After several months of hard work, I'm proud to present my first book about Spring Framework
You can get it at Apress site or Amazon:
Introducing Spring Framework
So if you want to learn more about Spring 4, Spring Boot and Spring XD
here you go:
Tuesday, July 1, 2014
Tuesday, December 24, 2013
Spring 4 with Groovy
Finally the wait is over, Spring 4 is here and one of the best features is that now has a fully support for Groovy. The Spring team did a fantastic job bringing the same concept from Grails into the Spring Framework.
In the past if you needed to incorporate Spring in your Groovy Applications or Scripts , normally you did something like this:
One of the benefits that I see is that Groovy removes all the unnecessary boiler plate the Java.
Then, is you wanted to add more flavor to your Groovy Apps using the Grail's BeanBuilder , you needed to do something like this:
And now with the new Spring 4 you can add all the Groovy flavor to your apps (without all the Grails Dependencies) and using the new GroovyBeanDefinitionReader from Spring 4:
And that's not all, also SpringBoot gives you even more power using Groovy:
To run the above code, install springboot and then just execute:
and then go to your browser and open http://localhost:8080 and you see:
Welcome!! John
Congratulations to the Spring Team!!
Keep grooving!!
References:
[1] https://spring.io/blog/2013/12/12/announcing-spring-framework-4-0-ga-release
[2] http://groovy.codehaus.org/Using+Spring+Factories+with+Groovy
[3] http://grails.org/doc/latest/guide/spring.html
[4] http://projects.spring.io/spring-boot/
[5] https://spring.io/guides
In the past if you needed to incorporate Spring in your Groovy Applications or Scripts , normally you did something like this:
@Grab('org.springframework:spring-context:4.0.0.RELEASE')
import org.springframework.context.support.GenericApplicationContext
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
@Component
class Login {
def authorize(User user){
if(user.credentials.username == "guest" && user.credentials.password == "guest"){
"${user.greetings} ${user.credentials.username}"
}else
"You are not ${user.greetings}"
}
}
@Component
class Credentials {
String username = "guest"
String password = "guest"
}
@Component
class User{
@Autowired
Credentials credentials
String greetings = "Welcome"
}
def ctx = new GenericApplicationContext()
new ClassPathBeanDefinitionScanner(ctx).scan('') // scan root package for components
ctx.refresh()
def login = ctx.getBean("login")
def user = ctx.getBean("user")
println login.authorize(user)
One of the benefits that I see is that Groovy removes all the unnecessary boiler plate the Java.
Then, is you wanted to add more flavor to your Groovy Apps using the Grail's BeanBuilder , you needed to do something like this:
@Grab(group='org.slf4j', module='slf4j-simple', version='1.7.5')
@Grab(group='org.grails', module='grails-web', version='2.3.4')
import grails.spring.BeanBuilder
import groovy.transform.ToString
class Login {
def authorize(User user){
if(user.credentials.username == "John" && user.credentials.password == "Doe"){
"${user.greetings} ${user.credentials.username}"
}else
"You are not ${user.greetings}"
}
}
@ToString(includeNames=true)
class Credentials{
String username
String password
}
@ToString(includeNames=true)
class User{
Credentials credentials
String greetings
}
def bb = new BeanBuilder()
bb.beans {
login(Login)
user(User){
credentials = new Credentials(username:"John", password:"Doe")
greetings = 'Welcome!!'
}
}
def ctx = bb.createApplicationContext()
def u = ctx.getBean("user")
println u
def l = ctx.getBean("login")
println l.authorize(u)
And now with the new Spring 4 you can add all the Groovy flavor to your apps (without all the Grails Dependencies) and using the new GroovyBeanDefinitionReader from Spring 4:
@Grab('org.springframework:spring-context:4.0.0.RELEASE')
import org.springframework.context.support.GenericApplicationContext
import org.springframework.beans.factory.groovy.GroovyBeanDefinitionReader
import groovy.transform.ToString
class Login {
def authorize(User user){
if(user.credentials.username == "John" && user.credentials.password == "Doe"){
"${user.greetings} ${user.credentials.username}"
}else
"You are not ${user.greetings}"
}
}
@ToString(includeNames=true)
class Credentials{
String username
String password
}
@ToString(includeNames=true)
class User{
Credentials credentials
String greetings
}
def ctx = new GenericApplicationContext()
def reader = new GroovyBeanDefinitionReader(ctx)
reader.beans {
login(Login)
user(User){
credentials = new Credentials(username:"John", password:"Doe")
greetings = 'Welcome!!'
}
}
ctx.refresh()
def u = ctx.getBean("user")
println u
def l = ctx.getBean("login")
println l.authorize(u)
And that's not all, also SpringBoot gives you even more power using Groovy:
//File:app.groovy
import org.springframework.boot.*
import org.springframework.boot.autoconfigure.*
import org.springframework.stereotype.*
import org.springframework.web.bind.annotation.*
import org.springframework.beans.factory.annotation.*
@Component
class Login {
def authorize(User user){
if(user.credentials.username == "John" && user.credentials.password == "Doe"){
"${user.greetings} ${user.credentials.username}"
}else
"You are not ${user.greetings}"
}
}
@Component
class Credentials{
String username
String password
}
@Component
class User{
Credentials credentials = new Credentials(username:"John", password:"Doe")
String greetings = "Welcome!!"
}
@Controller
@EnableAutoConfiguration
class SampleController {
@Autowired
def login
@Autowired
def user
@RequestMapping("/")
@ResponseBody
String home() {
return login.authorize(user)
}
}
To run the above code, install springboot and then just execute:
$ spring run app.groovy
and then go to your browser and open http://localhost:8080 and you see:
Welcome!! John
Congratulations to the Spring Team!!
Keep grooving!!
References:
[1] https://spring.io/blog/2013/12/12/announcing-spring-framework-4-0-ga-release
[2] http://groovy.codehaus.org/Using+Spring+Factories+with+Groovy
[3] http://grails.org/doc/latest/guide/spring.html
[4] http://projects.spring.io/spring-boot/
[5] https://spring.io/guides
Saturday, November 3, 2012
DMongo - Dynamic wrapper for the CSharp Mongo Driver
This is an wrapper of the CSharpDriver for Mongo, using the Microsoft Dynamic syntax.
The idea behind this implementation is to create a DSL simple to use, more oriented to the Mongo Shell commands.
Using the CSharpDriver for Mongo. This example was taken from: CSharp Driver Quickstart
Using DMongo: A simple way to use the collections (like the mongo shell)
Features:
- Dynamic Collections
- Data Types.
- DB Actions - Update, Insert, Delete
- DB Query - all Finders and Linq
- Same fuctionality from CSharp Driver
- Multithread
- Reduced Maps
- More and more...
Check it out: DMongo Project
Sunday, September 11, 2011
Asynchronous Method calls with Groovy: @Async AST
At work, I needed to create a very simple background job, without any concern about what I could get back, because mostly all the hard work was just batch processing and persistence, and all exceptions or roll-back concerns were already taking care of.
At the beginning I used a very simple way to call my background job, using: Executors.newSingleThreadExecutor()
void myBackgroundJob() {
Executors.newSingleThreadExecutor().submit(new Runnable() {
public void run() {
//My Background Job
}
});
}
And it worked great, just what I needed.
Using Groovy facilitate even more the way to create a new Background job, as simple as:
def myBackgroundJob() {
Thread.start {
//My Background Job
}
}
Then, after this simple way to send something into the background, I decided to create a new AST in groovy, that remove the need to remember or copy and paste the same logic.
I created two annotations that help to identify the class and the methods that are going to be put into a new Thread.
One for the Class:
package async
import org.codehaus.groovy.transform.GroovyASTTransformationClass
import java.lang.annotation.*
import xml.ToXmlTransformation
@Retention (RetentionPolicy.SOURCE)
@Target ([ElementType.TYPE])
@GroovyASTTransformationClass (["async.AsyncTransformation"])
public @interface Asynchronous { }
And the other for the Method:
package async
import org.codehaus.groovy.transform.GroovyASTTransformationClass
import java.lang.annotation.*
import async.AsyncTransformation
@Retention (RetentionPolicy.SOURCE)
@Target ([ElementType.METHOD])
@GroovyASTTransformationClass (["async.AsyncTransformation"])
public @interface Async { }
then the Asynchronous Transformation, using the AstBuilder().buildFromString(). Here I combined a GroovyInterceptable to connect the method being call with the AST transformation to wrapped it with the Thread logic.
package async
import org.codehaus.groovy.control.CompilePhase
import org.codehaus.groovy.transform.*
import org.codehaus.groovy.ast.*
import org.codehaus.groovy.control.SourceUnit
import org.codehaus.groovy.ast.builder.AstBuilder
import org.codehaus.groovy.ast.stmt.ExpressionStatement
import org.codehaus.groovy.ast.expr.MethodCallExpression
import org.codehaus.groovy.ast.expr.ClosureExpression
import org.codehaus.groovy.ast.expr.ConstantExpression
import org.codehaus.groovy.ast.stmt.BlockStatement
import org.codehaus.groovy.ast.expr.ClassExpression
import org.codehaus.groovy.ast.expr.ArgumentListExpression
@GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS)
class AsyncTransformation implements ASTTransformation{
void visit(ASTNode[] astNodes, SourceUnit sourceUnit) {
if (!astNodes ) return
if (!astNodes[0] || !astNodes[1]) return
if (!(astNodes[0] instanceof AnnotationNode)) return
if (astNodes[0].classNode?.name != Asynchronous.class.name) return
def methods = makeMethods(astNodes[1])
if(methods){
astNodes[1]?.interfaces = [ ClassHelper.make(GroovyInterceptable, false), ] as ClassNode []
astNodes[1]?.addMethod(methods?.find { it.name == 'invokeMethod' })
}
}
def makeMethods(ClassNode source){
def methods = source.methods
def annotatedMethods = methods.findAll { it?.annotations?.findAll { it?.classNode?.name == Async.class.name } }
if(annotatedMethods){
def expression = annotatedMethods.collect { "name == \"${it.name}\"" }.join(" || ")
def ast = new AstBuilder().buildFromString(CompilePhase.INSTRUCTION_SELECTION, false, """
package ${source.packageName}
class ${source.nameWithoutPackage} implements GroovyInterceptable {
def invokeMethod(String name, Object args){
if(${expression}){
Thread.start{
def calledMethod = ${source.nameWithoutPackage}.metaClass.getMetaMethod(name, args)
calledMethod?.invoke(this, args)
}
}else{
def calledMethod = ${source.nameWithoutPackage}.metaClass.getMetaMethod(name, args)?.invoke(this,args)
}
}
}
""")
ast[1].methods
}
}
}
The example:
package async
@Asynchronous
class Sample{
String name
String phone
@Async
def expensiveMethod(){
println "[${Thread.currentThread()}] Started expensiveMethod"
sleep 15000
println "[${Thread.currentThread()}] Finished expensiveMethod..."
}
@Async
def otherMethod(){
println "[${Thread.currentThread()}] Started otherMethod"
sleep 5000
println "[${Thread.currentThread()}] Finished otherMethod"
}
}
println "[${Thread.currentThread()}] Start"
def sample = new Sample(name:"AST Sample",phone:"1800-GROOVY")
sample.expensiveMethod()
sample.otherMethod()
println "[${Thread.currentThread()}] Finished"
Final Notes:
As you can see on the example I need to have the Asynchronous annotation on the class still. It could be better without it and just annotate the methods, something like the Groovy's SynchronizedASTTransformation. If you have any idea to complement this small example, please clone the source code [here], and let me know what you think.
I could used the @javax.ejb.Asynchronous or the Spring's @org.springframework.scheduling.annotation.Async, but I only needed a very simple solution without any other configuration or library inclusion.
The remain logic here could be play more with multi threading and expect some results like: java.util.concurrent.Future and its java.util.concurrent.Future.get() method or maybe integrated with another frameworks like Spring.
Source Code: [here]
At the beginning I used a very simple way to call my background job, using: Executors.newSingleThreadExecutor()
void myBackgroundJob() {
Executors.newSingleThreadExecutor().submit(new Runnable() {
public void run() {
//My Background Job
}
});
}
And it worked great, just what I needed.
Using Groovy facilitate even more the way to create a new Background job, as simple as:
def myBackgroundJob() {
Thread.start {
//My Background Job
}
}
Then, after this simple way to send something into the background, I decided to create a new AST in groovy, that remove the need to remember or copy and paste the same logic.
I created two annotations that help to identify the class and the methods that are going to be put into a new Thread.
One for the Class:
package async
import org.codehaus.groovy.transform.GroovyASTTransformationClass
import java.lang.annotation.*
import xml.ToXmlTransformation
@Retention (RetentionPolicy.SOURCE)
@Target ([ElementType.TYPE])
@GroovyASTTransformationClass (["async.AsyncTransformation"])
public @interface Asynchronous { }
And the other for the Method:
package async
import org.codehaus.groovy.transform.GroovyASTTransformationClass
import java.lang.annotation.*
import async.AsyncTransformation
@Retention (RetentionPolicy.SOURCE)
@Target ([ElementType.METHOD])
@GroovyASTTransformationClass (["async.AsyncTransformation"])
public @interface Async { }
then the Asynchronous Transformation, using the AstBuilder().buildFromString(). Here I combined a GroovyInterceptable to connect the method being call with the AST transformation to wrapped it with the Thread logic.
package async
import org.codehaus.groovy.control.CompilePhase
import org.codehaus.groovy.transform.*
import org.codehaus.groovy.ast.*
import org.codehaus.groovy.control.SourceUnit
import org.codehaus.groovy.ast.builder.AstBuilder
import org.codehaus.groovy.ast.stmt.ExpressionStatement
import org.codehaus.groovy.ast.expr.MethodCallExpression
import org.codehaus.groovy.ast.expr.ClosureExpression
import org.codehaus.groovy.ast.expr.ConstantExpression
import org.codehaus.groovy.ast.stmt.BlockStatement
import org.codehaus.groovy.ast.expr.ClassExpression
import org.codehaus.groovy.ast.expr.ArgumentListExpression
@GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS)
class AsyncTransformation implements ASTTransformation{
void visit(ASTNode[] astNodes, SourceUnit sourceUnit) {
if (!astNodes ) return
if (!astNodes[0] || !astNodes[1]) return
if (!(astNodes[0] instanceof AnnotationNode)) return
if (astNodes[0].classNode?.name != Asynchronous.class.name) return
def methods = makeMethods(astNodes[1])
if(methods){
astNodes[1]?.interfaces = [ ClassHelper.make(GroovyInterceptable, false), ] as ClassNode []
astNodes[1]?.addMethod(methods?.find { it.name == 'invokeMethod' })
}
}
def makeMethods(ClassNode source){
def methods = source.methods
def annotatedMethods = methods.findAll { it?.annotations?.findAll { it?.classNode?.name == Async.class.name } }
if(annotatedMethods){
def expression = annotatedMethods.collect { "name == \"${it.name}\"" }.join(" || ")
def ast = new AstBuilder().buildFromString(CompilePhase.INSTRUCTION_SELECTION, false, """
package ${source.packageName}
class ${source.nameWithoutPackage} implements GroovyInterceptable {
def invokeMethod(String name, Object args){
if(${expression}){
Thread.start{
def calledMethod = ${source.nameWithoutPackage}.metaClass.getMetaMethod(name, args)
calledMethod?.invoke(this, args)
}
}else{
def calledMethod = ${source.nameWithoutPackage}.metaClass.getMetaMethod(name, args)?.invoke(this,args)
}
}
}
""")
ast[1].methods
}
}
}
The example:
package async
@Asynchronous
class Sample{
String name
String phone
@Async
def expensiveMethod(){
println "[${Thread.currentThread()}] Started expensiveMethod"
sleep 15000
println "[${Thread.currentThread()}] Finished expensiveMethod..."
}
@Async
def otherMethod(){
println "[${Thread.currentThread()}] Started otherMethod"
sleep 5000
println "[${Thread.currentThread()}] Finished otherMethod"
}
}
println "[${Thread.currentThread()}] Start"
def sample = new Sample(name:"AST Sample",phone:"1800-GROOVY")
sample.expensiveMethod()
sample.otherMethod()
println "[${Thread.currentThread()}] Finished"
Final Notes:
As you can see on the example I need to have the Asynchronous annotation on the class still. It could be better without it and just annotate the methods, something like the Groovy's SynchronizedASTTransformation. If you have any idea to complement this small example, please clone the source code [here], and let me know what you think.
I could used the @javax.ejb.Asynchronous or the Spring's @org.springframework.scheduling.annotation.Async, but I only needed a very simple solution without any other configuration or library inclusion.
The remain logic here could be play more with multi threading and expect some results like: java.util.concurrent.Future
Source Code: [here]
Wednesday, June 1, 2011
A Groovy AST Example: @ToXml and @ToJson implementations
The groovy team have done an amazing job providing a way to use and extend the AST (Abstract Syntax Tree), and with the new release of the Groovy 1.8, they expose more functionality like this new code generation transformation:
@groovy.transform.ToString
that gives a class a standard toString() method, by default prints out the name of the class and all the fields values.
Example:
@groovy.transform.ToString
class Person {
String name,phone
}
def person = new Person(name:"Felipe",phone:"502123456")
assert person.toString() == 'Person(Felipe, 502123456)'
After playing around with all these new code transformations, I decided to experiment more creating two different local transformations that I needed. Normally I like to expose my domain classes as an XML or JSON string formats, and convert them back into objects, and I accomplished this using the XStream library, and the good thing is that Groovy comes with this library.
So, taking the same idea from the @ToString annotation, I created a very basic AST that will give me what I wanted to do.
Creating the @ToXml and @ToJson
This annotation will use the toString() to expose the Xml, and it will create a static function that will help to get the object from a Xml string.
1) Creating the annotation: We need to use a Source retention policy, because this is only visible at the source level, and this annotation is being used by the compiler. The target must be the class, so the ElementType.TYPE will be our target. The most important part here is to use the GroovyASTTransformationClass, passing as parameter the implementation class.
package xml
import org.codehaus.groovy.transform.GroovyASTTransformationClass
import java.lang.annotation.*
import xml.ToXmlTransformation
@Retention (RetentionPolicy.SOURCE)
@Target ([ElementType.TYPE])
@GroovyASTTransformationClass (["xml.ToXmlTransformation"])
public @interface ToXml { }
2) Create the Transformation: We need to implement the ASTTranformation and do the visit method. Here, we need to take care of the ASTNode[] parameter, where the element 0 contains the annotation, and the element 1 the ASTNode that was annotated, in this case the class. We add a method helper to create the toString() and the createInstanceFrom methods using the AstBuilder class and its buildFromString method.
package xml
import org.codehaus.groovy.control.CompilePhase
import org.codehaus.groovy.transform.*
import org.codehaus.groovy.ast.*
import org.codehaus.groovy.control.SourceUnit
import org.codehaus.groovy.ast.builder.AstBuilder
@GroovyASTTransformation(phase = CompilePhase.INSTRUCTION_SELECTION)
class ToXmlTransformation implements ASTTransformation {
void visit(ASTNode[] astNodes, SourceUnit sourceUnit) {
if (!astNodes ) return
if (!astNodes[0] || !astNodes[1]) return
if (!(astNodes[0] instanceof AnnotationNode)) return
if (astNodes[0].classNode?.name != ToXml.class.name) return
def toXmlMethods = makeToXmlMethod(astNodes[1])
astNodes[1].
addMethod(toXmlMethods.find { it.name == 'toString' })
astNodes[1].
addMethod(toXmlMethods.find { it.name == 'createInstanceFrom' })
}
def makeToXmlMethod(ClassNode source) {
def phase = CompilePhase.INSTRUCTION_SELECTION
def ast = new AstBuilder().buildFromString(phase, false, """
package ${source.packageName}
ast[1].methods
}
}
3) Create the Test/Example
package xml
@ToXml
class Person {
String name, phone
}
def person1 = new Person(name:"Felipe",phone:"502123456")
println person1
String xml = person1.toString()
def person2 = Person.createInstanceFrom(xml)
println person2
assert person1.toString() == person2.toString()
Pretty cool!! Now what about to create the @ToJson annotation??
Well, I include it on the Files, and it's pretty much the same, the only difference is that we need to add the jettison.jar library to our class path or into the groovy/lib folder.
Final Notes:
This is a very simple example, and is missing validations and errors checking like what would happen if the toString is already implemented, or if is extended, what would happen with the parent's toString()?? In such cases we should used the SourceUnit with the addError and addException methods.
These files contain the source and an extra example using the XStream annotations. Check it out. GitHub: GroovyAST-Examples
@groovy.transform.ToString
that gives a class a standard toString() method, by default prints out the name of the class and all the fields values.
Example:
@groovy.transform.ToString
class Person {
String name,phone
}
def person = new Person(name:"Felipe",phone:"502123456")
assert person.toString() == 'Person(Felipe, 502123456)'
After playing around with all these new code transformations, I decided to experiment more creating two different local transformations that I needed. Normally I like to expose my domain classes as an XML or JSON string formats, and convert them back into objects, and I accomplished this using the XStream library, and the good thing is that Groovy comes with this library.
So, taking the same idea from the @ToString annotation, I created a very basic AST that will give me what I wanted to do.
Creating the @ToXml and @ToJson
This annotation will use the toString() to expose the Xml, and it will create a static function that will help to get the object from a Xml string.
1) Creating the annotation: We need to use a Source retention policy, because this is only visible at the source level, and this annotation is being used by the compiler. The target must be the class, so the ElementType.TYPE will be our target. The most important part here is to use the GroovyASTTransformationClass, passing as parameter the implementation class.
package xml
import org.codehaus.groovy.transform.GroovyASTTransformationClass
import java.lang.annotation.*
import xml.ToXmlTransformation
@Retention (RetentionPolicy.SOURCE)
@Target ([ElementType.TYPE])
@GroovyASTTransformationClass (["xml.ToXmlTransformation"])
public @interface ToXml { }
2) Create the Transformation: We need to implement the ASTTranformation and do the visit method. Here, we need to take care of the ASTNode[] parameter, where the element 0 contains the annotation, and the element 1 the ASTNode that was annotated, in this case the class. We add a method helper to create the toString() and the createInstanceFrom methods using the AstBuilder class and its buildFromString method.
package xml
import org.codehaus.groovy.control.CompilePhase
import org.codehaus.groovy.transform.*
import org.codehaus.groovy.ast.*
import org.codehaus.groovy.control.SourceUnit
import org.codehaus.groovy.ast.builder.AstBuilder
@GroovyASTTransformation(phase = CompilePhase.INSTRUCTION_SELECTION)
class ToXmlTransformation implements ASTTransformation {
void visit(ASTNode[] astNodes, SourceUnit sourceUnit) {
if (!astNodes ) return
if (!astNodes[0] || !astNodes[1]) return
if (!(astNodes[0] instanceof AnnotationNode)) return
if (astNodes[0].classNode?.name != ToXml.class.name) return
def toXmlMethods = makeToXmlMethod(astNodes[1])
astNodes[1].
addMethod(toXmlMethods.find { it.name == 'toString' })
astNodes[1].
addMethod(toXmlMethods.find { it.name == 'createInstanceFrom' })
}
def makeToXmlMethod(ClassNode source) {
def phase = CompilePhase.INSTRUCTION_SELECTION
def ast = new AstBuilder().buildFromString(phase, false, """
package ${source.packageName}
import com.thoughtworks.xstream.XStream
import com.thoughtworks.xstream.annotations.XStreamAlias
import com.thoughtworks.xstream.annotations.XStreamAsAttribute
import com.thoughtworks.xstream.annotations.XStreamImplicit
import com.thoughtworks.xstream.io.xml.DomDriver
class ${source.nameWithoutPackage} {
String toString(){
XStream xstream = new XStream()
xstream.alias("${source.nameWithoutPackage.toLowerCase()}",
${source.nameWithoutPackage}.class)
xstream.
processAnnotations([${source.nameWithoutPackage}.class]
as Class[])
xstream.autodetectAnnotations(true)
xstream.toXML(this)
}
static def createInstanceFrom(xml){
XStream xstream = new XStream(new DomDriver())
xstream.alias("${source.nameWithoutPackage.toLowerCase()}",
${source.nameWithoutPackage}.class)
xstream.
processAnnotations([${source.nameWithoutPackage}.class]
as Class[])
xstream.autodetectAnnotations(true)
xstream.fromXML(xml)
}
}
""")ast[1].methods
}
}
3) Create the Test/Example
package xml
@ToXml
class Person {
String name, phone
}
def person1 = new Person(name:"Felipe",phone:"502123456")
println person1
String xml = person1.toString()
def person2 = Person.createInstanceFrom(xml)
println person2
assert person1.toString() == person2.toString()
Pretty cool!! Now what about to create the @ToJson annotation??
Well, I include it on the Files, and it's pretty much the same, the only difference is that we need to add the jettison.jar library to our class path or into the groovy/lib folder.
Final Notes:
This is a very simple example, and is missing validations and errors checking like what would happen if the toString is already implemented, or if is extended, what would happen with the parent's toString()?? In such cases we should used the SourceUnit with the addError and addException methods.
These files contain the source and an extra example using the XStream annotations. Check it out. GitHub: GroovyAST-Examples
Monday, February 15, 2010
JBoss Message Clustering by Example
It's amazing how the JBoss Team put together an easy way to do JMS Clustering. I'll start with an easy example, creating a Queue named "MyClusteredQueue". In this example I'm using JBoss AS 5.1. and two computers connected on the same network, with these IP's:
- Computer A: 192.168.0.143
- Computer B: 192.168.0.210
So, here are the steps:
1) Install the JBoss on both computers. We are going to use the "all" configuration for both computers.
2) We create our Queue on both servers.
Go to $JBOSS_HOME/server/all/deploy/messaging/ and edit the destinations-service.xml file. Add the MyClusteredQueue before the last server tag. It looks like this:
This is how you add a Queue to the JBoss, and the people how are familiar with this, the only new thing is to add the attribute "Clustered". This step must be on both computers. At the end of the article you can find the files.
3) Crate the MDB that will consume the messages, and deploy it into the two servers.
(The code is on the Resources, see at the end of the page).
4) Start the jboss with the following options:
Computer A:
$ cd $JBOSS_HOME/bin
$ ./run.sh -c all -b 192.168.0.143 -Djboss.messaging.ServerPeerID=1
Computer B:
$ cd $JBOSS_HOME/bin
$ ./run.sh -c all -b 192.168.0.210 -Djboss.messaging.ServerPeerID=2
It is necesary to give an ID to each server and this is accomplished with this directive:
-Djboss.messaging.ServerPeerID
when you start the jboss on computer A, you should see these on the logs:
- Computer A: 192.168.0.143
- Computer B: 192.168.0.210
So, here are the steps:
1) Install the JBoss on both computers. We are going to use the "all" configuration for both computers.
2) We create our Queue on both servers.
Go to $JBOSS_HOME/server/all/deploy/messaging/ and edit the destinations-service.xml file. Add the MyClusteredQueue before the last server tag. It looks like this:
This is how you add a Queue to the JBoss, and the people how are familiar with this, the only new thing is to add the attribute "Clustered". This step must be on both computers. At the end of the article you can find the files.
3) Crate the MDB that will consume the messages, and deploy it into the two servers.
(The code is on the Resources, see at the end of the page).
4) Start the jboss with the following options:
Computer A:
$ cd $JBOSS_HOME/bin
$ ./run.sh -c all -b 192.168.0.143 -Djboss.messaging.ServerPeerID=1
Computer B:
$ cd $JBOSS_HOME/bin
$ ./run.sh -c all -b 192.168.0.210 -Djboss.messaging.ServerPeerID=2
It is necesary to give an ID to each server and this is accomplished with this directive:
-Djboss.messaging.ServerPeerID
when you start the jboss on computer A, you should see these on the logs:
and once you start the jboss on computer B, you should see the following logs:
And the computer A, will be shown the new change with these logs:
5) Now it's time to send a Message to the Queue. To accomplish this it's necessary to change the connection factory to "ClusteredConnectionFactory". Also on the jndi.properties file it's necessary to add the two computers ip's separated by comma to the java.naming.provider.url property.
java.naming.provider.url=192.168.0.143:1099,192.168.0.210:1099
The client that I wrote (you can find it on the Resources) is a web application. You need to deploy it in any computer, in my case I deployed it on the computer A. And you can access it through this URL: http://192.168.0.143:8080/JMSWeb/ (just modify the IP where the JMSWeb.war was deployed).
You will see this:
In order to use it, just put any message and (if you want) you can increase the times that the message will be sent. If you put 10 times, and the message "Hello JMS Clustering", you will see that the message is clustered and the two servers process the Queue.
Resources: JMS-Clustering-Files
Saturday, February 6, 2010
Flex - BlazeDS with Grails, sending messages from Grails to Flex - BlazeDS
I started several weeks ago to see what we can do with Grails and its Enterprise side, and because where I'm working right now it's needed to do some messaging from the back-end to the clients (Flex clients), and well, I did some modifications to the flex/grails plug-in (developed by Marcel Overdijk) in order to be able to send messages from grails to Flex (consumer).
Assuming that we already have our domain, controllers and maybe some views, the only thing we need to do is install the flex plug-in, do some small modifications to the source (flex plug-in), create a helper class (to send the message), create a service (this will defined our destination), add the messaging service tag to the flex configuration (services-config.xml) and test it on your Flex application. For these steps I'm using Grails IDE on Eclipse.
So here are the steps:
1) Install the Flex plug-in:
(Using the Grails IDE on eclipse, you can bring up the grails command prompt with Ctrl+Alt+G for Windows or Cmd+Alt+G for Mac)
This will install the flex plug-in and it will give the following structure
2) Modify the Flex plug-in source code:
The files to modify will be GrailsBootstrapService.java and FlexUtils.java
GrailsBootstrapService.java, the bootstrap service will help to create dynamically the destination(s).
(This is the final version).
I added the lines 45 to 47.
FlexUtils.java
Here, I added several lines, and I know there is a better way to implement this (maybe put a Factory Pattern) to create the correct service.
a) Two new constants:
b) And these methods:
3) Create a Helper Class:
This class will send any message to any destination (provided by the service created).
Just create a new Groovy class into the src/groovy folder.
In this class, this method can be overloaded so we can pass more information, like Headers, IDs, etc. Take a look into the AsyncMessage.java (from BlazeDS API) for more information.
4) Create the Service:
Create the service using the grails command. And put the property identifier (static expose = ['flex-messaging'])
Final UpdateMessageService.groovy
The Bootstrap will create the updateMessageService destination
5) Add the Messaging service tag to the Flex configuration:
Its necessary to add new tags to the services-config.xml located on the web-app/WEB-INF/flex
This tag will be added to the existing services tag
And this is the complete file: services-config.xml
6) Test it in Flex
To Test the Flex client we need first to create a consumer tag and from any controller (from Grails) use the helper class to send a message to the updateMessageService destination.
On Grails (in any controller or any other source where the message is necessary), just use the Helper class to send the message:
Resources: Files
Notes:
1st Draft version: 0.1
Assuming that we already have our domain, controllers and maybe some views, the only thing we need to do is install the flex plug-in, do some small modifications to the source (flex plug-in), create a helper class (to send the message), create a service (this will defined our destination), add the messaging service tag to the flex configuration (services-config.xml) and test it on your Flex application. For these steps I'm using Grails IDE on Eclipse.
So here are the steps:
1) Install the Flex plug-in:
(Using the Grails IDE on eclipse, you can bring up the grails command prompt with Ctrl+Alt+G for Windows or Cmd+Alt+G for Mac)
This will install the flex plug-in and it will give the following structure
2) Modify the Flex plug-in source code:
The files to modify will be GrailsBootstrapService.java and FlexUtils.java
GrailsBootstrapService.java, the bootstrap service will help to create dynamically the destination(s).
(This is the final version).
I added the lines 45 to 47.
FlexUtils.java
Here, I added several lines, and I know there is a better way to implement this (maybe put a Factory Pattern) to create the correct service.
a) Two new constants:
b) And these methods:
3) Create a Helper Class:
This class will send any message to any destination (provided by the service created).
Just create a new Groovy class into the src/groovy folder.
In this class, this method can be overloaded so we can pass more information, like Headers, IDs, etc. Take a look into the AsyncMessage.java (from BlazeDS API) for more information.
4) Create the Service:
Create the service using the grails command. And put the property identifier (static expose = ['flex-messaging'])
Final UpdateMessageService.groovy
The Bootstrap will create the updateMessageService destination
5) Add the Messaging service tag to the Flex configuration:
Its necessary to add new tags to the services-config.xml located on the web-app/WEB-INF/flex
This tag will be added to the existing services tag
And this is the complete file: services-config.xml
6) Test it in Flex
To Test the Flex client we need first to create a consumer tag and from any controller (from Grails) use the helper class to send a message to the updateMessageService destination.
On Grails (in any controller or any other source where the message is necessary), just use the Helper class to send the message:
Resources: Files
Notes:
1st Draft version: 0.1
Labels:
java grails flex messaging
Subscribe to:
Posts (Atom)


















