Java Code Examples for org.apache.activemq.ActiveMQConnectionFactory#createConnection()

The following examples show how to use org.apache.activemq.ActiveMQConnectionFactory#createConnection() . 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: MessageCompressionTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private void sendTestStreamMessage(ActiveMQConnectionFactory factory, String message) throws JMSException {
   ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageProducer producer = session.createProducer(queue);
   StreamMessage streamMessage = session.createStreamMessage();

   streamMessage.writeBoolean(true);
   streamMessage.writeByte((byte) 10);
   streamMessage.writeBytes(TEXT.getBytes());
   streamMessage.writeChar('A');
   streamMessage.writeDouble(55.3D);
   streamMessage.writeFloat(79.1F);
   streamMessage.writeInt(37);
   streamMessage.writeLong(56652L);
   streamMessage.writeObject(new String("VVVV"));
   streamMessage.writeShort((short) 333);
   streamMessage.writeString(TEXT);

   producer.send(streamMessage);
   connection.close();
}
 
Example 2
Source File: QueuePurgeTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Override
protected void setUp() throws Exception {
   setMaxTestTime(10 * 60 * 1000); // 10 mins
   setAutoFail(true);
   super.setUp();
   broker = new BrokerService();

   File testDataDir = new File("target/activemq-data/QueuePurgeTest");
   broker.setDataDirectoryFile(testDataDir);
   broker.setUseJmx(true);
   broker.setDeleteAllMessagesOnStartup(true);
   broker.getSystemUsage().getMemoryUsage().setLimit(1024L * 1024 * 64);
   KahaDBPersistenceAdapter persistenceAdapter = new KahaDBPersistenceAdapter();
   persistenceAdapter.setDirectory(new File(testDataDir, "kahadb"));
   broker.setPersistenceAdapter(persistenceAdapter);
   broker.addConnector("tcp://localhost:0");
   broker.start();
   factory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri().toString());
   connection = factory.createConnection();
   connection.start();
}
 
Example 3
Source File: FailoverTimeoutTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testTimoutDoesNotFailConnectionAttempts() throws Exception {
   server.stop();
   long timeout = 1000;

   long startTime = System.currentTimeMillis();

   ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + tcpUri + ")" +
                                                                   "?timeout=" + timeout + "&useExponentialBackOff=false" +
                                                                   "&maxReconnectAttempts=5" + "&initialReconnectDelay=1000");
   Connection connection = cf.createConnection();
   try {
      connection.start();
      fail("Should have failed to connect");
   } catch (JMSException ex) {
      LOG.info("Caught exception on call to start: {}", ex.getMessage());
   }

   long endTime = System.currentTimeMillis();
   long duration = endTime - startTime;

   LOG.info("Time spent waiting to connect: {} ms", duration);

   assertTrue(duration > 3000);
}
 
Example 4
Source File: QueueUtils.java    From karate with MIT License 5 votes vote down vote up
public static Connection getConnection() {
    try {
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");
        Connection connection = connectionFactory.createConnection();
        connection.start();
        return connection;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 5
Source File: ConnectorXBeanConfigTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public void testForceBrokerRestart() throws Exception {
   brokerService.stop();
   brokerService.waitUntilStopped();

   brokerService.start(true); // force restart
   brokerService.waitUntilStarted();

   LOG.info("try and connect to restarted broker");
   //send and receive a message from a restarted broker
   ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61636");
   Connection conn = factory.createConnection();
   Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
   conn.start();
   Destination dest = new ActiveMQQueue("test");
   MessageConsumer consumer = sess.createConsumer(dest);
   MessageProducer producer = sess.createProducer(dest);
   producer.send(sess.createTextMessage("test"));
   TextMessage msg = (TextMessage) consumer.receive(1000);
   assertEquals("test", msg.getText());
}
 
Example 6
Source File: MsgProducer.java    From uccx-sample-code with MIT License 5 votes vote down vote up
public void init(String brokerURL) throws Exception {
	// Create a ConnectionFactory
       connectionFactory = new ActiveMQConnectionFactory(brokerURL);
       // Create a Connection
       connection = connectionFactory.createConnection();
       connection.start();
}
 
Example 7
Source File: KahaDBSchedulerMissingJournalLogsTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void fillUpSomeLogFiles() throws Exception {
   ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost");
   Connection connection = cf.createConnection();
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   Queue queue = session.createQueue("test.queue");
   MessageProducer producer = session.createProducer(queue);
   connection.start();
   while (true) {
      scheduleRepeating(session, producer);
      if (schedulerStore.getJournal().getFileMap().size() == NUM_LOGS) {
         break;
      }
   }
   connection.close();
}
 
Example 8
Source File: MessageCompressionTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private ActiveMQTextMessage receiveTestMessage(ActiveMQConnectionFactory factory) throws JMSException {
   ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
   connection.start();
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageConsumer consumer = session.createConsumer(queue);
   ActiveMQTextMessage rc = (ActiveMQTextMessage) consumer.receive();
   connection.close();
   return rc;
}
 
Example 9
Source File: RequestReplyTempDestRemovalAdvisoryRaceTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void noConsumerAdvisory() throws JMSException {
   for (BrokerItem item : brokers.values()) {
      ActiveMQConnectionFactory brokerAFactory = new ActiveMQConnectionFactory(item.broker.getTransportConnectorByScheme("tcp").getName() + "?jms.watchTopicAdvisories=false");
      Connection connection = brokerAFactory.createConnection();
      connection.start();
      connection.createSession(false, Session.AUTO_ACKNOWLEDGE).createConsumer(AdvisorySupport.getNoTopicConsumersAdvisoryTopic(new ActiveMQTempTopic(">"))).setMessageListener(new MessageListener() {
         @Override
         public void onMessage(Message message) {
            sendsWithNoConsumers.incrementAndGet();
         }
      });
   }
}
 
Example 10
Source File: SimpleOpenWireTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testFailoverTransportReconnect() throws Exception {
   Connection exConn = null;

   try {
      String urlString = "failover:(tcp://" + OWHOST + ":" + OWPORT + ")";
      ActiveMQConnectionFactory exFact = new ActiveMQConnectionFactory(urlString);

      Queue queue = new ActiveMQQueue(durableQueueName);

      exConn = exFact.createConnection();
      exConn.start();

      Session session = exConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer messageProducer = session.createProducer(queue);
      messageProducer.send(session.createTextMessage("Test"));

      MessageConsumer consumer = session.createConsumer(queue);
      assertNotNull(consumer.receive(5000));

      server.stop();
      Thread.sleep(3000);

      server.start();
      server.waitForActivation(10, TimeUnit.SECONDS);

      messageProducer.send(session.createTextMessage("Test2"));
      assertNotNull(consumer.receive(5000));
   } finally {
      if (exConn != null) {
         exConn.close();
      }
   }
}
 
Example 11
Source File: AbstractElasticSearchActiveMQTest.java    From camunda-bpm-elasticsearch with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
  broker = createBroker();
  connector = new TransportConnector();
  connector.setUri(new URI("vm://localhost"));
  broker.addConnector(connector);
  broker.start();

  ActiveMQConnectionFactory connFactory =
      new ActiveMQConnectionFactory(connector.getConnectUri() + "?jms.prefetchPolicy.all=1");
  connection = connFactory.createConnection();
  connection.start();
}
 
Example 12
Source File: SimpleOpenWireTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testProducerFlowControl() throws Exception {
   ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(urlString);

   factory.setProducerWindowSize(1024 * 64);

   Connection connection = factory.createConnection();
   Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
   Queue queue = session.createQueue(queueName);
   MessageProducer producer = session.createProducer(queue);
   producer.send(session.createTextMessage("test"));

   connection.close();
}
 
Example 13
Source File: SimpleAuthenticationPluginTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public void testSecurityContextClearedOnPurge() throws Exception {

      connection.close();
      ActiveMQConnectionFactory tcpFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString());
      ActiveMQConnection conn = (ActiveMQConnection) tcpFactory.createConnection("user", "password");
      Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      conn.start();

      final int numDests = broker.getRegionBroker().getDestinations().length;
      for (int i = 0; i < 10; i++) {
         MessageProducer p = sess.createProducer(new ActiveMQQueue("USERS.PURGE." + i));
         p.close();
      }

      assertTrue("dests are purged", Wait.waitFor(new Wait.Condition() {
         @Override
         public boolean isSatisified() throws Exception {
            LOG.info("dests, orig: " + numDests + ", now: " + broker.getRegionBroker().getDestinations().length);
            return (numDests + 1) == broker.getRegionBroker().getDestinations().length;
         }
      }));

      // verify removed from connection security context
      TransportConnection brokerConnection = broker.getTransportConnectors().get(0).getConnections().get(0);
      TransportConnectionState transportConnectionState = brokerConnection.lookupConnectionState(conn.getConnectionInfo().getConnectionId());
      assertEquals("no destinations", 0, transportConnectionState.getContext().getSecurityContext().getAuthorizedWriteDests().size());
   }
 
Example 14
Source File: JMSTestBase.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
public void produceMsg(String text) throws Exception
{
  // Create a ConnectionFactory
  ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");

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

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

  // Create the destination (Topic or Queue)
  Destination destination = session.createQueue("TEST.FOO");

  // Create a MessageProducer from the Session to the Topic or Queue
  MessageProducer producer = session.createProducer(destination);
  producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

  // Create a messages
  TextMessage message = session.createTextMessage(text);
  producer.send(message);

  // Clean up
  session.close();
  connection.close();
}
 
Example 15
Source File: MessageCompressionTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void sendTestMessage(ActiveMQConnectionFactory factory, String message) throws JMSException {
   ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageProducer producer = session.createProducer(queue);
   producer.send(session.createTextMessage(message));
   connection.close();
}
 
Example 16
Source File: FailoverTimeoutTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testTimeout() throws Exception {

   long timeout = 1000;
   ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + tcpUri + ")?timeout=" + timeout + "&useExponentialBackOff=false");
   Connection connection = cf.createConnection();
   try {
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer producer = session.createProducer(session.createQueue(QUEUE_NAME));
      TextMessage message = session.createTextMessage("Test message");
      producer.send(message);

      server.stop();

      try {
         producer.send(message);
      } catch (JMSException jmse) {
         assertEquals("Failover timeout of " + timeout + " ms reached.", jmse.getMessage());
      }

      Configuration config = createConfig(0);
      server = new EmbeddedJMS().setConfiguration(config).setJmsConfiguration(new JMSConfigurationImpl());
      server.start();

      producer.send(message);

      server.stop();
      server = null;
   } finally {
      if (connection != null) {
         connection.close();
      }
   }
}
 
Example 17
Source File: VirtualTopicToFQQNOpenWireTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testAutoVirtualTopicWildcardFQQN() throws Exception {
   Connection connection = null;

   SimpleString topicA = new SimpleString("VirtualTopic.Orders.A");
   SimpleString topicB = new SimpleString("VirtualTopic.Orders.B");
   SimpleString topic = new SimpleString("VirtualTopic.Orders.>");

   this.server.getAddressSettingsRepository().getMatch("VirtualTopic.#").setAutoCreateQueues(true);
   this.server.getAddressSettingsRepository().getMatch("VirtualTopic.#").setAutoCreateAddresses(true);

   try {
      ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(urlString);
      activeMQConnectionFactory.setWatchTopicAdvisories(false);
      connection = activeMQConnectionFactory.createConnection();
      connection.start();

      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Destination destination = session.createTopic(topicA.toString() + "," + topicB.toString());

      MessageConsumer messageConsumerA = session.createConsumer(session.createQueue("Consumer.A." + topic.toString()));
     // MessageConsumer messageConsumerB = session.createConsumer(session.createQueue("Consumer.B." + topic.toString()));

      MessageProducer producer = session.createProducer(destination);
      TextMessage message = session.createTextMessage("This is a text message");
      producer.send(message);

      TextMessage messageReceivedA = (TextMessage) messageConsumerA.receive(2000);
      TextMessage messageReceivedB = (TextMessage) messageConsumerA.receive(2000);

      assertTrue((messageReceivedA != null && messageReceivedB != null));
      String text = messageReceivedA.getText();
      assertEquals("This is a text message", text);

      messageConsumerA.close();

   } finally {
      if (connection != null) {
         connection.close();
      }
   }
}
 
Example 18
Source File: FQQNOpenWireTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testVirtualTopicFQQNConsumerAutoCreateQAndAddress() throws Exception {
   Connection exConn = null;

   SimpleString topic = new SimpleString("VirtualTopic.Orders");
   SimpleString subscriptionQ = new SimpleString("Consumer.A");

   // defaults are false via test setUp
   this.server.getAddressSettingsRepository().getMatch("VirtualTopic.#").setAutoCreateQueues(true);
   this.server.getAddressSettingsRepository().getMatch("VirtualTopic.#").setAutoCreateAddresses(true);

   try {
      ActiveMQConnectionFactory exFact = new ActiveMQConnectionFactory();
      exFact.setWatchTopicAdvisories(false);
      exConn = exFact.createConnection();
      exConn.start();

      Session session = exConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Destination destination = session.createTopic(topic.toString());
      Destination destinationFQN = session.createQueue(CompositeAddress.toFullyQualified(topic, subscriptionQ).toString());

      MessageConsumer messageConsumerA = session.createConsumer(destinationFQN);
      MessageConsumer messageConsumerB = session.createConsumer(destinationFQN);

      MessageProducer producer = session.createProducer(destination);
      TextMessage message = session.createTextMessage("This is a text message");
      producer.send(message);

      // only one consumer should get the message
      TextMessage messageReceivedA = (TextMessage) messageConsumerA.receive(2000);
      TextMessage messageReceivedB = (TextMessage) messageConsumerB.receive(2000);

      assertTrue((messageReceivedA == null || messageReceivedB == null));
      String text = messageReceivedA != null ? messageReceivedA.getText() : messageReceivedB.getText();
      assertEquals("This is a text message", text);

      messageConsumerA.close();
      messageConsumerB.close();

   } finally {
      if (exConn != null) {
         exConn.close();
      }
   }
}
 
Example 19
Source File: PeerTransportTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
protected Connection createConnection(int i) throws JMSException {
   LOG.info("creating connection ....");
   ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory("peer://" + getClass().getName() + "/node" + i);
   return fac.createConnection();
}
 
Example 20
Source File: Retailer.java    From chipster with MIT License 4 votes vote down vote up
public void run() {
	ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
	try {
		Connection connection = connectionFactory.createConnection();
		
		// The Retailer's session is non-trasacted.
		Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		Destination vendorOrderQueue = session.createQueue("VendorOrderQueue");
		TemporaryQueue retailerConfirmQueue = session.createTemporaryQueue();
		
		MessageProducer producer = session.createProducer(vendorOrderQueue);
		MessageConsumer replyConsumer = session.createConsumer(retailerConfirmQueue);

		connection.start();

		for (int i = 0; i < 5; i++) {
			MapMessage message = session.createMapMessage();
			message.setString("Item", "Computer(s)");
			int quantity = (int)(Math.random() * 4) + 1;
			message.setInt("Quantity", quantity);
			message.setJMSReplyTo(retailerConfirmQueue);
			producer.send(message);
			System.out.println("Retailer: Ordered " + quantity + " computers.");
			
			MapMessage reply = (MapMessage) replyConsumer.receive();
			if (reply.getBoolean("OrderAccepted")) {
				System.out.println("Retailer: Order Filled");
			} else {
				System.out.println("Retailer: Order Not Filled");
			}
		}
		
		// Send a non-MapMessage to signal the end
		producer.send(session.createMessage());
		
		replyConsumer.close();
		connection.close();
		
	} catch (JMSException e) {
		e.printStackTrace();
	}
}