Posting a message in JMS queue using JAVA
Asked Answered
B

2

9

I am new to JMS, after a long re search i googled out a code to connect to JMS and post a msg.

The problem is i need to post the message in a remote queue, But i am not sure how to establish connection to it and post the message.

SERVER TYPE : TIBCO EMS
SERVER HOST : **.*****.net
PORT : * **USername : user
passsword : user123
Queue : *.*....Order.Management..1

I would like to establish connection, post a simple msg and retrieve it back. Kindly help! thanks in advance

CODE WHICH I GOT FROM INTERNET

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Hashtable;
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class emm {


         // Defines the JNDI context factory.
         public final static String JNDI_FACTORY="com.tibco.tibjms.naming.TibjmsInitialContextFactory";

         // Defines the JMS context factory.
         public final static String JMS_FACTORY="jms/TestConnectionFactory";

         // Defines the queue.
         public final static String QUEUE="CPW.GBR.POR.Public.Request.Order.Management.UpdateProvisioningStatus.1";

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

         /**
          * Creates all the necessary objects for sending
          * messages to a JMS queue.
          *
          * @param ctx JNDI initial context
          * @param queueName name of queue
          * @exception NamingException if operation cannot be performed
          * @exception JMSException if JMS fails to initialize due to internal error
          */
         public void init(Context ctx, String queueName)
            throws NamingException, JMSException
         {

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

         /**
          * Sends a message to a JMS queue.
          *
          * @param message  message to be sent
          * @exception JMSException if JMS fails to send message due to internal error
          */
         public void send(String message) throws JMSException {
            msg.setText(message);
            qsender.send(msg);
         }

         /**
          * Closes JMS objects.
          * @exception JMSException if JMS fails to close objects due to internal error
          */
         public void close() throws JMSException {
            qsender.close();
            qsession.close();
            qcon.close();
         }
        /** main() method.
         *
         * @param args WebLogic Server URL
         * @exception Exception if operation fails
         */
         public static void main(String[] args) throws Exception {
            if (args.length != 1) {
             System.out.println("Usage: java examples.jms.queue.QueueSend WebLogicURL");
             return;
            }
            InitialContext ic = getInitialContext(args[0]);
            emm qs = new emm();
            qs.init(ic, QUEUE);
            readAndSend(qs);
            qs.close();
         }

         private static void readAndSend(emm qs)
            throws IOException, JMSException
         {
            BufferedReader msgStream = new BufferedReader(new InputStreamReader(System.in));
            String line=null;
            boolean quitNow = false;
            do {
             System.out.print("Enter message (\"quit\" to quit): \n");
             line = msgStream.readLine();
             if (line != null && line.trim().length() != 0) {
               qs.send(line);
               System.out.println("JMS Message Sent: "+line+"\n");
               quitNow = line.equalsIgnoreCase("quit");
             }
            } while (! quitNow);

         }

         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);
            return new InitialContext(env);
         }
        }
Befriend answered 24/7, 2014 at 14:19 Comment(8)
Can you describe the problem, what errors do you get? Are you passing the location of the naming service to the application (for some reason named 'WebLogicURL')?Ferrand
I have to connect i mean establish connection right.. I dunno how to do that.. cause the queue is a remote queue.. it has few credentials that i have mentioned aboveBefriend
The main method expects the URL to the initial context of your naming service. This is where the "remote" aspect come in (something like tcp://hostname:7222, but it really depends on your configuration). The credentials are passed when you create the Connection in qconFactory.createQueueConnection(usr,pwd)Ferrand
how do i pass the URL ??Befriend
WHen you run the program: java emm tcp://yadayadayada:7222Ferrand
can u modify my code given above with the credentials and post it as an answer pls ??Befriend
I will place some code for you to copy and paste. But remember we are here to answer questions and not to do your work - sorry). As i told you i will place some code for "inspiration". It also sounds you might be in over your head with this request. I would suggest you either follow the Java EE tutorial or sign up for a course.Ferrand
Let us continue this discussion in chat.Ferrand
B
8

Finally from different sources i found the best possible to way for this. This code will definitely work. I have tried this out and is running currently on my machine

import java.util.Properties;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.*;

public class JMSExample {

    static String serverUrl = "tcp://10.101.111.101:10001"; // values changed
    static String userName = "user";
    static String password = "pwd";

     static QueueConnection connection;
     static QueueReceiver queueReceiver;
     static Queue queue;

    static TextMessage message;

    public static void sendTopicMessage(String topicName, String messageStr) {

        Connection connection = null;
        Session session = null;
        MessageProducer msgProducer = null;
        Destination destination = null;


        try {
            TextMessage msg;

            System.out.println("Publishing to destination '" + topicName
                    + "'\n");

            ConnectionFactory factory = new com.tibco.tibjms.TibjmsConnectionFactory(
                    serverUrl);

            connection = factory.createConnection(userName, password);


            session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);



            destination = session.createQueue(topicName);


            msgProducer = session.createProducer(null);



            msg = session.createTextMessage();

            msg.setStringProperty("SourceId", userName);
            msg.setStringProperty("BusinessEvent", password);


            msg.setText(messageStr);


            msgProducer.send(destination, msg);



            System.out.println("Published message: " + messageStr);


            connection.close();

        } catch (JMSException e) {
            e.printStackTrace();
        }
    }



    public static void main(String[] args) throws JMSException {
        // TODO Auto-generated method stub

        JMSExample.sendTopicMessage("***.***.***.**.**.Order.Management.***.1",
                "Hi");
        //System.out.println(getMessage());

    }
Befriend answered 4/8, 2014 at 11:24 Comment(1)
Hi Ragesh, Hope this works for me as well but while adding the dependency I am getting error as below "Could not find artifact com.tibco:tibjms:pom:4.4.3 in central (repo.maven.apache.org/maven2) "Amiraamis
J
4

As i mentioned some code for inspiration (SLIGHTLY improved your code. Not something i would want to see in production!)

// Use the domain-agnostic API
private Connection connection;ery 
private Session session;
private MessageProducer producer;
private Queue queue;

public void init(Context ctx, String queueName) {

    try {
        ConnectionFactory cnf = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
        queue = (Queue) ctx.lookup(queueName);


        connection = cnf.createConnection("user", "user123");
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        producer = session.createProducer(queue);

        connection.start();
    } catch (NamingException e) {
        throw new RuntimeException(e);
    } catch (JMSException e) {
        throw new RuntimeException(e);
    }
}

And make your send like this (don't reuse the same Message object, but create a new one for each message you are sending)

public void send(String message) throws JMSException {
    TextMessage msg = session.createTextMessage();
    msg.setText(message);
    producer.send(msg);
}

Put a try..finally around the code in your main method:

    try {
        readAndSend(qs);
    } finally {
        qs.close();
    }

The code you are using is not very good (understatement). It is programmed too brittle for a production system. You should not use state the way this program does.

Also there is no need to use the domain specific JMS API. You can use the domain (queue/topic) agnostic one.

When you run the program pass in the JNDI URL for your TIBCO server.

Javanese answered 28/7, 2014 at 15:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.