Showing posts with label osgi. Show all posts
Showing posts with label osgi. 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...



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...

Thursday, August 12, 2010

Spring property-placeholder with OSGi

Here are some notes on adding support for properties files to a project. I have it deployed as an OSGI bundle on Fuse ESB 4.2 (aka Apache ServiceMix), but it can be used in various containers/configurations. Anyways, here are the steps...

first, add these required Maven dependencies to your project...
<dependency>
  <groupid>org.springframework.osgi</groupid>
  <artifactid>spring-osgi-core</artifactid>
  <version>1.2.0</version>
</dependency>
<dependency>
  <groupid>org.springframework</groupid>
  <artifactid>spring-context</artifactid>
  <version>2.5.6.SEC01</version>
</dependency>

then, add the following spring XML..
<beans xmlns:context="http://www.springframework.org/schema/context"
            xmlns:osgi="http://www.springframework.org/schema/osgi"
            xmlns:osgix="http://www.springframework.org/schema/osgi-compendium"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns="http://www.springframework.org/schema/beans"
            xsi:schemalocation="
                http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                http://www.springframework.org/schema/osgi http://www.springframework.org/schema/osgi/spring-osgi.xsd
                http://www.springframework.org/schema/osgi-compendium http://www.springframework.org/schema/osgi-compendium/spring-osgi-compendium.xsd">
    <osgix:cm-properties id="props" persistent-id="my.props">
        <prop key="property.name">default value</prop>
    </osgix:cm-properties>
    <context:property-placeholder properties-ref="props"></context:property-placeholder>
    <bean id="myBean" lass="com.company.MyClass">
        <property name="property" value="${property.name}"></property>
    </bean>
</beans>  

finally, create a properties file...
add a file called "my.props.cfg" to your container's classpath (/fuse/etc directory, etc) that contains key=value line separated properties...

tips on using this in practice...
  • the filename must match the <osgix:cm-properties> persistent-id attribute and end with ".cfg". also, avoid using dashes in the filename...
  • this will NOT work in unit tests, you'll need to override your spring XML file under /src/test/resources, remove references to osgi-compendium and hardcode the properties
another option altogether...use the SystemClassLoader
put your properties files in the /servicemix/conf/ directory (doesn't exist by default).  This is in a bundle's classpath and can be loaded as follows...
       
        try {
            Properties prop = new Properties();
            ClassLoader sysClassLoader = ClassLoader.getSystemClassLoader();
            InputStream is = sysClassLoader.getResourceAsStream("my.properties");
            prop.load(is);
        } catch (Exception e) {
            logger.error("error getting props->" + e);
        }

This won't leverage the osgi benefits, but is simple and will work for most cases...