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.
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 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();
}
}
To receive Jboss JMS messsage, I have written the JMS Asynchronous Message Receiver
See below code
public class QueueReceive implements MessageListener
{
public final static String JNDI_FACTORY="org.jnp.interfaces.NamingContextFactory";
public final static String JMS_FACTORY="ConnectionFactory";
public final static String QUEUE="/queue/requestQueue";
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 {
System.out.println("onMessage");
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());
}
}
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();
}
public void close()throws JMSException
{
qreceiver.close();
qsession.close();
qcon.close();
}
public static void main(String[] args) throws Exception {
InitialContext ic = getInitialContext("jnp://host:port");
QueueReceive qr = new QueueReceive();
System.out.println("Ready to initialize");
qr.init(ic, QUEUE);
System.out.println("JMS Ready To Receive Messages (To quit, send a \"quit\" message).");
// qr.onMessage(qr.qreceiver.receive());
System.out.println("Message Receivd");
// 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);
}
}
When I run java program, it will not call the onMessage method directly, Please help me how to received the JMS message.
From this code I am able to ping the JMS messenger and unable to read the message?
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.
i'm using JMS for the first time. And i thought i have done everything right but when i send a message from a servlet it's not all the time consumed by the listner i don't know what's wrong sometime it works and sometimes it doesn't.
here's some of my code:
public void onMessage(Message message) {
try {
ObjectMessage objectMessage = (ObjectMessage) message;
OrdreDeTransfert ordreDeTransfert = (OrdreDeTransfert) objectMessage.getObject();
Long compte1Id = ordreDeTransfert.getIdSource();
Long compte2Id = ordreDeTransfert.getIdDestination();
int montant = ordreDeTransfert.getMontant();
gestionnaireDeCompteBancaire.transfert(compte1Id, compte2Id, montant);
} catch (JMSException ex) {
Logger.getLogger(transfertBancaireMDB.class.getName()).log(Level.SEVERE, null, ex);
}
in my servlet
private Message createJMSMessageForjmsOrdresTransfertBancaire(Session session, OrdreDeTransfert messageData) throws JMSException {
ObjectMessage tm = session.createObjectMessage(messageData);
tm.setJMSPriority(9);
return tm;
}
private void sendJMSMessageToOrdresTransfertBancaire(OrdreDeTransfert messageData) throws JMSException {
Connection connection = null;
Session session = null;
connection = loggingMessagesFactory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer messageProducer = session.createProducer(ordresTransfertBancaire);
messageProducer.setPriority(9);
messageProducer.send(createJMSMessageForjmsOrdresTransfertBancaire(session, messageData));
}