org.apache.activemq.artemis.api.core.client.ClientSessionFactory Java Examples

The following examples show how to use org.apache.activemq.artemis.api.core.client.ClientSessionFactory. 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: ArtemisBenchmarkConsumer.java    From openmessaging-benchmark with Apache License 2.0 6 votes vote down vote up
public ArtemisBenchmarkConsumer(String topic, String queueName, ClientSessionFactory sessionFactory, ConsumerCallback callback)
        throws ActiveMQException {
    session = sessionFactory.createSession();
    session.createQueue(SimpleString.toSimpleString(topic), RoutingType.MULTICAST,
            SimpleString.toSimpleString(queueName), true /* durable */);
    consumer = session.createConsumer(queueName);
    consumer.setMessageHandler(message -> {
        byte[] payload = new byte[message.getBodyBuffer().readableBytes()];
        message.getBodyBuffer().readBytes(payload);
        callback.messageReceived(payload, message.getTimestamp());
        try {
            message.acknowledge();
        } catch (ActiveMQException e) {
            log.warn("Failed to acknowledge message", e);
        }
    });
    
    session.start();
}
 
Example #2
Source File: ShutdownServerTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testShutdownServer() throws Throwable {
   ClientSessionFactory sf = createSessionFactory(locator);

   ClientSession session = sf.createSession(false, true, true, false);

   session.createQueue(new QueueConfiguration(QUEUE));

   ClientConsumer consumer = session.createConsumer(QUEUE);

   ClientProducer producer = session.createProducer(QUEUE);
   ClientMessage message = session.createMessage(Message.TEXT_TYPE, true, 0, System.currentTimeMillis(), (byte) 4);
   message.getBodyBuffer().writeString("hi");
   message.putStringProperty("hello", "elo");
   producer.send(message);

   ActiveMQServerImpl impl = (ActiveMQServerImpl) server;
   JournalStorageManager journal = (JournalStorageManager) impl.getStorageManager();
   JDBCJournalImpl journalimpl = (JDBCJournalImpl) journal.getMessageJournal();
   journalimpl.handleException(null, new Exception("failure"));

   Wait.waitFor(() -> !server.isStarted());

   Assert.assertFalse(server.isStarted());

}
 
Example #3
Source File: ConsumerWindowSizeTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testConsumerWindowSizeAddressSettingsWildCard() throws Exception {
   ActiveMQServer messagingService = createServer(false, isNetty());

   final int defaultConsumerWindowSize = 1024 * 5;
   final AddressSettings settings = new AddressSettings();
   settings.setDefaultConsumerWindowSize(defaultConsumerWindowSize);
   messagingService.getConfiguration()
      .getAddressesSettings().put("#", settings);

   messagingService.start();
   messagingService.createQueue(new QueueConfiguration(queueA).setRoutingType(RoutingType.ANYCAST));

   ClientSessionFactory cf = createSessionFactory(locator);
   ClientSession session = cf.createSession(false, true, true);
   ClientConsumerImpl consumer = (ClientConsumerImpl) session.createConsumer(queueA);
   ClientConsumerImpl consumer2 = (ClientConsumerImpl) session.createConsumer(queueA);

   session.start();

   assertEquals(defaultConsumerWindowSize / 2, consumer.getClientWindowSize());
   assertEquals(defaultConsumerWindowSize / 2, consumer2.getClientWindowSize());
}
 
Example #4
Source File: AmqpBridgeClusterRedistributionTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendMessageToBroker0GetFromBroker1() throws Exception {
   try (ServerLocator locator = ActiveMQClient.createServerLocator(getServer1URL()); ClientSessionFactory sessionFactory = locator.createSessionFactory(); ClientSession session = sessionFactory.createSession(); ClientConsumer consumer = session.createConsumer(notificationsQueue)) {

      session.start();

      sendMessages("uswest.Provider.AMC.Agent.DIVERTED.CustomNotification", 1, RoutingType.ANYCAST, true);

      AMQPLargeMessagesTestUtil.validateAllTemporaryBuffers(server0);
      AMQPLargeMessagesTestUtil.validateAllTemporaryBuffers(server1);

      ClientMessage message = consumer.receive(5000);
      assertNotNull(message);

      message = consumer.receiveImmediate();
      assertNull(message);
   }

   AMQPLargeMessagesTestUtil.validateAllTemporaryBuffers(server0);
   AMQPLargeMessagesTestUtil.validateAllTemporaryBuffers(server1);
}
 
Example #5
Source File: InterceptorTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testClientOutgoingInterceptorRejectPacketOnBlockingSend() throws Exception {
   // must make the call block to exercise the right logic
   locator.setBlockOnNonDurableSend(true);
   ClientSessionFactory sf = createSessionFactory(locator);

   MyOutgoingInterceptor4 interceptor = new MyOutgoingInterceptor4();

   sf.getServerLocator().addOutgoingInterceptor(interceptor);

   ClientSession session = sf.createSession(false, true, true, true);

   session.createQueue(new QueueConfiguration(QUEUE).setDurable(false));

   ClientProducer producer = session.createProducer(QUEUE);

   ClientMessage message = session.createMessage(false);

   try {
      producer.send(message);
      Assert.fail();
   } catch (ActiveMQException e) {
      // expected exception
      Assert.assertTrue(e.getType().getCode() == ActiveMQExceptionType.INTERCEPTOR_REJECTED_PACKET.getCode());
   }
}
 
Example #6
Source File: LatencyTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
@BMRules(
   rules = {@BMRule(
      name = "trace ClientBootstrap.connect",
      targetClass = "org.jboss.netty.bootstrap.ClientBootstrap",
      targetMethod = "connect",
      targetLocation = "ENTRY",
      action = "org.apache.activemq.artemis.tests.extras.byteman.LatencyTest.debugLog(\"netty connecting\")"), @BMRule(
      name = "sleep OioWorker.run",
      targetClass = "org.jboss.netty.channel.socket.oio.OioWorker",
      targetMethod = "run",
      targetLocation = "ENTRY",
      action = "Thread.sleep(500)")})
public void testLatency() throws Exception {
   ActiveMQServer server = createServer(createDefaultNettyConfig());
   server.start();
   ServerLocator locator = createNettyNonHALocator();
   ClientSessionFactory factory = createSessionFactory(locator);
   ClientSession session = factory.createSession();
   session.close();
   server.stop();
}
 
Example #7
Source File: CoreClientOverTwoWayOpenSSLTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testTwoWaySSLVerifyClientTrustAllFalse() throws Exception {
   NettyAcceptor acceptor = (NettyAcceptor) server.getRemotingService().getAcceptor("nettySSL");
   acceptor.getConfiguration().put(TransportConstants.NEED_CLIENT_AUTH_PROP_NAME, true);
   server.getRemotingService().stop(false);
   server.getRemotingService().start();
   server.getRemotingService().startAcceptors();

   //Trust all defaults to false so this should fail with no trust store set
   tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true);
   tc.getParams().put(TransportConstants.KEYSTORE_PROVIDER_PROP_NAME, storeType);
   tc.getParams().put(TransportConstants.KEYSTORE_PATH_PROP_NAME, CLIENT_SIDE_KEYSTORE);
   tc.getParams().put(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME, PASSWORD);

   server.getRemotingService().addIncomingInterceptor(new MyInterceptor());

   ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(tc));
   try {
      ClientSessionFactory sf = createSessionFactory(locator);
      fail("Creating a session here should fail due to no trust store being set");
   } catch (ActiveMQNotConnectedException se) {
      // ignore
   }
}
 
Example #8
Source File: ExportFormatTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testConsumeFromFormat() throws Exception {
   ActiveMQServer server = createServer(true);

   DecodeJournal.importJournal(server.getConfiguration().getJournalLocation().getAbsolutePath(), "activemq-data", "amq", 2, 102400, new StringReader(journalFile));
   DecodeJournal.importJournal(server.getConfiguration().getBindingsLocation().getAbsolutePath(), "activemq-bindings", "bindings", 2, 1048576, new StringReader(bindingsFile));
   server.start();

   ServerLocator locator = createInVMNonHALocator();
   ClientSessionFactory factory = createSessionFactory(locator);
   ClientSession session = factory.createSession();
   session.start();

   ClientConsumer consumer = session.createConsumer("A1");
   for (int i = 0; i < 10; i++) {
      ClientMessage msg = consumer.receive(5000);
      assertNotNull(msg);
      msg.acknowledge();
      assertEquals(i, msg.getIntProperty("key").intValue());
   }

   session.commit();
}
 
Example #9
Source File: SecurityTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateTempQueueWithoutRole() throws Exception {
   ActiveMQServer server = createServer();

   server.start();
   HierarchicalRepository<Set<Role>> securityRepository = server.getSecurityRepository();
   ActiveMQJAASSecurityManager securityManager = (ActiveMQJAASSecurityManager) server.getSecurityManager();
   securityManager.getConfiguration().addUser("auser", "pass");
   Role role = new Role("arole", false, false, false, false, false, false, false, false, false, false);
   Set<Role> roles = new HashSet<>();
   roles.add(role);
   securityRepository.addMatch(SecurityTest.addressA, roles);
   securityManager.getConfiguration().addRole("auser", "arole");
   ClientSessionFactory cf = createSessionFactory(locator);
   ClientSession session = cf.createSession("auser", "pass", false, true, true, false, -1);
   try {
      session.createQueue(new QueueConfiguration(SecurityTest.queueA).setAddress(SecurityTest.addressA).setDurable(false));
      Assert.fail("should throw exception");
   } catch (ActiveMQSecurityException se) {
      //ok
   } catch (ActiveMQException e) {
      fail("Invalid Exception type:" + e.getType());
   }
   session.close();
}
 
Example #10
Source File: BridgeRoutingTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void testBridgeInternal(RoutingType sourceRoutingType,
                                RoutingType destinationRoutingType,
                                ComponentConfigurationRoutingType bridgeRoutingType,
                                long sleepTime,
                                int destinationMessageCount) throws Exception {
   SimpleString source = SimpleString.toSimpleString("source");
   SimpleString destination = SimpleString.toSimpleString("destination");

   server0.createQueue(new QueueConfiguration(source).setRoutingType(sourceRoutingType));
   server1.createQueue(new QueueConfiguration(destination).setRoutingType(destinationRoutingType));

   server0.deployBridge(new BridgeConfiguration()
                           .setRoutingType(bridgeRoutingType)
                           .setName("bridge")
                           .setForwardingAddress(destination.toString())
                           .setQueueName(source.toString())
                           .setConfirmationWindowSize(10)
                           .setStaticConnectors(Arrays.asList("connector")));

   try (ServerLocator locator = ActiveMQClient.createServerLocator(getServer0URL());
        ClientSessionFactory sessionFactory = locator.createSessionFactory();
        ClientSession session = sessionFactory.createSession();
        ClientProducer producer = session.createProducer(source)) {
      producer.send(session.createMessage(true).setRoutingType(sourceRoutingType));
   }

   Wait.waitFor(() -> server0.locateQueue(source).getMessageCount() == 0, 2000, 100);
   Wait.waitFor(() -> server0.getClusterManager().getBridges().get("bridge").getMetrics().getMessagesAcknowledged() == 1, 2000, 100);
   Thread.sleep(sleepTime);
   assertTrue(Wait.waitFor(() -> server1.locateQueue(destination).getMessageCount() == destinationMessageCount, 2000, 100));
}
 
Example #11
Source File: CoreClientOverOneWaySSLTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testOneWaySSLwithSNI() throws Exception {
   createCustomSslServer("myhost\\.com");
   String text = RandomUtil.randomString();

   tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true);
   tc.getParams().put(TransportConstants.TRUSTSTORE_PROVIDER_PROP_NAME, storeType);
   tc.getParams().put(TransportConstants.TRUSTSTORE_PATH_PROP_NAME, CLIENT_SIDE_TRUSTSTORE);
   tc.getParams().put(TransportConstants.TRUSTSTORE_PASSWORD_PROP_NAME, PASSWORD);
   tc.getParams().put(TransportConstants.SNIHOST_PROP_NAME, "myhost.com");

   ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(tc));
   ClientSessionFactory sf = addSessionFactory(createSessionFactory(locator));
   ClientSession session = addClientSession(sf.createSession(false, true, true));
   session.createQueue(new QueueConfiguration(CoreClientOverOneWaySSLTest.QUEUE).setDurable(false));
   ClientProducer producer = addClientProducer(session.createProducer(CoreClientOverOneWaySSLTest.QUEUE));

   ClientMessage message = createTextMessage(session, text);
   producer.send(message);

   ClientConsumer consumer = addClientConsumer(session.createConsumer(CoreClientOverOneWaySSLTest.QUEUE));
   session.start();

   ClientMessage m = consumer.receive(1000);
   Assert.assertNotNull(m);
   Assert.assertEquals(text, m.getBodyBuffer().readString());
}
 
Example #12
Source File: ReceiveTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultiConsumersOnSession() throws Exception {
   ClientSessionFactory cf = createSessionFactory(locator.setCallTimeout(10000000));
   ClientSession sendSession = cf.createSession(false, true, true);
   ClientProducer cp1 = sendSession.createProducer(addressA);
   ClientProducer cp2 = sendSession.createProducer(addressB);

   ClientSession session = cf.createSession(false, true, false);
   session.createQueue(new QueueConfiguration(queueA).setAddress(addressA).setDurable(false));
   session.createQueue(new QueueConfiguration(queueB).setAddress(addressB).setDurable(false));

   ClientConsumer cc1 = session.createConsumer(queueA);
   ClientConsumer cc2 = session.createConsumer(queueB);
   session.start();

   cp1.send(sendSession.createMessage(false));
   cp2.send(sendSession.createMessage(false));
   Assert.assertNotNull(cc1.receive().acknowledge());
   Assert.assertNotNull(cc2.receive().acknowledge());
   session.commit();

   final Queue queue1 = server.locateQueue(queueA);
   final Queue queue2 = server.locateQueue(queueB);

   Wait.assertTrue(() -> queue1.getMessageCount() == 0, 500, 100);
   Wait.assertTrue(() -> queue1.getMessagesAcknowledged() == 1, 500, 100);
   Wait.assertTrue(() -> queue2.getMessageCount() == 0, 500, 100);
   Wait.assertTrue(() -> queue2.getMessagesAcknowledged() == 1, 500, 100);

   session.close();
   sendSession.close();
}
 
Example #13
Source File: ClusterTestBase.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
protected void createQueue(final int node,
                           final String address,
                           final String queueName,
                           final String filterVal,
                           final boolean durable,
                           final String user,
                           final String password,
                           RoutingType routingType) throws Exception {
   ClientSessionFactory sf = sfs[node];

   if (sf == null) {
      throw new IllegalArgumentException("No sf at " + node);
   }

   ClientSession session = addClientSession(sf.createSession(user, password, false, true, true, ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE));

   String filterString = null;

   if (filterVal != null) {
      filterString = ClusterTestBase.FILTER_PROP.toString() + "='" + filterVal + "'";
   }

   log.debug("Creating " + queueName + " , address " + address + " on " + servers[node]);

   session.createQueue(new QueueConfiguration(queueName).setAddress(address).setRoutingType(routingType).setFilterString(filterString).setDurable(durable));

   session.close();
}
 
Example #14
Source File: ScaleDownTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testPaging() throws Exception {
   final int CHUNK_SIZE = 50;
   int messageCount = 0;
   final String addressName = "testAddress";
   final String queueName = "testQueue";

   createQueue(0, addressName, queueName, null, false);
   createQueue(1, addressName, queueName, null, false);

   ClientSessionFactory sf = sfs[0];
   ClientSession session = addClientSession(sf.createSession(false, false));
   ClientProducer producer = addClientProducer(session.createProducer(addressName));

   AddressSettings defaultSetting = new AddressSettings().setPageSizeBytes(10 * 1024).setMaxSizeBytes(20 * 1024);
   servers[0].getAddressSettingsRepository().addMatch("#", defaultSetting);

   while (!servers[0].getPagingManager().getPageStore(new SimpleString(addressName)).isPaging()) {
      for (int i = 0; i < CHUNK_SIZE; i++) {
         ClientMessage message = session.createMessage(true);
         message.getBodyBuffer().writeBytes(new byte[1024]);
         producer.send(message);
         messageCount++;
      }
      session.commit();
   }

   servers[0].stop();

   addConsumer(0, 1, queueName, null);
   for (int i = 0; i < messageCount; i++) {
      Assert.assertNotNull(consumers[0].getConsumer().receive(250));
   }

   Assert.assertNull(consumers[0].getConsumer().receive(250));
   removeConsumer(0);
}
 
Example #15
Source File: AutoCreateExpiryResourcesTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void triggerExpiration() throws Exception {
   server.createQueue(new QueueConfiguration(queueA).setAddress(addressA).setRoutingType(RoutingType.ANYCAST));
   ServerLocator locator = createInVMNonHALocator();
   ClientSessionFactory sessionFactory = createSessionFactory(locator);
   ClientSession session = addClientSession(sessionFactory.createSession(true, false));
   ClientProducer producer = addClientProducer(session.createProducer(addressA));
   ClientMessage message = session.createMessage(true);
   producer.send(message);
   producer.close();
   session.close();
   sessionFactory.close();
   locator.close();
}
 
Example #16
Source File: SecurityTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testJAASSecurityManagerAuthenticationBadPassword() throws Exception {
   ActiveMQJAASSecurityManager securityManager = new ActiveMQJAASSecurityManager("PropertiesLogin");
   ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(createDefaultInVMConfig().setSecurityEnabled(true), ManagementFactory.getPlatformMBeanServer(), securityManager, false));
   server.start();
   ClientSessionFactory cf = createSessionFactory(locator);

   try {
      cf.createSession("first", "badpassword", false, true, true, false, 0);
      Assert.fail("should throw exception here");
   } catch (Exception e) {
      // ignore
   }
}
 
Example #17
Source File: HangConsumerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * This would force a journal duplication on bindings even with the scenario that generated fixed,
 * the server shouldn't hold of from starting
 *
 * @throws Exception
 */
@Test
public void testForceDuplicationOnBindings() throws Exception {
   queue = server.createQueue(new QueueConfiguration(QUEUE).setRoutingType(RoutingType.ANYCAST));

   ClientSessionFactory factory = locator.createSessionFactory();
   ClientSession session = factory.createSession(false, false, false);

   ClientProducer producer = session.createProducer(QUEUE);

   producer.send(session.createMessage(true));
   session.commit();

   long queueID = server.getStorageManager().generateID();
   long txID = server.getStorageManager().generateID();

   // Forcing a situation where the server would unexpectedly create a duplicated queue. The server should still start normally
   LocalQueueBinding newBinding = new LocalQueueBinding(QUEUE,
                                                        new QueueImpl(queueID, QUEUE, QUEUE, null, null, true, false,
                                                                      false, null, null, null, null, null, null, null),
                                                        server.getNodeID());
   server.getStorageManager().addQueueBinding(txID, newBinding);
   server.getStorageManager().commitBindings(txID);

   server.stop();

   // a duplicate binding would impede the server from starting
   server.start();
   waitForServerToStart(server);

   server.stop();

}
 
Example #18
Source File: CoreClientOverTwoWayOpenSSLTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testTwoWaySSL() throws Exception {
   String text = RandomUtil.randomString();

   tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true);
   tc.getParams().put(TransportConstants.SSL_PROVIDER, TransportConstants.OPENSSL_PROVIDER);
   tc.getParams().put(TransportConstants.TRUSTSTORE_PROVIDER_PROP_NAME, storeType);
   tc.getParams().put(TransportConstants.KEYSTORE_PROVIDER_PROP_NAME, storeType);
   tc.getParams().put(TransportConstants.TRUSTSTORE_PATH_PROP_NAME, CLIENT_SIDE_TRUSTSTORE);
   tc.getParams().put(TransportConstants.TRUSTSTORE_PASSWORD_PROP_NAME, PASSWORD);
   tc.getParams().put(TransportConstants.KEYSTORE_PATH_PROP_NAME, CLIENT_SIDE_KEYSTORE);
   tc.getParams().put(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME, PASSWORD);
   //tc.getParams().put(TransportConstants.ENABLED_CIPHER_SUITES_PROP_NAME, "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256");

   server.getRemotingService().addIncomingInterceptor(new MyInterceptor());

   ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(tc));
   ClientSessionFactory sf = createSessionFactory(locator);
   ClientSession session = sf.createSession(false, true, true);
   session.createQueue(new QueueConfiguration(CoreClientOverTwoWayOpenSSLTest.QUEUE).setDurable(false));
   ClientProducer producer = session.createProducer(CoreClientOverTwoWayOpenSSLTest.QUEUE);

   ClientMessage message = createTextMessage(session, text);
   producer.send(message);

   ClientConsumer consumer = session.createConsumer(CoreClientOverTwoWayOpenSSLTest.QUEUE);
   session.start();

   ClientMessage m = consumer.receive(1000);
   Assert.assertNotNull(m);
   Assert.assertEquals(text, m.getBodyBuffer().readString());
}
 
Example #19
Source File: ScaleDownHandler.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public long scaleDownMessages(ClientSessionFactory sessionFactory,
                              SimpleString nodeId,
                              String user,
                              String password) throws Exception {
   long messageCount = 0;
   targetNodeId = nodeId != null ? nodeId.toString() : getTargetNodeId(sessionFactory);

   try (ClientSession session = sessionFactory.createSession(user, password, false, true, true, false, 0)) {
      ClientProducer producer = session.createProducer();

      // perform a loop per address
      for (SimpleString address : postOffice.getAddresses()) {
         logger.debug("Scaling down address " + address);
         Bindings bindings = postOffice.lookupBindingsForAddress(address);

         // It will get a list of queues on this address, ordered by the number of messages
         Set<Queue> queues = new TreeSet<>(new OrderQueueByNumberOfReferencesComparator());
         if (bindings != null) {
            for (Binding binding : bindings.getBindings()) {
               if (binding instanceof LocalQueueBinding) {
                  Queue queue = ((LocalQueueBinding) binding).getQueue();
                  // as part of scale down we will cancel any scheduled message and pass it to theWhile we scan for the queues we will also cancel any scheduled messages and deliver them right away
                  queue.deliverScheduledMessages();
                  queues.add(queue);
               }
            }
         }

         String sfPrefix =  ((PostOfficeImpl) postOffice).getServer().getInternalNamingPrefix() + "sf.";
         if (address.toString().startsWith(sfPrefix)) {
            messageCount += scaleDownSNF(address, queues, producer);
         } else {
            messageCount += scaleDownRegularMessages(address, queues, session, producer);
         }

      }
   }

   return messageCount;
}
 
Example #20
Source File: CoreClientOverOneWaySSLTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testOneWaySSLUsingDefaultSslContext() throws Exception {
   createCustomSslServer();
   String text = RandomUtil.randomString();

   tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true);
   tc.getParams().put(TransportConstants.USE_DEFAULT_SSL_CONTEXT_PROP_NAME, true);

   SSLContext.setDefault(new SSLSupport()
                            .setTruststoreProvider(storeType)
                            .setTruststorePath(CLIENT_SIDE_TRUSTSTORE)
                            .setTruststorePassword(PASSWORD)
                            .createContext());

   ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(tc));
   ClientSessionFactory sf = addSessionFactory(createSessionFactory(locator));
   ClientSession session = addClientSession(sf.createSession(false, true, true));
   session.createQueue(new QueueConfiguration(CoreClientOverOneWaySSLTest.QUEUE).setDurable(false));
   ClientProducer producer = addClientProducer(session.createProducer(CoreClientOverOneWaySSLTest.QUEUE));

   ClientMessage message = createTextMessage(session, text);
   producer.send(message);

   ClientConsumer consumer = addClientConsumer(session.createConsumer(CoreClientOverOneWaySSLTest.QUEUE));
   session.start();

   ClientMessage m = consumer.receive(1000);
   Assert.assertNotNull(m);
   Assert.assertEquals(text, m.getBodyBuffer().readString());
}
 
Example #21
Source File: AutoCreateDeadLetterResourcesTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testDivertedMessage() throws Exception {
   SimpleString dlqName = AddressSettings.DEFAULT_DEAD_LETTER_QUEUE_PREFIX.concat(addressA).concat(AddressSettings.DEFAULT_DEAD_LETTER_QUEUE_SUFFIX);
   String divertAddress = "divertAddress";

   server.deployDivert(new DivertConfiguration().setName("testDivert").setAddress(divertAddress).setForwardingAddress(addressA.toString()));

   server.createQueue(new QueueConfiguration(queueA).setAddress(addressA).setRoutingType(RoutingType.ANYCAST));

   ServerLocator locator = createInVMNonHALocator();
   ClientSessionFactory sessionFactory = createSessionFactory(locator);
   ClientSession session = addClientSession(sessionFactory.createSession(true, true));
   ClientProducer producer = addClientProducer(session.createProducer(divertAddress));
   producer.send(session.createMessage(true));
   producer.close();

   Wait.assertEquals(1L, () -> server.locateQueue(queueA).getMessageCount(), 2000, 100);

   triggerDlaDelivery();

   Wait.assertTrue(() -> server.locateQueue(dlqName).getMessageCount() == 1, 2000, 100);

   ClientConsumer consumer = session.createConsumer(dlqName);
   session.start();
   ClientMessage message = consumer.receive(1000);
   assertNotNull(message);
   message.acknowledge();
}
 
Example #22
Source File: ServerLocatorImpl.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public void notifyNodeUp(long uniqueEventID,
                         final String nodeID,
                         final String backupGroupName,
                         final String scaleDownGroupName,
                         final Pair<TransportConfiguration, TransportConfiguration> connectorPair,
                         final boolean last) {
   if (logger.isTraceEnabled()) {
      logger.trace("NodeUp " + this + "::nodeID=" + nodeID + ", connectorPair=" + connectorPair, new Exception("trace"));
   }

   TopologyMemberImpl member = new TopologyMemberImpl(nodeID, backupGroupName, scaleDownGroupName, connectorPair.getA(), connectorPair.getB());

   topology.updateMember(uniqueEventID, nodeID, member);

   TopologyMember actMember = topology.getMember(nodeID);

   if (actMember != null && actMember.getLive() != null && actMember.getBackup() != null) {
      HashSet<ClientSessionFactory> clonedFactories = new HashSet<>();
      synchronized (factories) {
         clonedFactories.addAll(factories);
      }

      for (ClientSessionFactory factory : clonedFactories) {
         ((ClientSessionFactoryInternal) factory).setBackupConnector(actMember.getLive(), actMember.getBackup());
      }
   }

   updateArraysAndPairs(uniqueEventID);

   if (last) {
      receivedTopology = true;
   }
}
 
Example #23
Source File: SecurityTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendManagementWithoutRole() throws Exception {
   ActiveMQServer server = createServer();

   server.start();
   HierarchicalRepository<Set<Role>> securityRepository = server.getSecurityRepository();
   ActiveMQJAASSecurityManager securityManager = (ActiveMQJAASSecurityManager) server.getSecurityManager();
   securityManager.getConfiguration().addUser("auser", "pass");
   Role role = new Role("arole", false, false, true, false, false, false, false, false, true, false);
   Set<Role> roles = new HashSet<>();
   roles.add(role);
   securityRepository.addMatch(configuration.getManagementAddress().toString(), roles);
   securityManager.getConfiguration().addRole("auser", "arole");
   ClientSessionFactory cf = createSessionFactory(locator);
   ClientSession session = cf.createSession("auser", "pass", false, true, true, false, -1);
   session.createQueue(new QueueConfiguration(SecurityTest.queueA).setAddress(configuration.getManagementAddress().toString()));
   ClientProducer cp = session.createProducer(configuration.getManagementAddress());
   cp.send(session.createMessage(false));
   try {
      cp.send(session.createMessage(false));
   } catch (ActiveMQSecurityException se) {
      //ok
   } catch (ActiveMQException e) {
      fail("Invalid Exception type:" + e.getType());
   }
   session.close();

}
 
Example #24
Source File: AcknowledgeTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsyncConsumerNoAck() throws Exception {
   ActiveMQServer server = createServer(false);

   server.start();
   ServerLocator locator = createInVMNonHALocator();
   ClientSessionFactory cf = createSessionFactory(locator);
   ClientSession sendSession = cf.createSession(false, true, true);
   ClientSession session = cf.createSession(false, true, true);
   sendSession.createQueue(new QueueConfiguration(queueA).setAddress(addressA).setDurable(false));
   ClientProducer cp = sendSession.createProducer(addressA);
   ClientConsumer cc = session.createConsumer(queueA);
   int numMessages = 3;
   for (int i = 0; i < numMessages; i++) {
      cp.send(sendSession.createMessage(false));
   }

   Thread.sleep(500);
   instanceLog.debug("woke up");

   final CountDownLatch latch = new CountDownLatch(numMessages);
   session.start();
   cc.setMessageHandler(new MessageHandler() {
      int c = 0;

      @Override
      public void onMessage(final ClientMessage message) {
         instanceLog.debug("Got message " + c++);
         latch.countDown();
      }
   });
   Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
   Queue q = (Queue) server.getPostOffice().getBinding(queueA).getBindable();
   Assert.assertEquals(numMessages, q.getDeliveringCount());
   sendSession.close();
   session.close();
}
 
Example #25
Source File: JMSXUserIDPluginTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddValidatedUserCore() throws Exception {
   ServerLocator locator = createNettyNonHALocator();
   ClientSessionFactory sf = createSessionFactory(locator);
   ClientSession session = sf.createSession(false, true, true);
   ClientProducer producer = session.createProducer(ADDRESS.toString());
   producer.send(session.createMessage(true));
   ClientConsumer consumer = session.createConsumer(ADDRESS.toString());
   session.start();
   ClientMessage clientMessage = consumer.receiveImmediate();
   Assert.assertNotNull(clientMessage);
   Assert.assertEquals(clientMessage.getValidatedUserID(), "testuser");
}
 
Example #26
Source File: ReplicationTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testConnectIntoNonBackup() throws Exception {
   setupServer(false);
   try {
      ClientSessionFactory sf = createSessionFactory(locator);
      manager = new ReplicationManager(null, (CoreRemotingConnection) sf.getConnection(), sf.getServerLocator().getCallTimeout(), sf.getServerLocator().getCallTimeout(), factory);
      addActiveMQComponent(manager);
      manager.start();
      Assert.fail("Exception was expected");
   } catch (ActiveMQNotConnectedException nce) {
      // ok
   } catch (ActiveMQException expected) {
      fail("Invalid Exception type:" + expected.getType());
   }
}
 
Example #27
Source File: ReceiveTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testBasicReceive() throws Exception {
   ClientSessionFactory cf = createSessionFactory(locator);
   ClientSession sendSession = cf.createSession(false, true, true);
   ClientProducer cp = sendSession.createProducer(addressA);
   ClientSession session = cf.createSession(false, true, true);
   session.createQueue(new QueueConfiguration(queueA).setAddress(addressA).setDurable(false));
   ClientConsumer cc = session.createConsumer(queueA);
   session.start();
   cp.send(sendSession.createMessage(false));
   Assert.assertNotNull(cc.receive());
   session.close();
   sendSession.close();
}
 
Example #28
Source File: SSLProviderTwoWayTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testProviderLoading2Way() throws Exception {
   Assume.assumeTrue(isOpenSSLSupported());

   final String text = "Hello SSL!";
   StringBuilder uri = new StringBuilder("tcp://" + tc.getParams().get(TransportConstants.HOST_PROP_NAME).toString()
           + ":" + tc.getParams().get(TransportConstants.PORT_PROP_NAME).toString());

   uri.append("?").append(TransportConstants.SSL_ENABLED_PROP_NAME).append("=true");
   uri.append("&").append(TransportConstants.SSL_PROVIDER).append("=").append(clientSslProvider);
   uri.append("&").append(TransportConstants.KEYSTORE_PROVIDER_PROP_NAME).append("=").append("JKS");
   uri.append("&").append(TransportConstants.KEYSTORE_PATH_PROP_NAME).append("=").append(CLIENT_SIDE_KEYSTORE);
   uri.append("&").append(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME).append("=").append(PASSWORD);
   uri.append("&").append(TransportConstants.TRUSTSTORE_PROVIDER_PROP_NAME).append("=JKS");
   uri.append("&").append(TransportConstants.TRUSTSTORE_PATH_PROP_NAME).append("=").append(CLIENT_SIDE_TRUSTSTORE);
   uri.append("&").append(TransportConstants.TRUSTSTORE_PASSWORD_PROP_NAME).append("=").append(PASSWORD);

   ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocator(uri.toString()));
   ClientSessionFactory sf = addSessionFactory(createSessionFactory(locator));
   ClientSession session = addClientSession(sf.createSession(false, true, true));
   session.createQueue(new QueueConfiguration(QUEUE).setRoutingType(RoutingType.ANYCAST));
   ClientProducer producer = addClientProducer(session.createProducer(QUEUE));

   ClientMessage message = createTextMessage(session, text);
   producer.send(message);

   ClientConsumer consumer = addClientConsumer(session.createConsumer(QUEUE));
   session.start();

   ClientMessage m = consumer.receive(1000);
   Assert.assertNotNull(m);
   Assert.assertEquals(text, m.getBodyBuffer().readString());

}
 
Example #29
Source File: SecurityFailoverTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
protected ClientSession createSession(ClientSessionFactory sf,
                                      boolean xa,
                                      boolean autoCommitSends,
                                      boolean autoCommitAcks) throws Exception {
   return createSession(sf, xa, autoCommitSends, autoCommitAcks, sf.getServerLocator().getAckBatchSize());
}
 
Example #30
Source File: SessionFactoryTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testCloseUnusedClientSessionFactoryWithoutGlobalPools() throws Exception {
   ServerLocator locator = ActiveMQClient.createServerLocatorWithoutHA(liveTC);

   ClientSessionFactory csf = createSessionFactory(locator);
   csf.close();
}