ActiveMQConnectionFactory - trusted packages not taken into account - java

I have an active MQ factory in a Spring Boot app, type ActiveMQConnectionFactory.
Right after instantiating it I set the trusted packages to just java.lang since I want to be able to send/receive just Strings via JMS in my app.
See also here:
SpringBoot + ActiveMQ - How to set trusted packages?
https://stackoverflow.com/a/36622567/2300597
#Bean(name="jmsConnectionFactory")
public ConnectionFactory getJMSConnectionFactory(){
_factory = new ActiveMQConnectionFactory(active_MQ_BrokerURL);
ActiveMQConnectionFactory fct = ((ActiveMQConnectionFactory)_factory);
fct.setTrustAllPackages(false);
fct.setTrustedPackages(Arrays.asList("java.lang"));
return _factory;
}
And yet I am able to send other objects (not from package java.lang)?!
I don't get an Exception of some sort when sending them.
Why is that? What am I doing wrong?
NOTE: I am using org.springframework.jms.core.JmsTemplate to send the messages
(in case that matters). The template is linked to that factory.
public void sendObjectMessage(final Serializable msg) {
try {
this.jmsTemplate.send(this.queue, new MessageCreator() {
public Message createMessage(final Session session) throws JMSException {
return session.createObjectMessage(msg);
}
});
logger.info("Success sending Object MQ message [{}]", msg);
} catch (Exception e) {
logger.error("Error sending Object MQ message [{}]", msg, e);
}
}

You can run the code below to validate that it is not an ActiveMQ issue.
What is the consumer side of your code?
How are you confirming messages are not sent?
There is a candidate if the messages are not being received-- if Spring JMS is using the JMS 2.0 API jar, there is a new API call for ObjectMessage that could be bombing out under the covers.
import java.io.Serializable;
import java.util.Arrays;
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnectionFactory;
public class JmsUrlTest {
private static String brokerUrl = "tcp://localhost:61616";
private static ActiveMQConnectionFactory activemqConnectionFactory = new ActiveMQConnectionFactory("admin", "admin", brokerUrl);
public static void main(String[] args) {
try {
activemqConnectionFactory.setTrustedPackages(Arrays.asList("java.lang"));
Connection connection = activemqConnectionFactory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer messageProducer = session.createProducer(session.createQueue("OBJECT.TEST"));
Message message = session.createObjectMessage(new String("Test object"));
message.setJMSType("java.lang.String");
messageProducer.send(message);
System.out.println("Sent message " + message.getJMSMessageID());
MessageConsumer messageConsumer = session.createConsumer(session.createQueue("OBJECT.TEST"));
boolean stop = false;
int loopCount = 0;
int maxLoops = 10;
Message recvMessage = null;
do {
recvMessage = messageConsumer.receive(2000l);
if(recvMessage != null || loopCount >= maxLoops) {
stop = true;
}
} while (!stop);
if(recvMessage != null && ObjectMessage.class.isAssignableFrom(recvMessage.getClass())) {
ObjectMessage recvObjectMessage = ObjectMessage.class.cast(recvMessage);
Serializable recvSerializableBody = recvObjectMessage.getObject();
if(recvSerializableBody.getClass().isAssignableFrom(String.class)) {
System.out.println("Recieved ObjectMessage w/ String body: " + String.class.cast(recvSerializableBody));
} else {
System.out.println("Received body was not a String.class");
}
} else {
System.out.println("No message received");
}
} catch (JMSException e) {
e.printStackTrace();
} finally {
}
}
}

Related

Any solution regarding sending a file to IBM MQ

Good afternoon all, I have an issue with IBM MQ, I'm supposed to use JMS to connect to a defined queue then send an XML file to the defined queue. Any help with this problem is gladly appreciated.
In this image it shows that no message is received even though in eclipse IDE it states other wise:
I have a coded application that should work it sends and receives a message the problem is that when I check my IBM MQ explorer and my linux MQ server nothing appears so I'm not sure if its the server configurations that are wrong.
Here is the code I was referring to :
package mqtest;
import javax.jms.Destination;
import javax.jms.JMSConsumer;
import javax.jms.JMSContext;
import javax.jms.JMSException;
import javax.jms.JMSProducer;
import javax.jms.TextMessage;
import com.ibm.msg.client.jms.JmsConnectionFactory;
import com.ibm.msg.client.jms.JmsFactoryFactory;
import com.ibm.msg.client.wmq.WMQConstants;
import javax.jms.JMSConsumer;
import javax.jms.JMSContext;
import javax.jms.JMSException;
import javax.jms.JMSProducer;
import javax.jms.TextMessage;
import com.ibm.msg.client.jms.JmsConnectionFactory;
import com.ibm.msg.client.jms.JmsFactoryFactory;
import com.ibm.msg.client.wmq.WMQConstants;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class JmsIOPutGet {
// System exit status value (assume unset value to be 1)
private static int status = 1;
// Create variables for the connection to MQ
private static final String HOST = "13.246.126.217"; // Host name or IP address
private static final int PORT = 1416; // Listener port for your queue manager
private static final String CHANNEL = "DEV.APP.SVRCONN"; // Channel name
private static final String QMGR = "qm5"; // Queue manager name
private static final String APP_USER = "mqm"; // Windows user name that application uses to connect to MQ
private static final String APP_PASSWORD = "Kion2018"; // Windows user password associated with APP_USER
private static final String QUEUE_NAME = "Q2"; // Queue that the application uses to put and get messages to and from
/**
* Main method
*
* #param args
*/
public static void main(String[] args) {
// Variables
JMSContext context = null;
Destination destination = null;
JMSProducer producer = null;
JMSConsumer consumer = null;
try {
// Create a connection factory
JmsFactoryFactory ff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
JmsConnectionFactory cf = ff.createConnectionFactory();
// Set the properties
cf.setStringProperty(WMQConstants.WMQ_HOST_NAME, HOST);
cf.setIntProperty(WMQConstants.WMQ_PORT, PORT);
cf.setStringProperty(WMQConstants.WMQ_CHANNEL, CHANNEL);
cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT);
cf.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, QMGR);
cf.setStringProperty(WMQConstants.WMQ_APPLICATIONNAME, "JmsPutGet (JMS)");
cf.setBooleanProperty(WMQConstants.USER_AUTHENTICATION_MQCSP, true);
cf.setStringProperty(WMQConstants.USERID, APP_USER);
cf.setStringProperty(WMQConstants.PASSWORD, APP_PASSWORD);
//cf.setStringProperty(WMQConstants.WMQ_SSL_CIPHER_SUITE, "*TLS12");
// Create JMS objects
context = cf.createContext();
destination = context.createQueue("queue:///" + QUEUE_NAME);
// Read given file
File myObj = new File("C:\\Users\\Lesego\\OneDrive\\Documents\\Test Files\\application.xml");
Scanner myReader = new Scanner(myObj);
String msg = "";
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
msg = msg + data;
}
myReader.close();
TextMessage message = context.createTextMessage(msg);
producer = context.createProducer();
producer.send(destination, message);
System.out.println("Sent message:\n" + message);
consumer = context.createConsumer(destination); // autoclosable
String receivedMessage = consumer.receiveBody(String.class, 15000); // in ms or 15 seconds
System.out.println("\nReceived message:\n" + receivedMessage);
recordSuccess();
} catch (JMSException jmsex) {
recordFailure(jmsex);
} catch (FileNotFoundException e) {
System.out.println("File not found.");
e.printStackTrace();
}
System.exit(status);
} // end main()
/**
* Record this run as successful.
*/
private static void recordSuccess() {
System.out.println("SUCCESS");
status = 0;
return;
}
/**
* Record this run as failure.
*
* #param ex
*/
private static void recordFailure(Exception ex) {
if (ex != null) {
if (ex instanceof JMSException) {
processJMSException((JMSException) ex);
} else {
System.out.println(ex);
}
}
System.out.println("FAILURE");
status = -1;
return;
}
/**
* Process a JMSException and any associated inner exceptions.
*
* #param jmsex
*/
private static void processJMSException(JMSException jmsex) {
System.out.println(jmsex);
Throwable innerException = jmsex.getLinkedException();
if (innerException != null) {
System.out.println("Inner exception(s):");
}
while (innerException != null) {
System.out.println(innerException);
innerException = innerException.getCause();
}
return;
}

How do I start a threaded session in Active MQ 5.x

I guess it is kind of a standard knowledge question, but will current_session run threaded or not?
ActiveMQSession current_session = (ActiveMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Thread sessionThreads = new Thread(current_session);
sessionThreads.start();
If not, can please someone show me a code example how I run a session threaded?
What I want is concurrent sessions with producers/consumers which write/listen to their specific queues. I already tried to write a custom Thread by passing the connection to the thread, but when I created Producers I run into an error, 'that I can't start a Producer on an unregistered session'.
There is no constructor for java.lang.Thread that will accept a org.apache.activemq.ActiveMQSession object. Your code won't even compile let alone run.
Here's a simple client that will create threads for producing and consuming messages:
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
public class MyMultiThreadedApp {
class MyConsumer extends Thread {
private final Connection connection;
private final Destination destination;
MyConsumer(Connection connection, Destination destination) {
this.connection = connection;
this.destination = destination;
}
#Override
public void run() {
try (Session session = connection.createSession(Session.AUTO_ACKNOWLEDGE)) {
MessageConsumer messageConsumer = session.createConsumer(destination);
connection.start();
Message message = messageConsumer.receive(5000);
if (message == null) {
System.out.println("Did not receive message within the allotted time.");
return;
}
System.out.println("Received message: " + message);
} catch (Throwable e) {
e.printStackTrace();
return;
}
}
}
class MyProducer extends Thread {
private final Connection connection;
private final Destination destination;
MyProducer(Connection connection, Destination destination) {
this.connection = connection;
this.destination = destination;
}
#Override
public void run() {
try (Session session = connection.createSession(Session.AUTO_ACKNOWLEDGE)) {
MessageProducer messageProducer = session.createProducer(destination);
messageProducer.send(session.createTextMessage("My message"));
System.out.println("Sent message");
} catch (Throwable e) {
e.printStackTrace();
return;
}
}
}
public static void main(String... args) throws Exception {
MyMultiThreadedApp myMultiThreadedApp = new MyMultiThreadedApp();
InitialContext initialContext = null;
initialContext = new InitialContext();
Queue queue = (Queue) initialContext.lookup("queue/exampleQueue");
ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory");
Connection connection = cf.createConnection();
Thread myConsumer = myMultiThreadedApp.runConsumer(connection, queue);
Thread myProducer = myMultiThreadedApp.runProducer(connection, queue);
myConsumer.join();
myProducer.join();
}
private Thread runConsumer(Connection connection, Destination destination) {
MyConsumer myConsumer = new MyConsumer(connection, destination);
myConsumer.start();
return myConsumer;
}
private Thread runProducer(Connection connection, Destination destination) {
MyProducer myProducer = new MyProducer(connection, destination);
myProducer.start();
return myProducer;
}
}

How to dequeue all messages in ActiveMQ?

I have this sender class which is sending messages to myQueue.
Sender.java
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.commons.collections.Factory;
public class Sender {
private ConnectionFactory factory = null;
private Connection connection = null;
private Session session = null;
private Destination destination = null;
private MessageProducer producer = null;
String [] messages = new String[] {"Hello ...My name is vaniiiiiiiiiii tanejaaaaaaaaaaaaaa",
"Hello ...My name is priyanka tanejaaaaaaaaaaaaaa",
"Hello ...My name is rahul tanejaaaaaaaaaaaaaa",
"Hello ...My name is popo tanejaaaaaaaaaaaaaa"};
public void sendMessage(){
factory = new ActiveMQConnectionFactory(
"tcp://localhost:61619");
try {
connection= factory.createConnection();
connection.start();
session= connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
destination=session.createQueue("Parul");
producer = session.createProducer(destination);
TextMessage message = session.createTextMessage();
for(int i=0;i<messages.length;i++){
message.setText(messages[i]);
System.out.println("Sent: " + message.getText());
producer.send(message);
}
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
Sender sender = new Sender();
sender.sendMessage();
}
}
My message is getting published to activemq now we want to read messages from activemq. So i have written class Consumer.
Consumer.java
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.camel.Main;
public class Reciever implements MessageListener{
private ConnectionFactory factory;
private Connection connection;
private Session session;
private Destination destination;
private MessageConsumer consumer = null;
Reciever(){
}
void recieveMessage(){
factory= new ActiveMQConnectionFactory("tcp://localhost:61619");
try {
connection=factory.createConnection();
connection.start();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
System.out.println("session started");
destination=session.createQueue("Parul");
consumer = session.createConsumer(destination);
System.out.println("Consumer created");
while (true) {
System.out.println("About to read");
Message msg = consumer.receive(5000);
if (msg instanceof TextMessage) {
TextMessage tm = (TextMessage) msg;
System.out.println(tm.getText());
}
else{
System.out.println("Queue Empty");
connection.stop();
break;
}
}
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
Reciever reciever = new Reciever();
reciever.recieveMessage();
}
}
But my consumer is not able to read message from queue. What is the issue. Can you help me out in this.I want to read all 4 messsages at same time.

Message MQTT not receive in subscribe client

I'm working on MQTT protocol and I try to publish and subscribe with 2 distincts Java applications.
My first application is "Publish". I'm publish on a MQTT server a message.
My second application is "Subscribe". I'm subscribe to a topic and try to receive the message. But I never receive the message.
When I run the 2 applications, I begin with the "Subscribe" application and after I run the "Publish" application. When the "Publish" application begin, I lose my connection to the "Subscribe" application and I can't receive my message.
In the "Subscribe" application, my method messageArrived() is never called by client.setCallback(this). (See the code below).
Here is my 2 code application :
Publish Application :
Class PubClient :
package publishclient;
import java.util.Random;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttAsyncClient;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class PubClient implements MqttCallback {
MqttClient client;
MqttConnectOptions connOpt;
Random rand = new Random();
int nbRandom = 0;
int valMax =151, valMin = 40;
public PubClient() throws MqttException {
String broker = "tcp://88.177.147.17:1883"; // Adress MQTT Server
String clientId = "0bdd-4445-82f3-928f8ddb1887"; // ClientID
String topic1f = "ApplicationRio/capteur"; // Topic
int QoSserveur = 2;
try {
String uuid = "ac8da3c6-0bdd-4445-82f3-928f8ddb3294";
MemoryPersistence persistence = new MemoryPersistence();
// Create 2 objects : client and connOpt
client = new MqttClient(broker, clientId, persistence);
connOpt = new MqttConnectOptions();
connOpt.setCleanSession(true);
client.setCallback(this);
// Connection to MQTT server
System.out.println("Connexion a : " + broker + " Publisher");
client.connect(connOpt);
//Create random number for my message
nbRandom = valMin + rand.nextInt(valMax-valMin);
System.out.println("nb aleatoire = " + nbRandom);
String messageAEnvoyer = uuid + "//" + nbRandom;
System.out.println("Message a envoyer : " + messageAEnvoyer);
MqttMessage message = new MqttMessage();
message.setPayload(messageAEnvoyer.getBytes());
message.setQos(QoSserveur);
client.publish(topic1f, message);
} catch(MqttException e) {
e.printStackTrace();
}
}
#Override
public void connectionLost(Throwable thrwbl) {System.out.println("Perdue connexion");}
#Override
public void messageArrived(String string, MqttMessage mm) throws Exception {
System.out.println("Message recu est : "+ new String(mm.getPayload()));}
#Override
public void deliveryComplete(IMqttDeliveryToken imdt) {
System.out.println("Message delivre au broker");
}
}
The main (Publish) :
package publishclient;
import org.eclipse.paho.client.mqttv3.MqttException;
public class PublishClient {
public static void main(String[] args) throws MqttException {
PubClient publieur = new PubClient();
}
The "subscribe" application :
Class SubClient :
package subscribeclient;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
public class SubClient implements MqttCallback {
MqttClient clientsub;
MqttConnectOptions connOpt;
public SubClient() throws MqttException{
String broker = "tcp://88.177.147.17:1883"; // Adress MQTT Server
String clientId = "0bdd-4445-82f3-928f8ddb1887"; // ClientID
String topic1f = "ApplicationRio/capteur"; // Topic
int QoSserveur = 2;
try{
// Create 2 objects : client and connOpt
clientsub = new MqttClient(broker, clientId);
connOpt = new MqttConnectOptions();
connOpt.setCleanSession(false);
connOpt.setKeepAliveInterval(30);
clientsub.setCallback(this);
// Connection to MQTT Server
System.out.println("Connexion a : " + broker + " Subscriber");
clientsub.connect(connOpt);
clientsub.subscribe(topic1f,QoSserveur);
} catch(MqttException e){
e.printStackTrace();
}
}
#Override
public void connectionLost(Throwable thrwbl) {
System.out.println("Connexion perdue");
}
#Override
public void messageArrived(String string, MqttMessage message) throws Exception {
System.out.println("Le message recu est : " + new String(message.getPayload()));
}
#Override
public void deliveryComplete(IMqttDeliveryToken imdt) {
System.out.println("Message arrive");
}
}
The main (Subscribe) :
package subscribeclient;
import org.eclipse.paho.client.mqttv3.MqttException;
public class SubscribeClient {
public static void main(String[] args) throws MqttException {
SubClient subscriber = new SubClient();
}
}
My 2 applications need to run in the same time, and I don't need to disconnect because I run applications all the time.
So, have you got an idea of why my "Subscribe Client" disconnect when I run the "Publish Client" and why I can't receive my message on my "Subscribe Message" ?
I use org.eclipse.paho.client.mqttv3-1.0.2.jar for the library for MQTT.
Client IDs have to be unique between ALL clients. You have used the same client ID for the publisher and subscriber so the broker will kick the subscriber off when the publisher connects.

Concurrent JMS messages cause NULL

I've tested JMS messages sending serially and concurrently(5 threads send jms messages concurrently from the producer).
When I send 100 messages concurrently, few messages payload at the receiving end are NULL. When sent serially there is no issue.
Do I need to setup a session pool or use MDB at the consumer side to handle the messages concurrently? The setup of the JMS is good, because we are receiving messages. Am I missing anything here?
Short description of the pproject setup:
Publisher is a stateless session bean
Weblogic 8.1 jms server connection factory and destination are retrieved through
JNDI
Consumer is a java class which subscribes to this server JMS queue
and performs the tasks. (this is not a MDB or a Threaded class, listens to the queue
asynchronously)
EDITED
JmsConsumer
package net;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Hashtable;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
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.Context;
import javax.naming.InitialContext;
public class ReadJMS implements MessageListener, ExceptionListener {
public final static String JNDI_FACTORY = "weblogic.jndi.WLInitialContextFactory";
public final static String PROVIDER_URL = "t3://address:7003";
public final static String JMS_FACTORY = "MSS.QueueConnectionFactory";
public final static String QUEUE = "jms.queue";
#SuppressWarnings("null")
public void receiveMessage() throws Exception {
// System.out.println("receiveMessage()..");
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
env.put(Context.PROVIDER_URL, PROVIDER_URL);
// Define queue
QueueReceiver qreceiver = null;
QueueSession qsession = null;
QueueConnection qcon = null;
ReadJMS async = new ReadJMS();
try {
InitialContext ctx = new InitialContext(env);
QueueConnectionFactory qconFactory = (QueueConnectionFactory) ctx
.lookup(JMS_FACTORY);
qcon = qconFactory.createQueueConnection();
qcon.setExceptionListener(async);
qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = (Queue) ctx.lookup(QUEUE);
qreceiver = qsession.createReceiver(queue);
qreceiver.setMessageListener(async);
qcon.start();
System.out.println("readingMessage()..");
// TextMessage msg = (TextMessage) qreceiver.receive();
// System.out.println("Message read from " + QUEUE + " : "
// + msg.getText());
// msg.acknowledge();
} catch (Exception ex) {
ex.printStackTrace();
}
// } finally {
// if (qreceiver != null)
// qreceiver.close();
// if (qsession != null)
// qsession.close();
// if (qcon != null)
// qcon.close();
// }
}
public static void main(String[] args) throws Exception {
ReadJMS test = new ReadJMS();
System.out.println("init");
test.receiveMessage();
while (true) {
Thread.sleep(10000);
}
}
public void onException(JMSException arg0) {
System.err.println("Exception: " + arg0.getLocalizedMessage());
}
public synchronized void onMessage(Message arg0) {
try {
if(((TextMessage)arg0).getText() == null || ((TextMessage)arg0).getText().trim().length()==0){
System.out.println(" " + QUEUE + " : "
+ ((TextMessage) arg0).getText());
}
System.out.print(".");
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter("Output.txt", true)));
Date now = new Date();
out.println("message: "+now.toString()+ " - "+((TextMessage)arg0).getText()+"");
out.close();
} catch (JMSException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
WriteJms
package net;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Hashtable;
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;
public class WriteJMS {
public final static String JNDI_FACTORY = "weblogic.jndi.WLInitialContextFactory";
public final static String PROVIDER_URL = "t3://url:7003";
public final static String JMS_FACTORY = "MSS.QueueConnectionFactory";
public final static String QUEUE = "jms.queue";
#SuppressWarnings("unchecked")
public void sendMessage() throws Exception {
#SuppressWarnings("rawtypes")
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
env.put(Context.PROVIDER_URL, PROVIDER_URL);
// Define queue
QueueSender qsender = null;
QueueSession qsession = null;
QueueConnection qcon = null;
try {
InitialContext ctx = new InitialContext(env);
QueueConnectionFactory qconFactory = (QueueConnectionFactory) ctx
.lookup(JMS_FACTORY);
qcon = qconFactory.createQueueConnection();
qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = (Queue) ctx.lookup(QUEUE);
TextMessage msg = qsession.createTextMessage();
msg.setText("<eventMessage><eventId>123</eventId><eventName>123</eventName><documentNumber>123</documentNumber><customerId>123</customerId><actDDTaskDate>123</actDDTaskDate><taskStatusErrorMessage>123</taskStatusErrorMessage></eventMessage>");
qsender = qsession.createSender(queue);
qsender.send(msg);
System.out.println("Message [" + msg.getText()
+ "] sent to Queue: " + QUEUE);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (qsender != null)
qsender.close();
if (qsession != null)
qsession.close();
if (qcon != null)
qcon.close();
}
}
}
Reusing a session across multiple threads is notoriously forbidden. But you don't do this. You create everything (connection session and producer) anew for each message. That is inefficient, but not incorrect and should not cause these errors. The code you give us looks good to me.
I am a little surprised that no exceptions occur at the sending side. Can you give some more details about the JMS implementation? Perhaps there's more information in the message broker's log?
Have you counted the messages and does the number received equal the amount sent? Could someone else be sending messages to the same queue?

Categories