3

i am learning JMS tried a simple example below but it gives error

package pointToPoint;
import javax.naming.InitialContext;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.QueueSession;
import javax.jms.QueueReceiver;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;

public class Receiver
{
    public static void main(String[] args) throws Exception
    {
       // get the initial context
       InitialContext ctx = new InitialContext();

       // lookup the queue object
       Queue queue = (Queue) ctx.lookup("queue/queue0");

       // lookup the queue connection factory
       QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.
           lookup("queue/connectionFactory");

       // create a queue connection
       QueueConnection queueConn = connFactory.createQueueConnection();

       // create a queue session
       QueueSession queueSession = queueConn.createQueueSession(false,
           Session.AUTO_ACKNOWLEDGE);

       // create a queue receiver
       QueueReceiver queueReceiver = queueSession.createReceiver(queue);

       // start the connection
       queueConn.start();

       // receive a message
       TextMessage message = (TextMessage) queueReceiver.receive();

       // print the message
       System.out.println("received: " + message.getText());

       // close the queue connection
       queueConn.close();
    }
}

error message:

Exception in thread "main" javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
    at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
    at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
    at javax.naming.InitialContext.getURLOrDefaultInitCtx(Unknown Source)
    at javax.naming.InitialContext.lookup(Unknown Source)
    at pointToPoint.Receiver.main(Receiver.java:22)

can anyone please help me with this.

Gopal
  • 655
  • 3
  • 9
  • 18

2 Answers2

3

The answer is in the stack trace. In a stand-alone application, you should pass an environment (implementation, urls, etc) to the InitialContext. Inside a J2EE container like JBoss, your code will work.

This should help: NoInitialContextException error

Community
  • 1
  • 1
Eran Harel
  • 2,325
  • 19
  • 28
0

What the responder above meant was that the tutorial would help you send messages to a receiver on the same application server. A lot more is needed for remote lookups

Dr Dave
  • 550
  • 1
  • 6
  • 22