@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(); }
@Override @Transactional("jmsTxManager") @CacheEvict( value = {"fixedDepositList"}, allEntries = true, beforeInvocation = true) public void createFixedDeposit(final FixedDepositDetails fdd) throws Exception { logger.info("createFixedDeposit method invoked"); jmsTemplate.send( "emailQueueDestination", new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { TextMessage textMessage = session.createTextMessage(); textMessage.setText(fdd.getEmail()); return textMessage; } }); // --this JMS message goes to the default destination configured for the // JmsTemplate jmsTemplate.send( new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { ObjectMessage objectMessage = session.createObjectMessage(); objectMessage.setObject(fdd); return objectMessage; } }); }
public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:integration-transformer.xml"); JmsTemplate jmsTemplate = context.getBean("jmsTemplate", JmsTemplate.class); jmsTemplate.send( new MessageCreator() { @Override public javax.jms.Message createMessage(Session session) throws JMSException { MapMessage message = session.createMapMessage(); message.setString("firstName", "John"); message.setString("lastName", "Smith"); message.setString("address", "100 State Street"); message.setString("city", "Los Angeles"); message.setString("state", "CA"); message.setString("zip", "90064"); System.out.println("Sending message: " + message); return message; } }); PollableChannel output = (PollableChannel) context.getBean("output"); Message<?> reply = output.receive(); System.out.println("received: " + reply.getPayload()); }
@Test public void testReceiveMessageWithJmsTemplate() { JmsMessageReceiver receiver = new JmsMessageReceiver(); receiver.setJmsTemplate(jmsTemplate); Map<String, Object> controlHeaders = new HashMap<String, Object>(); final Message<String> controlMessage = MessageBuilder.withPayload("<TestRequest><Message>Hello World!</Message></TestRequest>") .copyHeaders(controlHeaders) .build(); reset(jmsTemplate, connectionFactory, destination); jmsTemplate.setReceiveTimeout(5000L); expectLastCall().once(); expect(jmsTemplate.getDefaultDestination()).andReturn(destination).atLeastOnce(); expect(jmsTemplate.receiveAndConvert()).andReturn(controlMessage); replay(jmsTemplate, connectionFactory, destination); Message<?> receivedMessage = receiver.receive(); Assert.assertTrue(receivedMessage.equals(controlMessage)); verify(jmsTemplate, connectionFactory, destination); }
@Test public void validateSuccessfulConsumeAndTransferToSuccess() throws Exception { JmsTemplate jmsTemplate = CommonTest.buildJmsTemplateForDestination("cooQueue", false); JMSPublisher sender = new JMSPublisher(jmsTemplate, mock(ComponentLog.class)); sender.publish("Hey dude!".getBytes()); TestRunner runner = TestRunners.newTestRunner(new ConsumeJMS()); JMSConnectionFactoryProviderDefinition cs = mock(JMSConnectionFactoryProviderDefinition.class); when(cs.getIdentifier()).thenReturn("cfProvider"); when(cs.getConnectionFactory()).thenReturn(jmsTemplate.getConnectionFactory()); runner.addControllerService("cfProvider", cs); runner.enableControllerService(cs); runner.setProperty(PublishJMS.CF_SERVICE, "cfProvider"); runner.setProperty(ConsumeJMS.DESTINATION, "cooQueue"); runner.setProperty(ConsumeJMS.DESTINATION_TYPE, ConsumeJMS.QUEUE); runner.run(1, false); // final MockFlowFile successFF = runner.getFlowFilesForRelationship(PublishJMS.REL_SUCCESS).get(0); assertNotNull(successFF); assertEquals("cooQueue", successFF.getAttributes().get(JmsHeaders.DESTINATION)); successFF.assertContentEquals("Hey dude!".getBytes()); ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy(); }
@Test public void testWithReply() throws Exception { QueueChannel replies = new QueueChannel(); this.gateway1.setOutputChannel(replies); this.gateway1.start(); this.gateway1.handleMessage( MessageBuilder.withPayload("foo") .setHeader( JmsHeaders.CORRELATION_ID, "baz") // make sure it's restored in case we're from an upstream gw .build()); JmsTemplate template = new JmsTemplate(this.ccf); template.setReceiveTimeout(10000); final Message received = template.receive("asyncTest1"); assertNotNull(received); template.send( received.getJMSReplyTo(), new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { TextMessage textMessage = session.createTextMessage("bar"); textMessage.setJMSCorrelationID(received.getJMSCorrelationID()); return textMessage; } }); org.springframework.messaging.Message<?> reply = replies.receive(10000); assertNotNull(reply); assertEquals("bar", reply.getPayload()); assertEquals("baz", reply.getHeaders().get(JmsHeaders.CORRELATION_ID)); this.gateway1.stop(); }
// @PostConstruct public void init() { jmsTemplate.setConnectionFactory(jmsConnectionFactory); jmsTemplate.setDefaultDestination(truConnectQueue); jmsTemplate.setSessionTransacted(true); jmsTemplate.setDeliveryMode(DeliveryMode.PERSISTENT); jmsTemplate.setSessionAcknowledgeMode(Session.AUTO_ACKNOWLEDGE); }
@Bean @Lazy public JmsTemplate jmsTemplate() { final JmsTemplate jmsTemplate = new JmsTemplate(amqConnectionFactory()); jmsTemplate.setDefaultDestination(destination()); jmsTemplate.setReceiveTimeout(1000); return jmsTemplate; }
private void receiveAndSend(JmsTemplate template) { javax.jms.Message request = template.receive(requestQueue7); final javax.jms.Message jmsReply = request; try { template.send(request.getJMSReplyTo(), (MessageCreator) session -> jmsReply); } catch (JmsException | JMSException e) { } }
@Bean public JmsTemplate jmsTemplate() { JmsTemplate jmsTemplate = new JmsTemplate(); jmsTemplate.setConnectionFactory(connectionFactory()); jmsTemplate.setDefaultDestinationName("mail.queue"); jmsTemplate.setMessageConverter(mailMessageConverter()); return jmsTemplate; }
@Test public void pollingAdapterWithReceiveTimeout() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("jmsInboundWithReceiveTimeout.xml", this.getClass()); JmsTemplate jmsTemplate = TestUtils.getPropertyValue( context.getBean("adapter"), "source.jmsTemplate", JmsTemplate.class); assertEquals(99, jmsTemplate.getReceiveTimeout()); }
@Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean.getClass().isAssignableFrom(JmsTemplate.class)) { JmsTemplate jmsTemplate = (JmsTemplate) bean; jmsTemplate.setPubSubDomain(true); } return bean; }
private void sendMessage(Object msg) { try { final String text = converter.toXML(msg); MessageCreator creator = session -> session.createTextMessage(text); JmsTemplate template = context.getBean(JmsTemplate.class); template.setConnectionFactory(connectionFactory); template.send(serverQueue, creator); } catch (Exception e) { log.warn("Exception " + e.toString() + " sending message - ignoring"); } }
public void send(String target) { MessageCreator messageCreator = new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { return session.createTextMessage("test"); } }; JmsTemplate jmsTemplate = AppRun.getContext().getBean(JmsTemplate.class); jmsTemplate.send(target, messageCreator); }
@Test public void testPubSubDomainOverride() { load(TestConfiguration.class, "spring.jms.pubSubDomain:false"); JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); ActiveMQConnectionFactory connectionFactory = this.context.getBean(ActiveMQConnectionFactory.class); assertThat(jmsTemplate).isNotNull(); assertThat(jmsTemplate.isPubSubDomain()).isFalse(); assertThat(connectionFactory).isNotNull(); assertThat(connectionFactory).isEqualTo(jmsTemplate.getConnectionFactory()); }
@Test public void testActiveMQOverriddenPoolAndStandalone() { load(TestConfiguration.class, "spring.activemq.pooled:true", "spring.activemq.inMemory:false"); JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); PooledConnectionFactory pool = this.context.getBean(PooledConnectionFactory.class); assertThat(jmsTemplate).isNotNull(); assertThat(pool).isNotNull(); assertThat(pool).isEqualTo(jmsTemplate.getConnectionFactory()); ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) pool.getConnectionFactory(); assertThat(factory.getBrokerURL()).isEqualTo(ACTIVEMQ_NETWORK_URL); }
@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 testActiveMQOverriddenRemoteHost() { load(TestConfiguration.class, "spring.activemq.brokerUrl:tcp://remote-host:10000"); JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); ActiveMQConnectionFactory connectionFactory = this.context.getBean(ActiveMQConnectionFactory.class); assertThat(jmsTemplate).isNotNull(); assertThat(connectionFactory).isNotNull(); assertThat(connectionFactory).isEqualTo(jmsTemplate.getConnectionFactory()); assertThat(((ActiveMQConnectionFactory) jmsTemplate.getConnectionFactory()).getBrokerURL()) .isEqualTo("tcp://remote-host:10000"); }
@Test public void testActiveMQOverriddenStandalone() { load(TestConfiguration.class, "spring.activemq.inMemory:false"); JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); ActiveMQConnectionFactory connectionFactory = this.context.getBean(ActiveMQConnectionFactory.class); assertThat(jmsTemplate).isNotNull(); assertThat(connectionFactory).isNotNull(); assertThat(connectionFactory).isEqualTo(jmsTemplate.getConnectionFactory()); assertThat(((ActiveMQConnectionFactory) jmsTemplate.getConnectionFactory()).getBrokerURL()) .isEqualTo(ACTIVEMQ_NETWORK_URL); }
@Test public void topicReferenceChannel() { assertEquals(JmsDestinationBackedMessageChannel.class, topicReferenceChannel.getClass()); JmsDestinationBackedMessageChannel channel = (JmsDestinationBackedMessageChannel) topicReferenceChannel; DirectFieldAccessor accessor = new DirectFieldAccessor(channel); JmsTemplate jmsTemplate = (JmsTemplate) accessor.getPropertyValue("jmsTemplate"); AbstractMessageListenerContainer container = (AbstractMessageListenerContainer) accessor.getPropertyValue("container"); assertEquals(topic, jmsTemplate.getDefaultDestination()); assertEquals(topic, container.getDestination()); }
@Test public void testJmsTemplateBackOffEverything() { this.context = createContext(TestConfiguration2.class, TestConfiguration3.class, TestConfiguration5.class); JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); assertThat(jmsTemplate.getPriority()).isEqualTo(999); assertThat(this.context.getBean(ActiveMQConnectionFactory.class).getBrokerURL()) .isEqualTo("foobar"); JmsMessagingTemplate messagingTemplate = this.context.getBean(JmsMessagingTemplate.class); assertThat(messagingTemplate.getDefaultDestinationName()).isEqualTo("fooBar"); assertThat(messagingTemplate.getJmsTemplate()).isEqualTo(jmsTemplate); }
@Test public void adapterWithoutJmsTemplateAndAcknowlegeMode() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("jmsInboundWithJmsTemplate.xml", this.getClass()); JmsTemplate jmsTemplate = TestUtils.getPropertyValue( context.getBean("inboundAdapterWithoutJmsTemplate"), "source.jmsTemplate", JmsTemplate.class); assertEquals(0, jmsTemplate.getSessionAcknowledgeMode()); context.stop(); }
@Test public void queueNameWithResolverChannel() { assertEquals(JmsDestinationBackedMessageChannel.class, queueNameWithResolverChannel.getClass()); JmsDestinationBackedMessageChannel channel = (JmsDestinationBackedMessageChannel) queueNameWithResolverChannel; DirectFieldAccessor accessor = new DirectFieldAccessor(channel); JmsTemplate jmsTemplate = (JmsTemplate) accessor.getPropertyValue("jmsTemplate"); AbstractMessageListenerContainer container = (AbstractMessageListenerContainer) accessor.getPropertyValue("container"); assertEquals("foo", jmsTemplate.getDefaultDestinationName()); assertEquals("foo", container.getDestinationName()); }
public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); JmsTemplate jmsTemplate = (JmsTemplate) context.getBean("jmsTemplate"); jmsTemplate.send( new MessageCreator() { public ObjectMessage createMessage(Session session) throws JMSException { ObjectMessage message = session.createObjectMessage(); message.setObject("My first Message"); return message; } }); System.out.println("MESSAGE SENT TO myMessageQueue"); }
@Test public void gatewayWithReplyChannel() { ActiveMqTestUtils.prepare(); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("jmsGatewayWithReplyChannel.xml", this.getClass()); JmsMessageDrivenEndpoint gateway = (JmsMessageDrivenEndpoint) context.getBean("gateway"); Object replyChannel = TestUtils.getPropertyValue(gateway, "listener.gatewayDelegate.replyChannel"); assertEquals(context.getBean("replies"), replyChannel); JmsTemplate template = new JmsTemplate(context.getBean(ConnectionFactory.class)); template.convertAndSend("testDestination", "Hello"); assertNotNull(template.receive("testReplyDestination")); }
@Test public void testDefaultJmsConfiguration() { load(TestConfiguration.class); ActiveMQConnectionFactory connectionFactory = this.context.getBean(ActiveMQConnectionFactory.class); JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); JmsMessagingTemplate messagingTemplate = this.context.getBean(JmsMessagingTemplate.class); assertThat(connectionFactory).isEqualTo(jmsTemplate.getConnectionFactory()); assertThat(messagingTemplate.getJmsTemplate()).isEqualTo(jmsTemplate); assertThat(((ActiveMQConnectionFactory) jmsTemplate.getConnectionFactory()).getBrokerURL()) .isEqualTo(ACTIVEMQ_EMBEDDED_URL); assertThat(this.context.containsBean("jmsListenerContainerFactory")).isTrue(); }
public static void main(String[] args) { @SuppressWarnings("resource") ApplicationContext ctx = new ClassPathXmlApplicationContext("/beans.xml"); JmsTemplate template = (JmsTemplate) ctx.getBean("jmsTemplate"); Destination destination = (Destination) ctx.getBean("sessionAwareQueueDestination"); template.send( destination, new MessageCreator() { public Message createMessage(Session session) throws JMSException { return session.createTextMessage("Send the message for the SessionAwareQueue test"); } }); System.out.println("JMS Message Sent"); }
@Test public void testContainerWithDestNameNoCorrelation() 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(requestQueue4); gateway.setReplyDestinationName("reply4"); gateway.setUseReplyContainer(true); gateway.afterPropertiesSet(); gateway.start(); final AtomicReference<Object> reply = new AtomicReference<Object>(); final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); Executors.newSingleThreadExecutor() .execute( () -> { latch1.countDown(); try { reply.set(gateway.handleRequestMessage(new GenericMessage<String>("foo"))); } finally { latch2.countDown(); } }); assertTrue(latch1.await(10, TimeUnit.SECONDS)); JmsTemplate template = new JmsTemplate(); template.setConnectionFactory(getConnectionFactory()); template.setReceiveTimeout(10000); javax.jms.Message request = template.receive(requestQueue4); assertNotNull(request); final javax.jms.Message jmsReply = request; template.send( request.getJMSReplyTo(), (MessageCreator) session -> { jmsReply.setJMSCorrelationID(jmsReply.getJMSMessageID()); return jmsReply; }); assertTrue(latch2.await(10, TimeUnit.SECONDS)); assertNotNull(reply.get()); gateway.stop(); scheduler.destroy(); }
@Test public void testActiveMQOverriddenPoolAndRemoteServer() { load( TestConfiguration.class, "spring.activemq.pooled:true", "spring.activemq.brokerUrl:tcp://remote-host:10000"); JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); PooledConnectionFactory pool = this.context.getBean(PooledConnectionFactory.class); assertThat(jmsTemplate).isNotNull(); assertThat(pool).isNotNull(); assertThat(pool).isEqualTo(jmsTemplate.getConnectionFactory()); ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) pool.getConnectionFactory(); assertThat(factory.getBrokerURL()).isEqualTo("tcp://remote-host:10000"); }
/** * Creates a {@link org.springframework.jms.core.JmsOperations} object used for request/response * using a request timeout value */ public JmsOperations createInOutTemplate( JmsEndpoint endpoint, boolean pubSubDomain, String destination, long requestTimeout) { JmsOperations answer = createInOnlyTemplate(endpoint, pubSubDomain, destination); if (answer instanceof JmsTemplate && requestTimeout > 0) { JmsTemplate jmsTemplate = (JmsTemplate) answer; jmsTemplate.setExplicitQosEnabled(true); // prefer to use timeToLive over requestTimeout if both specified long ttl = timeToLive > 0 ? timeToLive : requestTimeout; if (ttl > 0 && !isDisableTimeToLive()) { // only use TTL if not disabled jmsTemplate.setTimeToLive(ttl); } jmsTemplate.setSessionTransacted(isTransactedInOut()); if (isTransactedInOut()) { jmsTemplate.setSessionAcknowledgeMode(Session.SESSION_TRANSACTED); } else { if (acknowledgementMode >= 0) { jmsTemplate.setSessionAcknowledgeMode(acknowledgementMode); } else if (acknowledgementModeName != null) { jmsTemplate.setSessionAcknowledgeModeName(acknowledgementModeName); } else { // default to AUTO jmsTemplate.setSessionAcknowledgeMode(Session.AUTO_ACKNOWLEDGE); } } } return answer; }