Custom (un)Marshalling with the Camel Rest DSL

Sometimes you want to use a custom marshaller to marshal or unmarshal your messages. In our case we needed to parse all date fields to a specific format when marshalling our output message. We noticed that we could set a custom jsonDataFormat or a custom xmlDataFormat. These options allow you to specify your own DataFormat class, in essence your customized marshaller.

We needed to send out XML or JSON, depending on the clients request (http header: Accept). Because you implement the same interface I will show only the JSON DataFormat. The dataFormat options expects a class that implements the “org.apache.camel.spi.DataFormat” interface. The interface defines two methods, marshal and unmarshal. When you only use the DataFormat for outgoing messages implementing the marshal method is sufficient.

public class JsonDataFormat implements DataFormat {

    private final ObjectMapper jacksonMapper;

    public JsonDataFormat() {
        jacksonMapper = new ObjectMapper();
    }

    @Override
    public void marshal(Exchange exchange, Object obj, OutputStream stream) throws Exception {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sss");
        jacksonMapper.setDateFormat(dateFormat);

        if (view != null) {
            ObjectWriter w = jacksonMapper.writerWithView(view);
            w.writeValue(stream, obj);
        } else {
            stream.write(jacksonMapper.writeValueAsBytes(obj));
        }
    }

    @Override
    public Object unmarshal(Exchange exchange, InputStream stream) throws Exception {
        return null;
    }

Now you cannot simply add the class as a bean and refer to it. You need to add it as a DataFormat to the camel context. This can be done by adding the following file to your META-INF directory: in the classpath: services.org.apache.camel.dataformat add a file which contains the following line:

class=nl.janssen.dataformats.JsonDataFormat

The last thing you need to do is tell your restConfiguration that you want to use your dataFormat. When setting the dataFormat you have to use the file name you specified in the above mentioned classpath. In my case JsonFormat.

restConfiguration()
      .component("jetty")
      .host("0.0.0.0")
      .port("8080")
      .bindingMode(RestBindingMode.auto)
      .xmlDataFormat("XmlFormat")
      .jsonDataFormat("JsonFormat");

If you want a custom xmlDataFormat you simply have to implement the DataFormat interface again but now with an XML (un)marshalling implementation.

Advertisements

Contract first Rest API

As an integration consultant I have an extensive background in web services. To be specific SOAP enabled web services. The way I used to create a service was by first defining the contract, the WSDL and the XSD files. Based on those files I could generate a service without the need for me to manually type any code.

However lately I started working with Rest services, both JSON and XML. I have written a post (Rest just got easy) on how to create a service using the rest DSL from camel. However in some situations you might want to use a JAX-RS implementation, for example using CXFRS. This means you have to first create the interface definition using POJO’s. You could do this the manual way, like me in my first couple of implementations. Or you could generate the code based on an interface design (Hooray for the lazy!). In this blog post I will show you how to generate your rest interface implementation using swagger documentation (Swagger in a nutshell).

Using a maven plugin you can easily generate the required code based on a yaml styled swagger specification file. The plugin can be found through this dependency:

<dependency>
   <groupId>io.swagger</groupId>
   <artifactId>swagger-codegen-maven-plugin</artifactId>
   <version>2.1.6</version>
</dependency>

Because I am using CXFRS I added the dependency for that as well to my pom file:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-cxf</artifactId>
</dependency>

After you have added the dependencies to the pom file you can configure the plugin.

<plugin>
   <groupId>io.swagger</groupId>
   <artifactId>swagger-codegen-maven-plugin</artifactId>
   <version>2.2.0-SNAPSHOT</version>
   <executions>
      <execution>
        <goals>
          <goal>generate</goal>
        </goals>
        <configuration>
		<!-- specify the swagger yaml -->
		<inputSpec>src/main/resources/yaml/swagger.yaml</inputSpec>
		<!-- target to generate -->
		<language>jaxrs-cxf</language>
		<apiPackage>nl.rubix.api</apiPackage>
		<modelPackage>nl.rubix.api.model</modelPackage>
		<configOptions>
		<sourceFolder>src/main/java</sourceFolder>
		</configOptions>
		</configuration>
     </execution>
   </executions>
</plugin>

The plugin has several configuration options.

  • inputSpec – OpenAPI Spec file path
  • language – target generation language
  • output – target output path (default is ${project.build.directory}/generated-sources/swagger)
  • templateDirectory – directory with mustache templates
  • addCompileSourceRoot – add the output directory to the project as a source root (true by default)
  • modelPackage – the package to use for generated model objects/classes
  • apiPackage – the package to use for generated api objects/classes
  • invokerPackage – the package to use for the generated invoker objects
  • configOptions – a map of language-specific parameters (see below)
  • configHelp – dumps the configuration help for the specified library (generates no sources)

As you can see in my example I specified the language to be “jaxrs-cxf”. Meaning that the generated sources will be specific for jaxrs-cxf. The modelPackage will contain the actual objects. If specified the plugin will add the XML declarations to the model POJO’s. The apiPackage will contain the interface specifications.

Create the yaml file on the specified location. My yaml file looks like this:

---
swagger: '2.0'
info:
  version: 0.0.0
  title: Simple API
paths:
  /:
    get:
      responses:
        200:
          description: OK

Meaning, a very simple interface that listens to the root (“/”) of servic epath and will return a http 200 if everything went as planned.

Now that the configuration is done, you can generate the sources with “mvn compile”. You will see the generated sources in the packages you specified.

If everything went correct you can now specify your service. In my example I am using blueprint in combination with the java DSL.

The blueprint definition for the cxfrs component:

<cxf:rsServer id="api" address="http://localhost:9092/test"
               serviceClass="nl.rubix.api.contractfirst.rest.DefaultApi"
               loggingFeatureEnabled="false">
   <cxf:providers>
     <bean class="org.apache.cxf.jaxrs.provider.json.JSONProvider" />
   </cxf:providers>
</cxf:rsServer>

And the route configuration:

from("cxfrs:bean:api?bindingStyle=SimpleConsumer").log("you did it!");

My example project can be found here: Download sources

Fuse contract first webservice

In this blog post I will explain how you can create a SOAP web service in Fuse. You can implement a SOAP interface with the help of CXF. Creating a soap web service with CXF can be done in two ways, contract first or code based. Code based means that the contract is based on the java code. Contract first means that you first specify the contract (WSDL, XSD) and base the implementation on that contract. Because contract first gives you complete control over the interface contract I think it is the best way to go.

In this example I have chosen to use blueprint in combination with the java DSL.

So the first thing, and in my opinion the hardest part, is creating the WSDL. You can find mine and the sources of the project (and the WSDL) here.

The next thing you need to do is generate the code based on the WSDL. This is done with mvn. By adding the following snippets to your pom.xml file mvn will generate the java code that represents the WSDL.

First add the CXF dependency:

<dependency>
    <groupId>org.apache.camel</groupId>
     <artifactId>camel-cxf</artifactId>
     <version><your camel version></version>
</dependency>

Add the plugin that generates the java source code for the contract. Make sure it points to the location of your WSDL and that the WSDL is inside the package:

<plugin>
	<groupId>org.apache.cxf</groupId>
	<artifactId>cxf-codegen-plugin</artifactId>
	<version>3.0.4.redhat-620133</version>
	<executions>
		<execution>
			<id>generate-sources</id>
			<phase>generate-sources</phase>
			<configuration>
				<sourceRoot>target/generated/src/main/java</sourceRoot>
				<wsdlOptions>
					<wsdlOption>
						<wsdl>${project.basedir}/src/main/resources/wsdl/newOrder.wsdl</wsdl>
						<extraargs>
							<extraarg>-impl</extraarg>
						</extraargs>
					</wsdlOption>
				</wsdlOptions>
				<fork>true</fork>
				<additionalJvmArgs>-Djavax.xml.accessExternalSchema=jar:file,file</additionalJvmArgs>
			</configuration>
			<goals>
				<goal>wsdl2java</goal>
			</goals>
		</execution>
	</executions>
</plugin>

After these changes are made you have to run “mvn generate-sources” in order to generate the sources. After this is done, you will probably need to update your project inside your IDE. Otherwise you might not see your generated sources in the project structure.

After the sources have been generated you can add the endpoint to the blueprint of your project. Do not forget to add the CXF namespace. By specifying the endpoint inside your blueprint you can later use it inside your route.

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cxf="http://camel.apache.org/schema/blueprint/cxf"
xmlns:camel="http://camel.apache.org/schema/blueprint"
xsi:schemaLocation="
                http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd
                http://camel.apache.org/schema/blueprint/cxf http://camel.apache.org/schema/blueprint/cxf/camel-cxf.xsd
                http://camel.apache.org/schema/blueprint http://camel.apache.org/schema/blueprint/camel-blueprint.xsd"
<cxf:cxfEndpoint id="newOrderEndpoint"  address="/newOrder/"  serviceClass="nl.rubix.service.neworder.NewOrderServiceOperationsPortType">

Now you are ready to create your endpoint in the camel route. Add the following statement to your route (in my case the java dsl), it should look like this:

from("cxf:bean:newOrderEndpoint")

If you want to see the results of your work you could deploy the bundle to your server. After this is done you should be able to see the service (and the contract) listed at http://localhost:8181/cxf.

Now that the configuration things are done we can actually start implementing the service. The contract in this example specifies two operations with, for the case of simplicity, the same response (xsd element). So we need to change the route so that it can process the two operations.

One way of doing this is by using the recipientList. This allows you to dynamically call another route. If you base the recipientList on the operationName header camel will send the message to the corresponding route.   All the HTTP / SOAP headers are accessible in the route so it is quite straightforward.

.recipientList(simple("direct:${header.operationName}"));
        
from("direct:getOrder")
.log("operation: getTheOrder")
.processRef("contractFirstProcessor");

from("direct:getTheSpecialOrder")
.log("operation: GetTheSpecialOrder")
.processRef("getTheSpecialOrderProcessor");

Each operation in a WSDL normally has a different implementation behind it. Within Fuse I solved it by creating sub routes and for each operation a separate processor. By adding the subroutes you can create specific orchestration per operation. For example call a different database procedure or underlying web service.

The final piece of the puzzle is of course the transformation of the input message and generating the output message. In this case I made a stub that maps part of the input message to the output message. This is done in the processors.

Accessing the input message in the processor can be done in one statement. The generated code contains the class that specifies the input message of the operation. In this case the GetOrderRequest.class. The only thing that you need to do is casting it to the right class. This can be done with the following statement:

GetOrderRequest input = exchange.getIn().getBody(GetOrderRequest.class);

In order to create the output message you can also use the classes generated by CXF. If everything has been generated successfully you should have an ObjectFactory class with which you can generate the output. I mapped the input to the output (OrderNumber) and made sure the generated XML was conform the contract specifications.

ObjectFactory objFac = new ObjectFactory();
GetOrderResponse outbody = objFac.createGetOrderResponse();
outbody.setOrderNumber(input.getOrderNumber());
CustomerType newCustomer = new CustomerType();
newCustomer.setName("Dirk");
newCustomer.setLastname("Janssen");
outbody.setCustomer(newCustomer);
OrderType order = new OrderType();
order.setPrice(12);
order.setProductName("TV");
OrderListType newOrderList = new OrderListType();
newOrderList.getOrder().add(order);

outbody.setOrderList(newOrderList);

After this is you only have to pass the output message back to CXF:

exchange.getOut().setBody(outbody);

Generate a similar processor for the other operation and you are done. Deploy the service to the server and test it (for example, with soapUI).

Read More »