List of usage examples for javax.jms Connection start
void start() throws JMSException;
From source file:org.codehaus.stomp.jms.ProtocolConverter.java
protected void onStompConnect(StompFrame command) throws IOException, JMSException { if (noneXaSession != null) { throw new ProtocolException("Already connected."); }/*w ww. j a v a 2 s . com*/ Map<String, Object> headers = command.getHeaders(); login = (String) headers.get(Stomp.Headers.Connect.LOGIN); passcode = (String) headers.get(Stomp.Headers.Connect.PASSCODE); clientId = (String) headers.get(Stomp.Headers.Connect.CLIENT_ID); Connection noneXaConnection; if (login != null) { noneXaConnection = noneXAConnectionFactory.createConnection(login, passcode); } else { noneXaConnection = noneXAConnectionFactory.createConnection(); } if (clientId != null) { noneXaConnection.setClientID(clientId); } noneXaConnection.start(); Session session = noneXaConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); if (log.isDebugEnabled()) { log.debug("Created session with ack mode: " + session.getAcknowledgeMode()); } this.noneXaSession = new StompSession(initialContext, this, session, noneXaConnection); Map<String, Object> responseHeaders = new HashMap<String, Object>(); responseHeaders.put(Stomp.Headers.Connected.SESSION, clientId); String requestId = (String) headers.get(Stomp.Headers.Connect.REQUEST_ID); if (requestId == null) { // TODO legacy requestId = (String) headers.get(Stomp.Headers.RECEIPT_REQUESTED); } if (requestId != null) { // TODO legacy responseHeaders.put(Stomp.Headers.Connected.RESPONSE_ID, requestId); responseHeaders.put(Stomp.Headers.Response.RECEIPT_ID, requestId); } StompFrame sc = new StompFrame(); sc.setAction(Stomp.Responses.CONNECTED); sc.setHeaders(responseHeaders); sendToStomp(sc); }
From source file:org.apache.qpid.systest.management.jmx.QueueManagementTest.java
public void testMoveMessagesBetweenQueuesWithActiveConsumerOnDestinationQueue() throws Exception { setTestClientSystemProperty(ClientProperties.MAX_PREFETCH_PROP_NAME, new Integer(1).toString()); Connection asyncConnection = getConnection(); asyncConnection.start(); final int numberOfMessagesToSend = 50; sendMessage(_session, _sourceQueue, numberOfMessagesToSend); syncSession(_session);/* www . ja v a2 s .c o m*/ assertEquals("Unexpected queue depth after send", numberOfMessagesToSend, _managedSourceQueue.getMessageCount().intValue()); List<Long> amqMessagesIds = getAMQMessageIdsOn(_managedSourceQueue, 1, numberOfMessagesToSend); long fromMessageId = amqMessagesIds.get(0); long toMessageId = amqMessagesIds.get(numberOfMessagesToSend - 1); AtomicInteger totalConsumed = new AtomicInteger(0); CountDownLatch allMessagesConsumedLatch = new CountDownLatch(numberOfMessagesToSend); startAsyncConsumerOn(_destinationQueue, asyncConnection, allMessagesConsumedLatch, totalConsumed); _managedSourceQueue.moveMessages(fromMessageId, toMessageId, _destinationQueueName); allMessagesConsumedLatch.await(5000, TimeUnit.MILLISECONDS); assertEquals("Did not consume all messages from destination queue", numberOfMessagesToSend, totalConsumed.intValue()); }
From source file:org.apache.qpid.systest.management.jmx.QueueManagementTest.java
public void testMoveMessagesBetweenQueuesWithActiveConsumerOnSourceQueue() throws Exception { setTestClientSystemProperty(ClientProperties.MAX_PREFETCH_PROP_NAME, new Integer(1).toString()); Connection asyncConnection = getConnection(); asyncConnection.start(); final int numberOfMessagesToSend = 50; sendMessage(_session, _sourceQueue, numberOfMessagesToSend); syncSession(_session);// ww w . ja v a2 s . c o m assertEquals("Unexpected queue depth after send", numberOfMessagesToSend, _managedSourceQueue.getMessageCount().intValue()); List<Long> amqMessagesIds = getAMQMessageIdsOn(_managedSourceQueue, 1, numberOfMessagesToSend); long fromMessageId = amqMessagesIds.get(0); long toMessageId = amqMessagesIds.get(numberOfMessagesToSend - 1); CountDownLatch consumerReadToHalfwayLatch = new CountDownLatch(numberOfMessagesToSend / 2); AtomicInteger totalConsumed = new AtomicInteger(0); startAsyncConsumerOn(_sourceQueue, asyncConnection, consumerReadToHalfwayLatch, totalConsumed); boolean halfwayPointReached = consumerReadToHalfwayLatch.await(5000, TimeUnit.MILLISECONDS); assertTrue("Did not read half of messages within time allowed", halfwayPointReached); _managedSourceQueue.moveMessages(fromMessageId, toMessageId, _destinationQueueName); asyncConnection.stop(); // The exact number of messages moved will be non deterministic, as the number of messages processed // by the consumer cannot be predicted. There is also the possibility that a message can remain // on the source queue. This situation will arise if a message has been acquired by the consumer, but not // yet delivered to the client application (i.e. MessageListener#onMessage()) when the Connection#stop() occurs. // // The number of messages moved + the number consumed + any messages remaining on source should // *always* be equal to the number we originally sent. int numberOfMessagesReadByConsumer = totalConsumed.intValue(); int numberOfMessagesOnDestinationQueue = _managedDestinationQueue.getMessageCount().intValue(); int numberOfMessagesRemainingOnSourceQueue = _managedSourceQueue.getMessageCount().intValue(); LOGGER.debug("Async consumer read : " + numberOfMessagesReadByConsumer + " Number of messages moved to destination : " + numberOfMessagesOnDestinationQueue + " Number of messages remaining on source : " + numberOfMessagesRemainingOnSourceQueue); assertEquals("Unexpected number of messages after move", numberOfMessagesToSend, numberOfMessagesReadByConsumer + numberOfMessagesOnDestinationQueue + numberOfMessagesRemainingOnSourceQueue); }
From source file:com.cws.esolutions.core.utils.MQUtils.java
/** * Puts an MQ message on a specified queue and returns the associated * correlation ID for retrieval upon request. * * @param connName - The connection name to utilize * @param authData - The authentication data to utilize, if required * @param requestQueue - The request queue name to put the message on * @param targetHost - The target host for the message * @param value - The data to place on the request. MUST be <code>Serialiable</code> * @return <code>String</code> - the JMS correlation ID associated with the message * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing *///www .j a v a 2 s .c o m public static final synchronized String sendMqMessage(final String connName, final List<String> authData, final String requestQueue, final String targetHost, final Serializable value) throws UtilityException { final String methodName = MQUtils.CNAME + "sendMqMessage(final String connName, final List<String> authData, final String requestQueue, final String targetHost, final Serializable value) throws UtilityException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", connName); DEBUGGER.debug("Value: {}", requestQueue); DEBUGGER.debug("Value: {}", targetHost); DEBUGGER.debug("Value: {}", value); } Connection conn = null; Session session = null; Context envContext = null; InitialContext initCtx = null; MessageProducer producer = null; ConnectionFactory connFactory = null; final String correlationId = RandomStringUtils.randomAlphanumeric(64); if (DEBUG) { DEBUGGER.debug("correlationId: {}", correlationId); } try { try { initCtx = new InitialContext(); envContext = (Context) initCtx.lookup(MQUtils.INIT_CONTEXT); connFactory = (ConnectionFactory) envContext.lookup(connName); } catch (NamingException nx) { // we're probably not in a container connFactory = new ActiveMQConnectionFactory(connName); } if (DEBUG) { DEBUGGER.debug("ConnectionFactory: {}", connFactory); } if (connFactory == null) { throw new UtilityException("Unable to create connection factory for provided name"); } // Create a Connection conn = connFactory.createConnection(authData.get(0), PasswordUtils.decryptText(authData.get(1), authData.get(2), authData.get(3), Integer.parseInt(authData.get(4)), Integer.parseInt(authData.get(5)), authData.get(6), authData.get(7), authData.get(8))); conn.start(); if (DEBUG) { DEBUGGER.debug("Connection: {}", conn); } // Create a Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); if (DEBUG) { DEBUGGER.debug("Session: {}", session); } // Create a MessageProducer from the Session to the Topic or Queue if (envContext != null) { try { producer = session.createProducer((Destination) envContext.lookup(requestQueue)); } catch (NamingException nx) { throw new UtilityException(nx.getMessage(), nx); } } else { Destination destination = session.createTopic(requestQueue); if (DEBUG) { DEBUGGER.debug("Destination: {}", destination); } producer = session.createProducer(destination); } if (producer == null) { throw new JMSException("Failed to create a producer object"); } producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); if (DEBUG) { DEBUGGER.debug("MessageProducer: {}", producer); } ObjectMessage message = session.createObjectMessage(true); message.setJMSCorrelationID(correlationId); message.setStringProperty("targetHost", targetHost); if (DEBUG) { DEBUGGER.debug("correlationId: {}", correlationId); } message.setObject(value); if (DEBUG) { DEBUGGER.debug("ObjectMessage: {}", message); } producer.send(message); } catch (JMSException jx) { throw new UtilityException(jx.getMessage(), jx); } finally { try { // Clean up if (!(session == null)) { session.close(); } if (!(conn == null)) { conn.close(); conn.stop(); } } catch (JMSException jx) { ERROR_RECORDER.error(jx.getMessage(), jx); } } return correlationId; }
From source file:org.mule.transport.jms.integration.AbstractJmsFunctionalTestCase.java
public void send(Scenario scenario) throws Exception { Connection connection = null; try {/*ww w . j a va 2 s. c om*/ connection = getConnection(false, false); connection.start(); Session session = null; try { session = connection.createSession(scenario.isTransacted(), scenario.getAcknowledge()); Destination destination = createInputDestination(session, scenario); MessageProducer producer = null; try { producer = session.createProducer(destination); if (scenario.isPersistent()) { producer.setDeliveryMode(DeliveryMode.PERSISTENT); } scenario.send(session, producer); } finally { if (producer != null) { producer.close(); } } } finally { if (session != null) { session.close(); } } } finally { if (connection != null) { connection.close(); } } }
From source file:org.mule.transport.jms.integration.AbstractJmsFunctionalTestCase.java
public Message receive(Scenario scenario) throws Exception { assertNotNull("scenario is null!", scenario); Connection connection = null; try {//from ww w .ja v a 2 s . co m connection = getConnection(false, false); connection.start(); Session session = null; try { session = connection.createSession(scenario.isTransacted(), scenario.getAcknowledge()); Destination destination = createOutputDestination(session, scenario); MessageConsumer consumer = null; try { consumer = session.createConsumer(destination); return scenario.receive(session, consumer); } finally { if (consumer != null) { consumer.close(); } } } finally { if (session != null) { session.close(); } } } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { logger.warn("Failed to close jms connection: " + e.getMessage()); } } } }
From source file:org.apache.activemq.network.BrokerNetworkWithStuckMessagesTest.java
@SuppressWarnings({ "unchecked", "unused" }) private Object[] browseQueueWithJms(BrokerService broker) throws Exception { Object[] messages = null;//w w w.j av a 2 s .c om Connection connection = null; Session session = null; try { URI brokerUri = connector.getUri(); ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUri.toString()); connection = connectionFactory.createConnection(); connection.start(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue destination = session.createQueue(queueName); QueueBrowser browser = session.createBrowser(destination); List<Message> list = new ArrayList<Message>(); for (Enumeration<Message> enumn = browser.getEnumeration(); enumn.hasMoreElements();) { list.add(enumn.nextElement()); } messages = list.toArray(); } finally { if (session != null) { session.close(); } if (connection != null) { connection.close(); } } LOG.info("+Browsed with JMS: " + messages.length); return messages; }
From source file:com.web.server.EJBDeployer.java
@Override public void fileChanged(FileChangeEvent arg0) throws Exception { try {//from w ww . java2 s.com FileObject baseFile = arg0.getFile(); EJBContext ejbContext; if (baseFile.getName().getURI().endsWith(".jar")) { fileDeleted(arg0); URLClassLoader classLoader = new URLClassLoader(new URL[] { new URL(baseFile.getName().getURI()) }, Thread.currentThread().getContextClassLoader()); ConfigurationBuilder config = new ConfigurationBuilder(); config.addUrls(ClasspathHelper.forClassLoader(classLoader)); config.addClassLoader(classLoader); org.reflections.Reflections reflections = new org.reflections.Reflections(config); EJBContainer container = EJBContainer.getInstance(baseFile.getName().getURI(), config); container.inject(); Set<Class<?>> cls = reflections.getTypesAnnotatedWith(Stateless.class); Set<Class<?>> clsMessageDriven = reflections.getTypesAnnotatedWith(MessageDriven.class); Object obj; System.gc(); if (cls.size() > 0) { ejbContext = new EJBContext(); ejbContext.setJarPath(baseFile.getName().getURI()); ejbContext.setJarDeployed(baseFile.getName().getBaseName()); for (Class<?> ejbInterface : cls) { //BeanPool.getInstance().create(ejbInterface); obj = BeanPool.getInstance().get(ejbInterface); System.out.println(obj); ProxyFactory factory = new ProxyFactory(); obj = UnicastRemoteObject.exportObject((Remote) factory.createWithBean(obj), servicesRegistryPort); String remoteBinding = container.getRemoteBinding(ejbInterface); System.out.println(remoteBinding + " for EJB" + obj); if (remoteBinding != null) { //registry.unbind(remoteBinding); registry.rebind(remoteBinding, (Remote) obj); ejbContext.put(remoteBinding, obj.getClass()); } //registry.rebind("name", (Remote) obj); } jarEJBMap.put(baseFile.getName().getURI(), ejbContext); } System.out.println("Class Message Driven" + clsMessageDriven); System.out.println("Class Message Driven" + clsMessageDriven); if (clsMessageDriven.size() > 0) { System.out.println("Class Message Driven"); MDBContext mdbContext; ConcurrentHashMap<String, MDBContext> mdbContexts; if (jarMDBMap.get(baseFile.getName().getURI()) != null) { mdbContexts = jarMDBMap.get(baseFile.getName().getURI()); } else { mdbContexts = new ConcurrentHashMap<String, MDBContext>(); } jarMDBMap.put(baseFile.getName().getURI(), mdbContexts); MDBContext mdbContextOld; for (Class<?> mdbBean : clsMessageDriven) { String classwithpackage = mdbBean.getName(); System.out.println("class package" + classwithpackage); classwithpackage = classwithpackage.replace("/", "."); System.out.println("classList:" + classwithpackage.replace("/", ".")); try { if (!classwithpackage.contains("$")) { //System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass); //System.out.println(); if (!mdbBean.isInterface()) { Annotation[] classServicesAnnot = mdbBean.getDeclaredAnnotations(); if (classServicesAnnot != null) { for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) { if (classServicesAnnot[annotcount] instanceof MessageDriven) { MessageDriven messageDrivenAnnot = (MessageDriven) classServicesAnnot[annotcount]; ActivationConfigProperty[] activationConfigProperties = messageDrivenAnnot .activationConfig(); mdbContext = new MDBContext(); mdbContext.setMdbName(messageDrivenAnnot.name()); for (ActivationConfigProperty activationConfigProperty : activationConfigProperties) { if (activationConfigProperty.propertyName() .equals(MDBContext.DESTINATIONTYPE)) { mdbContext.setDestinationType( activationConfigProperty.propertyValue()); } else if (activationConfigProperty.propertyName() .equals(MDBContext.DESTINATION)) { mdbContext.setDestination( activationConfigProperty.propertyValue()); } else if (activationConfigProperty.propertyName() .equals(MDBContext.ACKNOWLEDGEMODE)) { mdbContext.setAcknowledgeMode( activationConfigProperty.propertyValue()); } } if (mdbContext.getDestinationType().equals(Queue.class.getName())) { mdbContextOld = null; if (mdbContexts.get(mdbContext.getMdbName()) != null) { mdbContextOld = mdbContexts.get(mdbContext.getMdbName()); if (mdbContextOld != null && mdbContext.getDestination() .equals(mdbContextOld.getDestination())) { throw new Exception( "Only one MDB can listen to destination:" + mdbContextOld.getDestination()); } } mdbContexts.put(mdbContext.getMdbName(), mdbContext); Queue queue = (Queue) jms.lookup(mdbContext.getDestination()); Connection connection = connectionFactory .createConnection("guest", "guest"); connection.start(); Session session; if (mdbContext.getAcknowledgeMode() != null && mdbContext .getAcknowledgeMode().equals("Auto-Acknowledge")) { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } else { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } MessageConsumer consumer = session.createConsumer(queue); consumer.setMessageListener( (MessageListener) mdbBean.newInstance()); mdbContext.setConnection(connection); mdbContext.setSession(session); mdbContext.setConsumer(consumer); System.out.println("Queue=" + queue); } else if (mdbContext.getDestinationType() .equals(Topic.class.getName())) { if (mdbContexts.get(mdbContext.getMdbName()) != null) { mdbContextOld = mdbContexts.get(mdbContext.getMdbName()); if (mdbContextOld.getConsumer() != null) mdbContextOld.getConsumer().setMessageListener(null); if (mdbContextOld.getSession() != null) mdbContextOld.getSession().close(); if (mdbContextOld.getConnection() != null) mdbContextOld.getConnection().close(); } mdbContexts.put(mdbContext.getMdbName(), mdbContext); Topic topic = (Topic) jms.lookup(mdbContext.getDestination()); Connection connection = connectionFactory .createConnection("guest", "guest"); connection.start(); Session session; if (mdbContext.getAcknowledgeMode() != null && mdbContext .getAcknowledgeMode().equals("Auto-Acknowledge")) { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } else { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } MessageConsumer consumer = session.createConsumer(topic); consumer.setMessageListener( (MessageListener) mdbBean.newInstance()); mdbContext.setConnection(connection); mdbContext.setSession(session); mdbContext.setConsumer(consumer); System.out.println("Topic=" + topic); } } } } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } classLoader.close(); System.out.println(baseFile.getName().getURI() + " Deployed"); } } catch (Exception ex) { ex.printStackTrace(); } }
From source file:com.web.server.EJBDeployer.java
@Override public void fileCreated(FileChangeEvent arg0) throws Exception { try {// w w w . ja va 2 s.c om FileObject baseFile = arg0.getFile(); EJBContext ejbContext; if (baseFile.getName().getURI().endsWith(".jar")) { System.out.println(baseFile.getName().getURI()); URLClassLoader classLoader = new URLClassLoader(new URL[] { new URL(baseFile.getName().getURI()) }, Thread.currentThread().getContextClassLoader()); ConfigurationBuilder config = new ConfigurationBuilder(); config.addUrls(ClasspathHelper.forClassLoader(classLoader)); config.addClassLoader(classLoader); org.reflections.Reflections reflections = new org.reflections.Reflections(config); EJBContainer container = EJBContainer.getInstance(baseFile.getName().getURI(), config); container.inject(); Set<Class<?>> clsStateless = reflections.getTypesAnnotatedWith(Stateless.class); Set<Class<?>> clsMessageDriven = reflections.getTypesAnnotatedWith(MessageDriven.class); Object obj; System.gc(); if (clsStateless.size() > 0) { ejbContext = new EJBContext(); ejbContext.setJarPath(baseFile.getName().getURI()); ejbContext.setJarDeployed(baseFile.getName().getBaseName()); for (Class<?> ejbInterface : clsStateless) { //BeanPool.getInstance().create(ejbInterface); obj = BeanPool.getInstance().get(ejbInterface); System.out.println(obj); ProxyFactory factory = new ProxyFactory(); obj = UnicastRemoteObject.exportObject((Remote) factory.createWithBean(obj), servicesRegistryPort); String remoteBinding = container.getRemoteBinding(ejbInterface); System.out.println(remoteBinding + " for EJB" + obj); if (remoteBinding != null) { //registry.unbind(remoteBinding); registry.rebind(remoteBinding, (Remote) obj); ejbContext.put(remoteBinding, obj.getClass()); } //registry.rebind("name", (Remote) obj); } jarEJBMap.put(baseFile.getName().getURI(), ejbContext); } System.out.println("Class Message Driven" + clsMessageDriven); System.out.println("Class Message Driven" + clsMessageDriven); if (clsMessageDriven.size() > 0) { System.out.println("Class Message Driven"); MDBContext mdbContext; ConcurrentHashMap<String, MDBContext> mdbContexts; if (jarMDBMap.get(baseFile.getName().getURI()) != null) { mdbContexts = jarMDBMap.get(baseFile.getName().getURI()); } else { mdbContexts = new ConcurrentHashMap<String, MDBContext>(); } jarMDBMap.put(baseFile.getName().getURI(), mdbContexts); MDBContext mdbContextOld; for (Class<?> mdbBean : clsMessageDriven) { String classwithpackage = mdbBean.getName(); System.out.println("class package" + classwithpackage); classwithpackage = classwithpackage.replace("/", "."); System.out.println("classList:" + classwithpackage.replace("/", ".")); try { if (!classwithpackage.contains("$")) { //System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass); //System.out.println(); if (!mdbBean.isInterface()) { Annotation[] classServicesAnnot = mdbBean.getDeclaredAnnotations(); if (classServicesAnnot != null) { for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) { if (classServicesAnnot[annotcount] instanceof MessageDriven) { MessageDriven messageDrivenAnnot = (MessageDriven) classServicesAnnot[annotcount]; ActivationConfigProperty[] activationConfigProperties = messageDrivenAnnot .activationConfig(); mdbContext = new MDBContext(); mdbContext.setMdbName(messageDrivenAnnot.name()); for (ActivationConfigProperty activationConfigProperty : activationConfigProperties) { if (activationConfigProperty.propertyName() .equals(MDBContext.DESTINATIONTYPE)) { mdbContext.setDestinationType( activationConfigProperty.propertyValue()); } else if (activationConfigProperty.propertyName() .equals(MDBContext.DESTINATION)) { mdbContext.setDestination( activationConfigProperty.propertyValue()); } else if (activationConfigProperty.propertyName() .equals(MDBContext.ACKNOWLEDGEMODE)) { mdbContext.setAcknowledgeMode( activationConfigProperty.propertyValue()); } } if (mdbContext.getDestinationType().equals(Queue.class.getName())) { mdbContextOld = null; if (mdbContexts.get(mdbContext.getMdbName()) != null) { mdbContextOld = mdbContexts.get(mdbContext.getMdbName()); if (mdbContextOld != null && mdbContext.getDestination() .equals(mdbContextOld.getDestination())) { throw new Exception( "Only one MDB can listen to destination:" + mdbContextOld.getDestination()); } } mdbContexts.put(mdbContext.getMdbName(), mdbContext); Queue queue = (Queue) jms.lookup(mdbContext.getDestination()); Connection connection = connectionFactory .createConnection("guest", "guest"); connection.start(); Session session; if (mdbContext.getAcknowledgeMode() != null && mdbContext .getAcknowledgeMode().equals("Auto-Acknowledge")) { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } else { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } MessageConsumer consumer = session.createConsumer(queue); consumer.setMessageListener( (MessageListener) mdbBean.newInstance()); mdbContext.setConnection(connection); mdbContext.setSession(session); mdbContext.setConsumer(consumer); System.out.println("Queue=" + queue); } else if (mdbContext.getDestinationType() .equals(Topic.class.getName())) { if (mdbContexts.get(mdbContext.getMdbName()) != null) { mdbContextOld = mdbContexts.get(mdbContext.getMdbName()); if (mdbContextOld.getConsumer() != null) mdbContextOld.getConsumer().setMessageListener(null); if (mdbContextOld.getSession() != null) mdbContextOld.getSession().close(); if (mdbContextOld.getConnection() != null) mdbContextOld.getConnection().close(); } mdbContexts.put(mdbContext.getMdbName(), mdbContext); Topic topic = (Topic) jms.lookup(mdbContext.getDestination()); Connection connection = connectionFactory .createConnection("guest", "guest"); connection.start(); Session session; if (mdbContext.getAcknowledgeMode() != null && mdbContext .getAcknowledgeMode().equals("Auto-Acknowledge")) { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } else { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } MessageConsumer consumer = session.createConsumer(topic); consumer.setMessageListener( (MessageListener) mdbBean.newInstance()); mdbContext.setConnection(connection); mdbContext.setSession(session); mdbContext.setConsumer(consumer); System.out.println("Topic=" + topic); } } } } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } classLoader.close(); } System.out.println(baseFile.getName().getURI() + " Deployed"); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:org.mule.transport.jms.integration.AbstractJmsFunctionalTestCase.java
/** * Purge destinations for clean test setup. Especially applicable to WMQ tests, as messages from * other tests may still exist from other tests' runs. * <p/>/*from w ww . ja v a2 s. co m*/ * Well-behaving tests should drain both inbound and outbound destinations, as well as any intermediary ones. * @param destination destination name without any protocol specifics */ protected void purge(final String destination) throws JMSException { Connection c = null; Session s = null; try { logger.debug("purging queue : " + destination); c = getConnection(false, false); assertNotNull(c); c.start(); s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination d = s.createQueue(destination); MessageConsumer consumer = s.createConsumer(d); while (consumer.receiveNoWait() != null) { logger.debug("Destination " + destination + " isn't empty, draining it"); } } catch (Exception e) { logger.error("unable to purge : " + destination); } finally { if (c != null) { c.stop(); if (s != null) { s.close(); } try { c.close(); } catch (JMSException e) { logger.warn("Failed to close jms connection: " + e.getMessage()); } } } }