Setting up a JMS bridge between Weblogic and ActiveMQ

Almost four years ago, I wrote about how to setup a JMS bridge between Weblogic and HornetQ. Lately, I’ve had to research how to do the same work with ActiveMQ. Here you have my findings. As it was for HornetQ, the first step was to copy the client libraries to a folder residing in a filesystem of my Weblogic server, in the case of ActiveMQ these files are:

  • activemq-client-5.10.0.jar
  • hawtbuf-1.10.jar
  • slf4j-api-1.7.5.jar

Later on, I set the PRE_CLASSPATH variable pointing it to these libraries into the script setDomainEnv. Creating messaging destinations is more or less the same job as it was for HornetQ, you just have to change the initial context factory and connection url parameters:

  <name>JMS Bridge Destination-Target</name>

But the former configuration is not enough, because ActiveMQ hasn’t his own JNDI provider (I had ActiveMQ as a JMS provider for a ServiceMix ESB) and requires a file with the mappings between physical destinations and tha jndi ones, but, how to configure the properties file in the context of a Weblogic messaging bridge? Here is the trick: create a JAR archive containing the file and put the JAR in the CLASSPATH (the same way at it was described before for activemq-client-5.10.0.jar). The steps to create the JAR archive are:

  • Create a file called with the following entries:

connectionFactoryNames=ConnectionFactory,XAConnectionFactory queue.TestQueue=TestQueue

  • Create the archive with the following command:

jar cvf jndi.jar

I found this trick in this post, after have tested many different configurations, including the setup of a Weblogic Foreign JMS Server, without success. Finally, I’d like to point out that I am not completely happy with this setup because it has an obvious drawback: you have modify and redeploy the jndi.jar archive every time you add a new queue or topic, so suggestions are welcome!!!


Working with Oracle XMLType and JPA over Weblogic

I’ve been working with the object type of Oracle databases for XML for a long time, but always in the context of PL/SQL programming. Last week,  I developed a Java EE module that made use of JPA entities, supported by tables with SYS.XMLType columns, so I’d like to share my findings with an example.

First of all, here you have the creation sentence of a table that offers persistence to a simple messaging interface:

create table messages
    message_id     number  constraint message_pk primary key,
    reception_date date    not null,
    msg_content    xmltype not null 
                           constraint message_msg_content_ck check(
                              xmlisvalid(msg_content) = 1)
  xmltype column msg_content store as clob xmlschema
  element "Messages";

This is an excerpt of a JPA entity that could represent the former table:

package com.wordpress.fcosfc.test.messaging;


import org.eclipse.persistence.annotations.Customizer;

@Table(name = "MESSAGES")
public class Messages implements Serializable {

    @Column(name = "MESSAGE_ID", nullable = false)
    private BigDecimal messageId;

    @Column(name = "RECEPTION_DATE", nullable = false)
    private Date receptionDate;

    @Column(nullable = false, name ="msg_content")    
    private String msgContent;


I’m sure you’ve realized that there is an special annotation Customizer, which makes reference to this class:

package com.wordpress.fcosfc.test.messaging;

import org.eclipse.persistence.config.DescriptorCustomizer;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.mappings.xdb.DirectToXMLTypeMapping;

public class XMLTypeAttributeCustomizer implements DescriptorCustomizer {

    public void customize(final ClassDescriptor descriptor) throws Exception {
        final DirectToXMLTypeMapping mapping = new DirectToXMLTypeMapping();


This class has a method that changes the default mapping of the EclipseLink JPA provider in order to use the proper type from Oracle: SYS.XMLType.

Finally, I’d like to point out that the first time I deployed my module over an Oracle Weblogic 10.3.5 application server I got a ClassNotFoundException: oracle/xdb/xmltype , so I had to extend my Weblogic domain in order to support Oracle XMType. Here you have my reference about how to do it, I just followed the instructions to support Oracle XDB.


Weblogic: Interoperating with Oracle AQ JMS. A tip for sending messages

I usually work with Oracle Streams Advanced Queuing (AQ) integrated with Weblogic. In PL/SQL programs you can set the exception queue where you want to move the messages that couldn’t be delivered to their destinations, when you send a message, for example:

  enq_msgid raw(16) ;
  eopt      dbms_aq.enqueue_options_t;
  mprop     dbms_aq.message_properties_t;
  mprop.priority        := 1;
  mprop.exception_queue := 'test_exception_q';
  message               :=$_jms_text_message.construct() ;
  message.set_text('This is a Test') ;
  dbms_aq.enqueue(queue_name => 'test_q', 
                  enqueue_options => eopt,
                  message_properties => mprop, 
                  payload => message, 
                  msgid => enq_msgid) ;


But, how to set the exception queue when you’re programming in Java, in the context of an integration between Oracle AQ and Weblogic? The solution I’ve found is to set the string property called JMS_OracleExcpQ to the message with the name of the Oracle AQ exception queue, for example:

javax.jms.TextMessage msg = jmsSession.createTextMessage();
msg.setStringProperty("JMS_OracleExcpQ", "TEST.TEST_EXCEPTION_Q");
msg.setText("This is a Test");

An important advice: put the name in uppercase and preceded by the name of the schema.

Finally, I’d like to point out that this is a good solution in the context of an integration between Oracle AQ and Weblogic, but makes the code non portable, if you want to change the messaging provider of your Weblogic Application Server.


Trying to set up a JMS bridge between HornetQ and Oracle AQ

I’ve been interested in setting up a JMS bridge between HornetQ and Oracle Advanced Queuing (AQ) for a while, even I wrote about this issue in a response to a question of the HornetQ user’s forum. I resume the matter in this post with some improvements, although, to be perfectly honest, I am not happy with the configuration.

In theory, the bridge is possible because both systems are JMS 1.1. compliant. If you use a HornetQ 2.2.5 standalone installation, you simply have to add some managed beans to the hornetq-beans.xml file, as is described in the user manual. The key point here is to use the proper connection factory and set up the destination following the rules of the Weblogic manual: “Interoperating with Oracle AQ JMS”. Here you have an excerpt of the hornetq-beans.xml file:

<bean name="JMSBridge">
    <!-- concatenate JMS messageID to the target's message header -->
<!-- TargetCFF describes the ConnectionFactory used to connect to the target destination -->
<bean name="TargetCFF">
      <inject bean="TargetJNDI" />
<!-- TargetDestinationFactory describes the Destination used as the target -->
<bean name="TargetDestinationFactory">
      <inject bean="TargetJNDI" />
<!-- JNDI is a Hashtable containing the JNDI properties required -->
<!-- to connect to the *target* JMS resources                    -->
<bean name="TargetJNDI">
    <map keyClass="java.lang.String" valueClass="java.lang.String">

The former configuration runs properly with the DUPLICATES_OK quality of service, but when you moves to a ONCE_AND_ONLY_ONCE one, changing the TargetCFF to XAQueueConnectionFactory, you get a NullPointerException:

  oracle.jms.AQjmsException: Error creating the db_connection
    at oracle.jms.AQjmsDBConnMgr.getConnection
    at oracle.jms.AQjmsDBConnMgr.
    at oracle.jms.AQjmsXAConnection.
    at oracle.jms.AQjmsXAQueueConnectionFactory.createAllXAConnection
    at oracle.jms.AQjmsXAQueueConnectionFactory.createXAQueueConnection

After a research on Oracle Support notes, I found that the Oracle API has a bug (10102373) that it will be fixed on the future release 12.1 There are workarounds for not receiving duplicate messages, for example: to save the JMS Message ID in a Oracle table and implement a unique index on that column, you have to take into account that the JMS Messege ID sent by HornetQ is a property that can be recovered with the method get_string_property of the Oracle type aq$_jms_message.

But, why Weblogic can interoperate with Oracle AQ in XA configurations? I suspect that the reason is because uses datasources with pre-created database connections. So, I’ve tried to deploy the bridge within JBoss AS 6.0.0, with HornetQ as its default JMS provider. First of all, I created an Oracle XA datasource. After that, I set up the configuration file jms-bridge-jboss-beans.xml in a similar way as before, the only change is to change the db_url parameter by the parameter datasource:

<bean name="TargetJNDI">
    <map keyClass="java.lang.String" valueClass="java.lang.String">

But, when I tried to run the former configuration, the bridge didn’t start. Another bug, a HornetQ one in this case, prevented me from reaching my goal. To be perfectly honest, I didn’t patch the installation, but I restart the managed bean through the JMX console and I got another exception, a ClassCastException, because JBoss pass a wrapped Oracle connection to the class AQjmsInitialContextFactory, which is waiting for an native internal connection. I really felt powerless!

Finally, I adopted the solution of setting up an Oracle Weblogic server as a mediator,  the guru Edwin Biemond describes this configuration in this article.

Security notes about Hornetq as a JBoss JMS provider

I’ve been recently involved in a project where my client had to share information with some partners, using HornetQ 2.2.5 queues deployed on a JBoss 4.2.1 GA application server, and I had to face up to a security problem. Here you have the case: the first step that a remote client has to perform when it tries to send a message to a queue is to lookup for a connection factory and the queue in a JNDI tree; at this point, you should not simply open your JBoss JNDI port (1099 by default), even having configured your firewall to open the port just to your partners’ servers and having an user authentication process for JNDI, because they might list all the names of your global JNDI namespace and exploit any security bug you may have. On the other hand, although I would have opened the port, our JBoss application server runs into a demilitarized zone (DMZ) with a NAT (Network Address Translation) standard configuration, in this situation you can’t use RMI.

The solution to my problem was to force the partners to access JNDI over HTTP an secure that access in a manner that they  just could perform lookup operations over a controlled read-only context, so they got their connection factories and queues from that context and, later on, opened their JMS sessions, through a HTTPS tunnel, after an user authentication process.

In order to run a basic test case,  the first step is to create a role for the remote users (named remoteRole in this example) and another for local ones (localRole) on JBoss. On the other hand, I created one key store for the SSL connection:

keytool -genkeypair -alias test -keyalg RSA -keysize 1024 -dname OU=TEST,CN=TEST,CN=LOCAL
        -keypass test1234 -keystore hornetq.test.keystore -storepass test1234

The following task is to deploy the netty servlet that provide the HTTP transport, please follow this link where you have the WAR file I setup.  The next step is to edit the file  hornetq-configuration.xml file  of the HornetQ installation and to add a servlet connector (please, notice that the path to the test keystore is referred to the client file system and you have to provide it with the keystore) and its corresponding acceptor :

   <connector name="netty-servlet">
      <param key="host" value="${jboss.bind.address:localhost}"/>
      <param key="port" value="8443"/>
      <param key="use-servlet" value="true"/>
      <param key="servlet-path" value="/messaging/HornetQServlet"/>
      <param key="ssl-enabled" value="true"/>
      <param key="key-store-path" value="C:\\Software\\KeyStores\\hornetq.test.keystore"/>
      <param key="key-store-password" value="test1234"/>

   <acceptor name="netty-invm">
      <param key="use-invm" value="true"/>
      <param key="host" value="org.hornetq"/>

The following task is to be sure that the HTTPS connector of the JBoss 4.2.1 AS is running, if not you have to edit the file server.xml located in the folder \deploy\jboss-web.deployer

I also add a security constraint to this  hornetq-configuration.xml configuration file, so the remote users just can send messages to our queues:

  <security-setting match="jms.queue.ReadOnly.#">
    <permission type="consume" roles="localRole"/>
    <permission type="send" roles="remoteRole"/>

The following task is to edit the hornetq-jms.xml file and add a connection factory and a queue, deployed under the readonly context:

<connection-factory name="ReadOnly.NettyConnectionFactory">
    <connector-ref connector-name="netty-servlet"/>
    <entry name="readonly/XAConnectionFactory"/>
<queue name="ReadOnly.TestQueue">
  <entry name="readonly/TestQueue"/>

The next step is to code a basic messages producer, in order to be used by the remote part:

public class RemoteJMSProducer {

    public void sendMessages() {
        ConnectionFactory connectionFactory;
        Connection connection = null;
        Session session = null;
        Queue queue;
        MessageProducer producer;
        TextMessage message;
        Context initialContext;
        Properties jndiConfig;

        try {
            jndiConfig = new Properties();
            initialContext = new InitialContext(jndiConfig);

            connectionFactory = (ConnectionFactory)
            connection = connectionFactory.createConnection("remoteUser", "test");
            queue = (Queue) initialContext.lookup("readonly/TestQueue");

            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            producer = session.createProducer(queue);
            message = session.createTextMessage();

            for (int i = 0; i < 10; i++) {
                message.setText("This is the test message number " + i);

            System.out.println("Messages sent!");
        } catch (NamingException ex) {
            System.err.println("JNDI exception: " + ex.getMessage());
        } catch (JMSException ex) {
            System.err.println("JMS exception: " + ex.getMessage());
        } finally {
            try {
            } catch (Exception ignore) {
            try {
            } catch (Exception ignore) {

     * @param args the command line arguments
    public static void main(String[] args) {
        RemoteJMSProducer remoteJMSProducer;

        remoteJMSProducer = new RemoteJMSProducer();

The former class doesn’t use the typical org.jnp.interfaces.NamingContextFactory, but the org.jboss.naming.HttpNamingContextFactory as the initial context factory. On the other hand, I’d like to point out that the provider URL is http://remote-jboss-server/invoker/ReadOnlyJNDIFactory. In order to run the example, you need to put the following libraries on your classpath:

  • hornetq-core-client.jar
  • hornetq-jms-client.jar
  • netty.jar
  • concurrent.jar
  • jboss-client.jar
  • jboss-common-client.jar
  • jboss-j2ee.jar
  • jboss-remoting.jar
  • jboss-serialization.jar
  • jbosssx-client.jar

Please, realize that if you try to perform a list or a rename operation, you get an exception.


Tracking of a Weblogic JMS bridge

I’ve been talking about JMS bridges between Weblogic and HornetQ for a while, today I’d like to deal with the issue of tracking, which is especially useful when you need to know the time when a message was dispatched to the destination system.

The idea is to configure Weblogic to debug messaging bridge runtime events, add a custom logging handler that captures and saves these events into a table and to analyze them, in order to track the pass of the messages through the bridge.

Therefore, the first task is to enable the debugging of the messaging bridge events in Weblogic. One of the methods to achieve this goal is to add the following lines to the setDomainEnv.cmd script:

set JAVA_OPTIONS=%JAVA_OPTIONS% -Dweblogic.debug.DebugMessagingBridgeStartup=true
set JAVA_OPTIONS=%JAVA_OPTIONS% -Dweblogic.debug.DebugMessagingBridgeRuntime=true

The next step is to create a table to give persistence to the events:

(log_id        NUMBER              CONSTRAINT wl_log_pk PRIMARY KEY,
 log_timestamp TIMESTAMP           NOT NULL,
 msg_id        VARCHAR2(25 CHAR)   NOT NULL,
 log_level     VARCHAR2(25 CHAR)   NOT NULL,
 subsystem     VARCHAR2(50 CHAR)   NOT NULL,
 message       VARCHAR2(4000 CHAR) NOT NULL);

MAXVALUE 999999999999

The following task is to create a custom logging handler that will capture and save the events into the former table (this class has references to a properties file, where I put the parameters needed to connect to the Oracle database):

public class WLCustomLoggingHandler extends Handler {
    private Connection dbConn = null;
    private PreparedStatement psmt = null;

    public WLCustomLoggingHandler() throws IOException,
                                           SQLException {

        Properties dbProperties;

        dbProperties = new Properties();
        this.dbConn =
        this.psmt =
                this.dbConn.prepareStatement("INSERT INTO wl_log " +
                                             "(log_id, log_timestamp, msg_id, " +
                                             "log_level, subsystem, message) " +
                                             "VALUES(wl_log_s.nextval, ?, ?, ?, ?, ?)");

        this.setErrorManager(new ErrorManager() {
            public void error(String msg, Exception ex, int code) {
                System.err.println("Error reported by TestWLLoggingHandler "
                                   + msg + ex.getMessage());

    public void publish(LogRecord record) {
        WLLogRecord wlLogRecord = (WLLogRecord)record;
        if (this.isLoggable(wlLogRecord)) {
            try {
                psmt.setTimestamp(1, new Timestamp(wlLogRecord.getMillis()));
                psmt.setString(2, wlLogRecord.getId());
                psmt.setString(3, wlLogRecord.getLevel().getName());
                psmt.setString(4, wlLogRecord.getLoggerName());
                psmt.setString(5, wlLogRecord.getMessage());
            } catch (SQLException ex) {
                this.reportError("WLCustomLoggingHandlerpublish: ",

    public void flush() {
        try {
        } catch (SQLException ex) {
            this.reportError("WLCustomLoggingHandlerflush: ",

    public void close() throws SecurityException {
        try {
        } catch (SQLException ex) {
            this.reportError("WLCustomLoggingHandlerclose: ",

We just want to analyze the events regarding to the messaging bridge, so we have to create a logging filter:

public class WLCustomLoggingFilter implements Filter {
    public WLCustomLoggingFilter() {

    public boolean isLoggable(LogRecord record) {
        if (record instanceof WLLogRecord) {
            WLLogRecord wlLogRecord = (WLLogRecord)record;

            return wlLogRecord.getSubsystem().equals("MessagingBridge") ||
        } else {
            return false;

The next step is to code a Weblogic startup class:

public class WLCustomLoggingHandlerStartupClass {
    public WLCustomLoggingHandlerStartupClass() {

    public void configureLogger() {
        Logger logger = null;
        Handler handler = null;

        try {
            logger = LoggingHelper.getServerLogger();
            handler = new WLCustomLoggingHandler();
            handler.setFilter(new WLCustomLoggingFilter());
        } catch (Exception ex) {
            System.err.println("WLCustomLoggingHandlerStartupClass.configureLogger: "
                               + ex.getMessage());
            try {
            } catch (Exception ignore) {

    public static void main(String[] args) {
        WLCustomLoggingHandlerStartupClass testWLCustomLoggingHandlerStartupClass =
            new WLCustomLoggingHandlerStartupClass();

This class has to be configured in Weblogic by going to the Enviroment->Startup and Shutdown Classes of the console (obviously, the corresponding jar file containing the former code has to be available on the weblogic classpath):

Weblogic Startup and Shutdown Classes
The last step is to analyze the log entries in order to know when each message is dispatched to its destination, when the bridge was up and running, etc. MessagingBridge Subsystem Messages are helpful to achieve this goal, especially:

  • BEA-200028: The bridge “arg01” has started transferring messages.
  • BEA-200024: Bridge “arg0” refused to obtain connections and transfer any messages, because it has been stopped or suspended, or is shutting down.
  • BEA-200015: An error occurred in bridge “arg0” during the transfer of messages (e).

But, the pass of a message through a bridge has to be discovered by analyzing the log entries with id BEA-000000, of course the sender program has to save the message and its ID on persistent storage at the time it sends it. The bridge dequeues each message from the source and enqueues it to the destination, all in the context of a XA batch transaction (10 messages by default):

03/03/12 10:12:11,859000000	"Bridge: TestBridge (processMessages()) received message:
                                 JMS Message Class: TextMessage
                                 JMSMessageID: ID:B3AD885BC54B4391976BEDA9EC00E8F4
                                 JMSCorrelationID: null
                                 JMSDeliveryMode: PERSISTENT
                                 JMSDestination: TestQueue
                                 JMSExpiration: 0
                                 JMSPriority: 8
                                 JMSRedelivered: false
                                 JMSReplyTo: null
                                 JMSTimestamp: 1330851452000 (Sun Mar 04 09:57:32 CET 2012)
                                 JMSType: null
                                 Transaction Id: BEA1-00018D19CC5B9E472B1E
                                 This is a test message: 010"
03/03/12 10:12:11,859000000	"Bridge: TestBridge (processMessages()) successfully sent message:
                                 JMS Message Class: TextMessage
                                 Old JMS MessageID: ID:B3AD885BC54B4391976BEDA9EC00E8F4
                                 New JMS MessageID: ID:2064fac7-65da-11e1-9824-005056c00008
                                 This is a test message: 010"
03/03/12 10:12:12,671000000	Bridge: TestBridge (processMessages()) committed the transaction


Weblogic: receiving messages from a remote HornetQ destination

I’ve talked in former posts about setting up a JMS bridge between Weblogic and HornetQ and how to secure that connection, but the bridge is just appropriate for sending messages from Weblogic to HornetQ, the proper way for receiving data send to HornetQ queues in Weblogic is to implement a Message Driven Bean (MDB), as you can read on the documentation of Weblogic. How to connect the MDB deployed in Weblogic to a HornetQ destination? After a research, I think that the best answer is a Foreign Server.

First of all, I copied the following HornetQ client libraries to a folder residing in a filesystem of my Weblogic server:

  • hornetq-core-client.jar
  • hornetq-jms-client.jar
  • netty.jar
  • jnp-client.jar
  • jboss-logging.jar

Later on, I set the PRE_CLASSPATH variable pointing it to these libraries into the script setDomainEnv and started Weblogic. The next step was to create a new JMS System Module on the console, accepting the defaults.  After that, I edited the module and setup a new Foreign Server with the defaults and I entered its configuration: Weblogic Foreign Server Main Configuration

The following step was to link the destinations (topics and queues) and the connection factories I previously setup on HornetQ. To do this I used the wizards provided by the Weblogic console, it’s easy, I just have to point out that I had to edit the configuration of my connection factory to add the security credentials:

Details of a Foreign Connection Factory

Finally, I mapped the queue and the connection factory in my MDB, here you have an example:

@MessageDriven(mappedName = "jms/Test/TestQueue")
         connectionFactoryJNDIName = "jms/Test/TestXAConnectionFactory")
public class TestMDB implements MessageListener {
    static final Logger logger = LoggingHelper.getServerLogger();

    public void onMessage(Message message) {
        TextMessage msg = null;

        try {
            if (message instanceof TextMessage) {
                msg = (TextMessage) message;
      "MESSAGE BEAN: Message received: " + msg.getText());
            } else {
                logger.warning("Message of wrong type: " + 
        } catch (JMSException e) {
            logger.severe("TestMDB.onMessage: JMSException: " + e.toString());
        } catch (Throwable te) {
            logger.severe("TestMDB.onMessage: Exception: " + te.toString());