org.apache.activemq.artemis.core.server.ActiveMQServer

Here are the examples of the java api class org.apache.activemq.artemis.core.server.ActiveMQServer taken from open source projects.

1. LatencyTest#testLatency()

Project: activemq-artemis
Source File: LatencyTest.java
View license
/*
   * simple test to make sure connect still works with some network latency  built into netty
   * */
@Test
@BMRules(rules = { @BMRule(name = "trace ClientBootstrap.connect", targetClass = "org.jboss.netty.bootstrap.ClientBootstrap", targetMethod = "connect", targetLocation = "ENTRY", action = "System.out.println(\"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();
}

2. HeuristicXATest#testInvalidCall()

View license
// Static --------------------------------------------------------
// Constructors --------------------------------------------------
// Public --------------------------------------------------------
@Test
public void testInvalidCall() throws Exception {
    Configuration configuration = createDefaultInVMConfig().setJMXManagementEnabled(true);
    ActiveMQServer server = createServer(false, configuration);
    server.setMBeanServer(mbeanServer);
    server.start();
    ActiveMQServerControl jmxServer = ManagementControlHelper.createActiveMQServerControl(mbeanServer);
    Assert.assertFalse(jmxServer.commitPreparedTransaction("Nananananana"));
}

3. MultiServerTestBase#startServers()

View license
protected void startServers() throws Exception {
    for (ActiveMQServer server : servers) {
        server.start();
    }
    for (ActiveMQServer server : servers) {
        waitForServerToStart(server);
    }
    if (backupServers != null) {
        for (ActiveMQServer server : backupServers) {
            server.start();
        }
        for (ActiveMQServer server : backupServers) {
            waitForServerToStart(server);
        }
    }
    for (ActiveMQServer server : servers) {
        waitForTopology(server, getNumberOfServers(), useBackups() ? getNumberOfServers() : 0);
    }
}

4. AcceptorControlTest#testAttributes()

View license
// Static --------------------------------------------------------
// Constructors --------------------------------------------------
// Public --------------------------------------------------------
@Test
public void testAttributes() throws Exception {
    TransportConfiguration acceptorConfig = new TransportConfiguration(InVMAcceptorFactory.class.getName(), new HashMap<String, Object>(), RandomUtil.randomString());
    Configuration config = createBasicConfig().addAcceptorConfiguration(acceptorConfig);
    ActiveMQServer service = createServer(false, config);
    service.setMBeanServer(mbeanServer);
    service.start();
    AcceptorControl acceptorControl = createManagementControl(acceptorConfig.getName());
    Assert.assertEquals(acceptorConfig.getName(), acceptorControl.getName());
    Assert.assertEquals(acceptorConfig.getFactoryClassName(), acceptorControl.getFactoryClassName());
}

5. LargeMessageTest#testDeleteOnNoBinding()

View license
@Test
public void testDeleteOnNoBinding() throws Exception {
    final int messageSize = (int) (3.5 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE);
    ActiveMQServer server = createServer(true, isNetty(), storeType);
    server.start();
    ClientSessionFactory sf = addSessionFactory(createSessionFactory(locator));
    ClientSession session = addClientSession(sf.createSession(false, true, false));
    ClientProducer producer = session.createProducer(UUID.randomUUID().toString());
    Message clientFile = createLargeClientMessageStreaming(session, messageSize, true);
    producer.send(clientFile);
    session.close();
    validateNoFilesOnLargeDir();
}

6. MessageRateTest#testProduceRate()

View license
// Attributes ----------------------------------------------------
// Static --------------------------------------------------------
// Constructors --------------------------------------------------
// Public --------------------------------------------------------
@Test
public void testProduceRate() throws Exception {
    ActiveMQServer server = createServer(false);
    server.start();
    locator.setProducerMaxRate(10);
    ClientSessionFactory sf = createSessionFactory(locator);
    ClientSession session = sf.createSession(false, true, true);
    session.createQueue(ADDRESS, ADDRESS, true);
    ClientProducer producer = session.createProducer(ADDRESS);
    long start = System.currentTimeMillis();
    for (int i = 0; i < 10; i++) {
        producer.send(session.createMessage(false));
    }
    long end = System.currentTimeMillis();
    Assert.assertTrue("TotalTime = " + (end - start), end - start >= 1000);
    session.close();
}

7. NIOvsOIOTest#testPerf()

Project: activemq-artemis
Source File: NIOvsOIOTest.java
View license
private void testPerf(boolean nio) throws Exception {
    Configuration config = createDefaultInVMConfig();
    Map<String, Object> params = new HashMap<>();
    params.put(TransportConstants.USE_NIO_PROP_NAME, nio);
    config.getAcceptorConfigurations().add(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params));
    ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));
    AddressSettings addressSettings = new AddressSettings().setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK).setMaxSizeBytes(10 * 1024 * 1024);
    final String dest = "test-destination";
    HierarchicalRepository<AddressSettings> repos = server.getAddressSettingsRepository();
    repos.addMatch(dest, addressSettings);
    server.start();
    for (int i = 0; i < 2; i++) {
        doTest(dest);
    }
}

8. TransactionalSendTest#testSendWithCommit()

View license
@Test
public void testSendWithCommit() throws Exception {
    ActiveMQServer server = createServer(false);
    server.start();
    ClientSessionFactory cf = createSessionFactory(locator);
    ClientSession session = cf.createSession(false, false, false);
    session.createQueue(addressA, queueA, false);
    ClientProducer cp = session.createProducer(addressA);
    int numMessages = 100;
    for (int i = 0; i < numMessages; i++) {
        cp.send(session.createMessage(false));
    }
    Queue q = (Queue) server.getPostOffice().getBinding(queueA).getBindable();
    Assert.assertEquals(0, getMessageCount(q));
    session.commit();
    Assert.assertEquals(getMessageCount(q), numMessages);
    // now send some more
    for (int i = 0; i < numMessages; i++) {
        cp.send(session.createMessage(false));
    }
    Assert.assertEquals(numMessages, getMessageCount(q));
    session.commit();
    Assert.assertEquals(numMessages * 2, getMessageCount(q));
    session.close();
}

9. TransactionalSendTest#testSendWithRollback()

View license
@Test
public void testSendWithRollback() throws Exception {
    ActiveMQServer server = createServer(false);
    server.start();
    ClientSessionFactory cf = createSessionFactory(locator);
    ClientSession session = cf.createSession(false, false, false);
    session.createQueue(addressA, queueA, false);
    ClientProducer cp = session.createProducer(addressA);
    int numMessages = 100;
    for (int i = 0; i < numMessages; i++) {
        cp.send(session.createMessage(false));
    }
    Queue q = (Queue) server.getPostOffice().getBinding(queueA).getBindable();
    Assert.assertEquals(getMessageCount(q), 0);
    session.rollback();
    Assert.assertEquals(getMessageCount(q), 0);
    // now send some more
    for (int i = 0; i < numMessages; i++) {
        cp.send(session.createMessage(false));
    }
    Assert.assertEquals(0, getMessageCount(q));
    session.commit();
    Assert.assertEquals(numMessages, getMessageCount(q));
    session.close();
}

10. ManagementServiceImplTest#testHandleManagementMessageWithOperation()

View license
@Test
public void testHandleManagementMessageWithOperation() throws Exception {
    String queue = RandomUtil.randomString();
    String address = RandomUtil.randomString();
    Configuration config = createBasicConfig().setJMXManagementEnabled(false);
    ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));
    server.start();
    // invoke attribute and operation on the server
    ServerMessage message = new ServerMessageImpl(1, 100);
    ManagementHelper.putOperationInvocation(message, ResourceNames.CORE_SERVER, "createQueue", queue, address);
    ServerMessage reply = server.getManagementService().handleMessage(message);
    Assert.assertTrue(ManagementHelper.hasOperationSucceeded(reply));
}

11. ManagementServiceImplTest#testHandleManagementMessageWithOperationWhichFails()

View license
@Test
public void testHandleManagementMessageWithOperationWhichFails() throws Exception {
    Configuration config = createBasicConfig().setJMXManagementEnabled(false);
    ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));
    server.start();
    // invoke attribute and operation on the server
    ServerMessage message = new ServerMessageImpl(1, 100);
    ManagementHelper.putOperationInvocation(message, ResourceNames.CORE_SERVER, "thereIsNoSuchOperation");
    ServerMessage reply = server.getManagementService().handleMessage(message);
    Assert.assertFalse(ManagementHelper.hasOperationSucceeded(reply));
    Assert.assertNotNull(ManagementHelper.getResult(reply));
}

12. ManagementServiceImplTest#testHandleManagementMessageWithUnknowResource()

View license
@Test
public void testHandleManagementMessageWithUnknowResource() throws Exception {
    Configuration config = createBasicConfig().setJMXManagementEnabled(false);
    ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));
    server.start();
    // invoke attribute and operation on the server
    ServerMessage message = new ServerMessageImpl(1, 100);
    ManagementHelper.putOperationInvocation(message, "Resouce.Does.Not.Exist", "toString");
    ServerMessage reply = server.getManagementService().handleMessage(message);
    Assert.assertFalse(ManagementHelper.hasOperationSucceeded(reply));
    Assert.assertNotNull(ManagementHelper.getResult(reply));
}

13. ManagementServiceImplTest#testHandleManagementMessageWithUnknownAttribute()

View license
@Test
public void testHandleManagementMessageWithUnknownAttribute() throws Exception {
    Configuration config = createBasicConfig().setJMXManagementEnabled(false);
    ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));
    server.start();
    // invoke attribute and operation on the server
    ServerMessage message = new ServerMessageImpl(1, 100);
    ManagementHelper.putAttribute(message, ResourceNames.CORE_SERVER, "started");
    ServerMessage reply = server.getManagementService().handleMessage(message);
    Assert.assertTrue(ManagementHelper.hasOperationSucceeded(reply));
    Assert.assertTrue((Boolean) ManagementHelper.getResult(reply));
}

14. ManagementServiceImplTest#testHandleManagementMessageWithKnownAttribute()

View license
@Test
public void testHandleManagementMessageWithKnownAttribute() throws Exception {
    Configuration config = createBasicConfig().setJMXManagementEnabled(false);
    ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));
    server.start();
    // invoke attribute and operation on the server
    ServerMessage message = new ServerMessageImpl(1, 100);
    ManagementHelper.putAttribute(message, ResourceNames.CORE_SERVER, "attribute.Does.Not.Exist");
    ServerMessage reply = server.getManagementService().handleMessage(message);
    Assert.assertFalse(ManagementHelper.hasOperationSucceeded(reply));
    Assert.assertNotNull(ManagementHelper.getResult(reply));
}

15. SecurityManagementWithConfiguredAdminUserTest#setupAndStartActiveMQServer()

View license
// Package protected ---------------------------------------------
// Protected -----------------------------------------------------
@Override
protected ActiveMQServer setupAndStartActiveMQServer() throws Exception {
    Configuration config = createDefaultInVMConfig().setSecurityEnabled(true);
    ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));
    server.start();
    HierarchicalRepository<Set<Role>> securityRepository = server.getSecurityRepository();
    ActiveMQJAASSecurityManager securityManager = (ActiveMQJAASSecurityManager) server.getSecurityManager();
    securityManager.getConfiguration().addUser(validAdminUser, validAdminPassword);
    securityManager.getConfiguration().addUser(invalidAdminUser, invalidAdminPassword);
    securityManager.getConfiguration().addRole(validAdminUser, "admin");
    securityManager.getConfiguration().addRole(validAdminUser, "guest");
    securityManager.getConfiguration().addRole(invalidAdminUser, "guest");
    Set<Role> adminRole = securityRepository.getMatch(ActiveMQDefaultConfiguration.getDefaultManagementAddress().toString());
    adminRole.add(new Role("admin", true, true, true, true, true, true, true));
    securityRepository.addMatch(ActiveMQDefaultConfiguration.getDefaultManagementAddress().toString(), adminRole);
    Set<Role> guestRole = securityRepository.getMatch("*");
    guestRole.add(new Role("guest", true, true, true, true, true, true, false));
    securityRepository.addMatch("*", guestRole);
    return server;
}

16. ExportFormatTest#testConsumeFromFormat()

View license
@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();
}

17. SecurityTest#testJAASSecurityManagerAuthentication()

Project: activemq-artemis
Source File: SecurityTest.java
View license
@Test
public void testJAASSecurityManagerAuthentication() 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 {
        ClientSession session = cf.createSession("first", "secret", false, true, true, false, 0);
        session.close();
    } catch (ActiveMQException e) {
        e.printStackTrace();
        Assert.fail("should not throw exception");
    }
}

18. SecurityTest#testJAASSecurityManagerAuthenticationBadPassword()

Project: activemq-artemis
Source File: SecurityTest.java
View license
@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) {
    }
}

19. SecurityTest#testJAASSecurityManagerAuthenticationGuest()

Project: activemq-artemis
Source File: SecurityTest.java
View license
@Test
public void testJAASSecurityManagerAuthenticationGuest() throws Exception {
    ActiveMQJAASSecurityManager securityManager = new ActiveMQJAASSecurityManager("GuestLogin");
    ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(createDefaultInVMConfig().setSecurityEnabled(true), ManagementFactory.getPlatformMBeanServer(), securityManager, false));
    server.start();
    ClientSessionFactory cf = createSessionFactory(locator);
    try {
        ClientSession session = cf.createSession("first", "secret", false, true, true, false, 0);
        session.close();
    } catch (ActiveMQException e) {
        e.printStackTrace();
        Assert.fail("should not throw exception");
    }
}

20. SecurityTest#testCreateSessionWithNullUserPass()

Project: activemq-artemis
Source File: SecurityTest.java
View license
@Test
public void testCreateSessionWithNullUserPass() throws Exception {
    ActiveMQServer server = createServer();
    ActiveMQJAASSecurityManager securityManager = (ActiveMQJAASSecurityManager) server.getSecurityManager();
    securityManager.getConfiguration().addUser("guest", "guest");
    securityManager.getConfiguration().setDefaultUser("guest");
    server.start();
    ClientSessionFactory cf = createSessionFactory(locator);
    try {
        ClientSession session = cf.createSession(false, true, true);
        session.close();
    } catch (ActiveMQException e) {
        Assert.fail("should not throw exception");
    }
}

21. SecurityTest#testCreateSessionWithNullUserPassNoGuest()

Project: activemq-artemis
Source File: SecurityTest.java
View license
@Test
public void testCreateSessionWithNullUserPassNoGuest() throws Exception {
    ActiveMQServer server = createServer();
    server.start();
    ClientSessionFactory cf = createSessionFactory(locator);
    try {
        cf.createSession(false, true, true);
        Assert.fail("should throw exception");
    } catch (ActiveMQSecurityException se) {
    } catch (ActiveMQException e) {
        fail("Invalid Exception type:" + e.getType());
    }
}

22. SecurityTest#testCreateSessionWithCorrectUserWrongPass()

Project: activemq-artemis
Source File: SecurityTest.java
View license
@Test
public void testCreateSessionWithCorrectUserWrongPass() throws Exception {
    ActiveMQServer server = createServer();
    ActiveMQJAASSecurityManager securityManager = (ActiveMQJAASSecurityManager) server.getSecurityManager();
    securityManager.getConfiguration().addUser("newuser", "apass");
    server.start();
    ClientSessionFactory cf = createSessionFactory(locator);
    try {
        cf.createSession("newuser", "awrongpass", false, true, true, false, -1);
        Assert.fail("should not throw exception");
    } catch (ActiveMQSecurityException se) {
    } catch (ActiveMQException e) {
        fail("Invalid Exception type:" + e.getType());
    }
}

23. SecurityTest#testCreateSessionWithCorrectUserCorrectPass()

Project: activemq-artemis
Source File: SecurityTest.java
View license
@Test
public void testCreateSessionWithCorrectUserCorrectPass() throws Exception {
    ActiveMQServer server = createServer();
    ActiveMQJAASSecurityManager securityManager = (ActiveMQJAASSecurityManager) server.getSecurityManager();
    securityManager.getConfiguration().addUser("newuser", "apass");
    server.start();
    ClientSessionFactory cf = createSessionFactory(locator);
    try {
        ClientSession session = cf.createSession("newuser", "apass", false, true, true, false, -1);
        session.close();
    } catch (ActiveMQException e) {
        Assert.fail("should not throw exception");
    }
}

24. SecurityTest#testCreateDurableQueueWithRole()

Project: activemq-artemis
Source File: SecurityTest.java
View license
@Test
public void testCreateDurableQueueWithRole() 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);
    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);
    session.createQueue(SecurityTest.addressA, SecurityTest.queueA, true);
    session.close();
}

25. SecurityTest#testDeleteDurableQueueWithRole()

Project: activemq-artemis
Source File: SecurityTest.java
View license
@Test
public void testDeleteDurableQueueWithRole() 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, true, 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);
    session.createQueue(SecurityTest.addressA, SecurityTest.queueA, true);
    session.deleteQueue(SecurityTest.queueA);
    session.close();
}

26. SecurityTest#testCreateTempQueueWithRole()

Project: activemq-artemis
Source File: SecurityTest.java
View license
@Test
public void testCreateTempQueueWithRole() 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, true, 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);
    session.createQueue(SecurityTest.addressA, SecurityTest.queueA, false);
    session.close();
}

27. SecurityTest#testDeleteTempQueueWithRole()

Project: activemq-artemis
Source File: SecurityTest.java
View license
@Test
public void testDeleteTempQueueWithRole() 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, true, true, 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);
    session.createQueue(SecurityTest.addressA, SecurityTest.queueA, false);
    session.deleteQueue(SecurityTest.queueA);
    session.close();
}

28. SecurityTest#testNonBlockSendWithoutRole()

Project: activemq-artemis
Source File: SecurityTest.java
View license
@Test
public void testNonBlockSendWithoutRole() 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);
    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);
    session.createQueue(SecurityTest.addressA, SecurityTest.queueA, true);
    ClientProducer cp = session.createProducer(SecurityTest.addressA);
    cp.send(session.createMessage(false));
    session.close();
    Queue binding = (Queue) server.getPostOffice().getBinding(new SimpleString(SecurityTest.queueA)).getBindable();
    Assert.assertEquals(0, getMessageCount(binding));
}

29. SecurityTest#testSendManagementWithRole()

Project: activemq-artemis
Source File: SecurityTest.java
View license
@Test
public void testSendManagementWithRole() 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, true);
    Set<Role> roles = new HashSet<>();
    roles.add(role);
    securityRepository.addMatch(configuration.getManagementAddress().toString(), roles);
    securityManager.getConfiguration().addRole("auser", "arole");
    locator.setBlockOnNonDurableSend(true);
    ClientSessionFactory cf = createSessionFactory(locator);
    ClientSession session = cf.createSession("auser", "pass", false, true, true, false, -1);
    ClientProducer cp = session.createProducer(configuration.getManagementAddress());
    cp.send(session.createMessage(false));
    session.close();
}

30. SecurityTest#testNonBlockSendManagementWithoutRole()

Project: activemq-artemis
Source File: SecurityTest.java
View license
@Test
public void testNonBlockSendManagementWithoutRole() 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);
    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(configuration.getManagementAddress().toString(), SecurityTest.queueA, true);
    ClientProducer cp = session.createProducer(configuration.getManagementAddress());
    cp.send(session.createMessage(false));
    session.close();
    Queue binding = (Queue) server.getPostOffice().getBinding(new SimpleString(SecurityTest.queueA)).getBindable();
    Assert.assertEquals(0, getMessageCount(binding));
}

31. PotentialOOMELoggingTest#testBlockLogging()

View license
@Test
public /**
    * When running this test from an IDE add this to the test command line so that the AssertionLoggerHandler works properly:
    *
    *   -Djava.util.logging.manager=org.jboss.logmanager.LogManager  -Dlogging.configuration=file:<path_to_source>/tests/config/logging.properties
    */
void testBlockLogging() throws Exception {
    ActiveMQServer server = createServer(false, createDefaultInVMConfig());
    for (int i = 0; i < 10000; i++) {
        server.getConfiguration().addQueueConfiguration(new CoreQueueConfiguration().setAddress(UUID.randomUUID().toString()).setName(UUID.randomUUID().toString()));
    }
    server.getConfiguration().getAddressesSettings().put("#", new AddressSettings().setMaxSizeBytes(10485760 * 10));
    server.start();
    // Using the code only so the test doesn't fail just because someone edits the log text
    Assert.assertTrue("Expected to find 222205", AssertionLoggerHandler.findText("AMQ222205"));
}

32. AcceptorsTest#testMultipleAcceptorsWithSameHostPortDifferentName()

Project: activemq-artemis
Source File: AcceptorsTest.java
View license
@Test
public void testMultipleAcceptorsWithSameHostPortDifferentName() throws Exception {
    final String acceptorFactoryClass = FakeAcceptorFactory.class.getName();
    Map<String, Object> params = new HashMap<>();
    params.put("host", "localhost");
    params.put("port", 5445);
    Set<TransportConfiguration> tcs = new HashSet<>();
    tcs.add(new TransportConfiguration(acceptorFactoryClass, params, "Acceptor1"));
    tcs.add(new TransportConfiguration(acceptorFactoryClass, params, "Acceptor2"));
    Configuration config = createBasicConfig();
    config.setAcceptorConfigurations(tcs);
    ActiveMQServer server = createServer(config);
    server.start();
    waitForServerToStart(server);
    assertNotNull(server.getRemotingService().getAcceptor("Acceptor1"));
    assertNotNull(server.getRemotingService().getAcceptor("Acceptor2"));
}

33. MQTTConnectionManager#createServerSession()

View license
/**
    * Creates an internal Server Session.
    *
    * @param username
    * @param password
    * @return
    * @throws Exception
    */
ServerSessionImpl createServerSession(String username, String password) throws Exception {
    String id = UUIDGenerator.getInstance().generateStringUUID();
    ActiveMQServer server = session.getServer();
    ServerSession serverSession = server.createSession(id, username, password, ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, session.getConnection(), MQTTUtil.SESSION_AUTO_COMMIT_SENDS, MQTTUtil.SESSION_AUTO_COMMIT_ACKS, MQTTUtil.SESSION_PREACKNOWLEDGE, MQTTUtil.SESSION_XA, null, session.getSessionCallback(), MQTTUtil.SESSION_AUTO_CREATE_QUEUE);
    return (ServerSessionImpl) serverSession;
}

34. ColocatedHAManager#stop()

View license
/**
    * stop any backups
    */
@Override
public void stop() {
    for (ActiveMQServer activeMQServer : backupServers.values()) {
        try {
            activeMQServer.stop();
        } catch (Exception e) {
            ActiveMQServerLogger.LOGGER.warn(e.getMessage(), e);
        }
    }
    backupServers.clear();
    started = false;
}

35. ColocatedHAManager#activateReplicatedBackup()

View license
/**
    * activate a backup server replicating from a specified node.
    *
    * decline and the requesting server can cast a re vote
    *
    * @param nodeID the id of the node to replicate from
    * @return true if the server was created and started
    * @throws Exception
    */
private synchronized boolean activateReplicatedBackup(SimpleString nodeID) throws Exception {
    Configuration configuration = server.getConfiguration().copy();
    ActiveMQServer backup = server.createBackupServer(configuration);
    try {
        TopologyMember member = server.getClusterManager().getDefaultConnection(null).getTopology().getMember(nodeID.toString());
        int portOffset = haPolicy.getBackupPortOffset() * (backupServers.size() + 1);
        String name = "colocated_backup_" + backupServers.size() + 1;
        //make sure we don't restart as we are colocated
        haPolicy.getBackupPolicy().setRestartBackup(false);
        //set the backup policy
        backup.setHAPolicy(haPolicy.getBackupPolicy());
        updateReplicatedConfiguration(configuration, name, portOffset, haPolicy.getExcludedConnectors(), haPolicy.getBackupPolicy().getScaleDownPolicy() == null);
        backup.addActivationParam(ActivationParams.REPLICATION_ENDPOINT, member);
        backupServers.put(configuration.getName(), backup);
        backup.start();
    } catch (Exception e) {
        backup.stop();
        ActiveMQServerLogger.LOGGER.activateReplicatedBackupFailed(e);
        return false;
    }
    ActiveMQServerLogger.LOGGER.activatingReplica(nodeID);
    return true;
}

36. ActiveMQTestBase#createServer()

View license
protected final ActiveMQServer createServer(final boolean realFiles, final Configuration configuration, final long pageSize, final long maxAddressSize, final Map<String, AddressSettings> settings) {
    ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(configuration, realFiles));
    if (settings != null) {
        for (Map.Entry<String, AddressSettings> setting : settings.entrySet()) {
            server.getAddressSettingsRepository().addMatch(setting.getKey(), setting.getValue());
        }
    }
    AddressSettings defaultSetting = new AddressSettings().setPageSizeBytes(pageSize).setMaxSizeBytes(maxAddressSize).setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE);
    server.getAddressSettingsRepository().addMatch("#", defaultSetting);
    return server;
}

37. ArtemisBrokerBase#createServer()

View license
protected final ActiveMQServer createServer(final boolean realFiles, final Configuration configuration, final int pageSize, final int maxAddressSize, final AddressFullMessagePolicy fullPolicy, final Map<String, AddressSettings> settings) {
    ActiveMQServer server = ActiveMQServers.newActiveMQServer(configuration, realFiles);
    if (settings != null) {
        for (Map.Entry<String, AddressSettings> setting : settings.entrySet()) {
            server.getAddressSettingsRepository().addMatch(setting.getKey(), setting.getValue());
        }
    }
    AddressSettings defaultSetting = new AddressSettings();
    defaultSetting.setPageSizeBytes(pageSize);
    defaultSetting.setMaxSizeBytes(maxAddressSize);
    defaultSetting.setAddressFullMessagePolicy(fullPolicy);
    server.getAddressSettingsRepository().addMatch("#", defaultSetting);
    return server;
}

38. ClusterTestBase#setupClusterConnection()

View license
protected void setupClusterConnection(final String name, final String uri, int server) throws Exception {
    ActiveMQServer serverFrom = servers[server];
    if (serverFrom == null) {
        throw new IllegalStateException("No server at node " + server);
    }
    ClusterConnectionConfiguration configuration = new ClusterConnectionConfiguration(new URI(uri)).setName(name);
    serverFrom.getConfiguration().addClusterConfiguration(configuration);
}

39. ClusterTestBase#setupDiscoveryClusterConnection()

View license
protected void setupDiscoveryClusterConnection(final String name, final int node, final String discoveryGroupName, final String address, final MessageLoadBalancingType messageLoadBalancingType, final int maxHops, final boolean netty) {
    ActiveMQServer server = servers[node];
    if (server == null) {
        throw new IllegalStateException("No server at node " + node);
    }
    TransportConfiguration connectorConfig = createTransportConfiguration(netty, false, generateParams(node, netty));
    server.getConfiguration().getConnectorConfigurations().put(name, connectorConfig);
    Configuration config = server.getConfiguration();
    ClusterConnectionConfiguration clusterConf = new ClusterConnectionConfiguration().setName(name).setAddress(address).setConnectorName(name).setRetryInterval(100).setDuplicateDetection(true).setMessageLoadBalancingType(messageLoadBalancingType).setMaxHops(maxHops).setConfirmationWindowSize(1024).setDiscoveryGroupName(discoveryGroupName);
    List<ClusterConnectionConfiguration> clusterConfs = config.getClusterConfigurations();
    clusterConfs.add(clusterConf);
}

40. ValidateAIOTest#testValidateAIO()

View license
@Test
public void testValidateAIO() throws Exception {
    Configuration config = createDefaultInVMConfig().setJournalType(// This will force AsyncIO
    JournalType.ASYNCIO);
    ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, true));
    try {
        server.start();
    } finally {
        server.stop();
    }
}

41. JMSServerDeployerTest#setUp()

View license
// Package protected ---------------------------------------------
// Protected -----------------------------------------------------
@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    DiscoveryGroupConfiguration dcg = new DiscoveryGroupConfiguration().setName("mygroup").setRefreshTimeout(5432).setDiscoveryInitialWaitTimeout(5432).setBroadcastEndpointFactory(new UDPBroadcastEndpointFactory().setGroupAddress("243.7.7.7").setGroupPort(12345).setLocalBindAddress("172.16.8.10"));
    config = createBasicConfig().addConnectorConfiguration("netty", new TransportConfiguration(NettyConnectorFactory.class.getName())).addDiscoveryGroupConfiguration("mygroup", dcg);
    ActiveMQServer server = createServer(false, config);
    jmsServer = new JMSServerManagerImpl(server);
    context = new InVMNamingContext();
    jmsServer.setRegistry(new JndiBindingRegistry(context));
    jmsServer.start();
}

42. JMSServerStartStopTest#setUp()

View license
@Override
@Before
public void setUp() throws Exception {
    FileConfiguration fc = new FileConfiguration();
    FileJMSConfiguration fileConfiguration = new FileJMSConfiguration();
    FileDeploymentManager deploymentManager = new FileDeploymentManager("server-start-stop-config1.xml");
    deploymentManager.addDeployable(fc);
    deploymentManager.addDeployable(fileConfiguration);
    deploymentManager.readConfiguration();
    ActiveMQJAASSecurityManager sm = new ActiveMQJAASSecurityManager(InVMLoginModule.class.getName(), new SecurityConfiguration());
    ActiveMQServer server = addServer(new ActiveMQServerImpl(fc, sm));
    jmsServer = new JMSServerManagerImpl(server, fileConfiguration);
    jmsServer.setRegistry(null);
}

43. PagingCounterTest#newActiveMQServer()

View license
private ActiveMQServer newActiveMQServer() throws Exception {
    OperationContextImpl.clearContext();
    ActiveMQServer server = super.createServer(true, false);
    AddressSettings defaultSetting = new AddressSettings().setPageSizeBytes(10 * 1024).setMaxSizeBytes(20 * 1024);
    server.getAddressSettingsRepository().addMatch("#", defaultSetting);
    return server;
}

44. ExtraStompTest#createPersistentServerWithStompMinLargeSize()

View license
protected JMSServerManager createPersistentServerWithStompMinLargeSize(int sz) throws Exception {
    Map<String, Object> params = new HashMap<>();
    params.put(TransportConstants.PROTOCOLS_PROP_NAME, StompProtocolManagerFactory.STOMP_PROTOCOL_NAME);
    params.put(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_STOMP_PORT);
    params.put(TransportConstants.STOMP_CONSUMERS_CREDIT, "-1");
    params.put(TransportConstants.STOMP_MIN_LARGE_MESSAGE_SIZE, sz);
    TransportConfiguration stompTransport = new TransportConfiguration(NettyAcceptorFactory.class.getName(), params);
    Configuration config = createBasicConfig().setPersistenceEnabled(true).addAcceptorConfiguration(stompTransport).addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
    ActiveMQServer activeMQServer = addServer(ActiveMQServers.newActiveMQServer(config, defUser, defPass));
    JMSConfiguration jmsConfig = new JMSConfigurationImpl();
    jmsConfig.getQueueConfigurations().add(new JMSQueueConfigurationImpl().setName(getQueueName()).setBindings(getQueueName()));
    jmsConfig.getTopicConfigurations().add(new TopicConfigurationImpl().setName(getTopicName()).setBindings(getTopicName()));
    server = new JMSServerManagerImpl(activeMQServer, jmsConfig);
    server.setRegistry(new JndiBindingRegistry((new InVMNamingContext())));
    return server;
}

45. ExtraStompTest#createServerWithExtraStompOptions()

View license
protected JMSServerManager createServerWithExtraStompOptions(String ttl, Boolean enableMessageID) throws Exception {
    Map<String, Object> params = new HashMap<>();
    params.put(TransportConstants.PROTOCOLS_PROP_NAME, StompProtocolManagerFactory.STOMP_PROTOCOL_NAME);
    params.put(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_STOMP_PORT);
    if (ttl != null) {
        params.put(TransportConstants.CONNECTION_TTL, ttl);
    }
    if (enableMessageID != null) {
        params.put(TransportConstants.STOMP_ENABLE_MESSAGE_ID, enableMessageID);
    }
    params.put(TransportConstants.STOMP_CONSUMERS_CREDIT, "-1");
    TransportConfiguration stompTransport = new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params);
    Configuration config = createBasicConfig().setPersistenceEnabled(false).addAcceptorConfiguration(stompTransport).addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY));
    ActiveMQServer activeMQServer = addServer(ActiveMQServers.newActiveMQServer(config, defUser, defPass));
    JMSConfiguration jmsConfig = new JMSConfigurationImpl();
    jmsConfig.getQueueConfigurations().add(new JMSQueueConfigurationImpl().setName(getQueueName()).setDurable(false).setBindings(getQueueName()));
    jmsConfig.getTopicConfigurations().add(new TopicConfigurationImpl().setName(getTopicName()).setBindings(getTopicName()));
    server = new JMSServerManagerImpl(activeMQServer, jmsConfig);
    server.setRegistry(new JndiBindingRegistry(new InVMNamingContext()));
    return server;
}

46. ExtraStompTest#createServerWithStompInterceptor()

View license
protected JMSServerManager createServerWithStompInterceptor(List<String> stompIncomingInterceptor, List<String> stompOutgoingInterceptor) throws Exception {
    Map<String, Object> params = new HashMap<>();
    params.put(TransportConstants.PROTOCOLS_PROP_NAME, StompProtocolManagerFactory.STOMP_PROTOCOL_NAME);
    params.put(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_STOMP_PORT);
    params.put(TransportConstants.STOMP_CONSUMERS_CREDIT, "-1");
    TransportConfiguration stompTransport = new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params);
    Configuration config = createBasicConfig().setPersistenceEnabled(false).addAcceptorConfiguration(stompTransport).addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY)).setIncomingInterceptorClassNames(stompIncomingInterceptor).setOutgoingInterceptorClassNames(stompOutgoingInterceptor);
    ActiveMQServer hornetQServer = addServer(ActiveMQServers.newActiveMQServer(config, defUser, defPass));
    JMSConfiguration jmsConfig = new JMSConfigurationImpl();
    jmsConfig.getQueueConfigurations().add(new JMSQueueConfigurationImpl().setName(getQueueName()).setDurable(false).setBindings(getQueueName()));
    jmsConfig.getTopicConfigurations().add(new TopicConfigurationImpl().setName(getTopicName()).setBindings(getTopicName()));
    server = new JMSServerManagerImpl(hornetQServer, jmsConfig);
    server.setRegistry(new JndiBindingRegistry(new InVMNamingContext()));
    return server;
}

47. StompTestBase#createServer()

Project: activemq-artemis
Source File: StompTestBase.java
View license
/**
    * @return
    * @throws Exception
    */
protected JMSServerManager createServer() throws Exception {
    Map<String, Object> params = new HashMap<>();
    params.put(TransportConstants.PROTOCOLS_PROP_NAME, StompProtocolManagerFactory.STOMP_PROTOCOL_NAME);
    params.put(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_STOMP_PORT);
    params.put(TransportConstants.STOMP_CONSUMERS_CREDIT, "-1");
    TransportConfiguration stompTransport = new TransportConfiguration(NettyAcceptorFactory.class.getName(), params);
    TransportConfiguration allTransport = new TransportConfiguration(NettyAcceptorFactory.class.getName());
    Configuration config = createBasicConfig().setPersistenceEnabled(false).addAcceptorConfiguration(stompTransport).addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
    config.addAcceptorConfiguration(allTransport);
    ActiveMQServer activeMQServer = addServer(ActiveMQServers.newActiveMQServer(config, defUser, defPass));
    JMSConfiguration jmsConfig = new JMSConfigurationImpl();
    jmsConfig.getQueueConfigurations().add(new JMSQueueConfigurationImpl().setName(getQueueName()).setDurable(false).setBindings(getQueueName()));
    jmsConfig.getTopicConfigurations().add(new TopicConfigurationImpl().setName(getTopicName()).setBindings(getTopicName()));
    server = new JMSServerManagerImpl(activeMQServer, jmsConfig);
    server.setRegistry(new JndiBindingRegistry(new InVMNamingContext()));
    return server;
}

48. StompWebSocketTest#createServer()

View license
/**
    * @return
    * @throws Exception
    */
private JMSServerManager createServer() throws Exception {
    Map<String, Object> params = new HashMap<>();
    params.put(TransportConstants.PROTOCOLS_PROP_NAME, StompProtocolManagerFactory.STOMP_PROTOCOL_NAME);
    params.put(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_STOMP_PORT + 1);
    TransportConfiguration stompTransport = new TransportConfiguration(NettyAcceptorFactory.class.getName(), params);
    Configuration config = createBasicConfig().addAcceptorConfiguration(stompTransport).addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())).addQueueConfiguration(new CoreQueueConfiguration().setAddress(getQueueName()).setName(getQueueName()).setDurable(false));
    ActiveMQServer activeMQServer = addServer(ActiveMQServers.newActiveMQServer(config));
    JMSConfiguration jmsConfig = new JMSConfigurationImpl();
    server = new JMSServerManagerImpl(activeMQServer, jmsConfig);
    server.setRegistry(null);
    return server;
}

49. StompV11TestBase#createServer()

View license
/**
    * @return
    * @throws Exception
    */
protected JMSServerManager createServer() throws Exception {
    Map<String, Object> params = new HashMap<>();
    params.put(TransportConstants.PROTOCOLS_PROP_NAME, StompProtocolManagerFactory.STOMP_PROTOCOL_NAME);
    params.put(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_STOMP_PORT);
    params.put(TransportConstants.STOMP_CONSUMERS_CREDIT, "-1");
    TransportConfiguration stompTransport = new TransportConfiguration(NettyAcceptorFactory.class.getName(), params);
    Configuration config = createBasicConfig().setPersistenceEnabled(persistenceEnabled).addAcceptorConfiguration(stompTransport).addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
    ActiveMQServer activeMQServer = addServer(ActiveMQServers.newActiveMQServer(config, defUser, defPass));
    JMSConfiguration jmsConfig = new JMSConfigurationImpl();
    jmsConfig.getQueueConfigurations().add(new JMSQueueConfigurationImpl().setName(getQueueName()).setBindings(getQueueName()));
    jmsConfig.getTopicConfigurations().add(new TopicConfigurationImpl().setName(getTopicName()).setBindings(getTopicName()));
    server = new JMSServerManagerImpl(activeMQServer, jmsConfig);
    server.setRegistry(new JndiBindingRegistry(new InVMNamingContext()));
    return server;
}

50. ManifestTest#testManifestEntries()

Project: activemq-artemis
Source File: ManifestTest.java
View license
// Constants -----------------------------------------------------
// Static --------------------------------------------------------
// Attributes ----------------------------------------------------
// Constructors --------------------------------------------------
// Public --------------------------------------------------------
@Test
public void testManifestEntries() throws Exception {
    Properties props = System.getProperties();
    String userDir = props.getProperty("build.lib");
    UnitTestLogger.LOGGER.trace("userDir is " + userDir);
    // The jar must be there
    File file = new File("build/jars", "activemq-core.jar");
    Assert.assertTrue(file.exists());
    // Open the jar and load MANIFEST.MF
    JarFile jar = new JarFile(file);
    Manifest manifest = jar.getManifest();
    ActiveMQServer server = ActiveMQServers.newActiveMQServer(createBasicConfig());
    ConnectionMetaData meta = new ActiveMQConnectionMetaData(server.getVersion());
    // Compare the value from ConnectionMetaData and MANIFEST.MF
    Attributes attrs = manifest.getMainAttributes();
    Assert.assertEquals(meta.getProviderVersion(), attrs.getValue("ActiveMQ-Version"));
}

51. ExpiryLargeMessageTest#testCompatilityWithLinks()

View license
/**
    * Tests if the system would still couple with old data where the LargeMessage was linked to its previous copy
    *
    * @throws Exception
    */
@Test
public void testCompatilityWithLinks() throws Exception {
    ActiveMQServer server = createServer(true);
    server.getConfiguration().setMessageExpiryScanPeriod(600000);
    AddressSettings setting = new AddressSettings().setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE).setMaxDeliveryAttempts(5).setMaxSizeBytes(-1).setPageSizeBytes(10 * 1024).setExpiryAddress(EXPIRY).setDeadLetterAddress(DLQ);
    server.getAddressSettingsRepository().addMatch(MY_QUEUE.toString(), setting);
    server.getAddressSettingsRepository().addMatch(EXPIRY.toString(), setting);
    server.start();
    server.createQueue(EXPIRY, EXPIRY, null, true, false);
    server.createQueue(DLQ, DLQ, null, true, false);
    server.createQueue(MY_QUEUE, MY_QUEUE, null, true, false);
    ServerLocator locator = createInVMNonHALocator();
    ClientSessionFactory sf = addSessionFactory(createSessionFactory(locator));
    ClientSession session = sf.createSession(true, true, 0);
    byte[] bufferSample = new byte[messageSize];
    for (int i = 0; i < bufferSample.length; i++) {
        bufferSample[i] = getSamplebyte(i);
    }
    ClientProducer producer = session.createProducer(MY_QUEUE);
    long timeToExpiry = System.currentTimeMillis() + 1000;
    for (int i = 0; i < numberOfMessages; i++) {
        ClientMessage message = session.createMessage(true);
        message.putIntProperty("count", i);
        // Everything is going to be a large message
        message.putBooleanProperty("tst-large", true);
        message.setBodyInputStream(createFakeLargeStream(messageSize));
        message.setExpiration(timeToExpiry);
        producer.send(message);
    }
    server.stop();
    server.start();
    sf = createSessionFactory(locator);
    session = sf.createSession(true, true, 0);
    session.start();
    Thread.sleep(1500);
    ClientConsumer cons = session.createConsumer(MY_QUEUE);
    assertNull(cons.receive(1000));
    session.close();
    session = sf.createSession(false, false);
    cons = session.createConsumer(EXPIRY);
    session.start();
    ClientMessage msg = cons.receive(5000);
    assertNotNull(msg);
    msg.acknowledge();
    session.rollback();
    server.stop();
    // rename the file, simulating old behaviour
    long messageID = msg.getMessageID();
    long oldID = msg.getLongProperty(Message.HDR_ORIG_MESSAGE_ID);
    File largeMessagesFileDir = new File(getLargeMessagesDir());
    File oldFile = new File(largeMessagesFileDir, oldID + ".msg");
    File currentFile = new File(largeMessagesFileDir, messageID + ".msg");
    currentFile.renameTo(oldFile);
    server.start();
    sf = createSessionFactory(locator);
    session = sf.createSession(true, true, 0);
    session.start();
    cons = session.createConsumer(EXPIRY);
    for (int i = 0; i < numberOfMessages; i++) {
        ClientMessage message = cons.receive(5000);
        assertNotNull(message);
        if (i % 10 == 0) {
            System.out.println("Received " + i);
        }
        for (int location = 0; location < messageSize; location++) {
            assertEquals(getSamplebyte(location), message.getBodyBuffer().readByte());
        }
        message.acknowledge();
    }
    session.commit();
    session.close();
}

52. InterruptedLargeMessageTest#testSendPreparedXA()

View license
@Test
public void testSendPreparedXA() throws Exception {
    ClientSession session = null;
    LargeMessageTestInterceptorIgnoreLastPacket.disableInterrupt();
    ActiveMQServer server = createServer(true, createDefaultConfig(isNetty()), 10000, 20000, new HashMap<String, AddressSettings>());
    server.getConfiguration().getIncomingInterceptorClassNames().add(LargeMessageTestInterceptorIgnoreLastPacket.class.getName());
    server.start();
    locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true);
    ClientSessionFactory sf = createSessionFactory(locator);
    session = sf.createSession(true, false, false);
    Xid xid1 = newXID();
    Xid xid2 = newXID();
    session.createQueue(ADDRESS, ADDRESS, true);
    ClientProducer producer = session.createProducer(ADDRESS);
    session.start(xid1, XAResource.TMNOFLAGS);
    for (int i = 0; i < 10; i++) {
        Message clientFile = createLargeClientMessageStreaming(session, LARGE_MESSAGE_SIZE, true);
        clientFile.putIntProperty("txid", 1);
        producer.send(clientFile);
    }
    session.end(xid1, XAResource.TMSUCCESS);
    session.prepare(xid1);
    session.start(xid2, XAResource.TMNOFLAGS);
    for (int i = 0; i < 10; i++) {
        Message clientFile = createLargeClientMessageStreaming(session, LARGE_MESSAGE_SIZE, true);
        clientFile.putIntProperty("txid", 2);
        clientFile.putIntProperty("i", i);
        producer.send(clientFile);
    }
    session.end(xid2, XAResource.TMSUCCESS);
    session.prepare(xid2);
    session.close();
    sf.close();
    server.stop(false);
    server.start();
    for (int start = 0; start < 2; start++) {
        System.out.println("Start " + start);
        sf = createSessionFactory(locator);
        if (start == 0) {
            session = sf.createSession(true, false, false);
            session.commit(xid1, false);
            session.close();
        }
        session = sf.createSession(false, false, false);
        ClientConsumer cons1 = session.createConsumer(ADDRESS);
        session.start();
        for (int i = 0; i < 10; i++) {
            log.info("I = " + i);
            ClientMessage msg = cons1.receive(5000);
            Assert.assertNotNull(msg);
            Assert.assertEquals(1, msg.getIntProperty("txid").intValue());
            msg.acknowledge();
        }
        if (start == 1) {
            session.commit();
        } else {
            session.rollback();
        }
        session.close();
        sf.close();
        server.stop();
        server.start();
    }
    server.stop();
    validateNoFilesOnLargeDir(server.getConfiguration().getLargeMessagesDirectory(), 10);
    server.start();
    sf = createSessionFactory(locator);
    session = sf.createSession(true, false, false);
    session.rollback(xid2);
    sf.close();
    server.stop();
    server.start();
    server.stop();
    validateNoFilesOnLargeDir();
}

53. ExpiryLargeMessageTest#testExpiryMessagesThenDLQ()

View license
// Attributes ----------------------------------------------------
// Static --------------------------------------------------------
// Constructors --------------------------------------------------
// Public --------------------------------------------------------
@Test
public void testExpiryMessagesThenDLQ() throws Exception {
    ActiveMQServer server = createServer(true);
    server.getConfiguration().setMessageExpiryScanPeriod(600000);
    AddressSettings setting = new AddressSettings().setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE).setMaxDeliveryAttempts(5).setMaxSizeBytes(50 * 1024).setPageSizeBytes(10 * 1024).setExpiryAddress(EXPIRY).setDeadLetterAddress(DLQ);
    server.getAddressSettingsRepository().addMatch(MY_QUEUE.toString(), setting);
    server.getAddressSettingsRepository().addMatch(EXPIRY.toString(), setting);
    server.start();
    server.createQueue(EXPIRY, EXPIRY, null, true, false);
    server.createQueue(DLQ, DLQ, null, true, false);
    server.createQueue(MY_QUEUE, MY_QUEUE, null, true, false);
    ServerLocator locator = createInVMNonHALocator();
    ClientSessionFactory sf = addSessionFactory(createSessionFactory(locator));
    ClientSession session = sf.createSession(true, true, 0);
    byte[] bufferSample = new byte[messageSize];
    for (int i = 0; i < bufferSample.length; i++) {
        bufferSample[i] = getSamplebyte(i);
    }
    ClientProducer producer = session.createProducer(MY_QUEUE);
    long timeToExpiry = System.currentTimeMillis() + 1000;
    for (int i = 0; i < numberOfMessages; i++) {
        ClientMessage message = session.createMessage(true);
        message.putIntProperty("count", i);
        // Send a few regular messages first, then all is just large messages
        if (i % 2 == 0) {
            message.putBooleanProperty("tst-large", false);
            message.getBodyBuffer().writeBytes(bufferSample);
        } else {
            message.putBooleanProperty("tst-large", true);
            message.setBodyInputStream(createFakeLargeStream(messageSize));
        }
        message.setExpiration(timeToExpiry);
        producer.send(message);
    }
    session.close();
    server.stop();
    server.start();
    Queue queueExpiry = server.locateQueue(EXPIRY);
    Queue myQueue = server.locateQueue(MY_QUEUE);
    sf = createSessionFactory(locator);
    Thread.sleep(1500);
    long timeout = System.currentTimeMillis() + 5000;
    while (timeout > System.currentTimeMillis() && getMessageCount(queueExpiry) != numberOfMessages) {
        // What the Expiry Scan would be doing
        myQueue.expireReferences();
        Thread.sleep(50);
    }
    assertEquals(50, getMessageCount(queueExpiry));
    session = sf.createSession(false, false);
    ClientConsumer cons = session.createConsumer(EXPIRY);
    session.start();
    // Consume half of the messages to make sure all the messages are paging (on the second try)
    for (int i = 0; i < numberOfMessages / 2; i++) {
        ClientMessage msg = cons.receive(5000);
        assertNotNull(msg);
        msg.acknowledge();
    }
    session.commit();
    cons.close();
    for (int rep = 0; rep < 6; rep++) {
        cons = session.createConsumer(EXPIRY);
        session.start();
        log.info("Trying " + rep);
        for (int i = 0; i < numberOfMessages / 2; i++) {
            ClientMessage message = cons.receive(5000);
            assertNotNull(message);
            if (i % 10 == 0) {
                System.out.println("Received " + i);
            }
            for (int location = 0; location < messageSize; location++) {
                assertEquals(getSamplebyte(location), message.getBodyBuffer().readByte());
            }
            message.acknowledge();
        }
        session.rollback();
        cons.close();
        session.close();
        sf.close();
        if (rep == 0) {
            // restart the server at the first try
            server.stop();
            server.start();
        }
        sf = createSessionFactory(locator);
        session = sf.createSession(false, false);
        session.start();
    }
    cons = session.createConsumer(EXPIRY);
    session.start();
    assertNull(cons.receiveImmediate());
    cons.close();
    session.close();
    sf.close();
    for (int rep = 0; rep < 2; rep++) {
        sf = createSessionFactory(locator);
        session = sf.createSession(false, false);
        cons = session.createConsumer(DLQ);
        session.start();
        for (int i = 0; i < numberOfMessages / 2; i++) {
            ClientMessage message = cons.receive(5000);
            assertNotNull(message);
            if (i % 10 == 0) {
                System.out.println("Received " + i);
            }
            for (int location = 0; location < messageSize; location++) {
                assertEquals(getSamplebyte(location), message.getBodyBuffer().readByte());
            }
            message.acknowledge();
        }
        if (rep == 0) {
            session.rollback();
            session.close();
            sf.close();
            server.stop();
            server.start();
        }
    }
    session.commit();
    assertNull(cons.receiveImmediate());
    session.close();
    sf.close();
    locator.close();
    validateNoFilesOnLargeDir();
}

54. InterruptedLargeMessageTest#testConsumeAfterRestart()

View license
@Test
public void testConsumeAfterRestart() throws Exception {
    ClientSession session = null;
    LargeMessageTestInterceptorIgnoreLastPacket.clearInterrupt();
    ActiveMQServer server = createServer(true, isNetty());
    server.start();
    QueueFactory original = server.getQueueFactory();
    locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true);
    ClientSessionFactory sf = createSessionFactory(locator);
    session = sf.createSession(false, true, true);
    session.createQueue(ADDRESS, ADDRESS, true);
    ClientProducer producer = session.createProducer(ADDRESS);
    for (int i = 0; i < 10; i++) {
        Message clientFile = createLargeClientMessageStreaming(session, LARGE_MESSAGE_SIZE, true);
        producer.send(clientFile);
    }
    session.commit();
    session.close();
    sf.close();
    server.stop();
    server.start();
    sf = createSessionFactory(locator);
    session = sf.createSession(false, false);
    ClientConsumer cons = session.createConsumer(ADDRESS);
    session.start();
    for (int i = 0; i < 10; i++) {
        ClientMessage msg = cons.receive(5000);
        Assert.assertNotNull(msg);
        msg.saveToOutputStream(new java.io.OutputStream() {

            @Override
            public void write(int b) throws IOException {
            }
        });
        msg.acknowledge();
        session.commit();
    }
    ((ActiveMQServerImpl) server).replaceQueueFactory(original);
    server.stop(false);
    server.start();
    server.stop();
    validateNoFilesOnLargeDir();
}

55. TransactionDurabilityTest#testRolledBackAcknowledgeWithSameMessageAckedByOtherSession()

View license
/*
    * This tests the following situation:
    *
    * (With the old implementation)
    * Currently when a new persistent message is routed to persistent queues, the message is first stored, then the message is routed.
    * Let's say it has been routed to two different queues A, B.
    * Ref R1 gets consumed and acknowledged by transacted session S1, this decrements the ref count and causes an acknowledge record to be written to storage,
    * transactionally, but it's not committed yet.
    * Ref R2 then gets consumed and acknowledged by non transacted session S2, this causes a delete record to be written to storage.
    * R1 then rolls back, and the server is restarted - unfortunatelt since the delete record was written R1 is not ready to be consumed again.
    *
    * It's therefore crucial the messages aren't deleted from storage until AFTER any ack records are committed to storage.
    *
    *
    */
@Test
public void testRolledBackAcknowledgeWithSameMessageAckedByOtherSession() throws Exception {
    final SimpleString testAddress = new SimpleString("testAddress");
    final SimpleString queue1 = new SimpleString("queue1");
    final SimpleString queue2 = new SimpleString("queue2");
    ActiveMQServer server = createServer(true, createDefaultInVMConfig());
    server.start();
    ServerLocator locator = createInVMNonHALocator();
    ClientSessionFactory sf = createSessionFactory(locator);
    ClientSession session1 = addClientSession(sf.createSession(false, true, true));
    ClientSession session2 = addClientSession(sf.createSession(false, false, false));
    session1.createQueue(testAddress, queue1, null, true);
    session1.createQueue(testAddress, queue2, null, true);
    ClientProducer producer = session1.createProducer(testAddress);
    ClientMessage message = session1.createMessage(true);
    producer.send(message);
    session1.start();
    session2.start();
    ClientConsumer consumer1 = session1.createConsumer(queue1);
    ClientConsumer consumer2 = session2.createConsumer(queue2);
    ClientMessage m1 = consumer1.receive(1000);
    Assert.assertNotNull(m1);
    ClientMessage m2 = consumer2.receive(1000);
    Assert.assertNotNull(m2);
    m2.acknowledge();
    // Don't commit session 2
    m1.acknowledge();
    session2.rollback();
    session1.close();
    session2.close();
    server.stop();
    server.start();
    sf = createSessionFactory(locator);
    session1 = addClientSession(sf.createSession(false, true, true));
    session2 = addClientSession(sf.createSession(false, true, true));
    session1.start();
    session2.start();
    consumer1 = session1.createConsumer(queue1);
    consumer2 = session2.createConsumer(queue2);
    m1 = consumer1.receiveImmediate();
    Assert.assertNull(m1);
    m2 = consumer2.receive(1000);
    Assert.assertNotNull(m2);
    m2.acknowledge();
    session1.close();
    session2.close();
    server.stop();
    server.start();
    sf = createSessionFactory(locator);
    session1 = addClientSession(sf.createSession(false, true, true));
    session2 = addClientSession(sf.createSession(false, true, true));
    session1.start();
    session2.start();
    consumer1 = session1.createConsumer(queue1);
    consumer2 = session2.createConsumer(queue2);
    m1 = consumer1.receiveImmediate();
    Assert.assertNull(m1);
    m2 = consumer2.receiveImmediate();
    Assert.assertNull(m2);
    session1.close();
    session2.close();
    locator.close();
    server.stop();
}

56. InterruptedLargeMessageTest#testInterruptLargeMessageSend()

View license
@Test
public void testInterruptLargeMessageSend() throws Exception {
    ClientSession session = null;
    LargeMessageTestInterceptorIgnoreLastPacket.clearInterrupt();
    ActiveMQServer server = createServer(true, isNetty());
    server.getConfiguration().getIncomingInterceptorClassNames().add(LargeMessageTestInterceptorIgnoreLastPacket.class.getName());
    server.start();
    locator.setBlockOnNonDurableSend(false).setBlockOnDurableSend(false);
    ClientSessionFactory sf = createSessionFactory(locator);
    session = sf.createSession(false, true, true);
    session.createQueue(ADDRESS, ADDRESS, true);
    ClientProducer producer = session.createProducer(ADDRESS);
    Message clientFile = createLargeClientMessageStreaming(session, LARGE_MESSAGE_SIZE, true);
    clientFile.setExpiration(System.currentTimeMillis());
    producer.send(clientFile);
    Thread.sleep(500);
    for (ServerSession srvSession : server.getSessions()) {
        ((ServerSessionImpl) srvSession).clearLargeMessage();
    }
    server.stop(false);
    ActiveMQTestBase.forceGC();
    server.start();
    server.stop();
    validateNoFilesOnLargeDir();
}

57. PagingTest#testDeleteQueueRestart()

Project: activemq-artemis
Source File: PagingTest.java
View license
@Test
public void testDeleteQueueRestart() throws Exception {
    clearDataRecreateServerDirs();
    // disable compact
    Configuration config = createDefaultInVMConfig().setJournalDirectory(getJournalDir()).setJournalSyncNonTransactional(false).setJournalCompactMinFiles(0);
    ActiveMQServer server = createServer(true, config, PagingTest.PAGE_SIZE, PagingTest.PAGE_MAX, new HashMap<String, AddressSettings>());
    server.start();
    final int numberOfMessages = 5000;
    locator = createInVMNonHALocator().setConsumerWindowSize(10 * 1024 * 1024).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true);
    SimpleString QUEUE2 = ADDRESS.concat("-2");
    ClientSessionFactory sf = locator.createSessionFactory();
    ClientSession session = sf.createSession(false, false, false);
    session.createQueue(PagingTest.ADDRESS, PagingTest.ADDRESS, null, true);
    session.createQueue(PagingTest.ADDRESS, QUEUE2, null, true);
    ClientProducer producer = session.createProducer(PagingTest.ADDRESS);
    // This is just to hold some messages as being delivered
    ClientConsumerInternal cons = (ClientConsumerInternal) session.createConsumer(ADDRESS);
    ClientConsumerInternal cons2 = (ClientConsumerInternal) session.createConsumer(QUEUE2);
    ClientMessage message = null;
    byte[] body = new byte[MESSAGE_SIZE];
    ByteBuffer bb = ByteBuffer.wrap(body);
    for (int j = 1; j <= MESSAGE_SIZE; j++) {
        bb.put(getSamplebyte(j));
    }
    for (int i = 0; i < numberOfMessages; i++) {
        message = session.createMessage(true);
        ActiveMQBuffer bodyLocal = message.getBodyBuffer();
        bodyLocal.writeBytes(body);
        producer.send(message);
        if (i % 1000 == 0) {
            session.commit();
        }
    }
    session.commit();
    producer.close();
    session.start();
    long timeout = System.currentTimeMillis() + 30000;
    // I want the buffer full to make sure there are pending messages on the server's side
    while (System.currentTimeMillis() < timeout && (cons.getBufferSize() < 1000 || cons2.getBufferSize() < 1000)) {
        System.out.println("cons1 buffer = " + cons.getBufferSize() + ", cons2 buffer = " + cons2.getBufferSize());
        Thread.sleep(100);
    }
    assertTrue(cons.getBufferSize() >= 1000);
    assertTrue(cons2.getBufferSize() >= 1000);
    session.close();
    Queue queue = server.locateQueue(QUEUE2);
    long deletedQueueID = queue.getID();
    server.destroyQueue(QUEUE2);
    sf.close();
    locator.close();
    locator = null;
    sf = null;
    server.stop();
    final HashMap<Integer, AtomicInteger> recordsType = countJournal(config);
    for (Map.Entry<Integer, AtomicInteger> entry : recordsType.entrySet()) {
        System.out.println(entry.getKey() + "=" + entry.getValue());
    }
    assertNull("The system is acking page records instead of just delete data", recordsType.get(new Integer(JournalRecordIds.ACKNOWLEDGE_CURSOR)));
    Pair<List<RecordInfo>, List<PreparedTransactionInfo>> journalData = loadMessageJournal(config);
    HashSet<Long> deletedQueueReferences = new HashSet<>();
    for (RecordInfo info : journalData.getA()) {
        if (info.getUserRecordType() == JournalRecordIds.ADD_REF) {
            DescribeJournal.ReferenceDescribe ref = (ReferenceDescribe) DescribeJournal.newObjectEncoding(info);
            if (ref.refEncoding.queueID == deletedQueueID) {
                deletedQueueReferences.add(new Long(info.id));
            }
        } else if (info.getUserRecordType() == JournalRecordIds.ACKNOWLEDGE_REF) {
            AckDescribe ref = (AckDescribe) DescribeJournal.newObjectEncoding(info);
            if (ref.refEncoding.queueID == deletedQueueID) {
                deletedQueueReferences.remove(new Long(info.id));
            }
        }
    }
    if (!deletedQueueReferences.isEmpty()) {
        for (Long value : deletedQueueReferences) {
            System.out.println("Deleted Queue still has a reference:" + value);
        }
        fail("Deleted queue still have references");
    }
    server.start();
    locator = createInVMNonHALocator();
    locator.setConsumerWindowSize(10 * 1024 * 1024);
    sf = locator.createSessionFactory();
    session = sf.createSession(false, false, false);
    cons = (ClientConsumerInternal) session.createConsumer(ADDRESS);
    session.start();
    for (int i = 0; i < numberOfMessages; i++) {
        message = cons.receive(5000);
        assertNotNull(message);
        message.acknowledge();
        if (i % 1000 == 0) {
            session.commit();
        }
    }
    session.commit();
    producer.close();
    session.close();
    queue = server.locateQueue(PagingTest.ADDRESS);
    assertEquals(0, getMessageCount(queue));
    timeout = System.currentTimeMillis() + 10000;
    while (timeout > System.currentTimeMillis() && queue.getPageSubscription().getPagingStore().isPaging()) {
        Thread.sleep(100);
    }
    assertFalse(queue.getPageSubscription().getPagingStore().isPaging());
    server.stop();
}

58. PersistentDivertTest#doTestPersistentDivertRestartBeforeConsume()

View license
public void doTestPersistentDivertRestartBeforeConsume(final boolean largeMessage) throws Exception {
    final String testAddress = "testAddress";
    final String forwardAddress1 = "forwardAddress1";
    final String forwardAddress2 = "forwardAddress2";
    final String forwardAddress3 = "forwardAddress3";
    DivertConfiguration divertConf1 = new DivertConfiguration().setName("divert1").setRoutingName("divert1").setAddress(testAddress).setForwardingAddress(forwardAddress1);
    DivertConfiguration divertConf2 = new DivertConfiguration().setName("divert2").setRoutingName("divert2").setAddress(testAddress).setForwardingAddress(forwardAddress2);
    DivertConfiguration divertConf3 = new DivertConfiguration().setName("divert3").setRoutingName("divert3").setAddress(testAddress).setForwardingAddress(forwardAddress3);
    Configuration config = createDefaultInVMConfig().addDivertConfiguration(divertConf1).addDivertConfiguration(divertConf2).addDivertConfiguration(divertConf3);
    ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config));
    server.start();
    ServerLocator locator = createInVMNonHALocator().setBlockOnAcknowledge(true).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true);
    ClientSessionFactory sf = createSessionFactory(locator);
    ClientSession session = sf.createSession(true, true, 0);
    final SimpleString queueName1 = new SimpleString("queue1");
    final SimpleString queueName2 = new SimpleString("queue2");
    final SimpleString queueName3 = new SimpleString("queue3");
    final SimpleString queueName4 = new SimpleString("queue4");
    session.createQueue(new SimpleString(forwardAddress1), queueName1, null, true);
    session.createQueue(new SimpleString(forwardAddress2), queueName2, null, true);
    session.createQueue(new SimpleString(forwardAddress3), queueName3, null, true);
    session.createQueue(new SimpleString(testAddress), queueName4, null, true);
    ClientProducer producer = session.createProducer(new SimpleString(testAddress));
    final int numMessages = 10;
    final SimpleString propKey = new SimpleString("testkey");
    for (int i = 0; i < numMessages; i++) {
        ClientMessage message = session.createMessage(true);
        message.putIntProperty(propKey, i);
        if (largeMessage) {
            message.setBodyInputStream(ActiveMQTestBase.createFakeLargeStream(minLargeMessageSize));
        }
        producer.send(message);
    }
    session.close();
    sf.close();
    server.stop();
    waitForServerToStop(server);
    server.start();
    ServerLocator locator2 = createInVMNonHALocator().setBlockOnDurableSend(true);
    sf = createSessionFactory(locator2);
    session = sf.createSession(false, true, true);
    session.start();
    ClientConsumer consumer1 = session.createConsumer(queueName1);
    ClientConsumer consumer2 = session.createConsumer(queueName2);
    ClientConsumer consumer3 = session.createConsumer(queueName3);
    ClientConsumer consumer4 = session.createConsumer(queueName4);
    for (int i = 0; i < numMessages; i++) {
        ClientMessage message = consumer1.receive(5000);
        Assert.assertNotNull(message);
        if (largeMessage) {
            checkLargeMessage(message);
        }
        Assert.assertEquals(i, message.getObjectProperty(propKey));
        message.acknowledge();
    }
    Assert.assertNull(consumer1.receiveImmediate());
    for (int i = 0; i < numMessages; i++) {
        ClientMessage message = consumer2.receive(5000);
        Assert.assertNotNull(message);
        if (largeMessage) {
            checkLargeMessage(message);
        }
        Assert.assertEquals(i, message.getObjectProperty(propKey));
        message.acknowledge();
    }
    Assert.assertNull(consumer2.receiveImmediate());
    for (int i = 0; i < numMessages; i++) {
        ClientMessage message = consumer3.receive(5000);
        Assert.assertNotNull(message);
        if (largeMessage) {
            checkLargeMessage(message);
        }
        Assert.assertEquals(i, message.getObjectProperty(propKey));
        message.acknowledge();
    }
    Assert.assertNull(consumer3.receiveImmediate());
    for (int i = 0; i < numMessages; i++) {
        ClientMessage message = consumer4.receive(5000);
        Assert.assertNotNull(message);
        if (largeMessage) {
            checkLargeMessage(message);
        }
        Assert.assertEquals(i, message.getObjectProperty(propKey));
        message.acknowledge();
    }
    Assert.assertNull(consumer4.receiveImmediate());
    session.close();
    sf.close();
    server.stop();
    waitForServerToStop(server);
    server.start();
    ServerLocator locator3 = createInVMNonHALocator().setBlockOnDurableSend(true);
    sf = createSessionFactory(locator3);
    session = sf.createSession(false, true, true);
    consumer1 = session.createConsumer(queueName1);
    consumer2 = session.createConsumer(queueName2);
    consumer3 = session.createConsumer(queueName3);
    consumer4 = session.createConsumer(queueName4);
    Assert.assertNull(consumer1.receiveImmediate());
    Assert.assertNull(consumer2.receiveImmediate());
    Assert.assertNull(consumer3.receiveImmediate());
    Assert.assertNull(consumer4.receiveImmediate());
}

59. HeuristicXATest#doHeuristicCompletionWithRestart()

View license
private void doHeuristicCompletionWithRestart(final boolean isCommit) throws Exception {
    Configuration configuration = createDefaultInVMConfig().setJMXManagementEnabled(true);
    ActiveMQServer server = createServer(true, configuration);
    server.setMBeanServer(mbeanServer);
    server.start();
    Xid xid = newXID();
    ClientSessionFactory sf = createSessionFactory(locator);
    ClientSession session = sf.createSession(true, false, false);
    session.createQueue(ADDRESS, ADDRESS, true);
    session.start(xid, XAResource.TMNOFLAGS);
    ClientProducer producer = session.createProducer(ADDRESS);
    ClientMessage msg = session.createMessage(true);
    msg.getBodyBuffer().writeString(body);
    producer.send(msg);
    session.end(xid, XAResource.TMSUCCESS);
    session.prepare(xid);
    session.close();
    ActiveMQServerControl jmxServer = ManagementControlHelper.createActiveMQServerControl(mbeanServer);
    String[] preparedTransactions = jmxServer.listPreparedTransactions();
    Assert.assertEquals(1, preparedTransactions.length);
    System.out.println(preparedTransactions[0]);
    if (isCommit) {
        jmxServer.commitPreparedTransaction(XidImpl.toBase64String(xid));
    } else {
        jmxServer.rollbackPreparedTransaction(XidImpl.toBase64String(xid));
    }
    preparedTransactions = jmxServer.listPreparedTransactions();
    Assert.assertEquals(0, preparedTransactions.length);
    if (isCommit) {
        Assert.assertEquals(1, getMessageCount(((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable())));
        session = sf.createSession(false, false, false);
        session.start();
        ClientConsumer consumer = session.createConsumer(ADDRESS);
        msg = consumer.receive(1000);
        Assert.assertNotNull(msg);
        msg.acknowledge();
        Assert.assertEquals(body, msg.getBodyBuffer().readString());
        session.commit();
        session.close();
    }
    Assert.assertEquals(0, getMessageCount(((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable())));
    server.stop();
    server.start();
    jmxServer = ManagementControlHelper.createActiveMQServerControl(mbeanServer);
    if (isCommit) {
        String[] listHeuristicCommittedTransactions = jmxServer.listHeuristicCommittedTransactions();
        Assert.assertEquals(1, listHeuristicCommittedTransactions.length);
        System.out.println(listHeuristicCommittedTransactions[0]);
    } else {
        String[] listHeuristicRolledBackTransactions = jmxServer.listHeuristicRolledBackTransactions();
        Assert.assertEquals(1, listHeuristicRolledBackTransactions.length);
        System.out.println(listHeuristicRolledBackTransactions[0]);
    }
}

60. HeuristicXATest#doRecoverHeuristicCompletedTxWithRestart()

View license
private void doRecoverHeuristicCompletedTxWithRestart(final boolean heuristicCommit) throws Exception {
    Configuration configuration = createDefaultInVMConfig().setJMXManagementEnabled(true);
    ActiveMQServer server = createServer(true, configuration);
    server.setMBeanServer(mbeanServer);
    server.start();
    Xid xid = newXID();
    ClientSessionFactory sf = createSessionFactory(locator);
    ClientSession session = sf.createSession(true, false, false);
    session.createQueue(ADDRESS, ADDRESS, true);
    session.start(xid, XAResource.TMNOFLAGS);
    ClientProducer producer = session.createProducer(ADDRESS);
    ClientMessage msg = session.createMessage(true);
    msg.getBodyBuffer().writeString(body);
    producer.send(msg);
    session.end(xid, XAResource.TMSUCCESS);
    session.prepare(xid);
    session.close();
    ActiveMQServerControl jmxServer = ManagementControlHelper.createActiveMQServerControl(mbeanServer);
    String[] preparedTransactions = jmxServer.listPreparedTransactions();
    Assert.assertEquals(1, preparedTransactions.length);
    System.out.println(preparedTransactions[0]);
    if (heuristicCommit) {
        jmxServer.commitPreparedTransaction(XidImpl.toBase64String(xid));
    } else {
        jmxServer.rollbackPreparedTransaction(XidImpl.toBase64String(xid));
    }
    preparedTransactions = jmxServer.listPreparedTransactions();
    Assert.assertEquals(0, preparedTransactions.length);
    if (heuristicCommit) {
        Assert.assertEquals(1, getMessageCount(((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable())));
        session = sf.createSession(false, false, false);
        session.start();
        ClientConsumer consumer = session.createConsumer(ADDRESS);
        msg = consumer.receive(1000);
        Assert.assertNotNull(msg);
        msg.acknowledge();
        Assert.assertEquals(body, msg.getBodyBuffer().readString());
        session.commit();
        session.close();
    }
    Assert.assertEquals(0, getMessageCount(((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable())));
    server.stop();
    server.start();
    // we need to recreate the locator and session sf
    sf = createSessionFactory(locator);
    jmxServer = ManagementControlHelper.createActiveMQServerControl(mbeanServer);
    if (heuristicCommit) {
        String[] listHeuristicCommittedTransactions = jmxServer.listHeuristicCommittedTransactions();
        Assert.assertEquals(1, listHeuristicCommittedTransactions.length);
        System.out.println(listHeuristicCommittedTransactions[0]);
    } else {
        String[] listHeuristicRolledBackTransactions = jmxServer.listHeuristicRolledBackTransactions();
        Assert.assertEquals(1, listHeuristicRolledBackTransactions.length);
        System.out.println(listHeuristicRolledBackTransactions[0]);
    }
    session = sf.createSession(true, false, false);
    Xid[] recoveredXids = session.recover(XAResource.TMSTARTRSCAN);
    Assert.assertEquals(1, recoveredXids.length);
    Assert.assertEquals(xid, recoveredXids[0]);
    Assert.assertEquals(0, session.recover(XAResource.TMENDRSCAN).length);
    session.close();
}

61. HeuristicXATest#doForgetHeuristicCompletedTxAndRestart()

View license
private void doForgetHeuristicCompletedTxAndRestart(final boolean heuristicCommit) throws Exception {
    Configuration configuration = createDefaultInVMConfig().setJMXManagementEnabled(true);
    ActiveMQServer server = createServer(true, configuration);
    server.setMBeanServer(mbeanServer);
    server.start();
    Xid xid = newXID();
    ClientSessionFactory sf = createSessionFactory(locator);
    ClientSession session = sf.createSession(true, false, false);
    session.createQueue(ADDRESS, ADDRESS, true);
    session.start(xid, XAResource.TMNOFLAGS);
    ClientProducer producer = session.createProducer(ADDRESS);
    ClientMessage msg = session.createMessage(true);
    msg.getBodyBuffer().writeBytes(new byte[123]);
    producer.send(msg);
    session.end(xid, XAResource.TMSUCCESS);
    session.prepare(xid);
    ActiveMQServerControl jmxServer = ManagementControlHelper.createActiveMQServerControl(mbeanServer);
    String[] preparedTransactions = jmxServer.listPreparedTransactions();
    Assert.assertEquals(1, preparedTransactions.length);
    System.out.println(preparedTransactions[0]);
    if (heuristicCommit) {
        jmxServer.commitPreparedTransaction(XidImpl.toBase64String(xid));
    } else {
        jmxServer.rollbackPreparedTransaction(XidImpl.toBase64String(xid));
    }
    preparedTransactions = jmxServer.listPreparedTransactions();
    Assert.assertEquals(0, preparedTransactions.length);
    session.forget(xid);
    session.close();
    if (heuristicCommit) {
        Assert.assertEquals(0, jmxServer.listHeuristicCommittedTransactions().length);
    } else {
        Assert.assertEquals(0, jmxServer.listHeuristicRolledBackTransactions().length);
    }
    server.stop();
    server.start();
    // we need to recreate the sf
    sf = createSessionFactory(locator);
    session = sf.createSession(true, false, false);
    Xid[] recoveredXids = session.recover(XAResource.TMSTARTRSCAN);
    Assert.assertEquals(0, recoveredXids.length);
    jmxServer = ManagementControlHelper.createActiveMQServerControl(mbeanServer);
    if (heuristicCommit) {
        Assert.assertEquals(0, jmxServer.listHeuristicCommittedTransactions().length);
    } else {
        Assert.assertEquals(0, jmxServer.listHeuristicRolledBackTransactions().length);
    }
    session.close();
}

62. InterruptedLargeMessageTest#testSendNonPersistentQueue()

View license
@Test
public void testSendNonPersistentQueue() throws Exception {
    ClientSession session = null;
    LargeMessageTestInterceptorIgnoreLastPacket.disableInterrupt();
    ActiveMQServer server = createServer(true, isNetty());
    server.start();
    locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true);
    ClientSessionFactory sf = createSessionFactory(locator);
    session = sf.createSession(false, true, true);
    session.createQueue(ADDRESS, ADDRESS, false);
    ClientProducer producer = session.createProducer(ADDRESS);
    for (int i = 0; i < 10; i++) {
        Message clientFile = createLargeClientMessageStreaming(session, LARGE_MESSAGE_SIZE, true);
        producer.send(clientFile);
    }
    session.commit();
    session.close();
    session = sf.createSession(false, false);
    ClientConsumer cons = session.createConsumer(ADDRESS);
    session.start();
    for (int h = 0; h < 5; h++) {
        for (int i = 0; i < 10; i++) {
            ClientMessage clientMessage = cons.receive(5000);
            Assert.assertNotNull(clientMessage);
            for (int countByte = 0; countByte < LARGE_MESSAGE_SIZE; countByte++) {
                Assert.assertEquals(ActiveMQTestBase.getSamplebyte(countByte), clientMessage.getBodyBuffer().readByte());
            }
            clientMessage.acknowledge();
        }
        session.rollback();
    }
    server.stop(false);
    server.start();
    server.stop();
    validateNoFilesOnLargeDir();
}

63. InterruptedLargeMessageTest#testRestartBeforeDelete()

View license
@Test
public void testRestartBeforeDelete() throws Exception {
    class NoPostACKQueue extends QueueImpl {

        NoPostACKQueue(long id, SimpleString address, SimpleString name, Filter filter, SimpleString user, PageSubscription pageSubscription, boolean durable, boolean temporary, boolean autoCreated, ScheduledExecutorService scheduledExecutor, PostOffice postOffice, StorageManager storageManager, HierarchicalRepository<AddressSettings> addressSettingsRepository, Executor executor) {
            super(id, address, name, filter, pageSubscription, user, durable, temporary, autoCreated, scheduledExecutor, postOffice, storageManager, addressSettingsRepository, executor);
        }

        @Override
        public void postAcknowledge(final MessageReference ref) {
            System.out.println("Ignoring postACK on message " + ref);
        }

        @Override
        public void deliverScheduledMessages() {
        }
    }
    class NoPostACKQueueFactory implements QueueFactory {

        final StorageManager storageManager;

        final PostOffice postOffice;

        final ScheduledExecutorService scheduledExecutor;

        final HierarchicalRepository<AddressSettings> addressSettingsRepository;

        final ExecutorFactory execFactory;

        NoPostACKQueueFactory(StorageManager storageManager, PostOffice postOffice, ScheduledExecutorService scheduledExecutor, HierarchicalRepository<AddressSettings> addressSettingsRepository, final ExecutorFactory execFactory) {
            this.storageManager = storageManager;
            this.postOffice = postOffice;
            this.scheduledExecutor = scheduledExecutor;
            this.addressSettingsRepository = addressSettingsRepository;
            this.execFactory = execFactory;
        }

        @Override
        public Queue createQueue(long persistenceID, SimpleString address, SimpleString name, Filter filter, PageSubscription pageSubscription, SimpleString user, boolean durable, boolean temporary, boolean autoCreated) {
            return new NoPostACKQueue(persistenceID, address, name, filter, user, pageSubscription, durable, temporary, autoCreated, scheduledExecutor, postOffice, storageManager, addressSettingsRepository, execFactory.getExecutor());
        }

        /* (non-Javadoc)
          * @see org.apache.activemq.artemis.core.server.QueueFactory#setPostOffice(org.apache.activemq.artemis.core.postoffice.PostOffice)
          */
        @Override
        public void setPostOffice(PostOffice postOffice) {
        }
    }
    ClientSession session = null;
    LargeMessageTestInterceptorIgnoreLastPacket.disableInterrupt();
    ActiveMQServer server = createServer(true, isNetty());
    server.start();
    QueueFactory original = server.getQueueFactory();
    ((ActiveMQServerImpl) server).replaceQueueFactory(new NoPostACKQueueFactory(server.getStorageManager(), server.getPostOffice(), server.getScheduledPool(), server.getAddressSettingsRepository(), server.getExecutorFactory()));
    locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true);
    ClientSessionFactory sf = createSessionFactory(locator);
    session = sf.createSession(false, true, true);
    session.createQueue(ADDRESS, ADDRESS, true);
    ClientProducer producer = session.createProducer(ADDRESS);
    for (int i = 0; i < 10; i++) {
        Message clientFile = createLargeClientMessageStreaming(session, LARGE_MESSAGE_SIZE, true);
        producer.send(clientFile);
    }
    session.commit();
    session.close();
    session = sf.createSession(false, false);
    ClientConsumer cons = session.createConsumer(ADDRESS);
    session.start();
    for (int i = 0; i < 10; i++) {
        ClientMessage msg = cons.receive(5000);
        Assert.assertNotNull(msg);
        msg.saveToOutputStream(new java.io.OutputStream() {

            @Override
            public void write(int b) throws IOException {
            }
        });
        msg.acknowledge();
        session.commit();
    }
    ((ActiveMQServerImpl) server).replaceQueueFactory(original);
    server.stop(false);
    server.start();
    server.stop();
    validateNoFilesOnLargeDir();
}

64. BridgeTest#testInjectedTransformer()

Project: activemq-artemis
Source File: BridgeTest.java
View license
@Test
public void testInjectedTransformer() throws Exception {
    final SimpleString ADDRESS = new SimpleString("myAddress");
    final SimpleString QUEUE = new SimpleString("myQueue");
    final String BRIDGE = "myBridge";
    ServiceRegistryImpl serviceRegistry = new ServiceRegistryImpl();
    Transformer transformer = new Transformer() {

        @Override
        public ServerMessage transform(ServerMessage message) {
            return null;
        }
    };
    serviceRegistry.addBridgeTransformer(BRIDGE, transformer);
    Configuration config = createDefaultInVMConfig().addConnectorConfiguration("in-vm", new TransportConfiguration(INVM_CONNECTOR_FACTORY));
    ActiveMQServer server = addServer(new ActiveMQServerImpl(config, null, null, null, serviceRegistry));
    server.start();
    server.waitForActivation(100, TimeUnit.MILLISECONDS);
    server.deployQueue(ADDRESS, QUEUE, null, false, false);
    List<String> connectors = new ArrayList<>();
    connectors.add("in-vm");
    server.deployBridge(new BridgeConfiguration().setName(BRIDGE).setQueueName(QUEUE.toString()).setForwardingAddress(ADDRESS.toString()).setStaticConnectors(connectors));
    Bridge bridge = server.getClusterManager().getBridges().get(BRIDGE);
    assertNotNull(bridge);
    assertEquals(transformer, ((BridgeImpl) bridge).getTransformer());
}

65. DivertTest#testInjectedTransformer()

Project: activemq-artemis
Source File: DivertTest.java
View license
@Test
public void testInjectedTransformer() throws Exception {
    final SimpleString ADDRESS = new SimpleString("myAddress");
    final String DIVERT = "myDivert";
    ServiceRegistryImpl serviceRegistry = new ServiceRegistryImpl();
    Transformer transformer = new Transformer() {

        @Override
        public ServerMessage transform(ServerMessage message) {
            return null;
        }
    };
    serviceRegistry.addDivertTransformer(DIVERT, transformer);
    ActiveMQServer server = addServer(new ActiveMQServerImpl(null, null, null, null, serviceRegistry));
    server.start();
    server.waitForActivation(100, TimeUnit.MILLISECONDS);
    server.deployQueue(ADDRESS, SimpleString.toSimpleString("myQueue"), null, false, false);
    server.deployDivert(new DivertConfiguration().setName(DIVERT).setAddress(ADDRESS.toString()).setForwardingAddress(ADDRESS.toString()));
    Collection<Binding> bindings = server.getPostOffice().getBindingsForAddress(ADDRESS).getBindings();
    Divert divert = null;
    for (Binding binding : bindings) {
        if (binding instanceof DivertBinding) {
            divert = ((DivertBinding) binding).getDivert();
        }
    }
    assertNotNull(divert);
    assertEquals(transformer, divert.getTransformer());
}

66. DeleteQueueRestartTest#internalDeleteQueueAndRestart()

View license
private void internalDeleteQueueAndRestart() throws Exception {
    ActiveMQServer server = createServer(true);
    server.start();
    ServerLocator locator = createInVMNonHALocator().setBlockOnDurableSend(true).setBlockOnNonDurableSend(true).setMinLargeMessageSize(1024 * 1024);
    ClientSessionFactory factory = createSessionFactory(locator);
    final ClientSession session = factory.createSession(false, true, true);
    session.createQueue(DeleteQueueRestartTest.ADDRESS, DeleteQueueRestartTest.ADDRESS, true);
    ClientProducer prod = session.createProducer(DeleteQueueRestartTest.ADDRESS);
    for (int i = 0; i < 100; i++) {
        ClientMessage msg = createBytesMessage(session, ActiveMQBytesMessage.TYPE, new byte[0], true);
        prod.send(msg);
    }
    final CountDownLatch count = new CountDownLatch(1);
    // Using another thread, as the deleteQueue is a blocked call
    new Thread() {

        @Override
        public void run() {
            try {
                session.deleteQueue(DeleteQueueRestartTest.ADDRESS);
                session.close();
                count.countDown();
            } catch (ActiveMQException e) {
            }
        }
    }.start();
    Assert.assertTrue(count.await(5, TimeUnit.SECONDS));
    server.stop();
    server.start();
    server.stop();
}

67. XmlImportExportStressTest#testHighVolume()

View license
@Test
public void testHighVolume() throws Exception {
    final String FILE_NAME = getTestDir() + "/export.out";
    final String QUEUE_NAME = "A1";
    ActiveMQServer server = createServer(true);
    server.start();
    ServerLocator locator = createInVMNonHALocator();
    ClientSessionFactory factory = locator.createSessionFactory();
    ClientSession session = factory.createSession(false, false, false);
    session.createQueue(QUEUE_NAME, QUEUE_NAME, true);
    ClientProducer producer = session.createProducer(QUEUE_NAME);
    ClientMessage msg = session.createMessage(true);
    final int SIZE = 10240;
    final int COUNT = 20000;
    byte[] bodyTst = new byte[SIZE];
    for (int i = 0; i < SIZE; i++) {
        bodyTst[i] = (byte) (i + 1);
    }
    msg.getBodyBuffer().writeBytes(bodyTst);
    assertEquals(bodyTst.length, msg.getBodySize());
    for (int i = 0; i < COUNT; i++) {
        producer.send(msg);
        if (i % 500 == 0) {
            System.out.println("Sent " + i);
            session.commit();
        }
    }
    session.commit();
    session.close();
    locator.close();
    server.stop();
    System.out.println("Writing XML...");
    FileOutputStream xmlOutputStream = new FileOutputStream(FILE_NAME);
    BufferedOutputStream bufferOut = new BufferedOutputStream(xmlOutputStream);
    XmlDataExporter xmlDataExporter = new XmlDataExporter();
    xmlDataExporter.process(bufferOut, getBindingsDir(), getJournalDir(), getPageDir(), getLargeMessagesDir());
    bufferOut.close();
    System.out.println("Done writing XML.");
    deleteDirectory(new File(getJournalDir()));
    deleteDirectory(new File(getBindingsDir()));
    deleteDirectory(new File(getPageDir()));
    deleteDirectory(new File(getLargeMessagesDir()));
    server.start();
    locator = createInVMNonHALocator();
    factory = locator.createSessionFactory();
    session = factory.createSession(false, false, true);
    ClientSession managementSession = factory.createSession(false, true, true);
    System.out.println("Reading XML...");
    FileInputStream xmlInputStream = new FileInputStream(FILE_NAME);
    XmlDataImporter xmlDataImporter = new XmlDataImporter();
    xmlDataImporter.process(xmlInputStream, session, managementSession);
    xmlInputStream.close();
    System.out.println("Done reading XML.");
    ClientConsumer consumer = session.createConsumer(QUEUE_NAME);
    session.start();
    for (int i = 0; i < COUNT; i++) {
        msg = consumer.receive(CONSUMER_TIMEOUT);
        assertNotNull(msg);
        msg.acknowledge();
        if (i % 500 == 0) {
            System.out.println("Received " + i);
            session.commit();
        }
        assertEquals(msg.getBodySize(), bodyTst.length);
        byte[] bodyRead = new byte[bodyTst.length];
        msg.getBodyBuffer().readBytes(bodyRead);
        assertEqualsByteArrays(bodyTst, bodyRead);
    }
    session.close();
    locator.close();
    server.stop();
    File temp = new File(FILE_NAME);
    temp.delete();
}

68. InterruptedLargeMessageTest#testForcedInterruptUsingJMS()

View license
@Test
public void testForcedInterruptUsingJMS() throws Exception {
    ActiveMQServer server = createServer(true, isNetty());
    server.start();
    SimpleString jmsAddress = new SimpleString("jms.queue.Test");
    server.createQueue(jmsAddress, jmsAddress, null, true, false);
    final AtomicInteger unexpectedErrors = new AtomicInteger(0);
    final AtomicInteger expectedErrors = new AtomicInteger(0);
    ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://0");
    Connection connection = cf.createConnection();
    Session session = connection.createSession(Session.SESSION_TRANSACTED);
    connection.start();
    final MessageConsumer consumer = session.createConsumer(session.createQueue(jmsAddress.toString()));
    Thread t = new Thread() {

        @Override
        public void run() {
            try {
                System.out.println("Receiving message");
                javax.jms.Message msg = consumer.receive(5000);
                if (msg == null) {
                    System.err.println("Message not received");
                    unexpectedErrors.incrementAndGet();
                    return;
                }
            } catch (JMSException e) {
                log.debug("This exception was ok as it was expected", e);
                expectedErrors.incrementAndGet();
            } catch (Throwable e) {
                log.warn("Captured unexpected exception", e);
                unexpectedErrors.incrementAndGet();
            }
        }
    };
    t.start();
    t.interrupt();
    t.join();
    Assert.assertEquals(0, unexpectedErrors.get());
    Assert.assertEquals(1, expectedErrors.get());
    session.close();
    server.stop();
}

69. InterruptedLargeMessageTest#testSendPaging()

View license
@Test
public void testSendPaging() throws Exception {
    ClientSession session = null;
    LargeMessageTestInterceptorIgnoreLastPacket.disableInterrupt();
    ActiveMQServer server = createServer(true, createDefaultConfig(isNetty()), 10000, 20000, new HashMap<String, AddressSettings>());
    // server.getConfiguration()
    // .getIncomingInterceptorClassNames()
    // .add(LargeMessageTestInterceptorIgnoreLastPacket.class.getName());
    server.start();
    locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true);
    ClientSessionFactory sf = createSessionFactory(locator);
    session = sf.createSession(false, true, true);
    session.createQueue(ADDRESS, ADDRESS, true);
    server.getPagingManager().getPageStore(ADDRESS).startPaging();
    ClientProducer producer = session.createProducer(ADDRESS);
    for (int i = 0; i < 10; i++) {
        Message clientFile = createLargeClientMessageStreaming(session, LARGE_MESSAGE_SIZE, true);
        producer.send(clientFile);
    }
    session.commit();
    validateNoFilesOnLargeDir(server.getConfiguration().getLargeMessagesDirectory(), 10);
    for (int h = 0; h < 5; h++) {
        session.close();
        sf.close();
        server.stop();
        server.start();
        sf = createSessionFactory(locator);
        session = sf.createSession(false, false);
        ClientConsumer cons = session.createConsumer(ADDRESS);
        session.start();
        for (int i = 0; i < 10; i++) {
            ClientMessage clientMessage = cons.receive(5000);
            Assert.assertNotNull(clientMessage);
            for (int countByte = 0; countByte < LARGE_MESSAGE_SIZE; countByte++) {
                Assert.assertEquals(ActiveMQTestBase.getSamplebyte(countByte), clientMessage.getBodyBuffer().readByte());
            }
            clientMessage.acknowledge();
        }
        if (h == 4) {
            session.commit();
        } else {
            session.rollback();
        }
        session.close();
        sf.close();
    }
    server.stop(false);
    server.start();
    validateNoFilesOnLargeDir();
}

70. LargeMessageAvoidLargeMessagesTest#testDLALargeMessage()

View license
//this test won't leave any large messages in the large-messages dir
//because after compression, the messages are regulars at server.
@Override
@Test
public void testDLALargeMessage() throws Exception {
    final int messageSize = (int) (3.5 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE);
    ClientSession session = null;
    ActiveMQServer server = createServer(true, isNetty());
    server.start();
    ClientSessionFactory sf = addSessionFactory(createSessionFactory(locator));
    session = addClientSession(sf.createSession(false, false, false));
    session.createQueue(ADDRESS, ADDRESS, true);
    session.createQueue(ADDRESS, ADDRESS.concat("-2"), true);
    SimpleString ADDRESS_DLA = ADDRESS.concat("-dla");
    AddressSettings addressSettings = new AddressSettings().setDeadLetterAddress(ADDRESS_DLA).setMaxDeliveryAttempts(1);
    server.getAddressSettingsRepository().addMatch("*", addressSettings);
    session.createQueue(ADDRESS_DLA, ADDRESS_DLA, true);
    ClientProducer producer = session.createProducer(ADDRESS);
    Message clientFile = createLargeClientMessageStreaming(session, messageSize, true);
    producer.send(clientFile);
    session.commit();
    session.start();
    ClientConsumer consumer = session.createConsumer(ADDRESS_DLA);
    ClientConsumer consumerRollback = session.createConsumer(ADDRESS);
    ClientMessage msg1 = consumerRollback.receive(1000);
    Assert.assertNotNull(msg1);
    msg1.acknowledge();
    session.rollback();
    consumerRollback.close();
    msg1 = consumer.receive(10000);
    Assert.assertNotNull(msg1);
    for (int i = 0; i < messageSize; i++) {
        Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), msg1.getBodyBuffer().readByte());
    }
    session.close();
    server.stop();
    server = createServer(true, isNetty());
    server.start();
    sf = createSessionFactory(locator);
    session = sf.createSession(false, false, false);
    session.start();
    consumer = session.createConsumer(ADDRESS_DLA);
    msg1 = consumer.receive(10000);
    Assert.assertNotNull(msg1);
    for (int i = 0; i < messageSize; i++) {
        Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), msg1.getBodyBuffer().readByte());
    }
    msg1.acknowledge();
    session.commit();
    //large message becomes a regular at server.
    validateNoFilesOnLargeDir(server.getConfiguration().getLargeMessagesDirectory(), 0);
    consumer = session.createConsumer(ADDRESS.concat("-2"));
    msg1 = consumer.receive(10000);
    Assert.assertNotNull(msg1);
    for (int i = 0; i < messageSize; i++) {
        Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), msg1.getBodyBuffer().readByte());
    }
    msg1.acknowledge();
    session.commit();
    session.close();
    validateNoFilesOnLargeDir();
}

71. LargeMessageCompressTest#testLargeMessageCompressionRestartAndCheckSize()

View license
@Test
public void testLargeMessageCompressionRestartAndCheckSize() throws Exception {
    final int messageSize = 1024 * 1024;
    ActiveMQServer server = createServer(true, isNetty());
    server.start();
    ClientSessionFactory sf = createSessionFactory(locator);
    ClientSession session = addClientSession(sf.createSession(false, false, false));
    session.createQueue(ADDRESS, ADDRESS, true);
    ClientProducer producer = session.createProducer(ADDRESS);
    byte[] msgs = new byte[1024 * 1024];
    for (int i = 0; i < msgs.length; i++) {
        msgs[i] = RandomUtil.randomByte();
    }
    Message clientFile = createLargeClientMessage(session, msgs, true);
    producer.send(clientFile);
    session.commit();
    session.close();
    sf.close();
    locator.close();
    server.stop();
    server = createServer(true, isNetty());
    server.start();
    locator = createFactory(isNetty());
    sf = createSessionFactory(locator);
    session = sf.createSession();
    session.start();
    ClientConsumer consumer = session.createConsumer(ADDRESS);
    ClientMessage msg1 = consumer.receive(1000);
    Assert.assertNotNull(msg1);
    assertEquals(messageSize, msg1.getBodySize());
    String testDir = getTestDir();
    File testFile = new File(testDir, "async_large_message");
    FileOutputStream output = new FileOutputStream(testFile);
    msg1.saveToOutputStream(output);
    msg1.acknowledge();
    session.commit();
    consumer.close();
    session.close();
    //verify
    FileInputStream input = new FileInputStream(testFile);
    for (int i = 0; i < messageSize; i++) {
        byte b = (byte) input.read();
        assertEquals("position = " + i, msgs[i], b);
    }
    input.close();
    testFile.delete();
    validateNoFilesOnLargeDir();
}

72. LargeMessageTest#testDLALargeMessage()

View license
@Test
public void testDLALargeMessage() throws Exception {
    final int messageSize = (int) (3.5 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE);
    ClientSession session = null;
    ActiveMQServer server = createServer(true, isNetty(), storeType);
    server.start();
    ClientSessionFactory sf = addSessionFactory(createSessionFactory(locator));
    session = addClientSession(sf.createSession(false, false, false));
    session.createQueue(ADDRESS, ADDRESS, true);
    session.createQueue(ADDRESS, ADDRESS.concat("-2"), true);
    SimpleString ADDRESS_DLA = ADDRESS.concat("-dla");
    AddressSettings addressSettings = new AddressSettings().setDeadLetterAddress(ADDRESS_DLA).setMaxDeliveryAttempts(1);
    server.getAddressSettingsRepository().addMatch("*", addressSettings);
    session.createQueue(ADDRESS_DLA, ADDRESS_DLA, true);
    ClientProducer producer = session.createProducer(ADDRESS);
    Message clientFile = createLargeClientMessageStreaming(session, messageSize, true);
    producer.send(clientFile);
    session.commit();
    session.start();
    ClientConsumer consumer = session.createConsumer(ADDRESS_DLA);
    ClientConsumer consumerRollback = session.createConsumer(ADDRESS);
    ClientMessage msg1 = consumerRollback.receive(1000);
    Assert.assertNotNull(msg1);
    msg1.acknowledge();
    session.rollback();
    consumerRollback.close();
    msg1 = consumer.receive(10000);
    Assert.assertNotNull(msg1);
    for (int i = 0; i < messageSize; i++) {
        Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), msg1.getBodyBuffer().readByte());
    }
    session.close();
    server.stop();
    server = createServer(true, isNetty(), storeType);
    server.start();
    sf = createSessionFactory(locator);
    session = sf.createSession(false, false, false);
    session.start();
    consumer = session.createConsumer(ADDRESS_DLA);
    msg1 = consumer.receive(10000);
    Assert.assertNotNull(msg1);
    for (int i = 0; i < messageSize; i++) {
        Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), msg1.getBodyBuffer().readByte());
    }
    msg1.acknowledge();
    session.commit();
    if (storeType != StoreConfiguration.StoreType.DATABASE) {
        validateNoFilesOnLargeDir(server.getConfiguration().getLargeMessagesDirectory(), isCompressedTest ? 0 : 1);
    }
    consumer = session.createConsumer(ADDRESS.concat("-2"));
    msg1 = consumer.receive(10000);
    Assert.assertNotNull(msg1);
    for (int i = 0; i < messageSize; i++) {
        Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), msg1.getBodyBuffer().readByte());
    }
    msg1.acknowledge();
    session.commit();
    session.close();
    if (storeType != StoreConfiguration.StoreType.DATABASE) {
        validateNoFilesOnLargeDir();
    }
}

73. LargeMessageTest#testDLAOnExpiryNonDurableMessage()

View license
@Test
public void testDLAOnExpiryNonDurableMessage() throws Exception {
    final int messageSize = (int) (3.5 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE);
    ClientSession session = null;
    ActiveMQServer server = createServer(true, isNetty(), storeType);
    server.start();
    ClientSessionFactory sf = addSessionFactory(createSessionFactory(locator));
    SimpleString ADDRESS_DLA = ADDRESS.concat("-dla");
    SimpleString ADDRESS_EXPIRY = ADDRESS.concat("-expiry");
    AddressSettings addressSettings = new AddressSettings().setDeadLetterAddress(ADDRESS_DLA).setExpiryAddress(ADDRESS_EXPIRY).setMaxDeliveryAttempts(1);
    server.getAddressSettingsRepository().addMatch("*", addressSettings);
    session = sf.createSession(false, false, false);
    session.createQueue(ADDRESS, ADDRESS, true);
    session.createQueue(ADDRESS_DLA, ADDRESS_DLA, true);
    session.createQueue(ADDRESS_EXPIRY, ADDRESS_EXPIRY, true);
    ClientProducer producer = session.createProducer(ADDRESS);
    Message clientFile = createLargeClientMessageStreaming(session, messageSize, false);
    clientFile.setExpiration(System.currentTimeMillis());
    producer.send(clientFile);
    session.commit();
    session.start();
    ClientConsumer consumerExpired = session.createConsumer(ADDRESS);
    // to kick expiry quicker than waiting reaper thread
    Assert.assertNull(consumerExpired.receiveImmediate());
    consumerExpired.close();
    ClientConsumer consumerExpiry = session.createConsumer(ADDRESS_EXPIRY);
    ClientMessage msg1 = consumerExpiry.receive(5000);
    assertTrue(msg1.isLargeMessage());
    Assert.assertNotNull(msg1);
    msg1.acknowledge();
    for (int j = 0; j < messageSize; j++) {
        Assert.assertEquals(ActiveMQTestBase.getSamplebyte(j), msg1.getBodyBuffer().readByte());
    }
    session.rollback();
    consumerExpiry.close();
    for (int i = 0; i < 10; i++) {
        consumerExpiry = session.createConsumer(ADDRESS_DLA);
        msg1 = consumerExpiry.receive(5000);
        Assert.assertNotNull(msg1);
        msg1.acknowledge();
        for (int j = 0; j < messageSize; j++) {
            Assert.assertEquals(ActiveMQTestBase.getSamplebyte(j), msg1.getBodyBuffer().readByte());
        }
        session.rollback();
        consumerExpiry.close();
    }
    session.close();
    session = sf.createSession(false, false, false);
    session.start();
    consumerExpiry = session.createConsumer(ADDRESS_DLA);
    msg1 = consumerExpiry.receive(5000);
    Assert.assertNotNull(msg1);
    msg1.acknowledge();
    for (int i = 0; i < messageSize; i++) {
        Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), msg1.getBodyBuffer().readByte());
    }
    session.commit();
    consumerExpiry.close();
    session.commit();
    session.close();
    server.stop();
    server.start();
    validateNoFilesOnLargeDir();
}

74. LargeMessageTest#testDLAOnExpiry()

View license
@Test
public void testDLAOnExpiry() throws Exception {
    final int messageSize = (int) (3.5 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE);
    ClientSession session = null;
    ActiveMQServer server = createServer(true, isNetty(), storeType);
    server.start();
    ClientSessionFactory sf = addSessionFactory(createSessionFactory(locator));
    SimpleString ADDRESS_DLA = ADDRESS.concat("-dla");
    SimpleString ADDRESS_EXPIRY = ADDRESS.concat("-expiry");
    AddressSettings addressSettings = new AddressSettings().setDeadLetterAddress(ADDRESS_DLA).setExpiryAddress(ADDRESS_EXPIRY).setMaxDeliveryAttempts(1);
    server.getAddressSettingsRepository().addMatch("*", addressSettings);
    session = sf.createSession(false, false, false);
    session.createQueue(ADDRESS, ADDRESS, true);
    session.createQueue(ADDRESS_DLA, ADDRESS_DLA, true);
    session.createQueue(ADDRESS_EXPIRY, ADDRESS_EXPIRY, true);
    ClientProducer producer = session.createProducer(ADDRESS);
    Message clientFile = createLargeClientMessageStreaming(session, messageSize, true);
    clientFile.setExpiration(System.currentTimeMillis());
    producer.send(clientFile);
    session.commit();
    session.start();
    ClientConsumer consumerExpired = session.createConsumer(ADDRESS);
    // to kick expiry quicker than waiting reaper thread
    Assert.assertNull(consumerExpired.receiveImmediate());
    consumerExpired.close();
    ClientConsumer consumerExpiry = session.createConsumer(ADDRESS_EXPIRY);
    ClientMessage msg1 = consumerExpiry.receive(5000);
    Assert.assertNotNull(msg1);
    msg1.acknowledge();
    for (int j = 0; j < messageSize; j++) {
        Assert.assertEquals(ActiveMQTestBase.getSamplebyte(j), msg1.getBodyBuffer().readByte());
    }
    session.rollback();
    consumerExpiry.close();
    for (int i = 0; i < 10; i++) {
        consumerExpiry = session.createConsumer(ADDRESS_DLA);
        msg1 = consumerExpiry.receive(5000);
        Assert.assertNotNull(msg1);
        msg1.acknowledge();
        for (int j = 0; j < messageSize; j++) {
            Assert.assertEquals(ActiveMQTestBase.getSamplebyte(j), msg1.getBodyBuffer().readByte());
        }
        session.rollback();
        consumerExpiry.close();
    }
    session.close();
    server.stop();
    server = createServer(true, isNetty(), storeType);
    server.start();
    sf = createSessionFactory(locator);
    session = sf.createSession(false, false, false);
    session.start();
    consumerExpiry = session.createConsumer(ADDRESS_DLA);
    msg1 = consumerExpiry.receive(5000);
    Assert.assertNotNull(msg1);
    msg1.acknowledge();
    for (int i = 0; i < messageSize; i++) {
        Assert.assertEquals(ActiveMQTestBase.getSamplebyte(i), msg1.getBodyBuffer().readByte());
    }
    session.commit();
    consumerExpiry.close();
    session.commit();
    session.close();
    validateNoFilesOnLargeDir();
}

75. LargeMessageTest#testPageOnLargeMessageMultipleQueues()

View license
// JBPAPP-6237
@Test
public void testPageOnLargeMessageMultipleQueues() throws Exception {
    Configuration config = createDefaultConfig(isNetty());
    final int PAGE_MAX = 20 * 1024;
    final int PAGE_SIZE = 10 * 1024;
    HashMap<String, AddressSettings> map = new HashMap<>();
    AddressSettings value = new AddressSettings();
    map.put(ADDRESS.toString(), value);
    ActiveMQServer server = createServer(true, config, PAGE_SIZE, PAGE_MAX, map, storeType);
    server.start();
    final int numberOfBytes = 1024;
    final int numberOfBytesBigMessage = 400000;
    locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true);
    ClientSessionFactory sf = addSessionFactory(createSessionFactory(locator));
    ClientSession session = sf.createSession(null, null, false, true, true, false, 0);
    session.createQueue(ADDRESS, ADDRESS.concat("-0"), null, true);
    session.createQueue(ADDRESS, ADDRESS.concat("-1"), null, true);
    ClientProducer producer = session.createProducer(ADDRESS);
    ClientMessage message = null;
    for (int i = 0; i < 100; i++) {
        message = session.createMessage(true);
        message.getBodyBuffer().writerIndex(0);
        message.getBodyBuffer().writeBytes(new byte[numberOfBytes]);
        for (int j = 1; j <= numberOfBytes; j++) {
            message.getBodyBuffer().writeInt(j);
        }
        producer.send(message);
    }
    ClientMessage clientFile = createLargeClientMessageStreaming(session, numberOfBytesBigMessage);
    clientFile.putBooleanProperty("TestLarge", true);
    producer.send(clientFile);
    for (int i = 0; i < 100; i++) {
        message = session.createMessage(true);
        message.getBodyBuffer().writeBytes(new byte[numberOfBytes]);
        producer.send(message);
    }
    session.close();
    server.stop();
    server = createServer(true, config, PAGE_SIZE, PAGE_MAX, map, storeType);
    server.start();
    sf = createSessionFactory(locator);
    for (int ad = 0; ad < 2; ad++) {
        session = sf.createSession(false, false, false);
        ClientConsumer consumer = session.createConsumer(ADDRESS.concat("-" + ad));
        session.start();
        for (int i = 0; i < 100; i++) {
            ClientMessage message2 = consumer.receive(LargeMessageTest.RECEIVE_WAIT_TIME);
            Assert.assertNotNull(message2);
            message2.acknowledge();
            Assert.assertNotNull(message2);
        }
        session.commit();
        for (int i = 0; i < 5; i++) {
            ClientMessage messageLarge = consumer.receive(RECEIVE_WAIT_TIME);
            assertTrue(messageLarge.getBooleanProperty("TestLarge"));
            Assert.assertNotNull(messageLarge);
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            messageLarge.acknowledge();
            messageLarge.saveToOutputStream(bout);
            byte[] body = bout.toByteArray();
            assertEquals(numberOfBytesBigMessage, body.length);
            for (int bi = 0; bi < body.length; bi++) {
                assertEquals(getSamplebyte(bi), body[bi]);
            }
            if (i < 4)
                session.rollback();
            else
                session.commit();
        }
        for (int i = 0; i < 100; i++) {
            ClientMessage message2 = consumer.receive(LargeMessageTest.RECEIVE_WAIT_TIME);
            Assert.assertNotNull(message2);
            message2.acknowledge();
            Assert.assertNotNull(message2);
        }
        session.commit();
        consumer.close();
        session.close();
    }
}

76. PagingOrderTest#testPageCounter()

View license
@Test
public void testPageCounter() throws Throwable {
    boolean persistentMessages = true;
    Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false);
    ActiveMQServer server = createServer(true, config, PAGE_SIZE, PAGE_MAX, new HashMap<String, AddressSettings>());
    server.start();
    final int messageSize = 1024;
    final int numberOfMessages = 500;
    ServerLocator locator = createInVMNonHALocator().setClientFailureCheckPeriod(1000).setConnectionTTL(2000).setReconnectAttempts(0).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true).setConsumerWindowSize(1024 * 1024);
    ClientSessionFactory sf = createSessionFactory(locator);
    ClientSession session = sf.createSession(false, false, false);
    Queue q1 = server.createQueue(ADDRESS, ADDRESS, null, true, false);
    Queue q2 = server.createQueue(ADDRESS, new SimpleString("inactive"), null, true, false);
    ClientProducer producer = session.createProducer(PagingTest.ADDRESS);
    byte[] body = new byte[messageSize];
    ByteBuffer bb = ByteBuffer.wrap(body);
    for (int j = 1; j <= messageSize; j++) {
        bb.put(getSamplebyte(j));
    }
    final AtomicInteger errors = new AtomicInteger(0);
    Thread t1 = new Thread() {

        @Override
        public void run() {
            try {
                ServerLocator sl = createInVMNonHALocator();
                ClientSessionFactory sf = sl.createSessionFactory();
                ClientSession sess = sf.createSession(true, true, 0);
                sess.start();
                ClientConsumer cons = sess.createConsumer(ADDRESS);
                for (int i = 0; i < numberOfMessages; i++) {
                    ClientMessage msg = cons.receive(5000);
                    assertNotNull(msg);
                    assertEquals(i, msg.getIntProperty("id").intValue());
                    msg.acknowledge();
                }
                assertNull(cons.receiveImmediate());
                sess.close();
                sl.close();
            } catch (Throwable e) {
                e.printStackTrace();
                errors.incrementAndGet();
            }
        }
    };
    t1.start();
    for (int i = 0; i < numberOfMessages; i++) {
        ClientMessage message = session.createMessage(persistentMessages);
        ActiveMQBuffer bodyLocal = message.getBodyBuffer();
        bodyLocal.writeBytes(body);
        message.putIntProperty(new SimpleString("id"), i);
        producer.send(message);
        if (i % 20 == 0) {
            session.commit();
        }
    }
    session.commit();
    t1.join();
    assertEquals(0, errors.get());
    assertEquals(numberOfMessages, getMessageCount(q2));
    assertEquals(numberOfMessages, getMessagesAdded(q2));
    assertEquals(0, getMessageCount(q1));
    assertEquals(numberOfMessages, getMessagesAdded(q1));
    session.close();
    sf.close();
    locator.close();
    server.stop();
    server.start();
    Bindings bindings = server.getPostOffice().getBindingsForAddress(ADDRESS);
    q1 = null;
    q2 = null;
    for (Binding bind : bindings.getBindings()) {
        if (bind instanceof LocalQueueBinding) {
            LocalQueueBinding qb = (LocalQueueBinding) bind;
            if (qb.getQueue().getName().equals(ADDRESS)) {
                q1 = qb.getQueue();
            }
            if (qb.getQueue().getName().equals(new SimpleString("inactive"))) {
                q2 = qb.getQueue();
            }
        }
    }
    assertNotNull(q1);
    assertNotNull(q2);
    assertEquals("q2 msg count", numberOfMessages, getMessageCount(q2));
    assertEquals("q2 msgs added", numberOfMessages, getMessagesAdded(q2));
    assertEquals("q1 msg count", 0, getMessageCount(q1));
    // 0, since nothing was sent to the queue after the server was restarted
    assertEquals("q1 msgs added", 0, getMessagesAdded(q1));
}

77. PagingOrderTest#testOrderOverRollback2()

View license
@Test
public void testOrderOverRollback2() throws Throwable {
    boolean persistentMessages = true;
    Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false);
    ActiveMQServer server = createServer(true, config, PAGE_SIZE, PAGE_MAX, new HashMap<String, AddressSettings>());
    server.start();
    final int messageSize = 1024;
    final int numberOfMessages = 200;
    ServerLocator locator = createInVMNonHALocator().setClientFailureCheckPeriod(1000).setConnectionTTL(2000).setReconnectAttempts(0).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true).setConsumerWindowSize(0);
    ClientSessionFactory sf = createSessionFactory(locator);
    ClientSession session = sf.createSession(false, false, false);
    QueueImpl queue = (QueueImpl) server.createQueue(ADDRESS, ADDRESS, null, true, false);
    ClientProducer producer = session.createProducer(PagingTest.ADDRESS);
    byte[] body = new byte[messageSize];
    ByteBuffer bb = ByteBuffer.wrap(body);
    for (int j = 1; j <= messageSize; j++) {
        bb.put(getSamplebyte(j));
    }
    for (int i = 0; i < numberOfMessages; i++) {
        ClientMessage message = session.createMessage(persistentMessages);
        ActiveMQBuffer bodyLocal = message.getBodyBuffer();
        bodyLocal.writeBytes(body);
        message.putIntProperty(new SimpleString("id"), i);
        producer.send(message);
        if (i % 1000 == 0) {
            session.commit();
        }
    }
    session.commit();
    session.close();
    session = sf.createSession(false, false, 0);
    session.start();
    ClientConsumer consumer = session.createConsumer(ADDRESS);
    // number of references without paging
    int numberOfRefs = queue.getNumberOfReferences();
    // consume all non-paged references
    for (int ref = 0; ref < numberOfRefs; ref++) {
        ClientMessage msg = consumer.receive(5000);
        assertNotNull(msg);
        msg.acknowledge();
    }
    session.commit();
    session.close();
    session = sf.createSession(false, false, 0);
    session.start();
    consumer = session.createConsumer(ADDRESS);
    ClientMessage msg = consumer.receive(5000);
    assertNotNull(msg);
    int msgIDRolledBack = msg.getIntProperty("id").intValue();
    msg.acknowledge();
    session.rollback();
    msg = consumer.receive(5000);
    assertNotNull(msg);
    assertEquals(msgIDRolledBack, msg.getIntProperty("id").intValue());
    session.rollback();
    session.close();
    sf.close();
    locator.close();
    server.stop();
    server.start();
    locator = createInVMNonHALocator().setClientFailureCheckPeriod(1000).setConnectionTTL(2000).setReconnectAttempts(0).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true).setConsumerWindowSize(0);
    sf = createSessionFactory(locator);
    session = sf.createSession(false, false, 0);
    session.start();
    consumer = session.createConsumer(ADDRESS);
    for (int i = msgIDRolledBack; i < numberOfMessages; i++) {
        ClientMessage message = consumer.receive(5000);
        assertNotNull(message);
        assertEquals(i, message.getIntProperty("id").intValue());
        message.acknowledge();
    }
    session.commit();
    session.close();
}

78. PagingTest#testPageOnLargeMessageMultipleQueues()

Project: activemq-artemis
Source File: PagingTest.java
View license
@Test
public void testPageOnLargeMessageMultipleQueues() throws Exception {
    Configuration config = createDefaultInVMConfig();
    final int PAGE_MAX = 20 * 1024;
    final int PAGE_SIZE = 10 * 1024;
    HashMap<String, AddressSettings> map = new HashMap<>();
    AddressSettings value = new AddressSettings();
    map.put(ADDRESS.toString(), value);
    ActiveMQServer server = createServer(true, config, PAGE_SIZE, PAGE_MAX, map);
    server.start();
    final int numberOfBytes = 1024;
    locator.setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true);
    ClientSessionFactory sf = addSessionFactory(createSessionFactory(locator));
    ClientSession session = sf.createSession(null, null, false, true, true, false, 0);
    session.createQueue(ADDRESS, ADDRESS.concat("-0"), null, true);
    session.createQueue(ADDRESS, ADDRESS.concat("-1"), null, true);
    ClientProducer producer = session.createProducer(ADDRESS);
    ClientMessage message = null;
    for (int i = 0; i < 201; i++) {
        message = session.createMessage(true);
        message.getBodyBuffer().writerIndex(0);
        message.getBodyBuffer().writeBytes(new byte[numberOfBytes]);
        for (int j = 1; j <= numberOfBytes; j++) {
            message.getBodyBuffer().writeInt(j);
        }
        producer.send(message);
    }
    session.close();
    server.stop();
    server = createServer(true, config, PAGE_SIZE, PAGE_MAX, map);
    server.start();
    sf = createSessionFactory(locator);
    for (int ad = 0; ad < 2; ad++) {
        session = sf.createSession(false, false, false);
        ClientConsumer consumer = session.createConsumer(ADDRESS.concat("-" + ad));
        session.start();
        for (int i = 0; i < 201; i++) {
            ClientMessage message2 = consumer.receive(LargeMessageTest.RECEIVE_WAIT_TIME);
            Assert.assertNotNull(message2);
            message2.acknowledge();
            Assert.assertNotNull(message2);
        }
        try {
            if (ad > -1) {
                session.commit();
            } else {
                session.rollback();
                for (int i = 0; i < 100; i++) {
                    ClientMessage message2 = consumer.receive(LargeMessageTest.RECEIVE_WAIT_TIME);
                    Assert.assertNotNull(message2);
                    message2.acknowledge();
                    Assert.assertNotNull(message2);
                }
                session.commit();
            }
        } catch (Throwable e) {
            System.err.println("here!!!!!!!");
            e.printStackTrace();
            System.exit(-1);
        }
        consumer.close();
        session.close();
    }
}

79. AutomaticColocatedQuorumVoteTest#testSimpleDistributionOfBackupsMaxBackupsExceeded()

View license
@Test
public void testSimpleDistributionOfBackupsMaxBackupsExceeded() throws Exception {
    ActiveMQServer server0 = createServer(0, 1, false);
    ActiveMQServer server1 = createServer(1, 0, false);
    ActiveMQServer server2 = createServer(2, 0, false);
    ActiveMQServer server3 = createServer(3, 0, false);
    TransportConfiguration liveConnector0 = getConnectorTransportConfiguration("liveConnector" + 0, 0);
    TransportConfiguration liveConnector1 = getConnectorTransportConfiguration("liveConnector" + 1, 1);
    TransportConfiguration liveConnector2 = getConnectorTransportConfiguration("liveConnector" + 2, 2);
    TransportConfiguration liveConnector3 = getConnectorTransportConfiguration("liveConnector" + 3, 3);
    try (ServerLocator serverLocator = ActiveMQClient.createServerLocatorWithoutHA(liveConnector0)) {
        server0.start();
        server1.start();
        ClientSessionFactory sessionFactory0 = serverLocator.createSessionFactory(liveConnector0);
        waitForRemoteBackup(sessionFactory0, 10);
        ClientSessionFactory sessionFactory1 = serverLocator.createSessionFactory(liveConnector1);
        waitForRemoteBackup(sessionFactory1, 10);
        Topology topology = serverLocator.getTopology();
        Collection<TopologyMemberImpl> members = topology.getMembers();
        Assert.assertEquals(members.size(), 2);
        Map<String, ActiveMQServer> backupServers0 = server0.getClusterManager().getHAManager().getBackupServers();
        Assert.assertEquals(backupServers0.size(), 1);
        Map<String, ActiveMQServer> backupServers1 = server1.getClusterManager().getHAManager().getBackupServers();
        Assert.assertEquals(backupServers1.size(), 1);
        ActiveMQServer backupServer0 = backupServers0.values().iterator().next();
        ActiveMQServer backupServer1 = backupServers1.values().iterator().next();
        waitForRemoteBackupSynchronization(backupServer0);
        waitForRemoteBackupSynchronization(backupServer1);
        Assert.assertEquals(server0.getNodeID(), backupServer1.getNodeID());
        Assert.assertEquals(server1.getNodeID(), backupServer0.getNodeID());
        server2.start();
        //just give server2 time to try both server 0 and 1
        ClientSessionFactory sessionFactory2 = serverLocator.createSessionFactory(liveConnector2);
        server3.start();
        ClientSessionFactory sessionFactory3 = serverLocator.createSessionFactory(liveConnector3);
        waitForRemoteBackup(sessionFactory2, 10);
        waitForRemoteBackup(sessionFactory3, 10);
        Assert.assertEquals(members.size(), 2);
        Map<String, ActiveMQServer> backupServers2 = server2.getClusterManager().getHAManager().getBackupServers();
        Assert.assertEquals(backupServers2.size(), 1);
        Map<String, ActiveMQServer> backupServers3 = server3.getClusterManager().getHAManager().getBackupServers();
        Assert.assertEquals(backupServers3.size(), 1);
        ActiveMQServer backupServer2 = backupServers2.values().iterator().next();
        ActiveMQServer backupServer3 = backupServers3.values().iterator().next();
        waitForRemoteBackupSynchronization(backupServer2);
        waitForRemoteBackupSynchronization(backupServer3);
        Assert.assertEquals(server0.getNodeID(), backupServer1.getNodeID());
        Assert.assertEquals(server1.getNodeID(), backupServer0.getNodeID());
        Assert.assertEquals(server2.getNodeID(), backupServer3.getNodeID());
        Assert.assertEquals(server3.getNodeID(), backupServer2.getNodeID());
    } finally {
        server0.stop();
        server1.stop();
        server2.stop();
        server3.stop();
    }
}

80. IsolatedTopologyTest#testIsolatedClusters()

View license
@Test
public void testIsolatedClusters() throws Exception {
    ActiveMQServer server1 = createServer1();
    ActiveMQServer server2 = createServer2();
    server1.start();
    server2.start();
    waitForTopology(server1, "cc1", 2, 5000);
    waitForTopology(server1, "cc2", 2, 5000);
    waitForTopology(server2, "cc1", 2, 5000);
    waitForTopology(server2, "cc2", 2, 5000);
    String node1 = server1.getNodeID().toString();
    String node2 = server2.getNodeID().toString();
    checkTopology(server1, "cc1", node1, node2, createInVMTransportConnectorConfig(1, "srv1"), createInVMTransportConnectorConfig(3, "srv1"));
    checkTopology(server2, "cc1", node1, node2, createInVMTransportConnectorConfig(1, "srv1"), createInVMTransportConnectorConfig(3, "srv1"));
    checkTopology(server1, "cc2", node1, node2, createInVMTransportConnectorConfig(2, "srv1"), createInVMTransportConnectorConfig(4, "srv1"));
    checkTopology(server2, "cc2", node1, node2, createInVMTransportConnectorConfig(2, "srv1"), createInVMTransportConnectorConfig(4, "srv1"));
    Thread.sleep(500);
}

81. SecurityTest#testJAASSecurityManagerAuthorizationNegative()

Project: activemq-artemis
Source File: SecurityTest.java
View license
@Test
public void testJAASSecurityManagerAuthorizationNegative() throws Exception {
    final SimpleString ADDRESS = new SimpleString("address");
    final SimpleString DURABLE_QUEUE = new SimpleString("durableQueue");
    final SimpleString NON_DURABLE_QUEUE = new SimpleString("nonDurableQueue");
    ActiveMQJAASSecurityManager securityManager = new ActiveMQJAASSecurityManager("PropertiesLogin");
    ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(createDefaultInVMConfig().setSecurityEnabled(true), ManagementFactory.getPlatformMBeanServer(), securityManager, false));
    Set<Role> roles = new HashSet<>();
    roles.add(new Role("programmers", false, false, false, false, false, false, false));
    server.getConfiguration().putSecurityRoles("#", roles);
    server.start();
    server.createQueue(ADDRESS, DURABLE_QUEUE, null, true, false);
    server.createQueue(ADDRESS, NON_DURABLE_QUEUE, null, false, false);
    ClientSessionFactory cf = createSessionFactory(locator);
    ClientSession session = addClientSession(cf.createSession("first", "secret", false, true, true, false, 0));
    // CREATE_DURABLE_QUEUE
    try {
        session.createQueue(ADDRESS, DURABLE_QUEUE, true);
        Assert.fail("should throw exception here");
    } catch (ActiveMQException e) {
    }
    // DELETE_DURABLE_QUEUE
    try {
        session.deleteQueue(DURABLE_QUEUE);
        Assert.fail("should throw exception here");
    } catch (ActiveMQException e) {
    }
    // CREATE_NON_DURABLE_QUEUE
    try {
        session.createQueue(ADDRESS, NON_DURABLE_QUEUE, false);
        Assert.fail("should throw exception here");
    } catch (ActiveMQException e) {
    }
    // DELETE_NON_DURABLE_QUEUE
    try {
        session.deleteQueue(NON_DURABLE_QUEUE);
        Assert.fail("should throw exception here");
    } catch (ActiveMQException e) {
    }
    // PRODUCE
    try {
        ClientProducer producer = session.createProducer(ADDRESS);
        producer.send(session.createMessage(true));
        Assert.fail("should throw exception here");
    } catch (ActiveMQException e) {
    }
    // CONSUME
    try {
        ClientConsumer consumer = session.createConsumer(DURABLE_QUEUE);
        Assert.fail("should throw exception here");
    } catch (ActiveMQException e) {
    }
    // MANAGE
    try {
        ClientProducer producer = session.createProducer(server.getConfiguration().getManagementAddress());
        producer.send(session.createMessage(true));
        Assert.fail("should throw exception here");
    } catch (ActiveMQException e) {
    }
}

82. SecurityTest#testJAASSecurityManagerAuthorizationNegativeWithCerts()

Project: activemq-artemis
Source File: SecurityTest.java
View license
@Test
public void testJAASSecurityManagerAuthorizationNegativeWithCerts() throws Exception {
    final SimpleString ADDRESS = new SimpleString("address");
    final SimpleString DURABLE_QUEUE = new SimpleString("durableQueue");
    final SimpleString NON_DURABLE_QUEUE = new SimpleString("nonDurableQueue");
    ActiveMQJAASSecurityManager securityManager = new ActiveMQJAASSecurityManager("CertLogin");
    ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(createDefaultInVMConfig().setSecurityEnabled(true), ManagementFactory.getPlatformMBeanServer(), securityManager, false));
    Map<String, Object> params = new HashMap<>();
    params.put(TransportConstants.SSL_ENABLED_PROP_NAME, true);
    params.put(TransportConstants.KEYSTORE_PATH_PROP_NAME, "server-side-keystore.jks");
    params.put(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME, "secureexample");
    params.put(TransportConstants.TRUSTSTORE_PATH_PROP_NAME, "server-side-truststore.jks");
    params.put(TransportConstants.TRUSTSTORE_PASSWORD_PROP_NAME, "secureexample");
    params.put(TransportConstants.NEED_CLIENT_AUTH_PROP_NAME, true);
    server.getConfiguration().addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params));
    Set<Role> roles = new HashSet<>();
    roles.add(new Role("programmers", false, false, false, false, false, false, false));
    server.getConfiguration().putSecurityRoles("#", roles);
    server.start();
    TransportConfiguration tc = new TransportConfiguration(NETTY_CONNECTOR_FACTORY);
    tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true);
    tc.getParams().put(TransportConstants.TRUSTSTORE_PATH_PROP_NAME, "client-side-truststore.jks");
    tc.getParams().put(TransportConstants.TRUSTSTORE_PASSWORD_PROP_NAME, "secureexample");
    tc.getParams().put(TransportConstants.KEYSTORE_PATH_PROP_NAME, "client-side-keystore.jks");
    tc.getParams().put(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME, "secureexample");
    ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(tc));
    ClientSessionFactory cf = createSessionFactory(locator);
    server.createQueue(ADDRESS, DURABLE_QUEUE, null, true, false);
    server.createQueue(ADDRESS, NON_DURABLE_QUEUE, null, false, false);
    ClientSession session = addClientSession(cf.createSession());
    // CREATE_DURABLE_QUEUE
    try {
        session.createQueue(ADDRESS, DURABLE_QUEUE, true);
        Assert.fail("should throw exception here");
    } catch (ActiveMQException e) {
    }
    // DELETE_DURABLE_QUEUE
    try {
        session.deleteQueue(DURABLE_QUEUE);
        Assert.fail("should throw exception here");
    } catch (ActiveMQException e) {
    }
    // CREATE_NON_DURABLE_QUEUE
    try {
        session.createQueue(ADDRESS, NON_DURABLE_QUEUE, false);
        Assert.fail("should throw exception here");
    } catch (ActiveMQException e) {
    }
    // DELETE_NON_DURABLE_QUEUE
    try {
        session.deleteQueue(NON_DURABLE_QUEUE);
        Assert.fail("should throw exception here");
    } catch (ActiveMQException e) {
    }
    // PRODUCE
    try {
        ClientProducer producer = session.createProducer(ADDRESS);
        producer.send(session.createMessage(true));
        Assert.fail("should throw exception here");
    } catch (ActiveMQException e) {
    }
    // CONSUME
    try {
        ClientConsumer consumer = session.createConsumer(DURABLE_QUEUE);
        Assert.fail("should throw exception here");
    } catch (ActiveMQException e) {
    }
    // MANAGE
    try {
        ClientProducer producer = session.createProducer(server.getConfiguration().getManagementAddress());
        producer.send(session.createMessage(true));
        Assert.fail("should throw exception here");
    } catch (ActiveMQException e) {
    }
}

83. FileLockTimeoutTest#doTest()

View license
protected void doTest(final boolean useAIO) throws Exception {
    if (useAIO) {
        Assert.assertTrue(String.format("libAIO is not loaded on %s %s %s", System.getProperty("os.name"), System.getProperty("os.arch"), System.getProperty("os.version")), LibaioContext.isLoaded());
    }
    Configuration config = super.createDefaultInVMConfig().setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration()).clearAcceptorConfigurations();
    ActiveMQServer server1 = createServer(true, config);
    if (useAIO) {
        server1.getConfiguration().setJournalType(JournalType.ASYNCIO);
    } else {
        server1.getConfiguration().setJournalType(JournalType.NIO);
    }
    server1.start();
    server1.waitForActivation(10, TimeUnit.SECONDS);
    final ActiveMQServer server2 = createServer(true, config);
    if (useAIO) {
        server2.getConfiguration().setJournalType(JournalType.ASYNCIO);
    } else {
        server2.getConfiguration().setJournalType(JournalType.NIO);
    }
    server2.getConfiguration().setJournalLockAcquisitionTimeout(5000);
    // if something happens that causes the timeout to misbehave we don't want the test to hang
    ExecutorService service = Executors.newSingleThreadExecutor(ActiveMQThreadFactory.defaultThreadFactory());
    Runnable r = new Runnable() {

        @Override
        public void run() {
            try {
                server2.start();
            } catch (final Exception e) {
                throw new RuntimeException(e);
            }
        }
    };
    Future<?> f = service.submit(r);
    try {
        f.get(15, TimeUnit.SECONDS);
    } catch (Exception e) {
        IntegrationTestLogger.LOGGER.warn("aborting test because server is taking too long to start");
    }
    service.shutdown();
    assertTrue("Expected to find AMQ224000", AssertionLoggerHandler.findText("AMQ224000"));
    assertTrue("Expected to find \"timed out waiting for lock\"", AssertionLoggerHandler.findText("timed out waiting for lock"));
}

84. PredefinedQueueTest#testDeployPreexistingQueues()

View license
@Test
public void testDeployPreexistingQueues() throws Exception {
    final String testAddress = "testAddress";
    final String queueName1 = "queue1";
    final String queueName2 = "queue2";
    final String queueName3 = "queue3";
    ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(configuration));
    server.start();
    ServerLocator locator = createInVMNonHALocator();
    ClientSessionFactory sf = createSessionFactory(locator);
    ClientSession session = addClientSession(sf.createSession(false, true, true));
    session.createQueue(testAddress, queueName1, null, true);
    session.createQueue(testAddress, queueName2, null, true);
    session.createQueue(testAddress, queueName3, null, true);
    session.close();
    sf.close();
    server.stop();
    CoreQueueConfiguration queue1 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName1);
    CoreQueueConfiguration queue2 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName2);
    CoreQueueConfiguration queue3 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName3);
    configuration.addQueueConfiguration(queue1).addQueueConfiguration(queue2).addQueueConfiguration(queue3);
    server.start();
    sf = createSessionFactory(locator);
    session = addClientSession(sf.createSession(false, true, true));
    session.start();
    ClientProducer producer = session.createProducer(new SimpleString(testAddress));
    ClientConsumer consumer1 = session.createConsumer(queueName1);
    ClientConsumer consumer2 = session.createConsumer(queueName2);
    ClientConsumer consumer3 = session.createConsumer(queueName3);
    final int numMessages = 10;
    final SimpleString propKey = new SimpleString("testkey");
    for (int i = 0; i < numMessages; i++) {
        ClientMessage message = session.createMessage(false);
        message.putIntProperty(propKey, i);
        producer.send(message);
    }
    for (int i = 0; i < numMessages; i++) {
        ClientMessage message = consumer1.receive(200);
        Assert.assertNotNull(message);
        Assert.assertEquals(i, message.getObjectProperty(propKey));
        message.acknowledge();
        message = consumer2.receive(200);
        Assert.assertNotNull(message);
        Assert.assertEquals(i, message.getObjectProperty(propKey));
        message.acknowledge();
        message = consumer3.receive(200);
        Assert.assertNotNull(message);
        Assert.assertEquals(i, message.getObjectProperty(propKey));
        message.acknowledge();
    }
    Assert.assertNull(consumer1.receiveImmediate());
    Assert.assertNull(consumer2.receiveImmediate());
    Assert.assertNull(consumer3.receiveImmediate());
}

85. PredefinedQueueTest#testDurableNonDurable()

View license
@Test
public void testDurableNonDurable() throws Exception {
    final String testAddress = "testAddress";
    final String queueName1 = "queue1";
    final String queueName2 = "queue2";
    CoreQueueConfiguration queue1 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName1).setDurable(false);
    CoreQueueConfiguration queue2 = new CoreQueueConfiguration().setAddress(testAddress).setName(queueName2);
    List<CoreQueueConfiguration> queueConfs = new ArrayList<>();
    queueConfs.add(queue1);
    queueConfs.add(queue2);
    configuration.addQueueConfiguration(queue1).addQueueConfiguration(queue2);
    ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(configuration));
    server.start();
    ServerLocator locator = createInVMNonHALocator();
    ClientSessionFactory sf = createSessionFactory(locator);
    ClientSession session = addClientSession(sf.createSession(false, true, true));
    ClientProducer producer = session.createProducer(new SimpleString(testAddress));
    final SimpleString propKey = new SimpleString("testkey");
    final int numMessages = 1;
    PredefinedQueueTest.log.info("sending messages");
    for (int i = 0; i < numMessages; i++) {
        ClientMessage message = session.createMessage(true);
        message.putIntProperty(propKey, i);
        producer.send(message);
    }
    session.close();
    PredefinedQueueTest.log.info("stopping");
    sf.close();
    server.stop();
    server.start();
    sf = createSessionFactory(locator);
    session = addClientSession(sf.createSession(false, true, true));
    session.start();
    ClientConsumer consumer1 = session.createConsumer(queueName1);
    ClientConsumer consumer2 = session.createConsumer(queueName2);
    ClientMessage message = consumer1.receiveImmediate();
    Assert.assertNull(message);
    for (int i = 0; i < numMessages; i++) {
        message = consumer2.receive(200);
        Assert.assertNotNull(message);
        Assert.assertEquals(i, message.getObjectProperty(propKey));
        message.acknowledge();
    }
    Assert.assertNull(consumer1.receiveImmediate());
    Assert.assertNull(consumer2.receiveImmediate());
}

86. StartStopDeadlockTest#testDeadlock()

View license
/*
   * simple test to make sure connect still works with some network latency  built into netty
   * */
@Test
@BMRules(rules = { @BMRule(name = "Server.start wait-init", targetClass = "org.apache.activemq.artemis.core.server.impl.ActiveMQServerImpl", targetMethod = "initialisePart2", targetLocation = "ENTRY", condition = "incrementCounter(\"server-Init\") == 2", action = "System.out.println(\"server backup init\"), waitFor(\"start-init\")"), @BMRule(name = "JMSServer.stop wait-init", targetClass = "org.apache.activemq.artemis.jms.server.impl.JMSServerManagerImpl", targetMethod = "stop", targetLocation = "ENTRY", action = "signalWake(\"start-init\", true)"), @BMRule(name = "StartStopDeadlockTest tearDown", targetClass = "org.apache.activemq.artemis.tests.extras.byteman.StartStopDeadlockTest", targetMethod = "tearDown", targetLocation = "ENTRY", action = "deleteCounter(\"server-Init\")") })
public void testDeadlock() throws Exception {
    // A live server that will always be crashed
    Configuration confLive = createDefaultNettyConfig().setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration());
    final ActiveMQServer serverLive = addServer(ActiveMQServers.newActiveMQServer(confLive));
    serverLive.start();
    // A backup that will be waiting to be activated
    Configuration config = createDefaultNettyConfig().setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration());
    final ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, true));
    final JMSServerManagerImpl jmsServer = new JMSServerManagerImpl(server);
    final InVMNamingContext context = new InVMNamingContext();
    jmsServer.setRegistry(new JndiBindingRegistry(context));
    jmsServer.start();
    final AtomicInteger errors = new AtomicInteger(0);
    final CountDownLatch align = new CountDownLatch(2);
    final CountDownLatch startLatch = new CountDownLatch(1);
    Thread tCrasher = new Thread("tStart") {

        @Override
        public void run() {
            try {
                align.countDown();
                startLatch.await();
                System.out.println("Crashing....");
                serverLive.stop(true);
            } catch (Exception e) {
                errors.incrementAndGet();
                e.printStackTrace();
            }
        }
    };
    Thread tStop = new Thread("tStop") {

        @Override
        public void run() {
            try {
                align.countDown();
                startLatch.await();
                jmsServer.stop();
            } catch (Exception e) {
                errors.incrementAndGet();
                e.printStackTrace();
            }
        }
    };
    tCrasher.start();
    tStop.start();
    align.await();
    startLatch.countDown();
    tCrasher.join();
    tStop.join();
    assertEquals(0, errors.get());
}

87. HeuristicXATest#internalTest()

View license
private void internalTest(final boolean isCommit) throws Exception {
    Configuration configuration = createDefaultInVMConfig().setJMXManagementEnabled(true);
    ActiveMQServer server = createServer(false, configuration);
    server.setMBeanServer(mbeanServer);
    server.start();
    Xid xid = newXID();
    ClientSessionFactory sf = createSessionFactory(locator);
    ClientSession session = sf.createSession(true, false, false);
    session.createQueue(ADDRESS, ADDRESS, true);
    session.start(xid, XAResource.TMNOFLAGS);
    ClientProducer producer = session.createProducer(ADDRESS);
    ClientMessage msg = session.createMessage(true);
    msg.getBodyBuffer().writeString(body);
    producer.send(msg);
    session.end(xid, XAResource.TMSUCCESS);
    session.prepare(xid);
    session.close();
    ActiveMQServerControl jmxServer = ManagementControlHelper.createActiveMQServerControl(mbeanServer);
    String[] preparedTransactions = jmxServer.listPreparedTransactions();
    Assert.assertEquals(1, preparedTransactions.length);
    System.out.println(preparedTransactions[0]);
    Assert.assertEquals(0, jmxServer.listHeuristicCommittedTransactions().length);
    Assert.assertEquals(0, jmxServer.listHeuristicRolledBackTransactions().length);
    if (isCommit) {
        jmxServer.commitPreparedTransaction(XidImpl.toBase64String(xid));
    } else {
        jmxServer.rollbackPreparedTransaction(XidImpl.toBase64String(xid));
    }
    Assert.assertEquals(0, jmxServer.listPreparedTransactions().length);
    if (isCommit) {
        Assert.assertEquals(1, jmxServer.listHeuristicCommittedTransactions().length);
        Assert.assertEquals(0, jmxServer.listHeuristicRolledBackTransactions().length);
    } else {
        Assert.assertEquals(0, jmxServer.listHeuristicCommittedTransactions().length);
        Assert.assertEquals(1, jmxServer.listHeuristicRolledBackTransactions().length);
    }
    if (isCommit) {
        Assert.assertEquals(1, getMessageCount(((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable())));
        session = sf.createSession(false, false, false);
        session.start();
        ClientConsumer consumer = session.createConsumer(ADDRESS);
        msg = consumer.receive(1000);
        Assert.assertNotNull(msg);
        msg.acknowledge();
        Assert.assertEquals(body, msg.getBodyBuffer().readString());
        session.commit();
        session.close();
    }
    Assert.assertEquals(0, getMessageCount(((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable())));
}

88. InterruptedLargeMessageTest#testCloseConsumerDuringTransmission()

View license
@Test
public void testCloseConsumerDuringTransmission() throws Exception {
    ActiveMQServer server = createServer(true, isNetty());
    LargeMessageTestInterceptorIgnoreLastPacket.disableInterrupt();
    server.start();
    locator.setBlockOnNonDurableSend(false).setBlockOnDurableSend(false).addIncomingInterceptor(new LargeMessageTestInterceptorIgnoreLastPacket());
    ClientSessionFactory sf = createSessionFactory(locator);
    final ClientSession session = sf.createSession(false, true, true);
    session.createQueue(ADDRESS, ADDRESS, true);
    ClientProducer producer = session.createProducer(ADDRESS);
    Message clientFile = createLargeClientMessageStreaming(session, LARGE_MESSAGE_SIZE, true);
    producer.send(clientFile);
    session.commit();
    LargeMessageTestInterceptorIgnoreLastPacket.clearInterrupt();
    final AtomicInteger unexpectedErrors = new AtomicInteger(0);
    final AtomicInteger expectedErrors = new AtomicInteger(0);
    final ClientConsumer cons = session.createConsumer(ADDRESS);
    session.start();
    Thread t = new Thread() {

        @Override
        public void run() {
            try {
                System.out.println("Receiving message");
                ClientMessage msg = cons.receive(5000);
                if (msg == null) {
                    System.err.println("Message not received");
                    unexpectedErrors.incrementAndGet();
                    return;
                }
                msg.checkCompletion();
            } catch (ActiveMQException e) {
                e.printStackTrace();
                expectedErrors.incrementAndGet();
            }
        }
    };
    t.start();
    LargeMessageTestInterceptorIgnoreLastPacket.awaitInterrupt();
    cons.close();
    t.join();
    Assert.assertEquals(0, unexpectedErrors.get());
    Assert.assertEquals(1, expectedErrors.get());
    session.close();
    server.stop();
}

89. PagingOrderTest#testOrder1()

View license
@Test
public void testOrder1() throws Throwable {
    boolean persistentMessages = true;
    Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false);
    ActiveMQServer server = createServer(true, config, PAGE_SIZE, PAGE_MAX, new HashMap<String, AddressSettings>());
    server.start();
    final int messageSize = 1024;
    final int numberOfMessages = 500;
    ServerLocator locator = createInVMNonHALocator().setClientFailureCheckPeriod(1000).setConnectionTTL(2000).setReconnectAttempts(0).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true).setConsumerWindowSize(1024 * 1024);
    ClientSessionFactory sf = createSessionFactory(locator);
    ClientSession session = sf.createSession(false, false, false);
    server.createQueue(ADDRESS, ADDRESS, null, true, false);
    ClientProducer producer = session.createProducer(PagingTest.ADDRESS);
    byte[] body = new byte[messageSize];
    ByteBuffer bb = ByteBuffer.wrap(body);
    for (int j = 1; j <= messageSize; j++) {
        bb.put(getSamplebyte(j));
    }
    for (int i = 0; i < numberOfMessages; i++) {
        ClientMessage message = session.createMessage(persistentMessages);
        ActiveMQBuffer bodyLocal = message.getBodyBuffer();
        bodyLocal.writeBytes(body);
        message.putIntProperty(new SimpleString("id"), i);
        producer.send(message);
        if (i % 1000 == 0) {
            session.commit();
        }
    }
    session.commit();
    session.close();
    session = sf.createSession(true, true, 0);
    session.start();
    ClientConsumer consumer = session.createConsumer(ADDRESS);
    for (int i = 0; i < numberOfMessages / 2; i++) {
        ClientMessage message = consumer.receive(5000);
        assertNotNull(message);
        assertEquals(i, message.getIntProperty("id").intValue());
        if (i < 100) {
            // Do not consume the last one so we could restart
            message.acknowledge();
        }
    }
    session.close();
    sf.close();
    sf = createSessionFactory(locator);
    session = sf.createSession(true, true, 0);
    session.start();
    consumer = session.createConsumer(ADDRESS);
    for (int i = 100; i < numberOfMessages; i++) {
        ClientMessage message = consumer.receive(5000);
        assertNotNull(message);
        assertEquals(i, message.getIntProperty("id").intValue());
        message.acknowledge();
    }
    session.close();
}

90. PagingOrderTest#testOrderOverRollback()

View license
@Test
public void testOrderOverRollback() throws Throwable {
    boolean persistentMessages = true;
    Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false);
    ActiveMQServer server = createServer(true, config, PAGE_SIZE, PAGE_MAX, new HashMap<String, AddressSettings>());
    server.start();
    final int messageSize = 1024;
    final int numberOfMessages = 3000;
    ServerLocator locator = createInVMNonHALocator().setClientFailureCheckPeriod(1000).setConnectionTTL(2000).setReconnectAttempts(0).setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true).setConsumerWindowSize(1024 * 1024);
    ClientSessionFactory sf = createSessionFactory(locator);
    ClientSession session = sf.createSession(false, false, false);
    server.createQueue(ADDRESS, ADDRESS, null, true, false);
    ClientProducer producer = session.createProducer(PagingTest.ADDRESS);
    byte[] body = new byte[messageSize];
    ByteBuffer bb = ByteBuffer.wrap(body);
    for (int j = 1; j <= messageSize; j++) {
        bb.put(getSamplebyte(j));
    }
    for (int i = 0; i < numberOfMessages; i++) {
        ClientMessage message = session.createMessage(persistentMessages);
        ActiveMQBuffer bodyLocal = message.getBodyBuffer();
        bodyLocal.writeBytes(body);
        message.putIntProperty(new SimpleString("id"), i);
        producer.send(message);
        if (i % 1000 == 0) {
            session.commit();
        }
    }
    session.commit();
    session.close();
    session = sf.createSession(false, false, 0);
    session.start();
    ClientConsumer consumer = session.createConsumer(ADDRESS);
    for (int i = 0; i < numberOfMessages / 2; i++) {
        ClientMessage message = consumer.receive(5000);
        assertNotNull(message);
        assertEquals(i, message.getIntProperty("id").intValue());
        message.acknowledge();
    }
    session.rollback();
    session.close();
    session = sf.createSession(false, false, 0);
    session.start();
    consumer = session.createConsumer(ADDRESS);
    for (int i = 0; i < numberOfMessages; i++) {
        ClientMessage message = consumer.receive(5000);
        assertNotNull(message);
        assertEquals(i, message.getIntProperty("id").intValue());
        message.acknowledge();
    }
    session.commit();
}

91. PagingSyncTest#testOrder1()

View license
@Test
public void testOrder1() throws Throwable {
    boolean persistentMessages = true;
    Configuration config = createDefaultInVMConfig().setJournalSyncNonTransactional(false);
    ActiveMQServer server = createServer(true, config, PAGE_SIZE, PAGE_MAX, new HashMap<String, AddressSettings>());
    server.start();
    final int messageSize = 1024;
    final int numberOfMessages = 500;
    ServerLocator locator = createInVMNonHALocator().setClientFailureCheckPeriod(1000).setConnectionTTL(2000).setReconnectAttempts(0).setBlockOnNonDurableSend(false).setBlockOnDurableSend(false).setBlockOnAcknowledge(false).setConsumerWindowSize(1024 * 1024);
    ClientSessionFactory sf = createSessionFactory(locator);
    ClientSession session = sf.createSession(false, false, false);
    server.createQueue(ADDRESS, ADDRESS, null, true, false);
    ClientProducer producer = session.createProducer(PagingTest.ADDRESS);
    byte[] body = new byte[messageSize];
    ByteBuffer bb = ByteBuffer.wrap(body);
    for (int j = 1; j <= messageSize; j++) {
        bb.put(getSamplebyte(j));
    }
    for (int i = 0; i < numberOfMessages; i++) {
        ClientMessage message = session.createMessage(persistentMessages);
        ActiveMQBuffer bodyLocal = message.getBodyBuffer();
        bodyLocal.writeBytes(body);
        message.putIntProperty(new SimpleString("id"), i);
        producer.send(message);
    }
    session.commit();
    session.close();
}

92. ClusterTestBase#setupLiveServer()

View license
protected void setupLiveServer(final int node, final boolean fileStorage, final boolean sharedStorage, final boolean netty, boolean liveOnly) throws Exception {
    if (servers[node] != null) {
        throw new IllegalArgumentException("Already a server at node " + node);
    }
    HAPolicyConfiguration haPolicyConfiguration = null;
    if (liveOnly) {
        haPolicyConfiguration = new LiveOnlyPolicyConfiguration();
    } else {
        if (sharedStorage)
            haPolicyConfiguration = new SharedStoreMasterPolicyConfiguration();
        else
            haPolicyConfiguration = new ReplicatedPolicyConfiguration();
    }
    Configuration configuration = createBasicConfig(node).setJournalMaxIO_AIO(1000).setThreadPoolMaxSize(10).clearAcceptorConfigurations().addAcceptorConfiguration(createTransportConfiguration(netty, true, generateParams(node, netty))).setHAPolicyConfiguration(haPolicyConfiguration).setResolveProtocols(false);
    ActiveMQServer server;
    if (fileStorage) {
        if (sharedStorage) {
            server = createInVMFailoverServer(true, configuration, nodeManagers[node], node);
        } else {
            server = createServer(configuration);
        }
    } else {
        if (sharedStorage) {
            server = createInVMFailoverServer(false, configuration, nodeManagers[node], node);
        } else {
            server = createServer(false, configuration);
        }
    }
    server.addProtocolManagerFactory(new CoreProtocolManagerFactory());
    server.setIdentity(this.getClass().getSimpleName() + "/Live(" + node + ")");
    servers[node] = addServer(server);
}

93. RelativePathTest#testRelativePathOnDefaultConfig()

View license
@Test
public void testRelativePathOnDefaultConfig() throws Exception {
    Configuration configuration = createDefaultConfig(false);
    ActiveMQServer server = createServer(true, configuration, AddressSettings.DEFAULT_PAGE_SIZE, AddressSettings.DEFAULT_MAX_SIZE_BYTES, new HashMap<String, AddressSettings>());
    server.start();
    server.stop();
    checkData(new File(configuration.getJournalDirectory()), ".amq");
    checkData(new File(configuration.getBindingsDirectory()), ".bindings");
}

94. RelativePathTest#testDataOutsideHome()

View license
@Test
public void testDataOutsideHome() throws Exception {
    Configuration configuration = createDefaultConfig(false);
    File instanceHome = new File(getTemporaryDir(), "artemisHome");
    configuration.setBrokerInstance(instanceHome);
    // the journal should be outside of the artemisInstance on this case
    File journalOutside = new File(getTemporaryDir(), "./journalOut").getAbsoluteFile();
    configuration.setJournalDirectory(journalOutside.getAbsolutePath());
    // Somewhere inside artemis.instance
    configuration.setBindingsDirectory("./bind");
    File bindingsInside = new File(instanceHome, "bind");
    //      configuration.setJournal
    System.out.println("Journal dir::" + configuration.getJournalDirectory());
    System.out.println("Journal loc::" + configuration.getJournalLocation());
    ActiveMQServer server = createServer(true, configuration, AddressSettings.DEFAULT_PAGE_SIZE, AddressSettings.DEFAULT_MAX_SIZE_BYTES, new HashMap<String, AddressSettings>());
    server.start();
    server.stop();
    checkData(journalOutside, ".amq");
    // Checking if the journal created the lock as well
    checkData(journalOutside, "server.lock");
    checkData(bindingsInside, ".bindings");
}

95. RelativePathTest#testRelativePath()

View license
@Test
public void testRelativePath() throws Exception {
    Configuration configuration = createDefaultConfig(false);
    File instanceHome = new File(getTemporaryDir(), "artemisHome");
    File dataHome = new File(instanceHome, "data");
    // One folder up for testing
    File bindingsHome = new File(instanceHome, "../binx");
    System.out.println("InstanceHome->" + instanceHome);
    instanceHome.mkdirs();
    configuration.setBrokerInstance(instanceHome);
    configuration.setJournalDirectory("./data");
    configuration.setPagingDirectory("./paging");
    configuration.setBindingsDirectory("../binx");
    // one folder up from instance home
    configuration.setLargeMessagesDirectory("./large");
    ActiveMQServer server = createServer(true, configuration, AddressSettings.DEFAULT_PAGE_SIZE, AddressSettings.DEFAULT_MAX_SIZE_BYTES, new HashMap<String, AddressSettings>());
    server.start();
    server.stop();
    checkData(dataHome, ".amq");
    checkData(bindingsHome, ".bindings");
}

96. AcceptorControlTest#testStartStop()

View license
@Test
public void testStartStop() throws Exception {
    TransportConfiguration acceptorConfig = new TransportConfiguration(InVMAcceptorFactory.class.getName(), new HashMap<String, Object>(), RandomUtil.randomString());
    Configuration config = createBasicConfig().addAcceptorConfiguration(acceptorConfig);
    ActiveMQServer service = createServer(false, config);
    service.setMBeanServer(mbeanServer);
    service.start();
    AcceptorControl acceptorControl = createManagementControl(acceptorConfig.getName());
    // started by the server
    Assert.assertTrue(acceptorControl.isStarted());
    ServerLocator locator = createInVMNonHALocator();
    ClientSessionFactory sf = createSessionFactory(locator);
    ClientSession session = sf.createSession(false, true, true);
    Assert.assertNotNull(session);
    session.close();
    acceptorControl.stop();
    Assert.assertFalse(acceptorControl.isStarted());
    try {
        sf.createSession(false, true, true);
        Assert.fail("acceptor must not accept connections when stopped accepting");
    } catch (ActiveMQException e) {
    }
    acceptorControl.start();
    Assert.assertTrue(acceptorControl.isStarted());
    locator = createInVMNonHALocator();
    sf = createSessionFactory(locator);
    session = sf.createSession(false, true, true);
    Assert.assertNotNull(session);
    session.close();
    acceptorControl.stop();
    Assert.assertFalse(acceptorControl.isStarted());
    try {
        sf.createSession(false, true, true);
        Assert.fail("acceptor must not accept connections when stopped accepting");
    } catch (ActiveMQException e) {
    }
}

97. AcceptorControlTest#testNotifications()

View license
@Test
public void testNotifications() throws Exception {
    TransportConfiguration acceptorConfig = new TransportConfiguration(InVMAcceptorFactory.class.getName(), new HashMap<String, Object>(), RandomUtil.randomString());
    Configuration config = createBasicConfig().addAcceptorConfiguration(acceptorConfig);
    ActiveMQServer service = createServer(false, config);
    service.setMBeanServer(mbeanServer);
    service.start();
    AcceptorControl acceptorControl = createManagementControl(acceptorConfig.getName());
    SimpleNotificationService.Listener notifListener = new SimpleNotificationService.Listener();
    service.getManagementService().addNotificationListener(notifListener);
    Assert.assertEquals(0, notifListener.getNotifications().size());
    acceptorControl.stop();
    Assert.assertEquals(1, notifListener.getNotifications().size());
    Notification notif = notifListener.getNotifications().get(0);
    Assert.assertEquals(CoreNotificationType.ACCEPTOR_STOPPED, notif.getType());
    Assert.assertEquals(InVMAcceptorFactory.class.getName(), notif.getProperties().getSimpleStringProperty(new SimpleString("factory")).toString());
    acceptorControl.start();
    Assert.assertEquals(2, notifListener.getNotifications().size());
    notif = notifListener.getNotifications().get(1);
    Assert.assertEquals(CoreNotificationType.ACCEPTOR_STARTED, notif.getType());
    Assert.assertEquals(InVMAcceptorFactory.class.getName(), notif.getProperties().getSimpleStringProperty(new SimpleString("factory")).toString());
}

98. ActiveMQServerControlTest#scaleDown()

View license
protected void scaleDown(ScaleDownHandler handler) throws Exception {
    SimpleString address = new SimpleString("testQueue");
    HashMap<String, Object> params = new HashMap<>();
    params.put(TransportConstants.SERVER_ID_PROP_NAME, "2");
    Configuration config = createDefaultInVMConfig(2).clearAcceptorConfigurations().addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName(), params));
    ActiveMQServer server2 = addServer(ActiveMQServers.newActiveMQServer(config, null, true));
    this.conf.clearConnectorConfigurations().addConnectorConfiguration("server2-connector", new TransportConfiguration(INVM_CONNECTOR_FACTORY, params));
    server2.start();
    server.createQueue(address, address, null, true, false);
    server2.createQueue(address, address, null, true, false);
    ServerLocator locator = createInVMNonHALocator();
    ClientSessionFactory csf = createSessionFactory(locator);
    ClientSession session = csf.createSession();
    ClientProducer producer = session.createProducer(address);
    for (int i = 0; i < 100; i++) {
        ClientMessage message = session.createMessage(true);
        message.getBodyBuffer().writeString("m" + i);
        producer.send(message);
    }
    ActiveMQServerControl managementControl = createManagementControl();
    handler.scaleDown(managementControl);
    locator.close();
    locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(new TransportConfiguration(INVM_CONNECTOR_FACTORY, params)));
    csf = createSessionFactory(locator);
    session = csf.createSession();
    session.start();
    ClientConsumer consumer = session.createConsumer(address);
    for (int i = 0; i < 100; i++) {
        ClientMessage m = consumer.receive(5000);
        assertNotNull(m);
    }
}

99. ExportFormatTest#testCreateFormat()

View license
@Test
@Ignore
public // Used to update the format, if you need to use this it means the data format was broken, Be careful on updating the format!
void testCreateFormat() throws Exception {
    ActiveMQServer server = createServer(true);
    server.start();
    ServerLocator locator = createInVMNonHALocator();
    ClientSessionFactory factory = createSessionFactory(locator);
    ClientSession session = factory.createSession(false, false, false);
    session.createQueue("A1", "A1", true);
    ClientProducer producer = session.createProducer("A1");
    for (int i = 0; i < 5; i++) {
        ClientMessage msg = session.createMessage(true);
        msg.putIntProperty("key", i);
        producer.send(msg);
    }
    session.commit();
    session.close();
    session = factory.createSession(false, true, true);
    producer = session.createProducer("A1");
    for (int i = 5; i < 10; i++) {
        ClientMessage msg = session.createMessage(true);
        msg.putIntProperty("key", i);
        producer.send(msg);
    }
    locator.close();
    server.stop();
    System.out.println();
    System.out.println("copy & paste the following as bindingsFile:");
    EncodeJournal.exportJournal(server.getConfiguration().getBindingsLocation().getAbsolutePath(), "activemq-bindings", "bindings", 2, 1048576, System.out);
    System.out.println();
    System.out.println("copy & paste the following as dataFile:");
    EncodeJournal.exportJournal(server.getConfiguration().getJournalLocation().getAbsolutePath(), "activemq-data", "amq", 2, 102400, System.out);
}

100. AddressFullLoggingTest#testBlockLogging()

View license
@Test
public /**
    * When running this test from an IDE add this to the test command line so that the AssertionLoggerHandler works properly:
    *
    *   -Djava.util.logging.manager=org.jboss.logmanager.LogManager  -Dlogging.configuration=file:<path_to_source>/tests/config/logging.properties
    */
void testBlockLogging() throws Exception {
    final int MAX_MESSAGES = 200;
    final String MY_ADDRESS = "myAddress";
    final String MY_QUEUE = "myQueue";
    ActiveMQServer server = createServer(false);
    AddressSettings defaultSetting = new AddressSettings().setPageSizeBytes(10 * 1024).setMaxSizeBytes(20 * 1024).setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK);
    server.getAddressSettingsRepository().addMatch("#", defaultSetting);
    server.start();
    ServerLocator locator = createInVMNonHALocator().setBlockOnNonDurableSend(true).setBlockOnDurableSend(true).setBlockOnAcknowledge(true);
    ClientSessionFactory factory = createSessionFactory(locator);
    ClientSession session = factory.createSession(false, true, true);
    session.createQueue(MY_ADDRESS, MY_QUEUE, true);
    final ClientProducer producer = session.createProducer(MY_ADDRESS);
    final ClientMessage message = session.createMessage(false);
    message.getBodyBuffer().writeBytes(new byte[1024]);
    ExecutorService executor = Executors.newFixedThreadPool(1, ActiveMQThreadFactory.defaultThreadFactory());
    Callable<Object> sendMessageTask = new Callable<Object>() {

        @Override
        public Object call() throws ActiveMQException {
            producer.send(message);
            return null;
        }
    };
    int sendCount = 0;
    for (int i = 0; i < MAX_MESSAGES; i++) {
        Future<Object> future = executor.submit(sendMessageTask);
        try {
            future.get(3, TimeUnit.SECONDS);
            sendCount++;
        } catch (TimeoutException ex) {
            break;
        } finally {
            // may or may not desire this
            future.cancel(true);
        }
    }
    executor.shutdown();
    session.close();
    session = factory.createSession(false, true, true);
    session.start();
    ClientConsumer consumer = session.createConsumer(MY_QUEUE);
    for (int i = 0; i < sendCount; i++) {
        ClientMessage msg = consumer.receive(250);
        if (msg == null)
            break;
        msg.acknowledge();
    }
    session.close();
    locator.close();
    server.stop();
    // Using the code only so the test doesn't fail just because someone edits the log text
    Assert.assertTrue("Expected to find AMQ222183", AssertionLoggerHandler.findText("AMQ222183", "myAddress"));
    Assert.assertTrue("Expected to find AMQ221046", AssertionLoggerHandler.findText("AMQ221046", "myAddress"));
}