List of usage examples for javax.jms Session createDurableSubscriber
TopicSubscriber createDurableSubscriber(Topic topic, String name) throws JMSException;
From source file:org.apache.activemq.usecases.DurableSubscriberWithNetworkDisconnectTest.java
public void testSendOnAReceiveOnBWithTransportDisconnect() throws Exception { bridgeBrokers(SPOKE, HUB);//from w ww.java2 s . com startAllBrokers(); // Setup connection URI hubURI = brokers.get(HUB).broker.getVmConnectorURI(); URI spokeURI = brokers.get(SPOKE).broker.getVmConnectorURI(); ActiveMQConnectionFactory facHub = new ActiveMQConnectionFactory(hubURI); ActiveMQConnectionFactory facSpoke = new ActiveMQConnectionFactory(spokeURI); Connection conHub = facHub.createConnection(); Connection conSpoke = facSpoke.createConnection(); conHub.setClientID("clientHUB"); conSpoke.setClientID("clientSPOKE"); conHub.start(); conSpoke.start(); Session sesHub = conHub.createSession(false, Session.AUTO_ACKNOWLEDGE); Session sesSpoke = conSpoke.createSession(false, Session.AUTO_ACKNOWLEDGE); ActiveMQTopic topic = new ActiveMQTopic("TEST.FOO"); String consumerName = "consumerName"; // Setup consumers MessageConsumer remoteConsumer = sesSpoke.createDurableSubscriber(topic, consumerName); remoteConsumer.setMessageListener(new MessageListener() { public void onMessage(Message msg) { try { TextMessage textMsg = (TextMessage) msg; receivedMsgs++; LOG.info("Received messages (" + receivedMsgs + "): " + textMsg.getText()); } catch (JMSException e) { e.printStackTrace(); } } }); // allow subscription information to flow back to Spoke sleep(1000); // Setup producer MessageProducer localProducer = sesHub.createProducer(topic); localProducer.setDeliveryMode(DeliveryMode.PERSISTENT); // Send messages for (int i = 0; i < MESSAGE_COUNT; i++) { sleep(50); if (i == 50 || i == 150) { if (simulateStalledNetwork) { socketProxy.pause(); } else { socketProxy.close(); } networkDownTimeStart = System.currentTimeMillis(); } else if (networkDownTimeStart > 0) { // restart after NETWORK_DOWN_TIME seconds sleep(NETWORK_DOWN_TIME); networkDownTimeStart = 0; if (simulateStalledNetwork) { socketProxy.goOn(); } else { socketProxy.reopen(); } } else { // slow message production to allow bridge to recover and limit message duplication sleep(500); } Message test = sesHub.createTextMessage("test-" + i); localProducer.send(test); } LOG.info("waiting for messages to flow"); Wait.waitFor(new Wait.Condition() { @Override public boolean isSatisified() throws Exception { return receivedMsgs >= MESSAGE_COUNT; } }); assertTrue("At least message " + MESSAGE_COUNT + " must be received, count=" + receivedMsgs, MESSAGE_COUNT <= receivedMsgs); brokers.get(HUB).broker.deleteAllMessages(); brokers.get(SPOKE).broker.deleteAllMessages(); conHub.close(); conSpoke.close(); }
From source file:org.apache.activemq.usecases.DurableSubscriberWithNetworkRestartTest.java
public void testSendOnAReceiveOnBWithTransportDisconnect() throws Exception { bridge(SPOKE, HUB);//from w ww .j a va2 s. co m startAllBrokers(); verifyDuplexBridgeMbean(); // Setup connection URI hubURI = brokers.get(HUB).broker.getTransportConnectors().get(0).getPublishableConnectURI(); URI spokeURI = brokers.get(SPOKE).broker.getTransportConnectors().get(0).getPublishableConnectURI(); ActiveMQConnectionFactory facHub = new ActiveMQConnectionFactory(hubURI); ActiveMQConnectionFactory facSpoke = new ActiveMQConnectionFactory(spokeURI); Connection conHub = facHub.createConnection(); Connection conSpoke = facSpoke.createConnection(); conHub.setClientID("clientHUB"); conSpoke.setClientID("clientSPOKE"); conHub.start(); conSpoke.start(); Session sesHub = conHub.createSession(false, Session.AUTO_ACKNOWLEDGE); Session sesSpoke = conSpoke.createSession(false, Session.AUTO_ACKNOWLEDGE); ActiveMQTopic topic = new ActiveMQTopic("TEST.FOO"); String consumerName = "consumerName"; // Setup consumers MessageConsumer remoteConsumer = sesHub.createDurableSubscriber(topic, consumerName); sleep(1000); remoteConsumer.close(); // Setup producer MessageProducer localProducer = sesSpoke.createProducer(topic); localProducer.setDeliveryMode(DeliveryMode.PERSISTENT); final String payloadString = new String(new byte[10 * 1024]); // Send messages for (int i = 0; i < MESSAGE_COUNT; i++) { Message test = sesSpoke.createTextMessage("test-" + i); test.setStringProperty("payload", payloadString); localProducer.send(test); } localProducer.close(); final String options = "?persistent=true&useJmx=true&deleteAllMessagesOnStartup=false"; for (int i = 0; i < 2; i++) { brokers.get(SPOKE).broker.stop(); sleep(1000); createBroker(new URI("broker:(tcp://localhost:61616)/" + SPOKE + options)); bridge(SPOKE, HUB); brokers.get(SPOKE).broker.start(); LOG.info("restarted spoke..:" + i); assertTrue("got mbeans on restart", Wait.waitFor(new Wait.Condition() { @Override public boolean isSatisified() throws Exception { return countMbeans(brokers.get(HUB).broker, "networkBridge", 20000) == (dynamicOnly ? 1 : 2); } })); } }
From source file:org.apache.qpid.disttest.jms.ClientJmsDelegate.java
public void createConsumer(final CreateConsumerCommand command) { try {//from w w w . j a va 2s . c o m final Session session = _testSessions.get(command.getSessionName()); if (session == null) { throw new DistributedTestException("No test session found called: " + command.getSessionName(), command); } synchronized (session) { Destination destination; MessageConsumer jmsConsumer; if (command.isTopic()) { Topic topic = session.createTopic(command.getDestinationName()); if (command.isDurableSubscription()) { String subscription = "subscription-" + command.getParticipantName() + System.currentTimeMillis(); jmsConsumer = session.createDurableSubscriber(topic, subscription); _testSubscriptions.put(subscription, session); LOGGER.debug("created durable suscription " + subscription + " to topic " + topic); } else { jmsConsumer = session.createConsumer(topic, command.getSelector()); } destination = topic; } else { destination = session.createQueue(command.getDestinationName()); jmsConsumer = session.createConsumer(destination, command.getSelector()); } _testConsumers.put(command.getParticipantName(), jmsConsumer); } } catch (final JMSException jmse) { throw new DistributedTestException("Unable to create new consumer: " + command, jmse); } }
From source file:org.mule.transport.jms.integration.AbstractJmsFunctionalTestCase.java
/** * Clear the specified topic/*from www. j a v a2 s . c o m*/ */ protected void purgeTopic(String destination, String topic) throws Exception { Connection c = null; Session s = null; try { logger.debug("purging topic : " + topic); c = getConnection(true, false); if (c == null) { logger.debug("could not create a connection to topic : " + destination); } c.start(); s = ((TopicConnection) c).createTopicSession(true, Session.SESSION_TRANSACTED); logger.debug("created topic session"); Topic dest = s.createTopic(destination); logger.debug("created topic destination"); if (client != null) { client.dispose(); } MessageConsumer consumer = null; try { consumer = s.createDurableSubscriber(dest, topic); logger.debug("created consumer"); while (consumer.receiveNoWait() != null) { logger.debug("Topic " + topic + " isn't empty, draining it"); } logger.debug("topic should be empty"); consumer.close(); s.unsubscribe(topic); } catch (JMSException e) { logger.debug("could not unsubscribe : " + topic); } } 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()); } } } logger.debug("completed draining topic :" + topic); }
From source file:org.openhie.openempi.notification.impl.NotificationServiceImpl.java
public void registerListener(List<String> eventTypeNames, MessageHandler handler) { if (brokerService == null || !brokerInitialized) { log.debug("The broker service is not running in registerListener."); return;/* w ww.ja v a 2s . c om*/ } if (!isValidHandler(handler)) { return; } ConnectionFactory connectionFactory = jmsTemplate.getConnectionFactory(); Connection connection = null; try { connection = connectionFactory.createConnection(); connection.setClientID(handler.getClientId()); } catch (JMSException e) { log.error("Failed while setting up a registrant for notification events. Error: " + e, e); throw new RuntimeException("Unable to setup registration for event notification: " + e.getMessage()); } for (String eventTypeName : eventTypeNames) { log.info("Registering handler for event " + eventTypeName); Topic topic = topicMap.get(eventTypeName); if (topic == null) { log.error("Caller attempted to register interest to events of unknown type " + eventTypeName); throw new RuntimeException("Unknown event type specified in registration request."); } if (isListenerRegistered(handler, eventTypeName)) { log.warn("Caller attempted to register interest for the same event again."); return; } try { Session topicSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); TopicSubscriber subscriber = topicSession.createDurableSubscriber(topic, topic.getTopicName()); MessageListenerImpl listener = new MessageListenerImpl(connection, topicSession, subscriber, handler); saveListenerRegistration(listener, eventTypeName); subscriber.setMessageListener(listener); } catch (JMSException e) { log.error("Failed while setting up a registrant for notification events. Error: " + e, e); throw new RuntimeException( "Unable to setup registration for event notification: " + e.getMessage()); } } try { connection.start(); } catch (JMSException e) { log.error("Failed while setting up a registrant for notification events. Error: " + e, e); throw new RuntimeException("Unable to setup registration for event notification: " + e.getMessage()); } }
From source file:org.wso2.andes.systest.TestingBaseCase.java
/** * Perform the Main test of a topic Consumer with the given AckMode. * * Test creates a new connection and sets up the connection to prevent * failover// w ww . ja v a 2s .c om * * A new consumer is connected and started so that it will prefetch msgs. * * An asynchrounous publisher is started to fill the broker with messages. * * We then wait to be notified of the disconnection via the ExceptionListener * * 0-10 does not have the same notification paths but sync() apparently should * give us the exception, currently it doesn't, so the test is excluded from 0-10 * * We should ensure that this test has the same path for all protocol versions. * * Clients should not have to modify their code based on the protocol in use. * * @param ackMode @see javax.jms.Session * * @throws Exception */ protected void topicConsumer(int ackMode, boolean durable) throws Exception { Connection connection = getConnection(); connection.setExceptionListener(this); Session session = connection.createSession(ackMode == Session.SESSION_TRANSACTED, ackMode); _destination = session.createTopic(getName()); MessageConsumer consumer; if (durable) { consumer = session.createDurableSubscriber(_destination, getTestQueueName()); } else { consumer = session.createConsumer(_destination); } connection.start(); // Start the consumer pre-fetching // Don't care about response as we will fill the broker up with messages // after this point and ensure that the client is disconnected at the // right point. consumer.receiveNoWait(); startPublisher(_destination); boolean disconnected = _disconnectionLatch.await(DISCONNECTION_WAIT, TimeUnit.SECONDS); assertTrue("Client was not disconnected", disconnected); assertTrue("Client was not disconnected.", _connectionException != null); Exception linked = _connectionException.getLinkedException(); _publisher.join(JOIN_WAIT); assertFalse("Publisher still running", _publisher.isAlive()); //Validate publishing occurred ok if (_publisherError != null) { throw _publisherError; } // NOTE these exceptions will need to be modeled so that they are not // 0-8 specific. e.g. JMSSessionClosedException assertNotNull("No error received onException listener.", _connectionException); assertNotNull("No linked exception set on:" + _connectionException.getMessage(), linked); assertTrue("Incorrect linked exception received.", linked instanceof AMQException); AMQException amqException = (AMQException) linked; assertEquals("Channel was not closed with correct code.", AMQConstant.RESOURCE_ERROR, amqException.getErrorCode()); }