@Test(invocationCount = 5, successPercentage = 19) public void topicConduit() throws Exception { String topicName = "JmsByteArrayTransportTest-topicConduit-" + System.getProperty("user.name") + "-" + System.currentTimeMillis(); ConnectionFactory cf = ActiveMQTestUtils.createTestConnectionFactory(); JmsTemplate jmsTemplate = new JmsTemplate(); jmsTemplate.setConnectionFactory(cf); jmsTemplate.setPubSubDomain(true); JmsByteArrayMessageSender messageSender = new JmsByteArrayMessageSender(topicName, jmsTemplate); CollectingByteArrayMessageReceiver collectingReceiver = new CollectingByteArrayMessageReceiver(); JmsByteArrayMessageDispatcher messageDispatcher = new JmsByteArrayMessageDispatcher(collectingReceiver); DefaultMessageListenerContainer container = new DefaultMessageListenerContainer(); container.setConnectionFactory(cf); container.setMessageListener(messageDispatcher); container.setDestinationName(topicName); container.setPubSubDomain(true); container.afterPropertiesSet(); container.start(); Random random = new Random(); byte[] randomBytes = new byte[1024]; random.nextBytes(randomBytes); while (!container.isRunning()) { Thread.sleep(10l); } // TODO: this is a hack. The context doesn't seem to have always set up the consumer completely // yet Thread.sleep(500l); messageSender.send(randomBytes); long startTime = System.currentTimeMillis(); while (collectingReceiver.getMessages().isEmpty()) { Thread.sleep(10l); if ((System.currentTimeMillis() - startTime) > TIMEOUT) { fail("Did not receive a message in " + (TIMEOUT / 1000) + " seconds."); } } s_logger.debug( "topicConduit message received {}ms before timeout limit", TIMEOUT - (System.currentTimeMillis() - startTime)); assertEquals(1, collectingReceiver.getMessages().size()); byte[] receivedBytes = collectingReceiver.getMessages().get(0); assertEquals(randomBytes.length, receivedBytes.length); for (int i = 0; i < randomBytes.length; i++) { assertEquals(randomBytes[i], receivedBytes[i]); } container.stop(); container.destroy(); }
private String getDestinationName() { if (listenerContainer.getDestination() != null) { return listenerContainer.getDestination().toString(); } else { return listenerContainer.getDestinationName(); } }
@Test public void testPubSubDomainActive() { load(TestConfiguration.class, "spring.jms.pubSubDomain:true"); JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); DefaultMessageListenerContainer defaultMessageListenerContainer = this.context .getBean(DefaultJmsListenerContainerFactory.class) .createListenerContainer(mock(JmsListenerEndpoint.class)); assertThat(jmsTemplate.isPubSubDomain()).isTrue(); assertThat(defaultMessageListenerContainer.isPubSubDomain()).isTrue(); }
@Test public void channelWithConcurrencySettings() { assertEquals( JmsDestinationBackedMessageChannel.class, channelWithConcurrencySettings.getClass()); JmsDestinationBackedMessageChannel channel = (JmsDestinationBackedMessageChannel) channelWithConcurrencySettings; DirectFieldAccessor accessor = new DirectFieldAccessor(channel); DefaultMessageListenerContainer container = (DefaultMessageListenerContainer) accessor.getPropertyValue("container"); assertEquals(11, container.getConcurrentConsumers()); assertEquals(55, container.getMaxConcurrentConsumers()); }
@Override protected void doStop() throws Exception { if (listenerContainer != null) { listenerContainer.stop(); listenerContainer.destroy(); } // null container and listener so they are fully re created if this consumer is restarted // then we will use updated configuration from jms endpoint that may have been managed using JMX listenerContainer = null; messageListener = null; super.doStop(); }
@Test public void testDefaultContainerFactoryNoTransactionManager() { this.context = createContext(EnableJmsConfiguration.class); JmsListenerContainerFactory<?> jmsListenerContainerFactory = this.context.getBean("jmsListenerContainerFactory", JmsListenerContainerFactory.class); assertThat(jmsListenerContainerFactory.getClass()) .isEqualTo(DefaultJmsListenerContainerFactory.class); DefaultMessageListenerContainer listenerContainer = ((DefaultJmsListenerContainerFactory) jmsListenerContainerFactory) .createListenerContainer(mock(JmsListenerEndpoint.class)); assertThat(listenerContainer.isSessionTransacted()).isTrue(); assertThat(new DirectFieldAccessor(listenerContainer).getPropertyValue("transactionManager")) .isNull(); }
@Test public void gatewayWithDurableSubscription() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "inboundGatewayWithDurableSubscription.xml", this.getClass()); JmsMessageDrivenEndpoint endpoint = context.getBean("gateway", JmsMessageDrivenEndpoint.class); DefaultMessageListenerContainer container = (DefaultMessageListenerContainer) new DirectFieldAccessor(endpoint).getPropertyValue("listenerContainer"); assertEquals(Boolean.TRUE, container.isPubSubDomain()); assertEquals(Boolean.TRUE, container.isSubscriptionDurable()); assertEquals("testDurableSubscriptionName", container.getDurableSubscriptionName()); assertEquals("testClientId", container.getClientId()); }
@Test public void testLazyContainerWithDest() throws Exception { BeanFactory beanFactory = mock(BeanFactory.class); when(beanFactory.containsBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME)) .thenReturn(true); ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); scheduler.initialize(); when(beanFactory.getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, TaskScheduler.class)) .thenReturn(scheduler); final JmsOutboundGateway gateway = new JmsOutboundGateway(); gateway.setBeanFactory(beanFactory); gateway.setConnectionFactory(getConnectionFactory()); gateway.setRequestDestination(requestQueue7); gateway.setReplyDestination(replyQueue7); gateway.setCorrelationKey("JMSCorrelationID"); gateway.setUseReplyContainer(true); gateway.setIdleReplyContainerTimeout(1, TimeUnit.SECONDS); gateway.setRequiresReply(true); gateway.setReceiveTimeout(20000); gateway.afterPropertiesSet(); gateway.start(); Executors.newSingleThreadExecutor() .execute( () -> { JmsTemplate template = new JmsTemplate(); template.setConnectionFactory(getConnectionFactory()); template.setReceiveTimeout(20000); receiveAndSend(template); receiveAndSend(template); }); assertNotNull(gateway.handleRequestMessage(new GenericMessage<String>("foo"))); DefaultMessageListenerContainer container = TestUtils.getPropertyValue( gateway, "replyContainer", DefaultMessageListenerContainer.class); int n = 0; while (n++ < 100 && container.isRunning()) { Thread.sleep(100); } assertFalse(container.isRunning()); assertNotNull(gateway.handleRequestMessage(new GenericMessage<String>("foo"))); assertTrue(container.isRunning()); gateway.stop(); assertFalse(container.isRunning()); scheduler.destroy(); }
@Test public void testCustomContainerFactoryWithConfigurer() { this.context = doLoad( new Class<?>[] {TestConfiguration9.class, EnableJmsConfiguration.class}, "spring.jms.listener.autoStartup=false"); assertThat(this.context.containsBean("jmsListenerContainerFactory")).isTrue(); JmsListenerContainerFactory<?> jmsListenerContainerFactory = this.context.getBean("customListenerContainerFactory", JmsListenerContainerFactory.class); assertThat(jmsListenerContainerFactory).isInstanceOf(DefaultJmsListenerContainerFactory.class); DefaultMessageListenerContainer listenerContainer = ((DefaultJmsListenerContainerFactory) jmsListenerContainerFactory) .createListenerContainer(mock(JmsListenerEndpoint.class)); assertThat(listenerContainer.getCacheLevel()) .isEqualTo(DefaultMessageListenerContainer.CACHE_CONSUMER); assertThat(listenerContainer.isAutoStartup()).isFalse(); }
@Test public void testContainerConfiguration() throws Exception { Map<String, DefaultMessageListenerContainer> containers = context.getBeansOfType(DefaultMessageListenerContainer.class); ConnectionFactory defaultConnectionFactory = context.getBean(DEFAULT_CONNECTION_FACTORY, ConnectionFactory.class); ConnectionFactory explicitConnectionFactory = context.getBean(EXPLICIT_CONNECTION_FACTORY, ConnectionFactory.class); int defaultConnectionFactoryCount = 0; int explicitConnectionFactoryCount = 0; for (DefaultMessageListenerContainer container : containers.values()) { if (container.getConnectionFactory().equals(defaultConnectionFactory)) { defaultConnectionFactoryCount++; assertEquals(2, container.getConcurrentConsumers()); assertEquals(3, container.getMaxConcurrentConsumers()); } else if (container.getConnectionFactory().equals(explicitConnectionFactory)) { explicitConnectionFactoryCount++; assertEquals(1, container.getConcurrentConsumers()); assertEquals(2, container.getMaxConcurrentConsumers()); } } assertEquals( "1 container should have the default connectionFactory", 1, defaultConnectionFactoryCount); assertEquals( "2 containers should have the explicit connectionFactory", 2, explicitConnectionFactoryCount); }
@Test public void testJmsListenerContainerFactoryWithCustomSettings() { load( EnableJmsConfiguration.class, "spring.jms.listener.autoStartup=false", "spring.jms.listener.acknowledgeMode=client", "spring.jms.listener.concurrency=2", "spring.jms.listener.maxConcurrency=10"); JmsListenerContainerFactory<?> jmsListenerContainerFactory = this.context.getBean("jmsListenerContainerFactory", JmsListenerContainerFactory.class); assertThat(jmsListenerContainerFactory.getClass()) .isEqualTo(DefaultJmsListenerContainerFactory.class); DefaultMessageListenerContainer listenerContainer = ((DefaultJmsListenerContainerFactory) jmsListenerContainerFactory) .createListenerContainer(mock(JmsListenerEndpoint.class)); assertThat(listenerContainer.isAutoStartup()).isFalse(); assertThat(listenerContainer.getSessionAcknowledgeMode()).isEqualTo(Session.CLIENT_ACKNOWLEDGE); assertThat(listenerContainer.getConcurrentConsumers()).isEqualTo(2); assertThat(listenerContainer.getMaxConcurrentConsumers()).isEqualTo(10); }
@Bean(destroyMethod = "destroy") public DefaultMessageListenerContainer jmsContainer() { final DefaultMessageListenerContainer jmsContainer = new DefaultMessageListenerContainer(); jmsContainer.setDestination(destination()); jmsContainer.setConnectionFactory(amqConnectionFactory()); jmsContainer.setMessageListener(messageListener()); jmsContainer.setConcurrency("5-10"); jmsContainer.setReceiveTimeout(5000); jmsContainer.afterPropertiesSet(); return jmsContainer; }
/** * Pre tests the connection before starting the listening. * * <p>In case of connection failure the exception is thrown which prevents Camel from starting. * * @throws FailedToCreateConsumerException is thrown if testing the connection failed */ protected void testConnectionOnStartup() throws FailedToCreateConsumerException { try { log.debug("Testing JMS Connection on startup for destination: {}", getDestinationName()); Connection con = listenerContainer.getConnectionFactory().createConnection(); JmsUtils.closeConnection(con); log.info( "Successfully tested JMS Connection on startup for destination: " + getDestinationName()); } catch (Exception e) { String msg = "Cannot get JMS Connection on startup for destination " + getDestinationName(); throw new FailedToCreateConsumerException(getEndpoint(), msg, e); } }
private synchronized void shutdown() { // Stop the container final LocalVisualizerProxy proxy = this; Runnable callback = proxy::closeConnection; container.stop(callback); while (connectionOpen) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } }
@Bean public AbstractMessageListenerContainer messageListenerContainer() { DefaultMessageListenerContainer defaultMessageListenerContainer = new DefaultMessageListenerContainer(); defaultMessageListenerContainer.setSessionTransacted(true); defaultMessageListenerContainer.setConnectionFactory(jmsConfiguration.connectionFactory()); defaultMessageListenerContainer.setDestination(jmsConfiguration.eventProcessorDestination()); defaultMessageListenerContainer.setMessageSelector( String.format("%s = '%s'", eventTypeHeaderName, TimedAction.empty().getTypeId())); defaultMessageListenerContainer.setConcurrency(concurrency); return defaultMessageListenerContainer; }
@Bean(name = "domainAdminIncomingOsgpCoreRequestsMessageListenerContainer") public DefaultMessageListenerContainer incomingOsgpCoreRequestsMessageListenerContainer() { final DefaultMessageListenerContainer messageListenerContainer = new DefaultMessageListenerContainer(); messageListenerContainer.setConnectionFactory(this.pooledConnectionFactory()); messageListenerContainer.setDestination(this.incomingOsgpCoreRequestsQueue()); messageListenerContainer.setConcurrentConsumers( Integer.parseInt( this.environment.getRequiredProperty( PROPERTY_NAME_JMS_INCOMING_OSGP_CORE_REQUESTS_CONCURRENT_CONSUMERS))); messageListenerContainer.setMaxConcurrentConsumers( Integer.parseInt( this.environment.getRequiredProperty( PROPERTY_NAME_JMS_INCOMING_OSGP_CORE_REQUESTS_MAX_CONCURRENT_CONSUMERS))); messageListenerContainer.setMessageListener(this.incomingOsgpCoreRequestMessageListener); messageListenerContainer.setSessionTransacted(true); return messageListenerContainer; }
@Bean public DefaultMessageListenerContainer dlmsRequestsMessageListenerContainer() { final DefaultMessageListenerContainer messageListenerContainer = new DefaultMessageListenerContainer(); messageListenerContainer.setConnectionFactory(this.pooledConnectionFactory()); messageListenerContainer.setDestination(this.dlmsRequestsQueue()); messageListenerContainer.setConcurrentConsumers( Integer.parseInt( this.environment.getRequiredProperty( PROPERTY_NAME_JMS_DLMS_REQUESTS_CONCURRENT_CONSUMERS))); messageListenerContainer.setMaxConcurrentConsumers( Integer.parseInt( this.environment.getRequiredProperty( PROPERTY_NAME_JMS_DLMS_REQUESTS_MAX_CONCURRENT_CONSUMERS))); messageListenerContainer.setMessageListener(this.dlmsRequestsMessageListener); messageListenerContainer.setSessionTransacted(true); return messageListenerContainer; }
@Override protected void doStart() throws Exception { super.doStart(); // create listener container if (listenerContainer == null) { createMessageListenerContainer(); } listenerContainer.afterPropertiesSet(); // only start listener if auto start is enabled or we are explicit invoking start later if (initialized || getEndpoint().isAutoStartup()) { // should we pre test connections before starting? if (getEndpoint().isTestConnectionOnStartup()) { testConnectionOnStartup(); } startListenerContainer(); } // mark as initialized for the first time initialized = true; }
// set up the jms queue void init(TournamentService host) { log.info("Server URL: " + serverUrl + ", queue: " + queueName); // Can't set this earlier, need the params from visualizerService ActiveMQConnectionFactory amqFactory = (ActiveMQConnectionFactory) connectionFactory.getTargetConnectionFactory(); amqFactory.setBrokerURL(serverUrl); // register host as listener container = new DefaultMessageListenerContainer(); container.setConnectionFactory(connectionFactory); container.setDestinationName(queueName); container.setMessageListener(host); container.setTaskExecutor(taskExecutor); container.afterPropertiesSet(); container.start(); connectionOpen = true; }
@Test public void createJmsContainerFullConfig() { DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); setDefaultJmsConfig(factory); factory.setCacheLevel(DefaultMessageListenerContainer.CACHE_CONSUMER); factory.setConcurrency("3-10"); factory.setMaxMessagesPerTask(5); SimpleJmsListenerEndpoint endpoint = new SimpleJmsListenerEndpoint(); MessageListener messageListener = new MessageListenerAdapter(); endpoint.setMessageListener(messageListener); endpoint.setDestination("myQueue"); DefaultMessageListenerContainer container = factory.createListenerContainer(endpoint); assertDefaultJmsConfig(container); assertEquals(DefaultMessageListenerContainer.CACHE_CONSUMER, container.getCacheLevel()); assertEquals(3, container.getConcurrentConsumers()); assertEquals(10, container.getMaxConcurrentConsumers()); assertEquals(5, container.getMaxMessagesPerTask()); assertEquals(messageListener, container.getMessageListener()); assertEquals("myQueue", container.getDestinationName()); }
private void run(String topicName) { ActiveMQConnectionFactory activeMqFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_BROKER_URL); CachingConnectionFactory factory = new CachingConnectionFactory(activeMqFactory); DefaultMessageListenerContainer container = new DefaultMessageListenerContainer(); container.setConnectionFactory(factory); container.setDestination(new ActiveMQTopic(topicName)); container.setMessageListener(new LoggerMessageListener()); container.start(); container.initialize(); try { TimeUnit.MINUTES.sleep(1); } catch (InterruptedException ex) { LOGGER.warn("Thread ended with exception", ex); } LOGGER.info("Done"); }
protected void configureMessageListenerContainer( DefaultMessageListenerContainer container, JmsEndpoint endpoint) throws Exception { container.setConnectionFactory(getListenerConnectionFactory()); if (endpoint instanceof DestinationEndpoint) { container.setDestinationResolver(createDestinationResolver((DestinationEndpoint) endpoint)); } else if (destinationResolver != null) { container.setDestinationResolver(destinationResolver); } container.setAutoStartup(autoStartup); if (durableSubscriptionName != null) { container.setDurableSubscriptionName(durableSubscriptionName); container.setSubscriptionDurable(true); } if (clientId != null) { container.setClientId(clientId); } if (exceptionListener != null) { container.setExceptionListener(exceptionListener); } container.setAcceptMessagesWhileStopping(acceptMessagesWhileStopping); container.setExposeListenerSession(exposeListenerSession); container.setSessionTransacted(transacted); if (endpoint.getSelector() != null && endpoint.getSelector().length() != 0) { container.setMessageSelector(endpoint.getSelector()); } if (concurrentConsumers >= 0) { container.setConcurrentConsumers(concurrentConsumers); } if (cacheLevel >= 0) { container.setCacheLevel(cacheLevel); } else if (cacheLevelName != null) { container.setCacheLevelName(cacheLevelName); } else { container.setCacheLevel(defaultCacheLevel(endpoint)); } if (idleTaskExecutionLimit >= 0) { container.setIdleTaskExecutionLimit(idleTaskExecutionLimit); } if (maxConcurrentConsumers > 0) { if (maxConcurrentConsumers < concurrentConsumers) { throw new IllegalArgumentException( "Property maxConcurrentConsumers: " + maxConcurrentConsumers + " must be higher than concurrentConsumers: " + concurrentConsumers); } container.setMaxConcurrentConsumers(maxConcurrentConsumers); } if (maxMessagesPerTask >= 0) { container.setMaxMessagesPerTask(maxMessagesPerTask); } container.setPubSubNoLocal(pubSubNoLocal); if (receiveTimeout >= 0) { container.setReceiveTimeout(receiveTimeout); } if (recoveryInterval >= 0) { container.setRecoveryInterval(recoveryInterval); } if (taskExecutor != null) { container.setTaskExecutor(taskExecutor); } if (transactionName != null) { container.setTransactionName(transactionName); } if (transactionTimeout >= 0) { container.setTransactionTimeout(transactionTimeout); } }
/** * Starts the JMS listener container * * <p>Can be used to start this consumer later if it was configured to not auto startup. */ public void startListenerContainer() { listenerContainer.start(); }
private MessageListener getListener(String containerBeanName) { DefaultMessageListenerContainer container = this.context.getBean(containerBeanName, DefaultMessageListenerContainer.class); return (MessageListener) container.getMessageListener(); }
@Override protected AbstractMessageListenerContainer createListenerContainer() throws Exception { // Use DefaultMessageListenerContainer as it supports reconnects (see CAMEL-3193) // request-reply listener container should not allow quick-stop so we can keep listening for // reply messages DefaultMessageListenerContainer answer = new DefaultJmsMessageListenerContainer(endpoint, false); answer.setDestinationName("temporary"); answer.setDestinationResolver(destResolver); answer.setAutoStartup(true); if (endpoint.getMaxMessagesPerTask() >= 0) { answer.setMaxMessagesPerTask(endpoint.getMaxMessagesPerTask()); } answer.setIdleConsumerLimit(endpoint.getIdleConsumerLimit()); answer.setIdleTaskExecutionLimit(endpoint.getIdleTaskExecutionLimit()); answer.setMessageListener(this); answer.setPubSubDomain(false); answer.setSubscriptionDurable(false); answer.setConcurrentConsumers(endpoint.getConcurrentConsumers()); if (endpoint.getMaxConcurrentConsumers() > 0) { answer.setMaxConcurrentConsumers(endpoint.getMaxConcurrentConsumers()); } answer.setConnectionFactory(endpoint.getConnectionFactory()); // we use CACHE_CONSUMER by default to cling to the consumer as long as we can, since we can // only consume // msgs from the JMS Connection that created the temp destination in the first place if (endpoint.getReplyToCacheLevelName() != null) { if ("CACHE_NONE".equals(endpoint.getReplyToCacheLevelName())) { throw new IllegalArgumentException( "ReplyToCacheLevelName cannot be CACHE_NONE when using temporary reply queues. The value must be either CACHE_CONSUMER, or CACHE_SESSION"); } answer.setCacheLevelName(endpoint.getReplyToCacheLevelName()); } else { answer.setCacheLevel(DefaultMessageListenerContainer.CACHE_CONSUMER); } String clientId = endpoint.getClientId(); if (clientId != null) { clientId += ".CamelReplyManager"; answer.setClientId(clientId); } // we cannot do request-reply over JMS with transaction answer.setSessionTransacted(false); // other optional properties answer.setExceptionListener( new TemporaryReplyQueueExceptionListener(destResolver, endpoint.getExceptionListener())); if (endpoint.getErrorHandler() != null) { answer.setErrorHandler(endpoint.getErrorHandler()); } else { answer.setErrorHandler( new DefaultSpringErrorHandler( TemporaryQueueReplyManager.class, endpoint.getErrorHandlerLoggingLevel(), endpoint.isErrorHandlerLogStackTrace())); } if (endpoint.getReceiveTimeout() >= 0) { answer.setReceiveTimeout(endpoint.getReceiveTimeout()); } if (endpoint.getRecoveryInterval() >= 0) { answer.setRecoveryInterval(endpoint.getRecoveryInterval()); } if (endpoint.getTaskExecutor() != null) { if (log.isDebugEnabled()) { log.debug( "Using custom TaskExecutor: {} on listener container: {}", endpoint.getTaskExecutor(), answer); } answer.setTaskExecutor(endpoint.getTaskExecutor()); } // setup a bean name which is used by Spring JMS as the thread name // use the name of the request destination String name = "TemporaryQueueReplyManager[" + endpoint.getDestinationName() + "]"; answer.setBeanName(name); if (answer.getConcurrentConsumers() > 1) { // log that we are using concurrent consumers log.info( "Using {}-{} concurrent consumers on {}", new Object[] {answer.getConcurrentConsumers(), answer.getMaxConcurrentConsumers(), name}); } return answer; }
/** * @see * org.springframework.jms.listener.DefaultMessageListenerContainer#noMessageReceived(java.lang.Object, * javax.jms.Session) */ @Override protected void noMessageReceived(final Object invoker, final Session session) { WeldRequestContext.end(); super.noMessageReceived(invoker, session); }
/** * @see * org.springframework.jms.listener.DefaultMessageListenerContainer#messageReceived(java.lang.Object, * javax.jms.Session) */ @Override protected void messageReceived(final Object invoker, final Session session) { super.messageReceived(invoker, session); WeldRequestContext.endThenBegin(); }
protected void createMessageListenerContainer() throws Exception { listenerContainer = getEndpoint().createMessageListenerContainer(); getEndpoint().configureListenerContainer(listenerContainer, this); listenerContainer.setMessageListener(getEndpointMessageListener()); }
@Test(invocationCount = 5, successPercentage = 19) public void requestConduit() throws Exception { String topicName = "JmsByteArrayTransportTest-requestConduit-" + System.getProperty("user.name") + "-" + System.currentTimeMillis(); ConnectionFactory cf = ActiveMQTestUtils.createTestConnectionFactory(); JmsTemplate jmsTemplate = new JmsTemplate(); jmsTemplate.setConnectionFactory(cf); jmsTemplate.setPubSubDomain(true); jmsTemplate.setReceiveTimeout(5000l); final Random random = new Random(); final byte[] responseBytes = new byte[512]; random.nextBytes(responseBytes); JmsByteArrayRequestSender requestSender = new JmsByteArrayRequestSender(topicName, jmsTemplate); JmsByteArrayRequestDispatcher requestDispatcher = new JmsByteArrayRequestDispatcher( new ByteArrayRequestReceiver() { @Override public byte[] requestReceived(byte[] message) { return responseBytes; } }); DefaultMessageListenerContainer container = new DefaultMessageListenerContainer(); container.setConnectionFactory(cf); container.setMessageListener(requestDispatcher); container.setDestinationName(topicName); container.setPubSubDomain(true); container.afterPropertiesSet(); container.start(); byte[] randomBytes = new byte[1024]; random.nextBytes(randomBytes); while (!container.isRunning()) { Thread.sleep(10l); } CollectingByteArrayMessageReceiver collectingReceiver = new CollectingByteArrayMessageReceiver(); requestSender.sendRequest(randomBytes, collectingReceiver); long startTime = System.currentTimeMillis(); while (collectingReceiver.getMessages().isEmpty()) { Thread.sleep(10l); if ((System.currentTimeMillis() - startTime) > TIMEOUT) { fail("Did not receive a response in " + (TIMEOUT / 1000) + " seconds."); } } s_logger.debug( "requestConduit message received {}ms before timeout limit", TIMEOUT - (System.currentTimeMillis() - startTime)); assertEquals(1, collectingReceiver.getMessages().size()); byte[] receivedBytes = collectingReceiver.getMessages().get(0); assertEquals(responseBytes.length, receivedBytes.length); for (int i = 0; i < responseBytes.length; i++) { assertEquals(responseBytes[i], receivedBytes[i]); } container.stop(); container.destroy(); }
@Override protected void doSuspend() throws Exception { if (listenerContainer != null) { listenerContainer.stop(); } }