Java Code Examples for org.apache.activemq.ActiveMQConnectionFactory

The following are top voted examples for showing how to use org.apache.activemq.ActiveMQConnectionFactory. 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: beam   File: JmsIOTest.java   Source Code and License 22 votes vote down vote up
@Before
public void startBroker() throws Exception {
  broker = new BrokerService();
  broker.setUseJmx(false);
  broker.setPersistenceAdapter(new MemoryPersistenceAdapter());
  broker.addConnector(BROKER_URL);
  broker.setBrokerName("localhost");
  broker.setPopulateJMSXUserID(true);
  broker.setUseAuthenticatedPrincipalForJMSXUserID(true);

  // enable authentication
  List<AuthenticationUser> users = new ArrayList<>();
  // username and password to use to connect to the broker.
  // This user has users privilege (able to browse, consume, produce, list destinations)
  users.add(new AuthenticationUser(USERNAME, PASSWORD, "users"));
  SimpleAuthenticationPlugin plugin = new SimpleAuthenticationPlugin(users);
  BrokerPlugin[] plugins = new BrokerPlugin[]{ plugin };
  broker.setPlugins(plugins);

  broker.start();

  // create JMS connection factory
  connectionFactory = new ActiveMQConnectionFactory(BROKER_URL);
  connectionFactoryWithoutPrefetch =
      new ActiveMQConnectionFactory(BROKER_URL + "?jms.prefetchPolicy.all=0");
}
 
Example 2
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 3
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 4
Project: pooled-jms   File: PooledSessionExhaustionTest.java   Source Code and License 6 votes vote down vote up
@Before
@Override
public void setUp() throws Exception {
    super.setUp();

    brokerService = new BrokerService();
    brokerService.setPersistent(false);
    brokerService.setUseJmx(false);
    brokerService.setAdvisorySupport(false);
    brokerService.setSchedulerSupport(false);
    TransportConnector connector = brokerService.addConnector("tcp://localhost:0");
    brokerService.start();
    connectionUri = connector.getPublishableConnectString();
    factory = new ActiveMQConnectionFactory(connectionUri);
    pooledFactory = new JmsPoolConnectionFactory();
    pooledFactory.setConnectionFactory(factory);
    pooledFactory.setMaxConnections(1);
    pooledFactory.setBlockIfSessionPoolIsFull(false);
    pooledFactory.setMaximumActiveSessionPerConnection(1);
}
 
Example 5
Project: pooled-jms   File: PooledConnectionFactoryTest.java   Source Code and License 6 votes vote down vote up
@Test(timeout = 60000)
public void testMaxConnectionsAreCreated() throws Exception {

    ActiveMQConnectionFactory amq = new ActiveMQConnectionFactory(
        "vm://broker1?marshal=false&broker.persistent=false&broker.useJmx=false");
    JmsPoolConnectionFactory cf = new JmsPoolConnectionFactory();
    cf.setConnectionFactory(amq);
    cf.setMaxConnections(3);

    JmsPoolConnection conn1 = (JmsPoolConnection) cf.createConnection();
    JmsPoolConnection conn2 = (JmsPoolConnection) cf.createConnection();
    JmsPoolConnection conn3 = (JmsPoolConnection) cf.createConnection();

    assertNotSame(conn1.getConnection(), conn2.getConnection());
    assertNotSame(conn1.getConnection(), conn3.getConnection());
    assertNotSame(conn2.getConnection(), conn3.getConnection());

    assertEquals(3, cf.getNumConnections());

    cf.stop();
}
 
Example 6
Project: pooled-jms   File: PooledConnectionFactoryTest.java   Source Code and License 6 votes vote down vote up
@Test(timeout = 60000)
public void testConnectionsAreRotated() throws Exception {

    ActiveMQConnectionFactory amq = new ActiveMQConnectionFactory(
        "vm://broker1?marshal=false&broker.persistent=false&broker.useJmx=false");
    JmsPoolConnectionFactory cf = new JmsPoolConnectionFactory();
    cf.setConnectionFactory(amq);
    cf.setMaxConnections(10);

    Connection previous = null;

    // Front load the pool.
    for (int i = 0; i < 10; ++i) {
        cf.createConnection();
    }

    for (int i = 0; i < 100; ++i) {
        Connection current = ((JmsPoolConnection) cf.createConnection()).getConnection();
        assertNotSame(previous, current);
        previous = current;
    }

    cf.stop();
}
 
Example 7
Project: pooled-jms   File: PooledConnectionFactoryTest.java   Source Code and License 6 votes vote down vote up
@Test(timeout = 60000)
public void testConnectionsArePooled() throws Exception {

    ActiveMQConnectionFactory amq = new ActiveMQConnectionFactory("vm://broker1?marshal=false&broker.persistent=false");
    JmsPoolConnectionFactory cf = new JmsPoolConnectionFactory();
    cf.setConnectionFactory(amq);
    cf.setMaxConnections(1);

    JmsPoolConnection conn1 = (JmsPoolConnection) cf.createConnection();
    JmsPoolConnection conn2 = (JmsPoolConnection) cf.createConnection();
    JmsPoolConnection conn3 = (JmsPoolConnection) cf.createConnection();

    assertSame(conn1.getConnection(), conn2.getConnection());
    assertSame(conn1.getConnection(), conn3.getConnection());
    assertSame(conn2.getConnection(), conn3.getConnection());

    assertEquals(1, cf.getNumConnections());

    cf.stop();
}
 
Example 8
Project: pooled-jms   File: PooledSessionNoPublisherCachingTest.java   Source Code and License 6 votes vote down vote up
@Override
@Before
public void setUp() throws Exception {
    super.setUp();

    brokerService = new BrokerService();
    brokerService.setPersistent(false);
    brokerService.setUseJmx(false);
    brokerService.setAdvisorySupport(false);
    brokerService.setSchedulerSupport(false);
    TransportConnector connector = brokerService.addConnector("tcp://localhost:0");
    brokerService.start();

    connectionUri = connector.getPublishableConnectString();
    factory = new ActiveMQConnectionFactory(connectionUri);
    pooledFactory = new JmsPoolConnectionFactory();
    pooledFactory.setConnectionFactory(factory);
    pooledFactory.setMaxConnections(1);
    pooledFactory.setBlockIfSessionPoolIsFull(false);
    pooledFactory.setUseAnonymousProducers(false);
}
 
Example 9
Project: pooled-jms   File: PooledSessionTest.java   Source Code and License 6 votes vote down vote up
@Override
@Before
public void setUp() throws Exception {
    super.setUp();

    brokerService = new BrokerService();
    brokerService.setPersistent(false);
    brokerService.setUseJmx(true);
    brokerService.getManagementContext().setCreateConnector(false);
    brokerService.setAdvisorySupport(false);
    brokerService.setSchedulerSupport(false);
    TransportConnector connector = brokerService.addConnector("tcp://localhost:0");
    brokerService.start();

    connectionUri = connector.getPublishableConnectString();
    factory = new ActiveMQConnectionFactory(connectionUri);
    pooledFactory = new JmsPoolConnectionFactory();
    pooledFactory.setConnectionFactory(factory);
    pooledFactory.setMaxConnections(1);
    pooledFactory.setBlockIfSessionPoolIsFull(false);
}
 
Example 10
Project: pooled-jms   File: PooledSessionExhaustionBlockTimeoutTest.java   Source Code and License 6 votes vote down vote up
@Override
public void setUp() throws Exception {
    super.setUp();

    brokerService = new BrokerService();
    brokerService.setPersistent(false);
    brokerService.setUseJmx(false);
    brokerService.setSchedulerSupport(false);
    brokerService.setAdvisorySupport(false);
    TransportConnector connector = brokerService.addConnector("tcp://localhost:0");
    brokerService.start();

    connectionUri = connector.getPublishableConnectString();
    factory = new ActiveMQConnectionFactory(connectionUri);
    pooledFactory = new JmsPoolConnectionFactory();
    pooledFactory.setConnectionFactory(factory);
    pooledFactory.setMaxConnections(1);
    pooledFactory.setBlockIfSessionPoolIsFull(true);
    pooledFactory.setBlockIfSessionPoolIsFullTimeout(500);
    pooledFactory.setMaximumActiveSessionPerConnection(1);
}
 
Example 11
Project: pooled-jms   File: PooledConnectionFactoryWithTemporaryDestinationsTest.java   Source Code and License 6 votes vote down vote up
@Override
@Before
public void setUp() throws Exception {
    super.setUp();

    brokerService = new BrokerService();
    brokerService.setUseJmx(false);
    brokerService.setPersistent(false);
    brokerService.setSchedulerSupport(false);
    brokerService.setAdvisorySupport(false);
    TransportConnector connector = brokerService.addConnector("tcp://localhost:0");
    brokerService.start();
    factory = new ActiveMQConnectionFactory("mock:" + connector.getConnectUri() + "?closeAsync=false");
    pooledFactory = new JmsPoolConnectionFactory();
    pooledFactory.setConnectionFactory(factory);
}
 
Example 12
Project: pooled-jms   File: PooledConnectionSecurityExceptionTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testFailoverWithInvalidCredentialsCanConnect() throws JMSException {

    ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(
        "failover:(" + connectionURI + ")");

    pooledConnFact = new JmsPoolConnectionFactory();
    pooledConnFact.setConnectionFactory(cf);
    pooledConnFact.setMaxConnections(1);

    Connection connection = pooledConnFact.createConnection("invalid", "credentials");

    try {
        connection.start();
        fail("Should fail to connect");
    } catch (JMSSecurityException ex) {
        LOG.info("Caught expected security error");
    }

    connection = pooledConnFact.createConnection("system", "manager");
    connection.start();

    LOG.info("Successfully create new connection.");

    connection.close();
}
 
Example 13
Project: pooled-jms   File: PooledConnectionExpiryEvictsFromPoolTest.java   Source Code and License 6 votes vote down vote up
@Override
@Before
public void setUp() throws Exception {
    super.setUp();

    brokerService = new BrokerService();
    brokerService.setUseJmx(false);
    brokerService.setPersistent(false);
    brokerService.setSchedulerSupport(false);
    brokerService.setAdvisorySupport(false);
    TransportConnector connector = brokerService.addConnector("tcp://localhost:0");
    brokerService.start();
    factory = new ActiveMQConnectionFactory("mock:" + connector.getConnectUri());
    pooledFactory = new JmsPoolConnectionFactory();
    pooledFactory.setConnectionFactory(factory);
    pooledFactory.setMaxConnections(1);
}
 
Example 14
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 15
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 16
Project: jeta   File: ServerSide.java   Source Code and License 6 votes vote down vote up
public ServerSide() {
    try {
        //This message broker is embedded
        BrokerService broker = new BrokerService();
        broker.setPersistent(false);
        broker.setUseJmx(false);
        broker.addConnector(messageBrokerUrl);
        broker.start();
    } catch (Exception e) {
        //Handle the exception appropriately
    }
    QueueConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
    //Delegating the handling of messages to another class, instantiate it before setting up JMS so it
    //is ready to handle messages
    this.messageProtocol = new MessageProtocol();
    this.setupMessageQueueConsumer(connectionFactory);
}
 
Example 17
Project: jeta   File: JmsClient.java   Source Code and License 6 votes vote down vote up
public JmsClient() {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
    try {
        connection = connectionFactory.createConnection();
        connection.start();
        session = connection.createSession(transacted, ackMode);
        Destination adminQueue = session.createQueue(clientQueueName);
 
        //Setup a message producer to send message to the queue the server is consuming from
        this.producer = session.createProducer(adminQueue);
        this.producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
 
        //Create a temporary queue that this client will listen for responses on then create a consumer
        //that consumes message from this temporary queue...for a real application a client should reuse
        //the same temp queue for each message to the server...one temp queue per client
        tempDest = session.createTemporaryQueue();
        MessageConsumer responseConsumer = session.createConsumer(tempDest);
 
        //This class will handle the messages to the temp queue as well
        responseConsumer.setMessageListener(this);
    } catch (JMSException e) {
        //Handle the exception appropriately
    }
    acks = 0;
}
 
Example 18
Project: connect-sample-apps   File: Publisher.java   Source Code and License 6 votes vote down vote up
public void create(String clientId, String topicName) throws JMSException {
      this.clientId = clientId;

String brokerUrl = System.getProperty("activemq.brokerurl", ActiveMQConnection.DEFAULT_BROKER_URL);

log.info("Got brokerurl: " + brokerUrl);

// create a Connection Factory
      ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl);

      // create a Connection
      connection = connectionFactory.createConnection();
      connection.setClientID(clientId);

      // create a Session
      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

      // create the Topic to which messages will be sent
      Topic topic = session.createTopic(topicName);

      // create a MessageProducer for sending messages
      messageProducer = session.createProducer(topic);
  }
 
Example 19
Project: axon-jms   File: JmsIntegrationTest.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  embeddedBroker.start();
  out = new SimpleEventBus();
  in = new SimpleEventBus();

  ActiveMQConnectionFactory connectionFactory = embeddedBroker.createConnectionFactory();
  topicConnection = connectionFactory.createTopicConnection();
  topicConnection.start();
  TopicSession topicSession = topicConnection.createTopicSession(
      true, Session.SESSION_TRANSACTED);
  TemporaryTopic topic = topicSession.createTemporaryTopic();
  consumer = topicSession.createConsumer(topic);

  publisher = new JmsPublisher(out);
  publisher.setTopic(topic);
  publisher.setConnectionFactory(connectionFactory);
  publisher.postConstruct();
  publisher.start();

  jmsMessageSource = new JmsMessageSource(this.consumer,
      new DefaultJmsMessageConverter(new XStreamSerializer()));
  jmsMessageSource.subscribe(in::publish);
}
 
Example 20
Project: smockin   File: MockedJmsServerEngine.java   Source Code and License 6 votes vote down vote up
void initServerConfig(final MockedServerConfigDTO config) throws MockServerException {
    logger.debug("initServerConfig called");

    try {

        // Configure the MQ broker
        synchronized (monitor) {
            broker = new BrokerService();
            broker.setPersistent(false);
            broker.setUseJmx(false);
            broker.addConnector(config.getNativeProperties().get("BROKER_URL") + config.getPort());
        }

        connectionFactory = new ActiveMQConnectionFactory(config.getNativeProperties().get("BROKER_URL") + config.getPort());
        connectionFactory.setMaxThreadPoolSize(config.getMaxThreads());
        connectionFactory.setRejectedTaskHandler(new ThreadPoolExecutor.CallerRunsPolicy());

    } catch (Throwable ex) {
        throw new MockServerException(ex);
    }

}
 
Example 21
Project: connectors   File: AbstractActiveMQConnector.java   Source Code and License 6 votes vote down vote up
@Override
public String createEndpointUri(String scheme, Map<String, String> options) throws URISyntaxException {

    // FIXME: SpringBootAutoConfigurationMojo MUST not ignore connectorOptions
    brokerUrl = options.remove("brokerUrl");
    username = options.remove("username");
    password = options.remove("password");

    // validate url
    if (ObjectHelper.isEmpty(this.brokerUrl)) {
        throw new IllegalArgumentException("Missing required property brokerUrl");
    }

    // create ActiveMQ Connection Factory
    ActiveMQConnectionFactory connectionFactory = ObjectHelper.isEmpty(username) ?
            new ActiveMQConnectionFactory(this.brokerUrl) : new ActiveMQConnectionFactory(username, password, this.brokerUrl);
    Sjms2Component delegate = getCamelContext().getComponent(getComponentName() + "-component", Sjms2Component.class);
    delegate.setConnectionFactory(connectionFactory);

    return super.createEndpointUri(scheme, options);
}
 
Example 22
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 23
Project: oneops   File: InstanceManager.java   Source Code and License 6 votes vote down vote up
private SensorListenerContainer buildOpsMQListenerContainer(String host) {
	
	int port = Integer.valueOf(System.getProperty(OPSMQ_PORT_PARAM, "61616"));
	String opsmqPass = System.getenv(OPSMQ_PASS_ENV_VAR);
	if (opsmqPass == null) {
		throw new RuntimeException(OPSMQ_PASS_ENV_VAR + " env var needs to be set!");
	}

	ActiveMQConnectionFactory opsmqConnectionFactory = new ActiveMQConnectionFactory();
	opsmqConnectionFactory.setBrokerURL(opsMQURI.build(host, port));
	opsmqConnectionFactory.setUserName(OPSMQ_USER);
	opsmqConnectionFactory.setPassword(opsmqPass);
	
	SensorListenerContainer listenerContainer = new SensorListenerContainer();
	
	listenerContainer.setConnectionFactory(opsmqConnectionFactory);
	listenerContainer.setMaxConcurrentConsumers(Integer.valueOf(System.getProperty(OPSMQ_MAX_SESSIONS, "24")));
	listenerContainer.setConcurrentConsumers(Integer.valueOf(System.getProperty(OPSMQ_MAX_SESSIONS, "24")));
	listenerContainer.setSessionAcknowledgeMode(Session.AUTO_ACKNOWLEDGE);
	listenerContainer.setMessageListener(this.sensorListener);
	
	return listenerContainer;
	
}
 
Example 24
Project: oneops   File: OpsEventPublisherTest.java   Source Code and License 6 votes vote down vote up
@Test(expectedExceptions=JMSException.class)
/** negative test that JMSException happens if bad factory*/
public void initFailTest() throws Exception {
	OpsEventPublisher oep = new OpsEventPublisher();

	ActiveMQConnectionFactory factoryMock = mock(ActiveMQConnectionFactory.class);
	try {
		when(factoryMock.createConnection()).thenThrow(
				new JMSException("from mock"));

		oep.setConnectionFactory(factoryMock);
		oep.setPersistent(false);
		oep.setQueue("mock-queue");
		oep.setTimeToLive(123L);

		oep.init();
	} catch (JMSException e) {
		throw e; //as expected, we are here
	}

}
 
Example 25
Project: java   File: DeliveryCheckSpout.java   Source Code and License 6 votes vote down vote up
private void setConnection(String clientid) {
  ConnectionFactory connectionFactory =
      new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_BROKER_URL);

  try {
    connection = connectionFactory.createConnection();
    if (clientid != null)
      connection.setClientID(clientid);
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);



  } catch (Exception e) {
    e.printStackTrace();
  }
}
 
Example 26
Project: flume-examples   File: InjectActiveMQMessage.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");

    Connection connection = factory.createConnection();
    connection.start();

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue destination = session.createQueue("business-events");
    MessageProducer producer = session.createProducer(destination);

    try {
        for (int i = 0; i < 10; ++i) {
            TextMessage message = session.createTextMessage();
            message.setText("Message-" + i);
            producer.send(message);
        }
    } finally {
        producer.close();
    }

    connection.close();
}
 
Example 27
Project: flume-examples   File: ConsumeActiveMQMessage.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");

    Connection connection = factory.createConnection();
    connection.start();

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue destination = session.createQueue("business-events");
    MessageConsumer consumer = session.createConsumer(destination);

    try {
        for (int i = 0; i < 10; ++i) {
            TextMessage message = (TextMessage) consumer.receive();
            System.out.println(message.getText());
        }
    } finally {
        consumer.close();
    }

    connection.close();
}
 
Example 28
Project: beyondj   File: DetectingGatewayTest.java   Source Code and License 6 votes vote down vote up
@Test
public void canDetectTheOpenwireProtocol() throws Exception {

    DetectingGateway gateway = createGateway();

    gateway.init();
    String url = "tcp://localhost:" + gateway.getBoundPort()+"?wireFormat.host=broker0";
    final ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(url);
    Connection connection = factory.createConnection();
    connection.start();

    assertConnectedToBroker(0);
    assertEquals(1, gateway.getSuccessfulConnectionAttempts());
    assertEquals(1, gateway.getConnectedClients().length);

    connection.close();
}
 
Example 29
Project: beyondj   File: DetectingGatewayTest.java   Source Code and License 6 votes vote down vote up
@Test
public void canDetectTheOpenwireSslProtocol() throws Exception {

    System.setProperty("javax.net.ssl.trustStore", new File(basedir(), "src/test/resources/client.ks").getCanonicalPath());
    System.setProperty("javax.net.ssl.trustStorePassword", "password");
    System.setProperty("javax.net.ssl.trustStoreType", "jks");

    DetectingGateway gateway = createGateway();

    String url = "ssl://localhost:" + gateway.getBoundPort()+"?wireFormat.host=broker0";
    final ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(url);
    Connection connection = factory.createConnection();
    connection.start();

    assertEquals(1, gateway.getSuccessfulConnectionAttempts());
    assertEquals(1, gateway.getConnectedClients().length);

    assertConnectedToBroker(0);
    connection.close();

}
 
Example 30
Project: JSearcher   File: Receiver.java   Source Code and License 6 votes vote down vote up
public Receiver(String queue_name) {	
	connectionFactory = new ActiveMQConnectionFactory(
               ActiveMQConnection.DEFAULT_USER,
               ActiveMQConnection.DEFAULT_PASSWORD,
               "tcp://localhost:61616");
	try {
		connection = connectionFactory.createConnection();
        connection.start();
        session = connection.createSession(Boolean.FALSE,
                Session.AUTO_ACKNOWLEDGE);
        destination = session.createQueue(queue_name);
        consumer = session.createConsumer(destination);

	} catch(JMSException je) {
		je.printStackTrace();
	}
}
 
Example 31
Project: OPCUA-AMQ   File: AMQBus.java   Source Code and License 6 votes vote down vote up
public void setupBus(MessageListener msgLis) {
	try {
		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
				ActiveMQConnectionFactory.DEFAULT_BROKER_BIND_URL);
		connection = connectionFactory.createConnection();

		session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		destination = session.createTopic("OPCUAMilo");
		//Setup producer
		producer = session.createProducer(destination);
		
		//setup consumer
		consumer = session.createConsumer(destination);
		connection.start();
		consumer.setMessageListener(msgLis);
		
	} catch (JMSException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

}
 
Example 32
Project: Unicorn   File: JMSProvider.java   Source Code and License 6 votes vote down vote up
public static void receiveMessage(final MessageListener listener, final String brokerHost, final String brokerPort, final String topic) throws JMSException {
	// Create a ConnectionFactory
	final ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(String.format("tcp://%s:%s", brokerHost, brokerPort));

	// Create a Connection
	final Connection connection = connectionFactory.createConnection();
	connection.start();

	// Create a Session
	final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

	// Create the destination (Topic or Queue)
	final Destination destination = session.createQueue(topic);

	// register MessageListener
	final MessageConsumer consumer = session.createConsumer(destination);
	consumer.setMessageListener(listener);
}
 
Example 33
Project: Unicorn   File: JMSProvider.java   Source Code and License 6 votes vote down vote up
public static String receiveMessage(MessageListener listener, String brokerHost, String brokerPort, String topic) throws JMSException {
	// Create a ConnectionFactory
	ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(String.format("tcp://%s:%s", brokerHost, brokerPort));

	// Create a Connection
	Connection connection = connectionFactory.createConnection();
	connection.start();

	// Create a Session
	Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

	// Create the destination (Topic or Queue)
	Destination destination = session.createQueue(topic);

	// register MessageListener
	MessageConsumer consumer = session.createConsumer(destination);
	Message message = consumer.receive();
	if (message instanceof TextMessage) {
		return ((TextMessage) message).getText();
	} else {
		return null;
	}
}
 
Example 34
Project: Camel   File: LoanBrokerQueueTest.java   Source Code and License 6 votes vote down vote up
@Before
public void startServices() throws Exception {
    deleteDirectory("activemq-data");

    camelContext = new DefaultCamelContext();
    broker = new JmsBroker("vm://localhost");
    broker.start();
    
    // Set up the ActiveMQ JMS Components
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");

    // Note we can explicitly name the component
    camelContext.addComponent("jms", JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));

    camelContext.addRoutes(new LoanBrokerRoute());
   
    template = camelContext.createProducerTemplate();
    camelContext.start();
}
 
Example 35
Project: bahir-flink   File: AMQSinkTest.java   Source Code and License 6 votes vote down vote up
@Before
public void before() throws Exception {
    connectionFactory = mock(ActiveMQConnectionFactory.class);
    producer = mock(MessageProducer.class);
    session = mock(Session.class);
    connection = mock(Connection.class);
    destination = mock(Destination.class);
    message = mock(BytesMessage.class);

    when(connectionFactory.createConnection()).thenReturn(connection);
    when(connection.createSession(anyBoolean(), anyInt())).thenReturn(session);
    when(session.createProducer(null)).thenReturn(producer);
    when(session.createBytesMessage()).thenReturn(message);
    serializationSchema = new SimpleStringSchema();

    AMQSinkConfig<String> config = new AMQSinkConfig.AMQSinkConfigBuilder<String>()
        .setConnectionFactory(connectionFactory)
        .setDestinationName(DESTINATION_NAME)
        .setSerializationSchema(serializationSchema)
        .build();
    amqSink = new AMQSink<>(config);
    amqSink.open(new Configuration());
}
 
Example 36
Project: Unicorn   File: JMSProvider.java   Source Code and License 6 votes vote down vote up
public static void destroyMessageQueue(String brokerHost, String brokerPort, String topic) throws JMSException {
	// Create a ConnectionFactory
	ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(String.format("tcp://%s:%s", brokerHost, brokerPort));

	// Create a Connection
	Connection connection = connectionFactory.createConnection();
	connection.start();

	// Create a Session
	Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

	// Create the destination (Topic or Queue)
	Destination destination = session.createQueue(topic);
	session.close();

	// Destroy Empty Queue
	((ActiveMQConnection) connection).destroyDestination((ActiveMQDestination) destination);
	connection.close();
}
 
Example 37
Project: bahir-flink   File: ActiveMQConnectorITCase.java   Source Code and License 6 votes vote down vote up
@Test
public void amqTopologyWithTopic() throws Exception {
    StreamExecutionEnvironment env = createExecutionEnvironment();
    AMQSinkConfig<String> sinkConfig = new AMQSinkConfig.AMQSinkConfigBuilder<String>()
        .setConnectionFactory(createConnectionFactory())
        .setDestinationName(TOPIC_NAME)
        .setSerializationSchema(new SimpleStringSchema())
        .setDestinationType(DestinationType.TOPIC)
        .build();
    createProducerTopology(env, sinkConfig);

    ActiveMQConnectionFactory sourceConnectionFactory = createConnectionFactory();
    AMQSourceConfig<String> sourceConfig = new AMQSourceConfig.AMQSourceConfigBuilder<String>()
        .setConnectionFactory(sourceConnectionFactory)
        .setDestinationName(TOPIC_NAME)
        .setDeserializationSchema(new SimpleStringSchema())
        .setDestinationType(DestinationType.TOPIC)
        .build();
    createConsumerTopology(env, sourceConfig);

    tryExecute(env, "AMQTest");
}
 
Example 38
Project: osgi-dynamic-service   File: ActiveMQServiceManager.java   Source Code and License 6 votes vote down vote up
synchronized void checkConnection() {
    log.info("Checking the status of the ActiveMQ Broker: {}", brokerUrl);
    Connection connection = null;
    try {
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");
        connection = factory.createConnection(userName, password);
        log.info( "Connection succeeded");
        registerService();
    } catch (Exception ex) {
        log.warn( "Connection failed");
        unregisterService();
    } finally {
        if (null != connection) {
            try {
                connection.close();
            } catch (JMSException jmxEx) {
                log.warn( "Closing connection failed");
            } finally {
                connection = null;
            }
        }
    }
}
 
Example 39
Project: osgi-dynamic-service   File: ActiveMQServiceManager.java   Source Code and License 6 votes vote down vote up
synchronized void checkConnection() {
    log.info("Checking the status of the ActiveMQ Broker: {}", brokerUrl);
    Connection connection = null;
    try {
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");
        connection = factory.createConnection(userName, password);
        log.info( "Connection succeeded");
        registerService();
    } catch (Exception ex) {
        log.warn( "Connection failed");
        unregisterService();
    } finally {
        if (null != connection) {
            try {
                connection.close();
            } catch (JMSException jmxEx) {
                log.warn( "Closing connection failed");
            } finally {
                connection = null;
            }
        }
    }
}
 
Example 40
Project: Camel   File: SjmsBatchEndpointTest.java   Source Code and License 6 votes vote down vote up
@Override
protected CamelContext createCamelContext() throws Exception {
    SimpleRegistry registry = new SimpleRegistry();
    registry.put("aggStrategy", AggregationStrategies.groupedExchange());

    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
    connectionFactory.setBrokerURL(broker.getTcpConnectorUri());

    SjmsComponent sjmsComponent = new SjmsComponent();
    sjmsComponent.setConnectionFactory(connectionFactory);

    SjmsBatchComponent sjmsBatchComponent = new SjmsBatchComponent();
    sjmsBatchComponent.setConnectionFactory(connectionFactory);

    CamelContext context = new DefaultCamelContext(registry);
    context.addComponent("sjms-batch", sjmsBatchComponent);
    context.addComponent("sjms", sjmsComponent);

    return context;
}