Publish messages to remote JMS provider in transaction
sai.pabbathi Mar 2, 2017 8:46 PMI have the following code which sends messages to a remote jms provider(Tibco) in this case, I am looking for a solution to put the sending code into a Bean managed transaction or the usertransaction, but not sure how to do that. I have the generic resource adapter setup already for consuming the messages from the tibco.
Tech stack/background:
Wildfly, CDI, Tibco ems 8.2 JMS provider, Java8, Using Standalone-full.xml, Added genericra.rar resource adapter file for consuming messages and that works. Message driven beans for consuming messages.
import java.util.Hashtable; import javax.annotation.Resource; import javax.inject.Singleton; 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.transaction.Transactional; import javax.transaction.Transactional.TxType; import javax.transaction.UserTransaction; @Singleton public class ServiceLayer implements IServiceLayer{ public final static String JNDI_FACTORY = "com.tibco.tibjms.naming.TibjmsInitialContextFactory"; public final static String PROVIDER_URL = "tcp://serverurl:7225"; public final static String JMS_FACTORY = "XAQueueConnectionFactory"; public final static String QUEUE = "Queue"; @Resource public UserTransaction utx; public void sendMessage(String message) throws Exception { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY); env.put(Context.PROVIDER_URL, PROVIDER_URL); for (int i = 0; i < 1; i++) { // Define queue QueueSender qsender = null; QueueSession qsession = null; QueueConnection qcon = null; try { utx.begin(); InitialContext ctx = new InitialContext(env); QueueConnectionFactory qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY); qcon = qconFactory.createQueueConnection(); qsession = qcon.createQueueSession(true, -1); Queue queue = (Queue) ctx.lookup(QUEUE); TextMessage msg = qsession.createTextMessage(); msg.setText(message); qsender = qsession.createSender(queue); qsender.send(msg); System.out.println("sleep 5 secs.." + message.toString()); Thread.sleep(5000); System.out.println("Message [" + msg.getText() + "] sent to Queue: " + QUEUE); // qsession.commit(); utx.commit(); } catch (Exception ex) { ex.printStackTrace(); } finally { if (qsender != null) qsender.close(); if (qsession != null) qsession.close(); if (qcon != null) qcon.close(); } } } }