I am a newbie to this so forgive me if my mistake seems stupid.I am using active mq with glassfish and eclipse. I have created JMS resources in glass fish such as Destination Resources and Connection Factories. Active Mq is running and I have deployed message driven bean on glassfish and no exceptions occur but i can't find my Queue on active mq and neither is the message printed on console.
I am basically using example given on here : https://www.javatpoint.com/message-driven-bean
public class MessageSender {
public static void sendMessage() throws JMSException, NamingException {
InitialContext ctx = new InitialContext();
QueueConnectionFactory f = (QueueConnectionFactory) ctx.lookup("jms/myQueueConnectionFactory");
QueueConnection connection = f.createQueueConnection();
connection.start();
QueueSession ses = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
Queue t = (Queue) ctx.lookup("jms/myQueue");
QueueSender sender = ses.createSender(t);
TextMessage message=ses.createTextMessage("Hello !!! Welcome to the world of ActiveMQ.");
sender.send(message);
connection.close();
}
}
#MessageDriven(mappedName = "jms/myQueue")
public class MessageReceiver implements MessageListener {
/**
* Default constructor.
*/
public MessageReceiver() {
// TODO Auto-generated constructor stub
}
/**
* #see MessageListener#onMessage(Message)
*/
public void onMessage(Message message) {
// TODO Auto-generated method stub
TextMessage m=(TextMessage) message;
try{
System.out.println("message received: "+m.getText());
}catch(Exception e){System.out.println(e);}
}
}
Related
I've created an app that must consumes an activemq topic, but in this project we don't need to use spring xml. I only created one class called ActiveMQConsumer that implements MessageListener and overrides onMessage method, but nothing happens... Is this approach ok? or something missing? I'm currently connecting through tcp.
public class ActiveMQConsumer implements MessageListener {
public ActiveMQConsumer() throws JMSException {
try {
ConnectionFactory factory = new ActiveMQConnectionFactory(CATALOG_BROKER_URL.getValue());
Connection connection = factory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createTopic(CATALOG_TOPIC_NAME.getValue());
MessageConsumer consumer = session.createConsumer(destination);
consumer.setMessageListener(this);
} catch (JMSException e) {
System.out.println("Error");
}
}
#Override
public void onMessage(final Message message) {
LOGGER.info("Start consuming message from Catalog");
try {
if (message instanceof TextMessage) {
TextMessage txtMessage = (TextMessage) message;
System.out.println("Message: " + txtMessage.getText());
} else {
System.out.println("Invalid Message !");
}
} catch (JMSException e) {
System.out.println("Exception" + e);
}
}
}
I've solved my problem using an ContextListener to call an runnable class. Just put it into web.xml and done.
I have a stateful session bean where I send and receive JMS messages. All the connection setup is handled manually, so the bean is holding instances of javax.jms.connection and javax.jms.session. The bean also implements MessageListener to be able receive messages.
Now, when I send a message, I create a temporary queue with session.createTemporaryQueue(). I set the message.setJMSReplyTo() to this same temporary queue, and at last creates a consumer of this queue and sets the MessageListener to the same stateful session bean that all this is implemented in.
I am abel to receive the message to the onMessage() method. However, I want to close the session and connection as soon as the message has been received, and this is apparently not allowed in the onMessage() method.
So the question is:
How can I close the session and connection once the message has been received? I must handle the connection setup manually and can not use a MDB.
Note that:
This is executed in the Java EE environment (GlassFish 4.0)
EDIT:
import javax.ejb.LocalBean;
import javax.ejb.Stateful;
import javax.inject.Inject;
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import com.sun.messaging.ConnectionConfiguration;
import com.sun.messaging.QueueConnectionFactory;
#LocalBean
#Stateful
public class OpenMqClient implements MessageListener{
private Connection connection;
private Session session;
private MessageConsumer responseConsumer;
public OpenMqClient(){}
public void sendMessage(String messageContent, String jmsBrokerUri, String queueName) {
try{
String host = System.getProperty("foo", jmsBrokerUri);
QueueConnectionFactory cf = new QueueConnectionFactory();
cf.setProperty(ConnectionConfiguration.imqAddressList, host);
connection = null;
session = null;
//Setup connection
connection = cf.createConnection();
connection.start();
session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
//Setup queue and producer
Queue queue = session.createQueue(queueName);
MessageProducer producer = session.createProducer(queue);
//Reply destination
Queue responseQueue = session.createTemporaryQueue();
responseConsumer = session.createConsumer(responseQueue);
responseConsumer.setMessageListener(this);
//Create message
TextMessage textMessage = session.createTextMessage();
textMessage.setJMSReplyTo(responseQueue);
textMessage.setJMSCorrelationID("test0101");
textMessage.setText(messageContent);
producer.send(textMessage);
System.out.println("Message sent");
} catch (JMSException e) {
e.printStackTrace();
System.out.println("JMSException in Sender");
}
}
#Override
public void onMessage(Message arg0) {
//On this event I want to close the session and connection, but it's not permitted
}
}
Personally, this is how I would do it (note I haven't tested or added much error handling to this code).
Make the connection static - you can (probably should) reuse the same connection for all your beans unless you have a specific reason not to
Close the session in a new thread
public class OpenMqClient implements MessageListener {
private static Connection connection;
private static final String mutex = "mutex";
private Session session;
private MessageConsumer responseConsumer;
public OpenMqClient() {
if(connection == null) {
synchronized(mutex) {
if(connection == null) {
String host = System.getProperty("foo", jmsBrokerUri);
QueueConnectionFactory cf = new QueueConnectionFactory();
cf.setProperty(ConnectionConfiguration.imqAddressList, host);
// Setup connection
connection = cf.createConnection();
connection.start();
}
}
}
}
public void sendMessage(String messageContent, String jmsBrokerUri, String queueName) {
try {
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// Setup queue and producer
Queue queue = session.createQueue(queueName);
MessageProducer producer = session.createProducer(queue);
// Reply destination
Queue responseQueue = session.createTemporaryQueue();
responseConsumer = session.createConsumer(responseQueue);
responseConsumer.setMessageListener(this);
// Create message
TextMessage textMessage = session.createTextMessage();
textMessage.setJMSReplyTo(responseQueue);
textMessage.setJMSCorrelationID("test0101");
textMessage.setText(messageContent);
producer.send(textMessage);
System.out.println("Message sent");
} catch (JMSException e) {
e.printStackTrace();
System.out.println("JMSException in Sender");
}
}
#Override
public void onMessage(Message arg0) {
// do stuff
new Thread(
new Runnable() {
#Override
public void run() {
if(session != null)
try {
session.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
).start();
}
}
I am new in JMS and want to create a basic MessageProducer who sends a message and MessageConsumer who receives the message asynchronously. When I run this code I get error message :
MessageProducer.java
package activemq.test;
import java.util.Date;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
public class MessageProducer{
javax.jms.MessageProducer producer = null;
Connection connection = null;
Session session = null;
public MessageProducer(){
try {
// Create a ConnectionFactory
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
// Create a Connection
connection = connectionFactory.createConnection();
connection.start();
// Create a Session
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// Create the destination (Topic or Queue)
Destination destination = session.createQueue("TEST.FOO");
// Create a MessageProducer from the Session to the Topic or Queue
producer = session.createProducer(destination);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
// Create a messages
String text = "Hello world! From: MessageProducer";
TextMessage message = session.createTextMessage(text);
// Tell the producer to send the message
System.out.println("Producer is going to send a message");
producer.send(message);
} catch (Exception e) {
System.out.println("Caught: " + e);
e.printStackTrace();
}
}
public void sendMessage(){
try
{
// Create a messages
String text = "Hello world! From: " + new Date();
TextMessage message = session.createTextMessage(text);
// Tell the producer to send the message
System.out.println("Sent message: "+ message.hashCode());
producer.send(message);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void close(){
// Clean up
try {
session.close();
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
MessageConsumer.java
package activemq.test;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
public class MessageConsumer implements ExceptionListener{
Connection connection = null;
javax.jms.MessageConsumer consumer = null;
Session session = null;
public MessageConsumer(){
try {
// Create a ConnectionFactory
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
// Create a Connection
connection = connectionFactory.createConnection();
connection.start();
connection.setExceptionListener(this);
// Create a Session
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// Create the destination (Topic or Queue)
Destination destination = session.createQueue("TEST.FOO");
// Create a MessageConsumer from the Session to the Topic or Queue
consumer = session.createConsumer(destination);
MessageListener listener = new MessageListener() {
public void onMessage(Message message) {
try {
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
System.out.println("Received message"
+ textMessage.getText() + "'");
}
} catch (JMSException e) {
System.out.println("Caught:" + e);
e.printStackTrace();
}
}
};
consumer.setMessageListener(listener);
} catch (Exception e) {
System.out.println("Caught: " + e);
e.printStackTrace();
}
}
#Override
public void onException(JMSException exception) {
System.out.println("JMS Exception occured. Shutting down client.");
}
public void close(){
// Clean up
try {
consumer.close();
session.close();
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
AppMain.java
public class AppMain {
public static void main(final String arg[]) throws Exception
{
MessageProducer msProducer = new MessageProducer();
msProducer.sendMessage();
msProducer.close();
MessageConsumer msConsumer = new MessageConsumer();
msConsumer.close();
}
}
When MessageConsumer is created, I get error message:
Caught: javax.jms.JMSException: AMQ119017: Queue jms.queue.TEST.FOO does not exist
javax.jms.JMSException: AMQ119017: Queue jms.queue.TEST.FOO does not exist
at org.apache.activemq.util.JMSExceptionSupport.create(JMSExceptionSupport.java:54)
at org.apache.activemq.ActiveMQConnection.syncSendPacket(ActiveMQConnection.java:1405)
at org.apache.activemq.ActiveMQSession.syncSendPacket(ActiveMQSession.java:1925)
at org.apache.activemq.ActiveMQMessageConsumer.<init>(ActiveMQMessageConsumer.java:275)
at org.apache.activemq.ActiveMQSession.createConsumer(ActiveMQSession.java:1157)
at org.apache.activemq.ActiveMQSession.createConsumer(ActiveMQSession.java:1101)
at org.apache.activemq.ActiveMQSession.createConsumer(ActiveMQSession.java:1014)
at org.apache.activemq.ActiveMQSession.createConsumer(ActiveMQSession.java:987)
at activemq.test.MessageConsumer.<init>(MessageConsumer.java:36)
at activemq.test.AppMain.main(AppMain.java:17)
Caused by: ActiveMQNonExistentQueueException[errorType=QUEUE_DOES_NOT_EXIST message=AMQ119017: Queue jms.queue.TEST.FOO does not exist]
at org.apache.activemq.core.server.impl.ServerSessionImpl.createConsumer(ServerSessionImpl.java:448)
at org.apache.activemq.core.protocol.openwire.amq.AMQServerSession.createConsumer(AMQServerSession.java:326)
at org.apache.activemq.core.protocol.openwire.amq.AMQConsumer.init(AMQConsumer.java:138)
at org.apache.activemq.core.protocol.openwire.amq.AMQSession.createConsumer(AMQSession.java:144)
at org.apache.activemq.core.protocol.openwire.OpenWireProtocolManager.addConsumer(OpenWireProtocolManager.java:544)
at org.apache.activemq.core.protocol.openwire.OpenWireConnection.processAddConsumer(OpenWireConnection.java:1118)
at org.apache.activemq.command.ConsumerInfo.visit(ConsumerInfo.java:347)
at org.apache.activemq.core.protocol.openwire.OpenWireConnection.bufferReceived(OpenWireConnection.java:272)
at org.apache.activemq.core.remoting.server.impl.RemotingServiceImpl$DelegatingBufferHandler.bufferReceived(RemotingServiceImpl.java:678)
at org.apache.activemq.core.remoting.impl.netty.ActiveMQChannelHandler.channelRead(ActiveMQChannelHandler.java:77)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:332)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:318)
at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:787)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:125)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:507)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:464)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:378)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:350)
at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:116)
at java.lang.Thread.run(Thread.java:745)
Why I get this error when MessageConsumer is created, but don't get this error when MessageProducer is created.
I use ActiveMQServer as a broker:
Server.java
package activemq.test;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import org.apache.activemq.api.core.TransportConfiguration;
import org.apache.activemq.core.config.Configuration;
import org.apache.activemq.core.config.impl.ConfigurationImpl;
import org.apache.activemq.core.remoting.impl.netty.NettyAcceptorFactory;
import org.apache.activemq.core.server.ActiveMQServer;
import org.apache.activemq.core.server.ActiveMQServers;
public class Server {
public static void main(final String arg[]) throws Exception
{
try
{
// Step 1. Create the Configuration, and set the properties accordingly
Configuration configuration = new ConfigurationImpl();
//we only need this for the server lock file
configuration.setJournalDirectory("target/data/journal");
configuration.setPersistenceEnabled(false); // http://activemq.apache.org/what-is-the-difference-between-persistent-and-non-persistent-delivery.html
configuration.setSecurityEnabled(false); // http://activemq.apache.org/security.html
/**
* this map with configuration values is not necessary (it configures the default values).
* If you want to modify it to run the example in two different hosts, remember to also
* modify the client's Connector at {#link EmbeddedRemoteExample}.
*/
Map<String, Object> map = new HashMap<String, Object>();
map.put("host", "localhost");
map.put("port", 61616);
// https://access.redhat.com/documentation/en-US/JBoss_Enterprise_Application_Platform/5/html/HornetQ_User_Guide/ch14s04.html
TransportConfiguration transpConf = new TransportConfiguration(NettyAcceptorFactory.class.getName(),map);
HashSet<TransportConfiguration> setTransp = new HashSet<TransportConfiguration>();
setTransp.add(transpConf);
configuration.setAcceptorConfigurations(setTransp); // https://github.com/apache/activemq-6/blob/master/activemq-server/src/main/java/org/apache/activemq/spi/core/remoting/Acceptor.java
// Step 2. Create and start the server
ActiveMQServer server = ActiveMQServers.newActiveMQServer(configuration);
server.start();
}
catch (Exception e)
{
e.printStackTrace();
throw e;
}
}
}
I think, in the producer, you are starting the connection before setting the destination.
Try it starting afterwards....
// Create a ConnectionFactory
ActiveMQConnectionFactory connectionFactory = new
ActiveMQConnectionFactory("tcp://localhost:61616");
// Create a Connection
connection = connectionFactory.createConnection();
// Create a Session
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// Create the destination (Topic or Queue)
Destination destination = session.createQueue("TEST.FOO");
// Create a MessageProducer from the Session to the Topic or Queue
producer = session.createProducer(destination);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
connection.start();
// Create a messages
String text = "Hello world! From: MessageProducer";
TextMessage message = session.createTextMessage(text);
// Tell the producer to send the message
System.out.println("Producer is going to send a message");
producer.send(message);
On the other hand, for the consumer, I suggest to implement MessageConsumer (instead of the Exception).
Once implemented, in the constructor you can initiate the consumer
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(url);
connection = factory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// Create the destination (Topic or Queue)
Destination destination = session.createQueue("TEST.FOO");
// Create a MessageConsumer from the Session to the Topic or Queue
consumer = session.createConsumer(destination).setMessageListener(this);
connection.start();
....
and then implement the onMessage method
public void onMessage(Message message) {
try {
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
System.out.println("Received message"
+ textMessage.getText() + "'");
}
} catch (JMSException e) {
System.out.println("Caught:" + e);
e.printStackTrace();
}
}
I'm trying develop aplication with comunication with JMS between C++ and Java.
I have a "server" with a broker in Java and i would like conect a c++ publisher/listner
How to i do this?
My classes im Java are:
"SERVER":
public class Queue {
private static ActiveMQConnectionFactory connectionFactory;
private static Destination destination;
private static boolean transacted = false;
private static Session session;
private static Connection connection;
public static void main(String[] args) throws Exception {
BrokerService broker = new BrokerService();
broker.setUseJmx(true);
broker.addConnector("tcp://localhost:61616");
broker.start();
Producer p=new Producer();
Consumer c= new Consumer();
connectionFactory = new ActiveMQConnectionFactory(
ActiveMQConnection.DEFAULT_USER,
ActiveMQConnection.DEFAULT_PASSWORD,
ActiveMQConnection.DEFAULT_BROKER_URL);
connection = connectionFactory.createConnection();
connection.start();
session = connection
.createSession(transacted, Session.AUTO_ACKNOWLEDGE);
destination = session.createQueue("queue");
c.createConsumerAndReceiveAMessage(connection, connectionFactory,session,destination );
p.createProducerAndSendAMessage(destination,session);
broker.stop();
}
PRODUCER
public class Producer {
void createProducerAndSendAMessage(Destination destination,
Session session) throws JMSException {
MessageProducer producer = session.createProducer(destination);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
Scanner sc=new Scanner(System.in);
String msg;
while(!(msg=sc.nextLine()).equals("exit") ){
TextMessage message = session.createTextMessage(msg);
System.out.println("Sending message " + message.getText());
producer.send(message);
}
}
CONSUMER:
public class Consumer {
public void createConsumerAndReceiveAMessage(Connection connection,
ActiveMQConnectionFactory connectionFactory, Session session,
Destination destination) throws JMSException, InterruptedException {
connection = connectionFactory.createConnection();
connection.start();
MessageConsumer consumer = session.createConsumer(destination);
MyConsumer myConsumer = new MyConsumer();
connection.setExceptionListener(myConsumer);
consumer.setMessageListener(myConsumer);
}
private static class MyConsumer implements MessageListener,
ExceptionListener {
synchronized public void onException(JMSException ex) {
System.out.println("JMS Exception occured. Shutting down client.");
System.exit(1);
}
public void onMessage(Message message) {
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
try {
System.out.println("Received message "
+ textMessage.getText());
} catch (JMSException ex) {
System.out.println("Error reading message " + ex);
}
} else {
System.out.println("Received " + message);
}
}
}
Regards
Have you looked at ActiveMQ-CPP? This is the ActiveMQ C++ client, in the main page for the project there is documentation, examples and tutorials.
I have a Glassfish 3.1.2 server running on a remote machine (JDK 1.6.0_30). The following code is the stand-alone client running in a Java SE environment, connecting to the JMS using a JNDI lookup. The client is publisher and subscriber at the same time.
I created the JMS connection pool and topic as follows:
./asadmin create-jms-resource --restype javax.jms.ConnectionFactory jms/TopicConnectionFactory
./asadmin create-jms-resource --restype javax.jms.Topic jms/TopicUpdate
I start two instances of this client. The messages seem to be delivered - no errors - but the messages do not arrive at the subscribers ...
What I am doing wrong ?
Any help appreciated - many thanks in advance!
public class JMS implements MessageListener {
private TopicConnectionFactory factory;
private TopicConnection connection;
private Topic topic;
private void subscribe() {
try {
System.setProperty("org.omg.CORBA.ORBInitialHost", "192.168.1.6");
System.setProperty("org.omg.CORBA.ORBInitialPort", "3700");
InitialContext ctx = new InitialContext();
factory = (TopicConnectionFactory)ctx.lookup("jms/TopicConnectionFactory");
topic = (Topic)ctx.lookup("jms/TopicUpdate");
connection = factory.createTopicConnection();
TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
TopicSubscriber subscriber = session.createSubscriber(topic);
subscriber.setMessageListener(this);
connection.start();
while(true) {
Thread.sleep(5000);
sendMessage();
}
} catch (InterruptedException ex) {
Logger.getLogger(JMS.class.getName()).log(Level.SEVERE, null, ex);
} catch (NamingException ex) {
Logger.getLogger(JMS.class.getName()).log(Level.SEVERE, null, ex);
} catch (JMSException ex) {
Logger.getLogger(JMS.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void sendMessage() {
try {
TopicSession session = connection.createTopicSession(true, Session.AUTO_ACKNOWLEDGE);
TopicPublisher publisher = session.createPublisher(topic);
TextMessage message = session.createTextMessage();
message.setText("Message from client.");
publisher.send(message);
session.close();
System.out.println("Message sent.");
} catch (JMSException ex) {
Logger.getLogger(JMS.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void onMessage(Message msg) {
System.out.println("Message received.");
}
public JMS() {
subscribe();
}
public static void main(String[] args) {
new JMS();
}
}
When you use true as the first argument when creating a session, the acknowledge mode is ignored and you're assumed to be transacted. try it with the first argument as false.
Just so it's clear, modify this line of code:
TopicSession session = connection.createTopicSession(true, Session.AUTO_ACKNOWLEDGE);
to be :
TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
In your send message method.
It's good idea to have publisher and subscriber different.I
Here is code how to subscribe using Spring JMS template.
public class MsgReader implements
SessionAwareMessageListener<Message> {
#Override
public void onMessage(Message message, Session session) throws JMSException {
if (message instanceof TextMessage) {
try {
System.out.println(((TextMessage) message).getText());
} catch (JMSException ex) {
throw new RuntimeException(ex);
}
} else {
throw new IllegalArgumentException(
"Message must be of type TextMessage");
}
}
}
Spring Bean file.
Finally load beans.
public class SpringJMSTest {
/**
* #param args
*/
public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext(new String[]{"/resource/consumerBean.xml"});
}
}
Now you will start receiving messages in console.