DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
11 Monitoring and Observability Tools for 2023
Learn more
  1. DZone
  2. Coding
  3. Languages
  4. A Groovy AST Example: @ToXml and @ToJson implementations

A Groovy AST Example: @ToXml and @ToJson implementations

Felipe Gutierrez user avatar by
Felipe Gutierrez
·
Jun. 01, 11 · Interview
Like (0)
Save
Tweet
Share
9.36K Views

Join the DZone community and get the full member experience.

Join For Free

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}

          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

Groovy (programming language) Implementation

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Is DevOps Dead?
  • Testing Repository Adapters With Hexagonal Architecture
  • Create Spider Chart With ReactJS
  • Multi-Cloud Integration

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: