Web service development with Apache CXF and Aegis

Learn to develop a web service using CXF and Aegis databinding

Aegis is one of the databinding standard supported by Apache CXF web service framework. Databinding is a feature that performs mapping between Java objects and XML documents. In this article, you will learn how to develop a CXF based Web service and customize its data binding needs using Aegis. The article will also feature benefits of using Aegis. The article will specifically focus on the use of Aegis external mapping file to customize the binding.

Rajeev Hathi, Java Architect, Writer

Rajeev Hathi works as a Software Consultant for the J2EE platform. His professional interests are architecting, designing and developing J2EE-based applications.  He has attained SUN certifications in Java and J2EE technologies (Core Java, Web, EJB, Architect). He has contributed several technical papers for IBM developerWorks portal. He is also the co-author of the book Apache CXF Web Service Development. His pastime hobbies are listening to music and watching sports. The author's official web site is http://www.rajeevhathi.com which is a technical blog site and he can be reached at rajeevhathi@gmail.com.



23 May 2011

Also available in Chinese Japanese

What is Aegis?

Apache CXF Web service framework provides the support of various databinding tools and one of them is Aegis. Aegis is a databinding API that performs mapping between Java objects and XML document. The CXF framework was derived from the XFire project where Aegis laid its foundation. XFire is now called as CXF. Aegis allows the developers to perform databinding with or without the use of annotations and through the use of external mapping file. The external mapping file enables developers to customize the data mapping and thereby gaining more control over the way mapping can be derived. The external mapping file configuration gives developer lot of flexibility as well in terms of data binding needs. In Web service parlance, data is called messages that are part of method parameters or return types. The mapping file allows you to customize bean and method names as well as method parameters and return types. Aegis can also be used in a standalone application outside of CXF environment.

Benefits of using Aegis

  • Aegis's use of external mapping file give the developers more control and flexibility and enable them to customize the mapping based on their project needs.
  • It keeps your Java classes clean. Unlike JAXB, there is no real need of providing annotations for your data binding needs. One can control the binding using the external mapping file
  • Aegis can perform schema validation for incoming messages or request. The validation feature is part of Woodstox 4.x Stax parser that comes along with the latest CXF release.
  • Aegis gives you the option of using annotations as well. So if you wish not to use external mapping file then annotations can be used for your data binding needs.
  • Aegis can be used independently outside of CXF environment. Its a more independent databinding tool that laid its foundation as part of XFire project.
  • An Aegis enabled Web service can be consumed by a non-Aegis client. The client application could be using JAXB or any other databinding tool and can still invoke Aegis based service.
  • With Aegis you can specify binding at the service level. Unlike JAXB where bindings are more at the property and parameter level, Aegis can allow to specify a generic binding. For example, the nillable=false defined at the service level will make sure that all the properties or parameters are not allowed null.

Sample illustration with code

I will illustrate the use of Aegis by taking a 'Create Course' use case of an online education system. As we know, with every education system, there are courses that are defined by the universities to be undertaken by the students. These courses can be categorized into different subject areas like management, art, science, mathematics etc. We will define a Web service function that will allow the course author to create the courses. To keep it simple, our function will simply display the course attributes on the console. Through this function, I will explain the application of Aegis and how you can control or customize the data binding. The customization will typically include changing the service method parameter name and the bean properties.

To visualize this better, you will develop a Web service named CourseManager with a function called addCourse. The addCourse method will take Course bean as a parameter. The Course bean will have two properties defined viz. code and name. Through Aegis external mapping file you will rename the method parameter and the bean properties and the results can be seen in the SOAP payload.

The operating environment will be Windows and Apache Maven will be used to perform build and execution. You will need the following dependencies in the Maven pom file:

Listing 1. Required Maven dependencies
<dependencies>
	<!-- Embedded Jetty server -->
	<dependency>
		<groupId>org.apache.cxf</groupId>
		<artifactId>cxf-rt-transports-http-jetty</artifactId>
		<version>${cxf.version}</version>
	</dependency>
	<!-- Aegis databinding JAR -->
	<dependency>
		<groupId>org.apache.cxf</groupId>
		<artifactId>cxf-rt-databinding-aegis</artifactId>
		<version>${cxf.version}</version>
	</dependency>
</dependencies>

The complete workflow will be divided into the following steps

  • Setting up the environment
  • Develop a Web service interface and implementation class
  • Develop a client and the server
  • Build and execute
  • Create a mapping file to customize data binding needs
  • Build and execute to see the databinding changes

Setting up the environment

As a first step, you will need Apache CXF distribution for Windows platform. It can be downloaded from http://cxf.apache.org/download.html. You will download the latest CXF release 2.4.0. Once the distribution archive is downloaded, extract the same to the appropriate location say C:\apache-cxf-2.4.0. You will then need Java version 6.0 and it can be downloaded from http://java.com/en/download/index.jsp. For the build purpose, you will use Apache Maven and it can be downloaded from http://maven.apache.org/download.html. Maven expects you to set JAVA_HOME environment variable that will point to the folder where JDK is installed. Finally set the respective bin folders of each installation to the PATH environment variable

Develop a Web service interface and implementation class

You will develop a simple POJO class CourseManagerImpl and the interface CourseManager. The interface will define a method addCourse that takes Course bean as a parameter. The implementation class will look like the following:

Listing 2. CourseManagerImpl implementation class
public class CourseManagerImpl implements CourseManager {

	public void addCourse(Course course) {
		System.out.println("Course code: " + course.getCode());
		System.out.println("Course name: " + course.getName());
	}
}

Apache CXF Frontends

Frontends in CXF are different programming APIs or models that can be used to develop, publish and consume Web services. Supported CXF frontends are Annotations, Dynamic Clients, JAX-WS and Simple. More details can be found at http://cxf.apache.org/docs/frontends.html

As you see from the above code, there is no mention of @Webservice annotation. What it means is you will use the CXF simple frontend to publish and consume CourseManager Web service. The simple frontend allows the developer to code the Web service class without any annotations as a pure POJO. The addCourse method simply prints the course attributes on the console. Ofcourse, in reality you may want to provide logic to actually add the course to the database. But as said earlier, we will keep it simple as our larger objective is to customize the Web service message parts using Aegis binding.

Develop a client and the server

First, you will develop a server that will publish the CourseManager Web service. The server code looks like the following:

Listing 3. Server code
public final class Server {

    public static void main(String args[]) throws Exception {
		CourseManagerImpl implementor = new CourseManagerImpl();
		ServerFactoryBean svrFactory = new ServerFactoryBean();
		svrFactory.setAddress("http://localhost:9000/CourseManager");
		svrFactory.setServiceBean(implementor);
		svrFactory.create();
		System.out.println("Server ready...");
    }
}

The above server code is pretty simple and straightforward. The server is represented by ServerFactoryBean class that is part of CXF's simple frontend API. Through this class, you will set the necessary properties like the Web service implementation class and the endpoint URL. The service implementation class will be CourseManagerImpl and the endpoint URL will be http://localhost:9000/CourseManager. The endpoint URL is where the CourseManager Web service will be published. The create method will start the embedded Jetty server on the port 9000

The next step is to write the client code that will consume the CourseManager Web service

Listing 4. Client code
public final class Client {

    public static void main(String args[]) throws Exception {
		ClientProxyFactoryBean factory = new ClientProxyFactoryBean();
		factory.setServiceClass(CourseManager.class);
		factory.setAddress("http://localhost:9000/CourseManager");
		factory.getOutInterceptors().add(new LoggingOutInterceptor());
		CourseManager client = (CourseManager) factory.create();
		Course course = new Course();
		course.setCode("C01");
		course.setName("English Grammer");
		client.addCourse(course);
    }
}

The client code is much similar to the server code. Except that here you will use the LoggingOutInterceptor interceptor class to log the SOAP message on the console. This is needed so that you can view the changes in the SOAP message once we apply the Aegis binding.

Build and Execute

You will build the above illustrated code using Maven. The server and client classes are main Java applications that will be run in a seperate command window. Ofcourse you can use Maven java:exec goal to run them. First start the server and then run the client program. You will see the following SOAP message passed from the client to the server.

Figure 1. SOAP Payload
SOAP Payload

Let's look carefully at the SOAP message. The method name addCourse is wrapped in a SOAP body as an element. The method parameter Course bean is written as a child element to the <addCourse> element. This child element is named <arg0>. The child elements to <arg0> element are the attributes of the Course bean viz. <code> and <name>.

You will now tweak the SOAP message by renaming these element names to make it more meaningful. Here is where you will apply Aegis binding to your CourseManager Web service. You will see that in the next step.

Create a mapping file to customize data binding needs

In this step, you will customize the SOAP elements using Aegis databinding. Since the element <arg0> represents our Course bean, let's rename this to <course> instead of <arg0>. You will also rename the <code> and <name> elements to <courseCode> and <courseName> respectively. You will use Aegis external mapping file to perform these element customization. Aegis comes with the concept of external mapping file where you can specify different customizations as per your binding needs.

First step is to rename the element <arg0> to <course>. Since the said element represents a Course bean which is a parameter to a addCourse service method, you will write a mapping file for our CourseManager service. The nomenclature for the mapping file is <classname>.aegis.xml. The mapping file must be placed alongside the mapped class in that same package. So the following CourseManager.aegis.xml will be part of demo.cxf.aegis package.

Listing 5. CourseManager.aegis.xml mapping file
<mappings>
    <mapping name="CourseManager">
        <method name="addCourse">
            <parameter index="0" mappedName="course" nillable='false' />
        </method>
    </mapping>
</mappings>

The above mapping file is simple to understand. The mapping name CourseManager indicates that you are mapping a CourseManager Web service. The method addCourse has one parameter which is Course bean and the parameter index is 0. So rename this zeroth index parameter to course when performing marshalling. This will ensure that the element <arg0> will be renamed to <course>. The nillable=false means the parameter cannot be null.

You will now rename the SOAP elements <code> and <name> that were part of <arg0> element. You will write another mapping file that will now map the Course bean, as its attributes needs to be renamed during binding. The following Course.aegis.xml file will be part of demo.cxf.aegis package.

Listing 6. Course.aegis.xml mapping file
<mappings>
    <mapping name="Course">
		<property name="code" mappedName="courseCode" nillable='false' />
		<property name="name" mappedName="courseName" nillable='false' />
    </mapping>
</mappings>

The above mapping file maps the Course bean and renames its marshalled parameter code and name to courseCode and courseName. With this you have successfully defined the binding rules for CourseManager Web service and the Course bean

Finally, you will need to add the Aegis capability to client and the server code.

Listing 7. Added Aegis databinding to the server code
. . .
		CourseManagerImpl implementor = new CourseManagerImpl();
		ServerFactoryBean svrFactory = new ServerFactoryBean();
		svrFactory.setAddress("http://localhost:9000/CourseManager");
		svrFactory.setServiceBean(implementor);
        svrFactory.getServiceFactory().setDataBinding(new AegisDatabinding());
		svrFactory.create();
		System.out.println("Server ready...");
    }
}
Listing 8. Added Aegis databiniding to the client code
. . .
		ClientProxyFactoryBean factory = new ClientProxyFactoryBean();
		factory.setServiceClass(CourseManager.class);
		factory.setAddress("http://localhost:9000/CourseManager");
        factory.getServiceFactory().setDataBinding(new AegisDatabinding());
. . .		
    }
}

Build and execute to see the databinding changes

Build the revised code and you will see the following output.

Figure 2. SOAP Payload after applying Aegis databinding
SOAP Payload after applying Aegis databinding

The above SOAP payload now looks more meaningful. After applying Aegis data binding, you can see the element <arg0> changed to <course> and the child elements <code> and <name> changed to <courseCode> and <courseName> respectively.

With Aegis binding, you can do lot of things apart from just renaming the SOAP payload elements. You can make an element as an attribute and make method parameter or bean properties nillable or not nillable. You can also add namespaces to element and attributes. You can also specify whether to serialize a certain bean property or not. Apart from all this, you can also provide custom types over the default Aegis types to perform mapping.

Resources

Learn

Get products and technologies

  • Evaluate IBM products in the way that suits you best: Download a product trial, try a product online, use a product in a cloud environment, or spend a few hours in the SOA Sandbox learning how to implement Service Oriented Architecture efficiently.

Discuss

  • Get involved in the My developerWorks community. Connect with other developerWorks users while exploring the developer-driven blogs, forums, groups, and wikis.

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into SOA and web services on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=SOA and web services
ArticleID=660131
ArticleTitle=Web service development with Apache CXF and Aegis
publish-date=05232011