Today one of our subscriber ziggy asked us using comment if we had any article which would show how to connect to a remote queue in JBoss AS7, hence we created this article which would help ziggy as well as others people also. Earlier versions of JBoss AS 7 where not having an inbuilt ability to connect to a queue remotely which was a huge concern given by the community people and users of JBoss. Hence the JBoss team took all the feedback given to them and have come up with a new version JBoss AS 7.1 Final which has an inbuilt ability to connect to a queue remotely and that too with security enabled by default. We personally are really thankful to the whole team members of JBoss AS 7 for putting this feature in the latest version of JBoss AS .

So in this article we will see how can one send messages from Box-2 [i.e. with IP 20.20.20.20] to a queue which is on the Box-1 [i.e. with IP 10.10.10.10] and those messages can be received by the receiver from the same box which is Box-1using a standalone JAVA code for sending and receiving messages. However you can also do vica-versa, which is sending messages to the queue on the same box and receive those messages from a remote box the steps remain same just the standalone JAVA code for sending and receiving messages would switch there places.

Things to remember

  • You should have the “/jboss-as-7.1.0.Final/bin/client/jboss-client-7.1.0.Final.jar” in the CLASSPATH of the client.
  • The URL would be as below, where 4447 is the remote port
  •  remote://<IP_ADDRESS>:4447
    
  • Also you need to create a user for “Application User” using the “/jboss-as-7.1.0.Final/bin/add-user.sh” which would be used for getting the connection with the JBoss on remote box
  • Last thing you would have to add the below code with the username and password created by the above step, for getting the Initial context factory as by default the remote connector is secured.
//*************** Creating Queue Connection using the UserName & Password *************************
qcon = qconFactory.createQueueConnection("USERNAME","PASSWORD");
.
.
//*************** UserName & Password for the Initial Context for JNDI lookup *************************
env.put(Context.SECURITY_PRINCIPAL, "USERNAME");
env.put(Context.SECURITY_CREDENTIALS, "PASSWORD");

In Box-1 [10.10.10.10]

Lets say we have our JBoss AS 7.1 Final in this box and we would be using standalone-full.xml for this article.

  1. Now we would create a queue called TestQ for which we would have to copy the below snip code in standalone-full.xml file inside jms-destinations tag. However you can even create the same queue from the console as well
  2. Console path:

    Profile => (+) Messaging =>  Messaging Provider => default (view ->) => JMS Destination

    Under Destination as Queue click on “Add” Button and enter the following details

    Or else can update the below xml file with the given snip-code

    standalone-full.xml

    .
    .
    <jms-destinations>
                        <jms-queue name="TestQ">
                            <entry name="java:jboss/exported/TestQ"/>
                            <durable>false</durable>
                        </jms-queue>
    .
    .
    

    Note: You would have to make sure you give “java:jboss/exported/” before giving the JNDI name of the queue in the name of “entry” attribute or else you would see the following error

    java QueueSend remote://10.10.10.10:4447
    Mar 3, 2012 6:24:29 PM org.xnio.Xnio
    INFO: XNIO Version 3.0.3.GA
    Mar 3, 2012 6:24:29 PM org.xnio.nio.NioXnio
    INFO: XNIO NIO Implementation Version 3.0.3.GA
    Mar 3, 2012 6:24:29 PM org.jboss.remoting3.EndpointImpl
    INFO: JBoss Remoting version 3.2.2.GA
    Exception in thread "main" javax.naming.NameNotFoundException: TestQ -- service jboss.naming.context.java.jboss.exported.TestQ
    	at org.jboss.as.naming.ServiceBasedNamingStore.lookup(ServiceBasedNamingStore.java:97)
    	at org.jboss.as.naming.NamingContext.lookup(NamingContext.java:177)
    	at org.jboss.naming.remote.protocol.v1.Protocol$1.handleServerMessage(Protocol.java:124)
    	at org.jboss.naming.remote.protocol.v1.RemoteNamingServerV1$MessageReciever$1.run(RemoteNamingServerV1.java:70)
    	at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    	at java.lang.Thread.run(Thread.java:662)
    
    
  3. Now we need to create a new Application User by running “${JBOSS_HOME}/bin/add-user.sh” script as following :
  4. [userone@localhost bin]$ ./add-user.sh
    
    What type of user do you wish to add?
     a) Management User (mgmt-users.properties)
     b) Application User (application-users.properties)
    (a): b
    
    Enter the details of the new user to add.
    Realm (ApplicationRealm) :  ApplicationRealm
    Username : testuser
    Password : testpassword
    Re-enter Password : testpassword
    
    What roles do you want this user to belong to? (Please enter a comma separated list, or leave blank for none) : testrole
    About to add user 'testuser' for realm 'ApplicationRealm'
    
    Is this correct yes/no? yes
    
    Added user 'testuser' to file '/home/userone/jboss-as-7.1.0.Final/standalone/configuration/application-users.properties'
    Added user 'testuser' to file '/home/userone/jboss-as-7.1.0.Final/domain/configuration/application-users.properties'
    Added user 'testuser' with roles testrole to file '/home/userone/jboss-as-7.1.0.Final/standalone/configuration/application-roles.properties'
    Added user 'testuser' with roles testrole to file '/home/userone/jboss-as-7.1.0.Final/domain/configuration/application-roles.properties'
    

    Updated: Thanks to “michaelbini”

    Note: You would have to make sure you add the new role which we just created “testrole” should be added in the “security-setting” inside “standalone-full.xml” becasue by default all the queues are only having “guest” as role, which has the permission to send and receive messages, however the new user which we made is under “testrole” role and not “guest”, hence we need to add it or else you would see the following error

    Exception in thread "main" javax.jms.JMSSecurityException: User: testuser doesn't have permission='SEND' on address jms.queue.TestQ
    	at org.hornetq.core.protocol.core.impl.ChannelImpl.sendBlocking(ChannelImpl.java:312)
    	at org.hornetq.core.client.impl.ClientProducerImpl.doSend(ClientProducerImpl.java:287)
    	at org.hornetq.core.client.impl.ClientProducerImpl.send(ClientProducerImpl.java:142)
    	at org.hornetq.jms.client.HornetQMessageProducer.doSend(HornetQMessageProducer.java:451)
    	at org.hornetq.jms.client.HornetQMessageProducer.send(HornetQMessageProducer.java:199)
    

    standalone-full.xml:

    Before:

    <security-settings>
      <security-setting match="#">
         <permission type="send" roles="guest"/>
         <permission type="consume" roles="guest"/>
         .
         . 
      </security-setting>
    </security-settings>
    

    After:

    <security-settings>
      <security-setting match="#">
         <permission type="send" roles="guest testrole"/>
         <permission type="consume" roles="guest testrole"/>
         .
         .
      </security-setting>
    </security-settings>
    
  5. Once the queue and application user has been created you can start you JBoss AS 7.1 final by using the following command to let it start using the IP address of the box on which it is running and in this example its 10.10.10.10
  6. bin]$ ./standalone.sh -c standalone-full.xml
     -Djboss.bind.address=10.10.10.10
    
  7. Create a directory somewhere in your file system like: “/urs/JBoss/HornetQ/Queue” to write the QueueReceive.java programs as shown below.
  8. import java.util.Hashtable;
    import javax.jms.*;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    
    public class QueueReceive implements MessageListener
    {
    public final static String JNDI_FACTORY="org.jboss.naming.remote.client.InitialContextFactory";
    
    //*************** Using the RemoteConnectionFactory JNDI name *************************
    public final static String JMS_FACTORY="jms/RemoteConnectionFactory";
    
    //*************** Created Queue's JNDI name *************************
    public final static String QUEUE="TestQ";
    
    private QueueConnectionFactory qconFactory;
    private QueueConnection qcon;
    private QueueSession qsession;
    private QueueReceiver qreceiver;
    private Queue queue;
    private boolean quit = false;
    
    public void onMessage(Message msg)
    {
    try {
    String msgText;
    if (msg instanceof TextMessage)
    {
    msgText = ((TextMessage)msg).getText();
    }
    else
    {
    msgText = msg.toString();
    }
    System.out.println("nt "+ msgText );
    if (msgText.equalsIgnoreCase("quit"))
    {
    synchronized(this)
    {
    quit = true;
    this.notifyAll(); // Notify main thread to quit
    }
    }
    }
    catch (JMSException jmse)
    {
    jmse.printStackTrace();
    }
    }
    public void init(Context ctx, String queueName) throws NamingException, JMSException
    {
    qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
    
    //*************** Creating Queue Connection using the UserName & Password *************************
    qcon = qconFactory.createQueueConnection("testuser","testpassword");			//<------------- Change the UserName & Password
    
    qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    queue = (Queue) ctx.lookup(queueName);
    qreceiver = qsession.createReceiver(queue);
    qreceiver.setMessageListener(this);
    qcon.start();
    }
    
    public void close()throws JMSException
    {
    qreceiver.close();
    qsession.close();
    qcon.close();
    }
    
    public static void main(String[] args) throws Exception
    {
    if (args.length != 1)
    {
    System.out.println("Usage: java QueueReceive URL");
    return;
    }
    InitialContext ic = getInitialContext(args[0]);
    QueueReceive qr = new QueueReceive();
    qr.init(ic, QUEUE);
    System.out.println("JMS Ready To Receive Messages (To quit, send a "quit" message from QueueSender.class).");
    // Wait until a "quit" message has been received.
    synchronized(qr)
    {
    while (! qr.quit)
    {
    try
    {
    qr.wait();
    }
    catch (InterruptedException ie)
    {}
    }
    }
    qr.close();
    }
    
    private static InitialContext getInitialContext(String url) throws NamingException
    {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
    env.put(Context.PROVIDER_URL, url);
    
    //*************** UserName & Password for the Initial Context for JNDI lookup *************************
    env.put(Context.SECURITY_PRINCIPAL, "testuser");
    env.put(Context.SECURITY_CREDENTIALS, "testpassword");
    
    return new InitialContext(env);
    }
    }
    

In Box-2 [20.20.20.20]

Now in this box we just need to keep the QueueSend, hence again create a directory somewhere in your file system like: “/urs/JBoss/HornetQ/Queue” to write the QueueSend.java programs as shown below.

QueueSend.java

import java.io.*;
import java.util.Hashtable;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class QueueSend
{
public final static String JNDI_FACTORY="org.jboss.naming.remote.client.InitialContextFactory";

//*************** Connection Factory JNDI name *************************
public final static String JMS_FACTORY="jms/RemoteConnectionFactory";

//*************** Queue Factory JNDI name *************************
public final static String QUEUE="TestQ";

private QueueConnectionFactory qconFactory;
private QueueConnection qcon;
private QueueSession qsession;
private QueueSender qsender;
private Queue queue;
private TextMessage msg;

public void init(Context ctx, String queueName)throws NamingException, JMSException
{
qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);

//*************** Creating Queue Connection using the UserName & Password *************************
qcon = qconFactory.createQueueConnection("testuser","testpassword");   			//<------------- Change the UserName & Password

qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
queue = (Queue) ctx.lookup(queueName);
qsender = qsession.createSender(queue);
msg = qsession.createTextMessage();
qcon.start();
}

public void send(String message) throws JMSException {
msg.setText(message);
qsender.send(msg);
}

public void close() throws JMSException {
qsender.close();
qsession.close();
qcon.close();
}

public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("Usage: java QueueSend URL");
return;
}
InitialContext ic = getInitialContext(args[0]);
QueueSend qs = new QueueSend();
qs.init(ic, QUEUE);
readAndSend(qs);
qs.close();
}

private static void readAndSend(QueueSend qs) throws IOException, JMSException
{
String line="Test Message Body with counter = ";
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
boolean readFlag=true;
System.out.println("ntStart Sending Messages (Enter QUIT to Stop):n");
while(readFlag)
{
System.out.print("<Msg_Sender> ");
String msg=br.readLine();
if(msg.equals("QUIT") || msg.equals("quit"))
{
qs.send(msg);
System.exit(0);
}
qs.send(msg);
System.out.println();
}
br.close();
}

private static InitialContext getInitialContext(String url) throws NamingException
{
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
env.put(Context.PROVIDER_URL, url);

//*************** UserName & Password for the Initial Context for JNDI lookup *************************
env.put(Context.SECURITY_PRINCIPAL, "testuser");
env.put(Context.SECURITY_CREDENTIALS, "testpassword");

return new InitialContext(env);
}
}

After following the above given steps, we have successfully configured all the setting. Now its time to test our configuration by following the below steps.

Testing

  1. Now open 1– command prompt on each boxes and run the “. ./setJBossEnv.sh” by adding two DOTs separated by a single space, in both the prompts to set the Environment (PATH & CLASSPATH).
  2. setJBossEnv.sh

    #!/bin/sh
    echo "Exporting JBOSS_HOME...."
    export JBOSS_HOME=/Jboss/jboss-as-7.1.0.Final/jboss-as   #<---- Change as per your environment
    echo "JBOSS_HOME Exported....!!!"
    echo ""
    echo "Exporting JAVA_HOME...."
    export JAVA_HOME=/Jdk/jdk1.6.0_21    #<---- Change as per your environment
    echo "JBOSS_HOME Exported....!!!"
    echo ""
    echo "Exporting CLASSPATH...."
    export CLASSPATH=$JBOSS_HOME/bin/client/jboss-client-7.1.0.Final.jar:$CLASSPATH:.:
    echo "CLASSPATH Exported....!!!"
    echo ""
    echo "Exporting PATH...."
    export PATH=$JAVA_HOME/bin:$PATH
    echo "PATH Exported....!!!"
    echo ""
    echo "========================================================================"
    echo "JBOSS_HOME = " $JBOSS_HOME
    echo ""
    echo "JAVA_HOME = " $JAVA_HOME
    echo ""
    echo "CLASSPATH = " $CLASSPATH
    echo ""
    echo "PATH = " $PATH
    echo "========================================================================"
    
  3. Then compile both the java codes the QueueSend.java and QueueReceive.java programs.
  4. Now run the code with the following command
  5. Prompt-1 on Box-1

    java QueueReceive remote://10.10.10.10:4447
     

    Prompt-2 on Box-2

    java QueueSend remote://10.10.10.10:4447
     

Once everything is up and running properly you just have to send around few messages in “Prompt-2” which is on Box-2 and you would notice that those messages would be shown in “Prompt-1” which is running which is on Box-1.

Hence our configuration worked and we are now able to connect to a remote queue in JBoss AS 7.1 Final version, now you can put the sender or receiver to any other box and follow the same steps which would work just fine.

– Should have the “/jboss-as-7.1.0.Final/bin/client/jboss-client-7.1.0.Final.jar” in the CLASSPATH of the client.
– The URL would be   URL =  remote://<IP_ADDRESS>:4447   (i.e. 4447 is the remote port)
– Also you need to create a user for “Application User” using the “/jboss-as-7.1.0.Final/bin/add-user.sh” which would be used for getting the connection with the JBoss on remote box
– IMP = you would have to add the below code with the username and password created by the above step, for getting the Initial context factory as by default the remoting connector is secured.//*************** Creating Queue Connection using the UserName & Password *************************
qcon = qconFactory.createQueueConnection(“USERNAME”,”PASSWORD”); 

//*************** UserName & Password for the Initial Context for JNDI lookup *************************
env.put(Context.SECURITY_PRINCIPAL, “USERNAME”);
env.put(Context.SECURITY_CREDENTIALS, “PASSWORD”);

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.