Java Code Examples for javax.jms.ConnectionFactory

The following are top voted examples for showing how to use javax.jms.ConnectionFactory. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: flume-release-1.7.0   File: TestIntegrationActiveMQ.java   Source Code and License 14 votes vote down vote up
private void putTopic(List<String> events) throws Exception {
  ConnectionFactory factory = new ActiveMQConnectionFactory(USERNAME,
      PASSWORD, BROKER_BIND_URL);
  Connection connection = factory.createConnection();
  connection.start();

  Session session = connection.createSession(true,
      Session.AUTO_ACKNOWLEDGE);
  Destination destination = session.createTopic(DESTINATION_NAME);
  MessageProducer producer = session.createProducer(destination);

  for (String event : events) {
    TextMessage message = session.createTextMessage();
    message.setText(event);
    producer.send(message);
  }
  session.commit();
  session.close();
  connection.close();
}
 
Example 2
Project: pooled-jms   File: JmsPoolXAConnectionFactory.java   Source Code and License 7 votes vote down vote up
@Override
protected XAJMSContext createProviderContext(String username, String password, int sessionMode) {
    if (connectionFactory instanceof ConnectionFactory) {
        if (username == null && password == null) {
            return ((XAConnectionFactory) connectionFactory).createXAContext();
        } else {
            return ((XAConnectionFactory) connectionFactory).createXAContext(username, password);
        }
    } else {
        throw new javax.jms.IllegalStateRuntimeException("connectionFactory should implement javax.jms.ConnectionFactory");
    }
}
 
Example 3
Project: pooled-jms   File: PooledConnectionTempQueueTest.java   Source Code and License 7 votes vote down vote up
public void receiveAndRespondWithMessageIdAsCorrelationId(ConnectionFactory connectionFactory, String queueName) throws JMSException {
    Connection connection = connectionFactory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(session.createQueue(queueName));
    final javax.jms.Message inMessage = consumer.receive();

    String requestMessageId = inMessage.getJMSMessageID();
    LOG.debug("Received message " + requestMessageId);
    final TextMessage replyMessage = session.createTextMessage("Result");
    replyMessage.setJMSCorrelationID(inMessage.getJMSMessageID());
    final MessageProducer producer = session.createProducer(inMessage.getJMSReplyTo());
    LOG.debug("Sending reply to " + inMessage.getJMSReplyTo());
    producer.send(replyMessage);

    producer.close();
    consumer.close();
    session.close();
    connection.close();
}
 
Example 4
Project: eds   File: EdsCamelConfig.java   Source Code and License 7 votes vote down vote up
@Bean(name="connectionFactory")
	public ConnectionFactory connectionFactory(){
		ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory();
//		activeMQConnectionFactory.setUseAsyncSend(true);
		activeMQConnectionFactory.setUserName(jmsUserName);
		activeMQConnectionFactory.setPassword(jmsPassword);
		activeMQConnectionFactory.setBrokerURL(jmsBrokerUrl);

		// 默认重复投递6次将转发到死信队列,改为无限次数
//		RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy();
//		redeliveryPolicy.setMaximumRedeliveries(-1);
//		
//		activeMQConnectionFactory.setRedeliveryPolicy(redeliveryPolicy);
		
		PooledConnectionFactory pooledConnectionFactory = new PooledConnectionFactory(activeMQConnectionFactory);
		pooledConnectionFactory.setMaxConnections(jmsMaxPooledConnections);
//		CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(pooledConnectionFactory);
//		cachingConnectionFactory.setSessionCacheSize(10);
		return pooledConnectionFactory;
	}
 
Example 5
Project: estafet-microservices-scrum-api-project-burndown   File: Application.java   Source Code and License 7 votes vote down vote up
@Bean
public JmsListenerContainerFactory<?> myFactory(ConnectionFactory connectionFactory,
		DefaultJmsListenerContainerFactoryConfigurer configurer) {
	DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
	configurer.configure(factory, connectionFactory);
	return factory;
}
 
Example 6
Project: pooled-jms   File: PooledConnectionTest.java   Source Code and License 6 votes vote down vote up
@Test(timeout = 60000)
public void testSetClientIDTwiceWithSameID() throws Exception {
    LOG.debug("running testRepeatedSetClientIDCalls()");

    // test: call setClientID("newID") twice
    // this should be tolerated and not result in an exception
    ConnectionFactory cf = createPooledConnectionFactory();
    Connection conn = cf.createConnection();
    conn.setClientID("newID");

    try {
        conn.setClientID("newID");
        conn.start();
        conn.close();
    } catch (IllegalStateException ise) {
        LOG.error("Repeated calls to newID2.setClientID(\"newID\") caused " + ise.getMessage());
        fail("Repeated calls to newID2.setClientID(\"newID\") caused " + ise.getMessage());
    } finally {
        ((JmsPoolConnectionFactory) cf).stop();
    }

    LOG.debug("Test finished.");
}
 
Example 7
Project: myth   File: JmsConfig.java   Source Code and License 6 votes vote down vote up
@Bean(name = "queueListenerContainerFactory")
@ConditionalOnProperty(prefix = "spring.activemq", name = "broker-url")
public JmsListenerContainerFactory<?> jmsListenerContainerQueue(ConnectionFactory activeMQConnectionFactory) {
    DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
    bean.setConnectionFactory(activeMQConnectionFactory);
    bean.setPubSubDomain(Boolean.FALSE);
    return bean;
}
 
Example 8
Project: pooled-jms   File: PooledConnectionTest.java   Source Code and License 6 votes vote down vote up
@Test(timeout = 60000)
public void testSetClientIDAfterConnectionStart() throws Exception {
    LOG.debug("running testRepeatedSetClientIDCalls()");

    ConnectionFactory cf = createPooledConnectionFactory();
    Connection conn = cf.createConnection();

    // test: try to call setClientID() after start()
    // should result in an exception
    try {
        conn.start();
        conn.setClientID("newID3");
        fail("Calling setClientID() after start() mut raise a JMSException.");
    } catch (IllegalStateException ise) {
        LOG.debug("Correctly received " + ise);
    } finally {
        conn.close();
        ((JmsPoolConnectionFactory) cf).stop();
    }

    LOG.debug("Test finished.");
}
 
Example 9
Project: pooled-jms   File: PooledSessionExhaustionBlockTimeoutTest.java   Source Code and License 6 votes vote down vote up
public void sendMessages(ConnectionFactory connectionFactory) throws Exception {
    for (int i = 0; i < NUM_MESSAGES; i++) {
        Connection connection = connectionFactory.createConnection();
        connection.start();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue(QUEUE);
        MessageProducer producer = session.createProducer(destination);

        String msgTo = "hello";
        TextMessage message = session.createTextMessage(msgTo);
        producer.send(message);
        connection.close();
        LOG.debug("sent " + i + " messages using " + connectionFactory.getClass());
    }
}
 
Example 10
Project: flume-release-1.7.0   File: TestIntegrationActiveMQ.java   Source Code and License 6 votes vote down vote up
private void putQueue(List<String> events) throws Exception {
  ConnectionFactory factory = new ActiveMQConnectionFactory(USERNAME,
      PASSWORD, BROKER_BIND_URL);
  Connection connection = factory.createConnection();
  connection.start();

  Session session = connection.createSession(true,
      Session.AUTO_ACKNOWLEDGE);
  Destination destination = session.createQueue(DESTINATION_NAME);
  MessageProducer producer = session.createProducer(destination);

  for (String event : events) {
    TextMessage message = session.createTextMessage();
    message.setText(event);
    producer.send(message);
  }
  session.commit();
  session.close();
  connection.close();
}
 
Example 11
Project: eds   File: CamelJmsTestHelper.java   Source Code and License 6 votes vote down vote up
private static ConnectionFactory createConnectionFactory(String options, Integer maximumRedeliveries) {
        // using a unique broker name improves testing when running the entire test suite in the same JVM
        int id = counter.incrementAndGet();
        String url = "tcp://192.168.3.103:61618";
//        if (options != null) {
//            url = url + "&" + options;
//        }
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
        // optimize AMQ to be as fast as possible so unit testing is quicker
        connectionFactory.setCopyMessageOnSend(false);
        connectionFactory.setOptimizeAcknowledge(true);
        connectionFactory.setOptimizedMessageDispatch(true);
        // When using asyncSend, producers will not be guaranteed to send in the order we
        // have in the tests (which may be confusing for queues) so we need this set to false.
        // Another way of guaranteeing order is to use persistent messages or transactions.
        connectionFactory.setUseAsyncSend(false);
        connectionFactory.setAlwaysSessionAsync(false);
        if (maximumRedeliveries != null) {
            connectionFactory.getRedeliveryPolicy().setMaximumRedeliveries(maximumRedeliveries);
        }
//        connectionFactory.setTrustAllPackages(true);
        return connectionFactory;
    }
 
Example 12
Project: eds   File: CamelJmsTestHelper.java   Source Code and License 6 votes vote down vote up
private static ConnectionFactory createPersistentConnectionFactory(String options) {
        // using a unique broker name improves testing when running the entire test suite in the same JVM
        int id = counter.incrementAndGet();

        // use an unique data directory in target
        String dir = "target/activemq-data-" + id;

        // remove dir so its empty on startup
        FileUtil.removeDir(new File(dir));

        String url = "vm://test-broker-" + id + "?broker.persistent=true&broker.useJmx=false&broker.dataDirectory=" + dir;
        if (options != null) {
            url = url + "&" + options;
        }
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
        // optimize AMQ to be as fast as possible so unit testing is quicker
        connectionFactory.setCopyMessageOnSend(false);
        connectionFactory.setOptimizeAcknowledge(true);
        connectionFactory.setOptimizedMessageDispatch(true);
        connectionFactory.setAlwaysSessionAsync(false);
//        connectionFactory.setTrustAllPackages(true);
        return connectionFactory;
    }
 
Example 13
Project: nifi-jms-jndi   File: AbstractJMSProcessor.java   Source Code and License 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 14
Project: nifi-jms-jndi   File: PublishJMSTest.java   Source Code and License 6 votes vote down vote up
@Test
public void validateFailedPublishAndTransferToFailure() throws Exception {
    ConnectionFactory cf = mock(ConnectionFactory.class);

    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, "fooQueue");

    runner.enqueue("Hello Joe".getBytes());

    runner.run();
    Thread.sleep(200);

    assertTrue(runner.getFlowFilesForRelationship(PublishJMS.REL_SUCCESS).isEmpty());
    assertNotNull(runner.getFlowFilesForRelationship(PublishJMS.REL_FAILURE).get(0));
}
 
Example 15
Project: nifi-jms-jndi   File: PublishJMSTest.java   Source Code and License 6 votes vote down vote up
@Test
public void validateFailedPublishAndTransferToFailureOverJNDI() throws Exception {
    ConnectionFactory cf = mock(ConnectionFactory.class);

    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, "fooQueue");

    runner.enqueue("Hello Joe".getBytes());

    runner.run();
    Thread.sleep(200);

    assertTrue(runner.getFlowFilesForRelationship(PublishJMS.REL_SUCCESS).isEmpty());
    assertNotNull(runner.getFlowFilesForRelationship(PublishJMS.REL_FAILURE).get(0));
}
 
Example 16
Project: nifi-jms-jndi   File: JMSConnectionFactoryProviderTest.java   Source Code and License 6 votes vote down vote up
@Test
public void validateFullConfigWithUserLib() throws Exception {
    TestRunner runner = TestRunners.newTestRunner(mock(Processor.class));
    JMSConnectionFactoryProvider cfProvider = new JMSConnectionFactoryProvider();
    runner.addControllerService("cfProvider", cfProvider);
    runner.setProperty(cfProvider, JMSConnectionFactoryProvider.BROKER_URI, "myhost:1234");

    runner.setProperty(cfProvider, JMSConnectionFactoryProvider.CLIENT_LIB_DIR_PATH,
            new File("test-lib").getAbsolutePath()); // see README in 'test-lib' dir for more info
    runner.setProperty(cfProvider, JMSConnectionFactoryProvider.CONNECTION_FACTORY_IMPL,
            "org.apache.nifi.jms.testcflib.TestConnectionFactory");
    runner.setProperty(cfProvider, "Foo", "foo");
    runner.setProperty(cfProvider, "Bar", "3");

    runner.enableControllerService(cfProvider);
    runner.assertValid(cfProvider);
    ConnectionFactory cf = cfProvider.getConnectionFactory();
    assertNotNull(cf);
    assertEquals("org.apache.nifi.jms.testcflib.TestConnectionFactory", cf.getClass().getName());
    assertEquals("myhost", this.get("getHost", cf));
    assertEquals(1234, ((Integer) this.get("getPort", cf)).intValue());
    assertEquals("foo", this.get("getFoo", cf));
    assertEquals(3, ((Integer) this.get("getBar", cf)).intValue());
}
 
Example 17
Project: nifi-jms-jndi   File: JNDIConnectionFactoryProviderTest.java   Source Code and License 6 votes vote down vote up
@Test
public void validateFullConfigWithUserLib() throws Exception {
    TestRunner runner = TestRunners.newTestRunner(mock(Processor.class));


    JNDIConnectionFactoryProvider cfProvider = new JNDIConnectionFactoryProvider();
    //when(cfProvider.getConnectionFactory()).thenReturn(mcf);
    runner.addControllerService("cfProvider", cfProvider);
    runner.setProperty(cfProvider, JNDIConnectionFactoryProvider.BROKER_URI, "vm://localhost?broker.persistent=false");
    runner.setProperty(cfProvider, JNDIConnectionFactoryProvider.JNDI_CF_LOOKUP, "ConnectionFactory");

    runner.setProperty(cfProvider, JNDIConnectionFactoryProvider.CLIENT_LIB_DIR_PATH,
            TestUtils.setupActiveMqLibForTesting(false)); // see README in 'test-lib' dir for more info
    runner.setProperty(cfProvider, JNDIConnectionFactoryProvider.CONNECTION_FACTORY_IMPL,
            "org.apache.activemq.jndi.ActiveMQInitialContextFactory");

    runner.enableControllerService(cfProvider);
    runner.assertValid(cfProvider);
    ConnectionFactory cf = cfProvider.getConnectionFactory();
    assertNotNull(cf);
    assertEquals("org.apache.activemq.ActiveMQConnectionFactory", cf.getClass().getName());
}
 
Example 18
Project: camunda-task-dispatcher   File: JmsExternalCommandListenerConfig.java   Source Code and License 6 votes vote down vote up
@Bean
@Autowired
public DefaultMessageListenerContainer taskMessageListenerContainer(JmsExternalCommandListener externalTaskListener
        , ConnectionFactory connectionFactory
        , ActiveMQQueue taskQueue) {
    DefaultMessageListenerContainer listenerContainer = new DefaultMessageListenerContainer();
    listenerContainer.setMessageListener(externalTaskListener);
    listenerContainer.setDestination(taskQueue);
    listenerContainer.setConnectionFactory(connectionFactory);

    listenerContainer.setAcceptMessagesWhileStopping(false);
    listenerContainer.setSessionTransacted(true);
    listenerContainer.setConcurrentConsumers(concurrentConsumers);
    listenerContainer.setMaxMessagesPerTask(maxMessagesPerTask);
    listenerContainer.setReceiveTimeout(receiveTimeout);
    LOG.debug("DefaultMessageListenerContainer for queue [{}] with message selector [{}] was started", listenerContainer.getDestination(), listenerContainer.getMessageSelector());
    return listenerContainer;
}
 
Example 19
Project: camunda-task-dispatcher   File: JmsExternalTaskReceiverConfig.java   Source Code and License 6 votes vote down vote up
@Bean
@Autowired
public DefaultMessageListenerContainer taskMessageListenerContainer(JmsExternalTaskListener externalTaskListener
        , ConnectionFactory receiverConnectionFactory
        , ActiveMQQueue taskQueue) {
    DefaultMessageListenerContainer listenerContainer = new DefaultMessageListenerContainer();
    listenerContainer.setMessageListener(externalTaskListener);
    listenerContainer.setDestination(taskQueue);
    listenerContainer.setConnectionFactory(receiverConnectionFactory);

    listenerContainer.setAcceptMessagesWhileStopping(false);
    listenerContainer.setSessionTransacted(true);
    listenerContainer.setConcurrentConsumers(concurrentConsumers);
    listenerContainer.setMaxMessagesPerTask(maxMessagesPerTask);
    listenerContainer.setReceiveTimeout(receiveTimeout);
    return listenerContainer;
}
 
Example 20
Project: qpid-jms-spring-boot   File: QpidJMSAutoConfigurationTest.java   Source Code and License 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 21
Project: asw   File: SimpleFilter.java   Source Code and License 6 votes vote down vote up
public SimpleFilter(String name, Destination sorgenteMessaggi, Destination destinazioneMessaggi,
		ConnectionFactory connectionFactory, SimpleMessageFilter mf, int maxDelay) {
	this.name = name;
   	this.messageSource = sorgenteMessaggi;
   	this.messageDestination = destinazioneMessaggi;
   	this.connectionFactory = connectionFactory;
   	this.messageFilter = mf;

   	this.maxDelay = maxDelay;

   	/* crea un consumatore su sorgenteMessaggi: 
   	 * girera' messaggi a questo oggetto (this) */
   	this.consumer =
   			new SimpleAsynchConsumer("Consumatore messaggi per " + this.name,
   					this.messageSource, this.connectionFactory, this, 10);
       logger.info("Creato consumatore: " + consumer.toString());

       /* crea un produttore su destinazioneMessaggi */
   	this.producer = new SimpleProducer("Produttore messaggi per " + this.name,
   			this.messageDestination, this.connectionFactory, 10);
       logger.info("Creato produttore: " + producer.toString());

       this.messagesReceived = 0;
       this.cancelled = false;
}
 
Example 22
Project: amqp-10-jms-spring-boot   File: AMQP10JMSAutoConfigurationTest.java   Source Code and License 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 23
Project: solace-integration-guides   File: AbstractJMSProcessor.java   Source Code and License 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 24
Project: solace-integration-guides   File: PublishJMSTest.java   Source Code and License 6 votes vote down vote up
@Test
public void validateFailedPublishAndTransferToFailure() throws Exception {
    ConnectionFactory cf = mock(ConnectionFactory.class);

    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, "fooQueue");

    runner.enqueue("Hello Joe".getBytes());

    runner.run();
    Thread.sleep(200);

    assertTrue(runner.getFlowFilesForRelationship(PublishJMS.REL_SUCCESS).isEmpty());
    assertNotNull(runner.getFlowFilesForRelationship(PublishJMS.REL_FAILURE).get(0));
}
 
Example 25
Project: solace-integration-guides   File: PublishJMSTest.java   Source Code and License 6 votes vote down vote up
@Test
public void validateFailedPublishAndTransferToFailureOverJNDI() throws Exception {
    ConnectionFactory cf = mock(ConnectionFactory.class);

    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, "fooQueue");

    runner.enqueue("Hello Joe".getBytes());

    runner.run();
    Thread.sleep(200);

    assertTrue(runner.getFlowFilesForRelationship(PublishJMS.REL_SUCCESS).isEmpty());
    assertNotNull(runner.getFlowFilesForRelationship(PublishJMS.REL_FAILURE).get(0));
}
 
Example 26
Project: solace-integration-guides   File: JNDIConnectionFactoryProvider.java   Source Code and License 6 votes vote down vote up
/**
 * Creates an instance of the {@link ConnectionFactory} from the provided 'CONNECTION_FACTORY_IMPL'.
 */
private void createConnectionFactoryInstance(ConfigurationContext context) {
    String connectionFactoryImplName = getContextValue(context, CONNECTION_FACTORY_IMPL);
    Properties env = new Properties();

    try {
        env.put(InitialContext.INITIAL_CONTEXT_FACTORY, connectionFactoryImplName);
        env.put(InitialContext.PROVIDER_URL, getContextValue(context, BROKER_URI));

        InitialContext initialContext = new InitialContext(env);
        this.connectionFactory = (ConnectionFactory) initialContext.lookup(context.getProperty(JNDI_CF_LOOKUP).evaluateAttributeExpressions().getValue());
        if (logger.isDebugEnabled())
            logger.debug("Connection factory is created");
    } catch (Exception e) {
        throw new IllegalStateException("Failed to load and/or instantiate class 'com.solacesystems.jndi.SolJNDIInitialContextFactory'", e);
    }
}
 
Example 27
Project: solace-integration-guides   File: JMSConnectionFactoryProviderTest.java   Source Code and License 6 votes vote down vote up
@Test
public void validateFullConfigWithUserLib() throws Exception {
    TestRunner runner = TestRunners.newTestRunner(mock(Processor.class));
    JMSConnectionFactoryProvider cfProvider = new JMSConnectionFactoryProvider();
    runner.addControllerService("cfProvider", cfProvider);
    runner.setProperty(cfProvider, JMSConnectionFactoryProvider.BROKER_URI, "myhost:1234");

    runner.setProperty(cfProvider, JMSConnectionFactoryProvider.CLIENT_LIB_DIR_PATH,
            new File("test-lib").getAbsolutePath()); // see README in 'test-lib' dir for more info
    runner.setProperty(cfProvider, JMSConnectionFactoryProvider.CONNECTION_FACTORY_IMPL,
            "org.apache.nifi.jms.testcflib.TestConnectionFactory");
    runner.setProperty(cfProvider, "Foo", "foo");
    runner.setProperty(cfProvider, "Bar", "3");

    runner.enableControllerService(cfProvider);
    runner.assertValid(cfProvider);
    ConnectionFactory cf = cfProvider.getConnectionFactory();
    assertNotNull(cf);
    assertEquals("org.apache.nifi.jms.testcflib.TestConnectionFactory", cf.getClass().getName());
    assertEquals("myhost", this.get("getHost", cf));
    assertEquals(1234, ((Integer) this.get("getPort", cf)).intValue());
    assertEquals("foo", this.get("getFoo", cf));
    assertEquals(3, ((Integer) this.get("getBar", cf)).intValue());
}
 
Example 28
Project: solace-integration-guides   File: JNDIConnectionFactoryProviderTest.java   Source Code and License 6 votes vote down vote up
@Test
public void validateFullConfigWithUserLib() throws Exception {
    TestRunner runner = TestRunners.newTestRunner(mock(Processor.class));


    JNDIConnectionFactoryProvider cfProvider = new JNDIConnectionFactoryProvider();
    //when(cfProvider.getConnectionFactory()).thenReturn(mcf);
    runner.addControllerService("cfProvider", cfProvider);
    runner.setProperty(cfProvider, JNDIConnectionFactoryProvider.BROKER_URI, "vm://localhost?broker.persistent=false");
    runner.setProperty(cfProvider, JNDIConnectionFactoryProvider.JNDI_CF_LOOKUP, "ConnectionFactory");

    runner.setProperty(cfProvider, JNDIConnectionFactoryProvider.CLIENT_LIB_DIR_PATH,
            TestUtils.setupActiveMqLibForTesting(false)); // see README in 'test-lib' dir for more info
    runner.setProperty(cfProvider, JNDIConnectionFactoryProvider.CONNECTION_FACTORY_IMPL,
            "org.apache.activemq.jndi.ActiveMQInitialContextFactory");

    runner.enableControllerService(cfProvider);
    runner.assertValid(cfProvider);
    ConnectionFactory cf = cfProvider.getConnectionFactory();
    assertNotNull(cf);
    assertEquals("org.apache.activemq.ActiveMQConnectionFactory", cf.getClass().getName());
}
 
Example 29
Project: JBoss-Developers-Guide   File: LoyaltyCardManager.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
   Connection connection = null;
   String csvData = System.getProperty(CSVDATA);
   if(CSVDATA == null || CSVDATA.equals(""))
       throw new RuntimeException("LoyaltyCardManager.main() must pass the "+CSVDATA +" system property With format  OPERATION;USERID;FIRSTNAME;LASTNAME;TRXID;TRXFEESAMOUNT;CURRENCY");
   System.out.println("LoyaltyCardManager() will connect to router: "+ROUTER_URL+" : at the following address: "+QUEUE_NAME);
   ConnectionFactory connectionFactory = new JmsConnectionFactory(ROUTER_URL);
   try {
      // Step 1. Create an AMQP qpid connection
      connection = connectionFactory.createConnection();
      // Step 2. Create a JMS session
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      // Step 3. Create a Producer
      Queue fidelityRequestQueue = session.createQueue(QUEUE_NAME);
      MessageProducer beosbankFidelityRequestProducer = session.createProducer(fidelityRequestQueue);
      // Step 4. send a CSV Text Data on user transactions 
      beosbankFidelityRequestProducer.send(session.createTextMessage(csvData));
      System.out.println("\nmessage sent:"+ csvData+" \n");
   } finally {
      if (connection != null) {
         // Step 9. close the connection
         connection.close();
      }
   }
}
 
Example 30
Project: flume-release-1.7.0   File: TestJMSSource.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testStartConsumerCreateThrowsException() throws Exception {
  when(consumerFactory.create(any(InitialContext.class), any(ConnectionFactory.class),
                              anyString(), any(JMSDestinationType.class),
                              any(JMSDestinationLocator.class), anyString(), anyInt(), anyLong(),
                              any(JMSMessageConverter.class), any(Optional.class),
                              any(Optional.class))).thenThrow(new RuntimeException());
  source.configure(context);
  source.start();
  try {
    source.process();
    Assert.fail();
  } catch (FlumeException expected) {

  }
}
 
Example 31
Project: jaffa-framework   File: JaffaConnectionFactory.java   Source Code and License 6 votes vote down vote up
/**
 * Obtains the JMS ConnectionFactory from the JNDI context, as defined in the
 * configuration file.
 * 
 * @throws FrameworkException
 *           in case any internal error occurs.
 * @throws ApplicationExceptions
 *           Indicates application error(s).
 * @return the JMS ConnectionFactory from the JNDI context, as defined in the
 *         configuration file.
 */
private ConnectionFactory getConnectionFactory()
    throws ApplicationExceptions, FrameworkException {
  try {
    final InitialContext context = InitialContextFactrory
        .obtainInitialContext();
    final JmsConfig jmsConfig = ConfigurationService.getInstance()
        .getJmsConfig();
    return (ConnectionFactory) context.lookup(jmsConfig
        .getConnectionFactory());
  } catch (NamingException e) {
    LOGGER.error("Error in locating the JMS ConnectionFactory", e);
    throw new JaffaMessagingFrameworkException(
        JaffaMessagingFrameworkException.CONNECTION_FACTORY_NOT_FOUND, null,
        e);
  }
}
 
Example 32
Project: org.ops4j.pax.transx   File: ActiveMQTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testSpringLocalTx() throws Exception {
    ConnectionFactory cf = createCF(BROKER_URL);
    JmsTemplate jms = new JmsTemplate(cf);
    jms.setDefaultDestinationName(QUEUE);
    jms.setReceiveTimeout(1000);
    PlatformTransactionManager tm = new JmsTransactionManager(cf);
    TransactionTemplate localTx = new TransactionTemplate(tm);

    localTx.execute(ts -> {
        jms.convertAndSend("Hello");
        return null;
    });
    Object msg = localTx.execute(ts -> jms.receiveAndConvert());
    assertEquals("Hello", msg);

    localTx.execute(ts -> {
        jms.convertAndSend("Hello");
        ts.setRollbackOnly();
        return null;
    });
    msg = localTx.execute(ts -> jms.receiveAndConvert());
    assertNull(msg);
}
 
Example 33
Project: pooled-jms   File: JmsPoolConnectionFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Given a {@link PooledConnectionKey} create a JMS {@link Connection} using the
 * configuration from the key and the assigned JMS {@link ConnectionFactory} instance.
 *
 * @param key
 * 		The {@link PooledSessionKey} to use as configuration for the new JMS Connection.
 *
 * @return a new JMS Connection created using the configured JMS ConnectionFactory.
 *
 * @throws JMSException if an error occurs while creating the new JMS Connection.
 */
protected Connection createProviderConnection(PooledConnectionKey key) throws JMSException {
    if (connectionFactory instanceof ConnectionFactory) {
        if (key.getUserName() == null && key.getPassword() == null) {
            return ((ConnectionFactory) connectionFactory).createConnection();
        } else {
            return ((ConnectionFactory) connectionFactory).createConnection(key.getUserName(), key.getPassword());
        }
    } else {
        throw new IllegalStateException("connectionFactory should implement javax.jms.ConnectionFactory");
    }
}
 
Example 34
Project: org.ops4j.pax.transx   File: ActiveMQTest.java   Source Code and License 5 votes vote down vote up
private ConnectionFactory createCF(String brokerUrl) throws Exception {
    ConnectionFactory cf = ManagedConnectionFactoryBuilder.builder()
            .transaction(TransactionSupportLevel.XATransaction)
            .transactionManager(tm)
            .name("vmbroker" + brokerId++ )
            .connectionFactory(new ActiveMQConnectionFactory(brokerUrl),
                               new ActiveMQXAConnectionFactory(brokerUrl))
            .build();
    if (cf instanceof AutoCloseable) {
        closeables.add((AutoCloseable) cf);
    }
    return cf;
}
 
Example 35
Project: flume-release-1.7.0   File: TestJMSSource.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
void afterSetup() throws Exception {
  baseDir = Files.createTempDir();
  passwordFile = new File(baseDir, "password");
  Assert.assertTrue(passwordFile.createNewFile());
  initialContext = mock(InitialContext.class);
  channelProcessor = mock(ChannelProcessor.class);
  events = Lists.newArrayList();
  doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocation) throws Throwable {
      events.addAll((List<Event>)invocation.getArguments()[0]);
      return null;
    }
  }).when(channelProcessor).processEventBatch(any(List.class));
  consumerFactory = mock(JMSMessageConsumerFactory.class);
  consumer = spy(create());
  when(consumerFactory.create(any(InitialContext.class), any(ConnectionFactory.class),
                              anyString(), any(JMSDestinationType.class),
                              any(JMSDestinationLocator.class), anyString(), anyInt(), anyLong(),
                              any(JMSMessageConverter.class), any(Optional.class),
                              any(Optional.class))).thenReturn(consumer);
  when(initialContext.lookup(anyString())).thenReturn(connectionFactory);
  contextFactory = mock(InitialContextFactory.class);
  when(contextFactory.create(any(Properties.class))).thenReturn(initialContext);
  source = new JMSSource(consumerFactory, contextFactory);
  source.setName("JMSSource-" + UUID.randomUUID());
  source.setChannelProcessor(channelProcessor);
  context = new Context();
  context.put(JMSSourceConfiguration.BATCH_SIZE, String.valueOf(batchSize));
  context.put(JMSSourceConfiguration.DESTINATION_NAME, "INBOUND");
  context.put(JMSSourceConfiguration.DESTINATION_TYPE,
      JMSSourceConfiguration.DESTINATION_TYPE_QUEUE);
  context.put(JMSSourceConfiguration.PROVIDER_URL, "dummy:1414");
  context.put(JMSSourceConfiguration.INITIAL_CONTEXT_FACTORY, "ldap://dummy:389");
}
 
Example 36
Project: JavaSamples   File: JmsListenerContainers.java   Source Code and License 5 votes vote down vote up
@Bean
public JmsListenerContainerFactory<?> jmsListenerContainerTopic(ConnectionFactory activeMQConnectionFactory) {
    DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
    bean.setPubSubDomain(true);
    bean.setConnectionFactory(activeMQConnectionFactory);
    return bean;
}
 
Example 37
Project: eds   File: ActiveMQWithCamelTest.java   Source Code and License 5 votes vote down vote up
protected CamelContext createCamelContext() throws Exception {
  CamelContext camelContext = super.createCamelContext();

  ConnectionFactory connectionFactory = CamelJmsTestHelper.createConnectionFactory();
  camelContext
      .addComponent("activemq", JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));

  return camelContext;
}
 
Example 38
Project: java-spring-cloud   File: JmsTest.java   Source Code and License 5 votes vote down vote up
@Bean
public JmsListenerContainerFactory<?> myFactory(ConnectionFactory connectionFactory,
    DefaultJmsListenerContainerFactoryConfigurer configurer) {
  DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
  // This provides all boot's default to this factory, including the message converter
  configurer.configure(factory, connectionFactory);
  // You could still override some of Boot's default if necessary.
  return factory;
}
 
Example 39
Project: nifi-jms-jndi   File: CommonTest.java   Source Code and License 5 votes vote down vote up
static ConnectionFactory buildJmsJndiConnectionFactory() throws Exception {
    Properties env =new Properties();
    env.setProperty(Context.PROVIDER_URL, "vm://localhost?broker.persistent=false");
    env.setProperty(Context.INITIAL_CONTEXT_FACTORY,
                "org.apache.activemq.jndi.ActiveMQInitialContextFactory");
    
    InitialContext initialContext = new InitialContext(env);
    // Lookup ConnectionFactory.
    ConnectionFactory connectionFactory = (ConnectionFactory) initialContext.lookup("ConnectionFactory");  
    return connectionFactory;
   
}
 
Example 40
Project: nifi-jms-jndi   File: JNDIConnectionFactoryProvider.java   Source Code and License 5 votes vote down vote up
/**
 *
 * @return new instance of {@link ConnectionFactory}
 */
@Override
public ConnectionFactory getConnectionFactory() {
    if (this.configured) {
        return this.connectionFactory;
    }
    throw new IllegalStateException("ConnectionFactory can not be obtained unless "
            + "this ControllerService is configured. See onConfigure(ConfigurationContext) method.");
}