org.springframework.jms.connection.CachingConnectionFactory Java Examples

The following examples show how to use org.springframework.jms.connection.CachingConnectionFactory. 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: MQConnectionFactoryConfiguration.java    From mq-jms-spring with Apache License 2.0 8 votes vote down vote up
@Bean
@ConditionalOnProperty(prefix = "spring.jms.cache", name = "enabled", havingValue = "true", matchIfMissing = true)
public CachingConnectionFactory cachingJmsConnectionFactory(MQConfigurationProperties properties,
    ObjectProvider<List<MQConnectionFactoryCustomizer>> factoryCustomizers, JmsProperties jmsProperties) {

  JmsProperties.Cache cacheProperties = jmsProperties.getCache();

  MQConnectionFactory wrappedConnectionFactory = createConnectionFactory(properties, factoryCustomizers);

  CachingConnectionFactory connectionFactory = new CachingConnectionFactory(wrappedConnectionFactory);
  connectionFactory.setCacheConsumers(cacheProperties.isConsumers());
  connectionFactory.setCacheProducers(cacheProperties.isProducers());
  connectionFactory.setSessionCacheSize(cacheProperties.getSessionCacheSize());

  return connectionFactory;
}
 
Example #2
Source File: AbstractJMSProcessor.java    From localization_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 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 #3
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 #4
Source File: JMSPublisherConsumerTest.java    From solace-integration-guides with Apache License 2.0 6 votes vote down vote up
public void validateFailOnUnsupportedMessageTypeOverJNDI() throws Exception {
    final String destinationName = "testQueue";
    JmsTemplate jmsTemplate = CommonTest.buildJmsJndiTemplateForDestination(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 #5
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 #6
Source File: JMSPublisherConsumerTest.java    From solace-integration-guides with Apache License 2.0 6 votes vote down vote up
@Test
public void validateJmsHeadersAndPropertiesAreTransferredFromFFAttributes() throws Exception {
    final String destinationName = "testQueue";
    JmsTemplate jmsTemplate = CommonTest.buildJmsTemplateForDestination(false);

    JMSPublisher publisher = new JMSPublisher(jmsTemplate, mock(ComponentLog.class));
    Map<String, String> flowFileAttributes = new HashMap<>();
    flowFileAttributes.put("foo", "foo");
    flowFileAttributes.put(JmsHeaders.REPLY_TO, "myTopic");
    publisher.publish(destinationName, "hellomq".getBytes(), flowFileAttributes);

    Message receivedMessage = jmsTemplate.receive(destinationName);
    assertTrue(receivedMessage instanceof BytesMessage);
    assertEquals("foo", receivedMessage.getStringProperty("foo"));
    assertTrue(receivedMessage.getJMSReplyTo() instanceof Topic);
    assertEquals("myTopic", ((Topic) receivedMessage.getJMSReplyTo()).getTopicName());

    ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
}
 
Example #7
Source File: JMSPublisherConsumerTest.java    From solace-integration-guides with Apache License 2.0 6 votes vote down vote up
@Test
public void validateJmsHeadersAndPropertiesAreTransferredFromFFAttributesOverJNDI() throws Exception {
    final String destinationName = "testQueue";
    JmsTemplate jmsTemplate = CommonTest.buildJmsJndiTemplateForDestination(false);

    JMSPublisher publisher = new JMSPublisher(jmsTemplate, mock(ComponentLog.class));
    Map<String, String> flowFileAttributes = new HashMap<>();
    flowFileAttributes.put("foo", "foo");
    flowFileAttributes.put(JmsHeaders.REPLY_TO, "myTopic");
    publisher.publish(destinationName, "hellomq".getBytes(), flowFileAttributes);

    Message receivedMessage = jmsTemplate.receive(destinationName);
    assertTrue(receivedMessage instanceof BytesMessage);
    assertEquals("foo", receivedMessage.getStringProperty("foo"));
    assertTrue(receivedMessage.getJMSReplyTo() instanceof Topic);
    assertEquals("myTopic", ((Topic) receivedMessage.getJMSReplyTo()).getTopicName());

    ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
}
 
Example #8
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 #9
Source File: JMSPublisherConsumerTest.java    From solace-integration-guides 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 #10
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 #11
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 #12
Source File: JMSPublisherConsumerIT.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void validateBytesConvertedToBytesMessageOnSend() throws Exception {
    final String destinationName = "validateBytesConvertedToBytesMessageOnSend";
    JmsTemplate jmsTemplate = CommonTest.buildJmsTemplateForDestination(false);

    try {
        JMSPublisher publisher = new JMSPublisher((CachingConnectionFactory) jmsTemplate.getConnectionFactory(), 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));
    } finally {
        ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
    }
}
 
Example #13
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 #14
Source File: ConsumeJMSManualTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void send(MessageCreator messageCreator) throws Exception {
    final String  destinationName = "TEST";

    ConnectionFactory activeMqConnectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
    final ConnectionFactory connectionFactory = new CachingConnectionFactory(activeMqConnectionFactory);

    JmsTemplate jmsTemplate = new JmsTemplate(connectionFactory);
    jmsTemplate.setPubSubDomain(false);
    jmsTemplate.setSessionAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE);
    jmsTemplate.setReceiveTimeout(10L);

    try {
        JMSPublisher sender = new JMSPublisher((CachingConnectionFactory) jmsTemplate.getConnectionFactory(), jmsTemplate, mock(ComponentLog.class));

        sender.jmsTemplate.send(destinationName, messageCreator);
    } finally {
        ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
    }
}
 
Example #15
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 #16
Source File: JMSPublisherConsumerTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void validateJmsHeadersAndPropertiesAreTransferredFromFFAttributes() throws Exception {
    final String destinationName = "testQueue";
    JmsTemplate jmsTemplate = CommonTest.buildJmsTemplateForDestination(false);

    JMSPublisher publisher = new JMSPublisher(jmsTemplate, mock(ComponentLog.class));
    Map<String, String> flowFileAttributes = new HashMap<>();
    flowFileAttributes.put("foo", "foo");
    flowFileAttributes.put(JmsHeaders.REPLY_TO, "myTopic");
    publisher.publish(destinationName, "hellomq".getBytes(), flowFileAttributes);

    Message receivedMessage = jmsTemplate.receive(destinationName);
    assertTrue(receivedMessage instanceof BytesMessage);
    assertEquals("foo", receivedMessage.getStringProperty("foo"));
    assertTrue(receivedMessage.getJMSReplyTo() instanceof Topic);
    assertEquals("myTopic", ((Topic) receivedMessage.getJMSReplyTo()).getTopicName());

    ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
}
 
Example #17
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 #18
Source File: ProducerConfiguration.java    From solace-samples-cloudfoundry-java with Apache License 2.0 5 votes vote down vote up
@Bean
public JmsTemplate jmsTemplate() {
	CachingConnectionFactory ccf = new CachingConnectionFactory(connectionFactory);
	JmsTemplate jmst = new JmsTemplate(ccf);
	jmst.setPubSubDomain(true);	// This sample is publishing to topics
	return jmst;
}
 
Example #19
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 #20
Source File: EventRegistryJmsConfiguration.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Bean
public CachingConnectionFactory cachingJmsConnectionFactory() {
    // configuration properties are Spring Boot defaults
    ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");
    activeMQConnectionFactory.setCloseTimeout((int) Duration.ofSeconds(15).toMillis());
    activeMQConnectionFactory.setNonBlockingRedelivery(false);
    activeMQConnectionFactory.setSendTimeout(0); // wait forever

    CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(activeMQConnectionFactory);
    cachingConnectionFactory.setCacheConsumers(false);
    cachingConnectionFactory.setCacheProducers(true);
    cachingConnectionFactory.setSessionCacheSize(1);

    return cachingConnectionFactory;
}
 
Example #21
Source File: SpringJmsConfig.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Bean
public ConnectionFactory connectionFactory() {
    ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");
    activeMQConnectionFactory.setUseAsyncSend(true);
    activeMQConnectionFactory.setAlwaysSessionAsync(true);
    activeMQConnectionFactory.setStatsEnabled(true);
    return new CachingConnectionFactory(activeMQConnectionFactory);
}
 
Example #22
Source File: TracingConnectionFactoryBeanPostProcessor.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
		throws BeansException {
	// Wrap the caching connection factories instead of its target, because it catches
	// callbacks
	// such as ExceptionListener. If we don't wrap, cached callbacks like this won't
	// be traced.
	if (bean instanceof CachingConnectionFactory) {
		return new LazyConnectionFactory(this.beanFactory,
				(CachingConnectionFactory) bean);
	}
	if (bean instanceof JmsMessageEndpointManager) {
		JmsMessageEndpointManager manager = (JmsMessageEndpointManager) bean;
		MessageListener listener = manager.getMessageListener();
		if (listener != null) {
			manager.setMessageListener(
					new LazyMessageListener(this.beanFactory, listener));
		}
		return bean;
	}
	if (bean instanceof XAConnectionFactory && bean instanceof ConnectionFactory) {
		return new LazyConnectionAndXaConnectionFactory(this.beanFactory,
				(ConnectionFactory) bean, (XAConnectionFactory) bean);
	}
	// We check XA first in case the ConnectionFactory also implements
	// XAConnectionFactory
	else if (bean instanceof XAConnectionFactory) {
		return new LazyXAConnectionFactory(this.beanFactory,
				(XAConnectionFactory) bean);
	}
	else if (bean instanceof TopicConnectionFactory) {
		return new LazyTopicConnectionFactory(this.beanFactory,
				(TopicConnectionFactory) bean);
	}
	else if (bean instanceof ConnectionFactory) {
		return new LazyConnectionFactory(this.beanFactory, (ConnectionFactory) bean);
	}
	return bean;
}
 
Example #23
Source File: MQHierachy.java    From Thunder with Apache License 2.0 5 votes vote down vote up
private void initializeCachingConnectionFactory() throws Exception {
    int sessionCacheSize = mqPropertyEntity.getInteger(ThunderConstant.MQ_SESSION_CACHE_SIZE_ATTRIBUTE_NAME);
    boolean cacheConsumers = mqPropertyEntity.getBoolean(ThunderConstant.MQ_CACHE_CONSUMERS_ATTRIBUTE_NAME);
    boolean cacheProducers = mqPropertyEntity.getBoolean(ThunderConstant.MQ_CACHE_PRODUCERS_ATTRIBUTE_NAME);
    boolean reconnectOnException = mqPropertyEntity.getBoolean(ThunderConstant.MQ_RECONNECT_ON_EXCEPTION_ATTRIBUTE_NAME);

    CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory();
    cachingConnectionFactory.setSessionCacheSize(sessionCacheSize);
    cachingConnectionFactory.setCacheConsumers(cacheConsumers);
    cachingConnectionFactory.setCacheProducers(cacheProducers);
    cachingConnectionFactory.setReconnectOnException(reconnectOnException);

    connectionFactory = cachingConnectionFactory;
}
 
Example #24
Source File: ConsumeJMS.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Will create an instance of {@link JMSConsumer}
 */
@Override
protected JMSConsumer finishBuildingJmsWorker(CachingConnectionFactory connectionFactory, JmsTemplate jmsTemplate, ProcessContext processContext) {
    int ackMode = processContext.getProperty(ACKNOWLEDGEMENT_MODE).asInteger();
    jmsTemplate.setSessionAcknowledgeMode(ackMode);

    long timeout = processContext.getProperty(TIMEOUT).evaluateAttributeExpressions().asTimePeriod(TimeUnit.MILLISECONDS);
    jmsTemplate.setReceiveTimeout(timeout);

    return new JMSConsumer(connectionFactory, jmsTemplate, this.getLogger());
}
 
Example #25
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 #26
Source File: ConsumeJMSIT.java    From 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);
    try {
        JMSPublisher sender = new JMSPublisher((CachingConnectionFactory) jmsTemplate.getConnectionFactory(), 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.assertAttributeExists("jms.messagetype");
        successFF.assertAttributeEquals("jms.messagetype", "BytesMessage");
        successFF.assertContentEquals("Hey dude!".getBytes());
        String sourceDestination = successFF.getAttribute(ConsumeJMS.JMS_SOURCE_DESTINATION_NAME);
        assertNotNull(sourceDestination);
    } finally {
        ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
    }
}
 
Example #27
Source File: JMSPublisherConsumerIT.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void validateConsumeWithCustomHeadersAndProperties() throws Exception {
    final String destinationName = "validateConsumeWithCustomHeadersAndProperties";
    JmsTemplate jmsTemplate = CommonTest.buildJmsTemplateForDestination(false);

    try {
        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((CachingConnectionFactory) jmsTemplate.getConnectionFactory(), jmsTemplate, mock(ComponentLog.class));
        final AtomicBoolean callbackInvoked = new AtomicBoolean();
        consumer.consume(destinationName, null, false, false, null, "UTF-8", 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());

    } finally {
        ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
    }
}
 
Example #28
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 #29
Source File: ConsumeJMSIT.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void testValidateErrorQueue(String destinationType, String errorQueue, boolean expectedValid) throws Exception {
    JmsTemplate jmsTemplate = CommonTest.buildJmsTemplateForDestination(false);

    try {
        TestRunner runner = TestRunners.newTestRunner(new ConsumeJMS());

        JMSConnectionFactoryProviderDefinition cfService = mock(JMSConnectionFactoryProviderDefinition.class);
        when(cfService.getIdentifier()).thenReturn("cfService");
        when(cfService.getConnectionFactory()).thenReturn(jmsTemplate.getConnectionFactory());

        runner.addControllerService("cfService", cfService);
        runner.enableControllerService(cfService);

        runner.setProperty(PublishJMS.CF_SERVICE, "cfService");
        runner.setProperty(ConsumeJMS.DESTINATION, "destination");
        runner.setProperty(ConsumeJMS.DESTINATION_TYPE, destinationType);
        if (errorQueue != null) {
            runner.setProperty(ConsumeJMS.ERROR_QUEUE, errorQueue);
        }

        if (expectedValid) {
            runner.assertValid();
        } else {
            runner.assertNotValid();
        }
    } finally {
        ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
    }
}
 
Example #30
Source File: ConsumeJMSIT.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnsupportedMessage() throws Exception {
    JmsTemplate jmsTemplate = CommonTest.buildJmsTemplateForDestination(false);
    try {
        ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");

        JMSPublisher sender = new JMSPublisher((CachingConnectionFactory) jmsTemplate.getConnectionFactory(), jmsTemplate, mock(ComponentLog.class));

        sender.jmsTemplate.send("testMapMessage", __ -> createUnsupportedMessage("unsupportedMessagePropertyKey", "unsupportedMessagePropertyValue"));

        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, "testMapMessage");
        runner.setProperty(ConsumeJMS.ERROR_QUEUE, "errorQueue");
        runner.setProperty(ConsumeJMS.DESTINATION_TYPE, ConsumeJMS.QUEUE);
        runner.run(1, false);

        JmsTemplate jmst = new JmsTemplate(cf);
        Message message = jmst.receive("errorQueue");

        assertNotNull(message);
        assertEquals(message.getStringProperty("unsupportedMessagePropertyKey"), "unsupportedMessagePropertyValue");
    } finally {
        ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
    }
}