Login
Register

Home

Trainings

Fusion Blog

EBS Blog

Authors

CONTACT US

Weblogic Server
  • Register

Oracle Gold Partners, our very popular training packages, training schedule is listed here
Designed by Five Star Rated Oracle Press Authors & Oracle ACE's.

webinar new

Search Courses

Purpose :
In this article, we will use a sample program to write a message to the queue and to read the message from that queue.
Please review the previous articles of JMS Queue if you have not already done so, as they contain prerequisites for executing the sample in this article.

A Simple Java Program to send the Messages to JMS Queue :
This example shows how to establish a connection and send a message to the JMS Queue. The class operates on the same JMS queue .

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="weblogic.jndi.WLInitialContextFactory";

// Defines connection factory
public final static String JMS_FACTORY="cf";

// Defines queue
public final static String QUEUE="q1";


private QueueConnectionFactory qconFactory;
private QueueConnection qcon;
private QueueSession qsession;
private QueueSender qsender; // qseneder object will be used to send the message
private Queue queue;
private TextMessage msg; // to store the messages that will be sent to the queue

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);// to set the auto acknowledge feature when consumer consumes the message
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);// send() will send the message to the queue .
}

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 WebLogicURL");
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)); // BufferedReader is used to create input stream to take input from user
boolean readFlag=true;
System.out.println("\n\tEnter Message (Enter "quit" to quit):\n");
while(readFlag)
{
System.out.print("<Msg_Sender> ");
String msg=br.readLine();// readLine() method will read the input and store it in msg variable
if(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);
return new InitialContext(env);
}
}

1.Before compiling the program make sure Weblogic jar file is in the Classpath by using the command "echo $CLASSPATH " as shown in below screen shot
a1

2. Compile the program using javac command .

a2

3. Once compiled run the QueueSend.java file using java keyword.
Before running the file you need to export the CLASSPATH variable to the current directory .

a3
java QueueSend http://192.168.1.12:6001

If Listener address is not set you may get following error :

a5

 

So to resolve the error we will give the listener address(to listen for the incoming connections ) as 192.1768.1.12 to the ms1 managed server .

a4

Also forcefully shutdown the ms1 server and restart it .

Now your QueueSend.java will successfully run and will ask you to enter the message as shown in the following screen shot .
It will ask you enter the message till you enter "quit".

a6

 

4. Click on JMS Modiles>jms-system-mod-ms1>q1

a7


-->Inside q1 go to Monitoring tab , you will find the Message Current value is 1. Since we have sent only one message to q1 through our java program .
a8

 

-->In order to see the message that was sent Select the queue and click on Show Messages button to see the message as shown in below screen shot .

a9


-->The message we sent was "A" , and every message comes with an message id as shown in below screen shot .

a10

 

-->Click on this message id to see the message .

a11

 

-->Now we will try to send some more messages .
a12

 


-->We can go back and the q1's monitoring tab to see the Messages Current value . It will be 7 as shown in below.
a13

 

This was how we were able to send the messages using JMS queue .

After sending the messages when you monitor the q1 , you will see that Consumer Current value is 0 , that means the messages we sent are not been received .

a14

A sample program for receiving the messages . 

import java.util.Hashtable;
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class QueueReceive implements MessageListener
{
// Defines the JNDI context factory.
public final static String JNDI_FACTORY="weblogic.jndi.WLInitialContextFactory";

// Defines the JMS connection factory for the queue.
public final static String JMS_FACTORY="cf";

// Defines the queue.
public final static String QUEUE="q1";

private QueueConnectionFactory qconFactory;
private QueueConnection qcon;
private QueueSession qsession;
private QueueReceiver qreceiver;
private Queue queue;
private boolean quit = false;

/**
* Message listener interface.
* @param msg message
*/
public void onMessage(Message msg)
{
try {
String msgText;
if (msg instanceof TextMessage) {
msgText = ((TextMessage)msg).getText();
} else {
msgText = msg.toString();
}

System.out.println("Message Received: "+ msgText );

if (msgText.equalsIgnoreCase("quit")) {
synchronized(this) {
quit = true;
this.notifyAll(); // Notify main thread to quit
}
}
} catch (JMSException jmse) {
System.err.println("An exception occurred: "+jmse.getMessage());
}
}

/**
* Creates all the necessary objects for receiving
* messages from 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);
qreceiver = qsession.createReceiver(queue);
qreceiver.setMessageListener(this);
qcon.start();
}

/**
* Closes JMS objects.
* @exception JMSException if JMS fails to close objects due to internal error
*/
public void close()throws JMSException
{
qreceiver.close();
qsession.close();
qcon.close();
}
/**
* main() method.
*
* @param args WebLogic Server URL
* @exception Exception if execution fails
*/

public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("Usage: java examples.jms.queue.QueueReceive WebLogicURL");
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).");

// 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);
return new InitialContext(env);
}
}

1. Compile the QueueReceive. java file

a16

 

2. Run the file : java QueueReceive http://192.168.1.12:6001
If the program is unable to receive the message un-target the ms1 and target it again .
a17

 

a18

 

 

3. To monitor go to JMS Modules>jms-system-mod-ms1>q1>Monitoring Tab
a19

 

 

4. Once you stop running the QueuReceive.java file you will see that the Consumer Current is 0 , which means currently no consumer available .

a20


This is how the messages are received using JMS .


Kashif Baksh

Add comment


Security code
Refresh

About the Author

Kashif Baksh

Search Trainings

Fully verifiable testimonials

Apps2Fusion - Event List

<<  May 2024  >>
 Mon  Tue  Wed  Thu  Fri  Sat  Sun 
    1  2  3  4  5
  6  7  8  9101112
13141516171819
20212223242526
2728293031  

Enquire For Training

Fusion Training Packages

Get Email Updates


Powered by Google FeedBurner