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

The following examples show how to use org.apache.activemq.artemis.jms.client.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: SecurityTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Login with valid user and password
 * But try send to address not authorised - Persistent
 * Should not allow and should throw exception
 */
@Test
public void testLoginValidUserAndPasswordButNotAuthorisedToSend() throws Exception {
   SimpleString queueName = SimpleString.toSimpleString("guest.cannot.send");
   if (getJmsServer().locateQueue(queueName) == null) {
      getJmsServer().createQueue(new QueueConfiguration(queueName).setRoutingType(RoutingType.ANYCAST));
   }
   ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
   Connection connection = connectionFactory.createConnection("guest", "guest");
   Session session = connection.createSession();
   Destination destination = session.createQueue(queueName.toString());
   MessageProducer messageProducer = session.createProducer(destination);
   try {
      messageProducer.send(session.createTextMessage("hello"));
      fail("JMSSecurityException expected as guest is not allowed to send");
   } catch (JMSSecurityException activeMQSecurityException) {
      //pass
   }
   connection.close();
}
 
Example 2
Source File: ConnectionTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testTwoConnectionsSameIDThroughCF() throws Exception {
   ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616?clientID=myid");

   conn = connectionFactory.createConnection();
   try {
      conn2 = connectionFactory.createConnection();
      Assert.fail("Exception expected");
   } catch (InvalidClientIDException expected) {
      // expected
   }


   Session session1 = conn.createSession();
   Session session2 = conn.createSession();

   session1.close();
   session2.close();
}
 
Example 3
Source File: ConnectionTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void testThroughNewConnectionFactory(ActiveMQConnectionFactory factory) throws Exception {
   Connection conn = factory.createConnection();
   conn.close();

   try (JMSContext ctx = factory.createContext()) {
      ctx.createProducer().send(ctx.createQueue("queue"), "Test");
   }

   try (JMSContext ctx = factory.createContext()) {
      Assert.assertNotNull(ctx.createConsumer(ctx.createQueue("queue")).receiveNoWait());
      Assert.assertNull(ctx.createConsumer(ctx.createQueue("queue")).receiveNoWait());
   }

   factory.close();
}
 
Example 4
Source File: EmbeddedJMSResourceTopicTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
   connectionFactory = new ActiveMQConnectionFactory(jmsServer.getVmURL());
   connection = connectionFactory.createConnection();
   session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   consumer = session.createConsumer(ActiveMQDestination.createDestination(TEST_DESTINATION_NAME, ActiveMQDestination.TYPE.TOPIC));
   connection.start();
}
 
Example 5
Source File: EmbeddedJMSResourceMultipleFileConfigurationTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
   connectionFactory = new ActiveMQConnectionFactory(jmsServer.getVmURL());
   connection = connectionFactory.createConnection();
   session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   consumer = (ActiveMQMessageConsumer) session.createConsumer(ActiveMQDestination.createDestination(TEST_TOPIC, ActiveMQDestination.TYPE.TOPIC));
   connection.start();
}
 
Example 6
Source File: EmbeddedJMSResource.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
void start() {
   connectionFactory = new ActiveMQConnectionFactory(getVmURL());
   try {
      connection = connectionFactory.createConnection();
      session = connection.createSession();
      producer = session.createProducer(null);
      connection.start();
   } catch (JMSException jmsEx) {
      throw new EmbeddedJMSResourceException("InternalClient creation failure", jmsEx);
   }
}
 
Example 7
Source File: HornetQProtocolManagerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/** This test will use an ArtemisConnectionFactory with clientProtocolManager=*/
@Test
public void testLegacy2() throws Exception {
   // WORKAROUND: the 2.0.0 broker introduced addressing change and the 2.2.0 broker added compatibility for old
   // client libraries relying on the legacy prefixes. The new client being used in this test needs prefix explicitly.
   Queue queue = new ActiveMQQueue("jms.queue.testQueue");
   ActiveMQConnectionFactory connectionFactory = ActiveMQJMSClient.createConnectionFactory("tcp://localhost:61616?protocolManagerFactoryStr=" + HornetQClientProtocolManagerFactory.class.getName(), "legacy");
   Connection connection = connectionFactory.createConnection();
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageProducer producer = session.createProducer(queue);

   TextMessage message = session.createTextMessage("Test");
   for (int i = 0; i < 5; i++) {
      message.setStringProperty(Message.HDR_DUPLICATE_DETECTION_ID.toString(), "duplicate");
      producer.send(message);
   }

   connection.start();
   MessageConsumer consumer = session.createConsumer(queue);
   TextMessage messageRec = (TextMessage) consumer.receive(5000);
   Assert.assertNotNull(messageRec);

   Assert.assertEquals("Test", messageRec.getText());
   Assert.assertNull(consumer.receiveNoWait());
   connection.close();
   connectionFactory.close();

}
 
Example 8
Source File: ActiveMQConnectionFactoryTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void sendObjectMessage(String qname, Serializable obj) throws Exception {
   ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://0");
   Connection connection = factory.createConnection();
   try {
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Queue q = session.createQueue(qname);
      MessageProducer producer = session.createProducer(q);
      ObjectMessage objMessage = session.createObjectMessage();
      objMessage.setObject(obj);
      producer.send(objMessage);
   } finally {
      connection.close();
   }
}
 
Example 9
Source File: ActiveMQConnectionFactoryTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testStaticConnectorLiveConstructor() throws Exception {
   ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, liveTC);
   assertFactoryParams(cf, new TransportConfiguration[]{liveTC}, null, null, ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, ActiveMQClient.DEFAULT_CONNECTION_TTL, ActiveMQClient.DEFAULT_CALL_TIMEOUT, ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE, ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, ActiveMQClient.DEFAULT_AUTO_GROUP, ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT, ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_RETRY_INTERVAL, ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS);
   Connection conn = cf.createConnection();

   conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

   testSettersThrowException(cf);

   cf.close();

   conn.close();
}
 
Example 10
Source File: PlainTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testPlain() throws Exception {
   ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory();
   Connection connection = cf.createConnection();
   Session session = connection.createSession();
   MessageProducer producer = session.createProducer(session.createQueue("queue"));
   producer.send(session.createTextMessage("hello"));
   connection.start();
   MessageConsumer consumer = session.createConsumer(session.createQueue("queue"));
   Assert.assertNotNull(consumer.receive(5000));
   connection.close();

}
 
Example 11
Source File: JMSReconnectTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testNoReconnectCloseAfterFailToReconnectWithTempQueue() throws Exception {
   ActiveMQConnectionFactory jbcf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY));

   jbcf.setReconnectAttempts(0);

   Connection conn = jbcf.createConnection();

   Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

   sess.createTemporaryQueue();

   Thread.sleep(2000);

   this.server.stop();

   this.server.start();

   sess.close();

   conn.close();
}
 
Example 12
Source File: TestDeadlockOnPurgePagingTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testDeadlockOnPurge() throws Exception {

   int NUMBER_OF_MESSAGES = 5000;
   clearDataRecreateServerDirs();

   Configuration config = createDefaultNettyConfig().setJournalSyncNonTransactional(false);

   server = createServer(true, config, TestDeadlockOnPurgePagingTest.PAGE_SIZE, TestDeadlockOnPurgePagingTest.PAGE_MAX);

   server.start();

   String queue = "purgeQueue";
   SimpleString ssQueue = new SimpleString(queue);
   server.addAddressInfo(new AddressInfo(ssQueue, RoutingType.ANYCAST));
   QueueImpl purgeQueue = (QueueImpl) server.createQueue(new QueueConfiguration(ssQueue).setRoutingType(RoutingType.ANYCAST).setMaxConsumers(1).setPurgeOnNoConsumers(true).setAutoCreateAddress(false));

   ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory();
   Connection connection = cf.createConnection();

   connection.start();

   Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
   javax.jms.Queue jmsQueue = session.createQueue(queue);

   MessageProducer producer = session.createProducer(jmsQueue);

   for (int i = 0; i < 100; i++) {
      producer.send(session.createTextMessage("hello" + i));
   }
   session.commit();

   Wait.assertEquals(0, purgeQueue::getMessageCount);

   Wait.assertEquals(0, purgeQueue.getPageSubscription().getPagingStore()::getAddressSize);

   MessageConsumer consumer = session.createConsumer(jmsQueue);

   for (int i = 0; i < NUMBER_OF_MESSAGES / 5; i++) {
      producer.send(session.createTextMessage("hello" + i));
      if (i == 10) {
         purgeQueue.getPageSubscription().getPagingStore().startPaging();
      }

      if (i > 10 && i % 10 == 0) {
         purgeQueue.getPageSubscription().getPagingStore().forceAnotherPage();
      }
   }
   session.commit();


   for (int i = 0; i < 100; i++) {
      Message message = consumer.receive(5000);
      Assert.assertNotNull(message);
   }
   session.commit();

   consumer.close();

   Wait.assertEquals(0L, purgeQueue::getMessageCount, 5000L, 10L);

   Wait.assertFalse(purgeQueue.getPageSubscription()::isPaging, 5000L, 10L);

   Wait.assertEquals(0L, purgeQueue.getPageSubscription().getPagingStore()::getAddressSize, 5000L, 10L);
}
 
Example 13
Source File: LoggingActiveMQServerPluginTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
protected Connection createActiveMQConnection() throws JMSException {
   ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");
   return (ActiveMQConnection) factory.createConnection();
}
 
Example 14
Source File: SimpleJNDIClientTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testRemoteCFWithTCPUserPassword() throws Exception {

   //setup user and role on broker
   ((ActiveMQJAASSecurityManager) liveService.getSecurityManager()).getConfiguration().addUser("myUser", "myPassword");
   ((ActiveMQJAASSecurityManager) liveService.getSecurityManager()).getConfiguration().addRole("myUser", "consumeCreateRole");
   Role consumeCreateRole = new Role("consumeCreateRole", false, true, true, true, true, true, true, true, true, true);
   Set<Role> consumerCreateRoles = new HashSet<>();
   consumerCreateRoles.add(consumeCreateRole);
   liveService.getSecurityRepository().addMatch("test.queue", consumerCreateRoles);

   Hashtable<String, String> props = new Hashtable<>();
   props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory");

   //user and password set on URL
   props.put("connectionFactory.myConnectionFactory", "tcp://127.0.0.1:61616?user=myUser&password=myPassword");
   Context ctx = new InitialContext(props);

   //create a connection factory
   ActiveMQConnectionFactory connectionFactory = (ActiveMQConnectionFactory) ctx.lookup("myConnectionFactory");
   Assert.assertEquals("ensure user is set", "myUser", connectionFactory.getUser());
   Assert.assertEquals("ensure password is set", "myPassword", connectionFactory.getPassword());

   //Connect to broker to verify credentials are used with connection
   Connection connection = connectionFactory.createConnection();
   connection.start();
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

   javax.jms.Queue queue = session.createQueue("test.queue");

   try {

      try {
         MessageProducer producer = session.createProducer(queue);
         producer.send(session.createTextMessage("test Msg"));
         Assert.fail("Sending message should throw a JMSSecurityException");
      } catch (JMSSecurityException e) {
         //expected
      }

      MessageConsumer consumer = session.createConsumer(queue);
   } finally {
      connection.close();
   }

}
 
Example 15
Source File: LVQTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testLastValueKeyUsingAddressQueueParameters() throws Exception {
   ActiveMQConnectionFactory fact = (ActiveMQConnectionFactory) getCF();

   //Set the consumer window size to 0 to not buffer any messages client side.
   fact.setConsumerWindowSize(0);
   Connection connection = fact.createConnection();

   try {

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

      Queue queue = session.createQueue("random?last-value-key=reuters_code");
      assertEquals("random", queue.getQueueName());

      ActiveMQDestination a = (ActiveMQDestination) queue;
      assertEquals("reuters_code", a.getQueueAttributes().getLastValueKey().toString());
      assertEquals("reuters_code", a.getQueueConfiguration().getLastValueKey().toString());

      MessageProducer producer = session.createProducer(queue);
      MessageConsumer consumer1 = session.createConsumer(queue);

      connection.start();
      for (int j = 0; j < 100; j++) {
         TextMessage message = session.createTextMessage();

         message.setText("Message" + j);
         message.setStringProperty("reuters_code", "key");
         producer.send(message);
      }

      //Last message only should go to the consumer
      TextMessage tm = (TextMessage) consumer1.receive(10000);

      assertNotNull(tm);

      assertEquals("Message99", tm.getText());

   } finally {
      connection.close();
   }
}
 
Example 16
Source File: LargeMessageOverBridgeTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
/**
 * The message won't be large to the client while it will be considered large through the bridge
 *
 * @throws Exception
 */
@Test
public void testSendLargeForBridge() throws Exception {
   createQueue(QUEUE);

   Queue queue = (Queue) context1.lookup("queue/" + QUEUE);

   ActiveMQConnectionFactory cf1 = ActiveMQJMSClient.createConnectionFactoryWithHA(JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY, generateInVMParams(1)));
   cf1.setMinLargeMessageSize(200 * 1024);

   Connection conn1 = cf1.createConnection();
   Session session1 = conn1.createSession(true, Session.SESSION_TRANSACTED);
   MessageProducer prod1 = session1.createProducer(queue);

   Connection conn2 = cf2.createConnection();
   Session session2 = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageConsumer cons2 = session2.createConsumer(queue);
   conn2.start();

   byte[] bytes = new byte[150 * 1024];

   for (int i = 0; i < bytes.length; i++) {
      bytes[i] = getSamplebyte(i);
   }

   for (int i = 0; i < 10; i++) {
      BytesMessage msg = session1.createBytesMessage();
      msg.writeBytes(bytes);
      prod1.send(msg);
   }

   session1.commit();

   for (int i = 0; i < 5; i++) {
      BytesMessage msg2 = (BytesMessage) cons2.receive(5000);
      assertNotNull(msg2);
      msg2.acknowledge();

      for (int j = 0; j < bytes.length; j++) {
         assertEquals("Position " + i, msg2.readByte(), bytes[j]);
      }
   }

   conn1.close();
   conn2.close();
}
 
Example 17
Source File: MessageGroup2Example.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
   final Map<String, String> messageReceiverMap = new ConcurrentHashMap<>();
   Connection connection = null;
   try {
      //Step 2. Perform a lookup on the queue
      Queue queue = ActiveMQJMSClient.createQueue("exampleQueue");

      //Step 3. Perform a lookup on the Connection Factory
      ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616?groupID=Group-0");

      //Step 4. Create a JMS Connection
      connection = cf.createConnection();

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

      //Step 6. Create 2 JMS Message Producers
      MessageProducer producer1 = session.createProducer(queue);

      MessageProducer producer2 = session.createProducer(queue);

      //Step 7. Create two consumers
      MessageConsumer consumer1 = session.createConsumer(queue);
      consumer1.setMessageListener(new SimpleMessageListener("consumer-1", messageReceiverMap));
      MessageConsumer consumer2 = session.createConsumer(queue);
      consumer2.setMessageListener(new SimpleMessageListener("consumer-2", messageReceiverMap));

      //Step 8. Create and send 10 text messages with each producer
      int msgCount = 10;
      for (int i = 0; i < msgCount; i++) {
         TextMessage m = session.createTextMessage("producer1 message " + i);
         producer1.send(m);
         System.out.println("Sent message: " + m.getText());
         TextMessage m2 = session.createTextMessage("producer2 message " + i);
         producer2.send(m2);
         System.out.println("Sent message: " + m2.getText());
      }

      System.out.println("all messages are sent");

      //Step 9. Start the connection
      connection.start();

      Thread.sleep(2000);

      //Step 10. check the group messages are received by only one consumer

      String trueReceiver = messageReceiverMap.get("producer1 message " + 0);
      for (int i = 0; i < msgCount; i++) {
         String receiver = messageReceiverMap.get("producer1 message " + i);
         if (!trueReceiver.equals(receiver)) {
            throw new IllegalStateException("Group message [producer1 message " + i + "] went to wrong receiver: " + receiver);
         }
         receiver = messageReceiverMap.get("producer2 message " + i);
         if (!trueReceiver.equals(receiver)) {
            throw new IllegalStateException("Group message [producer2 message " + i + "] went to wrong receiver: " + receiver);
         }
      }
   } finally {
      //Step 11. Be sure to close our JMS resources!
      if (connection != null) {
         connection.close();
      }
   }
}
 
Example 18
Source File: ActiveMQConnectionFactoryTest.java    From activemq-artemis with Apache License 2.0 3 votes vote down vote up
@Test
public void testStaticConnectorListConstructor() throws Exception {
   ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, liveTC);
   assertFactoryParams(cf, new TransportConfiguration[]{liveTC}, null, null, ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, ActiveMQClient.DEFAULT_CONNECTION_TTL, ActiveMQClient.DEFAULT_CALL_TIMEOUT, ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT, ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE, ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, ActiveMQClient.DEFAULT_AUTO_GROUP, ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT, ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_RETRY_INTERVAL, ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS);
   Connection conn = cf.createConnection();

   conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

   testSettersThrowException(cf);

   conn.close();

}
 
Example 19
Source File: RemoteConnectionStressTest.java    From activemq-artemis with Apache License 2.0 3 votes vote down vote up
@Test
public void testSimpleRemoteConnections() throws Exception {
   for (int i = 0; i < 1000; i++) {

      TransportConfiguration config = new TransportConfiguration(NETTY_CONNECTOR_FACTORY);
      ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, config);
      cf.setInitialConnectAttempts(10);
      cf.setRetryInterval(100);

      Connection conn = cf.createConnection();

      Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

      Queue queue = session.createQueue("SomeQueue");

      MessageProducer producer = session.createProducer(queue);

      TextMessage msg = session.createTextMessage();
      msg.setText("Message " + i);

      producer.send(msg);

      producer.close();
      session.close();
      conn.close();

      cf.close();

   }
}
 
Example 20
Source File: LVQTest.java    From activemq-artemis with Apache License 2.0 2 votes vote down vote up
@Test
public void testLastValueQueueTopicConsumerUsingAddressQueueParameters() throws Exception {
   ActiveMQConnectionFactory fact = (ActiveMQConnectionFactory) getCF();

   //Set the consumer window size to 0 to not buffer any messages client side.
   fact.setConsumerWindowSize(0);
   Connection connection = fact.createConnection();

   try {

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

      Topic topic = session.createTopic("topic?last-value=true");
      assertEquals("topic", topic.getTopicName());

      ActiveMQDestination a = (ActiveMQDestination) topic;
      assertTrue(a.getQueueAttributes().getLastValue());
      assertTrue(a.getQueueConfiguration().isLastValue());

      MessageProducer producer = session.createProducer(topic);
      MessageConsumer consumer1 = session.createConsumer(topic);
      MessageConsumer consumer2 = session.createConsumer(topic);

      connection.start();
      for (int j = 0; j < 100; j++) {
         TextMessage message = session.createTextMessage();

         message.setText("Message" + j);
         message.setStringProperty(Message.HDR_LAST_VALUE_NAME.toString(), "key");
         producer.send(message);
      }



      //Last message only should go to the consumer.
      TextMessage tm = (TextMessage) consumer1.receive(10000);

      assertNotNull(tm);

      assertEquals("Message99", tm.getText());

      //Last message only should go to the other consumer as well.
      TextMessage tm2 = (TextMessage) consumer2.receive(10000);

      assertNotNull(tm2);

      assertEquals("Message99", tm2.getText());

   } finally {
      connection.close();
   }
}