org.springframework.jms.core.JmsTemplate Java Examples

The following examples show how to use org.springframework.jms.core.JmsTemplate. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ChannelEventManagerTest.java    From blackduck-alert with Apache License 2.0 7 votes vote down vote up
@Test
public void testNotAbstractChannelEvent() throws Exception {
    AuditUtility auditUtility = Mockito.mock(AuditUtility.class);
    JmsTemplate jmsTemplate = Mockito.mock(JmsTemplate.class);
    ContentConverter contentConverter = Mockito.mock(ContentConverter.class);
    Mockito.doNothing().when(jmsTemplate).convertAndSend(Mockito.anyString(), Mockito.any(Object.class));
    ChannelEventManager eventManager = new ChannelEventManager(contentConverter, jmsTemplate, auditUtility);
    LinkableItem subTopic = new LinkableItem("subTopic", "sub topic", null);
    ProviderMessageContent content = new ProviderMessageContent.Builder()
                                         .applyProvider("testProvider", 1L, "testProviderConfig")
                                         .applyTopic("testTopic", "topic")
                                         .applySubTopic(subTopic.getName(), subTopic.getValue())
                                         .build();
    AlertEvent dbStoreEvent = new ContentEvent("", RestConstants.formatDate(new Date()), "", "FORMAT", MessageContentGroup.singleton(content));
    eventManager.sendEvent(dbStoreEvent);
}
 
Example #2
Source File: JmsTransactionManagerTests.java    From java-technology-stack with MIT License 7 votes vote down vote up
@Test
public void testTransactionRollback() throws JMSException {
	ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection con = mock(Connection.class);
	final Session session = mock(Session.class);

	given(cf.createConnection()).willReturn(con);
	given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session);

	JmsTransactionManager tm = new JmsTransactionManager(cf);
	TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
	JmsTemplate jt = new JmsTemplate(cf);
	jt.execute(new SessionCallback<Void>() {
		@Override
		public Void doInJms(Session sess) {
			assertTrue(sess == session);
			return null;
		}
	});
	tm.rollback(ts);

	verify(session).rollback();
	verify(session).close();
	verify(con).close();
}
 
Example #3
Source File: AMQP10JMSAutoConfigurationTest.java    From amqp-10-jms-spring-boot with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultsToLocalURI() {
    load(EmptyConfiguration.class);

    JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class);
    ConnectionFactory connectionFactory =
        this.context.getBean(ConnectionFactory.class);

    assertTrue(connectionFactory instanceof JmsConnectionFactory);

    JmsConnectionFactory qpidJmsFactory = (JmsConnectionFactory) connectionFactory;

    assertEquals(jmsTemplate.getConnectionFactory(), connectionFactory);
    assertEquals("amqp://localhost:5672", qpidJmsFactory.getRemoteURI());
    assertNull(qpidJmsFactory.getUsername());
    assertNull(qpidJmsFactory.getPassword());
}
 
Example #4
Source File: EventManagerTest.java    From blackduck-alert with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendEvents() throws Exception {
    JmsTemplate jmsTemplate = Mockito.mock(JmsTemplate.class);
    ContentConverter contentConverter = Mockito.mock(ContentConverter.class);
    Mockito.doNothing().when(jmsTemplate).convertAndSend(Mockito.anyString(), Mockito.any(Object.class));
    EventManager eventManager = new EventManager(contentConverter, jmsTemplate);

    LinkableItem subTopic = new LinkableItem("subTopic", "sub topic", null);
    ProviderMessageContent content = new ProviderMessageContent.Builder()
                                         .applyProvider("provider", 1L, "providerConfig")
                                         .applyTopic("testTopic", "topic")
                                         .applySubTopic(subTopic.getName(), subTopic.getValue())
                                         .build();
    FieldAccessor fieldAccessor = new FieldAccessor(Map.of());
    DistributionEvent event = new DistributionEvent(UUID.randomUUID().toString(), "destination", RestConstants.formatDate(new Date()), "provider", "FORMAT",
        MessageContentGroup.singleton(content), fieldAccessor);
    eventManager.sendEvents(List.of(event));
}
 
Example #5
Source File: JMSPublisherConsumerIT.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * At the moment the only two supported message types are TextMessage and
 * BytesMessage which is sufficient for the type if JMS use cases NiFi is
 * used. The may change to the point where all message types are supported
 * at which point this test will no be longer required.
 */
@Test
public void validateFailOnUnsupportedMessageType() throws Exception {
    final String destinationName = "validateFailOnUnsupportedMessageType";
    JmsTemplate jmsTemplate = CommonTest.buildJmsTemplateForDestination(false);

    try {
        jmsTemplate.send(destinationName, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                return session.createObjectMessage();
            }
        });

        JMSConsumer consumer = new JMSConsumer((CachingConnectionFactory) jmsTemplate.getConnectionFactory(), jmsTemplate, mock(ComponentLog.class));
        consumer.consume(destinationName, null, false, false, null, "UTF-8", new ConsumerCallback() {
            @Override
            public void accept(JMSResponse response) {
                // noop
            }
        });
    } finally {
        ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
    }
}
 
Example #6
Source File: AMQP10JMSAutoConfigurationTest.java    From amqp-10-jms-spring-boot with Apache License 2.0 6 votes vote down vote up
@Test
public void testReceiveLocalOnlyOptionsAppliedFromEnvOverridesURI() {
    load(EmptyConfiguration.class,
         "amqphub.amqp10jms.remote-url=amqp://127.0.0.1:5672" +
             "?jms.receiveLocalOnly=false&jms.receiveNoWaitLocalOnly=false",
         "amqphub.amqp10jms.receiveLocalOnly=true",
         "amqphub.amqp10jms.receiveNoWaitLocalOnly=true");

    JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class);
    JmsConnectionFactory connectionFactory =
        this.context.getBean(JmsConnectionFactory.class);

    assertEquals(jmsTemplate.getConnectionFactory(), connectionFactory);

    assertTrue(connectionFactory.isReceiveLocalOnly());
    assertTrue(connectionFactory.isReceiveNoWaitLocalOnly());
}
 
Example #7
Source File: AbstractJMSProcessor.java    From solace-integration-guides with Apache License 2.0 6 votes vote down vote up
/**
 * This method essentially performs initialization of this Processor by
 * obtaining an instance of the {@link ConnectionFactory} from the
 * {@link JMSConnectionFactoryProvider} (ControllerService) and performing a
 * series of {@link ConnectionFactory} adaptations which eventually results
 * in an instance of the {@link CachingConnectionFactory} used to construct
 * {@link JmsTemplate} used by this Processor.
 */
private void buildTargetResource(ProcessContext context) {
    if (this.targetResource == null) {
        JMSConnectionFactoryProviderDefinition cfProvider = context.getProperty(CF_SERVICE).asControllerService(JMSConnectionFactoryProviderDefinition.class);
        ConnectionFactory connectionFactory = cfProvider.getConnectionFactory();

        UserCredentialsConnectionFactoryAdapter cfCredentialsAdapter = new UserCredentialsConnectionFactoryAdapter();
        cfCredentialsAdapter.setTargetConnectionFactory(connectionFactory);
        cfCredentialsAdapter.setUsername(context.getProperty(USER).getValue());
        cfCredentialsAdapter.setPassword(context.getProperty(PASSWORD).getValue());

        this.cachingConnectionFactory = new CachingConnectionFactory(cfCredentialsAdapter);
        this.cachingConnectionFactory.setSessionCacheSize(Integer.parseInt(context.getProperty(SESSION_CACHE_SIZE).getValue()));

        JmsTemplate jmsTemplate = new JmsTemplate();
        jmsTemplate.setConnectionFactory(this.cachingConnectionFactory);
        jmsTemplate.setPubSubDomain(TOPIC.equals(context.getProperty(DESTINATION_TYPE).getValue()));

        // set of properties that may be good candidates for exposure via configuration
        jmsTemplate.setReceiveTimeout(1000);

        this.targetResource = this.finishBuildingTargetResource(jmsTemplate, context);
    }
}
 
Example #8
Source File: JMSPublisherConsumerTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void validateBytesConvertedToBytesMessageOnSend() throws Exception {
    final String destinationName = "testQueue";
    JmsTemplate jmsTemplate = CommonTest.buildJmsTemplateForDestination(false);

    JMSPublisher publisher = new JMSPublisher(jmsTemplate, mock(ComponentLog.class));
    publisher.publish(destinationName, "hellomq".getBytes());

    Message receivedMessage = jmsTemplate.receive(destinationName);
    assertTrue(receivedMessage instanceof BytesMessage);
    byte[] bytes = new byte[7];
    ((BytesMessage) receivedMessage).readBytes(bytes);
    assertEquals("hellomq", new String(bytes));

    ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
}
 
Example #9
Source File: JmsTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testLazyTransactionalSession() throws JMSException {
	ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection con = mock(Connection.class);
	final Session session = mock(Session.class);

	JmsTransactionManager tm = new JmsTransactionManager(cf);
	tm.setLazyResourceRetrieval(true);
	TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());

	given(cf.createConnection()).willReturn(con);
	given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session);

	JmsTemplate jt = new JmsTemplate(cf);
	jt.execute((SessionCallback<Void>) sess -> {
		assertSame(sess, session);
		return null;
	});
	tm.commit(ts);

	verify(session).commit();
	verify(session).close();
	verify(con).close();
}
 
Example #10
Source File: JMSPublisherConsumerTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * At the moment the only two supported message types are TextMessage and
 * BytesMessage which is sufficient for the type if JMS use cases NiFi is
 * used. The may change to the point where all message types are supported
 * at which point this test will no be longer required.
 */
@Test(expected = IllegalStateException.class)
public void validateFailOnUnsupportedMessageType() throws Exception {
    final String destinationName = "testQueue";
    JmsTemplate jmsTemplate = CommonTest.buildJmsTemplateForDestination(false);

    jmsTemplate.send(destinationName, new MessageCreator() {
        @Override
        public Message createMessage(Session session) throws JMSException {
            return session.createObjectMessage();
        }
    });

    JMSConsumer consumer = new JMSConsumer(jmsTemplate, mock(ComponentLog.class));
    try {
        consumer.consume(destinationName, new ConsumerCallback() {
            @Override
            public void accept(JMSResponse response) {
                // noop
            }
        });
    } finally {
        ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
    }
}
 
Example #11
Source File: JMSPublisherConsumerTest.java    From solace-integration-guides with Apache License 2.0 6 votes vote down vote up
/**
 * At the moment the only two supported message types are TextMessage and
 * BytesMessage which is sufficient for the type if JMS use cases NiFi is
 * used. The may change to the point where all message types are supported
 * at which point this test will no be longer required.
 */
@Test(expected = IllegalStateException.class)
public void validateFailOnUnsupportedMessageType() throws Exception {
    final String destinationName = "testQueue";
    JmsTemplate jmsTemplate = CommonTest.buildJmsTemplateForDestination(false);

    jmsTemplate.send(destinationName, new MessageCreator() {
        @Override
        public Message createMessage(Session session) throws JMSException {
            return session.createObjectMessage();
        }
    });

    JMSConsumer consumer = new JMSConsumer(jmsTemplate, mock(ComponentLog.class));
    try {
        consumer.consume(destinationName, new ConsumerCallback() {
            @Override
            public void accept(JMSResponse response) {
                // noop
            }
        });
    } finally {
        ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
    }
}
 
Example #12
Source File: JMSPublisherConsumerTest.java    From solace-integration-guides with Apache License 2.0 6 votes vote down vote up
@Test
public void validateBytesConvertedToBytesMessageOnSendOverJNDI() throws Exception {
    final String destinationName = "testQueue";
    JmsTemplate jmsTemplate = CommonTest.buildJmsJndiTemplateForDestination(false);

    JMSPublisher publisher = new JMSPublisher(jmsTemplate, mock(ComponentLog.class));
    publisher.publish(destinationName, "hellomq".getBytes());

    Message receivedMessage = jmsTemplate.receive(destinationName);
    assertTrue(receivedMessage instanceof BytesMessage);
    byte[] bytes = new byte[7];
    ((BytesMessage) receivedMessage).readBytes(bytes);
    assertEquals("hellomq", new String(bytes));

    ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
}
 
Example #13
Source File: AbstractJMSProcessor.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * This method essentially performs initialization of this Processor by
 * obtaining an instance of the {@link ConnectionFactory} from the
 * {@link JMSConnectionFactoryProvider} (ControllerService) and performing a
 * series of {@link ConnectionFactory} adaptations which eventually results
 * in an instance of the {@link CachingConnectionFactory} used to construct
 * {@link JmsTemplate} used by this Processor.
 */
private T buildTargetResource(ProcessContext context) {
    final ConnectionFactory connectionFactory = connectionFactoryProvider.getConnectionFactory();

    final UserCredentialsConnectionFactoryAdapter cfCredentialsAdapter = new UserCredentialsConnectionFactoryAdapter();
    cfCredentialsAdapter.setTargetConnectionFactory(connectionFactory);
    cfCredentialsAdapter.setUsername(context.getProperty(USER).evaluateAttributeExpressions().getValue());
    cfCredentialsAdapter.setPassword(context.getProperty(PASSWORD).getValue());

    final CachingConnectionFactory cachingFactory = new CachingConnectionFactory(cfCredentialsAdapter);
    setClientId(context, cachingFactory);

    JmsTemplate jmsTemplate = new JmsTemplate();
    jmsTemplate.setConnectionFactory(cachingFactory);
    jmsTemplate.setPubSubDomain(TOPIC.equals(context.getProperty(DESTINATION_TYPE).getValue()));

    return finishBuildingJmsWorker(cachingFactory, jmsTemplate, context);
}
 
Example #14
Source File: JMSPublisherConsumerIT.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void testMessage(String destinationName, MessageCreator messageCreator, ConsumerCallback responseChecker) {
    JmsTemplate jmsTemplate = CommonTest.buildJmsTemplateForDestination(false);

    AtomicBoolean callbackInvoked = new AtomicBoolean();

    try {
        jmsTemplate.send(destinationName, messageCreator);

        JMSConsumer consumer = new JMSConsumer((CachingConnectionFactory) jmsTemplate.getConnectionFactory(), jmsTemplate, mock(ComponentLog.class));
        consumer.consume(destinationName, null, false, false, null, "UTF-8", response -> {
            callbackInvoked.set(true);
            responseChecker.accept(response);
        });

        assertTrue(callbackInvoked.get());
    } finally {
        ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
    }
}
 
Example #15
Source File: SpringBootJmsV2Application.java    From pro-spring-boot with Apache License 2.0 6 votes vote down vote up
@Bean
CommandLineRunner start(JmsTemplate template){
	return args -> {
		log.info("Sending> ...");
		template.convertAndSend(queue, "SpringBoot Rocks!");
	};
}
 
Example #16
Source File: ConsumeJMSTest.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void validateSuccessfulConsumeAndTransferToSuccess() throws Exception {
    final String  destinationName = "cooQueue";
    JmsTemplate jmsTemplate = CommonTest.buildJmsTemplateForDestination(false);
    JMSPublisher sender = new JMSPublisher(jmsTemplate, mock(ComponentLog.class));
    final Map<String, String> senderAttributes = new HashMap<>();
    senderAttributes.put("filename", "message.txt");
    senderAttributes.put("attribute_from_sender", "some value");
    sender.publish(destinationName, "Hey dude!".getBytes(), senderAttributes);
    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, destinationName);
    runner.setProperty(ConsumeJMS.DESTINATION_TYPE, ConsumeJMS.QUEUE);
    runner.run(1, false);
    //
    final MockFlowFile successFF = runner.getFlowFilesForRelationship(PublishJMS.REL_SUCCESS).get(0);
    assertNotNull(successFF);
    successFF.assertAttributeExists(JmsHeaders.DESTINATION);
    successFF.assertAttributeEquals(JmsHeaders.DESTINATION, destinationName);
    successFF.assertAttributeExists("filename");
    successFF.assertAttributeEquals("filename", "message.txt");
    successFF.assertAttributeExists("attribute_from_sender");
    successFF.assertAttributeEquals("attribute_from_sender", "some value");
    successFF.assertContentEquals("Hey dude!".getBytes());
    String sourceDestination = successFF.getAttribute(ConsumeJMS.JMS_SOURCE_DESTINATION_NAME);
    assertNotNull(sourceDestination);

    ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
}
 
Example #17
Source File: PublishJMSTest.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void validateSuccessfulPublishAndTransferToSuccessWithEL() throws Exception {
    ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");

    final String destinationNameExpression = "${foo}Queue";
    final String destinationName = "fooQueue";
    PublishJMS pubProc = new PublishJMS();
    TestRunner runner = TestRunners.newTestRunner(pubProc);
    JMSConnectionFactoryProviderDefinition cs = mock(JMSConnectionFactoryProviderDefinition.class);
    when(cs.getIdentifier()).thenReturn("cfProvider");
    when(cs.getConnectionFactory()).thenReturn(cf);

    runner.addControllerService("cfProvider", cs);
    runner.enableControllerService(cs);

    runner.setProperty(PublishJMS.CF_SERVICE, "cfProvider");
    runner.setProperty(PublishJMS.DESTINATION, destinationNameExpression);

    Map<String, String> attributes = new HashMap<>();
    attributes.put("foo", "foo");
    attributes.put(JmsHeaders.REPLY_TO, "cooQueue");
    runner.enqueue("Hey dude!".getBytes(), attributes);
    runner.run(1, false);

    final MockFlowFile successFF = runner.getFlowFilesForRelationship(PublishJMS.REL_SUCCESS).get(0);
    assertNotNull(successFF);

    JmsTemplate jmst = new JmsTemplate(cf);
    BytesMessage message = (BytesMessage) jmst.receive(destinationName);

    byte[] messageBytes = MessageBodyToBytesConverter.toBytes(message);
    assertEquals("Hey dude!", new String(messageBytes));
    assertEquals("cooQueue", ((Queue) message.getJMSReplyTo()).getQueueName());
    assertEquals("foo", message.getStringProperty("foo"));
}
 
Example #18
Source File: AlarmJmsConfig.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Bean
public JmsTemplate alarmTopicPublisherJmsTemplate() {
  int ttl = properties.getJms().getClientTopicMsgTimeToLive();
  JmsTemplate jmsTemplate = JmsTopicTemplateFactory.createJmsTemplate(clientSingleConnectionFactory, ttl);

  String alarmTopic = properties.getJms().getAlarmTopic();
  jmsTemplate.setDefaultDestination(new ActiveMQTopic(alarmTopic));

  return jmsTemplate;
}
 
Example #19
Source File: JMSPublisherConsumerTest.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void validateConsumeWithCustomHeadersAndProperties() throws Exception {
    final String destinationName = "testQueue";
    JmsTemplate jmsTemplate = CommonTest.buildJmsTemplateForDestination(false);

    jmsTemplate.send(destinationName, new MessageCreator() {
        @Override
        public Message createMessage(Session session) throws JMSException {
            TextMessage message = session.createTextMessage("hello from the other side");
            message.setStringProperty("foo", "foo");
            message.setBooleanProperty("bar", false);
            message.setJMSReplyTo(session.createQueue("fooQueue"));
            return message;
        }
    });

    JMSConsumer consumer = new JMSConsumer(jmsTemplate, mock(ComponentLog.class));
    final AtomicBoolean callbackInvoked = new AtomicBoolean();
    consumer.consume(destinationName, new ConsumerCallback() {
        @Override
        public void accept(JMSResponse response) {
            callbackInvoked.set(true);
            assertEquals("hello from the other side", new String(response.getMessageBody()));
            assertEquals("fooQueue", response.getMessageHeaders().get(JmsHeaders.REPLY_TO));
            assertEquals("foo", response.getMessageProperties().get("foo"));
            assertEquals("false", response.getMessageProperties().get("bar"));
        }
    });
    assertTrue(callbackInvoked.get());

    ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
}
 
Example #20
Source File: PublishJMSTest.java    From solace-integration-guides with Apache License 2.0 5 votes vote down vote up
@Test
public void validateSuccessfulPublishAndTransferToSuccessOverJNDI() throws Exception {
    ActiveMQConnectionFactory cf = (ActiveMQConnectionFactory) CommonTest.buildJmsJndiConnectionFactory();

    final String destinationName = "fooQueue";
    PublishJMS pubProc = new PublishJMS();
    TestRunner runner = TestRunners.newTestRunner(pubProc);
    JMSConnectionFactoryProviderDefinition cs = mock(JMSConnectionFactoryProviderDefinition.class);
    when(cs.getIdentifier()).thenReturn("cfProvider");
    when(cs.getConnectionFactory()).thenReturn(cf);

    runner.addControllerService("cfProvider", cs);
    runner.enableControllerService(cs);

    runner.setProperty(PublishJMS.CF_SERVICE, "cfProvider");
    runner.setProperty(PublishJMS.DESTINATION, destinationName);

    Map<String, String> attributes = new HashMap<>();
    attributes.put("foo", "foo");
    attributes.put(JmsHeaders.REPLY_TO, "cooQueue");
    runner.enqueue("Hey dude!".getBytes(), attributes);
    runner.run(1, false);

    final MockFlowFile successFF = runner.getFlowFilesForRelationship(PublishJMS.REL_SUCCESS).get(0);
    assertNotNull(successFF);

    JmsTemplate jmst = new JmsTemplate(cf);
    BytesMessage message = (BytesMessage) jmst.receive(destinationName);

    byte[] messageBytes = MessageBodyToBytesConverter.toBytes(message);
    assertEquals("Hey dude!", new String(messageBytes));
    assertEquals("cooQueue", ((Queue) message.getJMSReplyTo()).getQueueName());
    assertEquals("foo", message.getStringProperty("foo"));
}
 
Example #21
Source File: CommonTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
static JmsTemplate buildJmsTemplateForDestination(boolean pubSub) {
    ConnectionFactory activeMqConnectionFactory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");
    final ConnectionFactory connectionFactory = new CachingConnectionFactory(activeMqConnectionFactory);

    JmsTemplate jmsTemplate = new JmsTemplate(connectionFactory);
    jmsTemplate.setPubSubDomain(pubSub);
    jmsTemplate.setSessionAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE);
    jmsTemplate.setReceiveTimeout(10L);
    return jmsTemplate;
}
 
Example #22
Source File: ConsumeJMS.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Will create an instance of {@link JMSConsumer}
 */
@Override
protected JMSConsumer finishBuildingTargetResource(JmsTemplate jmsTemplate, ProcessContext processContext) {
    int ackMode = processContext.getProperty(ACKNOWLEDGEMENT_MODE).asInteger();
    jmsTemplate.setSessionAcknowledgeMode(ackMode);
    return new JMSConsumer(jmsTemplate, this.getLogger());
}
 
Example #23
Source File: JMSPublisherConsumerIT.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void validateJmsHeadersAndPropertiesAreTransferredFromFFAttributes() throws Exception {
    final String destinationName = "validateJmsHeadersAndPropertiesAreTransferredFromFFAttributes";
    JmsTemplate jmsTemplate = CommonTest.buildJmsTemplateForDestination(false);

    try {
        JMSPublisher publisher = new JMSPublisher((CachingConnectionFactory) jmsTemplate.getConnectionFactory(), jmsTemplate, mock(ComponentLog.class));
        Map<String, String> flowFileAttributes = new HashMap<>();
        flowFileAttributes.put("foo", "foo");
        flowFileAttributes.put("hyphen-property", "value");
        flowFileAttributes.put("fullstop.property", "value");
        flowFileAttributes.put(JmsHeaders.REPLY_TO, "myTopic");
        flowFileAttributes.put(JmsHeaders.DELIVERY_MODE, "1");
        flowFileAttributes.put(JmsHeaders.PRIORITY, "1");
        flowFileAttributes.put(JmsHeaders.EXPIRATION, "never"); // value expected to be integer, make sure non-integer doesn't cause problems
        publisher.publish(destinationName, "hellomq".getBytes(), flowFileAttributes);

        Message receivedMessage = jmsTemplate.receive(destinationName);
        assertTrue(receivedMessage instanceof BytesMessage);
        assertEquals("foo", receivedMessage.getStringProperty("foo"));
        assertTrue(receivedMessage.propertyExists("hyphen-property"));
        assertTrue(receivedMessage.propertyExists("fullstop.property"));
        assertTrue(receivedMessage.getJMSReplyTo() instanceof Topic);
        assertEquals(1, receivedMessage.getJMSDeliveryMode());
        assertEquals(1, receivedMessage.getJMSPriority());
        assertEquals("myTopic", ((Topic) receivedMessage.getJMSReplyTo()).getTopicName());

    } finally {
        ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
    }
}
 
Example #24
Source File: SpringBootJmsApplication.java    From pro-spring-boot with Apache License 2.0 5 votes vote down vote up
@Bean
CommandLineRunner sendMessage(JmsTemplate jmsTemplate){
	return args -> {
		Producer producer = new Producer(jmsTemplate);
		producer.sendTo(queue, "Spring Boot Rocks!");
	};
}
 
Example #25
Source File: ActiveMQSubscribeConnectorTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Test
public void subscribeTest() throws InterruptedException {
    final String message = UUID.randomUUID().toString();

    MockEndpoint mock = getMockEndpoint("mock:result");
    mock.expectedMessageCount(1);
    mock.expectedBodiesReceived(message);

    JmsTemplate template = new JmsTemplate(broker.createConnectionFactory());
    template.send(testName.getMethodName(), session -> session.createTextMessage(message));

    mock.assertIsSatisfied();
}
 
Example #26
Source File: JmsConfig.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Bean
public JmsTemplate clientJmsTemplate() {
  JmsTemplate jmsTemplate = new JmsTemplate(new CachingConnectionFactory(clientJmsConnectionFactory()));
  jmsTemplate.setExplicitQosEnabled(true);
  jmsTemplate.setDeliveryPersistent(false);
  return jmsTemplate;
}
 
Example #27
Source File: ActiveMQSharedConnectionTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Test
public void sharedConnectionTest() {
    final String message = UUID.randomUUID().toString();
    final SjmsComponent sjms1 = context.getComponent("sjms-sjms-0-0", SjmsComponent.class);
    final SjmsComponent sjms2 = context.getComponent("sjms-sjms-0-1", SjmsComponent.class);

    Assertions.assertThat(sjms1).isEqualTo(sjms2);

    JmsTemplate template = new JmsTemplate(broker.createConnectionFactory());
    template.send("sub-" + testName.getMethodName(), session -> session.createTextMessage(message));
    Object answer = template.receive("pub-" + testName.getMethodName());

    Assertions.assertThat(answer).isInstanceOf(TextMessage.class);
    Assertions.assertThat(answer).hasFieldOrPropertyWithValue("text", message);
}
 
Example #28
Source File: MQProducer.java    From paas with Apache License 2.0 5 votes vote down vote up
/**
 * 延时发送
 * @param message 内容,一般为JSON
 * @param time 时间(单位:ms)
 * @author jitwxs
 * @since 2018/5/8 21:08
 */
public void delaySend(Destination destination,String message, Long time) {
    // 得到jmsTemplate
    JmsTemplate jmsTemplate = jmsMessagingTemplate.getJmsTemplate();
    // 发送消息
    jmsTemplate.send(destination, session -> {
        TextMessage textMessage = session.createTextMessage(message);
        // 设置延时时间
        textMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time);
        return textMessage;
    });
}
 
Example #29
Source File: JmsUtil.java    From zheng with MIT License 5 votes vote down vote up
/**
 * 发送文本消息
 * @param jmsTemplate
 * @param destination
 * @param textMessage
 */
public static void sendMessage(JmsTemplate jmsTemplate, Destination destination, final String textMessage) {
    jmsTemplate.send(destination, new MessageCreator() {
        @Override
        public Message createMessage(Session session) throws JMSException {
            return session.createTextMessage(textMessage);
        }
    });
}
 
Example #30
Source File: SolaceJmsAutoCloudConfigurationTest.java    From solace-jms-spring-boot with Apache License 2.0 5 votes vote down vote up
@Test
public void isCloudConfiguredBySolaceMessagingInfoAndOtherProperties() {
	makeCloudEnv();

	String JSONString = addOneSolaceService("VCAP_SERVICES");
	String CF_VCAP_SERVICES = "VCAP_SERVICES={ \"solace-pubsub\": [" + JSONString + "] }";

	load(CF_CLOUD_APP_ENV, CF_VCAP_SERVICES, "solace.jms.host=192.168.1.80:55500",
			"solace.jms.clientUsername=bob", "solace.jms.clientPassword=password", "solace.jms.msgVpn=newVpn");

	SpringSolJmsConnectionFactoryCloudFactory springSolConnectionFactoryCloudFactory = this.context
			.getBean(SpringSolJmsConnectionFactoryCloudFactory.class);
	assertNotNull(springSolConnectionFactoryCloudFactory);

	SolConnectionFactory solConnectionFactory = this.context.getBean(SolConnectionFactory.class);
	assertNotNull(solConnectionFactory);

	JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class);

	// Notice that the other properties where ineffective
	assertEquals(jmsTemplate.getConnectionFactory(), solConnectionFactory);
	assertEquals("tcp://192.168.1.50:7000", solConnectionFactory.getHost());
	assertEquals("sample-msg-vpn", solConnectionFactory.getVPN());
	assertEquals("sample-client-username", solConnectionFactory.getUsername());
	assertEquals("sample-client-password", solConnectionFactory.getPassword());
	assertFalse(solConnectionFactory.getDirectTransport());

}