Grails Web Services

In this blog we’ll expose a Grails service as a SOAP service. According to good practice we’ll build the WSDL first and then write the implementation code.
First things first. Let’s create a new grails application and call it grails-soap

grails> create-app grails-soap

 

CXF

For SOAP support we’ll be using the Grails CXF plugin. Just add the following line in the plugin section of your BuildConfig.groovy file to enable the plugin. Documentation for the plugin can be found here.

compile ':cxf:1.1.1'

 

WSDL

We’ll start with building the WSDL for the service. The service will be called DepartmentService and will return some Department data for a given id. We’ll place the WSDL in the src/java folder.

<?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions name="DepartmentService"
	targetNamespace="http://devjournal/DepartmentService" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
	xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12s/"
	xmlns:tns="http://devjournal/DepartmentService">
	<wsdl:types>
		<xsd:schema xmlns="http://www.w3.org/2001/XMLSchema">
			<import namespace="http://devjournal/DepartmentService"
				schemaLocation="DepartmentService.xsd" />
		</xsd:schema>
	</wsdl:types>
	<wsdl:message name="DepartmentServiceRequestMessage">
		<wsdl:part name="in" element="tns:DepartmentServiceRequest" />
	</wsdl:message>
	<wsdl:message name="DepartmentServiceResponseMessage">
		<wsdl:part name="out" element="tns:DepartmentServiceResponse" />
	</wsdl:message>
	<wsdl:portType name="GetDepartmentById">
		<wsdl:operation name="getDepartmentById">
			<wsdl:input message="tns:DepartmentServiceRequestMessage" />
			<wsdl:output message="tns:DepartmentServiceResponseMessage" />
		</wsdl:operation>
	</wsdl:portType>
	<wsdl:binding name="GetDepartmentByIdSoap12" type="tns:GetDepartmentById">
		<soap12:binding transport="http://schemas.xmlsoap.org/soap/http"
			style="document" />
		<wsdl:operation name="getDepartmentById">
			<soap12:operation
				soapAction="http://whitehorses.nl/Whitebook_SOA_UT/DepartmentService/GetDepartmentById"
				style="document" />
			<wsdl:input>
				<soap12:body use="literal" parts="in" />
			</wsdl:input>
			<wsdl:output>
				<soap12:body use="literal" parts="out" />
			</wsdl:output>
		</wsdl:operation>
	</wsdl:binding>
	<wsdl:service name="DepartmentService">
		<wsdl:port binding="tns:GetDepartmentByIdSoap12" name="GetDepartmentByIdSoap12">
			<soap12:address location="http://www.example.org/" />
		</wsdl:port>
	</wsdl:service>
</wsdl:definitions>

The underlying xml schema file contains the response element. This file will also be placed in the src/java folder.

<?xml version="1.0" encoding="UTF-8"?>
<schema attributeFormDefault="unqualified" elementFormDefault="qualified"
        targetNamespace="http://devjournal/DepartmentService"
        xmlns:tns="http://devjournal/DepartmentService"
        xmlns="http://www.w3.org/2001/XMLSchema">
 <element name="DepartmentServiceRequest">
  <complexType>
   <sequence>
    <element name="Id" type="int"/>
   </sequence>
  </complexType>
 </element>
 <element name="DepartmentServiceResponse">
  <complexType>
   <sequence>
    <element name="Department" type="tns:departmentType" maxOccurs="1"
             minOccurs="0"/>
   </sequence>
  </complexType>
 </element>
 <complexType name="departmentType">
  <sequence>
   <element name="Id" type="int"/>
   <element name="Name" type="string"/>
   <element name="Location" type="string"/>
  </sequence>
 </complexType>
</schema>

 

wsdl2java

Now that we have the WSDL it’s time to generate the Java stubs. Although the CXF plug-in comes with a wsdl-to-java command it kept giving me a “GroovyCastException” when I tried to run it. To workaround this problem, I downloaded the latest apache-cxf distribution here (2.7.11 at the time of this writing) and used its wsdl2java command to generate the stubs.

$ $CXF_HOME/apache-cxf-2.7.11/bin/wsdl2java DepartmentService.wsdl

After running this command from within the /src/java directory, the following stub classes are added to your grails application:

wsdl2java classes

wsdl2java classes

 

service

Now everything is in place, we can start implementing the service. First create a new grails service component called DepartmentService

grails> create-service department

We’ll have this service implement the generated @WebService interface GetDepartmentById and override the getDepartmentById method (corresponding with the SOAP operation of the same name) For simplicity sake, we’ll just hardcode a response:

package grails.soap

import javax.jws.WebService

import org.grails.cxf.utils.EndpointType

import devjournal.departmentservice.DepartmentServiceRequest
import devjournal.departmentservice.DepartmentServiceResponse
import devjournal.departmentservice.DepartmentType
import devjournal.departmentservice.GetDepartmentById


@WebService(targetNamespace = "http://devjournal/DepartmentService", name = "GetDepartmentById", serviceName = 'DepartmentService',
portName = 'GetDepartmentById')
class DepartmentService implements GetDepartmentById {

	static expose = EndpointType.JAX_WS_WSDL
	static soap12 = true
	static address = 'DepartmentService'
	
	def serviceMethod() {
	}

	@Override
	public DepartmentServiceResponse getDepartmentById(
			DepartmentServiceRequest departmentServiceRequest) {

		DepartmentType department = new DepartmentType(id: departmentServiceRequest.id, location:'Amsterdam', name: 'Sales')
		return new DepartmentServiceResponse(department:department)
	}
}

As you can see in the code above, we’ve implemented the GetDepartmentById interface and added the @WebService annotation to the service. With the serviceName and portName attributes we can influence the WSDL that’s eventually being served.
The cxf-plugin allows further configuration by means of static properties. Setting the soap12 property to “true” makes the DepartmentService adhere to the SOAP 1.2 specification. With the address property we can adjust the endpoint of the service. By default it would be the default address of the grails service, i.e. “/services/department”. In the above example the endpoint will be “/services/DepartmentService”. Refer to the cxf-plugin documentation for an overview of available properties.
 

Testing the web service

Now let’s fire up the application and give it a spin

grails> run-app

The WSDL should be available at http://localhost:8080/services/DepartmentService?WSDL and can be tested with SoapUI. The screenshot below shows the result.

DepartmentService Test

DepartmentService Test


 

Conclusion

In this blog I’ve shown how easy it is to expose a grails service via SOAP. Although the service had been turned into a SOAP service it’s still available as a normal grail service to the rest of the application, so there’s no violation of the DRY principle and code can be reused.

Grails in the Cloud Foundry

In this blog I’ll show you how easy it is to get a small Grails app up and running on Cloud Foundry making use of a mysql service provided by Cloud Foundry. We’ll be using the Groovy & Grails Toolsuite (ggts) for this, but I’ll also show you the grails commands you can use to accomplish each individual step.

Setup

  • At the time of this blogpost I’m using ggts version 3.1.0.RELEASE based on Eclipse Juno 4.2.1, which can be downloaded right here;
  • ggts comes with a full Grails installation. To make use of command line grails commands outside of the IDE, set the following environment variables. If you’re an Ubuntu user like me, just add these two lines to your ~/.bashrc file:
    • export GRAILS_HOME=<ggts_home>/grails-2.1.1;
    • export PATH=$PATH:$GRAILS_HOME/bin;
  • Apply for a Cloud Foundry account right here. You’ll receive an email of approval which will contain your  password;
  • Enable Cloud Foundry Integration in ggts. Click the Extensions link on the Dashboard, scroll down to Cloud Foundry Integration for Eclipse and install it.
Screenshot from 2013-02-17 15:40:52

Cloud Foundry Integration for Eclipse

Building a simple Grails app

We’re gonna develop a very simple Grails app. Just enough for demonstration purposes. It’ll be an app that enables you to create notes and store them in a database. We’ll call it one-note.

Grails Project

Choose File > New > Grails Project and supply the project-name. Alternatively you could use the command line and type:

grails create-app one-note

There’s also a command line interface available in ggts itself (Navigate > Open Grails Command Prompt). All commands are available here (just ommit the grails prefix), except for the creation of an application.

Screenshot from 2013-02-24 16:54:11

Grails Command Prompt

Domain Class

Choose File > New > Domain Class and name it Note. The Note.groovy domain class will be created for you. You can also create the class via this command line:

grails create-domain-class note

Add two simple fields to the domain class, so it looks like this:

package one.note

class Note {

    String content
    Date dateCreated

    static constraints = {
    }
}

The dateCreated is a standard field which will be supplied for by the Grails framework, the content field will contain the actual note.

Controller

Choose File > New > Controller and name it NoteController. The NoteController.groovy controller will be created for you. The equivalent command would be

grails create-controller note

Add scaffolding and reroute the index action to the list action. Your controller should now look like this

package one.note

class NoteController {

    def scaffold = true

    def index() {
        redirect(action:list)
    }
}

Testdrive the application

That’s basically all we need to run the application locally and make use of an in-memory hsqldb. Select Run > Run As > Grails Command (run-app), and point your browser to http://localhost:8080/one-note and you’re good to go. Select the NoteController in the Overview page, create some notes and your application should resemble the picture below.

Screenshot from 2013-02-24 18:05:49

one-note Grails application

Alternatively you could achieve the same via the command line:

grails run-app

Publish to Cloud Foundry

Although not entirely necessary, it’s a good practice to change your production configuration in the Datasource.groovy file. Add the following lines

environments {
    production {
        dataSource {
            dbCreate = &quot;update&quot;
            driverClassName = &quot;com.mysql.jdbc.Driver&quot;
        }
    }
}

Furthermore edit the BuildConfig.groovy and add the following dependency:

dependencies {
runtime &quot;mysql:mysql-connector-java:5.1.23&quot;
}

Cloud Foundry Integration style

Add a new server (File > New > Other > Server) and select Cloud Foundry as the type.

Screenshot from 2013-02-24 18:33:21

New Server > Define a New Server

Fill in your Cloud Foundry account information and press Validate Account to make sure you entered everything correctly.

Screenshot from 2013-02-24 18:33:35

New Server > Cloud Foundry Account

Now go to the Applications tab and Add the one-note application from Available to Configured and click Finish.

Change Runtime to Java 7, click Next >

Screenshot from 2013-02-24 18:38:11

Application > Application Details

Note the Deployed URL and click Next >

Screenshot from 2013-02-24 18:39:22

Application > Launch deployment

Click Add Service to add a mysql service, give it a name (I choose one-note) and select MySQL database as the type and click Finish.

Screenshot from 2013-02-24 18:40:33

Add Service > Service Configuration

Make sure, the new mysql service is selected and click Finish.

Screenshot from 2013-02-24 19:14:44

Application > Services selection

Now the application will get started and you’ll get a nice overview of your application running in Cloud Foundry.

Screenshot from 2013-02-24 18:49:41

Application overview

Also take note of the Remote Systems window in ggts. Here you can for one take a look at all the log files in your Cloud Foundry environment.

Screenshot from 2013-02-24 13:17:11

Remote Systems

That’s it. You can now test your application on the following url: http://one-note.cloudfoundry.com.

Screenshot from 2013-02-24 19:00:21

one-note in the cloud

Command line style

To enable Cloud Foundry commands via the command line you have to add a plugin to the application:

grails install-plugin cloud-foundry

Next add the following two lines to the ~/.grails/settings.groovy file:
grails.plugin.cloudfoundry.username = “yourusername”
grails.plugin.cloudfoundry.password = “yourpassword”

Now you can push the one-note application to Cloud Foundry:

grails prod cf-push

Accept the default url and  choose y at “Would you like to create and bind a mysql service” and n at the same question for a postgresql service.

While building the war for deployment, you might see and Error about a missing migrations directory. This is caused by the database-migration plugin. It’s harmless, but if you want to get rid of it, just add the migrations directory in the grails-app subdirectory of the application.

That’s it. You can test the application via the same url we used before when we used Cloud Foundry Integration: http://one-note.cloudfoundry.com.

There are lots of command available in the plugin. There are for example commands for restarting and deleting a deployed app or service. You can display the list of available commands with:

grails cf-help

Summary

In this blogpost we’ve built a simple Grails application and pushed it to Cloud Foundry, making use of a mysql database service. We’ve shown how to do it via the command line as well as via the Groovy/Grails Tool Suite with the Cloud Foundry Integration plugin. Whichever way you prefer, both ways are very powerful very easy to use. I myself often use a hybrid approach. For the creation of components and pushing the application to the cloud, I use the command line approach . And for managing the deployed applications, I make use of the nice overview interface that the Cloud Foundry Integration Plugin provides.

References

%d bloggers like this: