Thursday, January 21, 2016

Hawkular Command Gateway Clients

This document is to briefly explain how clients can use the command gateway to send requests to the Hawkular Server and receive responses. The typical use case (though certainly not the only way to use this feature) is for a browser to send requests to Hawkular WildFly Agents routed through the Hawkular Server, with the agent’s responses routed back to the browser (back through the server intermediary) that sent the request.

Brief Summary

The typical workflow is the following:
  1. Client makes a websocket connection to the server.
  2. Client immediately receives a WelcomeResponse JSON message from the server notifying the client what its session ID is.
  3. Client can send JSON requests over the Web Socket connection.
  4. Client can receive JSON responses over the Web Socket connection. These messages are received asynchronous from its requests and may not even be tied to a specific request.
  5. Client can keep the connection open as long as it wants, and can disconnect when it wants.

Make the Connection

Clients first need to make a WebSocket connection to the Hawkular Server. That is done by connecting to the URL: "ws://:8080/ui/ws".

Note that a secure connection via SSL can be made by connecting to “wss://:8443” but this requires the server to be configured properly with a certificate and a security realm defined. Such details are out of scope for this document. For more, see http://www.hawkular.org/docs/user/secure-comm.html

Receiving the Welcome Message

For each client websocket connection that is made, the server sends an initial WelcomeResponse message immediately to it. This message contains the client’s session ID. This is the session ID that the server will use to identify that client. This session ID is actually not needed by the client today, but it is available for future functionality. For now, clients can actually ignore this session ID.

An example WelcomeResponse message that a client could receive is:

WelcomeResponse={“sessionId”:”abc:123:xyz:789”}

The WelcomeResponse JSON schema is defined here.

Sending a Request Message

Once connected, clients can immediately begin sending any valid request over the web socket connection. Because clients are able to send in different kinds of requests, the client must ensure the request message’s JSON content is prefixed with the JSON schema name followed by “=” . Valid JSON schemas can be found here.

Within the JSON content, there must be an authentication node containing the credentials of the client. The authentication node’s JSON schema is defined here.

So, for example, if you want to execute the “Undeploy” operation on a web deployment resource, the request sent over the web socket connection will look something like this:

ExecuteOperationRequest={“authentication”:{“username”:”joe”,”password”:”pw”},“operationName”:”Undeploy”,”resourcePath”:”/t;tenant-id/e;env-id/r;resource-id-of-the-deployment-resource”}

Note that in order for a client to request something related to a specific resource in inventory, that client must know the resource’s “resource path” as defined in Hawkular Inventory. See the Hawkular Inventory REST API documentation for more details on how to obtain inventory data such as these resource paths.

Receiving a Response Message

The clients can receive messages in the same format as it sent them. In other words, the JSON content received by the client will be prefixed with the JSON schema name that is to be used to properly parse the JSON content received.

For example, when a client sends a request message destined to an agent, the server will immediately send a GenericSuccessResponse back to the client. This means the request was received by the server and has been successfully forward to the agent (note: it does not mean the request was successfully processed by the agent - the agent will send its own success or failure response message back once it processes the original request). Such a response message received by the client would look like this:

GenericSuccessResponse={“message”:”The request has been forwarded to the feed [foo]”}

Sending Binary Content

Sometimes a client needs to send raw binary data as part of a request (e.g. when a client wants to deploy a web application, it sends a DeployApplicationRequest along with the application’s .war file). To do this, the client sends the JSON message as usual (i.e. in the form “json-schema={json content}”) but immediately following the final curly brace of the JSON content, the client should stream the binary content.

Friday, January 1, 2016

Hawkular WildFly Agent API For Your Own Inventory and Metrics

The Hawkular WildFly Agent is well into development and is coming along nicely. It provides a way to monitor one or more WildFly or EAP application servers (including the one it is deployed into). It communicates with a Hawkular Server where the agent stores its inventory and metric data via the Hawkular Inventory and Hawkular Metrics components. You can use the Hawkular GUI to interact with your managed application servers: view historical graphs of metric data, deploy and undeploy applications, etc.

But the Hawkular WildFly Agent provides a hidden gem that might be useful to those developers that want to store metrics in a metric storage facility for later reporting and graphing but don't want to take the time to implement that storage facility. This hidden gem also provides a way for developers to store their own managed resource definitions in an inventory storage facility but, again, don't want to implement all of the backend required for such a thing.

The Hawkular WildFly Agent already integrates with Hawkular Inventory and Hawkular Metrics - this is to enable the agent to be able to store its own inventory and metrics. It makes sense to open that up for applications to use so they, too, can store inventory and metrics. To allow for this, Hawkular WildFly Agent stores a helpful object in JNDI called HawkularWildFlyAgentContext under the name "java:global/hawkular/agent/api" (side note: the agent can be told to bind this object to a different JNDI name if you want; it can also be told to not bind this hidden gem in JNDI at all if you do not wish to expose this feature).

The API this exposes is very simple - you can store or remove resources from inventory, and you can store metric data and availability data (availability data is just a "special" kind of metric that allows you to store "UP", "DOWN" or "UNKNOWN" availability states).

Any application that is deployed in the same WildFly or EAP application server as the agent can use this API by obtaining the agent context object via JNDI. A simple example of how you can obtain this agent context object from JNDI can be seen in a test war that is used in the agent integration tests - its a singleton EJB that gets this context object injected via @Resource. See the HawkularWildFlyAgentProvider class.

Once that HawkularWildFlyAgentContext object is obtained, your application can use it to store inventory, metric, and availability data. Note that you do not have to use all of these. For example, if you just want to store metrics in a historical time-based data store, just use the Metric Storage API that you get from the agent context object. This will send your data for storage to Hawkular Metrics. You could then do whatever you want with your data later - Hawkular Metrics provides a REST interface and some clients that you can use to query and report on your metric data.

The example test war can show you how the API is used to do these things - see the test MyAppServlet.java. This is just for integration testing, so it doesn't do anything earth-shattering, but it does show you how the API is used to create and remove managed resources from inventory, store metric data, and store availability data.

This feature of the Hawkular WildFly Agent is a relatively minor feature considering all the other main requirements that the agent must fulfill, but since it is rather hidden I decided to talk about it here.

Thursday, January 15, 2015

Hawkular Bus

Work under the new Hawkular umbrella has begun. More information about this new project will trickle out more and more from the team members in the coming weeks and months ahead. There's already a Twitter feed and a developer mailing list.

Here I'll briefly discuss the hawkular-bus work I've done.

The idea is that the hawkular-bus provides a framework to hook into a messaging bus including a Wildfly container that provides all the messaging infrastructure setup for you as well as a convienence API that frees you from the annoying JMS boilerplate code that you typically have to write when it comes to developing bus applications and EJB MDBs in Java.

hawkular-bus also has a REST API that allows any client (Java or non-Java) to produce messages on the bus or consume messages off the bus.

The container that you can use to deploy your bus-based components (be they WARs or EARs or Wildfly module extensions) is called a hawkular-nest. It is simply a pre-configured Wildfly server - it provides the necessary module extensions that give you the messaging infrastructure such that all you need to do is deploy WARs and EARs to it and they can immediately take advantage of the hawkular framework. You can deploy your WARs and EARs directly in the nest module extension (modules/system/layers/base/org/hawkular/nest/main/deployments), thus immediately allowing your applications to be patchable using Wildfly's patching mechanism. In the future, we may want to use this deployment to be able to deploy some kind of "Hawkular Plugin" but nothing has been fleshed out. Right now, WAR and EAR deployments make it easy for you to plug into the hawkular message bus. There is even a hawkular-bus-mdb API that provides an API to allow your MDBs to easily process RPC-like messages (that is, your MDB can not only listen for messages on the bus but then immediately return a response back to the client that sent the message).

I then prototyped a hawkular-audit component that uses hawkular-bus. Hawkular-audit is a server-side component that accepts "audit records" over the bus and places them in a backend storage (today, its just an in-memory H2 database - the one that comes with Wildfly). For example, if you have something that you want to track via an audit trail, that something can put its audit records on the bus and have hawkular-audit store it for you. Your client, if it is Java, can use hawkular-bus API to send the message, or if your client is not Java you can have it use the hawkular-bus REST API to put the message on the bus (for example, using curl).

To try out all this hawkular stuff:

1. Clone both hawkular-bus and hawkular-audit repos
2. Build them by just executing "mvn install" from each repo's root directory.
3. Unzip the distribution from hawkular-audit/hawkular-audit-distro/target and run the "standalone.sh" from the Wildfly's bin/ directory.
4. When the hawkular-audit server starts, it will log its own audit event to record when it started. To see the audit records, point your browser to "http://localhost:8080/hawkular-audit/AuditQueryServlet" and you'll see a simple HTML table with the data.
5. To add your own audit records to the audit trail, run curl to send your audit records over the REST API. For example, try something like this:

    curl -d "body={"subsystem":{"MyComponent":"MySubsystem"},"message":"My audit record message","details":{"key2":"value2","key1":"value1"}}" http://localhost:8080/hawkular-bus/message/AuditQueue?type=queue

Refresh your browser using the same URL mentioned in step 4 above and you'll see your new records.

Hawkular-audit is just a prototype that shows how you can build your own server components to utilize the hawkular-bus and hawkular-nest in order to plug into the bus framework and be able to receive (and send) messages off the bus. In the future, we'll want to cluster the bus so multiple components can talk to each other over one main bus and have clients hook into the bus to send messages to one or more of these server components.

Wednesday, November 12, 2014

Messaging Infrastructure using ActiveMQ


What is rhq-msg?

Before I get into the news about the new rhq-msg repository, let me first take a step back and summarize what rhq-msg is and what I'm trying to accomplish with it.

rhq-msg is a simple messaging API built on top of ActiveMQ and JMS. However, I wanted to isolate the user of the API from as much ActiveMQ and JMS specific classes and code as possible. I wanted a simpler API that provides basic messaging functionality without requiring the user from having to create and manage lots of little specific classes (like JMS Connections, Sessions, Destinations, Consumers, Producers, etc) and without having to know very many specific ActiveMQ details.

I also wanted to ensure that non-Java clients and servers can interact with rhq-msg clients and servers. So the messages that are sent and received from the rhq-msg API are JSON-encoded and thus can be sent to and received by other non-Java endpoints so long as they can handle JSON-encoded messages (ActiveMQ supports non-Java clients, I just wanted to make sure the messages rhq-msg handles can easily flow to/from those non-Java clients as well).

So the point is I have small, simple, easier-to-use messaging API that can talk to non-Java endpoints, but yet still retain all the nice functionality (like guaranteed delivery and things like that) that JMS and ActiveMQ provides.

New Repository for rhq-msg

My past few blog posts were about the prototyping work I'm doing with respect to rhq-msg and rhq-audit.

I just split out rhq-msg and put it in its own rhq-msg repository since it really does belong as a separate project.

I also added a nifty feature to it - you can now use it for request-response workflows. Before, the rhq-msg API really only supported fire-and-forget async messaging. You had a message and you sent it to an endpoint asynchronously and that was that. The problem is sometimes you want a response back, and many times you want to wait for that response to come back in an RPC-like fashion (as opposed to accepting the response asynchrously). I call this a request-response workflow.

Well, the API now supports this. In fact, it supports receiving the response both synchronously (via a Java Future implementation) and asynchronously (via a message listener implementation). More on this below.

A Quick Overview of the API

The main purpose of rhq-msg is to provide a simpler API to do messaging (simpler than, say, JMS). If I can't describe how to send and receive messages via rhq-msg in a couple paragraphs of a blog, then I think I failed :) So let me give a quick overview of what the API calls would look like if you want to send and receive messages. I will cover sending fire-and-forget messages, request-response messaging, and listening for incoming messages.

The main rhq-msg API is found in the rhq-msg-common module.

* Common Code For Both Producers and Consumers

Before I talk about how to send and receive messages, let me introduce the few classes both senders (aka producers) and receivers (aka consumers) use.

Each message that flows through rhq-msg is a BasicMessage. You can subclass that to create your own message types, but all messages must derive from BasicMessage. BasicMessage provides the JSON functionality needed to serialize the messages over the wire.

ConnectionContextFactory connects to your rhq-msg broker and creates contexts for both producers and consumers that are then passed to the MessageProcessor so it knows where to send/receive its messages from.

MessageProcessor provides the API to send and listen for messages.

OK, with that out of the way, let's talk about how to send and listen for messages. For these examples, let's assume you have a broker running on the local machine (127.0.0.1) listening to port 17173, you have a BasicMessage you want to send (or you want to listen for a BasicMessage) and the messages are to be found on a queue named "Foo".

* Sending Fire-and-Forget Messages

Fire-and-forget means you send a message off to an endpoint and forget about it - you don't need or expect a response back. You assume the message broker will deliver the message and the recipient will process the message properly.

   Endpoint endpoint = new Endpoint(Endpoint.Type.QUEUE, "Foo");
   ConnectionContextFactory factory = new ConnectionContextFactory("tcp://localhost:17173");
   ProducerConnectionContext context = factory.createProducerConnectionContext(endpoint);
   MessageProcessor processor = new MessageProcessor();
   processor.send(context, basicMessage);
   factory.close();

Here you create your factory so it connects to your broker. Using the factory, create a producer context. With that new producer context and your basic message, just tell a message processor to send it. That's it. Message is away. You can keep your factory around to create additional contexts which share the connection. But once you are done sending messages, close the factory so it cleans up all resources and closes its connection to the broker. Note that every class you see is a rhq-msg object. No ActiveMQ or JMS classes are used to code this up (though, obviously, under the covers, ActiveMQ and JMS is used heavily).

* Sending Request-Response Messages

Many times when you send a message request, you want a response back. In this example I will show how you can have an RPC-like request-response workflow. I will assume that the remote endpoint will process my BasicMessage and send back to me its own BasicMessage response. Note that, as I mentioned earlier, I could use custom message types (I don't have to use BasicMessage) but those custom message types must always derive from BasicMessage.

   Endpoint endpoint = new Endpoint(Endpoint.Type.QUEUE, "Foo");
   ConnectionContextFactory factory = new ConnectionContextFactory("tcp://localhost:17173");
   ProducerConnectionContext context = factory.createProducerConnectionContext(endpoint);
   MessageProcessor processor = new MessageProcessor();
   Future<BasicMessage> future = processor.sendRPC(context, basicMessage, BasicMessage.class);
   BasicMessage response = future.get(30, TimeUnit.SECONDS);

The first several lines are identical with the fire-and-forget example above. The difference starts with the API call made on the processor - here you call sendRPC() passing in the same context and your outgoing basicMessage request object as before, but you also now pass in the message type of the expected response message. In return, you get a Future object which you can use to retrieve the response when it is received. In this example, it blocks for 30 seconds waiting for the response.

There is another API I won't talk about in detail here, but suffice it to say there is another request-response API you can call on the MessageProcessor (as opposed to sendRPC()) and that is "sendAndListen()". sendAndListen() also allows you to send a request and listen for a response, but this API allows you to give your own message listener so it can wait for and receive the response, rather than go through a Future object. It seems more intuitive and easier to use Future, but in case you want to write your own listener object and listen for the response that way, this is doable. I'll explain the listener API below - it would be the same thing you would need to pass to sendAndListen().

* Listening for Incoming Messages

This last example shows how you implement consumers via rhq-msg API. You implement these via listeners. These listeners are your server-side code - they listen for and accept incoming messages from producers and process those messages. There are two general types: those that do not send responses back, and those that do. I'll cover both in that order.

To listen for "fire-and-forget" messages (that is, messages that are sent that do not require a response sent back to the sender) you implement a BasicMessageListener and hand that listener off to the message processor:

   Endpoint endpoint = new Endpoint(Endpoint.Type.QUEUE, "Foo");
   ConnectionContextFactory factory = new ConnectionContextFactory("tcp://localhost:17173");
   ConsumerConnectionContext context = factory.createConsumerConnectionContext(endpoint);
   MessageProcessor processor = new MessageProcessor();
   processor.listen(context, listener);

where "listener" is a subclass implementation of BasicMessageListener. An example is:

   public class MyCustomListener extends BasicMessageListener<BasicMessage> {
       @Override
       protected void onBasicMessage(BasicMessage receivedMessage) {
          // Process the received message.
       }
   }

Notice that we still create a ConnectionContextFactory (because we still need a connection to the message broker) but we ask that factory to create for us a consumer context this time. We call "listen()" on the message processor, passing to it that consumer context and our custom listener. That listener is now listening for messages to arrive on the "Foo" queue and will process them.

What about request-response processing? If your listener needs to send data back to the sender, it needs to implement a RPCBasicMessageListener. Other than that difference, the main code is still the same:

   Endpoint endpoint = new Endpoint(Endpoint.Type.QUEUE, "Foo");
   ConnectionContextFactory factory = new ConnectionContextFactory("tcp://localhost:17173");
   ConsumerConnectionContext context = factory.createConsumerConnectionContext(endpoint);
   MessageProcessor processor = new MessageProcessor();
   processor.listen(context, listener);

but this time "listener" is a subclass implementation of RPCBasicMessageListener. An example is:

   public class MyCustomRPCListener extends RPCBasicMessageListener<BasicMessage, AnotherMessage> {
       @Override
       protected AnotherMessage onBasicMessage(BasicMessage receivedMessage) {
          // Process the received message.
          AnotherMessage response = ...create your response message object...;
          return response;
       }
   }

Note the onBasicMessage() method now can return a non-void type - the response message type. This return type (the specific response message type) is declared in the generic type definition found in your class definition. The first generic type is that of the expected incoming message type, the second generic type is that of the response message type.

How to Build rhq-msg?

rhq-msg is composed of a set of Maven modules. From the parent root module directory, just run "mvn install" and everything will build, tests will run, and artifacts will be packaged.

There are also Eclipse project files that allow you to work with rhq-msg via M2E (the Eclipse Maven plugin).

How to Run a rhq-msg Broker

If you want to run your own code that utilizes the rhq-msg API, you will need to run a rhq-msg broker (which is really just an ActiveMQ broker). You can run a rhq-msg broker easily in a couple ways. You can run the EmbeddedBroker from the Maven command line or you can install the EmbeddedBroker in a WildFly 8 installation. This EmbeddedBroker code is found in the rhq-msg-broker Maven module.

* Running EmbeddedBroker from the command line

Starting a broker as a standalone process is relatively painless. You can use Maven to do it:

   mvn -Prun-test-broker install

Right now the rhq-msg broker is not packaged with all its dependencies, but if you do it yourself (that is, get all the dependency jars and start Java with the appropriate classpath) you can run straight from the Java command line:

   java -cp <the-appropriate-classpath> -jar rhq-msg-broker-0.1.jar -c broker-config.xml

where "broker-config.xml" is an actual ActiveMQ XML configuration file (you can also pass in a simpler ActiveMQ .properties configuration file if you wish). Examples are test-broker.xml and test-broker.properties.

* Installing EmbeddedBroker in WildFly 8

One of the artifacts within rhq-msg is a WildFly Extension Module that provides a broker. Once installed in WildFly, you will have an rhq-msg broker subsystem running within WildFly itself. It is a handy way to have your own broker running in your own WildFly instance. So this means you can have, for example, an rhq-msg client within a web application running in WildFly and provide your own broker for that client running in the same WildFly instance. Technically, this is useful for any ActiveMQ or JMS client - since this broker is nothing more than an ActiveMQ broker and can serve any client from anywhere, not just those using the rhq-msg API.

First, download and unzip the WildFly 8 app server (I have not tested on WildFly 9+). I'll use <wildfly-install-dir> to indicate where you installed WildFly.

Now install the custom rhq-msg broker WildFly Extension Module into WildFly. You can use the new Maven plugin "wildfly-extension-maven-plugin" to do this - the rhq-msg-broker-wf-extension Maven module has integrated that Maven plugin. I talk about this in a previous blog post. So, simply running this Maven command will install your rhq-msg broker WildFly Extension Module for you:

   mvn -Dorg.rhq.msg.broker.wildfly.home=<wildfly-install-dir> wildfly-extension:deploy

Since this is nothing more than a normal subsystem like all the other subsystems in WildFly, you can use the JBoss CLI to look at its configuration. To poke around, run the JBoss CLI in GUI mode ("jboss-cli.sh --gui") and look for the "org.rhq.msg.broker" subsystem.

In Closing

This is a prototype and was developed just to see how a messaging API around JMS and ActiveMQ can be made simpler and easier to use. I am sure I am missing some pieces of functionality (one such missing piece is security - this currently doesn't handle logging into a secured broker). If you see anything missing, let me know. Feel free to suggest corrections or enhancements. All the code is in github, so play around with it and see how useful it is.

Wednesday, November 5, 2014

Using a Message Broker to Send Audit Messages

One thing I've been working on on the side is a little project that uses a message broker to send and receive "auditing" events. Just briefly, the idea is that any piece of software might want to emit audit messages to log certain events that have occurred so that those events are captured for future reporting purposes. This project (call it rhq-audit for now) can provide a message broker if you need one, along with a high-level API that can be used to both emit and process these audit messages. For example, maybe you want your sales application to record each attempted login by a remote client, or maybe you want to record each sales order that has been submitted. Using the rhq-audit API, audit messages can be fired off on the message bus for later consumption by an rhq-audit consumer whose job it will be to store the audit record in a persistence store that can be used by reporting tools when audit reports need to be generated.

RHQ-Audit doesn't provide any reporting tools, but does provide a compact API that allows you to emit and store audit messages. You can persist your audit messages to a simple log file (see LoggerConsumer) or to a relationship database (see DataSourceConsumer), or to any custom backend (you would just need to implement your own BasicMessageListener and have the AuditRecordProcessor use it as its listener).

I talk a bit more detail on this type of thing in my previous blog on starting out with ActiveMQ. The code now in the rhq-audit repo is a bit different, but the concepts are still the same.

I separated out the message broker stuff (along with a generic and extensible consumer/producer API) into rhq-msg. rhq-audit extends rhq-msg to handle audit events. But the idea is rhq-msg can be used to provide a message bus along with an API for any type of messaging app you want to build.

In addition to the API, an embedded broker that you can use to embed in your VM or run standalone, and an extensible test API, there is also a custom Wildfly module extension that can be used to easily deploy a message broker inside your application server via Maven. See my previous blog on how to install that Wildfly extension via a mvn plugin.

To build and run the tests for rhq-audit and rhq-msg, all you need to do is run "mvn install" from the top level root directory.

Using the new Maven Wildfly Extension plugin to deploy module extensions

Libor is putting together a nice maven plugin to help you deploy your custom Wildfly module extensions to an existing Wildfly or EAP installation.

I decided to integrate it with my rhq-msg-broker-wf-extension project (I talked about my prototype of the rhq-msg work here). What this now allows us to do is deploy a message broker directly in an existing Wildfly or EAP installation via a simple mvn command line.

I won't repeat all of Libor's instructions - just go to his blog I linked above for the full details of how to integrate his mvn plugin in your mvn project - but in short all I had to do was create a snippet of .xml which includes the configuration I want to deploy in the Wildfly or EAP instance's standalone.xml (which includes the subsystem and the socket-binding) and then in the pom just define some settings for the plugin to let it know where to put my extension code and that XML configuration.

In the pom.xml, I have this to define the mvn plugin configuration - notice I allow the user to tell us where the app server is installed via a system property "org.rhq.msg.broker.wildfly.home":

        <plugin>
            <groupId>org.jboss.plugins</groupId>
            <artifactId>wildfly-extension-maven-plugin</artifactId>
            <configuration>
                <moduleZip>${project.build.directory}/${project.build.finalName}-module.zip</moduleZip>
                <jbossHome>${org.rhq.msg.broker.wildfly.home}</jbossHome>
                <modulesHome>modules/system/layers/base</modulesHome>
                <serverConfig>standalone/configuration/standalone.xml</serverConfig>
                <subsystem>${basedir}/src/main/scripts/standalone-subsystem.xml</subsystem>
                <profiles>
                    <profile>default</profile>
                </profiles>
                <socketBinding>${basedir}/src/main/scripts/socket-binding.xml</socketBinding>
                <socketBindingGroups>
                    <socketBindingGroup>standard-sockets</socketBindingGroup>
                </socketBindingGroups>
            </configuration>
        </plugin>

To publish the rhq-msg-broker-wf-extension custom module extension to an already-installed EAP instance, simply run this command (this sets the system property to point to a EAP install directory, and it uses the goal "wildfly-extension:deploy" which tells the mvn plugin to deploy the extension to that EAP installation):

mvn -Dorg.rhq.msg.broker.wildfly.home=/opt/jboss-eap-6.3 wildfly-extension:deploy

At this point, the standalone.xml will have been modified to include the custom module extension's subsystem configuration and the module code will have been copied to the EAP modules directory. At this point, once the app server is started, the module extension will be deployed and running.

Tuesday, July 29, 2014

Starting an ActiveMQ Project with Maven and Eclipse

I'm currently researching and prototyping a new subproject under the RHQ umbrella that will be a subsystem that can perform the emission and storage of audit messages (we're tentatively calling it "rhq-audit").

I decided to start the prototype with ActiveMQ. But one problem I had was I could not find a "starter" project that used ActiveMQ. I was looking for something with basic, skeleton Maven poms and Eclipse project files and some stub code that I could take and begin fleshing out to build a prototype. So I decided to publish my basic prototype to fill that void. If you are looking to start an ActiveMQ project, or just want to play with ActiveMQ and want a simple project to experiment with, then this might be a good starting point for you. This is specifically using ActiveMQ 5.10.

The code is in Github located at https://github.com/jmazzitelli/activemq-start

Once you clone it, you can run "mvn install" to compile everything and run the unit tests. Each maven module has an associated Eclipse project and can be directly imported into Eclipse as-is. If you have the Eclipse M2E plugin, these can be imported using that Eclipse Maven integration.

Here's a quick overview of the Maven modules and a quick description of some of the major parts of the code:

  • /pom.xml
    • This is the root Maven module's pom. The name of this parent module is rhq-audit-parent and is the container for all child modules. This root pom.xml file contains the dependency information for the project (e.g. dependency versions and the repositories where they can be found) and identifies the child modules that are built for the entire project.
  • rhq-audit-common
    • This Maven module contains some core code that is to be shared across all other modules in the project. The main purpose of this module is to provide code that is shared between consumer and producer (specifically, the message types that will flow from sender to receiver).
      • AuditRecord.java is the main message type the prototype project plans to have its producers emit and its consumers listen for. It provides JSON encoding and decoding so it can be sent and received as JSON strings.
      • AuditRecordProcessor.java is an abstract superclass that will wrap producers and consumers. This provides basic functionality such as connecting to an ActiveMQ broker and creating JMS sessions and destinations.
  • rhq-audit-broker
    • This provides the ability to start an ActiveMQ broker. It has a main() method to allow you to run it on the command line, as well as the ability to instantiate it in your own Java code or unit tests.
      • EmbeddedBroker.java is the class that provides the functionality to embed an ActiveMQ broker in your JVM. It can be configured using either an ActiveMQ .properties configuration file or an ActiveMQ .xml configuration file.
  • rhq-audit-test-common
    • The thinking with this module is that there is probably going to be common test code that is going to be needed between producer and consumer. This module is to support this. The intent is for other Maven modules in this project to list this module as a dependency with a scope of "test". For example, some common code will be needed to start a broker in unit tests - including this module as a test dependency will give unit tests that common code.
  • rhq-audit-producer
    • This provides the producer-side functionality of the project. The intent here is to flesh out the API further. This will become rhq-audit's producer API.
      • AuditRecordProducer.java provides a simple API that allows a caller to connect the producer to the broker and send messages. The caller need not worry about working with the JMS API as that is taken care of under the covers.
  • rhq-audit-consumer
    • This provides the consumer-side functionality of the project. The intent here is to flesh out the client-side API further. This will become the rhq-audit's consumer API.
      • AuditRecordConsumer.java provides a simple API that allows a caller to connect the consumer to the broker and attach listeners so they can process incoming messages.
      • AuditRecordListener.java provides the abstract listener class that is to be extended in order to process received audit records. The idea here is that subclasses can process audit records in different ways - perhaps one can store the audit records in a backend data store, and another can log the audit messages in rsyslog.
      • AuditRecordConsumerTest.java provides a simple end-to-end unit test that uses the embedded broker to pass messages between a producer and consumer.
Taking a look at AuditRecordConsumerTest shows how this initial prototype can be tested and shows how audit records can be sent and received through an ActiveMQ broker:

1. Create and start the embedded broker:
VMEmbeddedBrokerWrapper broker = new VMEmbeddedBrokerWrapper();
broker.start();
String brokerURL = broker.getBrokerURL();
3. Connect the producer and consumer to the test broker:
producer = new AuditRecordProducer(brokerURL);
consumer = new AuditRecordConsumer(brokerURL);
2. Prepare to listen for audit record messages:
consumer.listen(Subsystem.MISCELLANEOUS, listener);
3. Produce audit record messages:
producer.sendAuditRecord(auditRecord);
At this point, the messages are flowing and the test code will ensure that all the messages were received successfully and had the data expected.

A lot of the code in this prototype is generic enough to provide functionality for most messaging projects; but of course there are rhq-audit specific types such as AuditRecord involved. The idea is to now flesh out this generic prototype to further provide the requirements of the rhq-audit project. More on that will be discussed in the future. But for now, perhaps this could help others come up to speed quickly with an AcitveMQ project without having to start from scratch.