Friday, May 4, 2012

Grails : Rest Service with JAXB parsing - PART 1

In this blog I will show how RESTful Web Service can be developed in Grails without the use of any plugins. I will just make use of Grails Controller and JAXB parser to marshal/unmarshal xml.I have divided this into 2 parts blog series. In this blog I will cover very basic usage. In next blog it will be little more advanced with Exception handling.

So let's develop a REST service to create Employee Details. Suppose we have a xml in following format which represents Employee Details.

<?xml version="1.0" encoding="utf-8"?>
<Employee_Details>
    <employee_name>Gagan</employee_name>
    <employee_age>28</employee_age>
    <employee_department>SOFTWARE</employee_department>
</Employee_Details




Suppose we created a Grails Project with name "RestExample". We then create following domain class which represents Employee details.

class Employee {

    String name
    int age
    String department

}

I have intentionally kept Employee properties different than xml elements so that we can see how they can be mapped via JAXB bindings.

So let's now bind xml elements to Employee domain class properties with @XmlRootElement and @XmlElement annotations.

import javax.xml.bind.annotation.XmlRootElement
import javax.xml.bind.annotation.XmlElement

@XmlRootElement(name="Employee_Details")
@XmlAccessorType(XmlAccessType.FIELD)

class Employee {

    @XmlElement(name="employee_name")
    String name
    @XmlElement(name="employee_age")
    int age
    @XmlElement(name="employee_department")
    String department

}

Let's now create Grails Controller which will be exposed as REST Web Service.

import javax.xml.bind.JAXBContext
import javax.xml.bind.Unmarshaller

class EmployeeController {

    def create = {
        def xmlStream = request.inputStream
        
        JAXBContext context = JAXBContext.newInstance(Employee.class)
        Unmarshaller unmarshaller = context.createUnmarshaller()
        Employee employee = unmarshaller.unmarshal(xmlStream)
        employee.save()
        
        render "success"
    }

}

Here we get the xml from input stream. Then we pass this stream to JAXB api and get Employee object back. No need to do manual XML transformations.

That's it. We can now hit the service at URL http://localhost:8080/restExample/employee/create and send Employee Details XML in request. In response we will get "success" message and Employee details will be saved in database.

Part-2 of this series covers more advance usage. Click here to read Part-2 of the blog.

1 comment:

  1. I want to do CRUD operations for XMl file and provide view(GSP) to each of them. Any idea how to do that?

    ReplyDelete