Showing posts with label servicemix. Show all posts
Showing posts with label servicemix. Show all posts

Sunday, December 19, 2010

basic REST service in Apache CXF vs. Camel-CXF

This article demonstrates how to create/test a basic REST service in CXF vs. Camel-CXF. Given the range of configuration and deployment options, I'm focusing on building a basic OSGi bundle that can be deployed in Fuse 4.2 (ServiceMix)...basic knowledge of Maven, ServiceMix and Camel are assumed.

Apache CXF

For more details, see http://cxf.apache.org/docs/jax-rs.html.

Here is an overview of the steps to get a basic example running...

1. add dependencies to your pom.xml

   <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-frontend-jaxrs</artifactId>
      <version>2.3.0</version>
   </dependency>

2. setup the bundle-context.xml file

    <import resource="classpath:META-INF/cxf/cxf.xml" />
    <import resource="classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml" />
    <import resource="classpath:META-INF/cxf/cxf-extension-http.xml" />
    <import resource="classpath:META-INF/cxf/cxf-extension-http-jetty.xml" />

    <bean id="exampleBean" class="com.example.ExampleBean" />

    <jaxrs:server id="exampleService" address="http://localhost:9000/">
        <jaxrs:serviceBeans>
            <ref bean="exampleBean" />
        </jaxrs:serviceBeans>
    </jaxrs:server>

3. create a service bean class

@Path("/example")
public class ExampleBean {

    @GET
    @Path("/")
    public String ping() throws Exception {
        return "SUCCESS";
    }
}

4. deploy and test

  build the bundle using "mvn install"
  start servicemix
  deploy the bundle
  open a browser to "http://localhost:9000/example" (should see "SUCCESS")

Camel-CXF

For details, see http://camel.apache.org/cxfrs.html

Here is an overview of the steps to get a basic example running...

1. add dependencies to your pom.xml

        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-core</artifactId>
            <version>${camel.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-cxf</artifactId>
            <version>${camel.version}</version>
        </dependency>  

2. setup the bundle-context.xml file

    <camelContext trace="true" id="camelContext" xmlns="http://camel.apache.org/schema/spring">
        <package>com.example</package>
    </camelContext>

3. create a RouteBuilder class

public class ExampleRouter extends RouteBuilder {

    @Override
    public void configure() throws Exception {

        from("cxfrs://http://localhost:9000?resourceClasses=" + ExampleResource.class.getName())
            .process(new Processor() {
                public void process(Exchange exchange) throws Exception {
                    //custom processing here
                }
            })
            .setBody(constant("SUCCESS"));
        }
    }

4. create a REST Resource class

@Path("/example")
public class ExampleResource {

    @GET
    public void ping() {
        //strangely, this method is not called, only serves to configure the endpoint
    }
}

5.  deploy and test

  build bundle using "mvn install"
  start servicemix
  deploy the bundle
  open a browser to "http://localhost:9000/example" (should see "SUCCESS")

Unit Testing

To perform basic unit testing for either of these approaches, use the Apache HttpClient APIs by first adding this dependency to your pom.xml...

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.0.1</version>
        </dependency>


Then, you can use these APIs to create a basic test to validate the REST services created above...

        String url = "http://localhost:9000/example";
        HttpGet httpGet = new HttpGet(url);
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = httpclient.execute(httpGet);
        String responseMessage = EntityUtils.toString(response.getEntity());
        assertEquals("SUCCESS", responseMessage);
        assertEquals(200, response.getStatusLine().getStatusCode());


Summary

Overall, the approaches are very similar, but you can use various combinations of Spring XML and Java APIs to set this up.  I focused on a common approach to demonstrate the basics of each approach side-by-side.

That being said, if you have requirements for complex REST services (security, interceptors, filters, etc), I recommend grabbing a copy of Apache CXF Web Service Development and following some of the more complex examples on the Apache CXF, Camel-CXFRS pages.

In practice, I've generally used Camel-CXF because it gives you the flexibility of integrating with other Camel components and allows you to leverage the rich routing features of Camel.  I hope to cover more complex scenarios in future posts...



Sunday, August 15, 2010

Servicemix 4 development environment setup

Here is a quick guide to setting up a development environment for working on Apache Servicemix projects...

Java 1.6
  • download the JDK and run installation
  • add the /jdk/bin directory to your system path
  • create JAVA_HOME environment variable pointing to the root JDK directory
Maven 2.1
  • download binary and unzip to a local directory
  • edit the /bin/mvn.bat file to increase the Maven heap size (MAVEN_OPTS=-Xmx512m)
  • add the /maven/bin directory to your system path
Eclipse 3.4
  • download Eclipse and run installation
  • open Eclipse
    • create a new workspace
    • create new project or import any existing projects 
  • setup m2eclipse plugin
    • go to Help->Software Updates->Available Software tab
    • then click 'Add Site' and add 'http://m2eclipse.sonatype.org/update/ and call it 'm2eclipse'
    • select the m2clipse components to install, click finish and restart Eclipse
    • go to Windows->Preferences->Maven->Installations
      • set the user settings to your maven settings.xml file
      • verify that this setup the M2_REPO variable to point to your local repo under Java->Build Path->Classpath Variables
    • go to Windows->Preferences->Maven->Archetypes
      • click 'Add Remote Catalog'
        • catalog file = http://repo.fusesource.com/maven2
        • name = Fuse Catalog
        • click OK
Fuse ESB 4.2 (aka ServiceMix)
  • donwload Fuse ESB 4.2 and run installation
basic development process
  • create a new project using an archetype (Maven template) that best matches your application needs
    • from Eclipse
      • File->New->Maven->Maven Project
      • check 'use default workspace location' and click next
      • choose the 'Fuse Catalog' and enter a desire filter
      • choose an archetype
      • click next
      • enter a group id of 'com.<company>.<project>'
      • enter an artifact of '<component>'
      • enter a package name of 'com.<company>.<project>.<component>'
      • click finish 
        • note: I have seen issues with some archetypes in Eclipse, if this happens, use the command line approach instead
    • from command line
      • mvn archetype:create
        -DarchetypeGroupId=org.apache.servicemix.tooling
        -DarchetypeArtifactId=servicemix-osgi-camel-archetype
        -DarchetypeVersion=2010.01.0-fuse-01-00
        -DremoteRepositories=http://repo.fusesource.com/maven2
        -DgroupId=com.mycompany.project1
        -DartifactId=component1
        -Dversion=0.0.1-SNAPSHOT
  •  build the project
    • in Eclipse
      • right click on the project, go to Run As->Maven install
    • from command line
      • run 'mvn install'
    • project JAR will be created under the /target directory and deployed it to your local Maven repository
  • deploying the project to Fuse ESB 4.2
    • run /<smx>/bin/servicemix to start the server
    • make sure any required features/bundles have been installed
      • activemq, camel, etc
    • from the karaf console, install your project bundle
      • osgi:install -s mvn:com.mycompany.project1/component1
    • assuming that worked, you now have a working project
  • customize project and repeat build/deploy process
monitoring
  • watch the servicemix log file
    • tail -f /<smx>/data/log/karaf.log
  •  JConsole
    • <jdk>/bin/jconsole.exe
    • provides remote/local JVM monitoring
    • remote connection uri = service:jmx:rmi:///jndi/rmi://:1099/jmxrmi
    • default user/password = karaf/karaf
  • VisualVM
    • <jdk>/bin/jvisualvm.exe
    • provides remote/local JVM monitoring (slightly better than JConsole)
other recommended software (for Windows)
  • cygwin  - adds basic Linux command support for Windows
  • PowerCMD - tabbed command prompts...trial/not free
  • kdiff3 - excellent file/directory comparison tool
  • SoapUI - for testing HTTP endpoints

If you know of other configurations or tools that are relevant, let me know...

    Saturday, August 14, 2010

    OSGi bundle communication options

    There are various approaches to communicating between bundles...each having its own benefits/tradeoffs. Here are my (in progress) notes on evaluating the options with regards to Fuse ESB 4.2...

    OSGi Service Registry
    This is the most common (and well documented) approach from a pure OSGi perspective. Simple XML can be used to both register APIs as services and access other bundle's services. The service registry then provides an abstraction layer and an event framework to support dynamic binding, reacting to service lifecycle changes, etc. The whiteboard pattern can also help better manage this interaction in more complex/demanding scenarios.

    OSGi Import-Package/Export-Package
    This approach is more direct and relies on OSGi bundle manifests to tell the classloader which classes to export (make available to other bundles) or import (find classes in other bundles). This has the effect of making any imported classes look like any other class in a bundle.

    However, this tends to tightly couple bundles together and can cause various classloader/versioning issues when bundles get out of sync.

    JMS
    An ActiveMQ broker is provided with Fuse ESB and is easily setup/configured. JMS endpoints can then easily be setup using Camel to wrap access to POJO Java code, etc. This can easily serve as a bridge between bundles or even VMs/machines entirely. This approach povides the standard JMS benefits (guaranteed messaging, loose coupling, high performance, failover/load balancing, etc).

    Some initial performance concerns usually arise when considering use of persistent XML messaging. Most performance concerns can be mitigated by varying the JMS QoS or even using serialized object messages instead of XML, etc.

    HTTP (SOAP, REST)
    Another classic approach is to provide HTTP endpoints to interact with a bundle. This provides a loosely coupled strategy bound to either a SOAP WSDL or REST request/response format. Camel components can be used to setup these endpoints and wrap requests to POJO Java code, etc.

    Unfortunately, these endpoints aren't the easiest to configure/test and often impose a significant overhead in terms of marshaling request/response data around.

    NMR
    Though its roots were in JBI/XML based messaging, it has evolved to provide a more generic/configurable approach to bundle communication. It can be configured to be to be synchronous or asynchronous.  Also, the camel-nmr component makes it easy to define NMR endpoints to route data between bundles without the need to use JMS brokers or more complex HTTP definitions.

    See this post from Adrian Trenaman for more details on the new NMR...

    VM
    VM uses asynchronous SEDA to send messages between entities in the same virtual machine.  This has the benefit of using a seperate thread for a producer and consumer.  
    More to come on this...I'm still working out the differences between VM and NMR in OSGi.

    Distributed OSGi (DOSGi)
    This implements the remove services functionality using SOAP web services.  Its very new and I'm still coming up to speed on it...(thanks Ashwin for pointing this out)

    More to come on this...see these page for now.

    http://cxf.apache.org/distributed-osgi.html
    http://osgithoughts.blogspot.com/2010/07/cxf-distributed-osgi-12-is-out.html

    summary
    This is clearly still a work in progress.  There are a lot of options and I'm still trying to get my head around the trade-offs of each approach (hence this page).  As time permits, I'll try to expand on these more...

    If anyone has had good/bad experiences with these techniques or others, let me know...

    Friday, August 13, 2010

    Fuse ESB 4.2 quick start guide

    Here are some notes of getting started using Fuse ESB 4.2 (aka ServiceMix 4).

    For full documentation, click here

    install/config
    • prerequisites
      • required software - JDK 1.5+
      • recommended software - Maven 2.1+, Eclipse 3.4+
      • see this guide for more details
    • download Fuse ESB 4.2 here and follow the installation instructions
    basic structure
    • /bin - executable files
    • /etc - configuration files
    • /deploy - used to deploy bundles
    • /data - runtime files
    basic configuration
    • edit the "org.apache.felix.karaf.features.cfg" file to set necessary startup features (camel, activemq, etc)
    start server
    • cd /[fuse]/bin
    • run 'servicemix' (starts server and karaf shell)
    start shell against a running server
    • ssh -p 8101 karaf@localhost (default password:karaf)
    frequently used commands (for a full list click here)
    • managing features
      • features:list
      • features:listUrl
      • features:uninstall [name]
      • features:install [name]
    • managing bundles
      • osgi:uninstall [id]
      • osgi:install -s file:/bundles/example-1.0.jar
      • osgi:install -s mvn:com.company/example/1.0
      • osgi:update [id] (refresh from install location)
      • osgi:refresh [id] (reinitialize the bundle)
    • monitoring
      • osgi:list (list all bundles)
      • osgi:list | grep test
      • osgi:headers (view bundle header info)
      • osgi:headers | grep test
      • log:display
      • log:set [level] [log package] (log:set DEBUG com.foo.bar)
      • shutdown (stop servicemix)
    other tips
    • monitor log file
      • tail -f /[fuse]/data/log/karaf.log
    • deploy bundles
      • osgi:install or move bundle to the [fuse]/deploy directory