Monday, November 28, 2016

Real-Time Data Batching with Apache Camel

Over the past few years, I've been working with high volume real-time message based applications.  As we scale these systems out, resource usage becomes increasingly important and various trade-offs have to be considered.

From a storage perspective, many of the NoSQL techs claim to handle mass volumes of parallel requests and data with ease.  In the real world, however, most techs have similar system resource limitations (threading, CPU, memory, I/O, etc) that all contribute to latency/stability issues.  Though many symptoms can be masked by horizontal scaling...at the end of the day, the more efficiently your applications use resources, the better things scale out...

One approach is to batch process data to more efficiently use resources (threads/connections) by reducing per message/request overhead.  This is a widely used pattern for at-rest/bulk data processing, but not often considered for real-time/event driven processing.  As it turns out, this pattern is often a best practice (or even required) for reasonable performance from external systems and storage techs when working with high volume data.

I first encountered this use case when storing high volume messaging in Oracle.  The issue is that transaction commits are expensive and committing a single message at a time simply doesn't scale. Instead, we switched to aggregating messages in memory and then passed these to Oracle via an array.  The net result was dramatically reduced load against the database, negligible delays in processing data and a theoretical increased chance of message loss...overall, this addressed our performance issues with relatively little impact.

Then, as we moved into NoSQL solutions (Cassandra, HDFS, ElasticSearch, etc), I revisited the need for batching...it was obvious that the same batching strategy still applied to these new techs as well...

Luckily, we are working with Apache Camel and its implementation of EIPs (Enterprise Integration Patterns) make solving these types of issues fairly straight forward.  In particular, the split and aggregator patterns are designed for just this type of message flow.

For example, let's say I have 3 systems that process messages...A, B, C.  System A produces messages and sends them to system B.  system B does some processing and then sends them to system C for final processing.


in Camel, this is expressed by the following simple route (assuming ActiveMQ is used as a message bus in between systems)


now, if we find that system B requires batch sizes of 100.  I can easily batch these together using a simple aggregator as follows...


Given the config above, we'll pass on a batch after 100 messages are aggregated (completionSize) OR after 1000ms (completionTimeout)...the latter is key to limiting the delay in processing when volume is low.  also note, the above would pass on a batch size of 100 to system C...
Now, let's assume system C prefers a batch size of 10 and must get groups for the same accountId...here are the changes required


notice that in the system C route, I now call split(body()) which will split the incoming batch from system B and allow us to re-aggregate per the requirements for this system.  Also, the header("accountId") in place of constant(true) tells the aggregator to build batches/groups for similar accountId values only and still complete after 10 are received or after 1000ms...

As you can see, these are very flexible and easy to implement patterns for message flow.  That said, you do have to give some consideration to memory/CPU usage and overall message reliability requirements when using these.

Overall, I've used this pattern to successfully scale out high volume requests to Oracle, Cassandra, HDFS and ElasticSearch...

Wednesday, June 18, 2014

ApacheCon 2014 Presentation - Apache Camel Business Patterns

A few months back I had the opportunity to present at ApacheCon in Denver, CO.  While the conference was small, I had the chance to meet some interesting people in the community and learn about some other Apache projects.

My presentation was an introduction to how to use Camel to address common business problems (common to my experience anyways).

Here is a link to my presentation slides and the audio, feedback is welcome...

http://prezi.com/tf0hgra0yvn1/camel-business-patterns/

http://feathercast.apache.org/podcasts/ApacheConNA2014/lawrence_b/Lawrence-B_17Ben%20Oday.mp3




Tuesday, November 8, 2011

Creating A Custom Camel Component

While Camel supports an ever growing number of components, you might have a need to create a custom component. This could be to either promote reuse across projects, customize an existing component or provide a simplified interface to an existing system. Whatever the reason, here is an overview of the options that are available within the Camel framework...

first, consider just creating a Bean or Processor

Before you jump in and create a component, consider just creating a simple class to handle your custom logic. Behind the scenes, all components are just Processors with a bunch of lifecycle support around them.  Beans and Processors are simple, streamlined and easy to manage.

using a Bean...

from(uri).bean(MyBean.class);
... 
public class MyBean {
    public void doSomething(Exchange exchange) {
      //do something...
   }
}

using a Processor...

from(uri).process(new MyProcessor());
... 
public class MyProcessor implements Processor {
    public void process(Exchange exchange) throws Exception {
        //do something... 
    }
}

create a custom component

If you decide to go down this route, you should start by start by using a Maven archetype to stub out a new component project for you.

mvn archetype:generate
    -DarchetypeGroupId=org.apache.camel.archetypes
    -DarchetypeArtifactId=camel-archetype-component
    -DarchetypeVersion=2.9.2
    -DarchetypeRepository=https://repository.apache.org/content/groups/snapshots-group
    -DgroupId=org.apache.camel.component
    -DartifactId=camel-ben
 
This will create a new Maven component project that contains an example HelloWorld component as seen here...
 
 
 





The following core classes are created and have the following responsibilities:

  • HelloWorldComponent
    • endpoint factory which implements createEndpoint()
  • HelloWorldEndpoint
    • producer/consumer factory which implements createConsumer(), createProducer(), createExchange()
  • HelloWorldConsumer
    • acts as a service to consumes request at the start of a route
  • HelloWorldProducer
    • acts as a service consumer to dispatch outgoing requests and receive incoming replies
  • Exchange
    • encapsulate the in/out message payloads and meta data about the data flowing between endpoints
  • Message
    • represent the message payload
    • their is an IN and OUT message for each exchange 
So, how do all these classes/method actually work?  The best way to get your head around this is to load the project into Eclipse (or IntelliJ) and debug the unit test.  This will allow you to step into the route initialization and message processing to trace the flow.

Consumer Lifecycle

When you define a route that uses your new component as a consumer, like this
from("helloworld:foo").to("log:result");

It does the following:
  • creates a HelloWorldComponent instance (one per CamelContext)
  • calls HelloWorldComponent createEndpoint() with the given URI
  • creates a HelloWorldEndpoint instance (one per route reference)
  • creates a HelloWorldConsumer instance (one per route reference)
  • register the route with the CamelContext and call doStart() on the Consumer
  • consumers will then start in one of the following modes:
    • event driven - wait for message to trigger route
    • polling consumer - manually polls a resource for events
    • scheduled polling consumer - events automatically generated by timer
    • custom threading - custom management of the event lifecyle

Producer Lifecycle

When you define a route that uses your new component as a producer, like this
from("direct:start").to("helloworld:foo");
It does the following:
  • creates a HelloWorldComponent instance (one per CamelContext)
  • calls HelloWorldComponent createEndpoint() with the given URI
  • creates a HelloWorldEndpoint instance (one per route reference)
  • creates a HelloWorldProducer instance (one per route reference)
  • register the route with the CamelContext and start the route consumer
  • the Producer's process(Exchange) method is then executed
    • generally, this will decorate the Exchange by interfacing with some external resource (file, jms, database, etc)
Other Resources 
http://camel.apache.org/writing-components.html
http://fusesource.com/docs/mirrors/camel/developers/writing-components.html
http://fusesource.com/docs/mirrors/camel/documentation/user-guide/creating-a-new-camel-component.html
 

Friday, August 19, 2011

Performance Monitoring With Spring AOP

If you are using Spring to access/configure resources (DAOs/services), then you might as well add some basic performance monitoring while you are at it.  This is a trivial task with Spring AOP and doesn't require any changes to existing code, just some simple configuration. 

First, you need to include the spring-aop, aspectj and cglib libraries.  If you are using Maven, simply include the following dependencies...

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.5.4</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib-nodep</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-aop</artifactId>
          <version>2.5.6</version>
        </dependency>


Next, identify what needs monitoring and put the AOP hooks in place.  Generally, this just requires adding a pointcut and advisor configuration in your existing Spring XML configuration file.  This configuration will add method response time logging to all methods in the "com.mycompany.services" package.  Note: these classes must be instantiated with the Spring context...otherwise, the AOP hooks will not be executed.

    <bean id="performanceMonitor"
              class="org.springframework.aop.interceptor.PerformanceMonitorInterceptor" />

    <aop:config>
        <aop:pointcut id="allServiceMethods" expression="execution(* com.mycompany.services.*.*(..))"/>
        <aop:advisor pointcut-ref="allServiceMethods" advice-ref="performanceMonitor" order="2"/>
    </aop:config>

Next, you need to setup your logging (log4j, etc) to enable TRACE on the interceptor class.

    <logger name="org.springframework.aop.interceptor.PerformanceMonitorInterceptor" additivity="false">
        <level value="TRACE"/>
        <appender-ref ref="STDOUT"/>
    </logger>

That's it, now when you run your application, you will see the following logging...

TRACE PerformanceMonitorInterceptor  - StopWatch 'PerfTestService.processRequest': running time (millis) = 1322
TRACE PerformanceMonitorInterceptor  - StopWatch 'PerfTestService.processRequest': running time (millis) = 98
TRACE PerformanceMonitorInterceptor  - StopWatch 'PerfTestService.processRequest': running time (millis) = 1764


This is a some great raw data, but unfortunately is not very useful on its own.  Its for every method call and doesn't provide any other stats.  This quickly clutters up the log and without some way to process/aggregate the log entries, its hard to make sense out of it.  So, unless you plan of writing some log parsing or using 3rd party software (like Splunk or Cati), then you really should do some processing of the data before writing it to the log file.


One easy way to do this is to just write a simple interceptor class to use instead of the Spring default one (PerformanceMonitorInterceptor).  Below is an example of this that provides periodic stats (last, average and greatest response time) as well as warning whenever a method response time exceeds a configured threshold.

By default, it will log stats every 10 method calls and log a warning message anytime a method response time exceeds 1000ms.

public class PerfInterceptor implements MethodInterceptor {

     Logger logger = LoggerFactory.getLogger(PerfInterceptor.class.getName());
    private static ConcurrentHashMap<String, MethodStats> methodStats = new ConcurrentHashMap<String, MethodStats>();
    private static long statLogFrequency = 10;
    private static long methodWarningThreshold = 1000;
   
    public Object invoke(MethodInvocation method) throws Throwable {
        long start = System.currentTimeMillis();
        try {
            return method.proceed();
        }
        finally {
            updateStats(method.getMethod().getName(),(System.currentTimeMillis() - start));
        }
    }

    private void updateStats(String methodName, long elapsedTime) {
        MethodStats stats = methodStats.get(methodName);
        if(stats == null) {
            stats = new MethodStats(methodName);
            methodStats.put(methodName,stats);
        }
        stats.count++;
        stats.totalTime += elapsedTime;
        if(elapsedTime > stats.maxTime) {
            stats.maxTime = elapsedTime;
        }
       
        if(elapsedTime > methodWarningThreshold) {
            logger.warn("method warning: " + methodName + "(), cnt = " + stats.count + ", lastTime = " + elapsedTime + ", maxTime = " + stats.maxTime);
        }
       
        if(stats.count % statLogFrequency == 0) {
            long avgTime = stats.totalTime / stats.count;
            long runningAvg = (stats.totalTime-stats.lastTotalTime) / statLogFrequency;
            logger.debug("method: " + methodName + "(), cnt = " + stats.count + ", lastTime = " + elapsedTime + ", avgTime = " + avgTime + ", runningAvg = " + runningAvg + ", maxTime = " + stats.maxTime);
           
            //reset the last total time
            stats.lastTotalTime = stats.totalTime;   
        }
    }
   
    class MethodStats {
        public String methodName;
        public long count;
        public long totalTime;
        public long lastTotalTime;
        public long maxTime;
       
        public MethodStats(String methodName) {
            this.methodName = methodName;
        }
    } 
}


Now, you just need to wire this into your app by referencing this class in your Spring xml and logging config.  When you run your app, you will see stats like this...

WARN  PerfInterceptor - method warning: processRequest(), cnt = 10, lastTime = 1072, maxTime = 1937
TRACE PerfInterceptor - method: processRequest(), cnt = 10, lastTime = 1072, avgTime = 1243, runningAvg = 1243, maxTime = 1937
WARN  PerfInterceptor - method warning: processRequest(), cnt = 20, lastTime = 1466, maxTime = 1937
TRACE PerfInterceptor - method: processRequest(), cnt = 20, lastTime = 1466, avgTime = 1067, runningAvg = 892, maxTime = 1937

As you can see, these stats can provide valuable feedback about class/method performance with very little effort and without modifying any existing Java code.  This information can easily be used to find bottlenecks in your application (generally database or threading related, etc)...good luck

This page has been translated into Spanish language by Maria Ramos from Webhostinghub.com

Friday, April 8, 2011

Camel ActiveMQ Performance Test

Here is a simple unit test (extends CamelTestSupport) to get a feel for how quickly Camel routes add/remove from a JMS queue.  This should give you a ballpark latency estimate (~5ms for my setup).  You can also get some great AMQ performance stats via JMX to monitor an active system.

However, results will vary dramatically depending on thread and AMQ performance/QoS configurations. Refer to the AMQ performance page and the camel-jms page for more information...

private static final Logger logger = Logger.getLogger(AMQRouteTest.class.getName());
@EndpointInject(uri = "mock:mock")
protected MockEndpoint mock;

protected CamelContext createCamelContext() throws Exception {
       CamelContext camelContext = super.createCamelContext();
       String url ="vm://test-broker?broker.persistent=false&broker.useJmx=false";
       ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
       camelContext.addComponent("activemq", 
                                                     JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));
       return camelContext;
   }

@Test
 public void test() throws Exception {
       int messageCnt = 10000, poolSize = 5;
       mock.setMinimumExpectedMessageCount(messageCnt);

       ExecutorService executor = Executors.newFixedThreadPool(poolSize);

       for (int i = 0; i < messageCnt; i++) {
           executor.submit(new Callable() {
               public Object call() throws Exception {
                   template.sendBody("activemq:queue:test",System.currentTimeMillis());
                   return null;
               }
           });
       }
       mock.assertIsSatisfied();
}

@Override
 protected RouteBuilder createRouteBuilder() throws Exception {
      return new RouteBuilder() {
            @Override
             public void configure() throws Exception {
                     from("activemq:queue:test?concurrentConsumers=10")
                     .process(new Processor() {
                            long totalLatency, msgCnt;
                            public void process(Exchange exch) throws Exception {
                                   totalLatency += (System.currentTimeMillis() - exch.getIn().getBody(Long.class));
                                   if(++msgCnt % 1000 == 0) {
                                           logger.info("avgLatency=" + (totalLatency/msgCnt));
                                  }
                           }
                     })
                     .to("mock:mock");
          }
  };
}


Monday, January 3, 2011

Apache Camel Monitoring

I've seen a lot of discussion about how to monitor Camel based applications.  Most people are looking for the following features: ability to view services (contexts, endpoints, routes), to view performance statistics (route throughput, etc) and to perform basic operations (start/stop routes, send messages, etc).

This post will breakdown the options (that I know of) that are available today (as of Camel 2.8).  If you have used other approaches or know of other ongoing development in this area, please let me know.

JMX APIs

Camel uses JMX to provide a standardized way to access metadata about contexts/routes/endpoints defined in a given application.  Also, you can use JMX to interact with these components (start/stop routes, etc) in some interesting ways.

I recently had some very specific Camel/ActiveMQ monitoring requests from a client.  After looking at the options, we ended up building a standalone Tomcat web app that used JSPs, jQuery, Ajax and JMX APIs to view route/endpoint statistics, manage Camel routes (stop, start, etc) and monitor/manipulate ActiveMQ queues.  It provided some much needed visibility and management features for our Camel/ActiveMQ based message processing application...

CamelContext

If you have a handle to the CamelContext, there are various APIs that can help describe and manage routes and endpoints.  These are used by the existing Camel Web Console and can be used to build custom interface to retrieve and use this information in various ways...

here are some of the notable APIs...

getRouteDefinitions()
getEndpoints()
getEndpointsMap()
getRouteStatus(routeId)
startRoute(routeId)
stopRoute(routeId)
removeRoute(routeId)
addRoutes(routeBuilder)
suspendRoute(routeId)
resumeRoute(routeId)

With a little creativity, you can use these APIs to manage/monitor and re-wire a Camel application dynamically.

Camel Web Console

This console provides web and REST interfaces to Camel contexts/routes/endpoints and allows you to view/manage endpoints/routes, send messages to endpoints, viewing route statistics, etc.

That being said, using this web console with an existing Camel application is tricky at the moment.  It's currently deployed as a war file that only has access to the CamelContext defined in its embedded spring XML file.  Though the entire camel-web project can be embedded and customized in your application if you desire (and know Scalate).  Given my recent client requirements, I opted to build my own basic app using JSPs/JMX as described above.

There has been some recent support for deploying this console in OSGI, where it should be able to view any CamelContexts deployed in the container, etc.  However, I'm yet to see this work...more on this later.

Using Camel APIs

There are also a number of Camel technologies/patterns that can be used to add monitoring to existing routes.

  • wire tap - can add message logging (to a file or JMS queue/topic, etc) or other inline processing
  • advicewith - can be used to modify existing routes to apply before/after operations or add/remove operations in a route
  • intercept - can be used to intercept Exchanges while they are in route, can apply to all endpoints, certain endpoints or just starting endpoints
  • BrowsableEndpoint - is an interface which Endpoints may implement to support the browsing of the exchanges which are pending or have been sent on it.
That being said, it takes some creativity to use these effectively and caution to not adversely affect the routes you are trying to monitor.

 Hyperic HQ

You can use this tool to monitor Servicemix (or any process), but it more geared towards system monitoring and JVM stats.  I didn't find it useful for any Camel specific monitoring. 

HAWTIO - http://hawt.io/
This is a newer tool that has plugins for ActiveMQ, Camel, etc to expose some great information and allow your to perform JMX operations.

jConsole/VisualVM

these are standard JMX based consoles.  They aren't web based and can't be customized (easily anyways) to provide anything more than a tree-like view of JMX MBeans.  If you know where to look though, you can do a lot with it.

summary

These are just some quick notes at this point.  As I learn about other ways of monitoring Camel, I'll update this list and give some more detailed comparison.  Any comments are welcome...


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 21, 2010

practical benefits of Subversion

I recently worked with a legacy version control system and found myself missing Subversion instantly. As a consultant, I often work with clients that are using in-house processes/software to manage project artifacts.  I've grown used to many of SVN's features and just assumed everyone was using something comparable these days. Here are my notes on some of the practical benefits of using Subversion that I think apply to most projects...

core features/benefits
  • atomic commits
    • one transaction to add/update/delete files
    • promotes grouping related changes together in one commit to easily identify and revert
  • full revision history retained for files that are renamed, copied, moved or removed
  • no file locking (by design)
    • file locking is extremely counter-productive (especially for large teams in multiple timezones)
    • SVN's automatic merging and conflict resolution tools make locking unnecessary
  • working copy of files are always writable and all changes are local until committed
    • allows you to easily revert unwanted changes at commit time
  • fast and flexible update/commits
    • all tasks can be done from any level easily (updates, commits, merges, reverts, etc)
  • branching and tagging are cheap operations
    • simple to create a tag/branch and merge between them
  • ease of access to the commit log
    • provides high visibility to changes, file history, integrated file comparison
    • ease of reverting changes to a file or an entire commit
  • easy to setup email triggers (on checkins to keep team informed of changes, etc)
  • integrates with everything
    • windows explorer integration via Tortoise
    • with leading IDEs (Eclipse, IntelliJ)
    • Agile/continuous integration tools (Atlassian, Jira, Fisheye, TeamCity, Hudson, etc.)
    • various websites to provide project/committer stats (Ohloh, etc)
  • ease of setup and administration
benefits in practice (using Windows and Tortoise)
  • syncing up my local environment
    • open Windows Explorer and navigate to the root directory of my project
    • right-click and choose 'TortoiseSVN->Commit'
      • sounds counter-intuitive, but this show me a quick view of uncommitted local changes (aka 'mock commit')
        • reminds me what I was working on
        • lets me right-click on any files and choose 'compare with base' to get an instant diff
      • once I'm recalibrated to the project and any in-progress changes, I cancel the commit...
    • update my local working code
      • switch to another branch (if necessary)
        • if I need to work on another branch than what is currently selected, then I can switch to it easily
        • right-click on project and choose 'TortoiseSVN->Switch'
        • enter the SVN URL of the project I need to switch to
        • click 'OK' to sync up with my local files
      • otherwise, right-click and choose 'SVN Update'
        • this syncs up my local working directory with the latest changes in the repository
        • again, I can right-click on any files to compare them my local copy (to see what has changed)
        • any conflicts are marked (rare)
          • I can choose to either resolve it now or later, choose to use my version, or choose to use the repository version
  • working on bug fixes/enhancements
    • work on a single feature at a time
    • make all related changes, write any necessary unit tests and test locally (of course)
    • once complete, I commit the change...
      • flip back to Explorer (can also be done with Eclipse SVN plugins)
      • right-click on the project and choose 'TortoiseSVN->SVN Update' (optional)
        • only necessary if you are working with a large development team or its been a while since I last updated from SVN
        • this will insure that there weren't any other changes that might affect my commit
      • right-click on the base project directory and choose 'TortoiseSVN->SVN Commit'
        • dialogue box comes up to review my changes
        • right-click on any files in question, revert as necessary
        • check/uncheck the files I want to commit
        • enter a quick comment referencing the bug/enhancement worked on and a description of the change
        • click 'OK' to commit the changes
  • working on major refactoring or large feature development
    • I don't want this to affect the trunk, so I create a new development branch
    • right-click on the project root and choose 'TortoiseSVN->Branch/Tag'
    • in the dialogue box
      • enter a new directory for your branch (generally /branches/<branch name>)
      • enter a comment about the purpose of the branch
      • click 'OK'...
    • switch your local working directory to use the branch you just created (see instructions above)
    • that is it...you now have a development branch (whole process takes about 30 seconds unless you have a large project)
summary
Overall, I think Subversion provides many productivity/quality control benefits and can even prove cost-effective to switch to mid-project.  Given that most open source Java development projects use SVN, I feel pretty confident that it continues to be a solid choice for the most projects.

Wednesday, August 18, 2010

managing Camel routes with JMX APIs

here is a quick example of how to programmatically access Camel MBeans to monitor and manipulate routes...

first, get a connection to a JMX server (assumes localhost, port 1099, no auth)
note, always cache the connection for subsequent requests (can cause memory utilization issues otherwise)

JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi");
JMXConnector jmxc = JMXConnectorFactory.connect(url);
MBeanServerConnection server = jmxc.getMBeanServerConnection();

use the following to iterate over all routes and retrieve statistics (state, exchanges, etc)...

ObjectName objName = new ObjectName("org.apache.camel:type=routes,*");
List<ObjectName> cacheList = new LinkedList(server.queryNames(objName, null));
for (Iterator<ObjectName> iter = cacheList.iterator(); iter.hasNext();)
{
    objName = iter.next();
    String keyProps = objName.getCanonicalKeyPropertyListString();
    ObjectName objectInfoName = new ObjectName("org.apache.camel:" + keyProps);
    String routeId = (String) server.getAttribute(objectInfoName, "RouteId");
    String description = (String) server.getAttribute(objectInfoName, "Description");
    String state = (String) server.getAttribute(objectInfoName, "State");
    ...
}

use the following to execute operations against a Camel route (stop,start, etc)

ObjectName objName = new ObjectName("org.apache.camel:type=routes,*");
List<ObjectName> cacheList = new LinkedList(server.queryNames(objName, null));
for (Iterator<ObjectName> iter = cacheList.iterator(); iter.hasNext();)
{
    objName = iter.next();
    String keyProps = objName.getCanonicalKeyPropertyListString();
    if(keyProps.contains(routeID))
    {
        ObjectName objectRouteName = new ObjectName("org.apache.camel:" + keyProps);
        Object[] params = {};
        String[] sig = {};
        server.invoke(objectRouteName, operationName, params, sig);
        return;
    }
}

summary

These APIs can easily be used to build a web or command line based tool to support remote Camel management features. All of these features are available via the JMX console and Camel does provide a web console to support some management/monitoring tasks.

See these pages for more information...
http://camel.apache.org/camel-jmx.html
http://camel.apache.org/web-console.html



Tuesday, August 17, 2010

managing ActiveMQ with JMX APIs

here is a quick example of how to programmatically access ActiveMQ MBeans to monitor and manipulate message queues...

first, get a connection to a JMX server (assumes localhost, port 1099, no auth)
note, always cache the connection for subsequent requests (can cause memory utilization issues otherwise)

JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi");
JMXConnector jmxc = JMXConnectorFactory.connect(url);
MBeanServerConnection conn = jmxc.getMBeanServerConnection();

then, you can execute various operations such as addQueue, removeQueue, etc...

String operationName="addQueue";
String parameter="MyNewQueue";
ObjectName activeMQ = new ObjectName("org.apache.activemq:BrokerName=localhost,Type=Broker");
if(parameter != null) {
    Object[] params = {parameter};
    String[] sig = {"java.lang.String"};
    conn.invoke(activeMQ, operationName, params, sig);
} else {
    conn.invoke(activeMQ, operationName,null,null);
}

also, you can get an ActiveMQ QueueViewMBean instance for a specified queue name...

ObjectName activeMQ = new ObjectName("org.apache.activemq:BrokerName=localhost,Type=Broker");
BrokerViewMBean mbean = (BrokerViewMBean) MBeanServerInvocationHandler.newProxyInstance(conn, activeMQ,BrokerViewMBean.class, true);

for (ObjectName name : mbean.getQueues()) {
    QueueViewMBean queueMbean = (QueueViewMBean)
           MBeanServerInvocationHandler.newProxyInstance(mbsc, name, QueueViewMBean.class, true);

    if (queueMbean.getName().equals(queueName)) {
        queueViewBeanCache.put(cacheKey, queueMbean);
        return queueMbean;
    }
}

then, execute one of several APIs against the QueueViewMBean instance...

queue monitoring - getEnqueueCount(), getDequeueCount(), getConsumerCount(), etc...

queue manipulation - purge(), getMessage(String messageId), removeMessage(String messageId), moveMessageTo(String messageId, String destinationName), copyMessageTo(String messageId, String destinationName), etc...

summary
The APIs can easily be used to build a web or command line based tool to support remote ActiveMQ management features. That being said, all of these features are available via the JMX console itself and ActiveMQ does provide a web console to support some management/monitoring tasks.

See these pages for more information...

http://activemq.apache.org/jmx-support.html
http://activemq.apache.org/web-console.html


Camel exception handling overview

Here are some notes on adding Camel (v2.3) exception handling to a JavaDSL route.  There are various approaches/options available.  These notes cover the important distinctions between approaches...

default handling
The default mode uses the DefaultErrorHandler strategy which simply propagates any exception back to the caller and ends the route immediately.  This is rarely the desired behavior, at the very least, you should define a generic/global exception handler to log the errors and put them on a queue for further analysis (during development, testing, etc).

onException(Exception)
    .to("log:GeneralError?level=ERROR")
    .to("activemq:GeneralErrorQueue");

try-catch-finally
This approach mimics the Java for exception handling and is designed to be very readable and easy to implement.  It inlines the try/catch/finally blocks directly in the route and is useful for route specific error handling.

from("direct:start")
    .doTry()
        .process(new MyProcessor())
    .doCatch(Exception.class)
        .to("mock:error");
    .doFinally()
        .to("mock:end");

onException
This approach defines the exception clause separately from the route.  This makes the route and exception handling code more readable and reusable.  Also, the exception handling will apply to any routes defined in its CamelContext.

from("direct:start")
    .process(new MyProcessor())
    .to("mock:end");

onException(Exception.class)
    .to("mock:error");

handled/continued
These APIs provide valuable control over the flow.   Adding handled(true) tells Camel to not propagate the error back to the caller (should almost always be used).  The continued(true) tells Camel to resume the route where it left off (rarely used, but powerful).  These can both be used to control the flow of the route in interesting ways, for example...

from("direct:start")
    .process(new MyProcessor())
    .to("mock:end");

//send the exception back to the client (rarely used, clients need a meaningful response)
onException(ClientException.class)
    .handled(false)    //default
    .log("error sent back to the client");

//send a readable error message back to the client and handle the error internally
onException(HandledException.class)
    .handled(true)
    .setBody(constant("error"))
    .to("mock:error");

//ignore the exception and continue the route (can be dangerous, use wisely)
onException(ContinuedException.class)
    .continued(true);

using a processor for more control
If you need more control of the handler code, you can use an inline Processor to get a handle to the exception that was thrown and write your own handle code...

onException(Exception.class)
    .process(new Processor() {
         public void process(Exchange exchange) throws Exception {
               Exception exception = (Exception) exchange.getProperty(Exchange.EXCEPTION_CAUGHT);
               //log, email, reroute, etc.
         }
    });

Summary
Overall, the exception handling is very flexible and can meet almost any scenario you can come up with.  For the sake of focusing on the basics, many advanced features haven't been covered here.
  
For more details, see these pages on Camel's site...

http://camel.apache.org/error-handling-in-camel.html
http://camel.apache.org/try-catch-finally.html
http://camel.apache.org/exception-clause.html

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

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