diff options
| author | Kim van der Riet <kpvdr@apache.org> | 2012-08-03 12:13:32 +0000 |
|---|---|---|
| committer | Kim van der Riet <kpvdr@apache.org> | 2012-08-03 12:13:32 +0000 |
| commit | d43d1912b376322e27fdcda551a73f9ff5487972 (patch) | |
| tree | ce493e10baa95f44be8beb5778ce51783463196d /java/broker/src/test | |
| parent | 04877fec0c6346edec67072d7f2d247740cf2af5 (diff) | |
| download | qpid-python-d43d1912b376322e27fdcda551a73f9ff5487972.tar.gz | |
QPID-3858: Updated branch - merged from trunk r.1368650
git-svn-id: https://svn.apache.org/repos/asf/qpid/branches/asyncstore@1368910 13f79535-47bb-0310-9956-ffa450edef68
Diffstat (limited to 'java/broker/src/test')
55 files changed, 2879 insertions, 3233 deletions
diff --git a/java/broker/src/test/java/org/apache/log4j/xml/QpidLog4JConfiguratorTest.java b/java/broker/src/test/java/org/apache/log4j/xml/QpidLog4JConfiguratorTest.java deleted file mode 100644 index c06ce5e31a..0000000000 --- a/java/broker/src/test/java/org/apache/log4j/xml/QpidLog4JConfiguratorTest.java +++ /dev/null @@ -1,395 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.log4j.xml; - - -import junit.framework.TestCase; -import org.apache.log4j.xml.QpidLog4JConfigurator.IllegalLoggerLevelException; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; - -public class QpidLog4JConfiguratorTest extends TestCase -{ - private static final String NEWLINE = System.getProperty("line.separator"); - - private File _testConfigFile; - - private File createTempTestLog4JConfig(String loggerLevel,String rootLoggerLevel, boolean missingTagClose, boolean incorrectAttribute) - { - File tmpFile = null; - try - { - tmpFile = File.createTempFile("QpidLog4JConfiguratorTestLog4jConfig", ".tmp"); - tmpFile.deleteOnExit(); - - FileWriter fstream = new FileWriter(tmpFile); - BufferedWriter writer = new BufferedWriter(fstream); - - writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+NEWLINE); - writer.write("<!DOCTYPE log4j:configuration SYSTEM \"log4j.dtd\">"+NEWLINE); - - writer.write("<log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\" debug=\"null\" " + - "threshold=\"null\">"+NEWLINE); - - writer.write(" <appender class=\"org.apache.log4j.ConsoleAppender\" name=\"STDOUT\">"+NEWLINE); - writer.write(" <layout class=\"org.apache.log4j.PatternLayout\">"+NEWLINE); - writer.write(" <param name=\"ConversionPattern\" value=\"%d %-5p [%t] %C{2} (%F:%L) - %m%n\"/>"+NEWLINE); - writer.write(" </layout>"+NEWLINE); - writer.write(" </appender>"+NEWLINE); - - String closeTag="/"; - if(missingTagClose) - { - closeTag=""; - } - - //Example of a 'category' with a 'priority' - writer.write(" <category additivity=\"true\" name=\"logger1\">"+NEWLINE); - writer.write(" <priority value=\"" + loggerLevel+ "\"" + closeTag + ">"+NEWLINE); - writer.write(" <appender-ref ref=\"STDOUT\"/>"+NEWLINE); - writer.write(" </category>"+NEWLINE); - - String attributeName="value"; - if(incorrectAttribute) - { - attributeName="values"; - } - - //Example of a 'category' with a 'level' - writer.write(" <category additivity=\"true\" name=\"logger2\">"+NEWLINE); - writer.write(" <level " + attributeName + "=\"" + loggerLevel+ "\"/>"+NEWLINE); - writer.write(" <appender-ref ref=\"STDOUT\"/>"+NEWLINE); - writer.write(" </category>"+NEWLINE); - - //Example of a 'logger' with a 'level' - writer.write(" <logger additivity=\"true\" name=\"logger3\">"+NEWLINE); - writer.write(" <level value=\"" + loggerLevel+ "\"/>"+NEWLINE); - writer.write(" <appender-ref ref=\"STDOUT\"/>"+NEWLINE); - writer.write(" </logger>"+NEWLINE); - - //'root' logger - writer.write(" <root>"+NEWLINE); - writer.write(" <priority value=\"" + rootLoggerLevel+ "\"/>"+NEWLINE); - writer.write(" <appender-ref ref=\"STDOUT\"/>"+NEWLINE); - writer.write(" </root>"+NEWLINE); - - writer.write("</log4j:configuration>"+NEWLINE); - - writer.flush(); - writer.close(); - } - catch (IOException e) - { - fail("Unable to create temporary test log4j configuration"); - } - - return tmpFile; - } - - - - //******* Test Methods ******* // - - public void testCheckLevelsAndStrictParser() - { - //try the valid logger levels - _testConfigFile = createTempTestLog4JConfig("all", "info", false, false); - try - { - QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath()); - } - catch (Exception e) - { - fail("No exception expected, valid levels and xml were used"); - } - - _testConfigFile = createTempTestLog4JConfig("trace", "info", false, false); - try - { - QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath()); - } - catch (Exception e) - { - fail("No exception expected, valid levels and xml were used"); - } - - _testConfigFile = createTempTestLog4JConfig("debug", "info", false, false); - try - { - QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath()); - } - catch (Exception e) - { - fail("No exception expected, valid levels and xml were used"); - } - - _testConfigFile = createTempTestLog4JConfig("info", "info", false, false); - try - { - QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath()); - } - catch (Exception e) - { - fail("No exception expected, valid levels and xml were used"); - } - - _testConfigFile = createTempTestLog4JConfig("warn", "info", false, false); - try - { - QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath()); - } - catch (Exception e) - { - fail("No exception expected, valid levels and xml were used"); - } - - _testConfigFile = createTempTestLog4JConfig("error", "info", false, false); - try - { - QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath()); - } - catch (Exception e) - { - fail("No exception expected, valid levels and xml were used"); - } - - _testConfigFile = createTempTestLog4JConfig("fatal", "info", false, false); - try - { - QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath()); - } - catch (Exception e) - { - fail("No exception expected, valid levels and xml were used"); - } - - _testConfigFile = createTempTestLog4JConfig("off", "info", false, false); - try - { - QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath()); - } - catch (Exception e) - { - fail("No exception expected, valid levels and xml were used"); - } - - _testConfigFile = createTempTestLog4JConfig("null", "info", false, false); - try - { - QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath()); - } - catch (Exception e) - { - fail("No exception expected, valid levels and xml were used"); - } - - _testConfigFile = createTempTestLog4JConfig("inherited", "info", false, false); - try - { - QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath()); - } - catch (Exception e) - { - fail("No exception expected, valid levels and xml were used"); - } - - //now try an invalid logger level - _testConfigFile = createTempTestLog4JConfig("madeup", "info", false, false); - try - { - QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath()); - fail("IllegalLoggerLevelException expected, invalid levels used"); - } - catch (IllegalLoggerLevelException e) - { - //expected, ignore - } - catch (IOException e) - { - fail("Incorrect Exception, expected an IllegalLoggerLevelException"); - } - - - - //now try the valid rootLogger levels - _testConfigFile = createTempTestLog4JConfig("info", "all", false, false); - try - { - QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath()); - } - catch (Exception e) - { - fail("No exception expected, valid levels and xml were used"); - } - - _testConfigFile = createTempTestLog4JConfig("info", "trace", false, false); - try - { - QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath()); - } - catch (Exception e) - { - fail("No exception expected, valid levels and xml were used"); - } - - _testConfigFile = createTempTestLog4JConfig("info", "debug", false, false); - try - { - QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath()); - } - catch (Exception e) - { - fail("No exception expected, valid levels and xml were used"); - } - - _testConfigFile = createTempTestLog4JConfig("info", "info", false, false); - try - { - QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath()); - } - catch (Exception e) - { - fail("No exception expected, valid levels and xml were used"); - } - - _testConfigFile = createTempTestLog4JConfig("info", "warn", false, false); - try - { - QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath()); - } - catch (Exception e) - { - fail("No exception expected, valid levels and xml were used"); - } - - _testConfigFile = createTempTestLog4JConfig("info", "error", false, false); - try - { - QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath()); - } - catch (Exception e) - { - fail("No exception expected, valid levels and xml were used"); - } - - _testConfigFile = createTempTestLog4JConfig("info", "fatal", false, false); - try - { - QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath()); - } - catch (Exception e) - { - fail("No exception expected, valid levels and xml were used"); - } - - _testConfigFile = createTempTestLog4JConfig("info", "off", false, false); - try - { - QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath()); - } - catch (Exception e) - { - fail("No exception expected, valid levels and xml were used"); - } - - _testConfigFile = createTempTestLog4JConfig("info", "null", false, false); - try - { - QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath()); - } - catch (Exception e) - { - fail("No exception expected, valid levels and xml were used"); - } - - _testConfigFile = createTempTestLog4JConfig("info", "inherited", false, false); - try - { - QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath()); - } - catch (Exception e) - { - fail("No exception expected, valid levels and xml were used"); - } - - _testConfigFile = createTempTestLog4JConfig("info", "debug", false, false); - try - { - QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath()); - } - catch (Exception e) - { - fail("No exception expected, valid levels and xml were used"); - } - - //now try an invalid logger level - _testConfigFile = createTempTestLog4JConfig("info", "madeup", false, false); - try - { - QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath()); - fail("IllegalLoggerLevelException expected, invalid levels used"); - } - catch (IllegalLoggerLevelException e) - { - //expected, ignore - } - catch (IOException e) - { - fail("Incorrect Exception, expected an IllegalLoggerLevelException"); - } - - - - //now try invalid xml - _testConfigFile = createTempTestLog4JConfig("info", "info", true, false); - try - { - QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath()); - fail("IOException expected, malformed XML used"); - } - catch (IllegalLoggerLevelException e) - { - fail("Incorrect Exception, expected an IOException"); - } - catch (IOException e) - { - //expected, ignore - } - - _testConfigFile = createTempTestLog4JConfig("info", "info", false, true); - try - { - QpidLog4JConfigurator.checkLoggerLevels(_testConfigFile.getAbsolutePath()); - fail("IOException expected, malformed XML used"); - } - catch (IllegalLoggerLevelException e) - { - //expected, ignore - } - catch (IOException e) - { - fail("Incorrect Exception, expected an IllegalLoggerLevelException"); - } - } -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/AMQBrokerManagerMBeanTest.java b/java/broker/src/test/java/org/apache/qpid/server/AMQBrokerManagerMBeanTest.java deleted file mode 100644 index 5c500771c2..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/AMQBrokerManagerMBeanTest.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server; - -import org.apache.commons.configuration.XMLConfiguration; - -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.management.common.mbeans.ManagedBroker; -import org.apache.qpid.server.configuration.ServerConfiguration; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.exchange.ExchangeRegistry; -import org.apache.qpid.server.logging.SystemOutMessageLogger; -import org.apache.qpid.server.logging.actors.CurrentActor; -import org.apache.qpid.server.logging.actors.TestLogActor; -import org.apache.qpid.server.queue.AMQPriorityQueue; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.AMQQueueFactory; -import org.apache.qpid.server.queue.QueueRegistry; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.registry.IApplicationRegistry; -import org.apache.qpid.server.store.TestableMemoryMessageStore; -import org.apache.qpid.server.store.TestableMemoryMessageStoreFactory; -import org.apache.qpid.server.util.TestApplicationRegistry; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.test.utils.QpidTestCase; - -import java.util.HashMap; -import java.util.Map; - -public class AMQBrokerManagerMBeanTest extends QpidTestCase -{ - private QueueRegistry _queueRegistry; - private ExchangeRegistry _exchangeRegistry; - private VirtualHost _vHost; - - public void testExchangeOperations() throws Exception - { - String exchange1 = "testExchange1_" + System.currentTimeMillis(); - String exchange2 = "testExchange2_" + System.currentTimeMillis(); - String exchange3 = "testExchange3_" + System.currentTimeMillis(); - - assertTrue(_exchangeRegistry.getExchange(new AMQShortString(exchange1)) == null); - assertTrue(_exchangeRegistry.getExchange(new AMQShortString(exchange2)) == null); - assertTrue(_exchangeRegistry.getExchange(new AMQShortString(exchange3)) == null); - - - ManagedBroker mbean = new AMQBrokerManagerMBean((VirtualHostImpl.VirtualHostMBean) _vHost.getManagedObject()); - mbean.createNewExchange(exchange1, "direct", false); - mbean.createNewExchange(exchange2, "topic", false); - mbean.createNewExchange(exchange3, "headers", false); - - assertTrue(_exchangeRegistry.getExchange(new AMQShortString(exchange1)) != null); - assertTrue(_exchangeRegistry.getExchange(new AMQShortString(exchange2)) != null); - assertTrue(_exchangeRegistry.getExchange(new AMQShortString(exchange3)) != null); - - mbean.unregisterExchange(exchange1); - mbean.unregisterExchange(exchange2); - mbean.unregisterExchange(exchange3); - - assertTrue(_exchangeRegistry.getExchange(new AMQShortString(exchange1)) == null); - assertTrue(_exchangeRegistry.getExchange(new AMQShortString(exchange2)) == null); - assertTrue(_exchangeRegistry.getExchange(new AMQShortString(exchange3)) == null); - } - - public void testQueueOperations() throws Exception - { - String queueName = "testQueue_" + System.currentTimeMillis(); - - ManagedBroker mbean = new AMQBrokerManagerMBean((VirtualHostImpl.VirtualHostMBean) _vHost.getManagedObject()); - - assertTrue(_queueRegistry.getQueue(new AMQShortString(queueName)) == null); - - mbean.createNewQueue(queueName, "test", false); - assertTrue(_queueRegistry.getQueue(new AMQShortString(queueName)) != null); - - mbean.deleteQueue(queueName); - assertTrue(_queueRegistry.getQueue(new AMQShortString(queueName)) == null); - } - - public void testCreateNewQueueBindsToDefaultExchange() throws Exception - { - String queueName = "testQueue_" + System.currentTimeMillis(); - - ManagedBroker mbean = new AMQBrokerManagerMBean((VirtualHostImpl.VirtualHostMBean) _vHost.getManagedObject()); - ExchangeRegistry exReg = _vHost.getExchangeRegistry(); - Exchange defaultExchange = exReg.getDefaultExchange(); - - mbean.createNewQueue(queueName, "test", false); - assertTrue(_queueRegistry.getQueue(new AMQShortString(queueName)) != null); - - assertTrue("New queue should be bound to default exchange", defaultExchange.isBound(new AMQShortString(queueName))); - } - - /** - * Tests that setting the {@link AMQQueueFactory#X_QPID_MAXIMUM_DELIVERY_COUNT} argument does cause the - * maximum delivery count to be set on the Queue. - */ - public void testCreateNewQueueWithMaximumDeliveryCount() throws Exception - { - final Map<String,Object> args = new HashMap<String, Object>(); - args.put(AMQQueueFactory.X_QPID_MAXIMUM_DELIVERY_COUNT, 5); - - final AMQShortString queueName = new AMQShortString("testCreateNewQueueWithMaximumDeliveryCount"); - - final QueueRegistry qReg = _vHost.getQueueRegistry(); - - assertNull("The queue should not yet exist", qReg.getQueue(queueName)); - - final ManagedBroker mbean = new AMQBrokerManagerMBean((VirtualHostImpl.VirtualHostMBean) _vHost.getManagedObject()); - mbean.createNewQueue(queueName.asString(), "test", false, args); - - final AMQQueue createdQueue = qReg.getQueue(queueName); - assertNotNull("The queue was not registered as expected", createdQueue); - assertEquals("Unexpected maximum delivery count", 5, createdQueue.getMaximumDeliveryCount()); - } - - /** - * Tests that setting the {@link AMQQueueFactory#X_QPID_PRIORITIES} argument prompts creation of - * a Priority Queue. - */ - public void testCreatePriorityQueue() throws Exception - { - int numPriorities = 7; - Map<String,Object> args = new HashMap<String, Object>(); - args.put(AMQQueueFactory.X_QPID_PRIORITIES, numPriorities); - - AMQShortString queueName = new AMQShortString("testCreatePriorityQueue"); - - QueueRegistry qReg = _vHost.getQueueRegistry(); - - assertNull("The queue should not yet exist", qReg.getQueue(queueName)); - - ManagedBroker mbean = new AMQBrokerManagerMBean((VirtualHostImpl.VirtualHostMBean) _vHost.getManagedObject()); - mbean.createNewQueue(queueName.asString(), "test", false, args); - - AMQQueue queue = qReg.getQueue(queueName); - assertEquals("Queue is not a priorty queue", AMQPriorityQueue.class, queue.getClass()); - assertEquals("Number of priorities supported was not as expected", numPriorities, ((AMQPriorityQueue)queue).getPriorities()); - } - - @Override - public void setUp() throws Exception - { - super.setUp(); - - CurrentActor.set(new TestLogActor(new SystemOutMessageLogger())); - - XMLConfiguration configXml = new XMLConfiguration(); - configXml.addProperty("virtualhosts.virtualhost(-1).name", "test"); - configXml.addProperty("virtualhosts.virtualhost(-1).test.store.factoryclass", TestableMemoryMessageStoreFactory.class.getName()); - - ServerConfiguration configuration = new ServerConfiguration(configXml); - - ApplicationRegistry registry = new TestApplicationRegistry(configuration); - ApplicationRegistry.initialise(registry); - registry.getVirtualHostRegistry().setDefaultVirtualHostName("test"); - - IApplicationRegistry appRegistry = ApplicationRegistry.getInstance(); - _vHost = appRegistry.getVirtualHostRegistry().getVirtualHost("test"); - _queueRegistry = _vHost.getQueueRegistry(); - _exchangeRegistry = _vHost.getExchangeRegistry(); - } - - @Override - public void tearDown() throws Exception - { - try - { - super.tearDown(); - } - finally - { - ApplicationRegistry.remove(); - } - } -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/BrokerOptionsTest.java b/java/broker/src/test/java/org/apache/qpid/server/BrokerOptionsTest.java index bb20e0200b..43824e713f 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/BrokerOptionsTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/BrokerOptionsTest.java @@ -199,4 +199,31 @@ public class BrokerOptionsTest extends QpidTestCase _options.setLogWatchFrequency(myFreq); assertEquals(myFreq, _options.getLogWatchFrequency()); } + + public void testDefaultIncludesPortFor0_10() + { + assertEquals(Collections.EMPTY_SET, _options.getIncludedPorts(ProtocolInclusion.v0_10)); + } + + public void testOverriddenIncludesPortFor0_10() + { + _options.addIncludedPort(ProtocolInclusion.v0_10, TEST_PORT1); + assertEquals(Collections.singleton(TEST_PORT1), _options.getIncludedPorts(ProtocolInclusion.v0_10)); + } + + public void testManyOverriddenIncludedPortFor0_10() + { + _options.addIncludedPort(ProtocolInclusion.v0_10, TEST_PORT1); + _options.addIncludedPort(ProtocolInclusion.v0_10, TEST_PORT2); + final Set<Integer> expectedPorts = new HashSet<Integer>(Arrays.asList(new Integer[] {TEST_PORT1, TEST_PORT2})); + assertEquals(expectedPorts, _options.getIncludedPorts(ProtocolInclusion.v0_10)); + } + + public void testDuplicatedOverriddenIncludedPortFor0_10AreSilentlyIgnored() + { + _options.addIncludedPort(ProtocolInclusion.v0_10, TEST_PORT1); + _options.addIncludedPort(ProtocolInclusion.v0_10, TEST_PORT2); + final Set<Integer> expectedPorts = new HashSet<Integer>(Arrays.asList(new Integer[] {TEST_PORT1, TEST_PORT2})); + assertEquals(expectedPorts, _options.getIncludedPorts(ProtocolInclusion.v0_10)); + } } diff --git a/java/broker/src/test/java/org/apache/qpid/server/MainTest.java b/java/broker/src/test/java/org/apache/qpid/server/MainTest.java index 31d5028536..ffd607574e 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/MainTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/MainTest.java @@ -47,6 +47,11 @@ public class MainTest extends QpidTestCase { assertEquals(0, options.getExcludedPorts(pe).size()); } + + for(ProtocolInclusion pe : EnumSet.allOf(ProtocolInclusion.class)) + { + assertEquals(0, options.getIncludedPorts(pe).size()); + } } public void testPortOverriddenSingle() @@ -162,6 +167,20 @@ public class MainTest extends QpidTestCase assertTrue("Parsed command line didnt pick up help option", main.getCommandLine().hasOption("h")); } + public void testInclude010() + { + BrokerOptions options = startDummyMain("-p 5678 --include-0-10 5678"); + + assertTrue(options.getPorts().contains(5678)); + assertEquals(1, options.getPorts().size()); + assertTrue(options.getIncludedPorts(ProtocolInclusion.v0_10).contains(5678)); + assertEquals(1, options.getIncludedPorts(ProtocolInclusion.v0_10).size()); + assertEquals(0, options.getIncludedPorts(ProtocolInclusion.v0_9_1).size()); + assertEquals(0, options.getIncludedPorts(ProtocolInclusion.v0_9).size()); + assertEquals(0, options.getIncludedPorts(ProtocolInclusion.v0_8).size()); + assertEquals(0, options.getIncludedPorts(ProtocolInclusion.v1_0).size()); + } + private BrokerOptions startDummyMain(String commandLine) { return (new TestMain(commandLine.split("\\s"))).getOptions(); diff --git a/java/broker/src/test/java/org/apache/qpid/server/TransactionTimeoutHelperTest.java b/java/broker/src/test/java/org/apache/qpid/server/TransactionTimeoutHelperTest.java new file mode 100644 index 0000000000..9081dc49d6 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/TransactionTimeoutHelperTest.java @@ -0,0 +1,101 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.qpid.server; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.same; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +import org.apache.qpid.server.logging.LogActor; +import org.apache.qpid.server.logging.LogMessage; +import org.apache.qpid.server.logging.LogSubject; +import org.apache.qpid.server.logging.RootMessageLogger; +import org.apache.qpid.server.logging.actors.CurrentActor; +import org.apache.qpid.test.utils.QpidTestCase; + +public class TransactionTimeoutHelperTest extends QpidTestCase +{ + private final LogMessage _logMessage = mock(LogMessage.class); + private final LogActor _logActor = mock(LogActor.class); + private final LogSubject _logSubject = mock(LogSubject.class); + private TransactionTimeoutHelper _transactionTimeoutHelper; + private RootMessageLogger _rootMessageLogger; + + public void testLogIfNecessary() + { + _transactionTimeoutHelper.logIfNecessary(99, 100, _logMessage, ""); + verifyZeroInteractions(_logActor, _logMessage); + + _transactionTimeoutHelper.logIfNecessary(101, 100, _logMessage, ""); + verify(_logActor).message(_logSubject, _logMessage); + } + + public void testLogIfNecessaryWhenOperationalLoggingDisabled() + { + //disable the operational logging + when(_rootMessageLogger.isMessageEnabled( + same(_logActor), any(LogSubject.class), any(String.class))) + .thenReturn(false); + + //verify the actor is never asked to log a message + _transactionTimeoutHelper.logIfNecessary(101, 100, _logMessage, ""); + verify(_logActor, never()).message(any(LogMessage.class)); + verify(_logActor, never()).message(any(LogSubject.class), any(LogMessage.class)); + } + + public void testIsTimedOut() + { + assertFalse("Shouldn't have timed out", _transactionTimeoutHelper.isTimedOut(199,200)); + assertTrue("Should have timed out", _transactionTimeoutHelper.isTimedOut(201,200)); + } + + /** + * If TransactionTimeout is disabled, the timeout will be 0. This test verifies + * that the helper methods respond negatively in this scenario. + */ + public void testTransactionTimeoutDisabled() + { + assertFalse("Shouldn't have timed out", _transactionTimeoutHelper.isTimedOut(201,0)); + + _transactionTimeoutHelper.logIfNecessary(99, 0, _logMessage, ""); + verifyZeroInteractions(_logActor, _logMessage); + } + + @Override + protected void setUp() throws Exception + { + super.setUp(); + + CurrentActor.set(_logActor); + + _rootMessageLogger = mock(RootMessageLogger.class); + when(_logActor.getRootMessageLogger()).thenReturn(_rootMessageLogger); + + when(_rootMessageLogger.isMessageEnabled( + same(_logActor), any(LogSubject.class), any(String.class))) + .thenReturn(true); + + _transactionTimeoutHelper = new TransactionTimeoutHelper(_logSubject); + } + +} diff --git a/java/broker/src/test/java/org/apache/qpid/server/configuration/MockConnectionConfig.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/MockConnectionConfig.java index c0777d2f8f..00e5cd1222 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/configuration/MockConnectionConfig.java +++ b/java/broker/src/test/java/org/apache/qpid/server/configuration/MockConnectionConfig.java @@ -25,14 +25,14 @@ import java.util.UUID; public class MockConnectionConfig implements ConnectionConfig { - public MockConnectionConfig(UUID _id, ConnectionConfigType _configType, + public MockConnectionConfig(UUID _qmfId, ConnectionConfigType _configType, ConfiguredObject<ConnectionConfigType, ConnectionConfig> _parent, boolean _durable, long _createTime, VirtualHostConfig _virtualHost, String _address, Boolean _incoming, Boolean _systemConnection, Boolean _federationLink, String _authId, String _remoteProcessName, Integer _remotePID, Integer _remoteParentPID, ConfigStore _configStore, Boolean _shadow) { super(); - this._id = _id; + this._qmfId = _qmfId; this._configType = _configType; this._parent = _parent; this._durable = _durable; @@ -50,7 +50,7 @@ public class MockConnectionConfig implements ConnectionConfig this._shadow = _shadow; } - private UUID _id; + private UUID _qmfId; private ConnectionConfigType _configType; private ConfiguredObject<ConnectionConfigType, ConnectionConfig> _parent; private boolean _durable; @@ -68,9 +68,9 @@ public class MockConnectionConfig implements ConnectionConfig private Boolean _shadow; @Override - public UUID getId() + public UUID getQMFId() { - return _id; + return _qmfId; } @Override diff --git a/java/broker/src/test/java/org/apache/qpid/server/configuration/QueueConfigurationTest.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/QueueConfigurationTest.java index 36f131a30f..3c5b85cd90 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/configuration/QueueConfigurationTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/configuration/QueueConfigurationTest.java @@ -176,20 +176,29 @@ public class QueueConfigurationTest extends TestCase assertEquals(1, qConf.getMaximumMessageCount()); } - public void testGetMinimumAlertRepeatGap() throws ConfigurationException + public void testGetMinimumAlertRepeatGap() throws Exception { - // Check default value - QueueConfiguration qConf = new QueueConfiguration("test", _emptyConf); - assertEquals(0, qConf.getMinimumAlertRepeatGap()); + try + { + ApplicationRegistry registry = new TestApplicationRegistry(new ServerConfiguration(_env)); + ApplicationRegistry.initialise(registry); + // Check default value + QueueConfiguration qConf = new QueueConfiguration("test", _emptyConf); + assertEquals(ServerConfiguration.DEFAULT_MINIMUM_ALERT_REPEAT_GAP, qConf.getMinimumAlertRepeatGap()); - // Check explicit value - VirtualHostConfiguration vhostConfig = overrideConfiguration("minimumAlertRepeatGap", 2); - qConf = new QueueConfiguration("test", vhostConfig); - assertEquals(2, qConf.getMinimumAlertRepeatGap()); + // Check explicit value + VirtualHostConfiguration vhostConfig = overrideConfiguration("minimumAlertRepeatGap", 2); + qConf = new QueueConfiguration("test", vhostConfig); + assertEquals(2, qConf.getMinimumAlertRepeatGap()); - // Check inherited value - qConf = new QueueConfiguration("test", _fullHostConf); - assertEquals(1, qConf.getMinimumAlertRepeatGap()); + // Check inherited value + qConf = new QueueConfiguration("test", _fullHostConf); + assertEquals(1, qConf.getMinimumAlertRepeatGap()); + } + finally + { + ApplicationRegistry.remove(); + } } public void testSortQueueConfiguration() throws ConfigurationException @@ -204,6 +213,18 @@ public class QueueConfigurationTest extends TestCase assertEquals("test-sort-key", qConf.getQueueSortKey()); } + public void testQueueDescription() throws ConfigurationException + { + //Check default value + QueueConfiguration qConf = new QueueConfiguration("test", _emptyConf); + assertNull(qConf.getDescription()); + + // Check explicit value + final VirtualHostConfiguration vhostConfig = overrideConfiguration("description", "mydescription"); + qConf = new QueueConfiguration("test", vhostConfig); + assertEquals("mydescription", qConf.getDescription()); + } + private VirtualHostConfiguration overrideConfiguration(String property, Object value) throws ConfigurationException { diff --git a/java/broker/src/test/java/org/apache/qpid/server/configuration/ServerConfigurationTest.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/ServerConfigurationTest.java index 4caefc2f18..660ff5e7d4 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/configuration/ServerConfigurationTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/configuration/ServerConfigurationTest.java @@ -25,6 +25,7 @@ import org.apache.commons.configuration.XMLConfiguration; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.server.exchange.Exchange; +import org.apache.qpid.server.protocol.AmqpProtocolVersion; import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.registry.ConfigurationFileApplicationRegistry; import org.apache.qpid.server.util.TestApplicationRegistry; @@ -251,13 +252,13 @@ public class ServerConfigurationTest extends QpidTestCase { // Check default _serverConfig.initialise(); - assertEquals(true, _serverConfig.getManagementSSLEnabled()); + assertEquals(false, _serverConfig.getManagementSSLEnabled()); // Check value we set - _config.setProperty("management.ssl.enabled", false); + _config.setProperty("management.ssl.enabled", true); _serverConfig = new ServerConfiguration(_config); _serverConfig.initialise(); - assertEquals(false, _serverConfig.getManagementSSLEnabled()); + assertEquals(true, _serverConfig.getManagementSSLEnabled()); } public void testGetManagementKeystorePassword() throws ConfigurationException @@ -286,25 +287,17 @@ public class ServerConfigurationTest extends QpidTestCase assertEquals(false, _serverConfig.getQueueAutoRegister()); } - public void testGetManagementEnabled() throws ConfigurationException + public void testGetJMXManagementEnabled() throws ConfigurationException { // Check default _serverConfig.initialise(); - assertEquals(true, _serverConfig.getManagementEnabled()); + assertEquals(true, _serverConfig.getJMXManagementEnabled()); // Check value we set _config.setProperty("management.enabled", false); _serverConfig = new ServerConfiguration(_config); _serverConfig.initialise(); - assertEquals(false, _serverConfig.getManagementEnabled()); - } - - public void testSetManagementEnabled() throws ConfigurationException - { - // Check value we set - _serverConfig.initialise(); - _serverConfig.setManagementEnabled(false); - assertEquals(false, _serverConfig.getManagementEnabled()); + assertEquals(false, _serverConfig.getJMXManagementEnabled()); } public void testGetManagementRightsInferAllAccess() throws Exception @@ -401,7 +394,7 @@ public class ServerConfigurationTest extends QpidTestCase { // Check default _serverConfig.initialise(); - assertEquals(0, _serverConfig.getMinimumAlertRepeatGap()); + assertEquals(30000l, _serverConfig.getMinimumAlertRepeatGap()); // Check value we set _config.setProperty("minimumAlertRepeatGap", 10L); @@ -1588,6 +1581,168 @@ public class ServerConfigurationTest extends QpidTestCase assertEquals(false, _serverConfig.isAmqp08enabled()); } + public void testPortInclude08() throws ConfigurationException + { + // Check default + _serverConfig.initialise(); + assertEquals(true, _serverConfig.getPortInclude08().isEmpty()); + + // Check values we set + _config.addProperty(ServerConfiguration.CONNECTOR_INCLUDE_08, "1"); + _config.addProperty(ServerConfiguration.CONNECTOR_INCLUDE_08, "2"); + _serverConfig = new ServerConfiguration(_config); + _serverConfig.initialise(); + assertEquals(2, _serverConfig.getPortInclude08().size()); + assertTrue(_serverConfig.getPortInclude08().contains("1")); + assertTrue(_serverConfig.getPortInclude08().contains("2")); + } + + public void testPortInclude09() throws ConfigurationException + { + // Check default + _serverConfig.initialise(); + assertEquals(true, _serverConfig.getPortInclude09().isEmpty()); + + // Check values we set + _config.addProperty(ServerConfiguration.CONNECTOR_INCLUDE_09, "3"); + _config.addProperty(ServerConfiguration.CONNECTOR_INCLUDE_09, "4"); + _serverConfig = new ServerConfiguration(_config); + _serverConfig.initialise(); + assertEquals(2, _serverConfig.getPortInclude09().size()); + assertTrue(_serverConfig.getPortInclude09().contains("3")); + assertTrue(_serverConfig.getPortInclude09().contains("4")); + } + + public void testPortInclude091() throws ConfigurationException + { + // Check default + _serverConfig.initialise(); + assertEquals(true, _serverConfig.getPortInclude091().isEmpty()); + + // Check values we set + _config.addProperty(ServerConfiguration.CONNECTOR_INCLUDE_091, "5"); + _config.addProperty(ServerConfiguration.CONNECTOR_INCLUDE_091, "6"); + _serverConfig = new ServerConfiguration(_config); + _serverConfig.initialise(); + assertEquals(2, _serverConfig.getPortInclude091().size()); + assertTrue(_serverConfig.getPortInclude091().contains("5")); + assertTrue(_serverConfig.getPortInclude091().contains("6")); + } + + public void testPortInclude010() throws ConfigurationException + { + // Check default + _serverConfig.initialise(); + assertEquals(true, _serverConfig.getPortInclude010().isEmpty()); + + // Check values we set + _config.addProperty(ServerConfiguration.CONNECTOR_INCLUDE_010, "7"); + _config.addProperty(ServerConfiguration.CONNECTOR_INCLUDE_010, "8"); + _serverConfig = new ServerConfiguration(_config); + _serverConfig.initialise(); + assertEquals(2, _serverConfig.getPortInclude010().size()); + assertTrue(_serverConfig.getPortInclude010().contains("7")); + assertTrue(_serverConfig.getPortInclude010().contains("8")); + } + + public void testPortInclude10() throws ConfigurationException + { + // Check default + _serverConfig.initialise(); + assertEquals(true, _serverConfig.getPortInclude10().isEmpty()); + + // Check values we set + _config.addProperty(ServerConfiguration.CONNECTOR_INCLUDE_10, "9"); + _config.addProperty(ServerConfiguration.CONNECTOR_INCLUDE_10, "10"); + _serverConfig = new ServerConfiguration(_config); + _serverConfig.initialise(); + assertEquals(2, _serverConfig.getPortInclude10().size()); + assertTrue(_serverConfig.getPortInclude10().contains("9")); + assertTrue(_serverConfig.getPortInclude10().contains("10")); + } + + public void testGetDefaultSupportedProtocolReply() throws Exception + { + // Check default + _serverConfig.initialise(); + assertNull("unexpected default value", _serverConfig.getDefaultSupportedProtocolReply()); + + // Check values we set + _config.addProperty(ServerConfiguration.CONNECTOR_AMQP_SUPPORTED_REPLY, "v0_10"); + _serverConfig = new ServerConfiguration(_config); + _serverConfig.initialise(); + assertEquals(AmqpProtocolVersion.v0_10, _serverConfig.getDefaultSupportedProtocolReply()); + } + + public void testDefaultAuthenticationManager() throws Exception + { + // Check default + _serverConfig.initialise(); + assertNull("unexpected default value", _serverConfig.getDefaultAuthenticationManager()); + + // Check values we set + String testAuthManager = "myauthmanager"; + _config.addProperty("security.default-auth-manager", testAuthManager); + _serverConfig = new ServerConfiguration(_config); + _serverConfig.initialise(); + assertEquals(testAuthManager, _serverConfig.getDefaultAuthenticationManager()); + } + + public void testPortAuthenticationMappingsDefault() throws Exception + { + _serverConfig.initialise(); + assertEquals("unexpected default number of port/authmanager mappings", 0, _serverConfig.getPortAuthenticationMappings().size()); + } + + public void testPortAuthenticationMappingsWithSingleMapping() throws Exception + { + String testAuthManager = "myauthmanager"; + _config.addProperty("security.port-mappings.port-mapping.port", 1234); + _config.addProperty("security.port-mappings.port-mapping.auth-manager", testAuthManager); + + _serverConfig = new ServerConfiguration(_config); + _serverConfig.initialise(); + assertEquals("unexpected number of port/authmanager mappings", 1, _serverConfig.getPortAuthenticationMappings().size()); + assertEquals("unexpected mapping for port", testAuthManager, _serverConfig.getPortAuthenticationMappings().get(1234)); + } + + public void testPortAuthenticationMappingsWithManyMapping() throws Exception + { + String testAuthManager1 = "myauthmanager1"; + String testAuthManager2 = "myauthmanager2"; + _config.addProperty("security.port-mappings.port-mapping(-1).port", 1234); + _config.addProperty("security.port-mappings.port-mapping.auth-manager", testAuthManager1); + + _config.addProperty("security.port-mappings.port-mapping(-1).port", 2345); + _config.addProperty("security.port-mappings.port-mapping.auth-manager", testAuthManager2); + + _serverConfig = new ServerConfiguration(_config); + _serverConfig.initialise(); + + assertEquals("unexpected number of port/authmanager mappings", 2, _serverConfig.getPortAuthenticationMappings().size()); + assertEquals("unexpected mapping for port", testAuthManager1, _serverConfig.getPortAuthenticationMappings().get(1234)); + assertEquals("unexpected mapping for port", testAuthManager2, _serverConfig.getPortAuthenticationMappings().get(2345)); + } + + public void testPortAuthenticationMappingWithMissingAuthManager() throws Exception + { + _config.addProperty("security.port-mappings.port-mapping(-1).port", 1234); + // no auth manager defined for port + _serverConfig = new ServerConfiguration(_config); + try + { + _serverConfig.initialise(); + fail("Exception not thrown"); + } + catch(ConfigurationException ce) + { + // PASS + assertEquals("Incorrect error message", + "Validation error: Each port-mapping must have exactly one port and exactly one auth-manager.", + ce.getMessage()); + } + } + /** * Convenience method to output required security preamble for broker config */ @@ -1605,7 +1760,6 @@ public class ServerConfigurationTest extends QpidTestCase out.write("\t\t\t\t\t</attribute>\n"); out.write("\t\t\t\t</attributes>\n"); out.write("\t\t\t</principal-database>\n"); - out.write("\t\t\t<jmx-access>/dev/null</jmx-access>\n"); out.write("\t\t</pd-auth-manager>\n"); out.write("\t</security>\n"); } diff --git a/java/broker/src/test/java/org/apache/qpid/server/configuration/TopicConfigurationTest.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/TopicConfigurationTest.java index 59cd0cf1db..caf74a89ec 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/configuration/TopicConfigurationTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/configuration/TopicConfigurationTest.java @@ -26,8 +26,8 @@ import org.apache.qpid.AMQException; import org.apache.qpid.AMQInternalException; import org.apache.qpid.AMQSecurityException; import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.server.exchange.Exchange; +import org.apache.qpid.server.model.UUIDGenerator; import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.queue.AMQQueueFactory; import org.apache.qpid.server.util.InternalBrokerBaseCase; @@ -77,7 +77,7 @@ public class TopicConfigurationTest extends InternalBrokerBaseCase public void testSubscriptionWithTopicCreation() throws ConfigurationException, AMQException { - AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString(getName()+":stockSubscription"), false, new AMQShortString("testowner"), + AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), getName()+":stockSubscription", false, "testowner", false, false, getVirtualHost(), null); getVirtualHost().getQueueRegistry().registerQueue(queue); @@ -107,7 +107,7 @@ public class TopicConfigurationTest extends InternalBrokerBaseCase public void testSubscriptionCreation() throws ConfigurationException, AMQException { - AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString(getName()+":stockSubscription"), false, new AMQShortString("testowner"), + AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID() ,getName()+":stockSubscription", false, "testowner", false, false, getVirtualHost(), null); getVirtualHost().getQueueRegistry().registerQueue(queue); diff --git a/java/broker/src/test/java/org/apache/qpid/server/configuration/VirtualHostConfigurationTest.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/VirtualHostConfigurationTest.java index c4c93acfb6..50e7f0588b 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/configuration/VirtualHostConfigurationTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/configuration/VirtualHostConfigurationTest.java @@ -27,7 +27,6 @@ import org.apache.qpid.server.queue.AMQPriorityQueue; import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.store.TestableMemoryMessageStore; -import org.apache.qpid.server.store.TestableMemoryMessageStoreFactory; import org.apache.qpid.server.util.InternalBrokerBaseCase; import org.apache.qpid.server.virtualhost.VirtualHost; @@ -162,7 +161,7 @@ public class VirtualHostConfigurationTest extends InternalBrokerBaseCase getConfigXml().addProperty("virtualhosts.virtualhost." + getName() + "Extra.queues(-1).queue(-1).name", "r2d2"); getConfigXml().addProperty("virtualhosts.virtualhost." + getName() + "Extra.queues.queue.r2d2.deadLetterQueues", "true"); getConfigXml().addProperty("virtualhosts.virtualhost." + getName() + "Extra.queues(-1).queue(-1).name", "c3p0"); - getConfigXml().addProperty("virtualhosts.virtualhost." + getName() + "Extra.store.factoryclass", TestableMemoryMessageStoreFactory.class.getName()); + getConfigXml().addProperty("virtualhosts.virtualhost." + getName() + "Extra.store.class", TestableMemoryMessageStore.class.getName()); // Start the broker now. super.createBroker(); diff --git a/java/broker/src/test/java/org/apache/qpid/server/exchange/AbstractHeadersExchangeTestBase.java b/java/broker/src/test/java/org/apache/qpid/server/exchange/AbstractHeadersExchangeTestBase.java index afd8fd9ed2..4befd26ece 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/exchange/AbstractHeadersExchangeTestBase.java +++ b/java/broker/src/test/java/org/apache/qpid/server/exchange/AbstractHeadersExchangeTestBase.java @@ -83,7 +83,7 @@ public class AbstractHeadersExchangeTestBase extends InternalBrokerBaseCase protected void unbind(TestQueue queue, String... bindings) throws AMQException { String queueName = queue.getName(); - exchange.onUnbind(new Binding(null,queueName, queue, exchange, getHeadersMap(bindings))); + exchange.onUnbind(new Binding(null, null, queueName, queue, exchange, getHeadersMap(bindings))); } protected int getCount() @@ -95,7 +95,7 @@ public class AbstractHeadersExchangeTestBase extends InternalBrokerBaseCase { TestQueue queue = new TestQueue(new AMQShortString(queueName)); queues.add(queue); - exchange.onBind(new Binding(null,key, queue, exchange, args)); + exchange.onBind(new Binding(null, null, key, queue, exchange, args)); return queue; } @@ -276,7 +276,7 @@ public class AbstractHeadersExchangeTestBase extends InternalBrokerBaseCase public TestQueue(AMQShortString name) throws AMQException { - super(UUIDGenerator.generateUUID(), name, false, new AMQShortString("test"), true, false,ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost("test"), Collections.EMPTY_MAP); + super(UUIDGenerator.generateRandomUUID(), name, false, new AMQShortString("test"), true, false,ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost("test"), Collections.EMPTY_MAP); ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost("test").getQueueRegistry().registerQueue(this); } diff --git a/java/broker/src/test/java/org/apache/qpid/server/exchange/ExchangeMBeanTest.java b/java/broker/src/test/java/org/apache/qpid/server/exchange/ExchangeMBeanTest.java deleted file mode 100644 index 9034bf9c3a..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/exchange/ExchangeMBeanTest.java +++ /dev/null @@ -1,235 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.exchange; - -import org.apache.commons.lang.ArrayUtils; - -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.management.common.mbeans.ManagedExchange; -import org.apache.qpid.server.management.ManagedObject; -import org.apache.qpid.server.model.UUIDGenerator; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.AMQQueueFactory; -import org.apache.qpid.server.queue.QueueRegistry; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.registry.IApplicationRegistry; -import org.apache.qpid.server.util.InternalBrokerBaseCase; -import org.apache.qpid.server.virtualhost.VirtualHost; - -import javax.management.JMException; -import javax.management.openmbean.CompositeDataSupport; -import javax.management.openmbean.TabularData; -import java.util.ArrayList; -import java.util.Iterator; - -/** - * Unit test class for testing different Exchange MBean operations - */ -public class ExchangeMBeanTest extends InternalBrokerBaseCase -{ - private AMQQueue _queue; - private QueueRegistry _queueRegistry; - private VirtualHost _virtualHost; - - public void testGeneralProperties() throws Exception - { - DirectExchange exchange = new DirectExchange(); - exchange.initialise(UUIDGenerator.generateUUID(), _virtualHost, ExchangeDefaults.DIRECT_EXCHANGE_NAME, false, 0, true); - ManagedObject managedObj = exchange.getManagedObject(); - ManagedExchange mbean = (ManagedExchange)managedObj; - - // test general exchange properties - assertEquals("Unexpected exchange name", "amq.direct", mbean.getName()); - assertEquals("Unexpected exchange type", "direct", mbean.getExchangeType()); - assertEquals("Unexpected ticket number", Integer.valueOf(0), mbean.getTicketNo()); - assertFalse("Unexpected durable flag", mbean.isDurable()); - assertTrue("Unexpected auto delete flag", mbean.isAutoDelete()); - } - - public void testDirectExchangeMBean() throws Exception - { - DirectExchange exchange = new DirectExchange(); - exchange.initialise(UUIDGenerator.generateUUID(), _virtualHost, ExchangeDefaults.DIRECT_EXCHANGE_NAME, false, 0, true); - ManagedObject managedObj = exchange.getManagedObject(); - ManagedExchange mbean = (ManagedExchange)managedObj; - - mbean.createNewBinding(_queue.getNameShortString().toString(), "binding1"); - mbean.createNewBinding(_queue.getNameShortString().toString(), "binding2"); - - TabularData data = mbean.bindings(); - ArrayList<Object> list = new ArrayList<Object>(data.values()); - assertTrue(list.size() == 2); - } - - public void testTopicExchangeMBean() throws Exception - { - TopicExchange exchange = new TopicExchange(); - exchange.initialise(UUIDGenerator.generateUUID(), _virtualHost,ExchangeDefaults.TOPIC_EXCHANGE_NAME, false, 0, true); - ManagedObject managedObj = exchange.getManagedObject(); - ManagedExchange mbean = (ManagedExchange)managedObj; - - mbean.createNewBinding(_queue.getNameShortString().toString(), "binding1"); - mbean.createNewBinding(_queue.getNameShortString().toString(), "binding2"); - - TabularData data = mbean.bindings(); - ArrayList<Object> list = new ArrayList<Object>(data.values()); - assertTrue(list.size() == 2); - } - - public void testHeadersExchangeMBean() throws Exception - { - HeadersExchange exchange = new HeadersExchange(); - exchange.initialise(UUIDGenerator.generateUUID(), _virtualHost,ExchangeDefaults.HEADERS_EXCHANGE_NAME, false, 0, true); - ManagedObject managedObj = exchange.getManagedObject(); - ManagedExchange mbean = (ManagedExchange)managedObj; - - mbean.createNewBinding(_queue.getNameShortString().toString(), "x-match=any,key1=binding1,key2=binding2"); - - TabularData data = mbean.bindings(); - ArrayList<Object> list = new ArrayList<Object>(data.values()); - assertEquals("Unexpected number of bindings", 1, list.size()); - - final Iterator<CompositeDataSupport> rowItr = (Iterator<CompositeDataSupport>) data.values().iterator(); - CompositeDataSupport row = rowItr.next(); - assertBinding(1, _queue.getName(), new String[]{"x-match=any","key1=binding1","key2=binding2"}, row); - } - - /** - * Included to ensure 0-10 Specification compliance: - * 2.3.1.4 "the field in the bind arguments has no value and a field of the same name is present in the message headers - */ - public void testHeadersExchangeMBeanMatchPropertyNoValue() throws Exception - { - HeadersExchange exchange = new HeadersExchange(); - exchange.initialise(UUIDGenerator.generateUUID(), _virtualHost,ExchangeDefaults.HEADERS_EXCHANGE_NAME, false, 0, true); - ManagedObject managedObj = exchange.getManagedObject(); - ManagedExchange mbean = (ManagedExchange)managedObj; - - mbean.createNewBinding(_queue.getNameShortString().toString(), "x-match=any,key4,key5="); - - TabularData data = mbean.bindings(); - ArrayList<Object> list = new ArrayList<Object>(data.values()); - assertEquals("Unexpected number of bindings", 1, list.size()); - - final Iterator<CompositeDataSupport> rowItr = (Iterator<CompositeDataSupport>) data.values().iterator(); - CompositeDataSupport row = rowItr.next(); - assertBinding(1, _queue.getName(), new String[]{"x-match=any","key4=","key5="}, row); - } - - public void testInvalidHeaderBindingMalformed() throws Exception - { - HeadersExchange exchange = new HeadersExchange(); - exchange.initialise(UUIDGenerator.generateUUID(), _virtualHost,ExchangeDefaults.HEADERS_EXCHANGE_NAME, false, 0, true); - ManagedObject managedObj = exchange.getManagedObject(); - ManagedExchange mbean = (ManagedExchange)managedObj; - - try - { - mbean.createNewBinding(_queue.getNameShortString().toString(), "x-match=any,=value4"); - fail("Exception not thrown"); - } - catch (JMException jme) - { - //pass - } - } - - private void assertBinding(final int expectedBindingNo, final String expectedQueueName, final String[] expectedBindingArray, - final CompositeDataSupport row) - { - final Number bindingNumber = (Number) row.get(ManagedExchange.HDR_BINDING_NUMBER); - final String queueName = (String) row.get(ManagedExchange.HDR_QUEUE_NAME); - final String[] bindings = (String[]) row.get(ManagedExchange.HDR_QUEUE_BINDINGS); - assertEquals("Unexpected binding number", expectedBindingNo, bindingNumber); - assertEquals("Unexpected queue name", expectedQueueName, queueName); - assertEquals("Unexpected no of bindings", expectedBindingArray.length, bindings.length); - for(String binding : bindings) - { - assertTrue("Expected binding not found: " + binding, ArrayUtils.contains(expectedBindingArray, binding)); - } - } - - /** - * Test adding bindings and removing them from the default exchange via JMX. - * <p> - * QPID-2700 - */ - public void testDefaultBindings() throws Exception - { - int bindings = _queue.getBindingCount(); - - Exchange exchange = _queue.getVirtualHost().getExchangeRegistry().getDefaultExchange(); - ManagedExchange mbean = (ManagedExchange) ((AbstractExchange) exchange).getManagedObject(); - - mbean.createNewBinding(_queue.getName(), "robot"); - mbean.createNewBinding(_queue.getName(), "kitten"); - - assertEquals("Should have added two bindings", bindings + 2, _queue.getBindingCount()); - - mbean.removeBinding(_queue.getName(), "robot"); - - assertEquals("Should have one extra binding", bindings + 1, _queue.getBindingCount()); - - mbean.removeBinding(_queue.getName(), "kitten"); - - assertEquals("Should have original number of binding", bindings, _queue.getBindingCount()); - } - - /** - * Test adding bindings and removing them from the topic exchange via JMX. - * <p> - * QPID-2700 - */ - public void testTopicBindings() throws Exception - { - int bindings = _queue.getBindingCount(); - - Exchange exchange = _queue.getVirtualHost().getExchangeRegistry().getExchange(new AMQShortString("amq.topic")); - ManagedExchange mbean = (ManagedExchange) ((AbstractExchange) exchange).getManagedObject(); - - mbean.createNewBinding(_queue.getName(), "robot.#"); - mbean.createNewBinding(_queue.getName(), "#.kitten"); - - assertEquals("Should have added two bindings", bindings + 2, _queue.getBindingCount()); - - mbean.removeBinding(_queue.getName(), "robot.#"); - - assertEquals("Should have one extra binding", bindings + 1, _queue.getBindingCount()); - - mbean.removeBinding(_queue.getName(), "#.kitten"); - - assertEquals("Should have original number of binding", bindings, _queue.getBindingCount()); - } - - @Override - public void setUp() throws Exception - { - super.setUp(); - - IApplicationRegistry applicationRegistry = ApplicationRegistry.getInstance(); - _virtualHost = applicationRegistry.getVirtualHostRegistry().getVirtualHost("test"); - _queueRegistry = _virtualHost.getQueueRegistry(); - _queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("testQueue"), false, new AMQShortString("ExchangeMBeanTest"), false, false, - _virtualHost, null); - _queueRegistry.registerQueue(_queue); - } -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersBindingTest.java b/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersBindingTest.java index 4305cdadc6..3988edcb3c 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersBindingTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersBindingTest.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -20,6 +20,7 @@ */ package org.apache.qpid.server.exchange; +import java.util.Collection; import junit.framework.TestCase; import org.apache.qpid.server.binding.Binding; @@ -50,6 +51,16 @@ public class HeadersBindingTest extends TestCase return 0; } + public String getUserId() + { + return null; + } + + public String getAppId() + { + return null; + } + public String getMessageId() { return null; @@ -57,7 +68,7 @@ public class HeadersBindingTest extends TestCase public String getMimeType() { - return null; //To change body of implemented methods use File | Settings | File Templates. + return null; } public String getEncoding() @@ -105,6 +116,12 @@ public class HeadersBindingTest extends TestCase return _headers.keySet().containsAll(names); } + @Override + public Collection<String> getHeaderNames() + { + return _headers.keySet(); + } + public boolean containsHeader(String name) { return _headers.containsKey(name); @@ -125,13 +142,13 @@ public class HeadersBindingTest extends TestCase private MockHeader matchHeaders = new MockHeader(); private int _count = 0; private MockAMQQueue _queue; - + protected void setUp() { _count++; _queue = new MockAMQQueue(getQueueName()); } - + protected String getQueueName() { return "Queue" + _count; @@ -143,7 +160,7 @@ public class HeadersBindingTest extends TestCase matchHeaders.setString("A", "Value of A"); - Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); + Binding b = new Binding(null, null, getQueueName(), _queue, null, bindHeaders); assertTrue(new HeadersBinding(b).matches(matchHeaders)); } @@ -154,7 +171,7 @@ public class HeadersBindingTest extends TestCase matchHeaders.setString("A", "Value of A"); matchHeaders.setString("B", "Value of B"); - Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); + Binding b = new Binding(null, null, getQueueName(), _queue, null, bindHeaders); assertTrue(new HeadersBinding(b).matches(matchHeaders)); } @@ -164,7 +181,7 @@ public class HeadersBindingTest extends TestCase matchHeaders.setString("A", "Altered value of A"); - Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); + Binding b = new Binding(null, null, getQueueName(), _queue, null, bindHeaders); assertFalse(new HeadersBinding(b).matches(matchHeaders)); } @@ -175,7 +192,7 @@ public class HeadersBindingTest extends TestCase matchHeaders.setString("A", "Value of A"); - Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); + Binding b = new Binding(null, null, getQueueName(), _queue, null, bindHeaders); assertTrue(new HeadersBinding(b).matches(matchHeaders)); } @@ -187,7 +204,7 @@ public class HeadersBindingTest extends TestCase matchHeaders.setString("A", "Value of A"); - Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); + Binding b = new Binding(null, null, getQueueName(), _queue, null, bindHeaders); assertFalse(new HeadersBinding(b).matches(matchHeaders)); } @@ -200,7 +217,7 @@ public class HeadersBindingTest extends TestCase matchHeaders.setString("A", "Value of A"); matchHeaders.setString("B", "Value of B"); - Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); + Binding b = new Binding(null, null, getQueueName(), _queue, null, bindHeaders); assertTrue(new HeadersBinding(b).matches(matchHeaders)); } @@ -214,7 +231,7 @@ public class HeadersBindingTest extends TestCase matchHeaders.setString("B", "Value of B"); matchHeaders.setString("C", "Value of C"); - Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); + Binding b = new Binding(null, null, getQueueName(), _queue, null, bindHeaders); assertTrue(new HeadersBinding(b).matches(matchHeaders)); } @@ -228,7 +245,7 @@ public class HeadersBindingTest extends TestCase matchHeaders.setString("B", "Altered value of B"); matchHeaders.setString("C", "Value of C"); - Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); + Binding b = new Binding(null, null, getQueueName(), _queue, null, bindHeaders); assertFalse(new HeadersBinding(b).matches(matchHeaders)); } @@ -239,7 +256,7 @@ public class HeadersBindingTest extends TestCase matchHeaders.setString("A", "Value of A"); - Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); + Binding b = new Binding(null, null, getQueueName(), _queue, null, bindHeaders); assertTrue(new HeadersBinding(b).matches(matchHeaders)); } @@ -251,7 +268,7 @@ public class HeadersBindingTest extends TestCase matchHeaders.setString("A", "Value of A"); - Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); + Binding b = new Binding(null, null, getQueueName(), _queue, null, bindHeaders); assertTrue(new HeadersBinding(b).matches(matchHeaders)); } @@ -264,7 +281,7 @@ public class HeadersBindingTest extends TestCase matchHeaders.setString("A", "Value of A"); matchHeaders.setString("B", "Value of B"); - Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); + Binding b = new Binding(null, null, getQueueName(), _queue, null, bindHeaders); assertTrue(new HeadersBinding(b).matches(matchHeaders)); } @@ -278,7 +295,7 @@ public class HeadersBindingTest extends TestCase matchHeaders.setString("B", "Value of B"); matchHeaders.setString("C", "Value of C"); - Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); + Binding b = new Binding(null, null, getQueueName(), _queue, null, bindHeaders); assertTrue(new HeadersBinding(b).matches(matchHeaders)); } @@ -292,7 +309,7 @@ public class HeadersBindingTest extends TestCase matchHeaders.setString("B", "Altered value of B"); matchHeaders.setString("C", "Value of C"); - Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); + Binding b = new Binding(null, null, getQueueName(), _queue, null, bindHeaders); assertTrue(new HeadersBinding(b).matches(matchHeaders)); } @@ -306,7 +323,7 @@ public class HeadersBindingTest extends TestCase matchHeaders.setString("B", "Altered value of B"); matchHeaders.setString("C", "Value of C"); - Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); + Binding b = new Binding(null, null, getQueueName(), _queue, null, bindHeaders); assertFalse(new HeadersBinding(b).matches(matchHeaders)); } diff --git a/java/broker/src/test/java/org/apache/qpid/server/exchange/TopicExchangeTest.java b/java/broker/src/test/java/org/apache/qpid/server/exchange/TopicExchangeTest.java index 00c8a18d9f..92274afece 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/exchange/TopicExchangeTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/exchange/TopicExchangeTest.java @@ -30,6 +30,7 @@ import org.apache.qpid.framing.abstraction.MessagePublishInfo; import org.apache.qpid.server.binding.Binding; import org.apache.qpid.server.message.AMQMessage; import org.apache.qpid.server.message.MessageMetaData; +import org.apache.qpid.server.model.UUIDGenerator; import org.apache.qpid.server.protocol.InternalTestProtocolSession; import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.queue.AMQQueueFactory; @@ -64,8 +65,8 @@ public class TopicExchangeTest extends InternalBrokerBaseCase public void testNoRoute() throws AMQException { - AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("a*#b"), false, null, false, false, _vhost, null); - _exchange.registerQueue(new Binding(null,"a.*.#.b", queue,_exchange, null)); + AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), "a*#b", false, null, false, false, _vhost, null); + _exchange.registerQueue(new Binding(null, null, "a.*.#.b",queue, _exchange, null)); IncomingMessage message = createMessage("a.b"); @@ -76,8 +77,8 @@ public class TopicExchangeTest extends InternalBrokerBaseCase public void testDirectMatch() throws AMQException { - AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("ab"), false, null, false, false, _vhost, null); - _exchange.registerQueue(new Binding(null,"a.b", queue,_exchange, null)); + AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), "ab", false, null, false, false, _vhost, null); + _exchange.registerQueue(new Binding(null, null, "a.b",queue, _exchange, null)); IncomingMessage message = createMessage("a.b"); @@ -103,8 +104,8 @@ public class TopicExchangeTest extends InternalBrokerBaseCase public void testStarMatch() throws AMQException { - AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("a*"), false, null, false, false, _vhost, null); - _exchange.registerQueue(new Binding(null,"a.*", queue,_exchange, null)); + AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), "a*", false, null, false, false, _vhost, null); + _exchange.registerQueue(new Binding(null, null, "a.*",queue, _exchange, null)); IncomingMessage message = createMessage("a.b"); @@ -142,8 +143,8 @@ public class TopicExchangeTest extends InternalBrokerBaseCase public void testHashMatch() throws AMQException { - AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("a#"), false, null, false, false, _vhost, null); - _exchange.registerQueue(new Binding(null,"a.#", queue,_exchange, null)); + AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), "a#", false, null, false, false, _vhost, null); + _exchange.registerQueue(new Binding(null, null, "a.#",queue, _exchange, null)); IncomingMessage message = createMessage("a.b.c"); @@ -205,8 +206,8 @@ public class TopicExchangeTest extends InternalBrokerBaseCase public void testMidHash() throws AMQException { - AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("a"), false, null, false, false, _vhost, null); - _exchange.registerQueue(new Binding(null,"a.*.#.b", queue,_exchange, null)); + AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), "a", false, null, false, false, _vhost, null); + _exchange.registerQueue(new Binding(null, null, "a.*.#.b",queue, _exchange, null)); IncomingMessage message = createMessage("a.c.d.b"); @@ -235,8 +236,8 @@ public class TopicExchangeTest extends InternalBrokerBaseCase public void testMatchafterHash() throws AMQException { - AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("a#"), false, null, false, false, _vhost, null); - _exchange.registerQueue(new Binding(null,"a.*.#.b.c", queue,_exchange, null)); + AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), "a#", false, null, false, false, _vhost, null); + _exchange.registerQueue(new Binding(null, null, "a.*.#.b.c",queue, _exchange, null)); IncomingMessage message = createMessage("a.c.b.b"); @@ -281,8 +282,8 @@ public class TopicExchangeTest extends InternalBrokerBaseCase public void testHashAfterHash() throws AMQException { - AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("a#"), false, null, false, false, _vhost, null); - _exchange.registerQueue(new Binding(null,"a.*.#.b.c.#.d", queue,_exchange, null)); + AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), "a#", false, null, false, false, _vhost, null); + _exchange.registerQueue(new Binding(null, null, "a.*.#.b.c.#.d",queue, _exchange, null)); IncomingMessage message = createMessage("a.c.b.b.c"); @@ -308,8 +309,8 @@ public class TopicExchangeTest extends InternalBrokerBaseCase public void testHashHash() throws AMQException { - AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("a#"), false, null, false, false, _vhost, null); - _exchange.registerQueue(new Binding(null,"a.#.*.#.d", queue,_exchange, null)); + AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), "a#", false, null, false, false, _vhost, null); + _exchange.registerQueue(new Binding(null, null, "a.#.*.#.d",queue, _exchange, null)); IncomingMessage message = createMessage("a.c.b.b.c"); @@ -334,8 +335,8 @@ public class TopicExchangeTest extends InternalBrokerBaseCase public void testSubMatchFails() throws AMQException { - AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("a"), false, null, false, false, _vhost, null); - _exchange.registerQueue(new Binding(null,"a.b.c.d", queue,_exchange, null)); + AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), "a", false, null, false, false, _vhost, null); + _exchange.registerQueue(new Binding(null, null, "a.b.c.d",queue, _exchange, null)); IncomingMessage message = createMessage("a.b.c"); @@ -364,8 +365,8 @@ public class TopicExchangeTest extends InternalBrokerBaseCase public void testMoreRouting() throws AMQException { - AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("a"), false, null, false, false, _vhost, null); - _exchange.registerQueue(new Binding(null,"a.b", queue,_exchange, null)); + AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), "a", false, null, false, false, _vhost, null); + _exchange.registerQueue(new Binding(null, null, "a.b",queue, _exchange, null)); IncomingMessage message = createMessage("a.b.c"); @@ -379,8 +380,8 @@ public class TopicExchangeTest extends InternalBrokerBaseCase public void testMoreQueue() throws AMQException { - AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("a"), false, null, false, false, _vhost, null); - _exchange.registerQueue(new Binding(null,"a.b", queue,_exchange, null)); + AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), "a", false, null, false, false, _vhost, null); + _exchange.registerQueue(new Binding(null, null, "a.b",queue, _exchange, null)); IncomingMessage message = createMessage("a"); diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/log4j/LoggingFacadeTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/log4j/LoggingFacadeTest.java new file mode 100644 index 0000000000..f871baffe6 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/logging/log4j/LoggingFacadeTest.java @@ -0,0 +1,245 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.logging.log4j; + +import java.io.File; +import java.util.List; +import java.util.Map; + +import org.apache.log4j.Level; +import org.apache.qpid.util.FileUtils; + +import junit.framework.TestCase; + +public class LoggingFacadeTest extends TestCase +{ + private LoggingFacade _loggingFacade; + private String _log4jXmlFile; + + @Override + protected void setUp() throws Exception + { + super.setUp(); + _log4jXmlFile = createTestLog4jXml(); + _loggingFacade = LoggingFacade.configure(_log4jXmlFile); + } + + public void testGetAvailableLoggerLevels() throws Exception + { + List<String> levels = _loggingFacade.getAvailableLoggerLevels(); + assertTrue(levels.contains("ALL")); + assertTrue(levels.contains("TRACE")); + assertTrue(levels.contains("DEBUG")); + assertTrue(levels.contains("INFO")); + assertTrue(levels.contains("WARN")); + assertTrue(levels.contains("ERROR")); + assertTrue(levels.contains("FATAL")); + assertTrue(levels.contains("OFF")); + assertEquals(8, levels.size()); + } + + public void testRetrieveConfigFileRootLoggerLevel() throws Exception + { + String level = _loggingFacade.retrieveConfigFileRootLoggerLevel(); + assertEquals(Level.WARN.toString(), level); + } + + public void testSetConfigFileRootLoggerLevel() throws Exception + { + String oldLevel = _loggingFacade.retrieveConfigFileRootLoggerLevel(); + assertEquals("WARN", oldLevel); + + _loggingFacade.setConfigFileRootLoggerLevel("INFO"); + + String level = _loggingFacade.retrieveConfigFileRootLoggerLevel(); + assertEquals("INFO", level); + } + + public void testRetrieveConfigFileLoggerLevels() throws Exception + { + Map<String, String> levels = _loggingFacade.retrieveConfigFileLoggersLevels(); + assertEquals(3, levels.size()); + String abcLevel = levels.get("a.b.c"); + String abc1Level = levels.get("a.b.c.1"); + String abc2Level = levels.get("a.b.c.2"); + assertEquals("INFO", abcLevel); + assertEquals("DEBUG", abc1Level); + assertEquals("TRACE", abc2Level); + } + + public void testSetConfigFileLoggerLevels() throws Exception + { + final String loggerName = "a.b.c"; + + assertConfigFileLoggingLevel(loggerName, "INFO"); + + _loggingFacade.setConfigFileLoggerLevel(loggerName, "WARN"); + + Map<String, String> levels = _loggingFacade.retrieveConfigFileLoggersLevels(); + String abcLevel = levels.get(loggerName); + assertEquals("WARN", abcLevel); + } + + public void testSetConfigFileLoggerLevelsWhereLoggerDoesNotExist() throws Exception + { + try + { + _loggingFacade.setConfigFileLoggerLevel("does.not.exist", "WARN"); + fail("Exception not thrown"); + } + catch (LoggingFacadeException lfe) + { + // PASS + assertEquals("Can't find logger does.not.exist", lfe.getMessage()); + } + } + + public void testRetrieveRuntimeRootLoggerLevel() throws Exception + { + String level = _loggingFacade.retrieveRuntimeRootLoggerLevel(); + assertEquals(Level.WARN.toString(), level); + } + + public void testSetRuntimeRootLoggerLevel() throws Exception + { + String oldLevel = _loggingFacade.retrieveRuntimeRootLoggerLevel(); + assertEquals("WARN", oldLevel); + + _loggingFacade.setRuntimeRootLoggerLevel("INFO"); + + String level = _loggingFacade.retrieveRuntimeRootLoggerLevel(); + assertEquals("INFO", level); + } + + public void testRetrieveRuntimeLoggersLevels() throws Exception + { + Map<String, String> levels = _loggingFacade.retrieveRuntimeLoggersLevels(); + // Don't assert size as implementation itself uses logging and we'd count its loggers too + String abcLevel = levels.get("a.b.c"); + String abc1Level = levels.get("a.b.c.1"); + String abc2Level = levels.get("a.b.c.2"); + assertEquals("INFO", abcLevel); + assertEquals("DEBUG", abc1Level); + assertEquals("TRACE", abc2Level); + } + + public void testSetRuntimeLoggerLevel() throws Exception + { + final String loggerName = "a.b.c"; + + assertRuntimeLoggingLevel(loggerName, "INFO"); + + _loggingFacade.setRuntimeLoggerLevel(loggerName, "WARN"); + + assertRuntimeLoggingLevel(loggerName, "WARN"); + } + + public void testSetRuntimeLoggerToInheritFromParent() throws Exception + { + final String parentLoggerName = "a.b.c"; + final String childLoggerName = "a.b.c.1"; + + assertRuntimeLoggingLevel(parentLoggerName, "INFO"); + assertRuntimeLoggingLevel(childLoggerName, "DEBUG"); + + _loggingFacade.setRuntimeLoggerLevel(childLoggerName, null); + + assertRuntimeLoggingLevel(parentLoggerName, "INFO"); + assertRuntimeLoggingLevel(childLoggerName, "INFO"); + } + + public void testSetRuntimeLoggerLevelsWhereLoggerDoesNotExist() throws Exception + { + final String loggerName = "does.not.exist2"; + + Map<String, String> oldLevels = _loggingFacade.retrieveRuntimeLoggersLevels(); + assertFalse(oldLevels.containsKey(loggerName)); + + try + { + _loggingFacade.setRuntimeLoggerLevel(loggerName, "WARN"); + fail("Exception not thrown"); + } + catch (LoggingFacadeException lfe) + { + // PASS + assertEquals("Can't find logger " + loggerName, lfe.getMessage()); + } + + Map<String, String> levels = _loggingFacade.retrieveRuntimeLoggersLevels(); + assertFalse(levels.containsKey(loggerName)); + } + + public void testReloadOfChangedLog4JFileUpdatesRuntimeLogLevel() throws Exception + { + final String loggerName = "a.b.c"; + + assertRuntimeLoggingLevel(loggerName, "INFO"); + assertConfigFileLoggingLevel(loggerName, "INFO"); + + _loggingFacade.setConfigFileLoggerLevel(loggerName, "WARN"); + + assertRuntimeLoggingLevel(loggerName, "INFO"); + + _loggingFacade.reload(); + + assertRuntimeLoggingLevel(loggerName, "WARN"); + } + + + public void testReloadOfLog4JFileRevertsRuntimeChanges() throws Exception + { + final String loggerName = "a.b.c"; + + assertRuntimeLoggingLevel(loggerName, "INFO"); + assertConfigFileLoggingLevel(loggerName, "INFO"); + + _loggingFacade.setRuntimeLoggerLevel(loggerName, "WARN"); + + assertRuntimeLoggingLevel(loggerName, "WARN"); + + _loggingFacade.reload(); + + assertRuntimeLoggingLevel(loggerName, "INFO"); + } + + private void assertConfigFileLoggingLevel(final String loggerName, String expectedLevel) throws Exception + { + Map<String, String> levels = _loggingFacade.retrieveConfigFileLoggersLevels(); + String actualLevel = levels.get(loggerName); + assertEquals(expectedLevel, actualLevel); + } + + private void assertRuntimeLoggingLevel(final String loggerName, String expectedLevel) throws Exception + { + Map<String, String> levels = _loggingFacade.retrieveRuntimeLoggersLevels(); + String actualLevel = levels.get(loggerName); + assertEquals(expectedLevel, actualLevel); + } + + private String createTestLog4jXml() throws Exception + { + File dst = File.createTempFile("log4j." + getName(), "xml"); + File filename = new File(getClass().getResource("LoggingFacadeTest.log4j.xml").toURI()); + FileUtils.copy(filename, dst); + dst.deleteOnExit(); + return dst.getAbsolutePath(); + } +} diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/log4j/LoggingFacadeTest.log4j.xml b/java/broker/src/test/java/org/apache/qpid/server/logging/log4j/LoggingFacadeTest.log4j.xml new file mode 100644 index 0000000000..62ec877d3d --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/logging/log4j/LoggingFacadeTest.log4j.xml @@ -0,0 +1,41 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + - + - Licensed to the Apache Software Foundation (ASF) under one + - or more contributor license agreements. See the NOTICE file + - distributed with this work for additional information + - regarding copyright ownership. The ASF licenses this file + - to you under the Apache License, Version 2.0 (the + - "License"); you may not use this file except in compliance + - with the License. You may obtain a copy of the License at + - + - http://www.apache.org/licenses/LICENSE-2.0 + - + - Unless required by applicable law or agreed to in writing, + - software distributed under the License is distributed on an + - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + - KIND, either express or implied. See the License for the + - specific language governing permissions and limitations + - under the License. + - + --><!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> + +<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="null" threshold="null"> + + <category additivity="true" name="a.b.c"> + <priority value="INFO"/> + </category> + + <logger additivity="true" name="a.b.c.1"> + <level value="DEBUG"/> + </logger> + + <logger additivity="true" name="a.b.c.2"> + <level value="TRACE"/> + </logger> + + <root> + <priority value="WARN"/> + </root> + +</log4j:configuration> diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/management/LoggingManagementMBeanTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/management/LoggingManagementMBeanTest.java deleted file mode 100644 index f9ad81ae74..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/logging/management/LoggingManagementMBeanTest.java +++ /dev/null @@ -1,428 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.logging.management; - -import org.apache.log4j.Level; -import org.apache.log4j.Logger; - -import org.apache.qpid.server.util.InternalBrokerBaseCase; - -import static org.apache.qpid.management.common.mbeans.LoggingManagement.LOGGER_LEVEL; -import static org.apache.qpid.management.common.mbeans.LoggingManagement.LOGGER_NAME; - -import javax.management.JMException; -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.TabularDataSupport; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -public class LoggingManagementMBeanTest extends InternalBrokerBaseCase -{ - private static final String TEST_LOGGER = "LoggingManagementMBeanTestLogger"; - private static final String TEST_LOGGER_CHILD1 = "LoggingManagementMBeanTestLogger.child1"; - private static final String TEST_LOGGER_CHILD2 = "LoggingManagementMBeanTestLogger.child2"; - - private static final String TEST_CATEGORY_PRIORITY = "LogManMBeanTest.category.priority"; - private static final String TEST_CATEGORY_LEVEL = "LogManMBeanTest.category.level"; - private static final String TEST_LOGGER_LEVEL = "LogManMBeanTest.logger.level"; - - private static final String NEWLINE = System.getProperty("line.separator"); - - private File _testConfigFile; - - @Override - public void setUp() throws Exception - { - super.setUp(); - _testConfigFile = createTempTestLog4JConfig(); - } - - @Override - public void tearDown() throws Exception - { - File oldTestConfigFile = new File(_testConfigFile.getAbsolutePath() + ".old"); - if(oldTestConfigFile.exists()) - { - oldTestConfigFile.delete(); - } - - _testConfigFile.delete(); - - super.tearDown(); - } - - private File createTempTestLog4JConfig() - { - File tmpFile = null; - try - { - tmpFile = File.createTempFile("LogManMBeanTestLog4jConfig", ".tmp"); - tmpFile.deleteOnExit(); - - FileWriter fstream = new FileWriter(tmpFile); - BufferedWriter writer = new BufferedWriter(fstream); - - writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+NEWLINE); - writer.write("<!DOCTYPE log4j:configuration SYSTEM \"log4j.dtd\">"+NEWLINE); - - writer.write("<log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\" debug=\"null\" " + - "threshold=\"null\">"+NEWLINE); - - writer.write(" <appender class=\"org.apache.log4j.ConsoleAppender\" name=\"STDOUT\">"+NEWLINE); - writer.write(" <layout class=\"org.apache.log4j.PatternLayout\">"+NEWLINE); - writer.write(" <param name=\"ConversionPattern\" value=\"%d %-5p [%t] %C{2} (%F:%L) - %m%n\"/>"+NEWLINE); - writer.write(" </layout>"+NEWLINE); - writer.write(" </appender>"+NEWLINE); - - //Example of a 'category' with a 'priority' - writer.write(" <category additivity=\"true\" name=\"" + TEST_CATEGORY_PRIORITY +"\">"+NEWLINE); - writer.write(" <priority value=\"info\"/>"+NEWLINE); - writer.write(" <appender-ref ref=\"STDOUT\"/>"+NEWLINE); - writer.write(" </category>"+NEWLINE); - - //Example of a 'category' with a 'level' - writer.write(" <category additivity=\"true\" name=\"" + TEST_CATEGORY_LEVEL +"\">"+NEWLINE); - writer.write(" <level value=\"warn\"/>"+NEWLINE); - writer.write(" <appender-ref ref=\"STDOUT\"/>"+NEWLINE); - writer.write(" </category>"+NEWLINE); - - //Example of a 'logger' with a 'level' - writer.write(" <logger additivity=\"true\" name=\"" + TEST_LOGGER_LEVEL + "\">"+NEWLINE); - writer.write(" <level value=\"error\"/>"+NEWLINE); - writer.write(" <appender-ref ref=\"STDOUT\"/>"+NEWLINE); - writer.write(" </logger>"+NEWLINE); - - //'root' logger - writer.write(" <root>"+NEWLINE); - writer.write(" <priority value=\"info\"/>"+NEWLINE); - writer.write(" <appender-ref ref=\"STDOUT\"/>"+NEWLINE); - writer.write(" </root>"+NEWLINE); - - writer.write("</log4j:configuration>"+NEWLINE); - - writer.flush(); - writer.close(); - } - catch (IOException e) - { - fail("Unable to create temporary test log4j configuration"); - } - - return tmpFile; - } - - - - //******* Test Methods ******* // - - public void testSetRuntimeLoggerLevel() - { - LoggingManagementMBean lm = null; - try - { - lm = new LoggingManagementMBean(_testConfigFile.getAbsolutePath(), 0); - } - catch (JMException e) - { - fail("Could not create test LoggingManagementMBean"); - } - - //create a parent test logger, set its level explicitly - Logger log = Logger.getLogger(TEST_LOGGER); - log.setLevel(Level.toLevel("info")); - - //create child1 test logger, check its *effective* level is the same as the parent, "info" - Logger log1 = Logger.getLogger(TEST_LOGGER_CHILD1); - assertTrue("Test logger's level was not the expected value", - log1.getEffectiveLevel().toString().equalsIgnoreCase("info")); - - //now change its level to "warn" - assertTrue("Failed to set logger level", lm.setRuntimeLoggerLevel(TEST_LOGGER_CHILD1, "warn")); - - //check the change, see its actual level is "warn - assertTrue("Test logger's level was not the expected value", - log1.getLevel().toString().equalsIgnoreCase("warn")); - - //try an invalid level - assertFalse("Trying to set an invalid level succeded", lm.setRuntimeLoggerLevel(TEST_LOGGER_CHILD1, "made.up.level")); - } - - public void testSetRuntimeRootLoggerLevel() - { - LoggingManagementMBean lm = null; - try - { - lm = new LoggingManagementMBean(_testConfigFile.getAbsolutePath(), 0); - } - catch (JMException e) - { - fail("Could not create test LoggingManagementMBean"); - } - - Logger log = Logger.getRootLogger(); - - //get current root logger level - Level origLevel = log.getLevel(); - - //change level twice to ensure a new level is actually selected - - //set root loggers level to info - assertTrue("Failed to set root logger level", lm.setRuntimeRootLoggerLevel("debug")); - //check it is now actually info - Level currentLevel = log.getLevel(); - assertTrue("Logger level was not expected value", currentLevel.equals(Level.toLevel("debug"))); - - //try an invalid level - assertFalse("Trying to set an invalid level succeded", lm.setRuntimeRootLoggerLevel("made.up.level")); - - //set root loggers level to warn - assertTrue("Failed to set logger level", lm.setRuntimeRootLoggerLevel("info")); - //check it is now actually warn - currentLevel = log.getLevel(); - assertTrue("Logger level was not expected value", currentLevel.equals(Level.toLevel("info"))); - - //restore original level - log.setLevel(origLevel); - } - - public void testGetRuntimeRootLoggerLevel() - { - LoggingManagementMBean lm = null; - try - { - lm = new LoggingManagementMBean(_testConfigFile.getAbsolutePath(), 0); - } - catch (JMException e) - { - fail("Could not create test LoggingManagementMBean"); - } - - Logger log = Logger.getRootLogger(); - - //get current root logger level - Level origLevel = log.getLevel(); - - //change level twice to ensure a new level is actually selected - - //set root loggers level to debug - log.setLevel(Level.toLevel("debug")); - //check it is now actually debug - assertTrue("Logger level was not expected value", lm.getRuntimeRootLoggerLevel().equalsIgnoreCase("debug")); - - - //set root loggers level to warn - log.setLevel(Level.toLevel("info")); - //check it is now actually warn - assertTrue("Logger level was not expected value", lm.getRuntimeRootLoggerLevel().equalsIgnoreCase("info")); - - //restore original level - log.setLevel(origLevel); - } - - public void testViewEffectiveRuntimeLoggerLevels() - { - LoggingManagementMBean lm = null; - try - { - lm = new LoggingManagementMBean(_testConfigFile.getAbsolutePath(), 0); - } - catch (JMException e) - { - fail("Could not create test LoggingManagementMBean"); - } - - //(re)create a parent test logger, set its level explicitly - Logger log = Logger.getLogger(TEST_LOGGER); - log.setLevel(Level.toLevel("info")); - - //retrieve the current effective runtime logger level values - TabularDataSupport levels = (TabularDataSupport) lm.viewEffectiveRuntimeLoggerLevels(); - Collection<Object> records = levels.values(); - Map<String,String> list = new HashMap<String,String>(); - for (Object o : records) - { - CompositeData data = (CompositeData) o; - list.put(data.get(LOGGER_NAME).toString(), data.get(LOGGER_LEVEL).toString()); - } - - //check child2 does not exist already - assertFalse("Did not expect this logger to exist already", list.containsKey(TEST_LOGGER_CHILD2)); - - //create child2 test logger - Logger log2 = Logger.getLogger(TEST_LOGGER_CHILD2); - - //retrieve the current effective runtime logger level values - levels = (TabularDataSupport) lm.viewEffectiveRuntimeLoggerLevels(); - records = levels.values(); - list = new HashMap<String,String>(); - for (Object o : records) - { - CompositeData data = (CompositeData) o; - list.put(data.get(LOGGER_NAME).toString(), data.get(LOGGER_LEVEL).toString()); - } - - //verify the parent and child2 loggers are present in returned values - assertTrue(TEST_LOGGER + " logger was not in the returned list", list.containsKey(TEST_LOGGER)); - assertTrue(TEST_LOGGER_CHILD2 + " logger was not in the returned list", list.containsKey(TEST_LOGGER_CHILD2)); - - //check child2's effective level is the same as the parent, "info" - assertTrue("Test logger's level was not the expected value", - list.get(TEST_LOGGER_CHILD2).equalsIgnoreCase("info")); - - //now change its level explicitly to "warn" - log2.setLevel(Level.toLevel("warn")); - - //retrieve the current effective runtime logger level values - levels = (TabularDataSupport) lm.viewEffectiveRuntimeLoggerLevels(); - records = levels.values(); - list = new HashMap<String,String>(); - for (Object o : records) - { - CompositeData data = (CompositeData) o; - list.put(data.get(LOGGER_NAME).toString(), data.get(LOGGER_LEVEL).toString()); - } - - //check child2's effective level is now "warn" - assertTrue("Test logger's level was not the expected value", - list.get(TEST_LOGGER_CHILD2).equalsIgnoreCase("warn")); - } - - public void testViewAndSetConfigFileLoggerLevel() throws Exception - { - LoggingManagementMBean lm =null; - try - { - lm = new LoggingManagementMBean(_testConfigFile.getAbsolutePath(), 0); - } - catch (JMException e) - { - fail("Could not create test LoggingManagementMBean"); - } - - //retrieve the current values - TabularDataSupport levels = (TabularDataSupport) lm.viewConfigFileLoggerLevels(); - Collection<Object> records = levels.values(); - Map<String,String> list = new HashMap<String,String>(); - for (Object o : records) - { - CompositeData data = (CompositeData) o; - list.put(data.get(LOGGER_NAME).toString(), data.get(LOGGER_LEVEL).toString()); - } - - //check the 3 different types of logger definition are successfully retrieved before update - assertTrue("Wrong number of items in returned list", list.size() == 3); - assertTrue(TEST_CATEGORY_PRIORITY + " logger was not in the returned list", list.containsKey(TEST_CATEGORY_PRIORITY)); - assertTrue(TEST_CATEGORY_LEVEL + " logger was not in the returned list", list.containsKey(TEST_CATEGORY_LEVEL)); - assertTrue(TEST_LOGGER_LEVEL + " logger was not in the returned list", list.containsKey(TEST_LOGGER_LEVEL)); - - //check that their level is as expected - assertTrue(TEST_CATEGORY_PRIORITY + " logger's level was incorrect", list.get(TEST_CATEGORY_PRIORITY).equalsIgnoreCase("info")); - assertTrue(TEST_CATEGORY_LEVEL + " logger's level was incorrect", list.get(TEST_CATEGORY_LEVEL).equalsIgnoreCase("warn")); - assertTrue(TEST_LOGGER_LEVEL + " logger's level was incorrect", list.get(TEST_LOGGER_LEVEL).equalsIgnoreCase("error")); - - //increase their levels a notch to test the 3 different types of logger definition are successfully updated - //change the category+priority to warn - assertTrue("failed to set new level", lm.setConfigFileLoggerLevel(TEST_CATEGORY_PRIORITY, "warn")); - //change the category+level to error - assertTrue("failed to set new level", lm.setConfigFileLoggerLevel(TEST_CATEGORY_LEVEL, "error")); - //change the logger+level to trace - assertTrue("failed to set new level", lm.setConfigFileLoggerLevel(TEST_LOGGER_LEVEL, "trace")); - - //try an invalid level - assertFalse("Use of an invalid logger level was successfull", lm.setConfigFileLoggerLevel(TEST_LOGGER_LEVEL, "made.up.level")); - - //try an invalid logger name - assertFalse("Use of an invalid logger name was successfull", lm.setConfigFileLoggerLevel("made.up.logger.name", "info")); - - //retrieve the new values from the file and check them - levels = (TabularDataSupport) lm.viewConfigFileLoggerLevels(); - records = levels.values(); - list = new HashMap<String,String>(); - for (Object o : records) - { - CompositeData data = (CompositeData) o; - list.put(data.get(LOGGER_NAME).toString(), data.get(LOGGER_LEVEL).toString()); - } - - //check the 3 different types of logger definition are successfully retrieved after update - assertTrue("Wrong number of items in returned list", list.size() == 3); - assertTrue(TEST_CATEGORY_PRIORITY + " logger was not in the returned list", list.containsKey(TEST_CATEGORY_PRIORITY)); - assertTrue(TEST_CATEGORY_LEVEL + " logger was not in the returned list", list.containsKey(TEST_CATEGORY_LEVEL)); - assertTrue(TEST_LOGGER_LEVEL + " logger was not in the returned list", list.containsKey(TEST_LOGGER_LEVEL)); - - //check that their level is as expected after the changes - assertTrue(TEST_CATEGORY_PRIORITY + " logger's level was incorrect", list.get(TEST_CATEGORY_PRIORITY).equalsIgnoreCase("warn")); - assertTrue(TEST_CATEGORY_LEVEL + " logger's level was incorrect", list.get(TEST_CATEGORY_LEVEL).equalsIgnoreCase("error")); - assertTrue(TEST_LOGGER_LEVEL + " logger's level was incorrect", list.get(TEST_LOGGER_LEVEL).equalsIgnoreCase("trace")); - } - - public void testGetAndSetConfigFileRootLoggerLevel() throws Exception - { - LoggingManagementMBean lm =null; - try - { - lm = new LoggingManagementMBean(_testConfigFile.getAbsolutePath(), 0); - } - catch (JMException e) - { - fail("Could not create test LoggingManagementMBean"); - } - - //retrieve the current value - String level = lm.getConfigFileRootLoggerLevel(); - - //check the value was successfully retrieved before update - assertTrue("Retrieved RootLogger level was incorrect", level.equalsIgnoreCase("info")); - - //try an invalid level - assertFalse("Use of an invalid RootLogger level was successfull", lm.setConfigFileRootLoggerLevel("made.up.level")); - - //change the level to warn - assertTrue("Failed to set new RootLogger level", lm.setConfigFileRootLoggerLevel("warn")); - - //retrieve the current value - level = lm.getConfigFileRootLoggerLevel(); - - //check the value was successfully retrieved after update - assertTrue("Retrieved RootLogger level was incorrect", level.equalsIgnoreCase("warn")); - } - - public void testGetLog4jLogWatchInterval() - { - LoggingManagementMBean lm =null; - try - { - lm = new LoggingManagementMBean(_testConfigFile.getAbsolutePath(), 5000); - } - catch (JMException e) - { - fail("Could not create test LoggingManagementMBean"); - } - - assertTrue("Wrong value returned for logWatch period", lm.getLog4jLogWatchInterval() == 5000); - } - -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/BrokerMessagesTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/messages/BrokerMessagesTest.java index e87d292471..6571d20711 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/BrokerMessagesTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/logging/messages/BrokerMessagesTest.java @@ -20,10 +20,9 @@ */ package org.apache.qpid.server.logging.messages; +import java.text.NumberFormat; import java.util.List; -import org.apache.derby.iapi.services.io.FileUtil; - /** * Test BRK log Messages */ @@ -139,7 +138,7 @@ public class BrokerMessagesTest extends AbstractTestMessages _logMessage = BrokerMessages.MAX_MEMORY(oneGiga); List<Object> log = performLog(); - String[] expected = {"Maximum Memory :", "1,073,741,824", "bytes"}; + String[] expected = {"Maximum Memory :", NumberFormat.getNumberInstance().format(oneGiga), "bytes"}; validateLogMessage(log, "BRK-1011", expected); } diff --git a/java/broker/src/test/java/org/apache/qpid/server/management/AMQUserManagementMBeanTest.java b/java/broker/src/test/java/org/apache/qpid/server/management/AMQUserManagementMBeanTest.java deleted file mode 100644 index f7d85c11a8..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/management/AMQUserManagementMBeanTest.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.server.management; - -import org.apache.qpid.management.common.mbeans.UserManagement; -import org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase; -import org.apache.qpid.server.security.auth.management.AMQUserManagementMBean; -import org.apache.qpid.server.util.InternalBrokerBaseCase; - -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.TabularData; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; - -/** - * - * Tests the AMQUserManagementMBean and its interaction with the PrincipalDatabase. - * - */ -public class AMQUserManagementMBeanTest extends InternalBrokerBaseCase -{ - private PlainPasswordFilePrincipalDatabase _database; - private AMQUserManagementMBean _amqumMBean; - - private File _passwordFile; - - private static final String TEST_USERNAME = "testuser"; - private static final String TEST_PASSWORD = "password"; - - @Override - public void setUp() throws Exception - { - super.setUp(); - - _database = new PlainPasswordFilePrincipalDatabase(); - _amqumMBean = new AMQUserManagementMBean(); - loadFreshTestPasswordFile(); - } - - @Override - public void tearDown() throws Exception - { - //clean up test password/access files - File _oldPasswordFile = new File(_passwordFile.getAbsolutePath() + ".old"); - _oldPasswordFile.delete(); - _passwordFile.delete(); - - super.tearDown(); - } - - public void testDeleteUser() - { - assertEquals("Unexpected number of users before test", 1,_amqumMBean.viewUsers().size()); - assertTrue("Delete should return true to flag successful delete", _amqumMBean.deleteUser(TEST_USERNAME)); - assertEquals("Unexpected number of users after test", 0,_amqumMBean.viewUsers().size()); - } - - public void testDeleteUserWhereUserDoesNotExist() - { - assertEquals("Unexpected number of users before test", 1,_amqumMBean.viewUsers().size()); - assertFalse("Delete should return false to flag unsuccessful delete", _amqumMBean.deleteUser("made.up.username")); - assertEquals("Unexpected number of users after test", 1,_amqumMBean.viewUsers().size()); - - } - - public void testCreateUser() - { - assertEquals("Unexpected number of users before test", 1,_amqumMBean.viewUsers().size()); - assertTrue("Create should return true to flag successful create", _amqumMBean.createUser("newuser", "mypass")); - assertEquals("Unexpected number of users before test", 2,_amqumMBean.viewUsers().size()); - } - - public void testCreateUserWhereUserAlreadyExists() - { - assertEquals("Unexpected number of users before test", 1,_amqumMBean.viewUsers().size()); - assertFalse("Create should return false to flag unsuccessful create", _amqumMBean.createUser(TEST_USERNAME, "mypass")); - assertEquals("Unexpected number of users before test", 1,_amqumMBean.viewUsers().size()); - } - - public void testSetPassword() - { - assertTrue("Set password should return true to flag successful change", _amqumMBean.setPassword(TEST_USERNAME, "newpassword")); - } - - public void testSetPasswordWhereUserDoesNotExist() - { - assertFalse("Set password should return false to flag successful change", _amqumMBean.setPassword("made.up.username", "newpassword")); - } - - public void testViewUsers() - { - TabularData userList = _amqumMBean.viewUsers(); - - assertNotNull(userList); - assertEquals("Unexpected number of users in user list", 1, userList.size()); - assertTrue(userList.containsKey(new Object[]{TEST_USERNAME})); - - // Check the deprecated read, write and admin items continue to exist but return false. - CompositeData userRec = userList.get(new Object[]{TEST_USERNAME}); - assertTrue(userRec.containsKey(UserManagement.RIGHTS_READ_ONLY)); - assertEquals(false, userRec.get(UserManagement.RIGHTS_READ_ONLY)); - assertEquals(false, userRec.get(UserManagement.RIGHTS_READ_WRITE)); - assertTrue(userRec.containsKey(UserManagement.RIGHTS_READ_WRITE)); - assertTrue(userRec.containsKey(UserManagement.RIGHTS_ADMIN)); - assertEquals(false, userRec.get(UserManagement.RIGHTS_ADMIN)); - } - - // ============================ Utility methods ========================= - - private void loadFreshTestPasswordFile() - { - try - { - if(_passwordFile == null) - { - _passwordFile = File.createTempFile(this.getClass().getName(),".password"); - } - - BufferedWriter passwordWriter = new BufferedWriter(new FileWriter(_passwordFile, false)); - passwordWriter.write(TEST_USERNAME + ":" + TEST_PASSWORD); - passwordWriter.newLine(); - passwordWriter.flush(); - passwordWriter.close(); - _database.setPasswordFile(_passwordFile.toString()); - _amqumMBean.setPrincipalDatabase(_database); - } - catch (IOException e) - { - fail("Unable to create test password file: " + e.getMessage()); - } - } -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/model/UUIDGeneratorTest.java b/java/broker/src/test/java/org/apache/qpid/server/model/UUIDGeneratorTest.java new file mode 100644 index 0000000000..643132d371 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/model/UUIDGeneratorTest.java @@ -0,0 +1,213 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.model; + +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + +import org.apache.qpid.test.utils.QpidTestCase; + +public class UUIDGeneratorTest extends QpidTestCase +{ + private static final String VIRTUAL_HOST_NAME_1 = "virtualHost1"; + private static final String VIRTUAL_HOST_NAME_2 = "virtualHost2"; + private static final String VHOST_ALIAS_1 = "alias1"; + private static final String VHOST_ALIAS_2 = "alias2"; + private static final String QUEUE_NAME_1 = "queue1"; + private static final String QUEUE_NAME_2 = "queue2"; + private static final String EXCHANGE_NAME_1 = "exchange1"; + private static final String EXCHANGE_NAME_2 = "exchange2"; + private static final String BINDING_KEY_1 = "bindingKey1"; + private static final String BINDING_KEY_2 = "bindingKey2"; + private static final String PORT_1 = "port1"; + private static final String PORT_2 = "port2"; + private static final String CONN_REMOTE_ADDR_1 = "localhost:1234"; + private static final String CONN_REMOTE_ADDR_2 = "localhost:5678"; + private static final String CHANNEL_NUMBER_1 = "1"; + private static final String CHANNEL_NUMBER_2 = "2"; + private static final String CONSUMER_NAME_1 = "consumer1"; + private static final String CONSUMER_NAME_2 = "consumer2"; + private static final String PROVIDER_1 = "provider1"; + private static final String PROVIDER_2 = "provider2"; + private static final String USER_1 = "user1"; + private static final String USER_2 = "user2"; + + public void testDifferentObjectTypeReturnDifferentIdFromSameValues() throws Exception + { + String value = "name"; + Set<UUID> idSet = new HashSet<UUID>(); + + UUID id1 = UUIDGenerator.generateQueueUUID(value, value); + idSet.add(id1); + UUID id2 = UUIDGenerator.generateExchangeUUID(value, value); + idSet.add(id2); + UUID id3 = UUIDGenerator.generateBindingUUID(value, value, value, value); + idSet.add(id3); + UUID id4 = UUIDGenerator.generateConsumerUUID(value, value, value, value, value); + idSet.add(id4); + UUID id5 = UUIDGenerator.generateUserUUID(value, value); + idSet.add(id5); + UUID id6 = UUIDGenerator.generateVhostUUID(value); + idSet.add(id6); + UUID id7 = UUIDGenerator.generateVhostAliasUUID(value, value); + idSet.add(id7); + + assertEquals("The produced UUIDs were not all unique", 7, idSet.size()); + } + + public void testQueueIdGeneration() throws Exception + { + //check repeated generation is deterministic + UUID queue1 = UUIDGenerator.generateQueueUUID(QUEUE_NAME_1, VIRTUAL_HOST_NAME_1); + UUID queue2 = UUIDGenerator.generateQueueUUID(QUEUE_NAME_1, VIRTUAL_HOST_NAME_1); + assertEquals("Queue IDs should be equal", queue1, queue2); + + //check different name gives different ID + queue1 = UUIDGenerator.generateQueueUUID(QUEUE_NAME_1, VIRTUAL_HOST_NAME_1); + queue2 = UUIDGenerator.generateQueueUUID(QUEUE_NAME_2, VIRTUAL_HOST_NAME_1); + assertFalse("Queue IDs should not be equal", queue1.equals(queue2)); + + //check different vhost name gives different ID + queue1 = UUIDGenerator.generateQueueUUID(QUEUE_NAME_1, VIRTUAL_HOST_NAME_1); + queue2 = UUIDGenerator.generateQueueUUID(QUEUE_NAME_1, VIRTUAL_HOST_NAME_2); + assertFalse("Queue IDs should not be equal", queue1.equals(queue2)); + } + + public void testExchangeIdGeneration() throws Exception + { + //check repeated generation is deterministic + UUID exchange1 = UUIDGenerator.generateExchangeUUID(EXCHANGE_NAME_1, VIRTUAL_HOST_NAME_1); + UUID exchange2 = UUIDGenerator.generateExchangeUUID(EXCHANGE_NAME_1, VIRTUAL_HOST_NAME_1); + assertEquals("Exchange IDs should be equal", exchange1, exchange2); + + //check different name gives different ID + exchange1 = UUIDGenerator.generateExchangeUUID(EXCHANGE_NAME_1, VIRTUAL_HOST_NAME_1); + exchange2 = UUIDGenerator.generateExchangeUUID(EXCHANGE_NAME_2, VIRTUAL_HOST_NAME_1); + assertFalse("Exchange IDs should not be equal", exchange1.equals(exchange2)); + + //check different vhost name gives different ID + exchange1 = UUIDGenerator.generateExchangeUUID(EXCHANGE_NAME_1, VIRTUAL_HOST_NAME_1); + exchange2 = UUIDGenerator.generateExchangeUUID(EXCHANGE_NAME_1, VIRTUAL_HOST_NAME_2); + assertFalse("Exchange IDs should not be equal", exchange1.equals(exchange2)); + } + + public void testBindingIdGeneration() throws Exception + { + //check repeated generation is deterministic + UUID binding1 = UUIDGenerator.generateBindingUUID(EXCHANGE_NAME_1, QUEUE_NAME_1, BINDING_KEY_1, VIRTUAL_HOST_NAME_1); + UUID binding2 = UUIDGenerator.generateBindingUUID(EXCHANGE_NAME_1, QUEUE_NAME_1, BINDING_KEY_1, VIRTUAL_HOST_NAME_1); + assertEquals("Binding IDs should be equal", binding1, binding2); + + //check different name gives different ID + binding1 = UUIDGenerator.generateBindingUUID(EXCHANGE_NAME_1, QUEUE_NAME_1, BINDING_KEY_1, VIRTUAL_HOST_NAME_1); + binding2 = UUIDGenerator.generateBindingUUID(EXCHANGE_NAME_1, QUEUE_NAME_1, BINDING_KEY_2, VIRTUAL_HOST_NAME_1); + assertFalse("Binding IDs should not be equal", binding1.equals(binding2)); + + //check different vhost name gives different ID + binding1 = UUIDGenerator.generateBindingUUID(EXCHANGE_NAME_1, QUEUE_NAME_1, BINDING_KEY_1, VIRTUAL_HOST_NAME_1); + binding2 = UUIDGenerator.generateBindingUUID(EXCHANGE_NAME_1, QUEUE_NAME_1, BINDING_KEY_1, VIRTUAL_HOST_NAME_2); + assertFalse("Binding IDs should not be equal", binding1.equals(binding2)); + } + + public void testVhostIdGeneration() throws Exception + { + //check repeated generation is deterministic + UUID vhost1 = UUIDGenerator.generateVhostUUID(VIRTUAL_HOST_NAME_1); + UUID vhost2 = UUIDGenerator.generateVhostUUID(VIRTUAL_HOST_NAME_1); + assertTrue("Virtualhost IDs should be equal", vhost1.equals(vhost2)); + + //check different vhost name gives different ID + vhost1 = UUIDGenerator.generateVhostUUID(VIRTUAL_HOST_NAME_1); + vhost2 = UUIDGenerator.generateVhostUUID(VIRTUAL_HOST_NAME_2); + assertFalse("Virtualhost IDs should not be equal", vhost1.equals(vhost2)); + } + + public void testVhostAliasIdGeneration() throws Exception + { + //check repeated generation is deterministic + UUID alias1 = UUIDGenerator.generateVhostAliasUUID(VHOST_ALIAS_1, PORT_1); + UUID alias2 = UUIDGenerator.generateVhostAliasUUID(VHOST_ALIAS_1, PORT_1); + assertTrue("Virtualhost Alias IDs should be equal", alias1.equals(alias2)); + + //check different port name gives different ID + alias1 = UUIDGenerator.generateVhostAliasUUID(VHOST_ALIAS_1, PORT_1); + alias2 = UUIDGenerator.generateVhostAliasUUID(VHOST_ALIAS_2, PORT_1); + assertFalse("Virtualhost Alias IDs should not be equal", alias1.equals(alias2)); + + //check different alias name gives different ID + alias1 = UUIDGenerator.generateVhostAliasUUID(VHOST_ALIAS_1, PORT_1); + alias2 = UUIDGenerator.generateVhostAliasUUID(VHOST_ALIAS_1, PORT_2); + assertFalse("Virtualhost Alias IDs should not be equal", alias1.equals(alias2)); + } + + public void testConsumerIdGeneration() throws Exception + { + //check repeated generation is deterministic + UUID consumer1 = UUIDGenerator.generateConsumerUUID(VIRTUAL_HOST_NAME_1, QUEUE_NAME_1, CONN_REMOTE_ADDR_1, CHANNEL_NUMBER_1, CONSUMER_NAME_1); + UUID consumer2 = UUIDGenerator.generateConsumerUUID(VIRTUAL_HOST_NAME_1, QUEUE_NAME_1, CONN_REMOTE_ADDR_1, CHANNEL_NUMBER_1, CONSUMER_NAME_1); + assertTrue("Consumer IDs should be equal", consumer1.equals(consumer2)); + + //check different name gives different ID + consumer1 = UUIDGenerator.generateConsumerUUID(VIRTUAL_HOST_NAME_1, QUEUE_NAME_1, CONN_REMOTE_ADDR_1, CHANNEL_NUMBER_1, CONSUMER_NAME_1); + consumer2 = UUIDGenerator.generateConsumerUUID(VIRTUAL_HOST_NAME_1, QUEUE_NAME_1, CONN_REMOTE_ADDR_1, CHANNEL_NUMBER_1, CONSUMER_NAME_2); + assertFalse("Consumer IDs should not be equal", consumer1.equals(consumer2)); + + //check different vhost name gives different ID + consumer1 = UUIDGenerator.generateConsumerUUID(VIRTUAL_HOST_NAME_1, QUEUE_NAME_1, CONN_REMOTE_ADDR_1, CHANNEL_NUMBER_1, CONSUMER_NAME_1); + consumer2 = UUIDGenerator.generateConsumerUUID(VIRTUAL_HOST_NAME_2, QUEUE_NAME_1, CONN_REMOTE_ADDR_1, CHANNEL_NUMBER_1, CONSUMER_NAME_1); + assertFalse("Consumer IDs should not be equal", consumer1.equals(consumer2)); + + //check different consumer name gives different ID + consumer1 = UUIDGenerator.generateConsumerUUID(VIRTUAL_HOST_NAME_1, QUEUE_NAME_1, CONN_REMOTE_ADDR_1, CHANNEL_NUMBER_1, CONSUMER_NAME_1); + consumer2 = UUIDGenerator.generateConsumerUUID(VIRTUAL_HOST_NAME_1, QUEUE_NAME_1, CONN_REMOTE_ADDR_1, CHANNEL_NUMBER_2, CONSUMER_NAME_1); + assertFalse("Consumer IDs should not be equal", consumer1.equals(consumer2)); + + //check different address name gives different ID + consumer1 = UUIDGenerator.generateConsumerUUID(VIRTUAL_HOST_NAME_1, QUEUE_NAME_1, CONN_REMOTE_ADDR_1, CHANNEL_NUMBER_1, CONSUMER_NAME_1); + consumer2 = UUIDGenerator.generateConsumerUUID(VIRTUAL_HOST_NAME_1, QUEUE_NAME_1, CONN_REMOTE_ADDR_2, CHANNEL_NUMBER_1, CONSUMER_NAME_1); + assertFalse("Consumer IDs should not be equal", consumer1.equals(consumer2)); + + //check different queue name gives different ID + consumer1 = UUIDGenerator.generateConsumerUUID(VIRTUAL_HOST_NAME_1, QUEUE_NAME_1, CONN_REMOTE_ADDR_1, CHANNEL_NUMBER_1, CONSUMER_NAME_1); + consumer2 = UUIDGenerator.generateConsumerUUID(VIRTUAL_HOST_NAME_1, QUEUE_NAME_2, CONN_REMOTE_ADDR_1, CHANNEL_NUMBER_1, CONSUMER_NAME_1); + assertFalse("Consumer IDs should not be equal", consumer1.equals(consumer2)); + } + + public void testUserIdGeneration() throws Exception + { + //check repeated generation is deterministic + UUID user1 = UUIDGenerator.generateUserUUID(PROVIDER_1, USER_1); + UUID user2 = UUIDGenerator.generateUserUUID(PROVIDER_1, USER_1); + assertTrue("User IDs should be equal", user1.equals(user2)); + + //check different name gives different ID + user1 = UUIDGenerator.generateUserUUID(PROVIDER_1, USER_1); + user2 = UUIDGenerator.generateUserUUID(PROVIDER_1, USER_2); + assertFalse("User IDs should not be equal", user1.equals(user2)); + + //check different provider gives different ID + user1 = UUIDGenerator.generateUserUUID(PROVIDER_1, USER_1); + user2 = UUIDGenerator.generateUserUUID(PROVIDER_2, USER_1); + assertFalse("User IDs should not be equal", user1.equals(user2)); + } + +} diff --git a/java/broker/src/test/java/org/apache/qpid/server/plugins/OsgiSystemPackageUtilTest.java b/java/broker/src/test/java/org/apache/qpid/server/plugins/OsgiSystemPackageUtilTest.java index 267545c656..20abdd48cd 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/plugins/OsgiSystemPackageUtilTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/plugins/OsgiSystemPackageUtilTest.java @@ -73,11 +73,11 @@ public class OsgiSystemPackageUtilTest extends QpidTestCase _map.put("org.apache.qpid.xyz", "1.0.0"); _map.put("org.abc", "1.2.3"); - _util = new OsgiSystemPackageUtil(new Version("0.17"), _map); + _util = new OsgiSystemPackageUtil(new Version("0.19"), _map); final String systemPackageString = _util.getFormattedSystemPackageString(); - assertEquals("org.abc; version=1.2.3, org.apache.qpid.xyz; version=0.17.0", systemPackageString); + assertEquals("org.abc; version=1.2.3, org.apache.qpid.xyz; version=0.19.0", systemPackageString); } public void testWithQpidPackageWithoutQpidReleaseNumberSet() throws Exception diff --git a/java/broker/src/test/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBeanTest.java b/java/broker/src/test/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBeanTest.java deleted file mode 100644 index fe9bcc57a6..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBeanTest.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol; - -import org.apache.log4j.Logger; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.management.common.mbeans.ManagedConnection; -import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.AMQQueueFactory; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.TestableMemoryMessageStore; -import org.apache.qpid.server.util.InternalBrokerBaseCase; -import org.apache.qpid.server.virtualhost.VirtualHost; - -import javax.management.JMException; -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.TabularData; - - -/** Test class to test MBean operations for AMQMinaProtocolSession. */ -public class AMQProtocolSessionMBeanTest extends InternalBrokerBaseCase -{ - /** Used for debugging. */ - private static final Logger log = Logger.getLogger(AMQProtocolSessionMBeanTest.class); - - private MessageStore _messageStore = new TestableMemoryMessageStore(); - private AMQProtocolEngine _protocolSession; - private AMQChannel _channel; - private AMQProtocolSessionMBean _mbean; - - public void testChannels() throws Exception - { - // check the channel count is correct - int channelCount = _mbean.channels().size(); - assertTrue(channelCount == 1); - AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("testQueue_" + System.currentTimeMillis()), - false, - new AMQShortString("test"), - true, - false, _protocolSession.getVirtualHost(), null); - AMQChannel channel = new AMQChannel(_protocolSession, 2, _messageStore); - channel.setDefaultQueue(queue); - _protocolSession.addChannel(channel); - channelCount = _mbean.channels().size(); - assertTrue(channelCount == 2); - - // general properties test - _protocolSession.setMaximumNumberOfChannels(1000L); - assertTrue(_mbean.getMaximumNumberOfChannels() == 1000L); - - // check APIs - AMQChannel channel3 = new AMQChannel(_protocolSession, 3, _messageStore); - channel3.setLocalTransactional(); - _protocolSession.addChannel(channel3); - _mbean.rollbackTransactions(2); - _mbean.rollbackTransactions(3); - _mbean.commitTransactions(2); - _mbean.commitTransactions(3); - - // This should throw exception, because the channel does't exist - try - { - _mbean.commitTransactions(4); - fail(); - } - catch (JMException ex) - { - log.debug("expected exception is thrown :" + ex.getMessage()); - } - - // check channels() return type conveys flow control blocking status correctly - AMQChannel channel4 = new AMQChannel(_protocolSession, 4, _messageStore); - _protocolSession.addChannel(channel4); - channel4.setDefaultQueue(queue); - - final String blocking = ManagedConnection.FLOW_BLOCKED; - TabularData channels = _mbean.channels(); - CompositeData chan4result = channels.get(new Integer[]{4}); - assertNotNull(chan4result); - assertEquals("Flow should not have been blocked", false, chan4result.get(blocking)); - - channel4.block(queue); - channels = _mbean.channels(); - chan4result = channels.get(new Integer[]{4}); - assertNotNull(chan4result); - assertEquals("Flow should have been blocked", true, chan4result.get(blocking)); - - channel4.unblock(queue); - channels = _mbean.channels(); - chan4result = channels.get(new Integer[]{4}); - assertNotNull(chan4result); - assertEquals("Flow should have been unblocked", false, chan4result.get(blocking)); - - // check if closing of session works - _protocolSession.addChannel(new AMQChannel(_protocolSession, 5, _messageStore)); - _mbean.closeConnection(); - try - { - channelCount = _mbean.channels().size(); - assertTrue(channelCount == 0); - // session is now closed so adding another channel should throw an exception - _protocolSession.addChannel(new AMQChannel(_protocolSession, 6, _messageStore)); - fail(); - } - catch (AMQException ex) - { - log.debug("expected exception is thrown :" + ex.getMessage()); - } - } - - @Override - public void setUp() throws Exception - { - super.setUp(); - - VirtualHost vhost = ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost("test"); - _protocolSession = new InternalTestProtocolSession(vhost); - - _channel = new AMQChannel(_protocolSession, 1, _messageStore); - _protocolSession.addChannel(_channel); - _mbean = (AMQProtocolSessionMBean) _protocolSession.getManagedObject(); - } - -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/AMQPriorityQueueTest.java b/java/broker/src/test/java/org/apache/qpid/server/queue/AMQPriorityQueueTest.java index 01a2178911..c3d58f3bdc 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/queue/AMQPriorityQueueTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/queue/AMQPriorityQueueTest.java @@ -1,4 +1,3 @@ -package org.apache.qpid.server.queue; /* * * Licensed to the Apache Software Foundation (ASF) under one @@ -19,6 +18,7 @@ package org.apache.qpid.server.queue; * under the License. * */ +package org.apache.qpid.server.queue; import junit.framework.AssertionFailedError; diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueAlertTest.java b/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueAlertTest.java deleted file mode 100644 index 25d35aab16..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueAlertTest.java +++ /dev/null @@ -1,348 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.queue; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.abstraction.ContentChunk; -import org.apache.qpid.framing.abstraction.MessagePublishInfo; -import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.message.AMQMessage; -import org.apache.qpid.server.message.MessageMetaData; -import org.apache.qpid.server.protocol.InternalTestProtocolSession; -import org.apache.qpid.server.subscription.Subscription; -import org.apache.qpid.server.subscription.SubscriptionFactoryImpl; -import org.apache.qpid.server.util.InternalBrokerBaseCase; - -import javax.management.Notification; - -import java.nio.ByteBuffer; -import java.util.ArrayList; - -/** This class tests all the alerts an AMQQueue can throw based on threshold values of different parameters */ -public class AMQQueueAlertTest extends InternalBrokerBaseCase -{ - private final static long MAX_MESSAGE_COUNT = 50; - private final static long MAX_MESSAGE_AGE = 250; // 0.25 sec - private final static long MAX_MESSAGE_SIZE = 2000; // 2 KB - private final static long MAX_QUEUE_DEPTH = 10000; // 10 KB - private AMQQueueMBean _queueMBean; - private static final SubscriptionFactoryImpl SUBSCRIPTION_FACTORY = SubscriptionFactoryImpl.INSTANCE; - - /** - * Tests if the alert gets thrown when message count increases the threshold limit - * - * @throws Exception - */ - public void testMessageCountAlert() throws Exception - { - setSession(new InternalTestProtocolSession(getVirtualHost())); - AMQChannel channel = new AMQChannel(getSession(), 2, getMessageStore()); - getSession().addChannel(channel); - - setQueue(AMQQueueFactory.createAMQQueueImpl(new AMQShortString("testQueue1"), false, new AMQShortString("AMQueueAlertTest"), - false, false, - getVirtualHost(), null)); - _queueMBean = (AMQQueueMBean) getQueue().getManagedObject(); - - _queueMBean.setMaximumMessageCount(MAX_MESSAGE_COUNT); - - sendMessages(channel, MAX_MESSAGE_COUNT, 256l); - assertTrue(_queueMBean.getMessageCount() == MAX_MESSAGE_COUNT); - - Notification lastNotification = _queueMBean.getLastNotification(); - assertNotNull(lastNotification); - - String notificationMsg = lastNotification.getMessage(); - assertTrue(notificationMsg.startsWith(NotificationCheck.MESSAGE_COUNT_ALERT.name())); - } - - /** - * Tests if the Message Size alert gets thrown when message of higher than threshold limit is sent - * - * @throws Exception - */ - public void testMessageSizeAlert() throws Exception - { - setSession(new InternalTestProtocolSession(getVirtualHost())); - AMQChannel channel = new AMQChannel(getSession(), 2, getMessageStore()); - getSession().addChannel(channel); - - setQueue(AMQQueueFactory.createAMQQueueImpl(new AMQShortString("testQueue2"), false, new AMQShortString("AMQueueAlertTest"), - false, false, - getVirtualHost(), null)); - _queueMBean = (AMQQueueMBean) getQueue().getManagedObject(); - _queueMBean.setMaximumMessageCount(MAX_MESSAGE_COUNT); - _queueMBean.setMaximumMessageSize(MAX_MESSAGE_SIZE); - - sendMessages(channel, 1, MAX_MESSAGE_SIZE * 2); - assertTrue(_queueMBean.getMessageCount() == 1); - - Notification lastNotification = _queueMBean.getLastNotification(); - assertNotNull(lastNotification); - - String notificationMsg = lastNotification.getMessage(); - assertTrue(notificationMsg.startsWith(NotificationCheck.MESSAGE_SIZE_ALERT.name())); - } - - /** - * Tests if Queue Depth alert is thrown when queue depth reaches the threshold value - * - * Based on FT-402 subbmitted by client - * - * @throws Exception - */ - public void testQueueDepthAlertNoSubscriber() throws Exception - { - setSession(new InternalTestProtocolSession(getVirtualHost())); - AMQChannel channel = new AMQChannel(getSession(), 2, getMessageStore()); - getSession().addChannel(channel); - - setQueue(AMQQueueFactory.createAMQQueueImpl(new AMQShortString("testQueue3"), false, new AMQShortString("AMQueueAlertTest"), - false, false, - getVirtualHost(), null)); - _queueMBean = (AMQQueueMBean) getQueue().getManagedObject(); - _queueMBean.setMaximumMessageCount(MAX_MESSAGE_COUNT); - _queueMBean.setMaximumQueueDepth(MAX_QUEUE_DEPTH); - - while (getQueue().getQueueDepth() < MAX_QUEUE_DEPTH) - { - sendMessages(channel, 1, MAX_MESSAGE_SIZE); - } - - Notification lastNotification = _queueMBean.getLastNotification(); - assertNotNull(lastNotification); - - String notificationMsg = lastNotification.getMessage(); - assertTrue(notificationMsg.startsWith(NotificationCheck.QUEUE_DEPTH_ALERT.name())); - } - - /** - * Tests if MESSAGE AGE alert is thrown, when a message is in the queue for time higher than threshold value of - * message age - * - * Alternative test to FT-401 provided by client - * - * @throws Exception - */ - public void testMessageAgeAlert() throws Exception - { - setSession(new InternalTestProtocolSession(getVirtualHost())); - AMQChannel channel = new AMQChannel(getSession(), 2, getMessageStore()); - getSession().addChannel(channel); - - setQueue(AMQQueueFactory.createAMQQueueImpl(new AMQShortString("testQueue4"), false, new AMQShortString("AMQueueAlertTest"), - false, false, - getVirtualHost(), null)); - _queueMBean = (AMQQueueMBean) getQueue().getManagedObject(); - _queueMBean.setMaximumMessageCount(MAX_MESSAGE_COUNT); - _queueMBean.setMaximumMessageAge(MAX_MESSAGE_AGE); - - sendMessages(channel, 1, MAX_MESSAGE_SIZE); - - // Ensure message sits on queue long enough to age. - Thread.sleep(MAX_MESSAGE_AGE * 2); - - Notification lastNotification = _queueMBean.getLastNotification(); - assertNotNull("Last notification was null", lastNotification); - - String notificationMsg = lastNotification.getMessage(); - assertTrue(notificationMsg.startsWith(NotificationCheck.MESSAGE_AGE_ALERT.name())); - } - - /* - This test sends some messages to the queue with subscribers needing message to be acknowledged. - The messages will not be acknowledged and will be required twice. Why we are checking this is because - the bug reported said that the queueDepth keeps increasing when messages are requeued. - // TODO - queue depth now includes unacknowledged messages so does not go down when messages are delivered - - The QueueDepth should decrease when messages are delivered from the queue (QPID-408) - */ - public void testQueueDepthAlertWithSubscribers() throws Exception - { - AMQChannel channel = new AMQChannel(getSession(), 2, getMessageStore()); - getSession().addChannel(channel); - - // Create queue - setQueue(getNewQueue()); - Subscription subscription = - SUBSCRIPTION_FACTORY.createSubscription(channel.getChannelId(), getSession(), new AMQShortString("consumer_tag"), true, null, false, channel.getCreditManager()); - - getQueue().registerSubscription( - subscription, false); - - _queueMBean = (AMQQueueMBean) getQueue().getManagedObject(); - _queueMBean.setMaximumMessageCount(9999l); // Set a high value, because this is not being tested - _queueMBean.setMaximumQueueDepth(MAX_QUEUE_DEPTH); - - // Send messages(no of message to be little more than what can cause a Queue_Depth alert) - int messageCount = Math.round(MAX_QUEUE_DEPTH / MAX_MESSAGE_SIZE) + 10; - long totalSize = (messageCount * MAX_MESSAGE_SIZE); - sendMessages(channel, messageCount, MAX_MESSAGE_SIZE); - - // Check queueDepth. There should be no messages on the queue and as the subscriber is listening - // so there should be no Queue_Deoth alert raised - assertEquals(new Long(totalSize), new Long(_queueMBean.getQueueDepth())); - Notification lastNotification = _queueMBean.getLastNotification(); -// assertNull(lastNotification); - - // Kill the subscriber and check for the queue depth values. - // Messages are unacknowledged, so those should get requeued. All messages should be on the Queue - getQueue().unregisterSubscription(subscription); - channel.requeue(); - - assertEquals(new Long(totalSize), new Long(_queueMBean.getQueueDepth())); - - lastNotification = _queueMBean.getLastNotification(); - assertNotNull(lastNotification); - String notificationMsg = lastNotification.getMessage(); - assertTrue(notificationMsg.startsWith(NotificationCheck.QUEUE_DEPTH_ALERT.name())); - - // Connect a consumer again and check QueueDepth values. The queue should get emptied. - // Messages will get delivered but still are unacknowledged. - Subscription subscription2 = - SUBSCRIPTION_FACTORY.createSubscription(channel.getChannelId(), getSession(), new AMQShortString("consumer_tag"), true, null, false, channel.getCreditManager()); - - getQueue().registerSubscription( - subscription2, false); - - while (getQueue().getUndeliveredMessageCount()!= 0) - { - Thread.sleep(100); - } -// assertEquals(new Long(0), new Long(_queueMBean.getQueueDepth())); - - // Kill the subscriber again. Now those messages should get requeued again. Check if the queue depth - // value is correct. - getQueue().unregisterSubscription(subscription2); - channel.requeue(); - - assertEquals(new Long(totalSize), new Long(_queueMBean.getQueueDepth())); - getSession().closeSession(); - - // Check the clear queue - _queueMBean.clearQueue(); - assertEquals(new Long(0), new Long(_queueMBean.getQueueDepth())); - } - - protected IncomingMessage message(final boolean immediate, long size) throws AMQException - { - MessagePublishInfo publish = new MessagePublishInfo() - { - - public AMQShortString getExchange() - { - return null; - } - - public void setExchange(AMQShortString exchange) - { - //To change body of implemented methods use File | Settings | File Templates. - } - - public boolean isImmediate() - { - return immediate; - } - - public boolean isMandatory() - { - return false; - } - - public AMQShortString getRoutingKey() - { - return null; - } - }; - - ContentHeaderBody contentHeaderBody = new ContentHeaderBody(); - BasicContentHeaderProperties props = new BasicContentHeaderProperties(); - contentHeaderBody.setProperties(props); - contentHeaderBody.setBodySize(size); // in bytes - IncomingMessage message = new IncomingMessage(publish); - message.setContentHeaderBody(contentHeaderBody); - - return message; - } - - @Override - protected void configure() - { - // Increase Alert Check period - getConfiguration().setHousekeepingCheckPeriod(200); - } - - private void sendMessages(AMQChannel channel, long messageCount, final long size) throws AMQException - { - IncomingMessage[] messages = new IncomingMessage[(int) messageCount]; - MessageMetaData[] metaData = new MessageMetaData[(int) messageCount]; - for (int i = 0; i < messages.length; i++) - { - messages[i] = message(false, size); - ArrayList<AMQQueue> qs = new ArrayList<AMQQueue>(); - qs.add(getQueue()); - metaData[i] = messages[i].headersReceived(System.currentTimeMillis()); - messages[i].setStoredMessage(getMessageStore().addMessage(metaData[i])); - - messages[i].enqueue(qs); - - } - - for (int i = 0; i < messageCount; i++) - { - ContentChunk contentChunk = new ContentChunk() - { - private byte[] _data = new byte[(int)size]; - - public int getSize() - { - return (int) size; - } - - public byte[] getData() - { - return _data; - } - - public void reduceToFit() - { - } - }; - - messages[i].addContentBodyFrame(contentChunk); - messages[i].getStoredMessage().addContent(0, ByteBuffer.wrap(contentChunk.getData())); - - getQueue().enqueue(new AMQMessage(messages[i].getStoredMessage())); - } - } - - private AMQQueue getNewQueue() throws AMQException - { - return AMQQueueFactory.createAMQQueueImpl(new AMQShortString("testQueue" + Math.random()), - false, - new AMQShortString("AMQueueAlertTest"), - false, - false, getVirtualHost(), null); - } -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueFactoryTest.java b/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueFactoryTest.java index e123a968a4..186be4dff7 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueFactoryTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueFactoryTest.java @@ -20,8 +20,6 @@ */ package org.apache.qpid.server.queue; -import java.util.UUID; - import org.apache.commons.configuration.XMLConfiguration; import org.apache.qpid.AMQException; @@ -35,9 +33,9 @@ import org.apache.qpid.server.exchange.ExchangeRegistry; import org.apache.qpid.server.logging.SystemOutMessageLogger; import org.apache.qpid.server.logging.actors.CurrentActor; import org.apache.qpid.server.logging.actors.TestLogActor; +import org.apache.qpid.server.model.UUIDGenerator; import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.store.TestableMemoryMessageStore; -import org.apache.qpid.server.store.TestableMemoryMessageStoreFactory; import org.apache.qpid.server.util.TestApplicationRegistry; import org.apache.qpid.server.virtualhost.VirtualHost; import org.apache.qpid.test.utils.QpidTestCase; @@ -56,7 +54,7 @@ public class AMQQueueFactoryTest extends QpidTestCase XMLConfiguration configXml = new XMLConfiguration(); configXml.addProperty("virtualhosts.virtualhost(-1).name", getName()); - configXml.addProperty("virtualhosts.virtualhost(-1)."+getName()+".store.factoryclass", TestableMemoryMessageStoreFactory.class.getName()); + configXml.addProperty("virtualhosts.virtualhost(-1)."+getName()+".store.class", TestableMemoryMessageStore.class.getName()); ServerConfiguration configuration = new ServerConfiguration(configXml); @@ -100,8 +98,8 @@ public class AMQQueueFactoryTest extends QpidTestCase fieldTable.put(new AMQShortString(AMQQueueFactory.X_QPID_PRIORITIES), 5); - AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("testPriorityQueue"), false, new AMQShortString("owner"), false, - false, _virtualHost, fieldTable); + AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), "testPriorityQueue", false, "owner", false, + false, _virtualHost, FieldTable.convertToMap(fieldTable)); assertEquals("Queue not a priorty queue", AMQPriorityQueue.class, queue.getClass()); verifyQueueRegistered("testPriorityQueue"); @@ -111,13 +109,13 @@ public class AMQQueueFactoryTest extends QpidTestCase public void testSimpleQueueRegistration() throws Exception { - AMQShortString queueName = new AMQShortString("testSimpleQueueRegistration"); + String queueName = getName(); AMQShortString dlQueueName = new AMQShortString(queueName + AMQQueueFactory.DEFAULT_DLQ_NAME_SUFFIX); - AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(queueName, false, new AMQShortString("owner"), false, + AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), queueName, false, "owner", false, false, _virtualHost, null); assertEquals("Queue not a simple queue", SimpleAMQQueue.class, queue.getClass()); - verifyQueueRegistered("testSimpleQueueRegistration"); + verifyQueueRegistered(queueName); //verify that no alternate exchange or DLQ were produced QueueRegistry qReg = _virtualHost.getQueueRegistry(); @@ -138,7 +136,7 @@ public class AMQQueueFactoryTest extends QpidTestCase FieldTable fieldTable = new FieldTable(); fieldTable.setBoolean(AMQQueueFactory.X_QPID_DLQ_ENABLED, true); - AMQShortString queueName = new AMQShortString("testDeadLetterQueueEnabled"); + String queueName = "testDeadLetterQueueEnabled"; AMQShortString dlExchangeName = new AMQShortString(queueName + DefaultExchangeFactory.DEFAULT_DLE_NAME_SUFFIX); AMQShortString dlQueueName = new AMQShortString(queueName + AMQQueueFactory.DEFAULT_DLQ_NAME_SUFFIX); @@ -148,8 +146,8 @@ public class AMQQueueFactoryTest extends QpidTestCase assertNull("The DLQ should not yet exist", qReg.getQueue(dlQueueName)); assertNull("The alternate exchange should not yet exist", exReg.getExchange(dlExchangeName)); - AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(queueName, false, new AMQShortString("owner"), false, false, - _virtualHost, fieldTable); + AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), queueName, false, "owner", false, false, + _virtualHost, FieldTable.convertToMap(fieldTable)); Exchange altExchange = queue.getAlternateExchange(); assertNotNull("Queue should have an alternate exchange as DLQ is enabled", altExchange); @@ -179,7 +177,7 @@ public class AMQQueueFactoryTest extends QpidTestCase ApplicationRegistry.getInstance().getConfiguration().getConfig().addProperty("deadLetterQueues","true"); ApplicationRegistry.getInstance().getConfiguration().getConfig().addProperty("maximumDeliveryCount","5"); - AMQShortString queueName = new AMQShortString("testDeadLetterQueueEnabled"); + String queueName = "testDeadLetterQueueEnabled"; AMQShortString dlExchangeName = new AMQShortString(queueName + DefaultExchangeFactory.DEFAULT_DLE_NAME_SUFFIX); AMQShortString dlQueueName = new AMQShortString(queueName + AMQQueueFactory.DEFAULT_DLQ_NAME_SUFFIX); @@ -189,7 +187,7 @@ public class AMQQueueFactoryTest extends QpidTestCase assertNull("The DLQ should not yet exist", qReg.getQueue(dlQueueName)); assertNull("The alternate exchange should not yet exist", exReg.getExchange(dlExchangeName)); - AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(queueName, false, new AMQShortString("owner"), false, false, + AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), queueName, false, "owner", false, false, _virtualHost, null); assertEquals("Unexpected maximum delivery count", 5, queue.getMaximumDeliveryCount()); @@ -221,7 +219,7 @@ public class AMQQueueFactoryTest extends QpidTestCase FieldTable fieldTable = new FieldTable(); fieldTable.setBoolean(AMQQueueFactory.X_QPID_DLQ_ENABLED, false); - AMQShortString queueName = new AMQShortString("testDeadLetterQueueDisabled"); + String queueName = "testDeadLetterQueueDisabled"; AMQShortString dlExchangeName = new AMQShortString(queueName + DefaultExchangeFactory.DEFAULT_DLE_NAME_SUFFIX); AMQShortString dlQueueName = new AMQShortString(queueName + AMQQueueFactory.DEFAULT_DLQ_NAME_SUFFIX); @@ -231,8 +229,8 @@ public class AMQQueueFactoryTest extends QpidTestCase assertNull("The DLQ should not yet exist", qReg.getQueue(dlQueueName)); assertNull("The alternate exchange should not exist", exReg.getExchange(dlExchangeName)); - AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(queueName, false, new AMQShortString("owner"), false, false, - _virtualHost, fieldTable); + AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), queueName, false, "owner", false, false, + _virtualHost, FieldTable.convertToMap(fieldTable)); assertNull("Queue should not have an alternate exchange as DLQ is disabled", queue.getAlternateExchange()); assertNull("The alternate exchange should still not exist", exReg.getExchange(dlExchangeName)); @@ -254,7 +252,7 @@ public class AMQQueueFactoryTest extends QpidTestCase FieldTable fieldTable = new FieldTable(); fieldTable.setBoolean(AMQQueueFactory.X_QPID_DLQ_ENABLED, true); - AMQShortString queueName = new AMQShortString("testDeadLetterQueueNotCreatedForAutodeleteQueues"); + String queueName = "testDeadLetterQueueNotCreatedForAutodeleteQueues"; AMQShortString dlExchangeName = new AMQShortString(queueName + DefaultExchangeFactory.DEFAULT_DLE_NAME_SUFFIX); AMQShortString dlQueueName = new AMQShortString(queueName + AMQQueueFactory.DEFAULT_DLQ_NAME_SUFFIX); @@ -265,8 +263,8 @@ public class AMQQueueFactoryTest extends QpidTestCase assertNull("The alternate exchange should not exist", exReg.getExchange(dlExchangeName)); //create an autodelete queue - AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(queueName, false, new AMQShortString("owner"), true, false, - _virtualHost, fieldTable); + AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), queueName, false, "owner", true, false, + _virtualHost, FieldTable.convertToMap(fieldTable)); assertTrue("Queue should be autodelete", queue.isAutoDelete()); //ensure that the autodelete property overrides the request to enable DLQ @@ -287,10 +285,8 @@ public class AMQQueueFactoryTest extends QpidTestCase final FieldTable fieldTable = new FieldTable(); fieldTable.setInteger(AMQQueueFactory.X_QPID_MAXIMUM_DELIVERY_COUNT, 5); - final AMQShortString queueName = new AMQShortString("testMaximumDeliveryCount"); - - final AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(queueName, false, new AMQShortString("owner"), false, false, - _virtualHost, fieldTable); + final AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), "testMaximumDeliveryCount", false, "owner", false, false, + _virtualHost, FieldTable.convertToMap(fieldTable)); assertNotNull("The queue was not registered as expected ", queue); assertEquals("Maximum delivery count not as expected", 5, queue.getMaximumDeliveryCount()); @@ -304,10 +300,7 @@ public class AMQQueueFactoryTest extends QpidTestCase */ public void testMaximumDeliveryCountDefault() throws Exception { - - final AMQShortString queueName = new AMQShortString("testMaximumDeliveryCount"); - - final AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(queueName, false, new AMQShortString("owner"), false, false, + final AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), "testMaximumDeliveryCount", false, "owner", false, false, _virtualHost, null); assertNotNull("The queue was not registered as expected ", queue); @@ -323,7 +316,7 @@ public class AMQQueueFactoryTest extends QpidTestCase { try { - AMQQueueFactory.createAMQQueueImpl(null, false, new AMQShortString("owner"), true, false, _virtualHost, null); + AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), null, false, "owner", true, false, _virtualHost, null); fail("queue with null name can not be created!"); } catch (Exception e) @@ -350,8 +343,8 @@ public class AMQQueueFactoryTest extends QpidTestCase FieldTable fieldTable = new FieldTable(); fieldTable.setBoolean(AMQQueueFactory.X_QPID_DLQ_ENABLED, true); - AMQQueueFactory.createAMQQueueImpl(new AMQShortString(queueName), false, new AMQShortString("owner"), - false, false, _virtualHost, fieldTable); + AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), queueName, false, "owner", + false, false, _virtualHost, FieldTable.convertToMap(fieldTable)); fail("queue with DLQ name having more than 255 characters can not be created!"); } catch (Exception e) @@ -386,8 +379,8 @@ public class AMQQueueFactoryTest extends QpidTestCase FieldTable fieldTable = new FieldTable(); fieldTable.setBoolean(AMQQueueFactory.X_QPID_DLQ_ENABLED, true); - AMQQueueFactory.createAMQQueueImpl(new AMQShortString(queueName), false, new AMQShortString("owner"), - false, false, _virtualHost, fieldTable); + AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), queueName, false, "owner", + false, false, _virtualHost, FieldTable.convertToMap(fieldTable)); fail("queue with DLE name having more than 255 characters can not be created!"); } catch (Exception e) diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueMBeanTest.java b/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueMBeanTest.java deleted file mode 100644 index 45933e7064..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueMBeanTest.java +++ /dev/null @@ -1,553 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.queue; - -import org.apache.commons.lang.time.FastDateFormat; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.ContentBody; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.abstraction.ContentChunk; -import org.apache.qpid.framing.abstraction.MessagePublishInfo; -import org.apache.qpid.management.common.mbeans.ManagedQueue; -import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.message.AMQMessage; -import org.apache.qpid.server.message.MessageMetaData; -import org.apache.qpid.server.protocol.InternalTestProtocolSession; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.store.TestableMemoryMessageStore; -import org.apache.qpid.server.subscription.Subscription; -import org.apache.qpid.server.subscription.SubscriptionFactory; -import org.apache.qpid.server.subscription.SubscriptionFactoryImpl; -import org.apache.qpid.server.util.InternalBrokerBaseCase; - -import javax.management.JMException; -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.CompositeDataSupport; -import javax.management.openmbean.TabularData; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -/** - * Test class to test AMQQueueMBean attributes and operations - */ -public class AMQQueueMBeanTest extends InternalBrokerBaseCase -{ - private static long MESSAGE_SIZE = 1000; - private AMQQueueMBean _queueMBean; - private static final SubscriptionFactoryImpl SUBSCRIPTION_FACTORY = SubscriptionFactoryImpl.INSTANCE; - - public void testMessageCountTransient() throws Exception - { - int messageCount = 10; - sendMessages(messageCount, false); - assertTrue(_queueMBean.getMessageCount() == messageCount); - assertTrue(_queueMBean.getReceivedMessageCount() == messageCount); - long queueDepth = (messageCount * MESSAGE_SIZE); - assertTrue(_queueMBean.getQueueDepth() == queueDepth); - - _queueMBean.deleteMessageFromTop(); - assertTrue(_queueMBean.getMessageCount() == (messageCount - 1)); - assertTrue(_queueMBean.getReceivedMessageCount() == messageCount); - - _queueMBean.clearQueue(); - assertEquals(0,(int)_queueMBean.getMessageCount()); - assertTrue(_queueMBean.getReceivedMessageCount() == messageCount); - - //Ensure that the data has been removed from the Store - verifyBrokerState(); - } - - public void testMessageCountPersistent() throws Exception - { - int messageCount = 10; - sendMessages(messageCount, true); - assertEquals("", messageCount, _queueMBean.getMessageCount().intValue()); - assertTrue(_queueMBean.getReceivedMessageCount() == messageCount); - long queueDepth = (messageCount * MESSAGE_SIZE); - assertTrue(_queueMBean.getQueueDepth() == queueDepth); - - _queueMBean.deleteMessageFromTop(); - assertTrue(_queueMBean.getMessageCount() == (messageCount - 1)); - assertTrue(_queueMBean.getReceivedMessageCount() == messageCount); - - _queueMBean.clearQueue(); - assertTrue(_queueMBean.getMessageCount() == 0); - assertTrue(_queueMBean.getReceivedMessageCount() == messageCount); - - //Ensure that the data has been removed from the Store - verifyBrokerState(); - } - - public void testDeleteMessages() throws Exception - { - int messageCount = 10; - sendMessages(messageCount, true); - assertEquals("", messageCount, _queueMBean.getMessageCount().intValue()); - assertTrue(_queueMBean.getReceivedMessageCount() == messageCount); - long queueDepth = (messageCount * MESSAGE_SIZE); - assertTrue(_queueMBean.getQueueDepth() == queueDepth); - - //delete first message - _queueMBean.deleteMessages(1L,1L); - assertTrue(_queueMBean.getMessageCount() == (messageCount - 1)); - assertTrue(_queueMBean.getReceivedMessageCount() == messageCount); - try - { - _queueMBean.viewMessageContent(1L); - fail("Message should no longer be on the queue"); - } - catch(Exception e) - { - - } - - //delete last message, leaving 2nd to 9th - _queueMBean.deleteMessages(10L,10L); - assertTrue(_queueMBean.getMessageCount() == (messageCount - 2)); - assertTrue(_queueMBean.getReceivedMessageCount() == messageCount); - try - { - _queueMBean.viewMessageContent(10L); - fail("Message should no longer be on the queue"); - } - catch(Exception e) - { - - } - - //delete remaining messages, leaving none - _queueMBean.deleteMessages(2L,9L); - assertTrue(_queueMBean.getMessageCount() == (0)); - assertTrue(_queueMBean.getReceivedMessageCount() == messageCount); - - //Ensure that the data has been removed from the Store - verifyBrokerState(); - } - - - // todo: collect to a general testing class -duplicated from Systest/MessageReturntest - private void verifyBrokerState() - { - - TestableMemoryMessageStore store = (TestableMemoryMessageStore) getVirtualHost().getMessageStore(); - - // Unlike MessageReturnTest there is no need for a delay as there this thread does the clean up. - - assertEquals("Store should have no messages:" + store.getMessageCount(), 0, store.getMessageCount()); - } - - public void testConsumerCount() throws AMQException - { - - assertTrue(getQueue().getActiveConsumerCount() == 0); - assertTrue(_queueMBean.getActiveConsumerCount() == 0); - - - InternalTestProtocolSession protocolSession = new InternalTestProtocolSession(getVirtualHost()); - - AMQChannel channel = new AMQChannel(protocolSession, 1, getMessageStore()); - protocolSession.addChannel(channel); - - Subscription subscription = - SUBSCRIPTION_FACTORY.createSubscription(channel.getChannelId(), protocolSession, new AMQShortString("test"), false, null, false, channel.getCreditManager()); - - getQueue().registerSubscription(subscription, false); - assertEquals(1,(int)_queueMBean.getActiveConsumerCount()); - - - SubscriptionFactory subscriptionFactory = SUBSCRIPTION_FACTORY; - Subscription s1 = subscriptionFactory.createSubscription(channel.getChannelId(), - protocolSession, - new AMQShortString("S1"), - false, - null, - true, - channel.getCreditManager()); - - Subscription s2 = subscriptionFactory.createSubscription(channel.getChannelId(), - protocolSession, - new AMQShortString("S2"), - false, - null, - true, - channel.getCreditManager()); - getQueue().registerSubscription(s1,false); - getQueue().registerSubscription(s2,false); - assertTrue(_queueMBean.getActiveConsumerCount() == 3); - assertTrue(_queueMBean.getConsumerCount() == 3); - - s1.close(); - assertEquals(2, (int) _queueMBean.getActiveConsumerCount()); - assertTrue(_queueMBean.getConsumerCount() == 3); - } - - public void testGeneralProperties() throws Exception - { - long maxQueueDepth = 1000; // in bytes - _queueMBean.setMaximumMessageCount(50000l); - _queueMBean.setMaximumMessageSize(2000l); - _queueMBean.setMaximumQueueDepth(maxQueueDepth); - - assertEquals("Max MessageCount not set",50000,_queueMBean.getMaximumMessageCount().longValue()); - assertEquals("Max MessageSize not set",2000, _queueMBean.getMaximumMessageSize().longValue()); - assertEquals("Max QueueDepth not set",maxQueueDepth, _queueMBean.getMaximumQueueDepth().longValue()); - - assertEquals("Queue Name does not match", new AMQShortString(getName()), _queueMBean.getName()); - assertFalse("AutoDelete should not be set.",_queueMBean.isAutoDelete()); - assertFalse("Queue should not be durable.",_queueMBean.isDurable()); - - //set+get exclusivity using the mbean, and also verify it is actually updated in the queue - _queueMBean.setExclusive(true); - assertTrue("Exclusive property should be true.",_queueMBean.isExclusive()); - assertTrue("Exclusive property should be true.", getQueue().isExclusive()); - _queueMBean.setExclusive(false); - assertFalse("Exclusive property should be false.",_queueMBean.isExclusive()); - assertFalse("Exclusive property should be false.", getQueue().isExclusive()); - } - - /** - * Tests view messages with two test messages. The first message is non-persistent, the second persistent - * and has timestamp/expiration. - * - */ - public void testViewMessages() throws Exception - { - sendMessages(1, false); - final Date msg2Timestamp = new Date(); - final Date msg2Expiration = new Date(msg2Timestamp.getTime() + 1000); - sendMessages(1, true, msg2Timestamp.getTime(), msg2Expiration.getTime()); - - final TabularData tab = _queueMBean.viewMessages(1l, 2l); - assertEquals("Unexpected number of rows in table", 2, tab.size()); - final Iterator<CompositeDataSupport> rowItr = (Iterator<CompositeDataSupport>) tab.values().iterator(); - - // Check row1 - final CompositeDataSupport row1 = rowItr.next(); - assertEquals("Message should have AMQ message id", 1l, row1.get(ManagedQueue.MSG_AMQ_ID)); - assertNotNull("Expected message header array", row1.get(ManagedQueue.MSG_HEADER)); - final Map<String, String> row1Headers = headerArrayToMap((String[])row1.get(ManagedQueue.MSG_HEADER)); - assertEquals("Unexpected JMSPriority within header", "Non_Persistent", row1Headers.get("JMSDeliveryMode")); - assertEquals("Unexpected JMSTimestamp within header", "null", row1Headers.get("JMSTimestamp")); - assertEquals("Unexpected JMSExpiration within header", "null", row1Headers.get("JMSExpiration")); - - final CompositeDataSupport row2 = rowItr.next(); - assertEquals("Message should have AMQ message id", 2l, row2.get(ManagedQueue.MSG_AMQ_ID)); - assertNotNull("Expected message header array", row2.get(ManagedQueue.MSG_HEADER)); - final Map<String, String> row2Headers = headerArrayToMap((String[])row2.get(ManagedQueue.MSG_HEADER)); - assertEquals("Unexpected JMSPriority within header", "Persistent", row2Headers.get("JMSDeliveryMode")); - assertEquals("Unexpected JMSTimestamp within header", FastDateFormat.getInstance(AMQQueueMBean.JMSTIMESTAMP_DATETIME_FORMAT).format(msg2Timestamp), - row2Headers.get("JMSTimestamp")); - assertEquals("Unexpected JMSExpiration within header", FastDateFormat.getInstance(AMQQueueMBean.JMSTIMESTAMP_DATETIME_FORMAT).format(msg2Expiration), - row2Headers.get("JMSExpiration")); - } - - public void testViewMessageWithIllegalStartEndRanges() throws Exception - { - try - { - _queueMBean.viewMessages(0L, 3L); - fail(); - } - catch (JMException ex) - { - // PASS - } - - try - { - _queueMBean.viewMessages(2L, 1L); - fail(); - } - catch (JMException ex) - { - // PASS - } - - try - { - _queueMBean.viewMessages(-1L, 1L); - fail(); - } - catch (JMException ex) - { - // PASS - } - - try - { - long end = Integer.MAX_VALUE; - end+=2; - _queueMBean.viewMessages(1L, end); - fail("Expected Exception due to oversized(> 2^31) message range"); - } - catch (JMException ex) - { - // PASS - } - } - - public void testViewMessageContent() throws Exception - { - final List<AMQMessage> sentMessages = sendMessages(1, true); - final Long id = sentMessages.get(0).getMessageId(); - - final CompositeData messageData = _queueMBean.viewMessageContent(id); - assertNotNull(messageData); - } - - public void testViewMessageContentWithUnknownMessageId() throws Exception - { - final List<AMQMessage> sentMessages = sendMessages(1, true); - final Long id = sentMessages.get(0).getMessageId(); - - try - { - _queueMBean.viewMessageContent(id + 1); - fail(); - } - catch (JMException ex) - { - // PASS - } - } - - public void testFlowControlProperties() throws Exception - { - assertTrue(_queueMBean.getCapacity() == 0); - assertTrue(_queueMBean.getFlowResumeCapacity() == 0); - assertFalse(_queueMBean.isFlowOverfull()); - - //capacity currently 0, try setting FlowResumeCapacity above this - try - { - _queueMBean.setFlowResumeCapacity(1L); - fail("Should have failed to allow setting FlowResumeCapacity above Capacity"); - } - catch (IllegalArgumentException ex) - { - //expected exception - assertTrue(_queueMBean.getFlowResumeCapacity() == 0); - } - - //add a message to the queue - sendMessages(1, true); - - //(FlowResume)Capacity currently 0, set both to 2 - _queueMBean.setCapacity(2L); - assertTrue(_queueMBean.getCapacity() == 2L); - _queueMBean.setFlowResumeCapacity(2L); - assertTrue(_queueMBean.getFlowResumeCapacity() == 2L); - - //Try setting Capacity below FlowResumeCapacity - try - { - _queueMBean.setCapacity(1L); - fail("Should have failed to allow setting Capacity below FlowResumeCapacity"); - } - catch (IllegalArgumentException ex) - { - //expected exception - assertTrue(_queueMBean.getCapacity() == 2); - } - - //create a channel and use it to exercise the capacity check mechanism - AMQChannel channel = new AMQChannel(getSession(), 1, getMessageStore()); - getQueue().checkCapacity(channel); - - assertTrue(_queueMBean.isFlowOverfull()); - assertTrue(channel.getBlocking()); - - //set FlowResumeCapacity to MESSAGE_SIZE and check queue is now underfull and channel unblocked - _queueMBean.setCapacity(MESSAGE_SIZE);//must increase capacity too - _queueMBean.setFlowResumeCapacity(MESSAGE_SIZE); - - assertFalse(_queueMBean.isFlowOverfull()); - assertFalse(channel.getBlocking()); - } - - public void testMaximumDeliveryCount() throws IOException - { - assertEquals("Unexpected default maximum delivery count", Integer.valueOf(0), _queueMBean.getMaximumDeliveryCount()); - } - - public void testViewAllMessages() throws Exception - { - final int messageCount = 5; - sendPersistentMessages(messageCount); - - - final TabularData messageTable = _queueMBean.viewMessages(1L, 5L); - assertNotNull("Message table should not be null", messageTable); - assertEquals("Unexpected number of rows", messageCount, messageTable.size()); - - - final Iterator rowIterator = messageTable.values().iterator(); - // Get its message ID - final CompositeDataSupport row1 = (CompositeDataSupport) rowIterator.next(); - final Long msgId = (Long) row1.get("AMQ MessageId"); - final Long queuePosition = (Long) row1.get("Queue Position"); - final Integer deliveryCount = (Integer) row1.get("Delivery Count"); - - assertNotNull("Row should have value for queue position", queuePosition); - assertNotNull("Row should have value for msgid", msgId); - assertNotNull("Row should have value for deliveryCount", deliveryCount); - } - - - @Override - public void setUp() throws Exception - { - super.setUp(); - - _queueMBean = new AMQQueueMBean(getQueue()); - } - - public void tearDown() - { - ApplicationRegistry.remove(); - } - - private void sendPersistentMessages(int messageCount) throws AMQException - { - sendMessages(messageCount, true); - assertEquals("Expected " + messageCount + " messages in the queue", messageCount, _queueMBean - .getMessageCount().intValue()); - } - - private List<AMQMessage> sendMessages(int messageCount, boolean persistent) throws AMQException - { - return sendMessages(messageCount, persistent, 0l, 0l); - } - - private List<AMQMessage> sendMessages(int messageCount, boolean persistent, long timestamp, long expiration) throws AMQException - { - final List<AMQMessage> sentMessages = new ArrayList<AMQMessage>(); - - for (int i = 0; i < messageCount; i++) - { - IncomingMessage currentMessage = createIncomingMessage(false, persistent, timestamp, expiration); - ArrayList<AMQQueue> qs = new ArrayList<AMQQueue>(); - qs.add(getQueue()); - currentMessage.enqueue(qs); - - // route header - MessageMetaData mmd = currentMessage.headersReceived(System.currentTimeMillis()); - - // Add the message to the store so we have something to test later - currentMessage.setStoredMessage(getMessageStore().addMessage(mmd)); - ContentChunk chunk = getSession().getMethodRegistry() - .getProtocolVersionMethodConverter() - .convertToContentChunk( - new ContentBody(new byte[(int) MESSAGE_SIZE])); - currentMessage.addContentBodyFrame(chunk); - currentMessage.getStoredMessage().addContent(0, ByteBuffer.wrap(chunk.getData())); - - AMQMessage m = new AMQMessage(currentMessage.getStoredMessage()); - for(BaseQueue q : currentMessage.getDestinationQueues()) - { - q.enqueue(m); - } - - sentMessages.add(m); - } - - return sentMessages; - } - - private IncomingMessage createIncomingMessage(final boolean immediate, boolean persistent, long timestamp, long expiration) throws AMQException - { - MessagePublishInfo publish = new MessagePublishInfo() - { - - public AMQShortString getExchange() - { - return null; - } - - public void setExchange(AMQShortString exchange) - { - } - - public boolean isImmediate() - { - return immediate; - } - - public boolean isMandatory() - { - return false; - } - - public AMQShortString getRoutingKey() - { - return null; - } - }; - - ContentHeaderBody contentHeaderBody = new ContentHeaderBody(); - contentHeaderBody.setBodySize(MESSAGE_SIZE); // in bytes - final BasicContentHeaderProperties props = new BasicContentHeaderProperties(); - contentHeaderBody.setProperties(props); - props.setDeliveryMode((byte) (persistent ? 2 : 1)); - if (timestamp > 0) - { - props.setTimestamp(timestamp); - } - if (expiration > 0) - { - props.setExpiration(expiration); - } - IncomingMessage msg = new IncomingMessage(publish); - msg.setContentHeaderBody(contentHeaderBody); - return msg; - } - - /** - * - * Utility method to convert array of Strings in the form x = y into a - * map with key/value x => y. - * - */ - private Map<String,String> headerArrayToMap(final String[] headerArray) - { - final Map<String, String> headerMap = new HashMap<String, String>(); - final List<String> headerList = Arrays.asList(headerArray); - for (Iterator<String> iterator = headerList.iterator(); iterator.hasNext();) - { - final String nameValuePair = iterator.next(); - final String[] nameValue = nameValuePair.split(" *= *", 2); - headerMap.put(nameValue[0], nameValue[1]); - } - return headerMap; - } - - -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/AckTest.java b/java/broker/src/test/java/org/apache/qpid/server/queue/AckTest.java index 409b9fd92e..190d5c777b 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/queue/AckTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/queue/AckTest.java @@ -32,6 +32,7 @@ import org.apache.qpid.server.flow.LimitlessCreditManager; import org.apache.qpid.server.flow.Pre0_10CreditManager; import org.apache.qpid.server.message.AMQMessage; import org.apache.qpid.server.message.MessageMetaData; +import org.apache.qpid.server.model.UUIDGenerator; import org.apache.qpid.server.protocol.AMQProtocolSession; import org.apache.qpid.server.protocol.InternalTestProtocolSession; import org.apache.qpid.server.registry.ApplicationRegistry; @@ -76,7 +77,7 @@ public class AckTest extends InternalBrokerBaseCase _protocolSession.addChannel(_channel); - _queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString("myQ"), false, new AMQShortString("guest"), true, false, + _queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), "myQ", false, "guest", true, false, _virtualHost, null); } diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/ConflationQueueListTest.java b/java/broker/src/test/java/org/apache/qpid/server/queue/ConflationQueueListTest.java new file mode 100644 index 0000000000..a94548f1c3 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/queue/ConflationQueueListTest.java @@ -0,0 +1,211 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.queue; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import junit.framework.TestCase; + +import org.apache.qpid.server.message.AMQMessage; +import org.apache.qpid.server.message.AMQMessageHeader; +import org.apache.qpid.server.message.AMQMessageReference; +import org.apache.qpid.server.message.MessageMetaData; +import org.apache.qpid.server.message.ServerMessage; +import org.apache.qpid.server.virtualhost.VirtualHost; + +public class ConflationQueueListTest extends TestCase +{ + private static final String CONFLATION_KEY = "CONFLATION_KEY"; + + private static final String TEST_KEY_VALUE = "testKeyValue"; + private static final String TEST_KEY_VALUE1 = "testKeyValue1"; + private static final String TEST_KEY_VALUE2 = "testKeyValue2"; + + private ConflationQueueList _list; + private AMQQueue _queue = createTestQueue(); + + @Override + protected void setUp() throws Exception + { + super.setUp(); + _list = new ConflationQueueList(_queue, CONFLATION_KEY); + } + + public void testListHasNoEntries() + { + int numberOfEntries = countEntries(_list); + assertEquals(0, numberOfEntries); + } + + public void testAddMessageWithoutConflationKeyValue() + { + ServerMessage<MessageMetaData> message = createTestServerMessage(null); + + _list.add(message); + int numberOfEntries = countEntries(_list); + assertEquals(1, numberOfEntries); + } + + public void testAddAndDiscardMessageWithoutConflationKeyValue() + { + ServerMessage<MessageMetaData> message = createTestServerMessage(null); + + QueueEntry addedEntry = _list.add(message); + addedEntry.discard(); + + int numberOfEntries = countEntries(_list); + assertEquals(0, numberOfEntries); + } + + public void testAddMessageWithConflationKeyValue() + { + ServerMessage<MessageMetaData> message = createTestServerMessage(TEST_KEY_VALUE); + + _list.add(message); + int numberOfEntries = countEntries(_list); + assertEquals(1, numberOfEntries); + } + + public void testAddAndRemoveMessageWithConflationKeyValue() + { + ServerMessage<MessageMetaData> message = createTestServerMessage(TEST_KEY_VALUE); + + QueueEntry addedEntry = _list.add(message); + addedEntry.discard(); + + int numberOfEntries = countEntries(_list); + assertEquals(0, numberOfEntries); + } + + public void testAddTwoMessagesWithDifferentConflationKeyValue() + { + ServerMessage<MessageMetaData> message1 = createTestServerMessage(TEST_KEY_VALUE1); + ServerMessage<MessageMetaData> message2 = createTestServerMessage(TEST_KEY_VALUE2); + + _list.add(message1); + _list.add(message2); + + int numberOfEntries = countEntries(_list); + assertEquals(2, numberOfEntries); + } + + public void testAddTwoMessagesWithSameConflationKeyValue() + { + ServerMessage<MessageMetaData> message1 = createTestServerMessage(TEST_KEY_VALUE); + ServerMessage<MessageMetaData> message2 = createTestServerMessage(TEST_KEY_VALUE); + + _list.add(message1); + _list.add(message2); + + int numberOfEntries = countEntries(_list); + assertEquals(1, numberOfEntries); + } + + public void testSupersededEntryIsDiscardedOnRelease() + { + ServerMessage<MessageMetaData> message1 = createTestServerMessage(TEST_KEY_VALUE); + ServerMessage<MessageMetaData> message2 = createTestServerMessage(TEST_KEY_VALUE); + + QueueEntry entry1 = _list.add(message1); + entry1.acquire(); // simulate an in-progress delivery to consumer + + _list.add(message2); + assertFalse(entry1.isDeleted()); + + assertEquals(2, countEntries(_list)); + + entry1.release(); // simulate consumer rollback/recover + + assertEquals(1, countEntries(_list)); + assertTrue(entry1.isDeleted()); + } + + public void testConflationMapMaintained() + { + assertEquals(0, _list.getLatestValuesMap().size()); + + ServerMessage<MessageMetaData> message = createTestServerMessage(TEST_KEY_VALUE); + + QueueEntry addedEntry = _list.add(message); + + assertEquals(1, countEntries(_list)); + assertEquals(1, _list.getLatestValuesMap().size()); + + addedEntry.discard(); + + assertEquals(0, countEntries(_list)); + assertEquals(0, _list.getLatestValuesMap().size()); + } + + public void testConflationMapMaintainedWithDifferentConflationKeyValue() + { + + assertEquals(0, _list.getLatestValuesMap().size()); + + ServerMessage<MessageMetaData> message1 = createTestServerMessage(TEST_KEY_VALUE1); + ServerMessage<MessageMetaData> message2 = createTestServerMessage(TEST_KEY_VALUE2); + + QueueEntry addedEntry1 = _list.add(message1); + QueueEntry addedEntry2 = _list.add(message2); + + assertEquals(2, countEntries(_list)); + assertEquals(2, _list.getLatestValuesMap().size()); + + addedEntry1.discard(); + addedEntry2.discard(); + + assertEquals(0, countEntries(_list)); + assertEquals(0, _list.getLatestValuesMap().size()); + } + + private int countEntries(ConflationQueueList list) + { + QueueEntryIterator<SimpleQueueEntryImpl> iterator = list.iterator(); + int count = 0; + while(iterator.advance()) + { + count++; + } + return count; + } + + private ServerMessage<MessageMetaData> createTestServerMessage(String conflationKeyValue) + { + AMQMessage mockMessage = mock(AMQMessage.class); + + AMQMessageHeader messageHeader = mock(AMQMessageHeader.class); + when(messageHeader.getHeader(CONFLATION_KEY)).thenReturn(conflationKeyValue); + when(mockMessage.getMessageHeader()).thenReturn(messageHeader); + + AMQMessageReference messageReference = new AMQMessageReference(mockMessage); + when(mockMessage.newReference()).thenReturn(messageReference); + + return mockMessage; + } + + private AMQQueue createTestQueue() + { + AMQQueue queue = mock(AMQQueue.class); + VirtualHost virtualHost = mock(VirtualHost.class); + when(queue.getVirtualHost()).thenReturn(virtualHost); + + return queue; + } +} diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/MockAMQQueue.java b/java/broker/src/test/java/org/apache/qpid/server/queue/MockAMQQueue.java index afaa417415..bcb8d54636 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/queue/MockAMQQueue.java +++ b/java/broker/src/test/java/org/apache/qpid/server/queue/MockAMQQueue.java @@ -29,13 +29,14 @@ import org.apache.qpid.server.configuration.QueueConfigType; import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; import org.apache.qpid.server.exchange.Exchange; import org.apache.qpid.server.logging.LogSubject; -import org.apache.qpid.server.management.ManagedObject; import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.server.protocol.AMQSessionModel; import org.apache.qpid.server.security.AuthorizationHolder; import org.apache.qpid.server.subscription.Subscription; import org.apache.qpid.server.virtualhost.VirtualHost; +import java.util.Collection; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; @@ -51,7 +52,6 @@ public class MockAMQQueue implements AMQQueue private AuthorizationHolder _authorizationHolder; private AMQSessionModel _exclusiveOwner; - private AMQShortString _owner; private List<Binding> _bindings = new CopyOnWriteArrayList<Binding>(); private boolean _autoDelete; @@ -98,7 +98,12 @@ public class MockAMQQueue implements AMQQueue return "[MockAMQQueue]"; } - }; + }; + } + + public long getUnackedMessageBytes() + { + return 0; } public ConfigStore getConfigStore() @@ -121,6 +126,16 @@ public class MockAMQQueue implements AMQQueue return 0; } + public long getTotalDequeueCount() + { + return 0; + } + + public long getTotalEnqueueCount() + { + return 0; + } + public int getBindingCountHigh() { return 0; @@ -171,6 +186,12 @@ public class MockAMQQueue implements AMQQueue return null; } + @Override + public UUID getQMFId() + { + return null; + } + public QueueConfigType getConfigType() { return null; @@ -219,12 +240,27 @@ public class MockAMQQueue implements AMQQueue public void registerSubscription(Subscription subscription, boolean exclusive) throws AMQException { - + } public void unregisterSubscription(Subscription subscription) throws AMQException { - + + } + + public Collection<Subscription> getConsumers() + { + return Collections.emptyList(); + } + + public void addSubscriptionRegistrationListener(final SubscriptionRegistrationListener listener) + { + + } + + public void removeSubscriptionRegistrationListener(final SubscriptionRegistrationListener listener) + { + } public int getConsumerCount() @@ -283,7 +319,7 @@ public class MockAMQQueue implements AMQQueue } public int delete() throws AMQException - { + { _deleted = true; return getMessageCount(); } @@ -356,21 +392,6 @@ public class MockAMQQueue implements AMQQueue return null; } - public void moveMessagesToAnotherQueue(long fromMessageId, long toMessageId, String queueName) - { - - } - - public void copyMessagesToAnotherQueue(long fromMessageId, long toMessageId, String queueName) - { - - } - - public void removeMessagesFromQueue(long fromMessageId, long toMessageId) - { - - } - public long getMaximumMessageSize() { return 0; @@ -378,7 +399,7 @@ public class MockAMQQueue implements AMQQueue public void setMaximumMessageSize(long value) { - + } public long getMaximumMessageCount() @@ -388,7 +409,7 @@ public class MockAMQQueue implements AMQQueue public void setMaximumMessageCount(long value) { - + } public long getMaximumQueueDepth() @@ -398,7 +419,7 @@ public class MockAMQQueue implements AMQQueue public void setMaximumQueueDepth(long value) { - + } public long getMaximumMessageAge() @@ -408,7 +429,7 @@ public class MockAMQQueue implements AMQQueue public void setMaximumMessageAge(long maximumMessageAge) { - + } public long getMinimumAlertRepeatGap() @@ -418,7 +439,7 @@ public class MockAMQQueue implements AMQQueue public void deleteMessageFromTop() { - + } public long clearQueue() @@ -429,7 +450,7 @@ public class MockAMQQueue implements AMQQueue public void checkMessageStatus() throws AMQException { - + } public Set<NotificationCheck> getNotificationChecks() @@ -439,22 +460,22 @@ public class MockAMQQueue implements AMQQueue public void flushSubscription(Subscription sub) throws AMQException { - + } public void deliverAsync(Subscription sub) { - + } public void deliverAsync() { - + } public void stop() { - + } public boolean isExclusive() @@ -469,7 +490,7 @@ public class MockAMQQueue implements AMQQueue public void setAlternateExchange(Exchange exchange) { - + } public Map<String, Object> getArguments() @@ -481,11 +502,6 @@ public class MockAMQQueue implements AMQQueue { } - public ManagedObject getManagedObject() - { - return null; - } - public int compareTo(AMQQueue o) { return 0; @@ -503,7 +519,7 @@ public class MockAMQQueue implements AMQQueue public void setCapacity(long capacity) { - + } public long getFlowResumeCapacity() @@ -513,7 +529,7 @@ public class MockAMQQueue implements AMQQueue public void setFlowResumeCapacity(long flowResumeCapacity) { - + } public void configure(ConfigurationPlugin config) @@ -546,12 +562,6 @@ public class MockAMQQueue implements AMQQueue _exclusiveOwner = exclusiveOwner; } - - public String getResourceName() - { - return _name.toString(); - } - public boolean isOverfull() { return false; @@ -582,7 +592,7 @@ public class MockAMQQueue implements AMQQueue return 0; } - public void decrementUnackedMsgCount() + public void decrementUnackedMsgCount(QueueEntry queueEntry) { } @@ -599,7 +609,6 @@ public class MockAMQQueue implements AMQQueue public void setExclusive(boolean exclusive) { - } public int getMaximumDeliveryCount() @@ -611,11 +620,23 @@ public class MockAMQQueue implements AMQQueue { } - public void setAlternateExchange(String exchangeName) + public void visit(final QueueEntryVisitor visitor) + { + } + + @Override + public void setNotificationListener(NotificationListener listener) { } - public void visit(final Visitor visitor) + @Override + public void setDescription(String description) { } + + @Override + public String getDescription() + { + return null; + } } diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/NotificationCheckTest.java b/java/broker/src/test/java/org/apache/qpid/server/queue/NotificationCheckTest.java new file mode 100644 index 0000000000..df2de7f0e0 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/queue/NotificationCheckTest.java @@ -0,0 +1,106 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.queue; + +import static org.mockito.Matchers.contains; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +import static org.apache.qpid.server.queue.NotificationCheck.MESSAGE_AGE_ALERT; +import static org.apache.qpid.server.queue.NotificationCheck.MESSAGE_COUNT_ALERT; +import static org.apache.qpid.server.queue.NotificationCheck.MESSAGE_SIZE_ALERT; +import static org.apache.qpid.server.queue.NotificationCheck.QUEUE_DEPTH_ALERT; + + +import junit.framework.TestCase; + +import org.apache.qpid.server.message.ServerMessage; +import org.apache.qpid.server.queue.AMQQueue.NotificationListener; + +public class NotificationCheckTest extends TestCase +{ + + private ServerMessage<?> _message = mock(ServerMessage.class); + private AMQQueue _queue = mock(AMQQueue.class); + private NotificationListener _listener = mock(NotificationListener.class); + + public void testMessageCountAlertFires() throws Exception + { + when(_queue.getMaximumMessageCount()).thenReturn(1000l); + when(_queue.getMessageCount()).thenReturn(999, 1000, 1001); + + MESSAGE_COUNT_ALERT.notifyIfNecessary(_message, _queue, _listener); + verifyZeroInteractions(_listener); + + MESSAGE_COUNT_ALERT.notifyIfNecessary(_message, _queue, _listener); + verify(_listener).notifyClients(eq(MESSAGE_COUNT_ALERT), eq(_queue), eq("1000: Maximum count on queue threshold (1000) breached.")); + + MESSAGE_COUNT_ALERT.notifyIfNecessary(_message, _queue, _listener); + verify(_listener).notifyClients(eq(MESSAGE_COUNT_ALERT), eq(_queue), eq("1001: Maximum count on queue threshold (1000) breached.")); + } + + public void testMessageSizeAlertFires() throws Exception + { + when(_queue.getMaximumMessageSize()).thenReturn(1024l); + when(_message.getSize()).thenReturn(1023l, 1024l, 1025l); + + MESSAGE_SIZE_ALERT.notifyIfNecessary(_message, _queue, _listener); + verifyZeroInteractions(_listener); + + MESSAGE_SIZE_ALERT.notifyIfNecessary(_message, _queue, _listener); + verify(_listener).notifyClients(eq(MESSAGE_SIZE_ALERT), eq(_queue), contains("1024b : Maximum message size threshold (1024) breached.")); + + MESSAGE_SIZE_ALERT.notifyIfNecessary(_message, _queue, _listener); + verify(_listener).notifyClients(eq(MESSAGE_SIZE_ALERT), eq(_queue), contains("1025b : Maximum message size threshold (1024) breached.")); + } + + public void testMessageAgeAlertFires() throws Exception + { + long now = System.currentTimeMillis(); + when(_queue.getMaximumMessageAge()).thenReturn(1000l); + when(_queue.getOldestMessageArrivalTime()).thenReturn(now, now - 15000); + + MESSAGE_AGE_ALERT.notifyIfNecessary(_message, _queue, _listener); + verifyZeroInteractions(_listener); + + MESSAGE_AGE_ALERT.notifyIfNecessary(_message, _queue, _listener); + // Uses contains as first part of message is nondeterministic + verify(_listener).notifyClients(eq(MESSAGE_AGE_ALERT), eq(_queue), contains("s : Maximum age on queue threshold (1s) breached.")); + } + + public void testQueueDepthAlertFires() throws Exception + { + when(_queue.getMaximumQueueDepth()).thenReturn(1024l); + when(_queue.getQueueDepth()).thenReturn(1023l, 1024l, 2048l); + + QUEUE_DEPTH_ALERT.notifyIfNecessary(_message, _queue, _listener); + verifyZeroInteractions(_listener); + + QUEUE_DEPTH_ALERT.notifyIfNecessary(_message, _queue, _listener); + verify(_listener).notifyClients(eq(QUEUE_DEPTH_ALERT), eq(_queue), eq("1Kb : Maximum queue depth threshold (1Kb) breached.")); + + QUEUE_DEPTH_ALERT.notifyIfNecessary(_message, _queue, _listener); + verify(_listener).notifyClients(eq(QUEUE_DEPTH_ALERT), eq(_queue), eq("2Kb : Maximum queue depth threshold (1Kb) breached.")); + } +} diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueTest.java b/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueTest.java index 52ad4a7c5b..2cd423d4c9 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueTest.java @@ -21,6 +21,13 @@ package org.apache.qpid.server.queue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Matchers.contains; +import static org.mockito.Matchers.eq; + import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.qpid.AMQException; @@ -43,7 +50,6 @@ import org.apache.qpid.server.queue.SimpleAMQQueue.QueueEntryFilter; import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.store.StoredMessage; import org.apache.qpid.server.store.TestableMemoryMessageStore; -import org.apache.qpid.server.store.TestableMemoryMessageStoreFactory; import org.apache.qpid.server.subscription.MockSubscription; import org.apache.qpid.server.subscription.Subscription; import org.apache.qpid.server.txn.AutoCommitTransaction; @@ -80,7 +86,6 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase public void setExchange(AMQShortString exchange) { - //To change body of implemented methods use File | Settings | File Templates. } public boolean isImmediate() @@ -108,11 +113,11 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase PropertiesConfiguration env = new PropertiesConfiguration(); final VirtualHostConfiguration vhostConfig = new VirtualHostConfiguration(getClass().getName(), env); - vhostConfig.setMessageStoreFactoryClass(TestableMemoryMessageStoreFactory.class.getName()); + vhostConfig.setMessageStoreClass(TestableMemoryMessageStore.class.getName()); _virtualHost = new VirtualHostImpl(ApplicationRegistry.getInstance(), vhostConfig); applicationRegistry.getVirtualHostRegistry().registerVirtualHost(_virtualHost); - _queue = (SimpleAMQQueue) AMQQueueFactory.createAMQQueueImpl(_qname, false, _owner, false, false, _virtualHost, _arguments); + _queue = (SimpleAMQQueue) AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), _qname.asString(), false, _owner.asString(), false, false, _virtualHost, FieldTable.convertToMap(_arguments)); _exchange = (DirectExchange)_virtualHost.getExchangeRegistry().getExchange(ExchangeDefaults.DIRECT_EXCHANGE_NAME); } @@ -128,7 +133,7 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase { _queue.stop(); try { - _queue = (SimpleAMQQueue) AMQQueueFactory.createAMQQueueImpl(null, false, _owner, false, false, _virtualHost, _arguments ); + _queue = (SimpleAMQQueue) AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), null, false, _owner.asString(), false, false, _virtualHost, FieldTable.convertToMap(_arguments)); assertNull("Queue was created", _queue); } catch (IllegalArgumentException e) @@ -138,7 +143,7 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase } try { - _queue = new SimpleAMQQueue(UUIDGenerator.generateUUID(), _qname, false, _owner, false,false, null, Collections.EMPTY_MAP); + _queue = new SimpleAMQQueue(UUIDGenerator.generateRandomUUID(), _qname, false, _owner, false,false, null, Collections.EMPTY_MAP); assertNull("Queue was created", _queue); } catch (IllegalArgumentException e) @@ -147,8 +152,8 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase e.getMessage().contains("Host")); } - _queue = (SimpleAMQQueue) AMQQueueFactory.createAMQQueueImpl(_qname, false, _owner, false, - false, _virtualHost, _arguments); + _queue = (SimpleAMQQueue) AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), _qname.asString(), false, _owner.asString(), false, + false, _virtualHost, FieldTable.convertToMap(_arguments)); assertNotNull("Queue was not created", _queue); } @@ -480,7 +485,7 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase public void testAutoDeleteQueue() throws Exception { _queue.stop(); - _queue = new SimpleAMQQueue(UUIDGenerator.generateUUID(), _qname, false, null, true, false, _virtualHost, Collections.EMPTY_MAP); + _queue = new SimpleAMQQueue(UUIDGenerator.generateRandomUUID(), _qname, false, null, true, false, _virtualHost, Collections.EMPTY_MAP); _queue.setDeleteOnNoConsumers(true); _queue.registerSubscription(_subscription, false); AMQMessage message = createMessage(new Long(25)); @@ -692,7 +697,7 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase public void testProcessQueueWithUniqueSelectors() throws Exception { TestSimpleQueueEntryListFactory factory = new TestSimpleQueueEntryListFactory(); - SimpleAMQQueue testQueue = new SimpleAMQQueue(UUIDGenerator.generateUUID(), "testQueue", false,"testOwner", + SimpleAMQQueue testQueue = new SimpleAMQQueue(UUIDGenerator.generateRandomUUID(), "testQueue", false,"testOwner", false, false, _virtualHost, factory, null) { @Override @@ -840,120 +845,7 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase } } - /** - * Tests that dequeued message is not copied as part of invocation of - * {@link SimpleAMQQueue#copyMessagesToAnotherQueue(long, long, String)} - */ - public void testCopyMessagesWithDequeuedEntry() - { - int messageNumber = 4; - int dequeueMessageIndex = 1; - String anotherQueueName = "testQueue2"; - - // put test messages into a test queue - enqueueGivenNumberOfMessages(_queue, messageNumber); - - // dequeue message - dequeueMessage(_queue, dequeueMessageIndex); - - // create another queue - SimpleAMQQueue queue = createQueue(anotherQueueName); - - // copy messages into another queue - _queue.copyMessagesToAnotherQueue(0, messageNumber, anotherQueueName); - // get messages on another queue - List<QueueEntry> entries = queue.getMessagesOnTheQueue(); - - // assert another queue entries - assertEquals(messageNumber - 1, entries.size()); - int expectedId = 0; - for (int i = 0; i < messageNumber - 1; i++) - { - Long id = ((AMQMessage)entries.get(i).getMessage()).getMessageId(); - if (i == dequeueMessageIndex) - { - assertFalse("Message with id " + dequeueMessageIndex - + " was dequeued and should not been copied into another queue!", - new Long(expectedId).equals(id)); - expectedId++; - } - assertEquals("Expected message with id " + expectedId + " but got message with id " + id, - new Long(expectedId), id); - expectedId++; - } - } - - /** - * Tests that dequeued message is not moved as part of invocation of - * {@link SimpleAMQQueue#moveMessagesToAnotherQueue(long, long, String)} - */ - public void testMovedMessagesWithDequeuedEntry() - { - int messageNumber = 4; - int dequeueMessageIndex = 1; - String anotherQueueName = "testQueue2"; - - // put messages into a test queue - enqueueGivenNumberOfMessages(_queue, messageNumber); - - // dequeue message - dequeueMessage(_queue, dequeueMessageIndex); - - // create another queue - SimpleAMQQueue queue = createQueue(anotherQueueName); - - // move messages into another queue - _queue.moveMessagesToAnotherQueue(0, messageNumber, anotherQueueName); - - // get messages on another queue - List<QueueEntry> entries = queue.getMessagesOnTheQueue(); - - // assert another queue entries - assertEquals(messageNumber - 1, entries.size()); - int expectedId = 0; - for (int i = 0; i < messageNumber - 1; i++) - { - Long id = ((AMQMessage)entries.get(i).getMessage()).getMessageId(); - if (i == dequeueMessageIndex) - { - assertFalse("Message with id " + dequeueMessageIndex - + " was dequeued and should not been copied into another queue!", - new Long(expectedId).equals(id)); - expectedId++; - } - assertEquals("Expected message with id " + expectedId + " but got message with id " + id, - new Long(expectedId), id); - expectedId++; - } - } - - /** - * Tests that messages in given range including dequeued one are deleted - * from the queue on invocation of - * {@link SimpleAMQQueue#removeMessagesFromQueue(long, long)} - */ - public void testRemoveMessagesFromQueueWithDequeuedEntry() - { - int messageNumber = 4; - int dequeueMessageIndex = 1; - - // put messages into a test queue - enqueueGivenNumberOfMessages(_queue, messageNumber); - - // dequeue message - dequeueMessage(_queue, dequeueMessageIndex); - - // remove messages - _queue.removeMessagesFromQueue(0, messageNumber); - - // get queue entries - List<QueueEntry> entries = _queue.getMessagesOnTheQueue(); - - // assert queue entries - assertNotNull("Null is returned from getMessagesOnTheQueue", entries); - assertEquals("Queue should be empty", 0, entries.size()); - } /** * Tests that dequeued message on the top is not accounted and next message @@ -1029,7 +921,7 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase int dequeueMessageIndex = 1; // create queue with overridden method deliverAsync - SimpleAMQQueue testQueue = new SimpleAMQQueue(UUIDGenerator.generateUUID(), new AMQShortString("test"), + SimpleAMQQueue testQueue = new SimpleAMQQueue(UUIDGenerator.generateRandomUUID(), new AMQShortString("test"), false, new AMQShortString("testOwner"), false, false, _virtualHost, null) { @Override @@ -1097,10 +989,10 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase /** * Tests that entry in dequeued state are not enqueued and not delivered to subscription */ - public void testEqueueDequeuedEntry() + public void testEnqueueDequeuedEntry() { // create a queue where each even entry is considered a dequeued - SimpleAMQQueue queue = new SimpleAMQQueue(UUIDGenerator.generateUUID(), new AMQShortString("test"), false, + SimpleAMQQueue queue = new SimpleAMQQueue(UUIDGenerator.generateRandomUUID(), new AMQShortString("test"), false, new AMQShortString("testOwner"), false, false, _virtualHost, new QueueEntryListFactory() { public QueueEntryList createQueueEntryList(AMQQueue queue) @@ -1178,7 +1070,7 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase public void testActiveConsumerCount() throws Exception { - final SimpleAMQQueue queue = new SimpleAMQQueue(UUIDGenerator.generateUUID(), new AMQShortString("testActiveConsumerCount"), false, + final SimpleAMQQueue queue = new SimpleAMQQueue(UUIDGenerator.generateRandomUUID(), new AMQShortString("testActiveConsumerCount"), false, new AMQShortString("testOwner"), false, false, _virtualHost, new SimpleQueueEntryList.Factory(), null); //verify adding an active subscription increases the count @@ -1232,29 +1124,37 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase assertEquals("Unexpected active consumer count", 1, queue.getActiveConsumerCount()); } - /** - * A helper method to create a queue with given name - * - * @param name - * queue name - * @return queue - */ - private SimpleAMQQueue createQueue(String name) + public void testNotificationFiredOnEnqueue() throws Exception { - SimpleAMQQueue queue = null; - try - { - AMQShortString queueName = new AMQShortString(name); - AMQShortString ownerName = new AMQShortString(name + "Owner"); - queue = (SimpleAMQQueue) AMQQueueFactory.createAMQQueueImpl(queueName, false, ownerName, false, false, - _virtualHost, _arguments); - } - catch (AMQException e) - { - fail("Failure to create a queue:" + e.getMessage()); - } - assertNotNull("Queue was not created", queue); - return queue; + AMQQueue.NotificationListener listener = mock(AMQQueue.NotificationListener.class); + + _queue.setNotificationListener(listener); + _queue.setMaximumMessageCount(2); + + _queue.enqueue(createMessage(new Long(24))); + verifyZeroInteractions(listener); + + _queue.enqueue(createMessage(new Long(25))); + + verify(listener, atLeastOnce()).notifyClients(eq(NotificationCheck.MESSAGE_COUNT_ALERT), eq(_queue), contains("Maximum count on queue threshold")); + } + + public void testNotificationFiredAsync() throws Exception + { + AMQQueue.NotificationListener listener = mock(AMQQueue.NotificationListener.class); + + _queue.enqueue(createMessage(new Long(24))); + _queue.enqueue(createMessage(new Long(25))); + _queue.enqueue(createMessage(new Long(26))); + + _queue.setNotificationListener(listener); + _queue.setMaximumMessageCount(2); + + verifyZeroInteractions(listener); + + _queue.checkMessageStatus(); + + verify(listener, atLeastOnce()).notifyClients(eq(NotificationCheck.MESSAGE_COUNT_ALERT), eq(_queue), contains("Maximum count on queue threshold")); } /** diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueThreadPoolTest.java b/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueThreadPoolTest.java index 39ddd1d500..6b82cd361a 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueThreadPoolTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueThreadPoolTest.java @@ -21,8 +21,8 @@ package org.apache.qpid.server.queue; import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.pool.ReferenceCountingExecutorService; +import org.apache.qpid.server.model.UUIDGenerator; import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.util.InternalBrokerBaseCase; import org.apache.qpid.server.virtualhost.VirtualHost; @@ -37,9 +37,8 @@ public class SimpleAMQQueueThreadPoolTest extends InternalBrokerBaseCase try { - SimpleAMQQueue queue = (SimpleAMQQueue) AMQQueueFactory.createAMQQueueImpl(new AMQShortString("test"), false, - new AMQShortString("owner"), - false, false, test, null); + SimpleAMQQueue queue = (SimpleAMQQueue) AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), "test", false, + "owner", false, false, test, null); assertFalse("Creation did not start Pool.", ReferenceCountingExecutorService.getInstance().getPool().isShutdown()); diff --git a/java/broker/src/test/java/org/apache/qpid/server/registry/ApplicationRegistryShutdownTest.java b/java/broker/src/test/java/org/apache/qpid/server/registry/ApplicationRegistryShutdownTest.java index 9ff8f0a531..9af950d385 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/registry/ApplicationRegistryShutdownTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/registry/ApplicationRegistryShutdownTest.java @@ -49,7 +49,7 @@ public class ApplicationRegistryShutdownTest extends InternalBrokerBaseCase /** - * QPID-1399 : Ensure that the Authentiction manager unregisters any SASL providers created during + * QPID-1399 : Ensure that the Authentication manager unregisters any SASL providers created during * ApplicationRegistry initialisation. * */ diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/AnonymousAuthenticationManagerTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/AnonymousAuthenticationManagerTest.java new file mode 100644 index 0000000000..9dcd22c088 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/AnonymousAuthenticationManagerTest.java @@ -0,0 +1,109 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + * + */ +package org.apache.qpid.server.security.auth.manager; + +import javax.security.sasl.SaslException; +import javax.security.sasl.SaslServer; +import org.apache.commons.configuration.CompositeConfiguration; +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.configuration.XMLConfiguration; +import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; +import org.apache.qpid.server.security.auth.AuthenticationResult; +import org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase; +import org.apache.qpid.server.util.InternalBrokerBaseCase; + +public class AnonymousAuthenticationManagerTest extends InternalBrokerBaseCase +{ + + private AuthenticationManager _manager = null; + + public void setUp() throws Exception + { + _manager = AnonymousAuthenticationManager.INSTANCE; + } + + + public void tearDown() throws Exception + { + if(_manager != null) + { + _manager = null; + } + } + + private ConfigurationPlugin getPlainDatabaseConfig() throws ConfigurationException + { + final ConfigurationPlugin config = new PrincipalDatabaseAuthenticationManager.PrincipalDatabaseAuthenticationManagerConfiguration(); + + XMLConfiguration xmlconfig = new XMLConfiguration(); + xmlconfig.addProperty("pd-auth-manager.principal-database.class", PlainPasswordFilePrincipalDatabase.class.getName()); + + // Create a CompositeConfiguration as this is what the broker uses + CompositeConfiguration composite = new CompositeConfiguration(); + composite.addConfiguration(xmlconfig); + config.setConfiguration("security", xmlconfig); + return config; + } + + + public void testConfiguration() throws Exception + { + AuthenticationManager authenticationManager = + AnonymousAuthenticationManager.FACTORY.newInstance(getPlainDatabaseConfig()); + + assertNull("AnonymousAuthenticationManager unexpectedly created when not in config", authenticationManager); + } + + public void testGetMechanisms() throws Exception + { + assertEquals("ANONYMOUS", _manager.getMechanisms()); + } + + public void testCreateSaslServer() throws Exception + { + SaslServer server = _manager.createSaslServer("ANONYMOUS", "example.example.com", null); + + assertEquals("Sasl Server mechanism name is not as expected", "ANONYMOUS", server.getMechanismName()); + + try + { + server = _manager.createSaslServer("PLAIN", "example.example.com", null); + fail("Expected creating SaslServer with incorrect mechanism to throw an exception"); + } + catch (SaslException e) + { + // pass + } + } + + public void testAuthenticate() throws Exception + { + SaslServer saslServer = _manager.createSaslServer("ANONYMOUS", "example.example.com", null); + AuthenticationResult result = _manager.authenticate(saslServer, new byte[0]); + assertNotNull(result); + assertEquals("Expected authentication to be successful", + AuthenticationResult.AuthenticationStatus.SUCCESS, + result.getStatus()); + assertNotNull("Subject should not be null", result.getSubject()); + } + + +} diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/AuthenticationManagerRegistryTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/AuthenticationManagerRegistryTest.java new file mode 100644 index 0000000000..efb8df3a38 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/AuthenticationManagerRegistryTest.java @@ -0,0 +1,304 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.security.auth.manager; + +import static org.mockito.Mockito.*; + +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.qpid.server.configuration.ServerConfiguration; +import org.apache.qpid.server.plugins.Plugin; +import org.apache.qpid.server.plugins.PluginManager; +import org.apache.qpid.server.security.SecurityManager.SecurityConfiguration; +import org.mockito.Mockito; + +import junit.framework.TestCase; + +public class AuthenticationManagerRegistryTest extends TestCase +{ + private static final Map<String, AuthenticationManagerPluginFactory<? extends Plugin>> EMPTY_PLUGINMAP = Collections.emptyMap(); + + private PluginManager _pluginManager = Mockito.mock(PluginManager.class); + private ServerConfiguration _serverConfiguration = Mockito.mock(ServerConfiguration.class); + private SecurityConfiguration _securityConfiguration = Mockito.mock(SecurityConfiguration.class); + + private List<AuthenticationManager> _allCreatedAuthManagers = new ArrayList<AuthenticationManager>(); + + @Override + protected void setUp() throws Exception + { + super.setUp(); + + // Setup server configuration to return mock security config. + when(_serverConfiguration.getConfiguration(SecurityConfiguration.class.getName())).thenReturn(_securityConfiguration); + } + + @Override + protected void tearDown() throws Exception + { + try + { + verifyAllCreatedAuthManagersClosed(); + } + finally + { + super.tearDown(); + } + } + + public void testNoAuthenticationManagerFactoryPluginsFound() throws Exception + { + when(_pluginManager.getAuthenticationManagerPlugins()).thenReturn(EMPTY_PLUGINMAP); + try + { + new AuthenticationManagerRegistry(_serverConfiguration, _pluginManager); + fail("Exception not thrown"); + } + catch (ConfigurationException ce) + { + // PASS + assertEquals("No authentication manager factory plugins found. Check the desired authentication manager plugin has been placed in the plugins directory.", + ce.getMessage()); + } + } + + public void testSameAuthenticationManagerSpecifiedTwice() throws Exception + { + AuthenticationManagerPluginFactory<? extends Plugin> myAuthManagerFactory = newMockFactoryProducingMockAuthManagerImplementing(TestAuthenticationManager1.class); + + Map<String, AuthenticationManagerPluginFactory<? extends Plugin>> pluginMap = createPluginMap(myAuthManagerFactory, myAuthManagerFactory); + + when(_pluginManager.getAuthenticationManagerPlugins()).thenReturn(pluginMap); + + try + { + new AuthenticationManagerRegistry(_serverConfiguration, _pluginManager); + fail("Exception not thrown"); + } + catch (ConfigurationException ce) + { + // PASS + assertEquals("Cannot configure more than one authentication manager of type " + myAuthManagerFactory.getPluginClass().getSimpleName() + ". Remove configuration for one of the authentication managers.", + ce.getMessage()); + } + } + + public void testMultipleAuthenticationManagersSpecifiedButNoDefaultSpecified() throws Exception + { + AuthenticationManagerPluginFactory<? extends Plugin> myAuthManagerFactory1 = newMockFactoryProducingMockAuthManagerImplementing(TestAuthenticationManager1.class); + AuthenticationManagerPluginFactory<? extends Plugin> myAuthManagerFactory2 = newMockFactoryProducingMockAuthManagerImplementing(TestAuthenticationManager2.class); + + Map<String, AuthenticationManagerPluginFactory<? extends Plugin>> pluginMap = createPluginMap(myAuthManagerFactory1, myAuthManagerFactory2); + + when(_pluginManager.getAuthenticationManagerPlugins()).thenReturn(pluginMap); + when(_serverConfiguration.getDefaultAuthenticationManager()).thenReturn(null); + + try + { + new AuthenticationManagerRegistry(_serverConfiguration, _pluginManager); + fail("Exception not thrown"); + } + catch (ConfigurationException ce) + { + // PASS + assertEquals("If more than one authentication manager is configured a default MUST be specified.", + ce.getMessage()); + } + } + + public void testDefaultAuthenticationManagerNotKnown() throws Exception + { + String myDefaultAuthManagerSimpleClassName = "UnknownAuthenticationManager"; + + AuthenticationManagerPluginFactory<? extends Plugin> myAuthManagerFactory1 = newMockFactoryProducingMockAuthManagerImplementing(TestAuthenticationManager1.class); + AuthenticationManagerPluginFactory<? extends Plugin> myAuthManagerFactory2 = newMockFactoryProducingMockAuthManagerImplementing(TestAuthenticationManager2.class); + + Map<String, AuthenticationManagerPluginFactory<? extends Plugin>> pluginMap = createPluginMap(myAuthManagerFactory1, myAuthManagerFactory2); + + when(_pluginManager.getAuthenticationManagerPlugins()).thenReturn(pluginMap); + when(_serverConfiguration.getDefaultAuthenticationManager()).thenReturn(myDefaultAuthManagerSimpleClassName); + + try + { + new AuthenticationManagerRegistry(_serverConfiguration, _pluginManager); + fail("Exception not thrown"); + } + catch (ConfigurationException ce) + { + // PASS + assertTrue("Unexpected message " + ce.getMessage(), + ce.getMessage().startsWith("No authentication managers configured of type " + myDefaultAuthManagerSimpleClassName + " which is specified as the default")); + } + } + + public void testPortMappedToUnknownAuthenticationManager() throws Exception + { + String myDefaultAuthManagerSimpleClassName = "UnknownAuthenticationManager"; + int portNumber = 1234; + + AuthenticationManagerPluginFactory<? extends Plugin> myAuthManagerFactory1 = newMockFactoryProducingMockAuthManagerImplementing(TestAuthenticationManager1.class); + + Map<String, AuthenticationManagerPluginFactory<? extends Plugin>> pluginMap = createPluginMap(myAuthManagerFactory1); + + when(_pluginManager.getAuthenticationManagerPlugins()).thenReturn(pluginMap); + when(_serverConfiguration.getPortAuthenticationMappings()).thenReturn(Collections.singletonMap(portNumber, myDefaultAuthManagerSimpleClassName)); + + try + { + new AuthenticationManagerRegistry(_serverConfiguration, _pluginManager); + fail("Exception not thrown"); + } + catch (ConfigurationException ce) + { + // PASS + assertEquals("Unknown authentication manager class " + myDefaultAuthManagerSimpleClassName + " configured for port " + portNumber, ce.getMessage()); + } + } + + public void testGetAuthenticationManagerForInetSocketAddress() throws Exception + { + AuthenticationManagerPluginFactory<? extends Plugin> myAuthManagerFactory1 = newMockFactoryProducingMockAuthManagerImplementing(TestAuthenticationManager1.class); + Map<String, AuthenticationManagerPluginFactory<? extends Plugin>> pluginMap = createPluginMap(myAuthManagerFactory1); + + when(_pluginManager.getAuthenticationManagerPlugins()).thenReturn(pluginMap); + + AuthenticationManagerRegistry registry = new AuthenticationManagerRegistry(_serverConfiguration, _pluginManager); + + AuthenticationManager authenticationManager = registry.getAuthenticationManager(new InetSocketAddress(1234)); + assertEquals("TestAuthenticationManager1", authenticationManager.getMechanisms()); + + registry.close(); + } + + public void testGetAuthenticationManagerForNonInetSocketAddress() throws Exception + { + AuthenticationManagerPluginFactory<? extends Plugin> myAuthManagerFactory1 = newMockFactoryProducingMockAuthManagerImplementing(TestAuthenticationManager1.class); + Map<String, AuthenticationManagerPluginFactory<? extends Plugin>> pluginMap = createPluginMap(myAuthManagerFactory1); + + when(_pluginManager.getAuthenticationManagerPlugins()).thenReturn(pluginMap); + + AuthenticationManagerRegistry registry = new AuthenticationManagerRegistry(_serverConfiguration, _pluginManager); + + AuthenticationManager authenticationManager = registry.getAuthenticationManager(mock(SocketAddress.class)); + assertEquals("TestAuthenticationManager1", authenticationManager.getMechanisms()); + + registry.close(); + } + + public void testGetAuthenticationManagerWithMultipleAuthenticationManager() throws Exception + { + AuthenticationManagerPluginFactory<? extends Plugin> myAuthManagerFactory1 = newMockFactoryProducingMockAuthManagerImplementing(TestAuthenticationManager1.class); + AuthenticationManagerPluginFactory<? extends Plugin> myAuthManagerFactory2 = newMockFactoryProducingMockAuthManagerImplementing(TestAuthenticationManager2.class); + Map<String, AuthenticationManagerPluginFactory<? extends Plugin>> pluginMap = createPluginMap(myAuthManagerFactory1, myAuthManagerFactory2); + + String defaultAuthManger = myAuthManagerFactory1.getPluginName(); + int unmappedPortNumber = 1234; + int mappedPortNumber = 1235; + String mappedAuthManager = myAuthManagerFactory2.getPluginName(); + + when(_pluginManager.getAuthenticationManagerPlugins()).thenReturn(pluginMap); + when(_serverConfiguration.getDefaultAuthenticationManager()).thenReturn(defaultAuthManger); + when(_serverConfiguration.getPortAuthenticationMappings()).thenReturn(Collections.singletonMap(mappedPortNumber, mappedAuthManager)); + + AuthenticationManagerRegistry registry = new AuthenticationManagerRegistry(_serverConfiguration, _pluginManager); + + AuthenticationManager authenticationManager1 = registry.getAuthenticationManager(new InetSocketAddress(unmappedPortNumber)); + assertEquals("TestAuthenticationManager1", authenticationManager1.getMechanisms()); + + AuthenticationManager authenticationManager2 = registry.getAuthenticationManager(new InetSocketAddress(mappedPortNumber)); + assertEquals("TestAuthenticationManager2", authenticationManager2.getMechanisms()); + + registry.close(); + } + + public void testAuthenticationManagersAreClosed() throws Exception + { + AuthenticationManagerPluginFactory<? extends Plugin> myAuthManagerFactory1 = newMockFactoryProducingMockAuthManagerImplementing(TestAuthenticationManager1.class); + AuthenticationManagerPluginFactory<? extends Plugin> myAuthManagerFactory2 = newMockFactoryProducingMockAuthManagerImplementing(TestAuthenticationManager2.class); + Map<String, AuthenticationManagerPluginFactory<? extends Plugin>> pluginMap = createPluginMap(myAuthManagerFactory1, myAuthManagerFactory2); + + String defaultAuthManger = myAuthManagerFactory1.getPluginName(); + when(_pluginManager.getAuthenticationManagerPlugins()).thenReturn(pluginMap); + when(_serverConfiguration.getDefaultAuthenticationManager()).thenReturn(defaultAuthManger); + + AuthenticationManagerRegistry registry = new AuthenticationManagerRegistry(_serverConfiguration, _pluginManager); + + registry.close(); + } + + private AuthenticationManagerPluginFactory<? extends Plugin> newMockFactoryProducingMockAuthManagerImplementing(Class<? extends AuthenticationManager> authManagerClazz) + throws ConfigurationException + { + AuthenticationManager myAuthManager = mock(authManagerClazz); + when(myAuthManager.getMechanisms()).thenReturn(authManagerClazz.getSimpleName()); // used to verify the getAuthenticationManagerFor returns expected impl. + + AuthenticationManagerPluginFactory myAuthManagerFactory = mock(AuthenticationManagerPluginFactory.class); + when(myAuthManagerFactory.getPluginClass()).thenReturn(myAuthManager.getClass()); + when(myAuthManagerFactory.getPluginName()).thenReturn(myAuthManager.getClass().getSimpleName()); + when(myAuthManagerFactory.newInstance(_securityConfiguration)).thenReturn(myAuthManager); + + _allCreatedAuthManagers.add(myAuthManager); + return myAuthManagerFactory; + } + + private Map<String, AuthenticationManagerPluginFactory<? extends Plugin>> createPluginMap( + AuthenticationManagerPluginFactory<? extends Plugin> myAuthManagerFactory) + { + return createPluginMap(myAuthManagerFactory, null); + } + + private Map<String, AuthenticationManagerPluginFactory<? extends Plugin>> createPluginMap( + AuthenticationManagerPluginFactory<? extends Plugin> authManagerFactory1, + AuthenticationManagerPluginFactory<? extends Plugin> authManagerFactory2) + { + Map<String, AuthenticationManagerPluginFactory<? extends Plugin>> pluginMap = new HashMap<String, AuthenticationManagerPluginFactory<? extends Plugin>>(); + pluginMap.put("config.path.unused1", authManagerFactory1); + if (authManagerFactory2 != null) + { + pluginMap.put("config.path.unused2", authManagerFactory2); + } + return pluginMap; + } + + private void verifyAllCreatedAuthManagersClosed() + { + for (Iterator<AuthenticationManager> iterator = _allCreatedAuthManagers.iterator(); iterator.hasNext();) + { + AuthenticationManager authenticationManager = (AuthenticationManager) iterator.next(); + verify(authenticationManager).close(); + } + } + + private interface TestAuthenticationManager1 extends AuthenticationManager + { + } + + private interface TestAuthenticationManager2 extends AuthenticationManager + { + } +} diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/ExternalAuthenticationManagerTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/ExternalAuthenticationManagerTest.java new file mode 100644 index 0000000000..c1a55ef2ad --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/ExternalAuthenticationManagerTest.java @@ -0,0 +1,120 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.qpid.server.security.auth.manager; + +import javax.security.auth.x500.X500Principal; +import javax.security.sasl.SaslException; +import javax.security.sasl.SaslServer; +import org.apache.commons.configuration.CompositeConfiguration; +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.configuration.XMLConfiguration; +import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; +import org.apache.qpid.server.security.auth.AuthenticationResult; +import org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase; +import org.apache.qpid.server.util.InternalBrokerBaseCase; + +public class ExternalAuthenticationManagerTest extends InternalBrokerBaseCase +{ + + private AuthenticationManager _manager = null; + + public void setUp() throws Exception + { + _manager = ExternalAuthenticationManager.INSTANCE; + } + + + public void tearDown() throws Exception + { + if(_manager != null) + { + _manager = null; + } + } + + private ConfigurationPlugin getPlainDatabaseConfig() throws ConfigurationException + { + final ConfigurationPlugin config = new PrincipalDatabaseAuthenticationManager.PrincipalDatabaseAuthenticationManagerConfiguration(); + + XMLConfiguration xmlconfig = new XMLConfiguration(); + xmlconfig.addProperty("pd-auth-manager.principal-database.class", PlainPasswordFilePrincipalDatabase.class.getName()); + + // Create a CompositeConfiguration as this is what the broker uses + CompositeConfiguration composite = new CompositeConfiguration(); + composite.addConfiguration(xmlconfig); + config.setConfiguration("security", xmlconfig); + return config; + } + + + public void testConfiguration() throws Exception + { + AuthenticationManager authenticationManager = + ExternalAuthenticationManager.FACTORY.newInstance(getPlainDatabaseConfig()); + + assertNull("ExternalAuthenticationManager unexpectedly created when not in config", authenticationManager); + } + + public void testGetMechanisms() throws Exception + { + assertEquals("EXTERNAL", _manager.getMechanisms()); + } + + public void testCreateSaslServer() throws Exception + { + SaslServer server = _manager.createSaslServer("EXTERNAL", "example.example.com", null); + + assertEquals("Sasl Server mechanism name is not as expected", "EXTERNAL", server.getMechanismName()); + + try + { + server = _manager.createSaslServer("PLAIN", "example.example.com", null); + fail("Expected creating SaslServer with incorrect mechanism to throw an exception"); + } + catch (SaslException e) + { + // pass + } + } + + public void testAuthenticate() throws Exception + { + X500Principal principal = new X500Principal("CN=person, DC=example, DC=com"); + SaslServer saslServer = _manager.createSaslServer("EXTERNAL", "example.example.com", principal); + + AuthenticationResult result = _manager.authenticate(saslServer, new byte[0]); + assertNotNull(result); + assertEquals("Expected authentication to be successful", + AuthenticationResult.AuthenticationStatus.SUCCESS, + result.getStatus()); + assertEquals("Expected principal to be unchanged", + principal, + result.getSubject().getPrincipals().iterator().next()); + + saslServer = _manager.createSaslServer("EXTERNAL", "example.example.com", null); + result = _manager.authenticate(saslServer, new byte[0]); + assertNotNull(result); + assertEquals("Expected authentication to be unsuccessful", + AuthenticationResult.AuthenticationStatus.ERROR, + result.getStatus()); + + } + + +} diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManagerTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManagerTest.java index 1a42fe3886..47c189e4fa 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManagerTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManagerTest.java @@ -167,7 +167,7 @@ public class PrincipalDatabaseAuthenticationManagerTest extends InternalBrokerBa */ public void testSaslMechanismCreation() throws Exception { - SaslServer server = _manager.createSaslServer("CRAM-MD5", "localhost"); + SaslServer server = _manager.createSaslServer("CRAM-MD5", "localhost", null); assertNotNull(server); // Merely tests the creation of the mechanism. Mechanisms themselves are tested // by their own tests. diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/auth/rmi/RMIPasswordAuthenticatorTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/rmi/RMIPasswordAuthenticatorTest.java index bef03057ec..c0c55de92a 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/security/auth/rmi/RMIPasswordAuthenticatorTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/security/auth/rmi/RMIPasswordAuthenticatorTest.java @@ -20,23 +20,19 @@ */ package org.apache.qpid.server.security.auth.rmi; +import java.security.Principal; import junit.framework.TestCase; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.configuration.XMLConfiguration; -import org.apache.qpid.server.configuration.ServerConfiguration; import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; -import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.security.auth.AuthenticationResult; import org.apache.qpid.server.security.auth.AuthenticationResult.AuthenticationStatus; import org.apache.qpid.server.security.auth.manager.AuthenticationManager; -import org.apache.qpid.server.util.TestApplicationRegistry; import javax.management.remote.JMXPrincipal; import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; +import java.net.InetSocketAddress; import java.util.Collections; /** @@ -52,7 +48,7 @@ public class RMIPasswordAuthenticatorTest extends TestCase protected void setUp() throws Exception { - _rmipa = new RMIPasswordAuthenticator(); + _rmipa = new RMIPasswordAuthenticator(new InetSocketAddress(5672)); _credentials = new String[] {USERNAME, PASSWORD}; } @@ -76,14 +72,14 @@ public class RMIPasswordAuthenticatorTest extends TestCase newSubject.equals(expectedSubject)); } - + /** * Tests a unsuccessful authentication. */ public void testUsernameOrPasswordInvalid() { _rmipa.setAuthenticationManager(createTestAuthenticationManager(false, null)); - + try { _rmipa.authenticate(_credentials); @@ -122,17 +118,7 @@ public class RMIPasswordAuthenticatorTest extends TestCase */ public void testNullAuthenticationManager() throws Exception { - ServerConfiguration serverConfig = new ServerConfiguration(new XMLConfiguration()); - TestApplicationRegistry reg = new TestApplicationRegistry(serverConfig) - { - @Override - protected AuthenticationManager createAuthenticationManager() throws ConfigurationException - { - return null; - } - }; - ApplicationRegistry.initialise(reg); - + _rmipa.setAuthenticationManager(null); try { _rmipa.authenticate(_credentials); @@ -143,10 +129,6 @@ public class RMIPasswordAuthenticatorTest extends TestCase assertEquals("Unexpected exception message", RMIPasswordAuthenticator.UNABLE_TO_LOOKUP, se.getMessage()); } - finally - { - ApplicationRegistry.remove(); - } } /** @@ -185,7 +167,7 @@ public class RMIPasswordAuthenticatorTest extends TestCase assertEquals("Unexpected exception message", RMIPasswordAuthenticator.SHOULD_HAVE_2_ELEMENTS, se.getMessage()); } - + // Test handling of null credentials try { @@ -199,7 +181,7 @@ public class RMIPasswordAuthenticatorTest extends TestCase assertEquals("Unexpected exception message", RMIPasswordAuthenticator.CREDENTIALS_REQUIRED, se.getMessage()); } - + try { //send a null password @@ -212,7 +194,7 @@ public class RMIPasswordAuthenticatorTest extends TestCase assertEquals("Unexpected exception message", RMIPasswordAuthenticator.SHOULD_BE_NON_NULL, se.getMessage()); } - + try { //send a null username @@ -251,7 +233,7 @@ public class RMIPasswordAuthenticatorTest extends TestCase throw new UnsupportedOperationException(); } - public SaslServer createSaslServer(String mechanism, String localFQDN) throws SaslException + public SaslServer createSaslServer(String mechanism, String localFQDN, Principal externalPrincipal) throws SaslException { throw new UnsupportedOperationException(); } @@ -276,10 +258,6 @@ public class RMIPasswordAuthenticatorTest extends TestCase } } - public CallbackHandler getHandler(String mechanism) - { - return null; - } }; } } diff --git a/java/broker/src/test/java/org/apache/qpid/server/store/DurableConfigurationStoreTest.java b/java/broker/src/test/java/org/apache/qpid/server/store/DurableConfigurationStoreTest.java index a1cbb2cbc8..cd8d91d835 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/store/DurableConfigurationStoreTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/store/DurableConfigurationStoreTest.java @@ -1,3 +1,23 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ package org.apache.qpid.server.store; import static org.mockito.Matchers.any; @@ -27,7 +47,6 @@ import org.apache.qpid.server.exchange.Exchange; import org.apache.qpid.server.logging.SystemOutMessageLogger; import org.apache.qpid.server.logging.actors.CurrentActor; import org.apache.qpid.server.logging.actors.TestLogActor; -import org.apache.qpid.server.logging.subjects.TestBlankSubject; import org.apache.qpid.server.message.EnqueableMessage; import org.apache.qpid.server.model.UUIDGenerator; import org.apache.qpid.server.queue.AMQQueue; @@ -41,7 +60,7 @@ import org.apache.qpid.server.store.ConfigurationRecoveryHandler.ExchangeRecover import org.apache.qpid.server.store.ConfigurationRecoveryHandler.QueueRecoveryHandler; import org.apache.qpid.server.store.MessageStoreRecoveryHandler.StoredMessageRecoveryHandler; import org.apache.qpid.server.store.Transaction.Record; -import org.apache.qpid.server.store.derby.DerbyMessageStoreFactory; +import org.apache.qpid.server.store.derby.DerbyMessageStore; import org.apache.qpid.test.utils.QpidTestCase; import org.apache.qpid.util.FileUtils; @@ -75,11 +94,11 @@ public class DurableConfigurationStoreTest extends QpidTestCase { super.setUp(); - _queueId = UUIDGenerator.generateUUID(); - _exchangeId = UUIDGenerator.generateUUID(); + _queueId = UUIDGenerator.generateRandomUUID(); + _exchangeId = UUIDGenerator.generateRandomUUID(); _storeName = getName(); - _storePath = TMP_FOLDER + "/" + _storeName; + _storePath = TMP_FOLDER + File.separator + _storeName; FileUtils.delete(new File(_storePath), true); setTestSystemProperty("QPID_WORK", TMP_FOLDER); _configuration = mock(Configuration.class); @@ -94,9 +113,9 @@ public class DurableConfigurationStoreTest extends QpidTestCase _dtxRecordRecoveryHandler = mock(TransactionLogRecoveryHandler.DtxRecordRecoveryHandler.class); when(_messageStoreRecoveryHandler.begin()).thenReturn(_storedMessageRecoveryHandler); - when(_recoveryHandler.begin(isA(MessageStore.class))).thenReturn(_queueRecoveryHandler); - when(_queueRecoveryHandler.completeQueueRecovery()).thenReturn(_exchangeRecoveryHandler); - when(_exchangeRecoveryHandler.completeExchangeRecovery()).thenReturn(_bindingRecoveryHandler); + when(_recoveryHandler.begin(isA(MessageStore.class))).thenReturn(_exchangeRecoveryHandler); + when(_exchangeRecoveryHandler.completeExchangeRecovery()).thenReturn(_queueRecoveryHandler); + when(_queueRecoveryHandler.completeQueueRecovery()).thenReturn(_bindingRecoveryHandler); when(_bindingRecoveryHandler.completeBindingRecovery()).thenReturn(_linkRecoveryHandler); when(_logRecoveryHandler.begin(any(MessageStore.class))).thenReturn(_queueEntryRecoveryHandler); when(_queueEntryRecoveryHandler.completeQueueEntryRecovery()).thenReturn(_dtxRecordRecoveryHandler); @@ -142,8 +161,8 @@ public class DurableConfigurationStoreTest extends QpidTestCase public void testBindQueue() throws Exception { AMQQueue queue = createTestQueue(QUEUE_NAME, "queueOwner", false); - Binding binding = new Binding(UUIDGenerator.generateUUID(), ROUTING_KEY, queue, _exchange, - FieldTable.convertToMap(_bindingArgs)); + Binding binding = new Binding(UUIDGenerator.generateRandomUUID(), null, ROUTING_KEY, queue, + _exchange, FieldTable.convertToMap(_bindingArgs)); _store.bindQueue(binding); reopenStore(); @@ -156,8 +175,8 @@ public class DurableConfigurationStoreTest extends QpidTestCase public void testUnbindQueue() throws Exception { AMQQueue queue = createTestQueue(QUEUE_NAME, "queueOwner", false); - Binding binding = new Binding(UUIDGenerator.generateUUID(), ROUTING_KEY, queue, _exchange, - FieldTable.convertToMap(_bindingArgs)); + Binding binding = new Binding(UUIDGenerator.generateRandomUUID(), null, ROUTING_KEY, queue, + _exchange, FieldTable.convertToMap(_bindingArgs)); _store.bindQueue(binding); _store.unbindQueue(binding); @@ -173,7 +192,7 @@ public class DurableConfigurationStoreTest extends QpidTestCase _store.createQueue(queue); reopenStore(); - verify(_queueRecoveryHandler).queue(_queueId, getName(), getName() + "Owner", true, null); + verify(_queueRecoveryHandler).queue(_queueId, getName(), getName() + "Owner", true, null, null); } public void testCreateQueueAMQQueueFieldTable() throws Exception @@ -187,10 +206,29 @@ public class DurableConfigurationStoreTest extends QpidTestCase _store.createQueue(queue, arguments); reopenStore(); - verify(_queueRecoveryHandler).queue(_queueId, getName(), getName() + "Owner", true, arguments); + verify(_queueRecoveryHandler).queue(_queueId, getName(), getName() + "Owner", true, arguments, null); } - public void testUpdateQueue() throws Exception + public void testCreateQueueAMQQueueWithAlternateExchange() throws Exception + { + Exchange alternateExchange = createTestAlternateExchange(); + + AMQQueue queue = createTestQueue(getName(), getName() + "Owner", true, alternateExchange); + _store.createQueue(queue); + + reopenStore(); + verify(_queueRecoveryHandler).queue(_queueId, getName(), getName() + "Owner", true, null, alternateExchange.getId()); + } + + private Exchange createTestAlternateExchange() + { + UUID exchUuid = UUID.randomUUID(); + Exchange alternateExchange = mock(Exchange.class); + when(alternateExchange.getId()).thenReturn(exchUuid); + return alternateExchange; + } + + public void testUpdateQueueExclusivity() throws Exception { // create queue AMQQueue queue = createTestQueue(getName(), getName() + "Owner", true); @@ -205,7 +243,26 @@ public class DurableConfigurationStoreTest extends QpidTestCase _store.updateQueue(queue); reopenStore(); - verify(_queueRecoveryHandler).queue(_queueId, getName(), getName() + "Owner", false, arguments); + verify(_queueRecoveryHandler).queue(_queueId, getName(), getName() + "Owner", false, arguments, null); + } + + public void testUpdateQueueAlternateExchange() throws Exception + { + // create queue + AMQQueue queue = createTestQueue(getName(), getName() + "Owner", true); + Map<String, Object> attributes = new HashMap<String, Object>(); + attributes.put("x-qpid-dlq-enabled", Boolean.TRUE); + attributes.put("x-qpid-maximum-delivery-count", new Integer(10)); + FieldTable arguments = FieldTable.convertToFieldTable(attributes); + _store.createQueue(queue, arguments); + + // update the queue to have exclusive=false + Exchange alternateExchange = createTestAlternateExchange(); + queue = createTestQueue(getName(), getName() + "Owner", false, alternateExchange); + _store.updateQueue(queue); + + reopenStore(); + verify(_queueRecoveryHandler).queue(_queueId, getName(), getName() + "Owner", false, arguments, alternateExchange.getId()); } public void testRemoveQueue() throws Exception @@ -222,17 +279,23 @@ public class DurableConfigurationStoreTest extends QpidTestCase _store.removeQueue(queue); reopenStore(); verify(_queueRecoveryHandler, never()).queue(any(UUID.class), anyString(), anyString(), anyBoolean(), - any(FieldTable.class)); + any(FieldTable.class), any(UUID.class)); } private AMQQueue createTestQueue(String queueName, String queueOwner, boolean exclusive) throws AMQStoreException { + return createTestQueue(queueName, queueOwner, exclusive, null); + } + + private AMQQueue createTestQueue(String queueName, String queueOwner, boolean exclusive, Exchange alternateExchange) throws AMQStoreException + { AMQQueue queue = mock(AMQQueue.class); when(queue.getName()).thenReturn(queueName); when(queue.getNameShortString()).thenReturn(AMQShortString.valueOf(queueName)); when(queue.getOwner()).thenReturn(AMQShortString.valueOf(queueOwner)); when(queue.isExclusive()).thenReturn(exclusive); when(queue.getId()).thenReturn(_queueId); + when(queue.getAlternateExchange()).thenReturn(alternateExchange); return queue; } @@ -262,14 +325,14 @@ public class DurableConfigurationStoreTest extends QpidTestCase protected MessageStore createStore() throws Exception { - String storeFactoryClass = System.getProperty(MS_FACTORY_CLASS_NAME_KEY); - if (storeFactoryClass == null) + String storeClass = System.getProperty(MESSAGE_STORE_CLASS_NAME_KEY); + if (storeClass == null) { - storeFactoryClass = DerbyMessageStoreFactory.class.getName(); + storeClass = DerbyMessageStore.class.getName(); } CurrentActor.set(new TestLogActor(new SystemOutMessageLogger())); - MessageStoreFactory factory = (MessageStoreFactory) Class.forName(storeFactoryClass).newInstance(); - return factory.createMessageStore(); + MessageStore messageStore = (MessageStore) Class.forName(storeClass).newInstance(); + return messageStore; } public void testRecordXid() throws Exception @@ -297,7 +360,7 @@ public class DurableConfigurationStoreTest extends QpidTestCase private Record getTestRecord(long messageNumber) { - UUID queueId1 = UUIDGenerator.generateUUID(); + UUID queueId1 = UUIDGenerator.generateRandomUUID(); TransactionLogResource queue1 = mock(TransactionLogResource.class); when(queue1.getId()).thenReturn(queueId1); EnqueableMessage message1 = mock(EnqueableMessage.class); diff --git a/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreQuotaEventsTestBase.java b/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreQuotaEventsTestBase.java new file mode 100644 index 0000000000..f1976ecee3 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreQuotaEventsTestBase.java @@ -0,0 +1,178 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.store; + +import java.io.File; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import org.apache.commons.configuration.XMLConfiguration; +import org.apache.log4j.Logger; +import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.framing.BasicContentHeaderProperties; +import org.apache.qpid.framing.ContentHeaderBody; +import org.apache.qpid.framing.MethodRegistry; +import org.apache.qpid.framing.ProtocolVersion; +import org.apache.qpid.framing.abstraction.MessagePublishInfo; +import org.apache.qpid.framing.abstraction.MessagePublishInfoImpl; +import org.apache.qpid.server.message.EnqueableMessage; +import org.apache.qpid.server.message.MessageMetaData; +import org.apache.qpid.test.utils.QpidTestCase; +import org.apache.qpid.util.FileUtils; + +public abstract class MessageStoreQuotaEventsTestBase extends QpidTestCase implements EventListener, TransactionLogResource +{ + private static final Logger _logger = Logger.getLogger(MessageStoreQuotaEventsTestBase.class); + + protected static final byte[] MESSAGE_DATA = new byte[32 * 1024]; + + private MessageStore _store; + private File _storeLocation; + + private List<Event> _events; + private UUID _transactionResource; + + protected abstract MessageStore createStore() throws Exception; + + protected abstract void applyStoreSpecificConfiguration(XMLConfiguration config); + + protected abstract int getNumberOfMessagesToFillStore(); + + @Override + public void setUp() throws Exception + { + super.setUp(); + + _storeLocation = new File(new File(TMP_FOLDER), getTestName()); + FileUtils.delete(_storeLocation, true); + + XMLConfiguration config = new XMLConfiguration(); + config.addProperty("environment-path", _storeLocation.getAbsolutePath()); + applyStoreSpecificConfiguration(config); + + _store = createStore(); + _store.configureConfigStore("test", null, config); + + _transactionResource = UUID.randomUUID(); + _events = new ArrayList<Event>(); + _store.addEventListener(this, Event.PERSISTENT_MESSAGE_SIZE_OVERFULL, Event.PERSISTENT_MESSAGE_SIZE_UNDERFULL); + } + + @Override + public void tearDown() throws Exception + { + super.tearDown(); + FileUtils.delete(_storeLocation, true); + } + + public void testOverflow() throws Exception + { + Transaction transaction = _store.newTransaction(); + + List<EnqueableMessage> messages = new ArrayList<EnqueableMessage>(); + for (int i = 0; i < getNumberOfMessagesToFillStore(); i++) + { + EnqueableMessage m = addMessage(i); + messages.add(m); + transaction.enqueueMessage(this, m); + } + transaction.commitTran(); + + assertEvent(1, Event.PERSISTENT_MESSAGE_SIZE_OVERFULL); + + for (EnqueableMessage m : messages) + { + m.getStoredMessage().remove(); + } + + assertEvent(2, Event.PERSISTENT_MESSAGE_SIZE_UNDERFULL); + } + + protected EnqueableMessage addMessage(long id) + { + MessagePublishInfo pubInfoBody = new MessagePublishInfoImpl(new AMQShortString(getName()), false, false, + new AMQShortString(getName())); + BasicContentHeaderProperties props = new BasicContentHeaderProperties(); + props.setDeliveryMode(Integer.valueOf(BasicContentHeaderProperties.PERSISTENT).byteValue()); + props.setContentType(getTestName()); + + MethodRegistry methodRegistry = MethodRegistry.getMethodRegistry(ProtocolVersion.v0_9); + int classForBasic = methodRegistry.createBasicQosOkBody().getClazz(); + ContentHeaderBody contentHeaderBody = new ContentHeaderBody(classForBasic, 1, props, MESSAGE_DATA.length); + + MessageMetaData metaData = new MessageMetaData(pubInfoBody, contentHeaderBody, 1); + StoredMessage<MessageMetaData> handle = _store.addMessage(metaData); + handle.addContent(0, ByteBuffer.wrap(MESSAGE_DATA)); + TestMessage message = new TestMessage(id, handle); + return message; + } + + @Override + public void event(Event event) + { + _logger.debug("Test event listener received event " + event); + _events.add(event); + } + + private void assertEvent(int expectedNumberOfEvents, Event... expectedEvents) + { + assertEquals("Unexpected number of events received ", expectedNumberOfEvents, _events.size()); + for (Event event : expectedEvents) + { + assertTrue("Expected event is not found:" + event, _events.contains(event)); + } + } + + @Override + public UUID getId() + { + return _transactionResource; + } + + private static class TestMessage implements EnqueableMessage + { + private final StoredMessage<?> _handle; + private final long _messageId; + + public TestMessage(long messageId, StoredMessage<?> handle) + { + _messageId = messageId; + _handle = handle; + } + + public long getMessageNumber() + { + return _messageId; + } + + public boolean isPersistent() + { + return true; + } + + public StoredMessage<?> getStoredMessage() + { + return _handle; + } + } +} diff --git a/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreTest.java b/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreTest.java index 3fb0776083..a1536565ad 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreTest.java @@ -59,7 +59,6 @@ import java.io.File; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.UUID; /** * This tests the MessageStores by using the available interfaces. @@ -100,10 +99,10 @@ public class MessageStoreTest extends InternalBrokerBaseCase { super.setUp(); - String storePath = System.getProperty("QPID_WORK") + "/" + getName(); + String storePath = System.getProperty("QPID_WORK") + File.separator + getName(); _config = new PropertiesConfiguration(); - _config.addProperty("store.factoryclass", getTestProfileMessageStoreFactoryClassName()); + _config.addProperty("store.class", getTestProfileMessageStoreClassName()); _config.addProperty("store.environment-path", storePath); cleanup(new File(storePath)); @@ -268,15 +267,9 @@ public class MessageStoreTest extends InternalBrokerBaseCase //Validate normally expected properties of Queues/Topics validateDurableQueueProperties(); - //Update the durable exclusive queue's exclusivity and verify it is persisted and recovered correctly + //Update the durable exclusive queue's exclusivity setQueueExclusivity(false); validateQueueExclusivityProperty(false); - - //Reload the Virtualhost to recover the queues again - reloadVirtualHost(); - - //verify the change was persisted and recovered correctly - validateQueueExclusivityProperty(false); } /** @@ -702,8 +695,8 @@ public class MessageStoreTest extends InternalBrokerBaseCase //Ideally we would be able to use the QueueDeclareHandler here. try { - queue = AMQQueueFactory.createAMQQueueImpl(queueName, durable, queueOwner, false, exclusive, - getVirtualHost(), queueArguments); + queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), queueName.asString(), durable, queueOwner.asString(), false, exclusive, + getVirtualHost(), FieldTable.convertToMap(queueArguments)); validateQueueProperties(queue, usePriority, durable, exclusive, lastValueQueue); @@ -741,7 +734,7 @@ public class MessageStoreTest extends InternalBrokerBaseCase try { - exchange = type.newInstance(UUIDGenerator.generateUUID(), getVirtualHost(), name, durable, 0, false); + exchange = type.newInstance(UUIDGenerator.generateRandomUUID(), getVirtualHost(), name, durable, 0, false); } catch (AMQException e) { diff --git a/java/broker/src/test/java/org/apache/qpid/server/store/OperationalLoggingListenerTest.java b/java/broker/src/test/java/org/apache/qpid/server/store/OperationalLoggingListenerTest.java index 42746f9119..c309dad5eb 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/store/OperationalLoggingListenerTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/store/OperationalLoggingListenerTest.java @@ -1,3 +1,19 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.qpid.server.store; import java.util.ArrayList; @@ -12,22 +28,6 @@ import org.apache.qpid.server.logging.messages.ConfigStoreMessages; import org.apache.qpid.server.logging.messages.MessageStoreMessages; import org.apache.qpid.server.logging.messages.TransactionLogMessages; -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * <p/> - * http://www.apache.org/licenses/LICENSE-2.0 - * <p/> - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ public class OperationalLoggingListenerTest extends TestCase { @@ -73,11 +73,11 @@ public class OperationalLoggingListenerTest extends TestCase } - messageStore.attainState(State.CONFIGURING); + messageStore.attainState(State.INITIALISING); assertEquals("Unexpected number of operational log messages on configuring", 1, messages.size()); assertEquals(messages.remove(0).toString(), ConfigStoreMessages.CREATED().toString()); - messageStore.attainState(State.CONFIGURED); + messageStore.attainState(State.INITIALISED); assertEquals("Unexpected number of operational log messages on CONFIGURED", setStoreLocation ? 3 : 2, messages.size()); assertEquals(messages.remove(0).toString(), MessageStoreMessages.CREATED().toString()); assertEquals(messages.remove(0).toString(), TransactionLogMessages.CREATED().toString()); @@ -86,7 +86,7 @@ public class OperationalLoggingListenerTest extends TestCase assertEquals(messages.remove(0).toString(), MessageStoreMessages.STORE_LOCATION(STORE_LOCATION).toString()); } - messageStore.attainState(State.RECOVERING); + messageStore.attainState(State.ACTIVATING); assertEquals("Unexpected number of operational log messages on RECOVERING", 1, messages.size()); assertEquals(messages.remove(0).toString(), MessageStoreMessages.RECOVERY_START().toString()); @@ -147,6 +147,12 @@ public class OperationalLoggingListenerTest extends TestCase { _eventManager.addEventListener(eventListener, events); } + + @Override + public String getStoreType() + { + return "TEST"; + } } private static class TestActor implements LogActor diff --git a/java/broker/src/test/java/org/apache/qpid/server/store/StateManagerTest.java b/java/broker/src/test/java/org/apache/qpid/server/store/StateManagerTest.java index 97c88ca1d3..18efb976eb 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/store/StateManagerTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/store/StateManagerTest.java @@ -45,8 +45,8 @@ public class StateManagerTest extends TestCase implements EventListener { assertEquals(State.INITIAL, _manager.getState()); - _manager.stateTransition(State.INITIAL, State.CONFIGURING); - assertEquals(State.CONFIGURING, _manager.getState()); + _manager.attainState(State.INITIALISING); + assertEquals(State.INITIALISING, _manager.getState()); } public void testStateTransitionDisallowed() @@ -55,7 +55,7 @@ public class StateManagerTest extends TestCase implements EventListener try { - _manager.stateTransition(State.ACTIVE, State.CLOSING); + _manager.attainState(State.CLOSING); fail("Exception not thrown"); } catch (IllegalStateException e) @@ -98,22 +98,29 @@ public class StateManagerTest extends TestCase implements EventListener public void testValidStateTransitions() { assertEquals(State.INITIAL, _manager.getState()); - performValidTransition(StateManager.CONFIGURE); - performValidTransition(StateManager.CONFIGURE_COMPLETE); - performValidTransition(StateManager.RECOVER); + performValidTransition(StateManager.INITIALISE); + performValidTransition(StateManager.INITALISE_COMPLETE); performValidTransition(StateManager.ACTIVATE); + performValidTransition(StateManager.ACTIVATE_COMPLETE); performValidTransition(StateManager.QUIESCE); performValidTransition(StateManager.QUIESCE_COMPLETE); performValidTransition(StateManager.RESTART); - performValidTransition(StateManager.ACTIVATE); + performValidTransition(StateManager.ACTIVATE_COMPLETE); performValidTransition(StateManager.CLOSE_ACTIVE); performValidTransition(StateManager.CLOSE_COMPLETE); + + _manager = new StateManager(this); + assertEquals(State.INITIAL, _manager.getState()); + performValidTransition(StateManager.INITIALISE); + performValidTransition(StateManager.INITALISE_COMPLETE); + performValidTransition(StateManager.CLOSE_INITIALISED); + performValidTransition(StateManager.CLOSE_COMPLETE); _manager = new StateManager(this); - performValidTransition(StateManager.CONFIGURE); - performValidTransition(StateManager.CONFIGURE_COMPLETE); - performValidTransition(StateManager.RECOVER); + performValidTransition(StateManager.INITIALISE); + performValidTransition(StateManager.INITALISE_COMPLETE); performValidTransition(StateManager.ACTIVATE); + performValidTransition(StateManager.ACTIVATE_COMPLETE); performValidTransition(StateManager.QUIESCE); performValidTransition(StateManager.QUIESCE_COMPLETE); performValidTransition(StateManager.CLOSE_QUIESCED); @@ -132,54 +139,50 @@ public class StateManagerTest extends TestCase implements EventListener { assertEquals(State.INITIAL, _manager.getState()); - - performInvalidTransitions(StateManager.CONFIGURE, State.CONFIGURED); - performInvalidTransitions(StateManager.CONFIGURE_COMPLETE, State.RECOVERING); - performInvalidTransitions(StateManager.RECOVER, State.ACTIVE); - performInvalidTransitions(StateManager.ACTIVATE, State.QUIESCING, State.CLOSING); + performInvalidTransitions(StateManager.INITIALISE, State.INITIALISED); + performInvalidTransitions(StateManager.INITALISE_COMPLETE, State.ACTIVATING, State.CLOSING); + performInvalidTransitions(StateManager.ACTIVATE, State.ACTIVE); + performInvalidTransitions(StateManager.ACTIVATE_COMPLETE, State.QUIESCING, State.CLOSING, State.INITIALISED); performInvalidTransitions(StateManager.QUIESCE, State.QUIESCED); - performInvalidTransitions(StateManager.QUIESCE_COMPLETE, State.RECOVERING, State.CLOSING); + performInvalidTransitions(StateManager.QUIESCE_COMPLETE, State.ACTIVATING, State.CLOSING); performInvalidTransitions(StateManager.CLOSE_QUIESCED, State.CLOSED); performInvalidTransitions(StateManager.CLOSE_COMPLETE); - - - } - private void performInvalidTransitions(StateManager.Transition preTransition, State... validTransitions) + private void performInvalidTransitions(StateManager.Transition preTransition, State... validEndStates) { if(preTransition != null) { performValidTransition(preTransition); } - EnumSet<State> nextStates = EnumSet.allOf(State.class); + EnumSet<State> endStates = EnumSet.allOf(State.class); - if(validTransitions != null) + if(validEndStates != null) { - for(State state: validTransitions) + for(State state: validEndStates) { - nextStates.remove(state); + endStates.remove(state); } } - for(State nextState : nextStates) + for(State invalidEndState : endStates) { - performInvalidStateTransition(nextState); + performInvalidStateTransition(invalidEndState); } } - private void performInvalidStateTransition(State state) + private void performInvalidStateTransition(State invalidEndState) { try { _event = null; State startState = _manager.getState(); - _manager.attainState(state); - fail("Invalid state transition performed: " + startState + " to " + state); + _manager.attainState(invalidEndState); + fail("Invalid state transition performed: " + startState + " to " + invalidEndState); } catch(IllegalStateException e) { @@ -188,6 +191,7 @@ public class StateManagerTest extends TestCase implements EventListener assertNull("No event should have be fired", _event); } + @Override public void event(Event event) { _event = event; diff --git a/java/broker/src/test/java/org/apache/qpid/server/store/TestableMemoryMessageStoreFactory.java b/java/broker/src/test/java/org/apache/qpid/server/store/TestableMemoryMessageStoreFactory.java deleted file mode 100644 index 44070f22ad..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/store/TestableMemoryMessageStoreFactory.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.store; - -public class TestableMemoryMessageStoreFactory implements MessageStoreFactory -{ - - @Override - public MessageStore createMessageStore() - { - return new TestableMemoryMessageStore(); - } - - @Override - public String getStoreClassName() - { - return TestableMemoryMessageStore.class.getSimpleName(); - } - -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/store/derby/DerbyMessageStoreQuotaEventsTest.java b/java/broker/src/test/java/org/apache/qpid/server/store/derby/DerbyMessageStoreQuotaEventsTest.java new file mode 100644 index 0000000000..5d316fca43 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/store/derby/DerbyMessageStoreQuotaEventsTest.java @@ -0,0 +1,62 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.store.derby; + +import org.apache.commons.configuration.XMLConfiguration; +import org.apache.log4j.Logger; +import org.apache.qpid.server.store.MessageStore; +import org.apache.qpid.server.store.MessageStoreQuotaEventsTestBase; + +public class DerbyMessageStoreQuotaEventsTest extends MessageStoreQuotaEventsTestBase +{ + private static final Logger _logger = Logger.getLogger(DerbyMessageStoreQuotaEventsTest.class); + + private static final int NUMBER_OF_MESSAGES_TO_OVERFILL_STORE = 10; + + /** + * Estimated using an assumption that a physical disk space occupied by a + * message is 3 times bigger then a message size + */ + private static final int OVERFULL_SIZE = (int) (MESSAGE_DATA.length * 3 * NUMBER_OF_MESSAGES_TO_OVERFILL_STORE * 0.8); + + private static final int UNDERFULL_SIZE = (int) (OVERFULL_SIZE * 0.8); + + @Override + protected int getNumberOfMessagesToFillStore() + { + return NUMBER_OF_MESSAGES_TO_OVERFILL_STORE; + } + + @Override + protected void applyStoreSpecificConfiguration(XMLConfiguration config) + { + _logger.debug("Applying store specific config. overfull-sze=" + OVERFULL_SIZE + ", underfull-size=" + UNDERFULL_SIZE); + + config.addProperty("overfull-size", OVERFULL_SIZE); + config.addProperty("underfull-size", UNDERFULL_SIZE); + } + + @Override + protected MessageStore createStore() throws Exception + { + return new DerbyMessageStore(); + } +} diff --git a/java/broker/src/test/java/org/apache/qpid/server/subscription/MockSubscription.java b/java/broker/src/test/java/org/apache/qpid/server/subscription/MockSubscription.java index 5ba9c0c015..8c5d2684ff 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/subscription/MockSubscription.java +++ b/java/broker/src/test/java/org/apache/qpid/server/subscription/MockSubscription.java @@ -1,5 +1,3 @@ -package org.apache.qpid.server.subscription; - /* * * Licensed to the Apache Software Foundation (ASF) under one @@ -21,16 +19,24 @@ package org.apache.qpid.server.subscription; * */ +package org.apache.qpid.server.subscription; + import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.AMQChannel; +import org.apache.qpid.protocol.AMQConstant; import org.apache.qpid.server.logging.LogActor; +import org.apache.qpid.server.logging.LogSubject; +import org.apache.qpid.server.message.InboundMessage; +import org.apache.qpid.server.protocol.AMQConnectionModel; +import org.apache.qpid.server.protocol.AMQSessionModel; import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.queue.QueueEntry; import org.apache.qpid.server.queue.QueueEntry.SubscriptionAcquiredState; +import org.apache.qpid.server.stats.StatisticsCounter; import java.util.ArrayList; import java.util.List; +import java.util.UUID; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; @@ -42,7 +48,7 @@ public class MockSubscription implements Subscription private AMQShortString tag = new AMQShortString("mocktag"); private AMQQueue queue = null; private StateListener _listener = null; - private AMQQueue.Context _queueContext = null; + private volatile AMQQueue.Context _queueContext = null; private State _state = State.ACTIVE; private ArrayList<QueueEntry> messages = new ArrayList<QueueEntry>(); private final Lock _stateChangeLock = new ReentrantLock(); @@ -76,19 +82,9 @@ public class MockSubscription implements Subscription _state = State.CLOSED; } - public boolean filtersMessages() - { - return false; - } - - public AMQChannel getChannel() - { - return null; - } - - public AMQShortString getConsumerTag() + public String getConsumerName() { - return tag; + return tag == null ? null : tag.asString(); } public long getSubscriptionID() @@ -121,11 +117,36 @@ public class MockSubscription implements Subscription return false; } + public long getBytesOut() + { + return 0; // TODO - Implement + } + + public long getMessagesOut() + { + return 0; // TODO - Implement + } + + public long getUnacknowledgedBytes() + { + return 0; // TODO - Implement + } + + public long getUnacknowledgedMessages() + { + return 0; // TODO - Implement + } + public AMQQueue getQueue() { return queue; } + public AMQSessionModel getSessionModel() + { + return new MockSessionModel(); + } + public boolean trySendLock() { return _stateChangeLock.tryLock(); @@ -154,11 +175,6 @@ public class MockSubscription implements Subscription return _isActive ; } - public void confirmAutoClose() - { - - } - public void set(String key, Object value) { } @@ -173,11 +189,6 @@ public class MockSubscription implements Subscription return false; } - public boolean isBrowser() - { - return false; - } - public boolean isClosed() { return _closed; @@ -207,10 +218,6 @@ public class MockSubscription implements Subscription _stateChangeLock.unlock(); } - public void resend(QueueEntry entry) throws AMQException - { - } - public void onDequeue(QueueEntry queueEntry) { } @@ -232,7 +239,6 @@ public class MockSubscription implements Subscription messages.add(entry); } - @Override public void flushBatched() { @@ -249,7 +255,7 @@ public class MockSubscription implements Subscription } public void setNoLocal(boolean noLocal) - { + { } public void setStateListener(StateListener listener) @@ -285,4 +291,259 @@ public class MockSubscription implements Subscription { _isActive = isActive; } + + private static class MockSessionModel implements AMQSessionModel + { + + @Override + public int compareTo(AMQSessionModel o) + { + return 0; + } + + @Override + public UUID getQMFId() + { + return null; + } + + @Override + public AMQConnectionModel getConnectionModel() + { + return new MockConnectionModel(); + } + + @Override + public String getClientID() + { + return null; + } + + @Override + public void close() throws AMQException + { + } + + @Override + public LogSubject getLogSubject() + { + return null; + } + + @Override + public void checkTransactionStatus(long openWarn, long openClose, + long idleWarn, long idleClose) throws AMQException + { + } + + @Override + public void block(AMQQueue queue) + { + } + + @Override + public void unblock(AMQQueue queue) + { + } + + @Override + public void block() + { + } + + @Override + public void unblock() + { + } + + @Override + public boolean getBlocking() + { + return false; + } + + @Override + public boolean onSameConnection(InboundMessage inbound) + { + return false; + } + + @Override + public int getUnacknowledgedMessageCount() + { + return 0; + } + + @Override + public Long getTxnCount() + { + return null; + } + + @Override + public Long getTxnStart() + { + return null; + } + + @Override + public Long getTxnCommits() + { + return null; + } + + @Override + public Long getTxnRejects() + { + return null; + } + + @Override + public int getChannelId() + { + return 0; + } + + @Override + public int getConsumerCount() + { + return 0; + } + } + + private static class MockConnectionModel implements AMQConnectionModel + { + @Override + public void initialiseStatistics() + { + } + + @Override + public void registerMessageReceived(long messageSize, long timestamp) + { + } + + @Override + public void registerMessageDelivered(long messageSize) + { + } + + @Override + public StatisticsCounter getMessageDeliveryStatistics() + { + return null; + } + + @Override + public StatisticsCounter getMessageReceiptStatistics() + { + return null; + } + + @Override + public StatisticsCounter getDataDeliveryStatistics() + { + return null; + } + + @Override + public StatisticsCounter getDataReceiptStatistics() + { + return null; + } + + @Override + public void resetStatistics() + { + + } + + @Override + public void close(AMQConstant cause, String message) + throws AMQException + { + } + + @Override + public void closeSession(AMQSessionModel session, AMQConstant cause, + String message) throws AMQException + { + } + + @Override + public long getConnectionId() + { + return 0; + } + + @Override + public List<AMQSessionModel> getSessionModels() + { + return null; + } + + @Override + public void block() + { + } + + @Override + public void unblock() + { + } + + @Override + public LogSubject getLogSubject() + { + return null; + } + + @Override + public String getUserName() + { + return null; + } + + @Override + public boolean isSessionNameUnique(byte[] name) + { + return false; + } + + @Override + public String getRemoteAddressString() + { + return "remoteAddress:1234"; + } + + @Override + public String getClientId() + { + return null; + } + + @Override + public String getClientVersion() + { + return null; + } + + @Override + public String getPrincipalAsString() + { + return null; + } + + @Override + public long getSessionCountLimit() + { + return 0; + } + + @Override + public long getLastIoTime() + { + return 0; + } + } } diff --git a/java/broker/src/test/java/org/apache/qpid/server/transport/ServerConnectionMBeanTest.java b/java/broker/src/test/java/org/apache/qpid/server/transport/ServerConnectionMBeanTest.java deleted file mode 100644 index dcb3692cf5..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/transport/ServerConnectionMBeanTest.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.transport; - -import org.apache.qpid.management.common.mbeans.ManagedConnection; -import org.apache.qpid.server.configuration.MockConnectionConfig; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.util.InternalBrokerBaseCase; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.transport.Binary; -import org.apache.qpid.transport.Connection; -import org.apache.qpid.transport.Session; - -import javax.management.JMException; -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.TabularData; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicLong; - -public class ServerConnectionMBeanTest extends InternalBrokerBaseCase -{ - private ServerConnection _serverConnection; - private ServerSessionMock _serverSession; - private ServerConnectionMBean _mbean; - private List<Session> _sessions = new ArrayList<Session>(); - - @Override - public void setUp() throws Exception - { - super.setUp(); - - final VirtualHost vhost = ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost("test"); - _serverConnection = new ServerConnection(1) - { - protected Collection<Session> getChannels() - { - return _sessions; - } - public Session getSession(int channelId) - { - for(Session session : _sessions) - { - if (session.getChannel() == channelId) - { - return session; - } - } - return null; - } - @Override - public AtomicLong getLastIoTime() - { - return new AtomicLong(1); - } - }; - final MockConnectionConfig config = new MockConnectionConfig(UUID.randomUUID(), null, null, - false, 1, vhost, "address", Boolean.TRUE, Boolean.TRUE, Boolean.TRUE, - "authid", "remoteProcessName", new Integer(1967), new Integer(1970), vhost.getConfigStore(), Boolean.FALSE); - _serverConnection.setConnectionConfig(config); - _serverConnection.setVirtualHost(vhost); - _serverConnection.setConnectionDelegate(new ServerConnectionDelegate(getRegistry(), "")); - _serverSession = new ServerSessionMock(_serverConnection, 1); - _mbean = (ServerConnectionMBean) _serverConnection.getManagedObject(); - } - - public void testChannels() throws Exception - { - // check the channel count is correct - TabularData tabularData = _mbean.channels(); - - int channelCount = tabularData.size(); - assertEquals("Unexpected number of channels",1,channelCount); - _sessions.add(new ServerSession(_serverConnection, new ServerSessionDelegate(), - new Binary(getName().getBytes()), 2 , _serverConnection.getConfig())); - - channelCount = _mbean.channels().size(); - assertEquals("Unexpected number of channels",2,channelCount); - - final CompositeData chanresult = tabularData.get(new Integer[]{1}); - assertNotNull(chanresult); - assertEquals("Unexpected channel id", new Integer(1),(Integer)chanresult.get(ManagedConnection.CHAN_ID)); - assertNull("Unexpected default queue", chanresult.get(ManagedConnection.DEFAULT_QUEUE)); - assertFalse("Unexpected transactional flag", (Boolean)chanresult.get(ManagedConnection.TRANSACTIONAL)); - assertFalse("Flow should have been blocked", (Boolean)chanresult.get(ManagedConnection.FLOW_BLOCKED)); - assertEquals("Unexpected unack'd count", new Integer(1967), (Integer)chanresult.get(ManagedConnection.UNACKED_COUNT)); - } - - public void testMaxChannels() throws Exception - { - _serverConnection.getConnectionDelegate().setChannelMax(10001); - assertEquals("Max channels not got correctly", new Long(10001), _mbean.getMaximumNumberOfChannels()); - } - - public void testRollback() throws Exception - { - _mbean.rollbackTransactions(1); - assertFalse("Rollback performed despite not being transacted", _serverSession.isRolledback()); - - _serverSession.setTransactional(true); - _mbean.rollbackTransactions(1); - assertTrue("Rollback not performed", _serverSession.isRolledback()); - - try - { - _mbean.rollbackTransactions(2); - fail("Exception expected"); - } - catch (JMException jme) - { - //pass - } - } - - public void testCommit() throws Exception - { - _mbean.commitTransactions(1); - assertFalse("Commit performed despite not being transacted", _serverSession.isCommitted()); - - _serverSession.setTransactional(true); - _mbean.commitTransactions(1); - assertTrue("Commit not performed", _serverSession.isCommitted()); - - try - { - _mbean.commitTransactions(2); - fail("Exception expected"); - } - catch (JMException jme) - { - //pass - } - } - - public void testGetName() - { - assertEquals("Unexpected Object Instance Name", "\"address\"", _mbean.getObjectInstanceName()); - } - - public void testEnableStatistics() - { - assertFalse("Unexpected statistics enable flag", _mbean.isStatisticsEnabled()); - _mbean.setStatisticsEnabled(true); - assertTrue("Unexpected statistics enable flag", _mbean.isStatisticsEnabled()); - } - - public void testLastIOTime() - { - assertEquals("Unexpected last IO time", new Date(1), _mbean.getLastIoTime()); - } - - private class ServerSessionMock extends ServerSession - { - private int _channelId = 0; - private boolean _committed = false; - private boolean _rolledback = false; - private boolean _transacted = false; - - ServerSessionMock(Connection connection, int channelId) - { - super(connection, new ServerSessionDelegate(), new Binary(String.valueOf(channelId).getBytes()), 1 , _serverConnection.getConfig()); - _channelId = channelId; - _sessions.add(this); - } - - public int getChannel() - { - return _channelId; - } - - @Override - public void commit() - { - _committed = true; - } - - @Override - public void rollback() - { - _rolledback = true; - } - - public boolean isCommitted() - { - return _committed; - } - - public boolean isRolledback() - { - return _rolledback; - } - - @Override - public int getUnacknowledgedMessageCount() - { - return 1967; - } - - public boolean isTransactional() - { - return _transacted; - } - - public void setTransactional(boolean transacted) - { - _transacted = transacted; - } - } -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/txn/AsyncAutoCommitTransactionTest.java b/java/broker/src/test/java/org/apache/qpid/server/txn/AsyncAutoCommitTransactionTest.java new file mode 100644 index 0000000000..1aa91fa98a --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/txn/AsyncAutoCommitTransactionTest.java @@ -0,0 +1,140 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.qpid.server.txn; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.*; + +import java.util.Collections; + +import org.apache.qpid.server.message.EnqueableMessage; +import org.apache.qpid.server.queue.BaseQueue; +import org.apache.qpid.server.store.MessageStore; +import org.apache.qpid.server.store.StoreFuture; +import org.apache.qpid.server.store.Transaction; +import org.apache.qpid.server.txn.AsyncAutoCommitTransaction.FutureRecorder; +import org.apache.qpid.server.txn.ServerTransaction.Action; +import org.apache.qpid.test.utils.QpidTestCase; + +public class AsyncAutoCommitTransactionTest extends QpidTestCase +{ + private static final String STRICT_ORDER_SYSTEM_PROPERTY = AsyncAutoCommitTransaction.QPID_STRICT_ORDER_WITH_MIXED_DELIVERY_MODE; + + private FutureRecorder _futureRecorder = mock(FutureRecorder.class); + private EnqueableMessage _message = mock(EnqueableMessage.class); + private BaseQueue _queue = mock(BaseQueue.class); + private MessageStore _messageStore = mock(MessageStore.class); + private Transaction _storeTransaction = mock(Transaction.class); + private Action _postTransactionAction = mock(Action.class); + private StoreFuture _future = mock(StoreFuture.class); + + + @Override + protected void setUp() throws Exception + { + super.setUp(); + + when(_messageStore.newTransaction()).thenReturn(_storeTransaction); + when(_storeTransaction.commitTranAsync()).thenReturn(_future); + when(_queue.isDurable()).thenReturn(true); + } + + public void testEnqueuePersistentMessagePostCommitNotCalledWhenFutureAlreadyComplete() throws Exception + { + setTestSystemProperty(STRICT_ORDER_SYSTEM_PROPERTY, "false"); + + when(_message.isPersistent()).thenReturn(true); + when(_future.isComplete()).thenReturn(true); + + AsyncAutoCommitTransaction asyncAutoCommitTransaction = + new AsyncAutoCommitTransaction(_messageStore, _futureRecorder); + + asyncAutoCommitTransaction.enqueue(_queue, _message, _postTransactionAction); + + verify(_storeTransaction).enqueueMessage(_queue, _message); + verify(_futureRecorder).recordFuture(_future, _postTransactionAction); + verifyZeroInteractions(_postTransactionAction); + } + + public void testEnqueuePersistentMessageOnMultiplQueuesPostCommitNotCalled() throws Exception + { + setTestSystemProperty(STRICT_ORDER_SYSTEM_PROPERTY, "false"); + + when(_message.isPersistent()).thenReturn(true); + when(_future.isComplete()).thenReturn(true); + + AsyncAutoCommitTransaction asyncAutoCommitTransaction = + new AsyncAutoCommitTransaction(_messageStore, _futureRecorder); + + asyncAutoCommitTransaction.enqueue(Collections.singletonList(_queue), _message, _postTransactionAction, System.currentTimeMillis()); + + verify(_storeTransaction).enqueueMessage(_queue, _message); + verify(_futureRecorder).recordFuture(_future, _postTransactionAction); + verifyZeroInteractions(_postTransactionAction); + } + + public void testEnqueuePersistentMessagePostCommitNotCalledWhenFutureNotYetComplete() throws Exception + { + setTestSystemProperty(STRICT_ORDER_SYSTEM_PROPERTY, "false"); + + when(_message.isPersistent()).thenReturn(true); + when(_future.isComplete()).thenReturn(false); + + AsyncAutoCommitTransaction asyncAutoCommitTransaction = + new AsyncAutoCommitTransaction(_messageStore, _futureRecorder); + + asyncAutoCommitTransaction.enqueue(_queue, _message, _postTransactionAction); + + verify(_storeTransaction).enqueueMessage(_queue, _message); + verify(_futureRecorder).recordFuture(_future, _postTransactionAction); + verifyZeroInteractions(_postTransactionAction); + } + + public void testEnqueueTransientMessagePostCommitIsCalledWhenNotBehavingStrictly() throws Exception + { + setTestSystemProperty(STRICT_ORDER_SYSTEM_PROPERTY, "false"); + + when(_message.isPersistent()).thenReturn(false); + + AsyncAutoCommitTransaction asyncAutoCommitTransaction = + new AsyncAutoCommitTransaction(_messageStore, _futureRecorder); + + asyncAutoCommitTransaction.enqueue(_queue, _message, _postTransactionAction); + + verifyZeroInteractions(_storeTransaction); + verify(_postTransactionAction).postCommit(); + verifyZeroInteractions(_futureRecorder); + } + + public void testEnqueueTransientMessagePostCommitIsCalledWhenBehavingStrictly() throws Exception + { + setTestSystemProperty(STRICT_ORDER_SYSTEM_PROPERTY, "true"); + + when(_message.isPersistent()).thenReturn(false); + + AsyncAutoCommitTransaction asyncAutoCommitTransaction = + new AsyncAutoCommitTransaction(_messageStore, _futureRecorder); + + asyncAutoCommitTransaction.enqueue(_queue, _message, _postTransactionAction); + + verifyZeroInteractions(_storeTransaction); + verify(_futureRecorder).recordFuture(StoreFuture.IMMEDIATE_FUTURE, _postTransactionAction); + verifyZeroInteractions(_postTransactionAction); + } +} diff --git a/java/broker/src/test/java/org/apache/qpid/server/txn/MockStoreTransaction.java b/java/broker/src/test/java/org/apache/qpid/server/txn/MockStoreTransaction.java index af49238998..0221f3d509 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/txn/MockStoreTransaction.java +++ b/java/broker/src/test/java/org/apache/qpid/server/txn/MockStoreTransaction.java @@ -124,6 +124,12 @@ class MockStoreTransaction implements Transaction storeTransaction.setState(TransactionState.STARTED); return storeTransaction; } + + @Override + public String getStoreType() + { + return "TEST"; + } }; } }
\ No newline at end of file diff --git a/java/broker/src/test/java/org/apache/qpid/server/util/InternalBrokerBaseCase.java b/java/broker/src/test/java/org/apache/qpid/server/util/InternalBrokerBaseCase.java index 8a34e92985..d7a9078412 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/util/InternalBrokerBaseCase.java +++ b/java/broker/src/test/java/org/apache/qpid/server/util/InternalBrokerBaseCase.java @@ -20,8 +20,7 @@ */ package org.apache.qpid.server.util; -import java.util.UUID; - +import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; import org.apache.qpid.AMQException; @@ -38,6 +37,7 @@ import org.apache.qpid.server.exchange.Exchange; import org.apache.qpid.server.logging.SystemOutMessageLogger; import org.apache.qpid.server.logging.actors.CurrentActor; import org.apache.qpid.server.logging.actors.TestLogActor; +import org.apache.qpid.server.model.UUIDGenerator; import org.apache.qpid.server.protocol.InternalTestProtocolSession; import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.queue.AMQQueueFactory; @@ -45,7 +45,6 @@ import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.registry.IApplicationRegistry; import org.apache.qpid.server.store.MessageStore; import org.apache.qpid.server.store.TestableMemoryMessageStore; -import org.apache.qpid.server.store.TestableMemoryMessageStoreFactory; import org.apache.qpid.server.virtualhost.VirtualHost; import org.apache.qpid.test.utils.QpidTestCase; @@ -68,10 +67,10 @@ public class InternalBrokerBaseCase extends QpidTestCase super.setUp(); _configXml.addProperty("virtualhosts.virtualhost.name", "test"); - _configXml.addProperty("virtualhosts.virtualhost.test.store.factoryclass", TestableMemoryMessageStoreFactory.class.getName()); + _configXml.addProperty("virtualhosts.virtualhost.test.store.class", TestableMemoryMessageStore.class.getName()); _configXml.addProperty("virtualhosts.virtualhost(-1).name", getName()); - _configXml.addProperty("virtualhosts.virtualhost(-1)."+getName()+".store.factoryclass", TestableMemoryMessageStoreFactory.class.getName()); + _configXml.addProperty("virtualhosts.virtualhost(-1)."+getName()+".store.class", TestableMemoryMessageStore.class.getName()); createBroker(); } @@ -85,7 +84,7 @@ public class InternalBrokerBaseCase extends QpidTestCase configure(); - _registry = new TestApplicationRegistry(_configuration); + _registry = createApplicationRegistry(); ApplicationRegistry.initialise(_registry); _registry.getVirtualHostRegistry().setDefaultVirtualHostName(getName()); _virtualHost = _registry.getVirtualHostRegistry().getVirtualHost(getName()); @@ -93,7 +92,7 @@ public class InternalBrokerBaseCase extends QpidTestCase QUEUE_NAME = new AMQShortString("test"); // Create a queue on the test Vhost.. this will aid in diagnosing duff tests // as the ExpiredMessage Task will log with the test Name. - _queue = AMQQueueFactory.createAMQQueueImpl(QUEUE_NAME, false, new AMQShortString("testowner"), + _queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), QUEUE_NAME.asString(), false, "testowner", false, false, _virtualHost, null); Exchange defaultExchange = _virtualHost.getExchangeRegistry().getDefaultExchange(); @@ -102,7 +101,7 @@ public class InternalBrokerBaseCase extends QpidTestCase _virtualHost = _registry.getVirtualHostRegistry().getVirtualHost("test"); _messageStore = _virtualHost.getMessageStore(); - _queue = AMQQueueFactory.createAMQQueueImpl(new AMQShortString(getName()), false, new AMQShortString("testowner"), + _queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), getName(), false, "testowner", false, false, _virtualHost, null); _virtualHost.getQueueRegistry().registerQueue(_queue); @@ -119,6 +118,11 @@ public class InternalBrokerBaseCase extends QpidTestCase _session.addChannel(_channel); } + protected IApplicationRegistry createApplicationRegistry() throws ConfigurationException + { + return new TestApplicationRegistry(_configuration); + } + protected void configure() { // Allow other tests to override configuration @@ -250,7 +254,7 @@ public class InternalBrokerBaseCase extends QpidTestCase channel.publishContentHeader(_headerBody); } - + channel.sync(); } public void acknowledge(AMQChannel channel, long deliveryTag) diff --git a/java/broker/src/test/java/org/apache/qpid/server/util/TestApplicationRegistry.java b/java/broker/src/test/java/org/apache/qpid/server/util/TestApplicationRegistry.java index 7aa5ed23fe..a64ab620ab 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/util/TestApplicationRegistry.java +++ b/java/broker/src/test/java/org/apache/qpid/server/util/TestApplicationRegistry.java @@ -20,6 +20,9 @@ */ package org.apache.qpid.server.util; +import java.net.SocketAddress; +import java.util.Collections; +import java.util.Map; import org.apache.commons.configuration.ConfigurationException; import org.apache.qpid.server.configuration.ServerConfiguration; @@ -28,9 +31,11 @@ import org.apache.qpid.server.logging.NullRootMessageLogger; import org.apache.qpid.server.logging.actors.BrokerActor; import org.apache.qpid.server.logging.actors.CurrentActor; import org.apache.qpid.server.logging.actors.GenericActor; +import org.apache.qpid.server.plugins.PluginManager; import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.security.auth.database.PropertiesPrincipalDatabase; import org.apache.qpid.server.security.auth.manager.AuthenticationManager; +import org.apache.qpid.server.security.auth.manager.IAuthenticationManagerRegistry; import org.apache.qpid.server.security.auth.manager.PrincipalDatabaseAuthenticationManager; import java.util.Properties; @@ -51,11 +56,10 @@ public class TestApplicationRegistry extends ApplicationRegistry super.initialise(); } - /** - * @see org.apache.qpid.server.registry.ApplicationRegistry#createAuthenticationManager() - */ @Override - protected AuthenticationManager createAuthenticationManager() throws ConfigurationException + protected IAuthenticationManagerRegistry createAuthenticationManagerRegistry( + ServerConfiguration _configuration, PluginManager _pluginManager) + throws ConfigurationException { final Properties users = new Properties(); users.put("guest","guest"); @@ -63,7 +67,7 @@ public class TestApplicationRegistry extends ApplicationRegistry final PropertiesPrincipalDatabase ppd = new PropertiesPrincipalDatabase(users); - AuthenticationManager pdam = new PrincipalDatabaseAuthenticationManager() + final AuthenticationManager pdam = new PrincipalDatabaseAuthenticationManager() { /** @@ -83,12 +87,35 @@ public class TestApplicationRegistry extends ApplicationRegistry super.initialise(); } }; - pdam.initialise(); - return pdam; - } + return new IAuthenticationManagerRegistry() + { + @Override + public void close() + { + pdam.close(); + } + + @Override + public AuthenticationManager getAuthenticationManager( + SocketAddress address) + { + return pdam; + } + @Override + public Map<String, AuthenticationManager> getAvailableAuthenticationManagers() + { + return Collections.singletonMap(pdam.getClass().getName(), pdam); + } + + @Override + public void addRegistryChangeListener(RegistryChangeListener listener) + { + } + }; + } } diff --git a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/HouseKeepingTaskTest.java b/java/broker/src/test/java/org/apache/qpid/server/virtualhost/HouseKeepingTaskTest.java index 0794154e47..8b4a52bb79 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/HouseKeepingTaskTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/virtualhost/HouseKeepingTaskTest.java @@ -64,4 +64,50 @@ public class HouseKeepingTaskTest extends QpidTestCase //clean up the test actor CurrentActor.remove(); } + + public void testThreadNameIsSetForDurationOfTask() throws Exception + { + //create and set a test actor + LogActor testActor = new TestLogActor(new NullRootMessageLogger()); + CurrentActor.set(testActor); + + String originalThreadName = Thread.currentThread().getName(); + + String vhostName = "HouseKeepingTaskTestVhost"; + + String expectedThreadNameDuringExecution = vhostName + ":" + "ThreadNameRememberingTask"; + + ThreadNameRememberingTask testTask = new ThreadNameRememberingTask(new MockVirtualHost(vhostName)); + + testTask.run(); + + assertEquals("Thread name should have been set during execution", expectedThreadNameDuringExecution, testTask.getThreadNameDuringExecution()); + assertEquals("Thread name should have been reverted after task has run", originalThreadName, Thread.currentThread().getName()); + + //clean up the test actor + CurrentActor.remove(); + } + + + private static final class ThreadNameRememberingTask extends HouseKeepingTask + { + private String _threadNameDuringExecution; + + private ThreadNameRememberingTask(VirtualHost vhost) + { + super(vhost); + } + + @Override + public void execute() + { + _threadNameDuringExecution = Thread.currentThread().getName(); // store current thread name so we can assert it later + throw new RuntimeException("deliberate exception to check that thread name still gets reverted"); + } + + public String getThreadNameDuringExecution() + { + return _threadNameDuringExecution; + } + } } diff --git a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/MockVirtualHost.java b/java/broker/src/test/java/org/apache/qpid/server/virtualhost/MockVirtualHost.java index 91174c5d10..290c465785 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/MockVirtualHost.java +++ b/java/broker/src/test/java/org/apache/qpid/server/virtualhost/MockVirtualHost.java @@ -32,7 +32,6 @@ import org.apache.qpid.server.connection.IConnectionRegistry; import org.apache.qpid.server.exchange.ExchangeFactory; import org.apache.qpid.server.exchange.ExchangeRegistry; import org.apache.qpid.server.federation.BrokerLink; -import org.apache.qpid.server.management.ManagedObject; import org.apache.qpid.server.protocol.v1_0.LinkRegistry; import org.apache.qpid.server.queue.QueueRegistry; import org.apache.qpid.server.registry.IApplicationRegistry; @@ -141,11 +140,6 @@ public class MockVirtualHost implements VirtualHost return 0; } - public ManagedObject getManagedObject() - { - return null; - } - public MessageStore getMessageStore() { return null; @@ -222,6 +216,12 @@ public class MockVirtualHost implements VirtualHost return null; } + @Override + public UUID getQMFId() + { + return null; + } + public ConfiguredObject<VirtualHostConfigType, VirtualHostConfig> getParent() { return null; @@ -257,11 +257,6 @@ public class MockVirtualHost implements VirtualHost } - public boolean isStatisticsEnabled() - { - return false; - } - public void registerMessageDelivered(long messageSize) { @@ -277,14 +272,16 @@ public class MockVirtualHost implements VirtualHost } - public void setStatisticsEnabled(boolean enabled) + public State getState() { + return State.ACTIVE; + } + public void block() + { } - @Override - public State getState() + public void unblock() { - return State.ACTIVE; } }
\ No newline at end of file diff --git a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/VirtualHostImplTest.java b/java/broker/src/test/java/org/apache/qpid/server/virtualhost/VirtualHostImplTest.java index 87eb0f9d16..b8ba76e43d 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/VirtualHostImplTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/virtualhost/VirtualHostImplTest.java @@ -27,7 +27,7 @@ import org.apache.qpid.server.configuration.ServerConfiguration; import org.apache.qpid.server.exchange.Exchange; import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.store.MemoryMessageStoreFactory; +import org.apache.qpid.server.store.MemoryMessageStore; import org.apache.qpid.server.util.TestApplicationRegistry; import org.apache.qpid.test.utils.QpidTestCase; @@ -192,7 +192,7 @@ public class VirtualHostImplTest extends QpidTestCase writer.write(" <name>" + vhostName + "</name>"); writer.write(" <" + vhostName + ">"); writer.write(" <store>"); - writer.write(" <factoryclass>" + MemoryMessageStoreFactory.class.getName() + "</factoryclass>"); + writer.write(" <class>" + MemoryMessageStore.class.getName() + "</class>"); writer.write(" </store>"); if(exchangeName != null && !dontDeclare) { diff --git a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyTest.java b/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyTest.java index fdd163b323..aa8448b99d 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyTest.java @@ -146,7 +146,7 @@ public class TopicDeletePolicyTest extends InternalBrokerBaseCase MockAMQQueue queue = createOwnedQueue(); - queue.addBinding(new Binding(null, "bindingKey", queue, new DirectExchange(), null)); + queue.addBinding(new Binding(null, null, "bindingKey", queue, new DirectExchange(), null)); policy.performPolicy(queue); @@ -165,7 +165,7 @@ public class TopicDeletePolicyTest extends InternalBrokerBaseCase MockAMQQueue queue = createOwnedQueue(); - queue.addBinding(new Binding(null, "bindingKey", queue, new TopicExchange(), null)); + queue.addBinding(new Binding(null, null, "bindingKey", queue, new TopicExchange(), null)); queue.setAutoDelete(false); @@ -186,7 +186,7 @@ public class TopicDeletePolicyTest extends InternalBrokerBaseCase final MockAMQQueue queue = createOwnedQueue(); - queue.addBinding(new Binding(null, "bindingKey", queue, new TopicExchange(), null)); + queue.addBinding(new Binding(null, null, "bindingKey", queue, new TopicExchange(), null)); setQueueToAutoDelete(queue); @@ -207,7 +207,7 @@ public class TopicDeletePolicyTest extends InternalBrokerBaseCase MockAMQQueue queue = createOwnedQueue(); - queue.addBinding(new Binding(null, "bindingKey", queue, new TopicExchange(), null)); + queue.addBinding(new Binding(null, null, "bindingKey", queue, new TopicExchange(), null)); policy.performPolicy(queue); @@ -233,7 +233,7 @@ public class TopicDeletePolicyTest extends InternalBrokerBaseCase MockAMQQueue queue = createOwnedQueue(); - queue.addBinding(new Binding(null, "bindingKey", queue, new TopicExchange(), null)); + queue.addBinding(new Binding(null, null, "bindingKey", queue, new TopicExchange(), null)); policy.performPolicy(queue); @@ -253,7 +253,7 @@ public class TopicDeletePolicyTest extends InternalBrokerBaseCase MockAMQQueue queue = createOwnedQueue(); - queue.addBinding(new Binding(null, "bindingKey", queue, new TopicExchange(), null)); + queue.addBinding(new Binding(null, null, "bindingKey", queue, new TopicExchange(), null)); policy.performPolicy(queue); |
