...
Tutorial - camel-example-reportincident
...
Info | ||
---|---|---|
| ||
Work in progress by Claus Ibsen. Tutorial to be part of Camel 1.5. (CAMEL-601) |
...
...
Introduction
Creating this tutorial was inspired by a real life use-case I discussed over the phone with a collegecolleague. He was working at a client that whom uses a heavy-weight integration platform from a very large vendor. He was in talks with contractors developer shops to implement a new integration on this heavy piece of platform - his trouble was though that the price was tripled when the contractors heard it had to be on this platformplatform. His trouble was the shop tripled the price when they realized the platform of choice. So I was wondering how we could do this integration on with Camel. Can it be done in one day, without tripling the cost .
This tutorial is written during the development of the integration. I have decided to start off with a sample that isn't Camel's but standard Java and then plugin Camel as we goes. Just as when people needed to learn Spring you could consume it piece by piece, the same goes with Camel.
The target reader is person whom hasn't experience or just started using Camel.
Motivation for this tutorial
I wrote this tutorial motivated as Camel lacked an example application that was based on the web application deployment model. The entire world hasn't moved to pure OSGi deployments yet.
Tip |
---|
The full source code for this tutorial as complete is part of the Apache Camel distribution in the |
The use-case
The goal is to allow staff to report incidents into a central administration. For that they use client software where they report the incident and submit it to the central administration. As this is an integration in a transition phase the administration should get these incidents by email whereas they are manually added to the database. The client software should gather the incident and submit the information to the integration platform that in term will transform the report into an email and send it to the central administrator for manual processing.
...
We distill the use case as EIP patterns:
Initial Project Setup
We want the integration to be a standard .war application that can be deployed in any web container such as Tomcat, Jetty or even heavy weight application servers such as WebLogic or WebSphere. There fore we start off with the standard Maven webapp project that is created with the following long archetype command:
Code Block |
---|
mvn archetype:create -DgroupId=org.apache.camel -DartifactId=camel-example-reportincident -DarchetypeArtifactId=maven-archetype-webapp
|
Notice that the groupId etc. doens't have to be org.apache.camel it can be com.mycompany.whatever. But I have used these package names as the example is an official part of the Camel distribution.
Then we have the basic maven folder layout. We start out with the webservice part where we want to use Apache CXF for the webservice stuff. So we add this to the pom.xml
...
<properties>
<cxf-version>2.1.1</cxf-version>
</properties>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-core</artifactId>
<version>${cxf-version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>${cxf-version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>${cxf-version}</version>
</dependency>
Developing the WebService
As we want to develop webservice with the contract first approach we create our .wsdl file. As this is a example we have simplified the model of the incident to only include 8 fields. In real life the model would be a bit more complex, but not to much.
We put the wsdl file in the folder src/main/webapp/WEB-INF/wsdl
and name the file report_incident.wsdl
.
...
<?xml version="1.0" encoding="ISO-8859-1"?>
<wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://reportincident.example.camel.apache.org"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:http="http://schemas.xmlsoap.org/wsdl/http/"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
targetNamespace="http://reportincident.example.camel.apache.org">
<!-- Type definitions for input- and output parameters for webservice -->
<wsdl:types>
<xs:schema targetNamespace="http://reportincident.example.camel.apache.org">
<xs:element name="inputReportIncident">
<xs:complexType>
<xs:sequence>
<xs:element type="xs:string" name="incidentId"/>
<xs:element type="xs:string" name="incidentDate"/>
<xs:element type="xs:string" name="givenName"/>
<xs:element type="xs:string" name="familyName"/>
<xs:element type="xs:string" name="summary"/>
<xs:element type="xs:string" name="details"/>
<xs:element type="xs:string" name="email"/>
<xs:element type="xs:string" name="phone"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="outputReportIncident">
<xs:complexType>
<xs:sequence>
<xs:element type="xs:string" name="code"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
</wsdl:types>
<!-- Message definitions for input and output -->
<wsdl:message name="inputReportIncident">
<wsdl:part name="parameters" element="tns:inputReportIncident"/>
</wsdl:message>
<wsdl:message name="outputReportIncident">
<wsdl:part name="parameters" element="tns:outputReportIncident"/>
</wsdl:message>
<!-- Port (interface) definitions -->
<wsdl:portType name="ReportIncidentEndpoint">
<wsdl:operation name="ReportIncident">
<wsdl:input message="tns:inputReportIncident"/>
<wsdl:output message="tns:outputReportIncident"/>
</wsdl:operation>
</wsdl:portType>
<!-- Port bindings to transports and encoding - HTTP, document literal encoding is used -->
<wsdl:binding name="ReportIncidentBinding" type="tns:ReportIncidentEndpoint">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="ReportIncident">
<soap:operation
soapAction="http://reportincident.example.camel.apache.org/ReportIncident"
style="document"/>
<wsdl:input>
<soap:body parts="parameters" use="literal"/>
</wsdl:input>
<wsdl:output>
<soap:body parts="parameters" use="literal"/>
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<!-- Service definition -->
<wsdl:service name="ReportIncidentService">
<wsdl:port name="ReportIncidentPort" binding="tns:ReportIncidentBinding">
<soap:address location="http://reportincident.example.camel.apache.org"/>
</wsdl:port>
</wsdl:service>
</wsdl:definitions>
CXF wsdl2java
Then we integration the CXF wsdl2java generator in the pom.xml so we have CXF generate the needed POJO classes for our webservice contract.
However at first we must configure maven to live in the modern world of Java 1.5 so we must add this to the pom.xml
...
<!-- to compile with 1.5 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
And then we can add the CXF wsdl2java code generator that will hook into the compile goal so its automatic run all the time:
...
<!-- CXF wsdl2java generator, will plugin to the compile goal -->
<plugin>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-codegen-plugin</artifactId>
<version>${cxf-version}</version>
<executions>
<execution>
<id>generate-sources</id>
<phase>generate-sources</phase>
<configuration>
<sourceRoot>${basedir}/target/generated/src/main/java</sourceRoot>
<wsdlOptions>
<wsdlOption>
<wsdl>${basedir}/src/main/webapp/WEB-INF/wsdl/report_incident.xml</wsdl>
</wsdlOption>
</wsdlOptions>
</configuration>
<goals>
<goal>wsdl2java</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
Parts
This tutorial is divided into sections and parts:
Section A: Existing Solution, how to slowly use Camel
Part 1 - This first part explain how to setup the project and get a webservice exposed using Apache CXF. In fact we don't touch Camel yet.
Part 2 - Now we are ready to introduce Camel piece by piece (without using Spring or any XML configuration file) and create the full feature integration. This part will introduce different Camel's concepts and How we can build our solution using them like :
- CamelContext
- Endpoint, Exchange & Producer
- Components : Log, File
Part 3 - Continued from part 2 where we implement that last part of the solution with the event driven consumer and how to send the email through the Mail component.
Section B: The Camel Solution
Part 4 - We now turn into the path of Camel where it excels - the routing.
Part 5 - Is about how embed Camel with Spring and using CXF endpoints directly in Camel
Part 6 - Showing a alternative solution primarily using XML instead of Java code
Tip | ||
---|---|---|
| ||
See this blog entry by Sagara demonstrating how to use Apache Axis 2 instead of Apache CXF as the web service framework. |
Links
You are now setup and should be able to compile the project. So running the mvn compile
should run the CXF wsdl2java and generate the source code in the folder &{basedir}/target/generated/src/main/java
that we specified in the pom.xml above. Since its in the target/generated/src/main/java
maven will pick it up and include it in the build process.
Configuration of the web.xml
Next up is to configure the web.xml to be ready to use CXF so we can expose the webservice.
As Spring is the center of the universe, or at least is a very important framework in today's Java land we start with the listener that kick-starts Spring. This is the usual piece of code:
...
<!-- the listener that kick-starts Spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
And then we have the CXF part where we define the CXF servlet and its URI mappings to which we have chosen that all our webservices should be in the path /webservices/
...
<!-- CXF servlet -->
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- all our webservices are mapped under this URI pattern -->
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/webservices/*</url-pattern>
</servlet-mapping>
Then the last piece of the puzzle is to configure CXF, this is done in a spring XML that we link to fron the web.xml by the standard Spring contextConfigLocation
property in the web.xml
...
<!-- location of spring xml files -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:cxf-config.xml</param-value>
</context-param>
We have named our CXF configuration file cxf-config.xml
and its located in the root of the classpath. In Maven land that is we can have the cxf-config.xml
file in the src/main/resources
folder. We could also have the file located in the WEB-INF folder for instance <param-value>/WEB-INF/cxf-config.xml</param-value>
.
Getting rid of the old jsp world
The maven archetype that created the basic folder structure also created a sample .jsp file index.jsp. This file src/main/webapp/index.jsp
should be deleted.
Configuration of CXF
The cxf-config.xml is as follows:
...
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml"/>
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>
<import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>
<!-- implementation of the webservice -->
<bean id="reportIncidentEndpoint" class="org.apache.camel.example.reportincident.ReportIncidentEndpointImpl"/>
<!-- export the webservice using jaxws -->
<jaxws:endpoint id="reportIncident"
implementor="#reportIncidentEndpoint"
address="/incident"
wsdlLocation="/WEB-INF/wsdl/report_incident.xml"
endpointName="s:ReportIncidentPort"
serviceName="s:ReportIncidentService"
xmlns:s="http://reportincident.example.camel.apache.org"/>
</beans>
The configuration is standard CXF and is documented at the Apache CXF website.
The 3 import elements is needed by CXF and they must be in the file.
Noticed that we have a spring bean reportIncidentEndpoint that is the implementation of the webservice endpoint we let CXF expose.
Its linked from the jaxws element with the implementator attribute as we use the # mark to identify its a reference to a spring bean. We could have statet the classname directly as implementor="org.apache.camel.example.reportincident.ReportIncidentEndpoint"
but then we lose the ability to let the ReportIncidentEndpoint be configured by spring.
The address attribute defines the relative part of the URL of the exposed webservice. wsdlLocation is an optional parameter but for persons like me that likes contract-first we want to expose our own .wsdl contracts and not the auto generated by the frameworks, so with this attribute we can link to the real .wsdl file. The last stuff is needed by CXF as you could have several services so it needs to know which this one is. Configuring these is quite easy as all the information is in the wsdl already.
Implementing the ReportIncidentEndpoint
Phew after all these meta files its time for some java code so we should code the implementor of the webservice. So we fire up mvn compile
to let CXF generate the POJO classes for our webservice and we are ready to fire up a Java editor.
You can use mvn idea:idea
or mvn eclipse:eclipse
to create project files for these editors so you can load the project. However IDEA has been smarter lately and can load a pom.xml directly.
As we want to quickly see our webservice we implement just a quick and dirty as it can get. At first beware that since its jaxws and Java 1.5 we get annotations for the money, but they reside on the interface so we can remove them from our implementations so its a nice plain POJO again:
...
package org.apache.camel.example.reportincident;
/**
* The webservice we have implemented.
*/
public class ReportIncidentEndpointImpl implements ReportIncidentEndpoint {
public OutputReportIncident reportIncident(InputReportIncident parameters) {
System.out.println("Hello ReportIncidentEndpointImpl is called from " + parameters.getGivenName());
OutputReportIncident out = new OutputReportIncident();
out.setCode("OK");
return out;
}
}
We just output the person that invokes this webservice and returns a OK response. This class should be in the maven source root folder src/main/java
under the package name org.apache.camel.example.reportincident
. Beware that the maven archetype tool didn't create the src/main/java folder
, so you should create it manually.
To test if we are home free we run mvn clean compile
.
Running our webservice
Now that the code compiles we would like to run it in a web container, so we add jetty to our pom.xml so we can run mvn retty:run
:
...
<properties>
...
<jetty-version>6.1.1</jetty-version>
</properties>
<build>
<plugins>
...
<!-- so we can run mvn jetty:run -->
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>${jetty-version}</version>
</plugin>
Notice: We use Jetty v6.1.1 as never versions has troubles on my laptop. Feel free to try a newer version on your system, but v6.1.1 works flawless.
So to see if everything is in order we fire up jetty with mvn jetty:run
and if everything is okay you should be able to access http://localhost:8080
.
Jetty is smart that it will list the correct URI on the page to our web application, so just click on the link. This is smart as you don't have to remember the exact web context URI for your application - just fire up the default page and Jetty will help you.
So where is the damm webservice then? Well as we did configure the web.xml to instruct the CXF servlet to accept the pattern /webservices/*
we should hit this URL to get the attention of CXF: http://localhost:8080/my-webapp/webservices
.
Hitting the webservice
Now we have the webservice running in a standard .war application in a standard web container such as Jetty we would like to invoke the webservice and see if we get our code executed. Unfortunately this isn't the easiest task in the world - its not so easy as a REST URL, so we need tools for this. So we fire up our trusty webservice tool SoapUI and let it be the one to fire the webservice request and see the response.
Using SoapUI we sent a request to our webservice and we got the expected OK response and the console outputs the System.out so we are ready to code.
Remote Debugging
Okay a little sidestep but wouldn't it be cool to be able to debug your code when its fired up under Jetty? As Jetty is started from maven, we need to instruct maven to use debug mode.
Se we set the MAVEN_OPTS
environment to start in debug mode and listen on port 5005.
Code Block |
---|
MAVEN_OPTS=-Xmx512m -XX:MaxPermSize=128m -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005
|
Then you need to restart Jetty so its stopped with ctrl + c. Remember to start a new shell to pickup the new environment settings. And start jetty again.
Then we can from our IDE attach a remote debugger and debug as we want.
First we configure IDEA to attach to a remote debugger on port 5005:
Then we set a breakpoint in our code ReportIncidentEndpoint
and hit the SoapUI once again and we are breaked at the breakpoint where we can inspect the parameters:
Adding a unit test
Oh so much hard work just to hit a webservice, why can't we just use an unit test to invoke our webservice? Yes of course we can do this, and that's the next step.
First we create the folder structure src/test/java
and src/test/resources
. We then create the unit test in the src/test/java
folder.
...
package org.apache.camel.example.reportincident;
import junit.framework.TestCase;
/**
* Plain JUnit test of our webservice.
*/
public class ReportIncidentEndpointTest extends TestCase {
}
Here we have a plain old JUnit class. As we want to test webservices we need to start and expose our webservice in the unit test before we can test it. And JAXWS has pretty decent methods to help us here, the code is simple as:
...
import javax.xml.ws.Endpoint;
...
private static String ADDRESS = "http://localhost:9090/unittest";
protected void startServer() throws Exception {
// We need to start a server that exposes or webservice during the unit testing
// We use jaxws to do this pretty simple
ReportIncidentEndpointImpl server = new ReportIncidentEndpointImpl();
Endpoint.publish(ADDRESS, server);
}
The Endpoint class is the javax.xml.ws.Endpoint
that under the covers looks for a provider and in our case its CXF - so its CXF that does the heavy lifting of exposing out webservice on the given URL address. Since our class ReportIncidentEndpointImpl implements the interface ReportIncidentEndpoint that is decorated with all the jaxws annotations it got all the information it need to expose the webservice. Below is the CXF wsdl2java generated interface:
...
/*
*
*/
package org.apache.camel.example.reportincident;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.ParameterStyle;
import javax.xml.bind.annotation.XmlSeeAlso;
/**
* This class was generated by Apache CXF 2.1.1
* Wed Jul 16 12:40:31 CEST 2008
* Generated source version: 2.1.1
*
*/
/*
*
*/
@WebService(targetNamespace = "http://reportincident.example.camel.apache.org", name = "ReportIncidentEndpoint")
@XmlSeeAlso({ObjectFactory.class})
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
public interface ReportIncidentEndpoint {
/*
*
*/
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
@WebResult(name = "outputReportIncident", targetNamespace = "http://reportincident.example.camel.apache.org", partName = "parameters")
@WebMethod(operationName = "ReportIncident", action = "http://reportincident.example.camel.apache.org/ReportIncident")
public OutputReportIncident reportIncident(
@WebParam(partName = "parameters", name = "inputReportIncident", targetNamespace = "http://reportincident.example.camel.apache.org")
InputReportIncident parameters
);
}
Next up is to create a webservice client so we can invoke our webservice. For this we actually use the CXF framework directly as its a bit more easier to create a client using this framework than using the JAXWS style. We could have done the same for the server part, and you should do this if you need more power and access more advanced features.
...
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
...
protected ReportIncidentEndpoint createCXFClient() {
// we use CXF to create a client for us as its easier than JAXWS and works
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.setServiceClass(ReportIncidentEndpoint.class);
factory.setAddress(ADDRESS);
return (ReportIncidentEndpoint) factory.create();
}
So now we are ready for creating a unit test. We have the server and the client. So we just create a plain simple unit test method as the usual junit style:
...
public void testRendportIncident() throws Exception {
startServer();
ReportIncidentEndpoint client = createCXFClient();
InputReportIncident input = new InputReportIncident();
input.setIncidentId("123");
input.setIncidentDate("2008-07-16");
input.setGivenName("Claus");
input.setFamilyName("Ibsen");
input.setSummary("bla bla");
input.setDetails("more bla bla");
input.setEmail("davsclaus@apache.org");
input.setPhone("+45 2962 7576");
OutputReportIncident out = client.reportIncident(input);
assertEquals("Response code is wrong", "OK", out.getCode());
}
Now we are nearly there. But if you run the unit test with mvn test
then it will fail. Why!!! Well its because that CXF needs is missing some dependencies during unit testing. In fact it needs the web container, so we need to add this to our pom.xml.
...
<!-- cxf web container for unit testing -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>${cxf-version}</version>
<scope>test</scope>
</dependency>
Well what is that, CXF also uses Jetty for unit test - well its just shows how agile, embedable and popular Jetty is.
So lets run our junit test with, and it reports:
Code Block |
---|
mvn test
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESSFUL
|
Yep thats it for now. We have a basic project setup.
End of part 1
...