Unable to create JMS QueueConnection from QueueConnectionFactory in Jersey2 - jms

I'm working on migrating my existing EJB application from Jersey 1.x to 2.x. facing many challenges related to EJB and JMS queue concepts. I'm facing an Null pointer exception when the below code is executed.
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
public class SessionImpl implements SessionLocal {
#Resource(mappedName = "java:/RemoteJmsXA")
private QueueConnectionFactory queueConnectionFactory;
#Inject
private ConvRequestSessionLocal convRequestSession;
private RequestSessionLocal asyncSession;
#PostConstruct
public void initialize() {
QueueConnection connection = null;
QueueSession queueSession = null;
try {
connection = queueConnectionFactory.createQueueConnection();
queueSession = connection.createQueueSession(true, QueueSession.SESSION_TRANSACTED);
asyncSession = AsyncUtils.mixinAsync(convRequestSession);
} catch (JMSException e) {
LOG.error("Error ocurred while connecting to remote queues. " + e.getLocalizedMessage());
throw new RuntimeException("Error occured while connecting to remote queues.", e);
} finally {
try {
if (queueSession != null) {
queueSession.close();
}
if (connection != null) {
connection.close();
}
} catch (JMSException e) {
LOG.error("Error occured while closing connection to remote queues. " + e.getLocalizedMessage());
}
}
}
}
Exception:
2017-01-18 20:08:44,317 WARNING [org.glassfish.jersey.internal.Errors] (http-127.0.0.1-8080-4) The following warnings have been detected: WARNING: Unknown HK2 failure detected:
MultiException stack 1 of 2
java.lang.NullPointerException
at com.ejb.session.impl.SessionImpl.initialize(SessionImpl.java:809)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
stack trace shows that exception throws exactly in this line
connection = queueConnectionFactory.createQueueConnection();

Related

Messages not rolling back on K8s pod restarts when using Spring JMS Listener with Client Ack

We have Spring JMS application ( deployed on K8s) which processes about 100 - 400 messages/sec. The application consumes messages from IBM MQ and processes them. Off late we have started noticing messages getting dropped whenever K8s pod restarts or deployments are done even though we have message ack in place. I am looking for a solution here to resolve this issue.
Software
Version
Spring Boot
2.1.7.RELEASE
IBM MQ Client
9.1.0.5
JMS
2.0.1
Java
11
#Configuration
#EnableJms
public class MqConfiguration {
#Bean
public MQConnectionFactory mqConnectionFactory(Servers configProperties) {
MQConnectionFactory mqConnectionFactory = new MQConnectionFactory();
try {
mqConnectionFactory.setHostName(configProperties.getHost());
mqConnectionFactory.setQueueManager(configProperties.getQueueManager());
mqConnectionFactory.setPort(Integer.valueOf(configProperties.getPort()));
mqConnectionFactory.setChannel(configProperties.getChannel());
mqConnectionFactory.setTransportType(WMQConstants.WMQ_CM_CLIENT);
mqConnectionFactory.setCCSID(1208);
mqConnectionFactory.setClientReconnectOptions(WMQConstants.WMQ_CLIENT_RECONNECT);
} catch (Exception e) {
logger.logError(mqConnectionFactory, ,
"Failed to create MQ ConnectionFactory", String.valueOf(HttpStatus.SC_BAD_REQUEST), e);
}
return mqConnectionFactory;
}
#Bean(name = "messageListenerContainerFactory")
public DefaultJmsListenerContainerFactory provideJmsListenerContainerFactory(
MQConnectionFactory connectionFactory) {
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
factory.setSessionAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE);
factory.setErrorHandler(new ErrorHandler() {
#Override
public void handleError(Throwable t) {
ServiceMetrics metrics = new ServiceMetrics();
metrics.setCorrelationId(UUID.getUUID());
logger.logError(factory, "Exception occured at JMS Factory Container Listener", String.valueOf(HttpStatus.SC_BAD_REQUEST), t);
}
});
return factory;
}
#Bean(name = "jmsQueueTemplate")
public JmsTemplate provideJmsQueueTemplate(MQConnectionFactory connectionFactory) {
return new JmsTemplate(connectionFactory);
}
}
#Configuration
public class AsyncConfiguration {
#Autowired
private Servers configProperties;
#Bean(name = "asyncTaskExecutor")
public ExecutorService getAsyncTaskExecutor() {
String THREAD_POOL = "th-pool-";
return getExecutor(THREAD_POOL, 70,true);
}
private ExecutorService getExecutor(String threadName, int maxPoolSize, boolean cached) {
final ThreadFactory threadFactory = new CustomizableThreadFactory(threadName);
if (cached) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(0, maxPoolSize,
60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), threadFactory);
threadPoolExecutor.setRejectedExecutionHandler((r, executor) -> {
if (!executor.isShutdown()) {
try {
executor.getQueue().put(r);
} catch (InterruptedException e) {
throw new RejectedExecutionException(e);
}
}
});
return threadPoolExecutor;
} else {
return new ThreadPoolExecutor(maxPoolSize, maxPoolSize,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(),
threadFactory);
}
}
#Component
public class InputQueueListener {
#Autowired
private ExecutorService asyncTaskExecutor;
#JmsListener(destination = "${mqserver.queue}", containerFactory = "messageListenerContainerFactory", concurrency = "1-16")
public void processXMLMessage(Message message) {
CompletableFuture.runAsync(() -> processMessage(message), asyncTaskExecutor);
}
private void processMessage(Message message) {
String inputXmlMessage = null;
boolean isSuccess = false;
try {
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
inputXmlMessage = textMessage.getText();
} else if (message instanceof BytesMessage) {
BytesMessage byteMessage = (BytesMessage) message;
inputXmlMessage = CommonHelperUtil.getMessageFromBytes(byteMessage);
} else {
logger.logError(null, "Invalid message type received while converting Message to XML", String.valueOf(HttpStatus.SC_BAD_REQUEST));
errorQueuePublisher.publishErrorMessage(message);
try {
message.acknowledge();
} catch (JMSException jmsException) {
logger.logError(null, null, "Failed to Acknowledge XML message.",
String.valueOf(HttpStatus.SC_BAD_REQUEST), jmsException);
}
}
-
-
if (isSuccessProcessed) {
message.acknowledge();
} else {
message.acknowledge();
// Publishing back to the same queue
publishForRetry.publishMessageForRetry(message);
}
} catch (Exception e) {
if (StringUtils.isBlank(serviceMetrics.getCorrelationId())) {
serviceMetrics.setCorrelationId(UUID.getUUID());
}
logger.logError(null, null, "Exception while Converting Processing Message. Retrying to publish.",
String.valueOf(HttpStatus.SC_BAD_REQUEST), e);
// Publishing back to the same queue
publishForRetry.publishMessageForRetry(message);
try {
message.acknowledge();
} catch (JMSException jmsException) {
logger.logError(null, null,
"Failed to Acknowledge the Message when publishing" + "to Error Queue",
String.valueOf(HttpStatus.SC_BAD_REQUEST), jmsException);
}
}
}
}
}

com.ibm.mq.MQException: MQJE001: Completion Code 2, Reason 2009 using Sprint Boot with JMS (IBM MQ )

I am not sure what I am doing wrong, this issue is very sporadic, I have below code to send JMS Messages on IBM MQ. I am doing it in a seperate theread usign spring #async as below.
#Override
#Async
public void crewSeqAssignOrRemoveBatch(List<Batch> oBatchFosRequestList, String transactionType) throws InterruptedException {
long lStartTime = Instant.now().toEpochMilli();
logger.info("In Seperate Thread for FOS Submissoin, Thread Name is " + Thread.currentThread().getId() + ":"+Thread.currentThread().getName()+":"+Thread.currentThread().getThreadGroup()+":"+Thread.currentThread().activeCount()+":"+Thread.currentThread().getState());
logger.info("FHSeqAssignOrRemoveServiceImpl : crewSeqAssignOrRemoveBatch() : Start >>");
try
{
for (Iterator<Batch> iterator = oBatchFosRequestList.iterator(); iterator.hasNext();) {
Batch oBatchFosRequest = iterator.next();
UUID uniqueId = UUID.randomUUID();
String correlationId = uniqueId.toString() + "-" + oBatchFosRequest.getTransactionID() +"-"+ Calendar.getInstance().getTimeInMillis();
logger.info("correlationId generated is :" + correlationId);
try {
//JMSTextMessage message = null;
logger.info("Executing MessageCreator for ID "+ oBatchFosRequest.getTransactionID() +" on :" + new Date().toString());
MessageCreator mc = new MessageCreator() {
#Override
public Message createMessage(Session session) throws JMSException {
JMSTextMessage message = null;
try {
logger.info("Executing CreateMessage for ID "+ oBatchFosRequest.getTransactionID() +" on :" + new Date().toString());
//POINT 2
logger.info("Session Object ........ " + session.toString());
logger.info("Session Status - Is Session Transacted ?........ " + session.getTransacted());
logger.info("Session Status acknowledge mode........ " + session.getAcknowledgeMode());
logger.info("Ready to send message........ ");
logger.info("Send ConnectionFactory is: " + jmsQueueTemplate.getConnectionFactory().toString());
logger.info("Send destination is: " + jmsQueueTemplate.getDefaultDestination());
logger.info("Reply destination is: " + destination);
logger.info("Sent message correlationId is: " + correlationId);
logger.info("##########################################################");
message = (JMSTextMessage) session.createTextMessage();
String fosXmlBatchRequest = XMLUtil.createBatchFosRequestXML(oBatchFosRequest);
message.setText(fosXmlBatchRequest);
message.setJMSCorrelationID(correlationId);
logger.info(transactionType + " : Sending message is:");
logger.info(message.getText());
logger.info("##########################################################");
message.setJMSReplyTo(destination);
} catch (JMSException je) {
Exception ex = je.getLinkedException();
logger.info("JMS Linked Exception Occured :" + ex.getMessage());
ex.printStackTrace();
logger.info("JMS Exception Occured :" + je.getMessage());
je.printStackTrace();
}
catch (Exception e) {
logger.info("Exception Occured :" + e.getMessage());
e.printStackTrace();
}
return message;
}
};
logger.info("Executing send for ID "+ oBatchFosRequest.getTransactionID() +" on :" + new Date().toString());
logger.info("Calling Send Method ");
jmsQueueTemplate.send(mc);
logger.info("Send Completed");
My JMS Cnfiguration is as below :
import javax.jms.Destination;
import javax.jms.JMSException;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.jms.connection.CachingConnectionFactory;
import org.springframework.jms.connection.SingleConnectionFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
import org.springframework.jms.support.converter.MappingJackson2MessageConverter;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.MessageType;
import org.springframework.stereotype.Component;
import com.ibm.mq.jms.MQQueue;
import com.ibm.mq.jms.MQQueueConnectionFactory;
#Configurable
#Component
public class JMSConfiguration {
private final Logger log = LogManager.getLogger(JMSConfiguration.class);
#Autowired
MessageListenerReciever messageListenerReciever1;
#Autowired
MessageListenerReciever messageListenerReciever2;
private String hostName1;
private String hostName2;
private String hostName3;
private String writePort;
private String readPort;
private String channel;
private String transportType;
private String updateQueue;
private String replyQueue;
private String queueGateway;
#Autowired
JMSConfiguration(Environment environment){
this.hostName1 = environment.getRequiredProperty("jms.cf.write.hostName1");
this.hostName2 = environment.getRequiredProperty("jms.cf.read.hostName2");
this.hostName3 = environment.getRequiredProperty("jms.cf.read.hostName3");
this.writePort = environment.getRequiredProperty("jms.cf.write.port");
this.readPort = environment.getRequiredProperty("jms.cf.read.port");
this.channel = environment.getRequiredProperty("jms.cf.channel");
this.transportType = environment.getRequiredProperty("jms.cf.transportType");
this.updateQueue = environment.getRequiredProperty("jms.queue.update");
this.replyQueue = environment.getRequiredProperty("jms.queue.reply");
this.queueGateway = environment.getRequiredProperty("jms.queue.gateway");
}
#Bean
public MQQueueConnectionFactory connectionFactory1() {
MQQueueConnectionFactory connectionFactory = new MQQueueConnectionFactory();
try {
connectionFactory.setHostName(hostName1);
connectionFactory.setPort(Integer.parseInt(writePort));
connectionFactory.setChannel(channel);
connectionFactory.setTransportType(Integer.parseInt(transportType));
} catch (NumberFormatException | JMSException e) {
log.error(e.toString(),e);
}
return connectionFactory;
}
#Bean
#Primary
public CachingConnectionFactory cachingConnectionFactory(MQQueueConnectionFactory connectionFactory) {
CachingConnectionFactory oCachingConnectionFactory = new CachingConnectionFactory();
oCachingConnectionFactory.setTargetConnectionFactory(connectionFactory);
//oCachingConnectionFactory.setCacheProducers(true);
oCachingConnectionFactory.setSessionCacheSize(100);
oCachingConnectionFactory.setReconnectOnException(true);
return oCachingConnectionFactory;
}
public MQQueueConnectionFactory connectionFactory2() {
MQQueueConnectionFactory connectionFactory = new MQQueueConnectionFactory();
try {
connectionFactory.setHostName(hostName2);
connectionFactory.setPort(Integer.parseInt(readPort));
connectionFactory.setChannel(channel);
connectionFactory.setTransportType(Integer.parseInt(transportType));
} catch (NumberFormatException | JMSException e) {
log.error(e.toString(),e);
}
return connectionFactory;
}
public MQQueueConnectionFactory connectionFactory3() {
MQQueueConnectionFactory connectionFactory = new MQQueueConnectionFactory();
try {
connectionFactory.setHostName(hostName3);
connectionFactory.setPort(Integer.parseInt(readPort));
connectionFactory.setChannel(channel);
connectionFactory.setTransportType(Integer.parseInt(transportType));
} catch (NumberFormatException | JMSException e) {
log.error(e.toString(),e);
}
return connectionFactory;
}
#Bean
public Destination jmsDestinationResolverSender() throws JMSException {
return new MQQueue(updateQueue);
}
#Bean
public Destination jmsDestinationResolverReceiver() throws JMSException {
return new MQQueue(replyQueue);
}
#Bean
public Destination jmsDestinationResolverReplyTo() throws JMSException {
return new MQQueue(queueGateway, replyQueue);
}
#Bean
public JmsTemplate jmsQueueTemplate(SingleConnectionFactory oSingleConnectionFactory) throws JMSException {
JmsTemplate jmsTemplate = new JmsTemplate();
jmsTemplate.setConnectionFactory(oSingleConnectionFactory);
jmsTemplate.setDefaultDestination(jmsDestinationResolverSender());
jmsTemplate.afterPropertiesSet();
log.info("in jms configuration ConnectionFactory is:" + jmsTemplate.getConnectionFactory());
log.info("in jms configuration Send destination is:" + jmsTemplate.getDefaultDestination());
log.info("in jms configuration Send Delivery Delay is :" + jmsTemplate.getDeliveryDelay());
log.info("in jms configuration Send Delivery Mode is:" + jmsTemplate.getDeliveryMode());
return jmsTemplate;
}
#Bean
public DefaultMessageListenerContainer listenerContainer() throws JMSException {
DefaultMessageListenerContainer defMsgListCont = new DefaultMessageListenerContainer();
defMsgListCont.setConnectionFactory(connectionFactory3());
defMsgListCont.setDestination(jmsDestinationResolverReceiver());
defMsgListCont.setMessageListener(messageListenerReciever1);
defMsgListCont.afterPropertiesSet();
return defMsgListCont;
}
#Bean
public DefaultMessageListenerContainer listenerContainer2() throws JMSException {
DefaultMessageListenerContainer defMsgListCont = new DefaultMessageListenerContainer();
defMsgListCont.setConnectionFactory(connectionFactory2());
defMsgListCont.setDestination(jmsDestinationResolverReceiver());
defMsgListCont.setMessageListener(messageListenerReciever2);
defMsgListCont.afterPropertiesSet();
return defMsgListCont;
}
// Serialize message content to json using TextMessage
#Bean
public MessageConverter jacksonJmsMessageConverter() {
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
converter.setTargetType(MessageType.TEXT);
converter.setTypeIdPropertyName("_type");
return converter;
}
}
I am not sure where is the issue, But i strongly beleive its related to connection factory i am using , I am trying to use CachingConnectionFactory , But with below mentioend configuration it keeps sporadically failing with below code exception at this line
jmsQueueTemplate.send(mc);
Exceptiopn below :
> 12-12-2018 09:05:27.153 INFO htappp22 --- [ FAPS-FOS-5] c.a.f.s.FHSeqAssignOrRemoveServiceImpl : JMSException while Sending Message To FOS Outside
org.springframework.jms.UncategorizedJmsException: Uncategorized exception occurred during JMS processing; nested exception is javax.jms.JMSException: MQJMS2007: failed to send message to MQ queue; nested exception is com.ibm.mq.MQException: MQJE001: Completion Code 2, Reason 2009
at org.springframework.jms.support.JmsUtils.convertJmsAccessException(JmsUtils.java:316)
at org.springframework.jms.support.JmsAccessor.convertJmsAccessException(JmsAccessor.java:169)
at org.springframework.jms.core.JmsTemplate.execute(JmsTemplate.java:487)
at org.springframework.jms.core.JmsTemplate.send(JmsTemplate.java:559)
at org.springframework.jms.core.JmsTemplate.send(JmsTemplate.java:550)
at com.aa.faps.services.FHSeqAssignOrRemoveServiceImpl.crewSeqAssignOrRemoveBatch(FHSeqAssignOrRemoveServiceImpl.java:115)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.aop.interceptor.AsyncExecutionInterceptor$1.call(AsyncExecutionInterceptor.java:115)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.jms.JMSException: MQJMS2007: failed to send message to MQ queue
at com.ibm.mq.jms.services.ConfigEnvironment.newException(ConfigEnvironment.java:567)
at com.ibm.mq.jms.MQMessageProducer.sendInternal(MQMessageProducer.java:1743)
at com.ibm.mq.jms.MQMessageProducer.send(MQMessageProducer.java:1056)
at org.springframework.jms.connection.CachedMessageProducer.send(CachedMessageProducer.java:181)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.jms.connection.CachedMessageProducer$Jms2MessageProducerInvocationHandler.invoke(CachedMessageProducer.java:293)
at com.sun.proxy.$Proxy276.send(Unknown Source)
at org.springframework.jms.core.JmsTemplate.doSend(JmsTemplate.java:626)
at org.springframework.jms.core.JmsTemplate.doSend(JmsTemplate.java:597)
at org.springframework.jms.core.JmsTemplate$3.doInJms(JmsTemplate.java:562)
at org.springframework.jms.core.JmsTemplate.execute(JmsTemplate.java:484)
... 15 more

Mockito doThrow for JMS Client not throwing Exception

I am writing unit test case for my JMS client. But doThrow is not throwing any error. Looks like it is because my sendMessage method has return type as void and I have finally block to close the connection.
Is anyone facing the same issue?
doThrow(new JMSException("Expected")).when(messageSubmitter).sendMessage(message);
Here's the sendMessage method:
public void sendMessage(String message) throws JMSException,Exception {
Connection connection = connectionFactory.createConnection();
try {
connection.start();
try {
Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
try {
MessageProducer messageProducer =session.createProducer(messageQueue);
try {
TextMessage message = session.createTextMessage();
message.setText(messageQueue);
messageProducer.send(message);
}
} finally {
JmsUtils.closeProducer(messageProducer);
}
} finally {
JmsUtils.closeSession(session);
}
} finally {
JmsUtils.closeConnection(connection);
}
} catch (JMSException ex) {
throw ex;
} catch(Exception ex) {
throw ex;
}
}
This is my test method and above is my jms client method.
#Test
public void myAction_should_return_failure_result_in_case_of_JMS_excepti‌​on() throws Exception {
// given
String message ="Test";
doThrow(exception).when(MessageSubmitter.sendMessage(message‌​);
//when
ActionResult processingResult = Submitter.myActionOn("123");
//then
assertFalse(processingResult.isProcessedSuccessfully());
assertEquals(exception, processingResult.getException());
}

How to subscribe to an existing advisory topic?

I have activemq5.3.2 running and I wanted to subscribe existing advisory topics using my java program. while, `jndi` lookup I am getting following error:
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(NamingManager.java:657)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:259)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:296)
at javax.naming.InitialContext.lookup(InitialContext.java:363)
at jmsclient.Consumer.<init>(Consumer.java:38)
at jmsclient.Consumer.main(Consumer.java:74)
Exception occurred: javax.jms.InvalidDestinationException: Don't understand null destinations
Please suggest where the problem is, or how could I use my topic name to look for?
package jmsclient;
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.activemq.ActiveMQConnectionFactory;
public class Consumer implements MessageListener {
private static int ackMode;
private static String clientTopicName;
private boolean transacted = false;
//private MessageConsumer messageConsumer;
static {
clientTopicName = "ActiveMQ.Advisory.Consumer.Queue.example.A";
ackMode = Session.AUTO_ACKNOWLEDGE;
}
#SuppressWarnings("null")
public Consumer()
{// TODO Auto-generated method stub
TextMessage message = null;
Context jndiContext;
//TopicConnectionFactory topicConnectionFactory = null;
TopicConnection topicConnection = null;
TopicSession topicSession = null;
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://usaxwas012ccxra.ccmp.ibm.lab:61616");
try{
Topic myTopic = null;
try { jndiContext = new InitialContext();
myTopic = (Topic) jndiContext.lookup(clientTopicName);
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
topicConnection = connectionFactory.createTopicConnection();
topicConnection.start();
topicSession = topicConnection.createTopicSession(transacted, ackMode);
TopicSubscriber topicSubscriber = topicSession.createSubscriber(myTopic);
Message m = topicSubscriber.receive(1000);
if (m != null) {
if (m instanceof TextMessage) {
message = (TextMessage) m;
System.out.println("Reading message: " + message.getText());
}
}
} //try ends
catch (JMSException e) {
System.out.println("Exception occurred: " + e.toString());
} finally {
if (topicConnection != null) {
try {
topicConnection.close();
} catch (JMSException e) {}
}}}
public void onMessage(Message arg0) {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
new Consumer();
}
}

Db2 connection error

im trying to connect my java to db2 database but im getting an error :
"Execution failed due to a distribution protocol error that will affect the successful execution of subsequent DDM commands or SQL statements.
A connection could not be established to the database because manager 0x2407 at level 0x3 is not supported."
What do you think im doing wrong? Here is my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class conUrl {
public static void main(String[] args) {
String jdbcClassName="com.ibm.db2.jcc.DB2Driver";
String url="jdbc:db2://host:50000/test";
String user="dbuser";
String password="passwrod";
Connection connection = null;
//Statement st = null;
//Result rs = null;
try {
//Load class into memory
Class.forName(jdbcClassName);
//Establish connection
connection = DriverManager.getConnection(url,user,password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(connection!=null){
System.out.println("Connected successfully.");
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}

Resources