diff options
| author | Robert Gemmell <robbie@apache.org> | 2013-09-23 23:26:35 +0000 |
|---|---|---|
| committer | Robert Gemmell <robbie@apache.org> | 2013-09-23 23:26:35 +0000 |
| commit | efb5fc9fef693085e1eab22d84bd250f2bc241d6 (patch) | |
| tree | 0a6888de9581e64a9ece4453ee24fee3f0a4d171 /qpid/java/broker/src/test | |
| parent | 436a3013e6b78ed7c494c815a1c78f9653d96e7d (diff) | |
| download | qpid-python-efb5fc9fef693085e1eab22d84bd250f2bc241d6.tar.gz | |
QPID-5159: move the entire broker dir to broker-core, no other changes, fixups in next commit
git-svn-id: https://svn.apache.org/repos/asf/qpid/trunk@1525731 13f79535-47bb-0310-9956-ffa450edef68
Diffstat (limited to 'qpid/java/broker/src/test')
149 files changed, 0 insertions, 27588 deletions
diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/BrokerOptionsTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/BrokerOptionsTest.java deleted file mode 100644 index c22fcf4a14..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/BrokerOptionsTest.java +++ /dev/null @@ -1,329 +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 java.io.File; -import java.util.Map; - -import org.apache.qpid.server.configuration.BrokerProperties; -import org.apache.qpid.test.utils.QpidTestCase; - -public class BrokerOptionsTest extends QpidTestCase -{ - private BrokerOptions _options; - - protected void setUp() throws Exception - { - super.setUp(); - _options = new BrokerOptions(); - } - - public void testDefaultConfigurationStoreType() - { - assertEquals("json", _options.getConfigurationStoreType()); - } - - public void testOverriddenConfigurationStoreType() - { - _options.setConfigurationStoreType("dby"); - assertEquals("dby", _options.getConfigurationStoreType()); - } - - public void testDefaultConfigurationStoreLocationWithQpidWork() - { - String qpidWork = "/test/value"; - setTestSystemProperty("QPID_WORK", qpidWork); - - String expectedPath = new File(qpidWork, BrokerOptions.DEFAULT_CONFIG_NAME_PREFIX + "." + BrokerOptions.DEFAULT_STORE_TYPE).getAbsolutePath(); - assertEquals (expectedPath, _options.getConfigurationStoreLocation()); - } - - public void testDefaultConfigurationStoreLocationWithoutQpidWork() - { - setTestSystemProperty("QPID_WORK", null); - String userDir = System.getProperty("user.dir"); - - String expectedPath = new File(userDir, "work/" + BrokerOptions.DEFAULT_CONFIG_NAME_PREFIX + "." + BrokerOptions.DEFAULT_STORE_TYPE).getAbsolutePath(); - assertEquals (expectedPath, _options.getConfigurationStoreLocation()); - } - - public void testDefaultConfigurationStoreLocationWithQpidWorkAndDifferentStoreType() - { - String qpidWork = "/test/value"; - setTestSystemProperty("QPID_WORK", qpidWork); - - String storeType = "dby"; - _options.setConfigurationStoreType(storeType); - - String expectedPath = new File(qpidWork, BrokerOptions.DEFAULT_CONFIG_NAME_PREFIX + "." + storeType).getAbsolutePath(); - assertEquals (expectedPath, _options.getConfigurationStoreLocation()); - } - - public void testOverriddenConfigurationStoreLocation() - { - final String testConfigFile = "/my/test/store-location.dby"; - _options.setConfigurationStoreLocation(testConfigFile); - assertEquals(testConfigFile, _options.getConfigurationStoreLocation()); - } - - public void testDefaultLogConfigFileWithQpidHome() - { - String qpidHome = "/test/value"; - setTestSystemProperty(BrokerProperties.PROPERTY_QPID_HOME, qpidHome); - - String expectedPath = new File(qpidHome, BrokerOptions.DEFAULT_LOG_CONFIG_FILE).getAbsolutePath(); - - assertEquals(expectedPath, _options.getLogConfigFileLocation()); - } - - public void testDefaultLogConfigFileWithoutQpiddHome() - { - setTestSystemProperty(BrokerProperties.PROPERTY_QPID_HOME, null); - - String expectedPath = new File(BrokerOptions.DEFAULT_LOG_CONFIG_FILE).getAbsolutePath(); - - assertEquals(expectedPath, _options.getLogConfigFileLocation()); - } - - public void testOverriddenLogConfigFile() - { - final String testLogConfigFile = "etc/mytestlog4j.xml"; - _options.setLogConfigFileLocation(testLogConfigFile); - assertEquals(testLogConfigFile, _options.getLogConfigFileLocation()); - } - - public void testDefaultLogWatchFrequency() - { - assertEquals(0L, _options.getLogWatchFrequency()); - } - - public void testOverridenLogWatchFrequency() - { - final int myFreq = 10 * 1000; - - _options.setLogWatchFrequency(myFreq); - assertEquals(myFreq, _options.getLogWatchFrequency()); - } - - public void testDefaultInitialConfigurationLocation() - { - assertEquals(BrokerOptions.DEFAULT_INITIAL_CONFIG_LOCATION, _options.getInitialConfigurationLocation()); - } - - public void testOverriddenInitialConfigurationLocation() - { - final String testConfigFile = "etc/mytestconfig.json"; - _options.setInitialConfigurationLocation(testConfigFile); - assertEquals(testConfigFile, _options.getInitialConfigurationLocation()); - } - - public void testDefaultManagementMode() - { - assertEquals(false, _options.isManagementMode()); - } - - public void testOverriddenDefaultManagementMode() - { - _options.setManagementMode(true); - assertEquals(true, _options.isManagementMode()); - } - - public void testDefaultManagementModeQuiesceVirtualHosts() - { - assertEquals(false, _options.isManagementModeQuiesceVirtualHosts()); - } - - public void testOverriddenDefaultManagementModeQuiesceVirtualHosts() - { - _options.setManagementModeQuiesceVirtualHosts(true); - assertEquals(true, _options.isManagementModeQuiesceVirtualHosts()); - } - - public void testDefaultManagementModeRmiPortOverride() - { - assertEquals(0, _options.getManagementModeRmiPortOverride()); - } - - public void testOverriddenManagementModeRmiPort() - { - _options.setManagementModeRmiPortOverride(5555); - assertEquals(5555, _options.getManagementModeRmiPortOverride()); - } - - public void testDefaultManagementModeJmxPortOverride() - { - assertEquals(0, _options.getManagementModeJmxPortOverride()); - } - - public void testOverriddenManagementModeJmxPort() - { - _options.setManagementModeJmxPortOverride(5555); - assertEquals(5555, _options.getManagementModeJmxPortOverride()); - } - - public void testDefaultManagementModeHttpPortOverride() - { - assertEquals(0, _options.getManagementModeHttpPortOverride()); - } - - public void testOverriddenManagementModeHttpPort() - { - _options.setManagementModeHttpPortOverride(5555); - assertEquals(5555, _options.getManagementModeHttpPortOverride()); - } - - public void testDefaultSkipLoggingConfiguration() - { - assertFalse(_options.isSkipLoggingConfiguration()); - } - - public void testOverriddenSkipLoggingConfiguration() - { - _options.setSkipLoggingConfiguration(true); - assertTrue(_options.isSkipLoggingConfiguration()); - } - - public void testDefaultOverwriteConfigurationStore() - { - assertFalse(_options.isOverwriteConfigurationStore()); - } - - public void testOverriddenOverwriteConfigurationStore() - { - _options.setOverwriteConfigurationStore(true); - assertTrue(_options.isOverwriteConfigurationStore()); - } - - public void testManagementModePassword() - { - _options.setManagementModePassword("test"); - assertEquals("Unexpected management mode password", "test", _options.getManagementModePassword()); - } - - public void testGetDefaultConfigProperties() - { - //Unset QPID_WORK and QPID_HOME for this test. - //See below for specific tests of behaviour depending on their value - setTestSystemProperty("QPID_WORK", null); - setTestSystemProperty("QPID_HOME", null); - - Map<String,String> props = _options.getConfigProperties(); - - assertEquals("unexpected number of entries", 5, props.keySet().size()); - - assertEquals(BrokerOptions.DEFAULT_AMQP_PORT_NUMBER, props.get(BrokerOptions.QPID_AMQP_PORT)); - assertEquals(BrokerOptions.DEFAULT_HTTP_PORT_NUMBER, props.get(BrokerOptions.QPID_HTTP_PORT)); - assertEquals(BrokerOptions.DEFAULT_RMI_PORT_NUMBER, props.get(BrokerOptions.QPID_RMI_PORT)); - assertEquals(BrokerOptions.DEFAULT_JMX_PORT_NUMBER, props.get(BrokerOptions.QPID_JMX_PORT)); - assertEquals(BrokerOptions.DEFAULT_JMX_PORT_NUMBER, props.get(BrokerOptions.QPID_JMX_PORT)); - assertTrue(props.containsKey(BrokerOptions.QPID_WORK_DIR)); - assertFalse(props.containsKey(BrokerOptions.QPID_HOME_DIR)); - } - - public void testDefaultWorkDirWithQpidWork() - { - String qpidWork = new File(File.separator + "test" + File.separator + "value").getAbsolutePath(); - setTestSystemProperty("QPID_WORK", qpidWork); - - assertEquals (qpidWork, _options.getConfigProperties().get(BrokerOptions.QPID_WORK_DIR)); - } - - public void testDefaultWorkDirWithoutQpidWork() - { - setTestSystemProperty("QPID_WORK", null); - String userDir = System.getProperty("user.dir"); - - String expectedPath = new File(userDir, "work").getAbsolutePath(); - assertEquals (expectedPath, _options.getConfigProperties().get(BrokerOptions.QPID_WORK_DIR)); - } - - public void testOverriddenWorkDir() - { - final String testWorkDir = "/my/test/work/dir"; - _options.setConfigProperty(BrokerOptions.QPID_WORK_DIR, testWorkDir); - assertEquals(testWorkDir, _options.getConfigProperties().get(BrokerOptions.QPID_WORK_DIR)); - } - - public void testDefaultHomeDirWithQpidHome() - { - String qpidHome = new File(File.separator + "test" + File.separator + "value").getAbsolutePath(); - setTestSystemProperty("QPID_HOME", qpidHome); - - assertEquals (qpidHome, _options.getConfigProperties().get(BrokerOptions.QPID_HOME_DIR)); - assertEquals("unexpected number of entries", 6, _options.getConfigProperties().keySet().size()); - } - - public void testDefaultomeDirWithoutQpidHome() - { - setTestSystemProperty("QPID_HOME", null); - - assertNull(_options.getConfigProperties().get(BrokerOptions.QPID_HOME_DIR)); - assertFalse(_options.getConfigProperties().containsKey(BrokerOptions.QPID_HOME_DIR)); - assertEquals("unexpected number of entries", 5, _options.getConfigProperties().keySet().size()); - } - - public void testOverriddenHomeDir() - { - final String testHomeDir = "/my/test/home/dir"; - _options.setConfigProperty(BrokerOptions.QPID_HOME_DIR, testHomeDir); - assertEquals(testHomeDir, _options.getConfigProperties().get(BrokerOptions.QPID_HOME_DIR)); - assertEquals("unexpected number of entries", 6, _options.getConfigProperties().keySet().size()); - } - - public void testSetDefaultConfigProperties() - { - //Unset QPID_WORK and QPID_HOME for this test. - //See above for specific tests of behaviour depending on their value - setTestSystemProperty("QPID_WORK", null); - setTestSystemProperty("QPID_HOME", null); - - String oldPort = BrokerOptions.DEFAULT_AMQP_PORT_NUMBER; - String newPort = "12345"; - - //set a new value for a previously defaulted port number property - _options.setConfigProperty(BrokerOptions.QPID_AMQP_PORT, newPort); - Map<String,String> props = _options.getConfigProperties(); - assertEquals("unexpected number of entries", 5, props.keySet().size()); - assertEquals(newPort, props.get(BrokerOptions.QPID_AMQP_PORT)); - assertEquals(BrokerOptions.DEFAULT_HTTP_PORT_NUMBER, props.get(BrokerOptions.QPID_HTTP_PORT)); - assertEquals(BrokerOptions.DEFAULT_RMI_PORT_NUMBER, props.get(BrokerOptions.QPID_RMI_PORT)); - assertEquals(BrokerOptions.DEFAULT_JMX_PORT_NUMBER, props.get(BrokerOptions.QPID_JMX_PORT)); - - //clear the value to ensure the default returns - _options.setConfigProperty(BrokerOptions.QPID_AMQP_PORT, null); - props = _options.getConfigProperties(); - assertEquals("unexpected number of entries", 5, props.keySet().size()); - assertEquals(oldPort, props.get(BrokerOptions.QPID_AMQP_PORT)); - assertEquals(BrokerOptions.DEFAULT_HTTP_PORT_NUMBER, props.get(BrokerOptions.QPID_HTTP_PORT)); - assertEquals(BrokerOptions.DEFAULT_RMI_PORT_NUMBER, props.get(BrokerOptions.QPID_RMI_PORT)); - assertEquals(BrokerOptions.DEFAULT_JMX_PORT_NUMBER, props.get(BrokerOptions.QPID_JMX_PORT)); - - //set a user specified property - _options.setConfigProperty("name", "value"); - props = _options.getConfigProperties(); - assertEquals("unexpected number of entries", 6, props.keySet().size()); - assertEquals(oldPort, props.get(BrokerOptions.QPID_AMQP_PORT)); - assertEquals(BrokerOptions.DEFAULT_HTTP_PORT_NUMBER, props.get(BrokerOptions.QPID_HTTP_PORT)); - assertEquals(BrokerOptions.DEFAULT_RMI_PORT_NUMBER, props.get(BrokerOptions.QPID_RMI_PORT)); - assertEquals(BrokerOptions.DEFAULT_JMX_PORT_NUMBER, props.get(BrokerOptions.QPID_JMX_PORT)); - assertEquals("value", props.get("name")); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/MainTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/MainTest.java deleted file mode 100644 index f3b1749808..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/MainTest.java +++ /dev/null @@ -1,284 +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 java.io.File; -import java.util.Map; - -import org.apache.commons.cli.CommandLine; -import org.apache.qpid.server.configuration.BrokerProperties; -import org.apache.qpid.test.utils.QpidTestCase; - -/** - * Test to verify the command line parsing within the Main class, by - * providing it a series of command line arguments and verifying the - * BrokerOptions emerging for use in starting the Broker instance. - */ -public class MainTest extends QpidTestCase -{ - private Exception _startupException; - - public void testNoOptionsSpecified() - { - String qpidWork = "/qpid/work"; - setTestSystemProperty(BrokerProperties.PROPERTY_QPID_WORK, qpidWork); - String qpidHome = "/qpid/home"; - setTestSystemProperty(BrokerProperties.PROPERTY_QPID_HOME, qpidHome); - - String expectedStorePath = new File(qpidWork, BrokerOptions.DEFAULT_CONFIG_NAME_PREFIX + ".json").getAbsolutePath(); - String expectedLogConfigPath = new File(qpidHome, BrokerOptions.DEFAULT_LOG_CONFIG_FILE).getAbsolutePath(); - - BrokerOptions options = startDummyMain(""); - - assertEquals("json", options.getConfigurationStoreType()); - assertEquals(expectedStorePath, options.getConfigurationStoreLocation()); - assertEquals(expectedLogConfigPath, options.getLogConfigFileLocation()); - assertEquals(0, options.getLogWatchFrequency()); - assertEquals(BrokerOptions.DEFAULT_INITIAL_CONFIG_LOCATION, options.getInitialConfigurationLocation()); - assertFalse(options.isOverwriteConfigurationStore()); - assertFalse(options.isManagementMode()); - assertEquals(0, options.getManagementModeJmxPortOverride()); - assertEquals(0, options.getManagementModeRmiPortOverride()); - assertEquals(0, options.getManagementModeHttpPortOverride()); - } - - public void testConfigurationStoreLocation() - { - BrokerOptions options = startDummyMain("-sp abcd/config.xml"); - assertEquals("abcd/config.xml", options.getConfigurationStoreLocation()); - - options = startDummyMain("-store-path abcd/config2.xml"); - assertEquals("abcd/config2.xml", options.getConfigurationStoreLocation()); - } - - public void testConfigurationStoreType() - { - BrokerOptions options = startDummyMain("-st dby"); - assertEquals("dby", options.getConfigurationStoreType()); - - options = startDummyMain("-store-type bdb"); - assertEquals("bdb", options.getConfigurationStoreType()); - } - - public void testOverwriteConfigurationStore() - { - BrokerOptions options = startDummyMain("-os"); - assertTrue(options.isOverwriteConfigurationStore()); - - options = startDummyMain("-overwrite-store"); - assertTrue(options.isOverwriteConfigurationStore()); - } - - public void testLogConfig() - { - BrokerOptions options = startDummyMain("-l wxyz/log4j.xml"); - - assertEquals("wxyz/log4j.xml", options.getLogConfigFileLocation()); - } - - public void testLogWatch() - { - BrokerOptions options = startDummyMain("-w 9"); - - assertEquals(9, options.getLogWatchFrequency()); - } - - public void testVersion() - { - final TestMain main = new TestMain("-v".split("\\s")); - - assertNotNull("Command line not parsed correctly", main.getCommandLine()); - assertTrue("Parsed command line didnt pick up version option", main.getCommandLine().hasOption("v")); - } - - public void testHelp() - { - final TestMain main = new TestMain("-h".split("\\s")); - - assertNotNull("Command line not parsed correctly", main.getCommandLine()); - assertTrue("Parsed command line didnt pick up help option", main.getCommandLine().hasOption("h")); - } - - public void testInitailConfigurationLocation() - { - BrokerOptions options = startDummyMain("-icp abcd/initial-config.json"); - assertEquals("abcd/initial-config.json", options.getInitialConfigurationLocation()); - - options = startDummyMain("-initial-config-path abcd/initial-config.json"); - assertEquals("abcd/initial-config.json", options.getInitialConfigurationLocation()); - } - - public void testManagementMode() - { - BrokerOptions options = startDummyMain("-mm"); - assertTrue(options.isManagementMode()); - - options = startDummyMain("--management-mode"); - assertTrue(options.isManagementMode()); - } - - public void testManagementModeRmiPortOverride() - { - BrokerOptions options = startDummyMain("-mm -mmrmi 7777"); - assertTrue(options.isManagementMode()); - assertEquals(7777, options.getManagementModeRmiPortOverride()); - - options = startDummyMain("-mm --management-mode-rmi-registry-port 7777"); - assertTrue(options.isManagementMode()); - assertEquals(7777, options.getManagementModeRmiPortOverride()); - - options = startDummyMain("-mmrmi 7777"); - assertEquals(0, options.getManagementModeRmiPortOverride()); - } - - public void testManagementModeJmxPortOverride() - { - BrokerOptions options = startDummyMain("-mm -mmjmx 8888"); - assertTrue(options.isManagementMode()); - assertEquals(8888, options.getManagementModeJmxPortOverride()); - - options = startDummyMain("-mm --management-mode-jmx-connector-port 8888"); - assertTrue(options.isManagementMode()); - assertEquals(8888, options.getManagementModeJmxPortOverride()); - - options = startDummyMain("-mmjmx 8888"); - assertEquals(0, options.getManagementModeJmxPortOverride()); - } - - public void testManagementModeHttpPortOverride() - { - BrokerOptions options = startDummyMain("-mm -mmhttp 9999"); - assertTrue(options.isManagementMode()); - assertEquals(9999, options.getManagementModeHttpPortOverride()); - - options = startDummyMain("-mm --management-mode-http-port 9999"); - assertTrue(options.isManagementMode()); - assertEquals(9999, options.getManagementModeHttpPortOverride()); - - options = startDummyMain("-mmhttp 9999"); - assertEquals(0, options.getManagementModeHttpPortOverride()); - } - - public void testManagementModePassword() - { - String password = getTestName(); - BrokerOptions options = startDummyMain("-mm -mmpass " + password); - assertTrue(options.isManagementMode()); - assertEquals(password, options.getManagementModePassword()); - - options = startDummyMain("-mm --management-mode-password " + password); - assertTrue(options.isManagementMode()); - assertEquals(password, options.getManagementModePassword()); - - options = startDummyMain("-mmpass " + password); - assertNotNull(options.getManagementModePassword()); - } - - public void testDefaultManagementModePassword() - { - BrokerOptions options = startDummyMain("-mm"); - assertTrue(options.isManagementMode()); - assertNotNull(options.getManagementModePassword()); - } - - public void testSetConfigProperties() - { - //short name - String newPort = "12345"; - BrokerOptions options = startDummyMain("-prop name=value -prop " + BrokerOptions.QPID_AMQP_PORT + "=" + newPort); - - Map<String, String> props = options.getConfigProperties(); - - assertEquals(newPort, props.get(BrokerOptions.QPID_AMQP_PORT)); - assertEquals("value", props.get("name")); - - //long name - newPort = "678910"; - options = startDummyMain("--config-property name2=value2 --config-property " + BrokerOptions.QPID_AMQP_PORT + "=" + newPort); - - props = options.getConfigProperties(); - - assertEquals(newPort, props.get(BrokerOptions.QPID_AMQP_PORT)); - assertEquals("value2", props.get("name2")); - } - - public void testSetConfigPropertiesInvalidFormat() - { - //missing equals - startDummyMain("-prop namevalue"); - assertTrue("expected exception did not occur", - _startupException instanceof IllegalArgumentException); - - //no name specified - startDummyMain("-prop =value"); - assertTrue("expected exception did not occur", - _startupException instanceof IllegalArgumentException); - } - - private BrokerOptions startDummyMain(String commandLine) - { - return (new TestMain(commandLine.split("\\s"))).getOptions(); - } - - private class TestMain extends Main - { - private BrokerOptions _options; - - public TestMain(String[] args) - { - super(args); - } - - @Override - protected void execute() - { - try - { - super.execute(); - } - catch(Exception re) - { - MainTest.this._startupException = re; - } - } - - @Override - protected void startBroker(BrokerOptions options) - { - _options = options; - } - - @Override - protected void setExceptionHandler() - { - } - - public BrokerOptions getOptions() - { - return _options; - } - - public CommandLine getCommandLine() - { - return _commandLine; - } - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/SelectorParserTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/SelectorParserTest.java deleted file mode 100644 index 3e0e217eee..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/SelectorParserTest.java +++ /dev/null @@ -1,140 +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 junit.framework.TestCase; - -import org.apache.qpid.filter.SelectorParsingException; -import org.apache.qpid.filter.selector.ParseException; -import org.apache.qpid.server.filter.JMSSelectorFilter; - -public class SelectorParserTest extends TestCase -{ - public void testSelectorWithHyphen() - { - testPass("Cost = 2 AND \"property-with-hyphen\" = 'wibble'"); - } - - public void testLike() - { - testFail("Cost LIKE 2"); - testPass("Cost LIKE 'Hello'"); - } - - public void testStringQuoted() - { - testPass("string = 'Test'"); - } - - public void testProperty() - { - testPass("prop1 = prop2"); - } - - public void testPropertyNames() - { - testPass("$min= TRUE AND _max= FALSE AND Prop_2 = true AND prop$3 = false"); - } - - public void testProtected() - { - testFail("NULL = 0 "); - testFail("TRUE = 0 "); - testFail("FALSE = 0 "); - testFail("NOT = 0 "); - testFail("AND = 0 "); - testFail("OR = 0 "); - testFail("BETWEEN = 0 "); - testFail("LIKE = 0 "); - testFail("IN = 0 "); - testFail("IS = 0 "); - testFail("ESCAPE = 0 "); - } - - - public void testBoolean() - { - testPass("min= TRUE AND max= FALSE "); - testPass("min= true AND max= false"); - } - - public void testDouble() - { - testPass("positive=31E2 AND negative=-31.4E3"); - testPass("min=" + Double.MIN_VALUE + " AND max=" + Double.MAX_VALUE); - } - - public void testLong() - { - testPass("minLong=" + Long.MIN_VALUE + "L AND maxLong=" + Long.MAX_VALUE + "L"); - } - - public void testInt() - { - testPass("minInt=" + Integer.MIN_VALUE + " AND maxInt=" + Integer.MAX_VALUE); - } - - public void testSigned() - { - testPass("negative=-42 AND positive=+42"); - } - - public void testOctal() - { - testPass("octal=042"); - } - - - private void testPass(String selector) - { - try - { - new JMSSelectorFilter(selector); - } - catch (ParseException e) - { - fail("Selector '" + selector + "' was not parsed :" + e.getMessage()); - } - catch (SelectorParsingException e) - { - fail("Selector '" + selector + "' was not parsed :" + e.getMessage()); - } - } - - private void testFail(String selector) - { - try - { - new JMSSelectorFilter(selector); - fail("Selector '" + selector + "' was parsed "); - } - catch (ParseException e) - { - //normal path - } - catch (SelectorParsingException e) - { - //normal path - } - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/TransactionTimeoutHelperTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/TransactionTimeoutHelperTest.java deleted file mode 100644 index 96078d766c..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/TransactionTimeoutHelperTest.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; - -import static java.util.concurrent.TimeUnit.SECONDS; -import static org.apache.qpid.server.logging.messages.ChannelMessages.IDLE_TXN_LOG_HIERARCHY; -import static org.apache.qpid.server.logging.messages.ChannelMessages.OPEN_TXN_LOG_HIERARCHY; -import static org.mockito.Matchers.argThat; -import static org.mockito.Matchers.same; -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 org.apache.qpid.server.TransactionTimeoutHelper.CloseAction; -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.actors.CurrentActor; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.test.utils.QpidTestCase; -import org.hamcrest.Description; -import org.mockito.ArgumentMatcher; - -public class TransactionTimeoutHelperTest extends QpidTestCase -{ - private final LogActor _logActor = mock(LogActor.class); - private final LogSubject _logSubject = mock(LogSubject.class); - private final ServerTransaction _transaction = mock(ServerTransaction.class); - private final CloseAction _closeAction = mock(CloseAction.class); - private TransactionTimeoutHelper _transactionTimeoutHelper; - private long _now; - - public void testNotTransactional() throws Exception - { - when(_transaction.isTransactional()).thenReturn(false); - - _transactionTimeoutHelper.checkIdleOrOpenTimes(_transaction, 5, 10, 5, 10); - - verifyZeroInteractions(_logActor, _closeAction); - } - - public void testOpenTransactionProducesWarningOnly() throws Exception - { - final long sixtyOneSecondsAgo = _now - SECONDS.toMillis(61); - - configureMockTransaction(sixtyOneSecondsAgo, sixtyOneSecondsAgo); - - _transactionTimeoutHelper.checkIdleOrOpenTimes(_transaction, SECONDS.toMillis(30), 0, 0, 0); - - verify(_logActor).message(same(_logSubject), isLogMessage(OPEN_TXN_LOG_HIERARCHY, "CHN-1007 : Open Transaction : 61,\\d{3} ms")); - verifyZeroInteractions(_closeAction); - } - - public void testOpenTransactionProducesTimeoutActionOnly() throws Exception - { - final long sixtyOneSecondsAgo = _now - SECONDS.toMillis(61); - - configureMockTransaction(sixtyOneSecondsAgo, sixtyOneSecondsAgo); - - _transactionTimeoutHelper.checkIdleOrOpenTimes(_transaction, 0, SECONDS.toMillis(30), 0, 0); - - verify(_closeAction).doTimeoutAction("Open transaction timed out"); - verifyZeroInteractions(_logActor); - } - - public void testOpenTransactionProducesWarningAndTimeoutAction() throws Exception - { - final long sixtyOneSecondsAgo = _now - SECONDS.toMillis(61); - - configureMockTransaction(sixtyOneSecondsAgo, sixtyOneSecondsAgo); - - _transactionTimeoutHelper.checkIdleOrOpenTimes(_transaction, SECONDS.toMillis(15), SECONDS.toMillis(30), 0, 0); - - verify(_logActor).message(same(_logSubject), isLogMessage(OPEN_TXN_LOG_HIERARCHY, "CHN-1007 : Open Transaction : 61,\\d{3} ms")); - verify(_closeAction).doTimeoutAction("Open transaction timed out"); - } - - public void testIdleTransactionProducesWarningOnly() throws Exception - { - final long sixtyOneSecondsAgo = _now - SECONDS.toMillis(61); - final long thrityOneSecondsAgo = _now - SECONDS.toMillis(31); - - configureMockTransaction(sixtyOneSecondsAgo, thrityOneSecondsAgo); - - _transactionTimeoutHelper.checkIdleOrOpenTimes(_transaction, 0, 0, SECONDS.toMillis(30), 0); - - verify(_logActor).message(same(_logSubject), isLogMessage(IDLE_TXN_LOG_HIERARCHY, "CHN-1008 : Idle Transaction : 31,\\d{3} ms")); - verifyZeroInteractions(_closeAction); - } - - public void testIdleTransactionProducesTimeoutActionOnly() throws Exception - { - final long sixtyOneSecondsAgo = _now - SECONDS.toMillis(61); - final long thrityOneSecondsAgo = _now - SECONDS.toMillis(31); - - configureMockTransaction(sixtyOneSecondsAgo, thrityOneSecondsAgo); - - _transactionTimeoutHelper.checkIdleOrOpenTimes(_transaction, 0, 0, 0, SECONDS.toMillis(30)); - - verify(_closeAction).doTimeoutAction("Idle transaction timed out"); - verifyZeroInteractions(_logActor); - } - - public void testIdleTransactionProducesWarningAndTimeoutAction() throws Exception - { - final long sixtyOneSecondsAgo = _now - SECONDS.toMillis(61); - final long thrityOneSecondsAgo = _now - SECONDS.toMillis(31); - - configureMockTransaction(sixtyOneSecondsAgo, thrityOneSecondsAgo); - - _transactionTimeoutHelper.checkIdleOrOpenTimes(_transaction, 0, 0, SECONDS.toMillis(15), SECONDS.toMillis(30)); - - verify(_logActor).message(same(_logSubject), isLogMessage(IDLE_TXN_LOG_HIERARCHY, "CHN-1008 : Idle Transaction : 31,\\d{3} ms")); - verify(_closeAction).doTimeoutAction("Idle transaction timed out"); - } - - public void testIdleAndOpenWarnings() throws Exception - { - final long sixtyOneSecondsAgo = _now - SECONDS.toMillis(61); - final long thirtyOneSecondsAgo = _now - SECONDS.toMillis(31); - - configureMockTransaction(sixtyOneSecondsAgo, thirtyOneSecondsAgo); - - _transactionTimeoutHelper.checkIdleOrOpenTimes(_transaction, SECONDS.toMillis(60), 0, SECONDS.toMillis(30), 0); - - verify(_logActor).message(same(_logSubject), isLogMessage(IDLE_TXN_LOG_HIERARCHY, "CHN-1008 : Idle Transaction : 31,\\d{3} ms")); - verify(_logActor).message(same(_logSubject), isLogMessage(OPEN_TXN_LOG_HIERARCHY, "CHN-1007 : Open Transaction : 61,\\d{3} ms")); - verifyZeroInteractions(_closeAction); - } - - @Override - protected void setUp() throws Exception - { - super.setUp(); - - CurrentActor.set(_logActor); - - _transactionTimeoutHelper = new TransactionTimeoutHelper(_logSubject, _closeAction); - _now = System.currentTimeMillis(); - } - - @Override - protected void tearDown() throws Exception - { - try - { - super.tearDown(); - } - finally - { - CurrentActor.remove(); - } - } - - private void configureMockTransaction(final long startTime, final long updateTime) - { - when(_transaction.isTransactional()).thenReturn(true); - when(_transaction.getTransactionStartTime()).thenReturn(startTime); - when(_transaction.getTransactionUpdateTime()).thenReturn(updateTime); - } - - private LogMessage isLogMessage(String expectedlogHierarchy, String expectedText) - { - return argThat(new IsLogMessage(expectedlogHierarchy, expectedText)); - } - - class IsLogMessage extends ArgumentMatcher<LogMessage> - { - private final String _expectedLogHierarchy; - private final String _expectedLogMessageMatches; - private String _hierarchyMatchesFailure; - private String _logMessageMatchesFailure; - - public IsLogMessage(String expectedlogHierarchy, String expectedLogMessageMatches) - { - _expectedLogHierarchy = expectedlogHierarchy; - _expectedLogMessageMatches = expectedLogMessageMatches; - } - - public boolean matches(Object arg) - { - LogMessage logMessage = (LogMessage)arg; - - boolean hierarchyMatches = logMessage.getLogHierarchy().equals(_expectedLogHierarchy); - boolean logMessageMatches = logMessage.toString().matches(_expectedLogMessageMatches); - - if (!hierarchyMatches) - { - _hierarchyMatchesFailure = "LogHierarchy does not match. Expected " + _expectedLogHierarchy + " actual " + logMessage.getLogHierarchy(); - } - - if (!logMessageMatches) - { - _logMessageMatchesFailure = "LogMessage does not match. Expected " + _expectedLogMessageMatches + " actual " + logMessage.toString(); - } - - return hierarchyMatches && logMessageMatches; - } - - @Override - public void describeTo(Description description) - { - if (_hierarchyMatchesFailure != null) - { - description.appendText(_hierarchyMatchesFailure); - } - if (_logMessageMatchesFailure != null) - { - description.appendText(_logMessageMatchesFailure); - } - } - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/BrokerConfigurationStoreCreatorTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/BrokerConfigurationStoreCreatorTest.java deleted file mode 100644 index a7772ffd10..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/BrokerConfigurationStoreCreatorTest.java +++ /dev/null @@ -1,165 +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.configuration; - -import java.io.File; -import java.io.StringWriter; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -import org.apache.qpid.server.BrokerOptions; -import org.apache.qpid.server.configuration.store.JsonConfigurationEntryStore; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.Model; -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.test.utils.TestFileUtils; -import org.apache.qpid.util.FileUtils; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; - -public class BrokerConfigurationStoreCreatorTest extends QpidTestCase -{ - private File _userStoreLocation; - private BrokerConfigurationStoreCreator _storeCreator; - - public void setUp() throws Exception - { - super.setUp(); - - // check whether QPID_HOME JVM system property is set - if (QPID_HOME == null) - { - // set the properties in order to resolve the defaults store settings - setTestSystemProperty("QPID_HOME", TMP_FOLDER); - setTestSystemProperty("QPID_WORK", TMP_FOLDER + File.separator + "work"); - } - _storeCreator = new BrokerConfigurationStoreCreator(); - _userStoreLocation = new File(TMP_FOLDER, "_store_" + System.currentTimeMillis() + "_" + getTestName()); - } - - public void tearDown() throws Exception - { - try - { - super.tearDown(); - } - finally - { - if (_userStoreLocation != null) - { - FileUtils.delete(_userStoreLocation, true); - } - } - } - - public void testCreateJsonStore() - { - ConfigurationEntryStore store = _storeCreator.createStore(_userStoreLocation.getAbsolutePath(), "json", BrokerOptions.DEFAULT_INITIAL_CONFIG_LOCATION, false, new BrokerOptions().getConfigProperties()); - assertNotNull("Store was not created", store); - assertTrue("File should exists", _userStoreLocation.exists()); - assertTrue("File size should be greater than 0", _userStoreLocation.length() > 0); - JsonConfigurationEntryStore jsonStore = new JsonConfigurationEntryStore(_userStoreLocation.getAbsolutePath(), null, false, Collections.<String,String>emptyMap()); - Set<UUID> childrenIds = jsonStore.getRootEntry().getChildrenIds(); - assertFalse("Unexpected children: " + childrenIds, childrenIds.isEmpty()); - } - - public void testCreateJsonStoreFromInitialStore() throws Exception - { - createJsonStoreFromInitialStoreTestImpl(false); - } - - public void testOverwriteExistingJsonStoreWithInitialConfig() throws Exception - { - createJsonStoreFromInitialStoreTestImpl(true); - } - - public void createJsonStoreFromInitialStoreTestImpl(boolean overwrite) throws Exception - { - ObjectMapper objectMapper = new ObjectMapper(); - objectMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - - String defaultBrokerName = "Broker"; - String testBrokerName = getTestName(); - - Map<String, Object> brokerObjectMap = new HashMap<String, Object>(); - UUID testBrokerId = UUID.randomUUID(); - brokerObjectMap.put(Broker.ID, testBrokerId); - brokerObjectMap.put(Broker.NAME, testBrokerName); - brokerObjectMap.put(Broker.MODEL_VERSION, Model.MODEL_VERSION); - brokerObjectMap.put(Broker.STORE_VERSION, 1); - - StringWriter sw = new StringWriter(); - objectMapper.writeValue(sw, brokerObjectMap); - - String brokerJson = sw.toString(); - - File _initialStoreFile = TestFileUtils.createTempFile(this, ".json", brokerJson); - - ConfigurationEntryStore store = _storeCreator.createStore(_userStoreLocation.getAbsolutePath(), "json", _initialStoreFile.getAbsolutePath(), false, Collections.<String,String>emptyMap()); - assertNotNull("Store was not created", store); - assertTrue("File should exists", _userStoreLocation.exists()); - assertTrue("File size should be greater than 0", _userStoreLocation.length() > 0); - JsonConfigurationEntryStore jsonStore = new JsonConfigurationEntryStore(_userStoreLocation.getAbsolutePath(), null, false, Collections.<String,String>emptyMap()); - ConfigurationEntry entry = jsonStore.getRootEntry(); - assertEquals("Unexpected root id", testBrokerId, entry.getId()); - Map<String, Object> attributes = entry.getAttributes(); - assertNotNull("Unexpected attributes: " + attributes, attributes); - assertEquals("Unexpected attributes size: " + attributes.size(), 3, attributes.size()); - assertEquals("Unexpected attribute name: " + attributes.get("name"), testBrokerName, attributes.get(Broker.NAME)); - Set<UUID> childrenIds = entry.getChildrenIds(); - assertTrue("Unexpected children: " + childrenIds, childrenIds.isEmpty()); - - if(overwrite) - { - ConfigurationEntryStore overwrittenStore = _storeCreator.createStore(_userStoreLocation.getAbsolutePath(), "json", BrokerOptions.DEFAULT_INITIAL_CONFIG_LOCATION, true, new BrokerOptions().getConfigProperties()); - assertNotNull("Store was not created", overwrittenStore); - assertTrue("File should exists", _userStoreLocation.exists()); - assertTrue("File size should be greater than 0", _userStoreLocation.length() > 0); - - //check the contents reflect the test store content having been overwritten with the default store - JsonConfigurationEntryStore reopenedOverwrittenStore = new JsonConfigurationEntryStore(_userStoreLocation.getAbsolutePath(), null, false, Collections.<String,String>emptyMap()); - entry = reopenedOverwrittenStore.getRootEntry(); - assertFalse("Root id did not change, store content was not overwritten", testBrokerId.equals(entry.getId())); - attributes = entry.getAttributes(); - assertNotNull("No attributes found", attributes); - assertFalse("Test name should not equal default broker name", testBrokerName.equals(defaultBrokerName)); - assertEquals("Unexpected broker name value" , defaultBrokerName, attributes.get(Broker.NAME)); - childrenIds = entry.getChildrenIds(); - assertFalse("Expected children were not found" + childrenIds, childrenIds.isEmpty()); - } - } - - public void testCreateStoreWithUnknownType() - { - try - { - _storeCreator.createStore(_userStoreLocation.getAbsolutePath(), "other", null, false, Collections.<String,String>emptyMap()); - fail("Store is not yet supported"); - } - catch(IllegalConfigurationException e) - { - // pass - } - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/BrokerPropertiesTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/BrokerPropertiesTest.java deleted file mode 100644 index 5e9e19ffaf..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/BrokerPropertiesTest.java +++ /dev/null @@ -1,51 +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.configuration; - -import java.util.Locale; - -import org.apache.qpid.test.utils.QpidTestCase; - -public class BrokerPropertiesTest extends QpidTestCase -{ - public void testGetLocaleDefault() - { - Locale locale = BrokerProperties.getLocale(); - assertEquals("Unexpected locale", Locale.US, locale); - } - - public void testGetLocaleSetWithJVMProperty() - { - setTestSystemProperty(BrokerProperties.PROPERTY_LOCALE, "en_GB"); - Locale locale = BrokerProperties.getLocale(); - assertEquals("Unexpected locale", Locale.UK, locale); - } - - public void testGetLocaleSetWithJVMPropertyInUnexpectedFormat() - { - setTestSystemProperty(BrokerProperties.PROPERTY_LOCALE, "penguins_ANTARCTIC_Moubray_Bay"); - Locale locale = BrokerProperties.getLocale(); - assertEquals("Unexpected locale language", "penguins", locale.getLanguage()); - assertEquals("Unexpected locale country", "ANTARCTIC", locale.getCountry()); - assertEquals("Unexpected locale country", "Moubray_Bay", locale.getVariant()); - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/QueueConfigurationTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/QueueConfigurationTest.java deleted file mode 100644 index c10b3410a5..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/QueueConfigurationTest.java +++ /dev/null @@ -1,291 +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.configuration; - -import static org.mockito.Mockito.when; - -import java.util.Collections; -import junit.framework.TestCase; -import org.apache.commons.configuration.CompositeConfiguration; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.configuration.PropertiesConfiguration; - -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.util.BrokerTestHelper; - -public class QueueConfigurationTest extends TestCase -{ - private VirtualHostConfiguration _emptyConf; - private PropertiesConfiguration _env; - private VirtualHostConfiguration _fullHostConf; - private Broker _broker; - - @Override - public void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - _broker = BrokerTestHelper.createBrokerMock(); - _env = new PropertiesConfiguration(); - _emptyConf = new VirtualHostConfiguration("test", _env, _broker); - - PropertiesConfiguration fullEnv = new PropertiesConfiguration(); - fullEnv.setProperty("queues.maximumMessageAge", 1); - fullEnv.setProperty("queues.maximumQueueDepth", 1); - fullEnv.setProperty("queues.maximumMessageSize", 1); - fullEnv.setProperty("queues.maximumMessageCount", 1); - fullEnv.setProperty("queues.minimumAlertRepeatGap", 1); - fullEnv.setProperty("queues.deadLetterQueues", true); - fullEnv.setProperty("queues.maximumDeliveryCount", 5); - - _fullHostConf = new VirtualHostConfiguration("test", fullEnv, _broker); - - } - - @Override - public void tearDown() throws Exception - { - BrokerTestHelper.tearDown(); - super.tearDown(); - } - - public void testMaxDeliveryCount() throws Exception - { - // broker MAXIMUM_DELIVERY_ATTEMPTS attribute is not set - when(_broker.getAttribute(Broker.QUEUE_MAXIMUM_DELIVERY_ATTEMPTS)).thenReturn(null); - - // Check default value - QueueConfiguration qConf = new QueueConfiguration("test", _emptyConf); - assertEquals("Unexpected default server configuration for max delivery count ", 0, qConf.getMaxDeliveryCount()); - - // set broker MAXIMUM_DELIVERY_ATTEMPTS attribute to 2 - when(_broker.getAttribute(Broker.QUEUE_MAXIMUM_DELIVERY_ATTEMPTS)).thenReturn(2); - - // Check that queue inherits the MAXIMUM_DELIVERY_ATTEMPTS value from broker - qConf = new QueueConfiguration("test", _emptyConf); - assertEquals("Unexpected default server configuration for max delivery count ", 2, qConf.getMaxDeliveryCount()); - - // Check explicit value - VirtualHostConfiguration vhostConfig = overrideConfiguration("maximumDeliveryCount", 7); - qConf = new QueueConfiguration("test", vhostConfig); - assertEquals("Unexpected host configuration for max delivery count", 7, qConf.getMaxDeliveryCount()); - - // Check inherited value - qConf = new QueueConfiguration("test", _fullHostConf); - assertEquals("Unexpected queue configuration for max delivery count", 5, qConf.getMaxDeliveryCount()); - } - - /** - * Tests that the default setting for DLQ configuration is disabled, and verifies that it can be overridden - * at a broker or virtualhost level. - * @throws Exception - */ - public void testIsDeadLetterQueueEnabled() throws Exception - { - // enable dead letter queues broker wide - when(_broker.getAttribute(Broker.QUEUE_DEAD_LETTER_QUEUE_ENABLED)).thenReturn(true); - - // Check that queue inherits the broker setting - QueueConfiguration qConf = new QueueConfiguration("test", _emptyConf); - assertTrue("Unexpected queue configuration for dead letter enabled attribute", qConf.isDeadLetterQueueEnabled()); - - // broker DEAD_LETTER_QUEUE_ENABLED is not set - when(_broker.getAttribute(Broker.QUEUE_DEAD_LETTER_QUEUE_ENABLED)).thenReturn(null); - - // Check that queue dead letter queue is not enabled - qConf = new QueueConfiguration("test", _emptyConf); - assertFalse("Unexpected queue configuration for dead letter enabled attribute", qConf.isDeadLetterQueueEnabled()); - - // Check explicit value - VirtualHostConfiguration vhostConfig = overrideConfiguration("deadLetterQueues", true); - qConf = new QueueConfiguration("test", vhostConfig); - assertTrue("Unexpected queue configuration for dead letter enabled attribute", qConf.isDeadLetterQueueEnabled()); - - // Check inherited value - qConf = new QueueConfiguration("test", _fullHostConf); - assertTrue("Unexpected queue configuration for dead letter enabled attribute", qConf.isDeadLetterQueueEnabled()); - } - - public void testGetMaximumMessageAge() throws ConfigurationException - { - // Check default value - QueueConfiguration qConf = new QueueConfiguration("test", _emptyConf); - assertEquals(0, qConf.getMaximumMessageAge()); - - // Check explicit value - VirtualHostConfiguration vhostConfig = overrideConfiguration("maximumMessageAge", 2); - - qConf = new QueueConfiguration("test", vhostConfig); - assertEquals(2, qConf.getMaximumMessageAge()); - - // Check inherited value - qConf = new QueueConfiguration("test", _fullHostConf); - assertEquals(1, qConf.getMaximumMessageAge()); - } - - public void testGetMaximumQueueDepth() throws ConfigurationException - { - // Check default value - QueueConfiguration qConf = new QueueConfiguration("test", _emptyConf); - assertEquals(0, qConf.getMaximumQueueDepth()); - - // Check explicit value - VirtualHostConfiguration vhostConfig = overrideConfiguration("maximumQueueDepth", 2); - qConf = new QueueConfiguration("test", vhostConfig); - assertEquals(2, qConf.getMaximumQueueDepth()); - - // Check inherited value - qConf = new QueueConfiguration("test", _fullHostConf); - assertEquals(1, qConf.getMaximumQueueDepth()); - } - - public void testGetMaximumMessageSize() throws ConfigurationException - { - // Check default value - QueueConfiguration qConf = new QueueConfiguration("test", _emptyConf); - assertEquals(0, qConf.getMaximumMessageSize()); - - // Check explicit value - VirtualHostConfiguration vhostConfig = overrideConfiguration("maximumMessageSize", 2); - qConf = new QueueConfiguration("test", vhostConfig); - assertEquals(2, qConf.getMaximumMessageSize()); - - // Check inherited value - qConf = new QueueConfiguration("test", _fullHostConf); - assertEquals(1, qConf.getMaximumMessageSize()); - } - - public void testGetMaximumMessageCount() throws ConfigurationException - { - // Check default value - QueueConfiguration qConf = new QueueConfiguration("test", _emptyConf); - assertEquals(0, qConf.getMaximumMessageCount()); - - // Check explicit value - VirtualHostConfiguration vhostConfig = overrideConfiguration("maximumMessageCount", 2); - qConf = new QueueConfiguration("test", vhostConfig); - assertEquals(2, qConf.getMaximumMessageCount()); - - // Check inherited value - qConf = new QueueConfiguration("test", _fullHostConf); - assertEquals(1, qConf.getMaximumMessageCount()); - } - - public void testGetMinimumAlertRepeatGap() throws Exception - { - // set broker attribute ALERT_REPEAT_GAP to 10 - when(_broker.getAttribute(Broker.QUEUE_ALERT_REPEAT_GAP)).thenReturn(10); - - // check that broker level setting is available on queue configuration - QueueConfiguration qConf = new QueueConfiguration("test", _emptyConf); - assertEquals(10, qConf.getMinimumAlertRepeatGap()); - - // remove configuration for ALERT_REPEAT_GAP on broker level - when(_broker.getAttribute(Broker.QUEUE_ALERT_REPEAT_GAP)).thenReturn(null); - - // Check default value - qConf = new QueueConfiguration("test", _emptyConf); - assertEquals(0, 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()); - } - - public void testSortQueueConfiguration() throws ConfigurationException - { - //Check default value - QueueConfiguration qConf = new QueueConfiguration("test", _emptyConf); - assertNull(qConf.getQueueSortKey()); - - // Check explicit value - final VirtualHostConfiguration vhostConfig = overrideConfiguration("sortKey", "test-sort-key"); - qConf = new QueueConfiguration("test", vhostConfig); - 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()); - } - - - public void testQueueSingleArgument() throws ConfigurationException - { - //Check default value - QueueConfiguration qConf = new QueueConfiguration("test", _emptyConf); - assertTrue(qConf.getArguments().isEmpty()); - - // Check explicit value - final VirtualHostConfiguration vhostConfig = overrideConfiguration("argument", "qpid.group_header_key=mykey"); - qConf = new QueueConfiguration("test", vhostConfig); - assertEquals(Collections.singletonMap("qpid.group_header_key","mykey"), qConf.getArguments()); - } - - - public void testQueueMultipleArguments() throws ConfigurationException - { - //Check default value - QueueConfiguration qConf = new QueueConfiguration("test", _emptyConf); - assertTrue(qConf.getArguments().isEmpty()); - - - PropertiesConfiguration queueConfig = new PropertiesConfiguration(); - queueConfig.addProperty("queues.queue.test.argument", "qpid.group_header_key=mykey"); - queueConfig.addProperty("queues.queue.test.argument", "qpid.shared_msg_group=1"); - - CompositeConfiguration config = new CompositeConfiguration(); - config.addConfiguration(_fullHostConf.getConfig()); - config.addConfiguration(queueConfig); - - final VirtualHostConfiguration vhostConfig = new VirtualHostConfiguration("test", config, _broker);; - qConf = new QueueConfiguration("test", vhostConfig); - assertEquals(2, qConf.getArguments().size()); - assertEquals("mykey", qConf.getArguments().get("qpid.group_header_key")); - assertEquals("1", qConf.getArguments().get("qpid.shared_msg_group")); - } - - - private VirtualHostConfiguration overrideConfiguration(String property, Object value) - throws ConfigurationException - { - PropertiesConfiguration queueConfig = new PropertiesConfiguration(); - queueConfig.setProperty("queues.queue.test." + property, value); - - CompositeConfiguration config = new CompositeConfiguration(); - config.addConfiguration(_fullHostConf.getConfig()); - config.addConfiguration(queueConfig); - - return new VirtualHostConfiguration("test", config, _broker); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/VirtualHostConfigurationTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/VirtualHostConfigurationTest.java deleted file mode 100644 index dc9ddf7b32..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/VirtualHostConfigurationTest.java +++ /dev/null @@ -1,408 +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.configuration; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.apache.commons.configuration.Configuration; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.configuration.XMLConfiguration; - -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.queue.AMQPriorityQueue; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.store.TestableMemoryMessageStore; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.virtualhost.VirtualHostRegistry; -import org.apache.qpid.test.utils.QpidTestCase; - -public class VirtualHostConfigurationTest extends QpidTestCase -{ - private VirtualHostRegistry _virtualHostRegistry; - private XMLConfiguration _configXml; - private Broker _broker; - - @Override - public void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - _configXml = new XMLConfiguration(); - _configXml.addProperty("virtualhosts.virtualhost(-1).name", getName()); - _configXml.addProperty("virtualhosts.virtualhost(-1)."+getName()+".store.class", TestableMemoryMessageStore.class.getName()); - _virtualHostRegistry = new VirtualHostRegistry(); - _broker = mock(Broker.class); - when(_broker.getAttribute(Broker.VIRTUALHOST_HOUSEKEEPING_CHECK_PERIOD)).thenReturn(30000l); - } - - @Override - public void tearDown() throws Exception - { - try - { - if (_virtualHostRegistry != null) - { - _virtualHostRegistry.close(); - } - } - finally - { - BrokerTestHelper.tearDown(); - super.tearDown(); - } - } - - private XMLConfiguration getConfigXml() - { - return _configXml; - } - - private VirtualHost createVirtualHost(String hostName) throws Exception - { - Configuration config = getConfigXml().subset("virtualhosts.virtualhost." + XmlConfigurationUtilities.escapeTagName(hostName)); - VirtualHostConfiguration virtualHostConfiguration = new VirtualHostConfiguration(hostName, config, _broker); - return BrokerTestHelper.createVirtualHost(virtualHostConfiguration, _virtualHostRegistry); - } - - public void testQueuePriority() throws Exception - { - // Set up queue with 5 priorities - getConfigXml().addProperty("virtualhosts.virtualhost.testQueuePriority.queues(-1).queue(-1).name(-1)", - "atest"); - getConfigXml().addProperty("virtualhosts.virtualhost.testQueuePriority.queues.queue.atest(-1).exchange", - "amq.direct"); - getConfigXml().addProperty("virtualhosts.virtualhost.testQueuePriority.queues.queue.atest.priorities", - "5"); - - // Set up queue with JMS style priorities - getConfigXml().addProperty("virtualhosts.virtualhost.testQueuePriority.queues(-1).queue(-1).name(-1)", - "ptest"); - getConfigXml().addProperty("virtualhosts.virtualhost.testQueuePriority.queues.queue.ptest(-1).exchange", - "amq.direct"); - getConfigXml().addProperty("virtualhosts.virtualhost.testQueuePriority.queues.queue.ptest.priority", - "true"); - - // Set up queue with no priorities - getConfigXml().addProperty("virtualhosts.virtualhost.testQueuePriority.queues(-1).queue(-1).name(-1)", - "ntest"); - getConfigXml().addProperty("virtualhosts.virtualhost.testQueuePriority.queues.queue.ntest(-1).exchange", - "amq.direct"); - getConfigXml().addProperty("virtualhosts.virtualhost.testQueuePriority.queues.queue.ntest.priority", - "false"); - - VirtualHost vhost = createVirtualHost(getName()); - - // Check that atest was a priority queue with 5 priorities - AMQQueue atest = vhost.getQueue("atest"); - assertTrue(atest instanceof AMQPriorityQueue); - assertEquals(5, ((AMQPriorityQueue) atest).getPriorities()); - - // Check that ptest was a priority queue with 10 priorities - AMQQueue ptest = vhost.getQueue("ptest"); - assertTrue(ptest instanceof AMQPriorityQueue); - assertEquals(10, ((AMQPriorityQueue) ptest).getPriorities()); - - // Check that ntest wasn't a priority queue - AMQQueue ntest = vhost.getQueue("ntest"); - assertFalse(ntest instanceof AMQPriorityQueue); - } - - public void testQueueAlerts() throws Exception - { - // Set up queue with 5 priorities - getConfigXml().addProperty("virtualhosts.virtualhost.testQueueAlerts.queues.exchange", "amq.topic"); - getConfigXml().addProperty("virtualhosts.virtualhost.testQueueAlerts.queues.maximumQueueDepth", "1"); - getConfigXml().addProperty("virtualhosts.virtualhost.testQueueAlerts.queues.maximumMessageSize", "2"); - getConfigXml().addProperty("virtualhosts.virtualhost.testQueueAlerts.queues.maximumMessageAge", "3"); - - getConfigXml().addProperty("virtualhosts.virtualhost.testQueueAlerts.queues(-1).queue(1).name(1)", "atest"); - getConfigXml().addProperty("virtualhosts.virtualhost.testQueueAlerts.queues.queue.atest(-1).exchange", "amq.direct"); - getConfigXml().addProperty("virtualhosts.virtualhost.testQueueAlerts.queues.queue.atest(-1).maximumQueueDepth", "4"); - getConfigXml().addProperty("virtualhosts.virtualhost.testQueueAlerts.queues.queue.atest(-1).maximumMessageSize", "5"); - getConfigXml().addProperty("virtualhosts.virtualhost.testQueueAlerts.queues.queue.atest(-1).maximumMessageAge", "6"); - - getConfigXml().addProperty("virtualhosts.virtualhost.testQueueAlerts.queues(-1).queue(-1).name(-1)", "btest"); - - VirtualHost vhost = createVirtualHost(getName()); - - // Check specifically configured values - AMQQueue aTest = vhost.getQueue("atest"); - assertEquals(4, aTest.getMaximumQueueDepth()); - assertEquals(5, aTest.getMaximumMessageSize()); - assertEquals(6, aTest.getMaximumMessageAge()); - - // Check default values - AMQQueue bTest = vhost.getQueue("btest"); - assertEquals(1, bTest.getMaximumQueueDepth()); - assertEquals(2, bTest.getMaximumMessageSize()); - assertEquals(3, bTest.getMaximumMessageAge()); - } - - public void testMaxDeliveryCount() throws Exception - { - // Set up vhosts and queues - getConfigXml().addProperty("virtualhosts.virtualhost." + getName() + ".queues.maximumDeliveryCount", 5); - getConfigXml().addProperty("virtualhosts.virtualhost." + getName() + ".queues(-1).queue(-1).name", "biggles"); - getConfigXml().addProperty("virtualhosts.virtualhost." + getName() + ".queues.queue.biggles.maximumDeliveryCount", 4); - getConfigXml().addProperty("virtualhosts.virtualhost." + getName() + ".queues(-1).queue(-1).name", "beetle"); - - VirtualHost test = createVirtualHost(getName()); - - // Enabled specifically - assertEquals("Test vhost MDC was configured as enabled", 5 ,test.getConfiguration().getMaxDeliveryCount()); - - // Enabled by test vhost default - assertEquals("beetle queue DLQ was configured as enabled", test.getConfiguration().getMaxDeliveryCount(), test.getConfiguration().getQueueConfiguration("beetle").getMaxDeliveryCount()); - - // Disabled specifically - assertEquals("Biggles queue DLQ was configured as disabled", 4, test.getConfiguration().getQueueConfiguration("biggles").getMaxDeliveryCount()); - } - - /** - * Tests the full set of configuration options for enabling DLQs in the broker configuration. - */ - public void testIsDeadLetterQueueEnabled() throws Exception - { - // Set up vhosts and queues - getConfigXml().addProperty("virtualhosts.virtualhost." + getName() + ".queues.deadLetterQueues", "true"); - getConfigXml().addProperty("virtualhosts.virtualhost." + getName() + ".queues(-1).queue(-1).name", "biggles"); - getConfigXml().addProperty("virtualhosts.virtualhost." + getName() + ".queues.queue.biggles.deadLetterQueues", "false"); - getConfigXml().addProperty("virtualhosts.virtualhost." + getName() + ".queues(-1).queue(-1).name", "beetle"); - - - getConfigXml().addProperty("virtualhosts.virtualhost.name", getName() + "Extra"); - 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.class", TestableMemoryMessageStore.class.getName()); - - VirtualHost test = createVirtualHost(getName()); - VirtualHost extra = createVirtualHost(getName() + "Extra"); - - // Enabled specifically - assertTrue("Test vhost DLQ was configured as enabled", test.getConfiguration().isDeadLetterQueueEnabled()); - assertTrue("r2d2 queue DLQ was configured as enabled", extra.getConfiguration().getQueueConfiguration("r2d2").isDeadLetterQueueEnabled()); - - // Enabled by test vhost default - assertTrue("beetle queue DLQ was configured as enabled", test.getConfiguration().getQueueConfiguration("beetle").isDeadLetterQueueEnabled()); - - // Disabled specifically - assertFalse("Biggles queue DLQ was configured as disabled", test.getConfiguration().getQueueConfiguration("biggles").isDeadLetterQueueEnabled()); - - // Using broker default of disabled - assertFalse("Extra vhost DLQ disabled, using broker default", extra.getConfiguration().isDeadLetterQueueEnabled()); - assertFalse("c3p0 queue DLQ was configured as disabled", extra.getConfiguration().getQueueConfiguration("c3p0").isDeadLetterQueueEnabled()); - - // Get queues - AMQQueue biggles = test.getQueue("biggles"); - AMQQueue beetle = test.getQueue("beetle"); - AMQQueue r2d2 = extra.getQueue("r2d2"); - AMQQueue c3p0 = extra.getQueue("c3p0"); - - // Disabled specifically for this queue, overriding virtualhost setting - assertNull("Biggles queue should not have alt exchange as DLQ should be configured as disabled: " + biggles.getAlternateExchange(), biggles.getAlternateExchange()); - - // Enabled for all queues on the virtualhost - assertNotNull("Beetle queue should have an alt exchange as DLQ should be enabled, using test vhost default", beetle.getAlternateExchange()); - - // Enabled specifically for this queue, overriding the default broker setting of disabled - assertNotNull("R2D2 queue should have an alt exchange as DLQ should be configured as enabled", r2d2.getAlternateExchange()); - - // Disabled by the default broker setting - assertNull("C3PO queue should not have an alt exchange as DLQ should be disabled, using broker default", c3p0.getAlternateExchange()); - } - - /** - * Test that the house keeping pool sizes is correctly processed - * - * @throws Exception - */ - public void testHouseKeepingThreadCount() throws Exception - { - int initialPoolSize = 10; - - getConfigXml().addProperty("virtualhosts.virtualhost.testHouseKeepingThreadCount.housekeeping.poolSize", - initialPoolSize); - - VirtualHost vhost = createVirtualHost(getName()); - - assertEquals("HouseKeeping PoolSize not set correctly.", - initialPoolSize, vhost.getHouseKeepingPoolSize()); - } - - /** - * Test that we can dynamically change the thread pool size - * - * @throws Exception - */ - public void testDynamicHouseKeepingPoolSizeChange() throws Exception - { - int initialPoolSize = 10; - - getConfigXml().addProperty("virtualhosts.virtualhost.testDynamicHouseKeepingPoolSizeChange.housekeeping.poolSize", - initialPoolSize); - - VirtualHost vhost = createVirtualHost(getName()); - - assertEquals("HouseKeeping PoolSize not set correctly.", - initialPoolSize, vhost.getHouseKeepingPoolSize()); - - vhost.setHouseKeepingPoolSize(1); - - assertEquals("HouseKeeping PoolSize not correctly change.", - 1, vhost.getHouseKeepingPoolSize()); - - } - - /** - * Tests that the old element security.authentication.name is rejected. This element - * was never supported properly as authentication is performed before the virtual host - * is considered. - */ - public void testSecurityAuthenticationNameRejected() throws Exception - { - getConfigXml().addProperty("virtualhosts.virtualhost.testSecurityAuthenticationNameRejected.security.authentication.name", - "testdb"); - - try - { - createVirtualHost(getName()); - fail("Exception not thrown"); - } - catch(ConfigurationException ce) - { - assertEquals("Incorrect error message", - "Validation error : security/authentication/name is no longer a supported element within the configuration xml." + - " It appears in virtual host definition : " + getName(), - ce.getMessage()); - } - } - - /* - * Tests that the old element housekeeping.expiredMessageCheckPeriod. ... (that was - * replaced by housekeeping.checkPeriod) is rejected. - */ - public void testExpiredMessageCheckPeriodRejected() throws Exception - { - getConfigXml().addProperty("virtualhosts.virtualhost.testExpiredMessageCheckPeriodRejected.housekeeping.expiredMessageCheckPeriod", - 5); - - try - { - createVirtualHost(getName()); - fail("Exception not thrown"); - } - catch (ConfigurationException ce) - { - assertEquals("Incorrect error message", - "Validation error : housekeeping/expiredMessageCheckPeriod must be replaced by housekeeping/checkPeriod." + - " It appears in virtual host definition : " + getName(), - ce.getMessage()); - } - } - - /* - * Tests that the queues with dots in the names are fully supported. The XML configuration - * had problems with handling the tags containing dots due to the design of the Apache Commons - * Configuration library. The dots need to be escaped when accessing the XML configuration. - */ - public void testDotsInQueueName() throws Exception - { - // Set up vhosts and queue - getConfigXml().addProperty("virtualhosts.virtualhost." + getName() + ".queues(-1).queue(-1).name", "dot.in.a.name"); - // Add a single property which is inside the <dot.in.a.name> queue tag - the maximum delivery count - getConfigXml().addProperty("virtualhosts.virtualhost." + getName() + ".queues.queue.dot..in..a..name.maximumDeliveryCount", 5); - - VirtualHost test = createVirtualHost(getName()); - - // Check, that the property stored within the <dot.in.a.name> tag has been properly loaded - assertEquals("queue with dots in its name has been properly loaded", 5, test.getConfiguration().getQueueConfiguration("dot.in.a.name").getMaxDeliveryCount()); - } - - /* - * Tests that the virtual hosts with dots in the names are fully supported. The XML - * configuration had problems with handling the tags containing dots due to the design - * of the Apache Commons Configuration library. The dots need to be escaped when - * accessing the XML configuration. - */ - public void testDotsInVirtualHostName() throws Exception - { - // Set up vhosts - getConfigXml().addProperty("virtualhosts.virtualhost.name", "dot.in.a.name"); - // Add a single property which is inside the <dot.in.a.name> virtual host tag - the message store - getConfigXml().addProperty("virtualhosts.virtualhost.dot..in..a..name.store.class", TestableMemoryMessageStore.class.getName()); - - VirtualHost test = createVirtualHost("dot.in.a.name"); - - // Check, that the property stored within the <dot.in.a.name> tag has been properly loaded - assertEquals("virtual host with dots in the name has been properly loaded", TestableMemoryMessageStore.class.getName(), test.getMessageStore().getClass().getName()); - } - - public void testStoreTransactionIdleTimeoutClose() throws Exception - { - VirtualHost vhost = createVirtualHost(getName()); - assertEquals("Unexpected StoreTransactionIdleTimeoutClose value", 0, vhost.getConfiguration().getTransactionTimeoutIdleClose()); - - when(_broker.getAttribute(Broker.VIRTUALHOST_STORE_TRANSACTION_IDLE_TIMEOUT_CLOSE)).thenReturn(1000l); - assertEquals("Unexpected StoreTransactionIdleTimeoutClose value", 1000l, vhost.getConfiguration().getTransactionTimeoutIdleClose()); - - vhost.getConfiguration().getConfig().setProperty("transactionTimeout.idleClose", 2000l); - assertEquals("Unexpected StoreTransactionIdleTimeoutClose value", 2000l, vhost.getConfiguration().getTransactionTimeoutIdleClose()); - } - - public void testStoreTransactionIdleTimeoutWarn() throws Exception - { - VirtualHost vhost = createVirtualHost(getName()); - assertEquals("Unexpected StoreTransactionIdleTimeoutWarn value", 0, vhost.getConfiguration().getTransactionTimeoutIdleWarn()); - - when(_broker.getAttribute(Broker.VIRTUALHOST_STORE_TRANSACTION_IDLE_TIMEOUT_WARN)).thenReturn(1000l); - assertEquals("Unexpected StoreTransactionIdleTimeoutWarn value", 1000l, vhost.getConfiguration().getTransactionTimeoutIdleWarn()); - - vhost.getConfiguration().getConfig().setProperty("transactionTimeout.idleWarn", 2000l); - assertEquals("Unexpected StoreTransactionIdleTimeoutWarn value", 2000l, vhost.getConfiguration().getTransactionTimeoutIdleWarn()); - } - - public void testStoreTransactionOpenTimeoutClose() throws Exception - { - VirtualHost vhost = createVirtualHost(getName()); - assertEquals("Unexpected StoreTransactionOpenTimeoutClose value", 0, vhost.getConfiguration().getTransactionTimeoutOpenClose()); - - when(_broker.getAttribute(Broker.VIRTUALHOST_STORE_TRANSACTION_OPEN_TIMEOUT_CLOSE)).thenReturn(1000l); - assertEquals("Unexpected StoreTransactionOpenTimeoutClose value", 1000l, vhost.getConfiguration().getTransactionTimeoutOpenClose()); - - vhost.getConfiguration().getConfig().setProperty("transactionTimeout.openClose", 2000l); - assertEquals("Unexpected StoreTransactionOpenTimeoutClose value", 2000l, vhost.getConfiguration().getTransactionTimeoutOpenClose()); - } - - public void testStoreTransactionOpenTimeoutWarn() throws Exception - { - VirtualHost vhost = createVirtualHost(getName()); - assertEquals("Unexpected StoreTransactionOpenTimeoutWarn value", 0, vhost.getConfiguration().getTransactionTimeoutOpenWarn()); - - when(_broker.getAttribute(Broker.VIRTUALHOST_STORE_TRANSACTION_OPEN_TIMEOUT_WARN)).thenReturn(1000l); - assertEquals("Unexpected StoreTransactionOpenTimeoutWarn value", 1000l, vhost.getConfiguration().getTransactionTimeoutOpenWarn()); - - vhost.getConfiguration().getConfig().setProperty("transactionTimeout.openWarn", 2000l); - assertEquals("Unexpected StoreTransactionOpenTimeoutWarn value", 2000l, vhost.getConfiguration().getTransactionTimeoutOpenWarn()); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/plugins/AbstractConfigurationTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/plugins/AbstractConfigurationTest.java deleted file mode 100644 index 674abbfeb7..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/plugins/AbstractConfigurationTest.java +++ /dev/null @@ -1,210 +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.configuration.plugins; - -import org.apache.commons.configuration.CompositeConfiguration; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.configuration.XMLConfiguration; - -import org.apache.qpid.test.utils.QpidTestCase; - -import java.util.List; - -/** - * Test that verifies that given a Configuration a ConfigurationPlugin can - * process and validate that data. - */ -public class AbstractConfigurationTest extends QpidTestCase -{ - private static final double DOUBLE = 3.14; - private static final long POSITIVE_LONG = 1000; - private static final long NEGATIVE_LONG = -1000; - private static final int LIST_SIZE = 3; - - class TestConfigPlugin extends AbstractConfiguration - { - @Override - public String[] getElementsProcessed() - { - return new String[]{"[@property]", "name", - "positiveLong", "negativeLong", - "true", "list", "double"}; - } - - @Override - public void validateConfiguration() throws ConfigurationException - { - // no validation requried - } - - public String getName() - { - return getStringValue("name"); - } - - public String getProperty() - { - return getStringValue("[@property]"); - } - - - } - - private TestConfigPlugin _plugin; - - @Override - public void setUp() throws Exception - { - // Test does not directly use the AppRegistry but the configured broker - // is required for the correct ConfigurationPlugin processing - super.setUp(); - XMLConfiguration xmlconfig = new XMLConfiguration(); - xmlconfig.addProperty("base.element[@property]", "property"); - xmlconfig.addProperty("base.element.name", "name"); - // We make these strings as that is how they will be read from the file. - xmlconfig.addProperty("base.element.positiveLong", String.valueOf(POSITIVE_LONG)); - xmlconfig.addProperty("base.element.negativeLong", String.valueOf(NEGATIVE_LONG)); - xmlconfig.addProperty("base.element.boolean", String.valueOf(true)); - xmlconfig.addProperty("base.element.double", String.valueOf(DOUBLE)); - for (int i = 0; i < LIST_SIZE; i++) - { - xmlconfig.addProperty("base.element.list", i); - } - - //Use a composite configuration as this is what our broker code uses. - CompositeConfiguration composite = new CompositeConfiguration(); - composite.addConfiguration(xmlconfig); - - _plugin = new TestConfigPlugin(); - - try - { - _plugin.setConfiguration("base.element", composite.subset("base.element")); - } - catch (ConfigurationException e) - { - e.printStackTrace(); - fail(e.toString()); - } - - } - - public void testHasConfiguration() - { - assertTrue("Plugin has no configuration ", _plugin.hasConfiguration()); - _plugin = new TestConfigPlugin(); - assertFalse("Plugins has configuration", _plugin.hasConfiguration()); - } - - public void testValuesRetreived() - { - assertEquals("Name not correct", "name", _plugin.getName()); - assertEquals("Property not correct", "property", _plugin.getProperty()); - } - - public void testContainsPositiveLong() - { - assertTrue("positiveLong is not positive", _plugin.containsPositiveLong("positiveLong")); - assertFalse("NonExistentValue was found", _plugin.containsPositiveLong("NonExistentValue")); - - try - { - _plugin.validatePositiveLong("positiveLong"); - } - catch (ConfigurationException e) - { - fail(e.getMessage()); - } - - try - { - _plugin.validatePositiveLong("negativeLong"); - fail("negativeLong should not be positive"); - } - catch (ConfigurationException e) - { - assertEquals("negativeLong should not be reported as positive", - "TestConfigPlugin: unable to configure invalid negativeLong:" + NEGATIVE_LONG, e.getMessage()); - } - - } - - public void testDouble() - { - assertEquals("Double value not returned", DOUBLE, _plugin.getDoubleValue("double")); - assertEquals("default Double value not returned", 0.0, _plugin.getDoubleValue("NonExistent")); - assertEquals("set default Double value not returned", DOUBLE, _plugin.getDoubleValue("NonExistent", DOUBLE)); - } - - public void testLong() - { - assertTrue("Long value not returned", _plugin.containsLong("positiveLong")); - assertFalse("Long value returned", _plugin.containsLong("NonExistent")); - assertEquals("Long value not returned", POSITIVE_LONG, _plugin.getLongValue("positiveLong")); - assertEquals("default Long value not returned", 0, _plugin.getLongValue("NonExistent")); - assertEquals("set default Long value not returned", NEGATIVE_LONG, _plugin.getLongValue("NonExistent", NEGATIVE_LONG)); - } - - public void testInt() - { - assertTrue("Int value not returned", _plugin.containsInt("positiveLong")); - assertFalse("Int value returned", _plugin.containsInt("NonExistent")); - assertEquals("Int value not returned", (int) POSITIVE_LONG, _plugin.getIntValue("positiveLong")); - assertEquals("default Int value not returned", 0, _plugin.getIntValue("NonExistent")); - assertEquals("set default Int value not returned", (int) NEGATIVE_LONG, _plugin.getIntValue("NonExistent", (int) NEGATIVE_LONG)); - } - - public void testString() - { - assertEquals("String value not returned", "name", _plugin.getStringValue("name")); - assertNull("Null default String value not returned", _plugin.getStringValue("NonExistent", null)); - assertNull("default String value not returned", _plugin.getStringValue("NonExistent")); - assertEquals("default String value not returned", "Default", _plugin.getStringValue("NonExistent", "Default")); - } - - public void testBoolean() - { - assertTrue("Boolean value not returned", _plugin.containsBoolean("boolean")); - assertFalse("Boolean value not returned", _plugin.containsBoolean("NonExistent")); - assertTrue("Boolean value not returned", _plugin.getBooleanValue("boolean")); - assertFalse("default String value not returned", _plugin.getBooleanValue("NonExistent")); - assertTrue("set default String value not returned", _plugin.getBooleanValue("NonExistent", true)); - } - - public void testList() - { - assertTrue("list not found in plugin", _plugin.contains("list")); - List list = _plugin.getListValue("list"); - assertNotNull("Returned list should not be null", list); - assertEquals("List should not be empty", LIST_SIZE, list.size()); - - list = _plugin.getListValue("NonExistent"); - assertNotNull("Returned list should not be null", list); - assertEquals("List is not empty", 0, list.size()); - } - - public void testContains() - { - assertTrue("list not found in plugin", _plugin.contains("list")); - assertFalse("NonExistent found in plugin", _plugin.contains("NonExistent")); - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/AuthenticationProviderRecovererTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/AuthenticationProviderRecovererTest.java deleted file mode 100644 index eed54ef5bf..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/AuthenticationProviderRecovererTest.java +++ /dev/null @@ -1,143 +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.configuration.startup; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfigurationEntryStore; -import org.apache.qpid.server.configuration.ConfiguredObjectRecoverer; -import org.apache.qpid.server.configuration.RecovererProvider; -import org.apache.qpid.server.configuration.store.StoreConfigurationChangeListener; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.PreferencesProvider; -import org.apache.qpid.server.model.adapter.AuthenticationProviderFactory; -import org.apache.qpid.server.model.adapter.FileSystemPreferencesProvider; -import org.apache.qpid.server.model.adapter.PreferencesProviderCreator; -import org.apache.qpid.server.plugin.AuthenticationManagerFactory; -import org.apache.qpid.server.plugin.QpidServiceLoader; -import org.apache.qpid.server.security.auth.manager.PlainPasswordFileAuthenticationManagerFactory; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.test.utils.TestFileUtils; - -public class AuthenticationProviderRecovererTest extends QpidTestCase -{ - private Broker _broker; - private AuthenticationProviderRecoverer _recoverer; - private ConfigurationEntryStore _configurationStore; - private PreferencesProviderCreator _preferencesProviderCreator; - - public void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - _broker = BrokerTestHelper.createBrokerMock(); - _preferencesProviderCreator = new PreferencesProviderCreator(); - QpidServiceLoader<AuthenticationManagerFactory> serviceLoader = new QpidServiceLoader<AuthenticationManagerFactory>(); - AuthenticationProviderFactory authenticationProviderFactory = new AuthenticationProviderFactory(serviceLoader, _preferencesProviderCreator); - StoreConfigurationChangeListener storeChangeListener = mock(StoreConfigurationChangeListener.class); - _recoverer = new AuthenticationProviderRecoverer(authenticationProviderFactory, storeChangeListener); - _configurationStore = mock(ConfigurationEntryStore.class); - } - - public void tearDown() throws Exception - { - try - { - BrokerTestHelper.tearDown(); - } - finally - { - super.tearDown(); - } - } - - public void testRecoverAuthenticationProviderWithPreferencesProvider() - { - File authenticationProviderFile = TestFileUtils.createTempFile(this, "test-authenticator.txt", "test_user:test_user"); - try - { - Map<String, Object> authenticationAttributes = new HashMap<String, Object>(); - authenticationAttributes.put(AuthenticationManagerFactory.ATTRIBUTE_TYPE, - PlainPasswordFileAuthenticationManagerFactory.PROVIDER_TYPE); - authenticationAttributes.put(AuthenticationProvider.NAME, "test-authenticator"); - authenticationAttributes.put(PlainPasswordFileAuthenticationManagerFactory.ATTRIBUTE_PATH, - authenticationProviderFile.getAbsolutePath()); - UUID authenticationId = UUID.randomUUID(); - - final PreferencesProviderRecoverer preferencesRecoverer = new PreferencesProviderRecoverer(_preferencesProviderCreator); - RecovererProvider recovererProvider = new RecovererProvider() - { - @Override - public ConfiguredObjectRecoverer<? extends ConfiguredObject> getRecoverer(String type) - { - return preferencesRecoverer; - } - }; - - Map<String, Object> preferencesAttributes = new HashMap<String, Object>(); - UUID preferencesId = UUID.randomUUID(); - preferencesAttributes.put(PreferencesProvider.TYPE, FileSystemPreferencesProvider.class); - preferencesAttributes.put(PreferencesProvider.NAME, "test-provider"); - File file = TestFileUtils.createTempFile(this, ".prefs.json", - "{\"test_user\":{\"pref1\": \"pref1Value\", \"pref2\": 1.0} }"); - preferencesAttributes.put(FileSystemPreferencesProvider.PATH, file.getAbsolutePath()); - ConfigurationEntry preferencesEntry = new ConfigurationEntry(preferencesId, PreferencesProvider.class.getSimpleName(), - preferencesAttributes, Collections.<UUID> emptySet(), _configurationStore); - when(_configurationStore.getEntry(preferencesId)).thenReturn(preferencesEntry); - - ConfigurationEntry authenticationProviderEntry = new ConfigurationEntry(authenticationId, - AuthenticationProvider.class.getSimpleName(), authenticationAttributes, Collections.singleton(preferencesId), - _configurationStore); - try - { - AuthenticationProvider authenticationProvider = _recoverer.create(recovererProvider, authenticationProviderEntry, - _broker); - assertNotNull("Authentication provider was not recovered", authenticationProvider); - assertEquals("Unexpected name", "test-authenticator", authenticationProvider.getName()); - assertEquals("Unexpected id", authenticationId, authenticationProvider.getId()); - PreferencesProvider preferencesProvider = authenticationProvider.getPreferencesProvider(); - assertNotNull("Preferences provider was not recovered", preferencesProvider); - assertEquals("Unexpected path", file.getAbsolutePath(), - preferencesProvider.getAttribute(FileSystemPreferencesProvider.PATH)); - } - finally - { - file.delete(); - } - } - finally - { - authenticationProviderFile.delete(); - } - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/BrokerRecovererTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/BrokerRecovererTest.java deleted file mode 100644 index e6db5af222..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/BrokerRecovererTest.java +++ /dev/null @@ -1,394 +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.configuration.startup; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.UUID; - -import junit.framework.TestCase; - -import org.apache.qpid.server.BrokerOptions; -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfiguredObjectRecoverer; -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.configuration.RecovererProvider; -import org.apache.qpid.server.logging.LogRecorder; -import org.apache.qpid.server.logging.RootMessageLogger; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.GroupProvider; -import org.apache.qpid.server.model.KeyStore; -import org.apache.qpid.server.model.Model; -import org.apache.qpid.server.model.Plugin; -import org.apache.qpid.server.model.Port; -import org.apache.qpid.server.model.TrustStore; -import org.apache.qpid.server.model.UUIDGenerator; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.model.adapter.AccessControlProviderFactory; -import org.apache.qpid.server.model.adapter.AuthenticationProviderFactory; -import org.apache.qpid.server.model.adapter.GroupProviderFactory; -import org.apache.qpid.server.model.adapter.PortFactory; -import org.apache.qpid.server.model.adapter.PreferencesProviderCreator; -import org.apache.qpid.server.configuration.store.StoreConfigurationChangeListener; -import org.apache.qpid.server.configuration.updater.TaskExecutor; -import org.apache.qpid.server.stats.StatisticsGatherer; -import org.apache.qpid.server.virtualhost.VirtualHostRegistry; - -public class BrokerRecovererTest extends TestCase -{ - private BrokerRecoverer _brokerRecoverer; - private ConfigurationEntry _brokerEntry = mock(ConfigurationEntry.class); - - private UUID _brokerId = UUID.randomUUID(); - private Map<String, Collection<ConfigurationEntry>> _brokerEntryChildren = new HashMap<String, Collection<ConfigurationEntry>>(); - private ConfigurationEntry _authenticationProviderEntry1; - private AuthenticationProvider _authenticationProvider1; - private UUID _authenticationProvider1Id = UUID.randomUUID(); - - @Override - protected void setUp() throws Exception - { - super.setUp(); - - _brokerRecoverer = new BrokerRecoverer(mock(AuthenticationProviderFactory.class), mock(GroupProviderFactory.class), mock(AccessControlProviderFactory.class), mock(PortFactory.class), - mock(PreferencesProviderCreator.class), - mock(StatisticsGatherer.class), mock(VirtualHostRegistry.class), mock(LogRecorder.class), mock(RootMessageLogger.class), mock(TaskExecutor.class), mock(BrokerOptions.class), - mock(StoreConfigurationChangeListener.class)); - when(_brokerEntry.getId()).thenReturn(_brokerId); - when(_brokerEntry.getChildren()).thenReturn(_brokerEntryChildren); - when(_brokerEntry.getAttributes()).thenReturn(Collections.<String, Object>singletonMap(Broker.MODEL_VERSION, Model.MODEL_VERSION)); - - //Add a base AuthenticationProvider for all tests - _authenticationProvider1 = mock(AuthenticationProvider.class); - when(_authenticationProvider1.getName()).thenReturn("authenticationProvider1"); - when(_authenticationProvider1.getId()).thenReturn(_authenticationProvider1Id); - _authenticationProviderEntry1 = mock(ConfigurationEntry.class); - _brokerEntryChildren.put(AuthenticationProvider.class.getSimpleName(), Arrays.asList(_authenticationProviderEntry1)); - } - - public void testCreateBrokerAttributes() - { - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(Broker.DEFAULT_VIRTUAL_HOST, "test"); - attributes.put(Broker.QUEUE_ALERT_THRESHOLD_MESSAGE_AGE, 9l); - attributes.put(Broker.QUEUE_ALERT_THRESHOLD_QUEUE_DEPTH_MESSAGES, 8l); - attributes.put(Broker.QUEUE_ALERT_THRESHOLD_QUEUE_DEPTH_BYTES, 7l); - attributes.put(Broker.QUEUE_ALERT_THRESHOLD_MESSAGE_SIZE, 6l); - attributes.put(Broker.QUEUE_ALERT_REPEAT_GAP, 5l); - attributes.put(Broker.QUEUE_FLOW_CONTROL_SIZE_BYTES, 5l); - attributes.put(Broker.QUEUE_FLOW_CONTROL_RESUME_SIZE_BYTES, 3l); - attributes.put(Broker.QUEUE_MAXIMUM_DELIVERY_ATTEMPTS, 2); - attributes.put(Broker.QUEUE_DEAD_LETTER_QUEUE_ENABLED, true); - attributes.put(Broker.VIRTUALHOST_HOUSEKEEPING_CHECK_PERIOD, 1l); - attributes.put(Broker.CONNECTION_SESSION_COUNT_LIMIT, 1000); - attributes.put(Broker.CONNECTION_HEART_BEAT_DELAY, 2000); - attributes.put(Broker.STATISTICS_REPORTING_PERIOD, 4000); - attributes.put(Broker.STATISTICS_REPORTING_RESET_ENABLED, true); - attributes.put(Broker.MODEL_VERSION, Model.MODEL_VERSION); - - Map<String, Object> entryAttributes = new HashMap<String, Object>(); - for (Map.Entry<String, Object> attribute : attributes.entrySet()) - { - String value = convertToString(attribute.getValue()); - entryAttributes.put(attribute.getKey(), value); - } - - when(_brokerEntry.getAttributes()).thenReturn(entryAttributes); - - final ConfigurationEntry virtualHostEntry = mock(ConfigurationEntry.class); - String typeName = VirtualHost.class.getSimpleName(); - when(virtualHostEntry.getType()).thenReturn(typeName); - _brokerEntryChildren.put(typeName, Arrays.asList(virtualHostEntry)); - final VirtualHost virtualHost = mock(VirtualHost.class); - when(virtualHost.getName()).thenReturn("test"); - - RecovererProvider recovererProvider = createRecoveryProvider(new ConfigurationEntry[] { virtualHostEntry, _authenticationProviderEntry1 }, - new ConfiguredObject[] { virtualHost, _authenticationProvider1 }); - Broker broker = _brokerRecoverer.create(recovererProvider, _brokerEntry); - assertNotNull(broker); - assertEquals(_brokerId, broker.getId()); - - for (Map.Entry<String, Object> attribute : attributes.entrySet()) - { - Object attributeValue = broker.getAttribute(attribute.getKey()); - assertEquals("Unexpected value of attribute '" + attribute.getKey() + "'", attribute.getValue(), attributeValue); - } - } - - public void testCreateBrokerWithVirtualHost() - { - final ConfigurationEntry virtualHostEntry = mock(ConfigurationEntry.class); - - String typeName = VirtualHost.class.getSimpleName(); - when(virtualHostEntry.getType()).thenReturn(typeName); - _brokerEntryChildren.put(typeName, Arrays.asList(virtualHostEntry)); - - final VirtualHost virtualHost = mock(VirtualHost.class); - - RecovererProvider recovererProvider = createRecoveryProvider(new ConfigurationEntry[]{virtualHostEntry, _authenticationProviderEntry1}, - new ConfiguredObject[]{virtualHost, _authenticationProvider1}); - - Broker broker = _brokerRecoverer.create(recovererProvider, _brokerEntry); - - assertNotNull(broker); - assertEquals(_brokerId, broker.getId()); - assertEquals(1, broker.getVirtualHosts().size()); - assertEquals(virtualHost, broker.getVirtualHosts().iterator().next()); - } - - public void testCreateBrokerWithPorts() - { - ConfigurationEntry portEntry = mock(ConfigurationEntry.class); - Port port = mock(Port.class); - _brokerEntryChildren.put(Port.class.getSimpleName(), Arrays.asList(portEntry)); - - RecovererProvider recovererProvider = createRecoveryProvider(new ConfigurationEntry[]{portEntry, _authenticationProviderEntry1}, - new ConfiguredObject[]{port, _authenticationProvider1}); - - Broker broker = _brokerRecoverer.create(recovererProvider, _brokerEntry); - - assertNotNull(broker); - assertEquals(_brokerId, broker.getId()); - assertEquals(Collections.singletonList(port), broker.getPorts()); - } - - public void testCreateBrokerWithOneAuthenticationProvider() - { - RecovererProvider recovererProvider = createRecoveryProvider(new ConfigurationEntry[]{_authenticationProviderEntry1}, - new ConfiguredObject[]{_authenticationProvider1}); - - Broker broker = _brokerRecoverer.create(recovererProvider, _brokerEntry); - - assertNotNull(broker); - assertEquals(_brokerId, broker.getId()); - assertEquals(Collections.singletonList(_authenticationProvider1), broker.getAuthenticationProviders()); - } - - public void testCreateBrokerWithMultipleAuthenticationProvidersAndPorts() - { - //Create a second authentication provider - AuthenticationProvider authenticationProvider2 = mock(AuthenticationProvider.class); - when(authenticationProvider2.getName()).thenReturn("authenticationProvider2"); - ConfigurationEntry authenticationProviderEntry2 = mock(ConfigurationEntry.class); - _brokerEntryChildren.put(AuthenticationProvider.class.getSimpleName(), Arrays.asList(_authenticationProviderEntry1, authenticationProviderEntry2)); - - //Add a couple ports - ConfigurationEntry portEntry1 = mock(ConfigurationEntry.class); - Port port1 = mock(Port.class); - when(port1.getId()).thenReturn(UUIDGenerator.generateRandomUUID()); - when(port1.getName()).thenReturn("port1"); - when(port1.getPort()).thenReturn(5671); - when(port1.getAttribute(Port.AUTHENTICATION_PROVIDER)).thenReturn("authenticationProvider1"); - ConfigurationEntry portEntry2 = mock(ConfigurationEntry.class); - Port port2 = mock(Port.class); - when(port2.getId()).thenReturn(UUIDGenerator.generateRandomUUID()); - when(port2.getName()).thenReturn("port2"); - when(port2.getPort()).thenReturn(5672); - when(port2.getAttribute(Port.AUTHENTICATION_PROVIDER)).thenReturn("authenticationProvider2"); - _brokerEntryChildren.put(Port.class.getSimpleName(), Arrays.asList(portEntry1, portEntry2)); - - RecovererProvider recovererProvider = createRecoveryProvider( - new ConfigurationEntry[]{portEntry1, portEntry2, authenticationProviderEntry2, _authenticationProviderEntry1}, - new ConfiguredObject[]{port1, port2, authenticationProvider2, _authenticationProvider1}); - - Broker broker = _brokerRecoverer.create(recovererProvider, _brokerEntry); - - assertNotNull(broker); - assertEquals("Unexpected number of authentication providers", 2, broker.getAuthenticationProviders().size()); - - Collection<Port> ports = broker.getPorts(); - assertEquals("Unexpected number of ports", 2, ports.size()); - assertTrue(ports.contains(port1)); - assertTrue(ports.contains(port2)); - } - - public void testCreateBrokerWithGroupProvider() - { - ConfigurationEntry groupProviderEntry = mock(ConfigurationEntry.class); - GroupProvider groupProvider = mock(GroupProvider.class); - _brokerEntryChildren.put(GroupProvider.class.getSimpleName(), Arrays.asList(groupProviderEntry)); - - RecovererProvider recovererProvider = createRecoveryProvider(new ConfigurationEntry[]{groupProviderEntry, _authenticationProviderEntry1}, - new ConfiguredObject[]{groupProvider, _authenticationProvider1}); - - Broker broker = _brokerRecoverer.create(recovererProvider, _brokerEntry); - - assertNotNull(broker); - assertEquals(_brokerId, broker.getId()); - assertEquals(Collections.singletonList(groupProvider), broker.getGroupProviders()); - } - - public void testCreateBrokerWithPlugins() - { - ConfigurationEntry pluginEntry = mock(ConfigurationEntry.class); - Plugin plugin = mock(Plugin.class); - _brokerEntryChildren.put(Plugin.class.getSimpleName(), Arrays.asList(pluginEntry)); - - RecovererProvider recovererProvider = createRecoveryProvider(new ConfigurationEntry[]{pluginEntry, _authenticationProviderEntry1}, - new ConfiguredObject[]{plugin, _authenticationProvider1}); - - Broker broker = _brokerRecoverer.create(recovererProvider, _brokerEntry); - - assertNotNull(broker); - assertEquals(_brokerId, broker.getId()); - assertEquals(Collections.singleton(plugin), new HashSet<ConfiguredObject>(broker.getChildren(Plugin.class))); - } - - public void testCreateBrokerWithKeyStores() - { - ConfigurationEntry pluginEntry = mock(ConfigurationEntry.class); - KeyStore keyStore = mock(KeyStore.class); - _brokerEntryChildren.put(KeyStore.class.getSimpleName(), Arrays.asList(pluginEntry)); - - RecovererProvider recovererProvider = createRecoveryProvider(new ConfigurationEntry[]{pluginEntry, _authenticationProviderEntry1}, - new ConfiguredObject[]{keyStore, _authenticationProvider1}); - - Broker broker = _brokerRecoverer.create(recovererProvider, _brokerEntry); - - assertNotNull(broker); - assertEquals(_brokerId, broker.getId()); - assertEquals(Collections.singleton(keyStore), new HashSet<ConfiguredObject>(broker.getChildren(KeyStore.class))); - } - - public void testCreateBrokerWithTrustStores() - { - ConfigurationEntry pluginEntry = mock(ConfigurationEntry.class); - TrustStore trustStore = mock(TrustStore.class); - _brokerEntryChildren.put(TrustStore.class.getSimpleName(), Arrays.asList(pluginEntry)); - - RecovererProvider recovererProvider = createRecoveryProvider(new ConfigurationEntry[]{pluginEntry, _authenticationProviderEntry1}, - new ConfiguredObject[]{trustStore, _authenticationProvider1}); - - Broker broker = _brokerRecoverer.create(recovererProvider, _brokerEntry); - - assertNotNull(broker); - assertEquals(_brokerId, broker.getId()); - assertEquals(Collections.singleton(trustStore), new HashSet<ConfiguredObject>(broker.getChildren(TrustStore.class))); - } - - public void testModelVersionValidationForIncompatibleMajorVersion() throws Exception - { - Map<String, Object> brokerAttributes = new HashMap<String, Object>(); - String[] incompatibleVersions = {Integer.MAX_VALUE + "." + 0, "0.0"}; - for (String incompatibleVersion : incompatibleVersions) - { - brokerAttributes.put(Broker.MODEL_VERSION, incompatibleVersion); - when(_brokerEntry.getAttributes()).thenReturn(brokerAttributes); - - try - { - _brokerRecoverer.create(null, _brokerEntry); - fail("The broker creation should fail due to unsupported model version"); - } - catch (IllegalConfigurationException e) - { - assertEquals("The model version '" + incompatibleVersion - + "' in configuration is incompatible with the broker model version '" + Model.MODEL_VERSION + "'", e.getMessage()); - } - } - } - - - public void testModelVersionValidationForIncompatibleMinorVersion() throws Exception - { - Map<String, Object> brokerAttributes = new HashMap<String, Object>(); - String incompatibleVersion = Model.MODEL_MAJOR_VERSION + "." + Integer.MAX_VALUE; - brokerAttributes.put(Broker.MODEL_VERSION, incompatibleVersion); - when(_brokerEntry.getAttributes()).thenReturn(brokerAttributes); - - try - { - _brokerRecoverer.create(null, _brokerEntry); - fail("The broker creation should fail due to unsupported model version"); - } - catch (IllegalConfigurationException e) - { - assertEquals("The model version '" + incompatibleVersion - + "' in configuration is incompatible with the broker model version '" + Model.MODEL_VERSION + "'", e.getMessage()); - } - } - - public void testIncorrectModelVersion() throws Exception - { - Map<String, Object> brokerAttributes = new HashMap<String, Object>(); - String[] versions = { Integer.MAX_VALUE + "_" + 0, "", null }; - for (String modelVersion : versions) - { - brokerAttributes.put(Broker.MODEL_VERSION, modelVersion); - when(_brokerEntry.getAttributes()).thenReturn(brokerAttributes); - - try - { - _brokerRecoverer.create(null, _brokerEntry); - fail("The broker creation should fail due to unsupported model version"); - } - catch (IllegalConfigurationException e) - { - // pass - } - } - } - - private String convertToString(Object attributeValue) - { - return String.valueOf(attributeValue); - } - - private RecovererProvider createRecoveryProvider(final ConfigurationEntry[] entries, final ConfiguredObject[] objectsToRecoverer) - { - RecovererProvider recovererProvider = new RecovererProvider() - { - @Override - public ConfiguredObjectRecoverer<? extends ConfiguredObject> getRecoverer(String type) - { - @SuppressWarnings({ "unchecked", "rawtypes" }) - final ConfiguredObjectRecoverer<? extends ConfiguredObject> recovever = new ConfiguredObjectRecoverer() - { - @Override - public ConfiguredObject create(RecovererProvider recovererProvider, ConfigurationEntry entry, ConfiguredObject... parents) - { - for (int i = 0; i < entries.length; i++) - { - ConfigurationEntry e = entries[i]; - if (entry == e) - { - return objectsToRecoverer[i]; - } - } - return null; - } - }; - - return recovever; - } - }; - return recovererProvider; - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/DefaultRecovererProviderTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/DefaultRecovererProviderTest.java deleted file mode 100644 index 9e2f2fcf32..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/DefaultRecovererProviderTest.java +++ /dev/null @@ -1,69 +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.configuration.startup; - -import static org.mockito.Mockito.mock; -import junit.framework.TestCase; - -import org.apache.qpid.server.BrokerOptions; -import org.apache.qpid.server.configuration.ConfiguredObjectRecoverer; -import org.apache.qpid.server.logging.LogRecorder; -import org.apache.qpid.server.logging.RootMessageLogger; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.GroupProvider; -import org.apache.qpid.server.model.KeyStore; -import org.apache.qpid.server.model.Plugin; -import org.apache.qpid.server.model.Port; -import org.apache.qpid.server.model.TrustStore; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.configuration.store.StoreConfigurationChangeListener; -import org.apache.qpid.server.configuration.updater.TaskExecutor; -import org.apache.qpid.server.stats.StatisticsGatherer; -import org.apache.qpid.server.virtualhost.VirtualHostRegistry; - -public class DefaultRecovererProviderTest extends TestCase -{ - public void testGetRecoverer() - { - String[] supportedTypes = {Broker.class.getSimpleName(), - VirtualHost.class.getSimpleName(), AuthenticationProvider.class.getSimpleName(), - GroupProvider.class.getSimpleName(), Plugin.class.getSimpleName(), Port.class.getSimpleName(), - KeyStore.class.getSimpleName(), TrustStore.class.getSimpleName()}; - - // mocking the required object - StatisticsGatherer statisticsGatherer = mock(StatisticsGatherer.class); - VirtualHostRegistry virtualHostRegistry = mock(VirtualHostRegistry.class); - LogRecorder logRecorder = mock(LogRecorder.class); - RootMessageLogger rootMessageLogger = mock(RootMessageLogger.class); - TaskExecutor taskExecutor = mock(TaskExecutor.class); - - DefaultRecovererProvider provider = new DefaultRecovererProvider(statisticsGatherer, virtualHostRegistry, - logRecorder, rootMessageLogger, taskExecutor, mock(BrokerOptions.class), - mock(StoreConfigurationChangeListener.class)); - for (String configuredObjectType : supportedTypes) - { - ConfiguredObjectRecoverer<?> recovever = provider.getRecoverer(configuredObjectType); - assertNotNull("Null recoverer for type: " + configuredObjectType, recovever); - } - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/GroupProviderRecovererTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/GroupProviderRecovererTest.java deleted file mode 100644 index d6f03a9758..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/GroupProviderRecovererTest.java +++ /dev/null @@ -1,101 +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.configuration.startup; -import static org.mockito.Mockito.*; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.GroupProvider; -import org.apache.qpid.server.model.adapter.GroupProviderFactory; -import org.apache.qpid.server.plugin.GroupManagerFactory; -import org.apache.qpid.server.plugin.QpidServiceLoader; -import org.apache.qpid.server.security.group.GroupManager; - -import junit.framework.TestCase; - -public class GroupProviderRecovererTest extends TestCase -{ - - private UUID _id; - private Map<String, Object> _attributes; - - private GroupManagerFactory _factory; - private QpidServiceLoader<GroupManagerFactory> _groupManagerServiceLoader; - private Broker _broker; - private ConfigurationEntry _configurationEntry; - private GroupProviderFactory _groupProviderFactory; - - @SuppressWarnings("unchecked") - protected void setUp() throws Exception - { - super.setUp(); - _id = UUID.randomUUID(); - _attributes = new HashMap<String, Object>(); - - _factory = mock(GroupManagerFactory.class); - - _groupManagerServiceLoader = mock(QpidServiceLoader.class); - when(_groupManagerServiceLoader.instancesOf(GroupManagerFactory.class)).thenReturn(Collections.singletonList(_factory )); - _groupProviderFactory = new GroupProviderFactory(_groupManagerServiceLoader); - - _broker = mock(Broker.class); - - _configurationEntry = mock(ConfigurationEntry.class); - when(_configurationEntry.getId()).thenReturn(_id); - when(_configurationEntry.getAttributes()).thenReturn(_attributes); - } - - public void testCreate() - { - GroupManager groupManager = mock(GroupManager.class); - String name = groupManager.getClass().getSimpleName(); - _attributes.put(GroupProvider.NAME, name); - when(_factory.createInstance(_attributes)).thenReturn(groupManager); - GroupProviderRecoverer groupProviderRecoverer = new GroupProviderRecoverer(_groupProviderFactory); - GroupProvider groupProvider = groupProviderRecoverer.create(null, _configurationEntry, _broker); - assertNotNull("Null group provider", groupProvider); - assertEquals("Unexpected name", name, groupProvider.getName()); - assertEquals("Unexpected ID", _id, groupProvider.getId()); - } - - public void testCreateThrowsExceptionWhenNoGroupManagerIsCreated() - { - when(_factory.createInstance(_attributes)).thenReturn(null); - - GroupProviderRecoverer groupProviderRecoverer = new GroupProviderRecoverer(_groupProviderFactory); - try - { - groupProviderRecoverer.create(null, _configurationEntry, _broker); - fail("Configuration exception should be thrown when group manager is not created"); - } - catch(IllegalConfigurationException e) - { - // pass - } - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/KeyStoreRecovererTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/KeyStoreRecovererTest.java deleted file mode 100644 index e0a736df89..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/KeyStoreRecovererTest.java +++ /dev/null @@ -1,118 +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.configuration.startup; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import javax.net.ssl.KeyManagerFactory; - -import junit.framework.TestCase; - -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.KeyStore; -import org.apache.qpid.server.model.adapter.AbstractKeyStoreAdapter; -import org.apache.qpid.test.utils.TestSSLConstants; - -public class KeyStoreRecovererTest extends TestCase -{ - - public void testCreateWithAllAttributesProvided() - { - Map<String, Object> attributes = getKeyStoreAttributes(); - Map<String, Object> attributesCopy = new HashMap<String, Object>(attributes); - - UUID id = UUID.randomUUID(); - Broker broker = mock(Broker.class); - ConfigurationEntry entry = mock(ConfigurationEntry.class); - when(entry.getAttributes()).thenReturn(attributes); - when(entry.getId()).thenReturn(id); - - KeyStoreRecoverer recovever = new KeyStoreRecoverer(); - - KeyStore keyStore = recovever.create(null, entry, broker); - assertNotNull("Key store configured object is not created", keyStore); - assertEquals(id, keyStore.getId()); - - //verify we can retrieve the actual password using the method - assertEquals(TestSSLConstants.BROKER_TRUSTSTORE_PASSWORD, keyStore.getPassword()); - assertNotNull(keyStore.getPassword()); - - //verify that we havent configured the key store with the actual dummy password value - assertFalse(AbstractKeyStoreAdapter.DUMMY_PASSWORD_MASK.equals(keyStore.getPassword())); - - // Verify the remaining attributes, including that the password value returned - // via getAttribute is actually the dummy value and not the real password - attributesCopy.put(KeyStore.PASSWORD, AbstractKeyStoreAdapter.DUMMY_PASSWORD_MASK); - for (Map.Entry<String, Object> attribute : attributesCopy.entrySet()) - { - Object attributeValue = keyStore.getAttribute(attribute.getKey()); - assertEquals("Unexpected value of attribute '" + attribute.getKey() + "'", attribute.getValue(), attributeValue); - } - } - - public void testCreateWithMissedRequiredAttributes() - { - Map<String, Object> attributes = getKeyStoreAttributes(); - - UUID id = UUID.randomUUID(); - Broker broker = mock(Broker.class); - ConfigurationEntry entry = mock(ConfigurationEntry.class); - when(entry.getId()).thenReturn(id); - - KeyStoreRecoverer recovever = new KeyStoreRecoverer(); - - String[] mandatoryProperties = {KeyStore.NAME, KeyStore.PATH, KeyStore.PASSWORD}; - for (int i = 0; i < mandatoryProperties.length; i++) - { - Map<String, Object> properties = new HashMap<String, Object>(attributes); - properties.remove(mandatoryProperties[i]); - when(entry.getAttributes()).thenReturn(properties); - try - { - recovever.create(null, entry, broker); - fail("Cannot create key store without a " + mandatoryProperties[i]); - } - catch(IllegalArgumentException e) - { - // pass - } - } - } - - private Map<String, Object> getKeyStoreAttributes() - { - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(KeyStore.NAME, getName()); - attributes.put(KeyStore.PATH, TestSSLConstants.BROKER_KEYSTORE); - attributes.put(KeyStore.PASSWORD, TestSSLConstants.BROKER_KEYSTORE_PASSWORD); - attributes.put(KeyStore.TYPE, "jks"); - attributes.put(KeyStore.KEY_MANAGER_FACTORY_ALGORITHM, KeyManagerFactory.getDefaultAlgorithm()); - attributes.put(KeyStore.CERTIFICATE_ALIAS, "java-broker"); - return attributes; - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/PluginRecovererTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/PluginRecovererTest.java deleted file mode 100644 index 42fd742407..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/PluginRecovererTest.java +++ /dev/null @@ -1,117 +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.configuration.startup; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import junit.framework.TestCase; - -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.Plugin; -import org.apache.qpid.server.plugin.PluginFactory; -import org.apache.qpid.server.plugin.QpidServiceLoader; - -public class PluginRecovererTest extends TestCase -{ - private UUID _id; - private Map<String, Object> _attributes; - - private PluginFactory _factory; - private QpidServiceLoader<PluginFactory> _pluginFactoryServiceLoader; - private Broker _broker; - private ConfigurationEntry _configurationEntry; - - @SuppressWarnings("unchecked") - protected void setUp() throws Exception - { - super.setUp(); - _id = UUID.randomUUID(); - _attributes = new HashMap<String, Object>(); - - _factory = mock(PluginFactory.class); - - _pluginFactoryServiceLoader = mock(QpidServiceLoader.class); - when(_pluginFactoryServiceLoader.instancesOf(PluginFactory.class)).thenReturn(Collections.singletonList(_factory )); - - _broker = mock(Broker.class); - - _configurationEntry = mock(ConfigurationEntry.class); - when(_configurationEntry.getId()).thenReturn(_id); - when(_configurationEntry.getAttributes()).thenReturn(_attributes); - } - - public void testCreate() - { - Plugin pluginFromFactory = mock(Plugin.class); - when(pluginFromFactory.getId()).thenReturn(_id); - when(_factory.createInstance(_id, _attributes, _broker)).thenReturn(pluginFromFactory); - - PluginRecoverer pluginRecoverer = new PluginRecoverer(_pluginFactoryServiceLoader); - ConfiguredObject pluginFromRecoverer = pluginRecoverer.create(null, _configurationEntry, _broker); - assertNotNull("Null group provider", pluginFromRecoverer); - assertSame("Unexpected plugin", pluginFromFactory, pluginFromRecoverer); - assertEquals("Unexpected ID", _id, pluginFromRecoverer.getId()); - } - - public void testCreateThrowsExceptionForUnexpectedId() - { - Plugin pluginFromFactory = mock(Plugin.class); - when(pluginFromFactory.getId()).thenReturn(UUID.randomUUID()); - when(_factory.createInstance(_id, _attributes, _broker)).thenReturn(pluginFromFactory); - - PluginRecoverer pluginRecoverer = new PluginRecoverer(_pluginFactoryServiceLoader); - try - { - pluginRecoverer.create(null, _configurationEntry, _broker); - fail("An exception should be thrown for incorrect id"); - } - catch(IllegalStateException e) - { - //pass - } - } - - public void testCreateThrowsExceptionWhenNoPluginIsCreated() - { - when(_factory.createInstance(_id, _attributes, _broker)).thenReturn(null); - - PluginRecoverer pluginRecoverer = new PluginRecoverer(_pluginFactoryServiceLoader); - try - { - pluginRecoverer.create(null, _configurationEntry, _broker); - fail("Configuration exception should be thrown when plugin is not created"); - } - catch(IllegalConfigurationException e) - { - // pass - } - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/PreferencesProviderRecovererTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/PreferencesProviderRecovererTest.java deleted file mode 100644 index 8c316b5f53..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/PreferencesProviderRecovererTest.java +++ /dev/null @@ -1,96 +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.configuration.startup; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfigurationEntryStore; -import org.apache.qpid.server.configuration.RecovererProvider; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.PreferencesProvider; -import org.apache.qpid.server.model.adapter.FileSystemPreferencesProvider; -import org.apache.qpid.server.model.adapter.PreferencesProviderCreator; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.test.utils.TestFileUtils; - -public class PreferencesProviderRecovererTest extends QpidTestCase -{ - private AuthenticationProvider _authenticationProvider; - private Broker _broker; - - public void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - _authenticationProvider = mock(AuthenticationProvider.class); - _broker = BrokerTestHelper.createBrokerMock(); - when(_authenticationProvider.getParent(Broker.class)).thenReturn(_broker); - } - - public void tearDown() throws Exception - { - try - { - BrokerTestHelper.tearDown(); - } - finally - { - super.tearDown(); - } - } - - public void testRecoverFileSystemPreferencesProvider() - { - PreferencesProviderRecoverer recoverer = new PreferencesProviderRecoverer(new PreferencesProviderCreator()); - - Map<String, Object> attributes = new HashMap<String, Object>(); - UUID id = UUID.randomUUID(); - attributes.put(PreferencesProvider.TYPE, FileSystemPreferencesProvider.class); - attributes.put(PreferencesProvider.NAME, "test-provider"); - File file = TestFileUtils.createTempFile(this, ".prefs.json", "{\"test_user\":{\"pref1\": \"pref1Value\", \"pref2\": 1.0} }"); - try - { - attributes.put(FileSystemPreferencesProvider.PATH, file.getAbsolutePath()); - ConfigurationEntry entry = new ConfigurationEntry(id, PreferencesProvider.class.getSimpleName(), attributes, Collections.<UUID>emptySet(), mock(ConfigurationEntryStore.class)); - PreferencesProvider provider = recoverer.create(mock(RecovererProvider.class), entry, _authenticationProvider); - assertNotNull("Preferences provider was not recovered", provider); - assertEquals("Unexpected name", "test-provider", provider.getName()); - assertEquals("Unexpected id", id, provider.getId()); - assertEquals("Unexpected path", file.getAbsolutePath(), provider.getAttribute(FileSystemPreferencesProvider.PATH)); - } - finally - { - file.delete(); - } - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/TrustStoreRecovererTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/TrustStoreRecovererTest.java deleted file mode 100644 index 4d92f99306..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/TrustStoreRecovererTest.java +++ /dev/null @@ -1,117 +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.configuration.startup; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import javax.net.ssl.TrustManagerFactory; - -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.TrustStore; -import org.apache.qpid.server.model.adapter.AbstractKeyStoreAdapter; -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.test.utils.TestSSLConstants; - -public class TrustStoreRecovererTest extends QpidTestCase -{ - public void testCreateWithAllAttributesProvided() - { - Map<String, Object> attributes = getTrustStoreAttributes(); - Map<String, Object> attributesCopy = new HashMap<String, Object>(attributes); - - UUID id = UUID.randomUUID(); - Broker broker = mock(Broker.class); - ConfigurationEntry entry = mock(ConfigurationEntry.class); - when(entry.getAttributes()).thenReturn(attributes); - when(entry.getId()).thenReturn(id); - - TrustStoreRecoverer recoverer = new TrustStoreRecoverer(); - - TrustStore trustStore = recoverer.create(null, entry, broker); - assertNotNull("Trust store configured object is not created", trustStore); - assertEquals(id, trustStore.getId()); - - //verify we can retrieve the actual password using the method - assertEquals(TestSSLConstants.BROKER_TRUSTSTORE_PASSWORD, trustStore.getPassword()); - assertNotNull(trustStore.getPassword()); - - //verify that we havent configured the trust store with the actual dummy password value - assertFalse(AbstractKeyStoreAdapter.DUMMY_PASSWORD_MASK.equals(trustStore.getPassword())); - - // Verify the remaining attributes, including that the password value returned - // via getAttribute is actually the dummy value and not the real password - attributesCopy.put(TrustStore.PASSWORD, AbstractKeyStoreAdapter.DUMMY_PASSWORD_MASK); - for (Map.Entry<String, Object> attribute : attributesCopy.entrySet()) - { - Object attributeValue = trustStore.getAttribute(attribute.getKey()); - assertEquals("Unexpected value of attribute '" + attribute.getKey() + "'", attribute.getValue(), attributeValue); - } - } - - public void testCreateWithMissedRequiredAttributes() - { - Map<String, Object> attributes = getTrustStoreAttributes(); - - UUID id = UUID.randomUUID(); - Broker broker = mock(Broker.class); - ConfigurationEntry entry = mock(ConfigurationEntry.class); - when(entry.getAttributes()).thenReturn(attributes); - when(entry.getId()).thenReturn(id); - - TrustStoreRecoverer recovever = new TrustStoreRecoverer(); - - String[] mandatoryProperties = {TrustStore.NAME, TrustStore.PATH, TrustStore.PASSWORD}; - for (int i = 0; i < mandatoryProperties.length; i++) - { - Map<String, Object> properties = new HashMap<String, Object>(attributes); - properties.remove(mandatoryProperties[i]); - when(entry.getAttributes()).thenReturn(properties); - try - { - recovever.create(null, entry, broker); - fail("Cannot create key store without a " + mandatoryProperties[i]); - } - catch(IllegalArgumentException e) - { - // pass - } - } - } - - private Map<String, Object> getTrustStoreAttributes() - { - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(TrustStore.NAME, getName()); - attributes.put(TrustStore.PATH, TestSSLConstants.BROKER_TRUSTSTORE); - attributes.put(TrustStore.PASSWORD, TestSSLConstants.BROKER_TRUSTSTORE_PASSWORD); - attributes.put(TrustStore.TYPE, "jks"); - attributes.put(TrustStore.TRUST_MANAGER_FACTORY_ALGORITHM, TrustManagerFactory.getDefaultAlgorithm()); - attributes.put(TrustStore.PEERS_ONLY, Boolean.TRUE); - return attributes; - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/VirtualHostRecovererTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/VirtualHostRecovererTest.java deleted file mode 100644 index f00d12b77d..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/VirtualHostRecovererTest.java +++ /dev/null @@ -1,132 +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.configuration.startup; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.HashMap; -import java.util.Map; - -import junit.framework.TestCase; - -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.security.SecurityManager; -import org.apache.qpid.server.stats.StatisticsGatherer; -import org.apache.qpid.server.virtualhost.StandardVirtualHostFactory; -import org.apache.qpid.test.utils.TestFileUtils; - -public class VirtualHostRecovererTest extends TestCase -{ - public void testCreate() - { - StatisticsGatherer statisticsGatherer = mock(StatisticsGatherer.class); - SecurityManager securityManager = mock(SecurityManager.class); - ConfigurationEntry entry = mock(ConfigurationEntry.class); - Broker parent = mock(Broker.class); - when(parent.getAttribute(Broker.VIRTUALHOST_HOUSEKEEPING_CHECK_PERIOD)).thenReturn(3000l); - when(parent.getSecurityManager()).thenReturn(securityManager); - - VirtualHostRecoverer recoverer = new VirtualHostRecoverer(statisticsGatherer); - Map<String, Object> attributes = new HashMap<String, Object>(); - String name = getName(); - attributes.put(VirtualHost.NAME, name); - File file = TestFileUtils.createTempFile(this, ".xml", "<virtualhosts><virtualhost><name>" + name + "</name><" + name - + "></" + name + "></virtualhost></virtualhosts>"); - attributes.put(VirtualHost.CONFIG_PATH, file.getAbsolutePath()); - when(entry.getAttributes()).thenReturn(attributes); - - VirtualHost host = recoverer.create(null, entry, parent); - - assertNotNull("Null is returned", host); - assertEquals("Unexpected name", getName(), host.getName()); - } - - public void testCreateVirtualHostFromStoreConfigAtrributes() - { - StatisticsGatherer statisticsGatherer = mock(StatisticsGatherer.class); - SecurityManager securityManager = mock(SecurityManager.class); - ConfigurationEntry entry = mock(ConfigurationEntry.class); - Broker parent = mock(Broker.class); - when(parent.getAttribute(Broker.VIRTUALHOST_HOUSEKEEPING_CHECK_PERIOD)).thenReturn(3000l); - when(parent.getSecurityManager()).thenReturn(securityManager); - - VirtualHostRecoverer recoverer = new VirtualHostRecoverer(statisticsGatherer); - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(VirtualHost.NAME, getName()); - attributes.put(VirtualHost.TYPE, StandardVirtualHostFactory.TYPE); - - attributes.put(VirtualHost.STORE_TYPE, "TESTMEMORY"); - when(entry.getAttributes()).thenReturn(attributes); - - VirtualHost host = recoverer.create(null, entry, parent); - - assertNotNull("Null is returned", host); - assertEquals("Unexpected name", getName(), host.getName()); - } - - public void testCreateWithoutMandatoryAttributesResultsInException() - { - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(VirtualHost.NAME, getName()); - attributes.put(VirtualHost.CONFIG_PATH, "/path/to/virtualhost.xml"); - String[] mandatoryAttributes = {VirtualHost.NAME, VirtualHost.CONFIG_PATH}; - - checkMandatoryAttributesAreValidated(mandatoryAttributes, attributes); - - attributes = new HashMap<String, Object>(); - attributes.put(VirtualHost.NAME, getName()); - attributes.put(VirtualHost.STORE_TYPE, "MEMORY"); - mandatoryAttributes = new String[]{VirtualHost.NAME, VirtualHost.STORE_TYPE}; - - checkMandatoryAttributesAreValidated(mandatoryAttributes, attributes); - } - - public void checkMandatoryAttributesAreValidated(String[] mandatoryAttributes, Map<String, Object> attributes) - { - StatisticsGatherer statisticsGatherer = mock(StatisticsGatherer.class); - SecurityManager securityManager = mock(SecurityManager.class); - ConfigurationEntry entry = mock(ConfigurationEntry.class); - Broker parent = mock(Broker.class); - when(parent.getSecurityManager()).thenReturn(securityManager); - VirtualHostRecoverer recoverer = new VirtualHostRecoverer(statisticsGatherer); - - for (String name : mandatoryAttributes) - { - Map<String, Object> copy = new HashMap<String, Object>(attributes); - copy.remove(name); - when(entry.getAttributes()).thenReturn(copy); - try - { - recoverer.create(null, entry, parent); - fail("Cannot create a virtual host without a manadatory attribute " + name); - } - catch(IllegalConfigurationException e) - { - // pass - } - } - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/store/ConfigurationEntryStoreTestCase.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/store/ConfigurationEntryStoreTestCase.java deleted file mode 100644 index d56481340b..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/store/ConfigurationEntryStoreTestCase.java +++ /dev/null @@ -1,391 +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.configuration.store; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfigurationEntryStore; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.GroupProvider; -import org.apache.qpid.server.model.KeyStore; -import org.apache.qpid.server.model.Port; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.model.TrustStore; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.plugin.AuthenticationManagerFactory; -import org.apache.qpid.server.security.auth.manager.AnonymousAuthenticationManager; -import org.apache.qpid.server.security.auth.manager.ExternalAuthenticationManager; -import org.apache.qpid.test.utils.QpidTestCase; - -public abstract class ConfigurationEntryStoreTestCase extends QpidTestCase -{ - private ConfigurationEntryStore _store; - - private UUID _brokerId; - private UUID _virtualHostId; - private UUID _authenticationProviderId; - - private Map<String, Object> _brokerAttributes; - private Map<String, Object> _virtualHostAttributes; - private Map<String, Object> _authenticationProviderAttributes; - - public void setUp() throws Exception - { - super.setUp(); - - _brokerId = UUID.randomUUID(); - _brokerAttributes = new HashMap<String, Object>(); - _brokerAttributes.put(Broker.DEFAULT_VIRTUAL_HOST, "test"); - _brokerAttributes.put(Broker.QUEUE_ALERT_THRESHOLD_MESSAGE_AGE, 9); - _brokerAttributes.put(Broker.QUEUE_ALERT_THRESHOLD_QUEUE_DEPTH_MESSAGES, 8); - _brokerAttributes.put(Broker.QUEUE_ALERT_THRESHOLD_QUEUE_DEPTH_BYTES, 7); - _brokerAttributes.put(Broker.QUEUE_ALERT_THRESHOLD_MESSAGE_SIZE, 6); - _brokerAttributes.put(Broker.QUEUE_ALERT_REPEAT_GAP, 5); - _brokerAttributes.put(Broker.QUEUE_FLOW_CONTROL_SIZE_BYTES, 5); - _brokerAttributes.put(Broker.QUEUE_FLOW_CONTROL_RESUME_SIZE_BYTES, 3); - _brokerAttributes.put(Broker.QUEUE_MAXIMUM_DELIVERY_ATTEMPTS, 2); - _brokerAttributes.put(Broker.QUEUE_DEAD_LETTER_QUEUE_ENABLED, true); - _brokerAttributes.put(Broker.VIRTUALHOST_HOUSEKEEPING_CHECK_PERIOD, 1); - _brokerAttributes.put(Broker.CONNECTION_SESSION_COUNT_LIMIT, 1000); - _brokerAttributes.put(Broker.CONNECTION_HEART_BEAT_DELAY, 2000); - _brokerAttributes.put(Broker.STATISTICS_REPORTING_PERIOD, 4000); - _brokerAttributes.put(Broker.STATISTICS_REPORTING_RESET_ENABLED, true); - - _virtualHostId = UUID.randomUUID(); - _virtualHostAttributes = new HashMap<String, Object>(); - _virtualHostAttributes.put(VirtualHost.NAME, "test"); - _virtualHostAttributes.put(VirtualHost.CONFIG_PATH, "/path/to/phantom/test"); - - _authenticationProviderId = UUID.randomUUID(); - _authenticationProviderAttributes = new HashMap<String, Object>(); - _authenticationProviderAttributes.put(AuthenticationProvider.NAME, "authenticationProvider1"); - _authenticationProviderAttributes.put(AuthenticationManagerFactory.ATTRIBUTE_TYPE, AnonymousAuthenticationManager.class.getSimpleName()); - - _store = createStore(_brokerId, _brokerAttributes); - addConfiguration(_virtualHostId, VirtualHost.class.getSimpleName(), _virtualHostAttributes); - addConfiguration(_authenticationProviderId, AuthenticationProvider.class.getSimpleName(), _authenticationProviderAttributes); - } - - // ??? perhaps it should not be abstract - protected abstract ConfigurationEntryStore createStore(UUID brokerId, Map<String, Object> brokerAttributes) throws Exception; - - protected abstract void addConfiguration(UUID id, String type, Map<String, Object> attributes); - - protected ConfigurationEntryStore getStore() - { - return _store; - } - - public void testGetRootEntry() - { - ConfigurationEntry brokerConfigEntry = _store.getRootEntry(); - assertNotNull("Root entry does not exist", brokerConfigEntry); - assertEquals("Unexpected id", _brokerId, brokerConfigEntry.getId()); - assertEquals("Unexpected type ", Broker.class.getSimpleName(), brokerConfigEntry.getType()); - Map<String, Object> attributes = brokerConfigEntry.getAttributes(); - assertNotNull("Attributes cannot be null", attributes); - for (Map.Entry<String, Object> attribute : _brokerAttributes.entrySet()) - { - assertEquals("Unexpected attribute " + attribute.getKey(), attribute.getValue(), attributes.get(attribute.getKey())); - } - } - - public void testGetEntry() - { - ConfigurationEntry authenticationProviderConfigEntry = _store.getEntry(_authenticationProviderId); - assertNotNull("Provider with id " + _authenticationProviderId + " should exist", authenticationProviderConfigEntry); - assertEquals("Unexpected id", _authenticationProviderId, authenticationProviderConfigEntry.getId()); - assertEquals("Unexpected type ", AuthenticationProvider.class.getSimpleName(), authenticationProviderConfigEntry.getType()); - Map<String, Object> attributes = authenticationProviderConfigEntry.getAttributes(); - assertNotNull("Attributes cannot be null", attributes); - assertEquals("Unexpected attributes", _authenticationProviderAttributes, attributes); - } - - public void testRemove() - { - Map<String, Object> virtualHostAttributes = new HashMap<String, Object>(); - virtualHostAttributes.put(VirtualHost.NAME, getName()); - virtualHostAttributes.put(VirtualHost.CONFIG_PATH, "/path/to/phantom/virtualhost/config"); - UUID virtualHostId = UUID.randomUUID(); - addConfiguration(virtualHostId, VirtualHost.class.getSimpleName(), virtualHostAttributes); - - assertNotNull("Virtual host with id " + virtualHostId + " should exist", _store.getEntry(virtualHostId)); - - _store.remove(virtualHostId); - assertNull("Authentication provider configuration should be removed", _store.getEntry(virtualHostId)); - } - - public void testRemoveMultipleEntries() - { - Map<String, Object> virtualHost1Attributes = new HashMap<String, Object>(); - virtualHost1Attributes.put(VirtualHost.NAME, "test1"); - virtualHost1Attributes.put(VirtualHost.CONFIG_PATH, "/path/to/phantom/virtualhost/config1"); - UUID virtualHost1Id = UUID.randomUUID(); - addConfiguration(virtualHost1Id, VirtualHost.class.getSimpleName(), virtualHost1Attributes); - - Map<String, Object> virtualHost2Attributes = new HashMap<String, Object>(); - virtualHost2Attributes.put(VirtualHost.NAME, "test1"); - virtualHost2Attributes.put(VirtualHost.CONFIG_PATH, "/path/to/phantom/virtualhost/config2"); - UUID virtualHost2Id = UUID.randomUUID(); - addConfiguration(virtualHost2Id, VirtualHost.class.getSimpleName(), virtualHost2Attributes); - - assertNotNull("Virtual host with id " + virtualHost1Id + " should exist", _store.getEntry(virtualHost1Id)); - assertNotNull("Virtual host with id " + virtualHost2Id + " should exist", _store.getEntry(virtualHost2Id)); - - UUID[] deletedIds = _store.remove(virtualHost1Id, virtualHost2Id); - assertNotNull("Unexpected deleted ids", deletedIds); - assertEquals("Unexpected id of first deleted virtual host", virtualHost1Id , deletedIds[0]); - assertEquals("Unexpected id of second deleted virtual host", virtualHost2Id , deletedIds[1]); - assertNull("First virtual host configuration should be removed", _store.getEntry(virtualHost1Id)); - assertNull("Second virtual host configuration should be removed", _store.getEntry(virtualHost2Id)); - } - - public void testSaveBroker() - { - ConfigurationEntry brokerConfigEntry = _store.getRootEntry(); - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(Broker.DEFAULT_VIRTUAL_HOST, "test"); - attributes.put(Broker.QUEUE_ALERT_THRESHOLD_MESSAGE_AGE, 19); - attributes.put(Broker.QUEUE_ALERT_THRESHOLD_QUEUE_DEPTH_MESSAGES, 18); - attributes.put(Broker.QUEUE_ALERT_THRESHOLD_QUEUE_DEPTH_BYTES, 17); - attributes.put(Broker.QUEUE_ALERT_THRESHOLD_MESSAGE_SIZE, 16); - attributes.put(Broker.QUEUE_ALERT_REPEAT_GAP, 15); - attributes.put(Broker.QUEUE_FLOW_CONTROL_SIZE_BYTES, 15); - attributes.put(Broker.QUEUE_FLOW_CONTROL_RESUME_SIZE_BYTES, 13); - attributes.put(Broker.QUEUE_MAXIMUM_DELIVERY_ATTEMPTS, 12); - attributes.put(Broker.QUEUE_DEAD_LETTER_QUEUE_ENABLED, false); - attributes.put(Broker.VIRTUALHOST_HOUSEKEEPING_CHECK_PERIOD, 11); - attributes.put(Broker.CONNECTION_SESSION_COUNT_LIMIT, 11000); - attributes.put(Broker.CONNECTION_HEART_BEAT_DELAY, 12000); - attributes.put(Broker.STATISTICS_REPORTING_PERIOD, 14000); - attributes.put(Broker.STATISTICS_REPORTING_RESET_ENABLED, false); - ConfigurationEntry updatedBrokerEntry = new ConfigurationEntry(_brokerId, Broker.class.getSimpleName(), attributes, - brokerConfigEntry.getChildrenIds(), _store); - - _store.save(updatedBrokerEntry); - - ConfigurationEntry newBrokerConfigEntry = _store.getRootEntry(); - assertNotNull("Root entry does not exist", newBrokerConfigEntry); - assertEquals("Unexpected id", _brokerId, newBrokerConfigEntry.getId()); - assertEquals("Unexpected type ", Broker.class.getSimpleName(), newBrokerConfigEntry.getType()); - Map<String, Object> newBrokerattributes = newBrokerConfigEntry.getAttributes(); - assertNotNull("Attributes cannot be null", newBrokerattributes); - assertEquals("Unexpected attributes", attributes, newBrokerattributes); - } - - public void testSaveNewVirtualHost() - { - Map<String, Object> virtualHostAttributes = new HashMap<String, Object>(); - virtualHostAttributes.put(VirtualHost.NAME, "test1"); - virtualHostAttributes.put(VirtualHost.CONFIG_PATH, "/path/to/phantom/virtualhost/config1"); - UUID virtualHostId = UUID.randomUUID(); - ConfigurationEntry hostEntry = new ConfigurationEntry(virtualHostId, VirtualHost.class.getSimpleName(), virtualHostAttributes, - Collections.<UUID> emptySet(), _store); - - _store.save(hostEntry); - - ConfigurationEntry configurationEntry = _store.getEntry(virtualHostId); - assertEquals("Unexpected virtual host configuration", hostEntry, configurationEntry); - assertEquals("Unexpected type", VirtualHost.class.getSimpleName(), configurationEntry.getType()); - assertEquals("Unexpected virtual host attributes", hostEntry.getAttributes(), configurationEntry.getAttributes()); - assertTrue("Unexpected virtual host children found", hostEntry.getChildrenIds().isEmpty()); - } - - public void testSaveExistingVirtualHost() - { - ConfigurationEntry hostEntry = _store.getEntry(_virtualHostId); - assertNotNull("Host configuration is not found", hostEntry); - - Map<String, Object> virtualHostAttributes = new HashMap<String, Object>(); - virtualHostAttributes.put(VirtualHost.NAME, "test"); - virtualHostAttributes.put(VirtualHost.CONFIG_PATH, "/path/to/new/phantom/test/configuration"); - - ConfigurationEntry updatedEntry = new ConfigurationEntry(_virtualHostId, VirtualHost.class.getSimpleName(), virtualHostAttributes, - hostEntry.getChildrenIds(), _store); - _store.save(updatedEntry); - - ConfigurationEntry newHostEntry = _store.getEntry(_virtualHostId); - assertEquals("Unexpected virtual host configuration", updatedEntry, newHostEntry); - assertEquals("Unexpected type", VirtualHost.class.getSimpleName(), newHostEntry.getType()); - assertEquals("Unexpected virtual host attributes", updatedEntry.getAttributes(), newHostEntry.getAttributes()); - assertEquals("Unexpected virtual host children found", updatedEntry.getChildrenIds(), newHostEntry.getChildrenIds()); - } - - public void testSaveNewAuthenticationProvider() - { - UUID authenticationProviderId = UUID.randomUUID(); - Map<String, Object> authenticationProviderAttributes = new HashMap<String, Object>(); - authenticationProviderAttributes.put(AuthenticationProvider.NAME, "authenticationProvider1"); - authenticationProviderAttributes.put(AuthenticationManagerFactory.ATTRIBUTE_TYPE, ExternalAuthenticationManager.class.getSimpleName()); - ConfigurationEntry providerEntry = new ConfigurationEntry(authenticationProviderId, AuthenticationProvider.class.getSimpleName(), - authenticationProviderAttributes, Collections.<UUID> emptySet(), _store); - - _store.save(providerEntry); - - ConfigurationEntry storeEntry = _store.getEntry(authenticationProviderId); - assertEquals("Unexpected provider configuration", providerEntry, storeEntry); - assertEquals("Unexpected type", AuthenticationProvider.class.getSimpleName(), storeEntry.getType()); - assertEquals("Unexpected provider attributes", providerEntry.getAttributes(), storeEntry.getAttributes()); - assertTrue("Unexpected provider children found", storeEntry.getChildrenIds().isEmpty()); - } - - public void testSaveExistingAuthenticationProvider() - { - ConfigurationEntry providerEntry = _store.getEntry(_authenticationProviderId); - assertNotNull("provider configuration is not found", providerEntry); - - Map<String, Object> authenticationProviderAttributes = new HashMap<String, Object>(); - authenticationProviderAttributes.put(AuthenticationProvider.NAME, "authenticationProvider1"); - authenticationProviderAttributes.put(AuthenticationManagerFactory.ATTRIBUTE_TYPE, ExternalAuthenticationManager.class.getSimpleName()); - ConfigurationEntry updatedEntry = new ConfigurationEntry(_authenticationProviderId, AuthenticationProvider.class.getSimpleName(), - authenticationProviderAttributes, Collections.<UUID> emptySet(), _store); - _store.save(updatedEntry); - - ConfigurationEntry storeEntry = _store.getEntry(_authenticationProviderId); - assertEquals("Unexpected provider configuration", updatedEntry, storeEntry); - assertEquals("Unexpected type", AuthenticationProvider.class.getSimpleName(), storeEntry.getType()); - assertEquals("Unexpected provider attributes", updatedEntry.getAttributes(), storeEntry.getAttributes()); - assertTrue("Unexpected provider children found", storeEntry.getChildrenIds().isEmpty()); - } - - public void testSaveTrustStore() - { - UUID trustStoreId = UUID.randomUUID(); - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(TrustStore.NAME, getName()); - attributes.put(TrustStore.PATH, "/path/to/truststore"); - attributes.put(TrustStore.PASSWORD, "my-secret-password"); - attributes.put(TrustStore.TYPE, "NON-JKS"); - attributes.put(TrustStore.TRUST_MANAGER_FACTORY_ALGORITHM, "NON-STANDARD"); - attributes.put(TrustStore.DESCRIPTION, "Description"); - - ConfigurationEntry trustStoreEntry = new ConfigurationEntry(trustStoreId, TrustStore.class.getSimpleName(), attributes, - Collections.<UUID> emptySet(), _store); - - _store.save(trustStoreEntry); - - ConfigurationEntry storeEntry = _store.getEntry(trustStoreId); - assertEquals("Unexpected trust store configuration", trustStoreEntry, storeEntry); - assertEquals("Unexpected type", TrustStore.class.getSimpleName(), storeEntry.getType()); - assertEquals("Unexpected provider attributes", trustStoreEntry.getAttributes(), storeEntry.getAttributes()); - assertTrue("Unexpected provider children found", storeEntry.getChildrenIds().isEmpty()); - } - - public void testSaveKeyStore() - { - UUID keyStoreId = UUID.randomUUID(); - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(KeyStore.NAME, getName()); - attributes.put(KeyStore.PATH, "/path/to/truststore"); - attributes.put(KeyStore.PASSWORD, "my-secret-password"); - attributes.put(KeyStore.TYPE, "NON-JKS"); - attributes.put(KeyStore.KEY_MANAGER_FACTORY_ALGORITHM, "NON-STANDARD"); - attributes.put(KeyStore.DESCRIPTION, "Description"); - attributes.put(KeyStore.CERTIFICATE_ALIAS, "Alias"); - - ConfigurationEntry keyStoreEntry = new ConfigurationEntry(keyStoreId, KeyStore.class.getSimpleName(), attributes, Collections.<UUID> emptySet(), - _store); - - _store.save(keyStoreEntry); - - ConfigurationEntry storeEntry = _store.getEntry(keyStoreId); - assertEquals("Unexpected key store configuration", keyStoreEntry, storeEntry); - assertEquals("Unexpected type", KeyStore.class.getSimpleName(), storeEntry.getType()); - assertEquals("Unexpected provider attributes", keyStoreEntry.getAttributes(), storeEntry.getAttributes()); - assertTrue("Unexpected provider children found", storeEntry.getChildrenIds().isEmpty()); - } - - public void testSaveGroupProvider() - { - UUID groupProviderId = UUID.randomUUID(); - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(GroupProvider.NAME, getName()); - - ConfigurationEntry groupProviderEntry = new ConfigurationEntry(groupProviderId, GroupProvider.class.getSimpleName(), attributes, - Collections.<UUID> emptySet(), _store); - - _store.save(groupProviderEntry); - - ConfigurationEntry storeEntry = _store.getEntry(groupProviderId); - assertEquals("Unexpected group provider configuration", groupProviderEntry, storeEntry); - assertEquals("Unexpected type", GroupProvider.class.getSimpleName(), storeEntry.getType()); - assertEquals("Unexpected group provider attributes", groupProviderEntry.getAttributes(), storeEntry.getAttributes()); - assertTrue("Unexpected provider children found", storeEntry.getChildrenIds().isEmpty()); - } - - public void testSavePort() - { - UUID portId = UUID.randomUUID(); - Map<String, Object> attributes = new HashMap<String, Object>(); - Set<String> tcpTransportSet = Collections.singleton(Transport.TCP.name()); - attributes.put(Port.PORT, 9999); - attributes.put(Port.TRANSPORTS, tcpTransportSet); - attributes.put(Port.TCP_NO_DELAY, true); - attributes.put(Port.RECEIVE_BUFFER_SIZE, 1); - attributes.put(Port.SEND_BUFFER_SIZE, 2); - attributes.put(Port.NEED_CLIENT_AUTH, true); - attributes.put(Port.WANT_CLIENT_AUTH, true); - - ConfigurationEntry portEntry = new ConfigurationEntry(portId, Port.class.getSimpleName(), attributes, Collections.<UUID> emptySet(), _store); - - _store.save(portEntry); - - ConfigurationEntry storeEntry = _store.getEntry(portId); - assertEquals("Unexpected port configuration", portEntry, storeEntry); - assertEquals("Unexpected type", Port.class.getSimpleName(), storeEntry.getType()); - assertEquals("Unexpected port attributes", portEntry.getAttributes(), storeEntry.getAttributes()); - assertTrue("Unexpected port children found", storeEntry.getChildrenIds().isEmpty()); - } - - public void testMultipleSave() - { - UUID virtualHostId = UUID.randomUUID(); - Map<String, Object> virtualHostAttributes = new HashMap<String, Object>(); - virtualHostAttributes.put(VirtualHost.NAME, "test1"); - virtualHostAttributes.put(VirtualHost.CONFIG_PATH, "/path/to/phantom/virtualhost/config1"); - ConfigurationEntry hostEntry = new ConfigurationEntry(virtualHostId, VirtualHost.class.getSimpleName(), virtualHostAttributes, - Collections.<UUID> emptySet(), _store); - - UUID keyStoreId = UUID.randomUUID(); - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(KeyStore.NAME, getName()); - attributes.put(KeyStore.PATH, "/path/to/truststore"); - attributes.put(KeyStore.PASSWORD, "my-secret-password"); - attributes.put(KeyStore.TYPE, "NON-JKS"); - attributes.put(KeyStore.KEY_MANAGER_FACTORY_ALGORITHM, "NON-STANDARD"); - attributes.put(KeyStore.DESCRIPTION, "Description"); - attributes.put(KeyStore.CERTIFICATE_ALIAS, "Alias"); - - ConfigurationEntry keyStoreEntry = new ConfigurationEntry(keyStoreId, KeyStore.class.getSimpleName(), attributes, Collections.<UUID> emptySet(), - _store); - - _store.save(hostEntry, keyStoreEntry); - - assertNotNull("Virtual host is not found", _store.getEntry(virtualHostId)); - assertNotNull("Key store is not found", _store.getEntry(keyStoreId)); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/store/JsonConfigurationEntryStoreTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/store/JsonConfigurationEntryStoreTest.java deleted file mode 100644 index 3412543030..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/store/JsonConfigurationEntryStoreTest.java +++ /dev/null @@ -1,236 +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.configuration.store; - -import java.io.File; -import java.io.IOException; -import java.io.StringWriter; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfigurationEntryStore; -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.test.utils.TestFileUtils; -import org.codehaus.jackson.JsonGenerationException; -import org.codehaus.jackson.map.JsonMappingException; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; - -public class JsonConfigurationEntryStoreTest extends ConfigurationEntryStoreTestCase -{ - private File _storeFile; - private ObjectMapper _objectMapper; - - @Override - public void setUp() throws Exception - { - _objectMapper = new ObjectMapper(); - _objectMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - super.setUp(); - } - - @Override - public void tearDown() throws Exception - { - _storeFile.delete(); - super.tearDown(); - } - - @Override - protected ConfigurationEntryStore createStore(UUID brokerId, Map<String, Object> brokerAttributes) throws Exception - { - _storeFile = createStoreFile(brokerId, brokerAttributes); - JsonConfigurationEntryStore store = new JsonConfigurationEntryStore(_storeFile.getAbsolutePath(), null, false, Collections.<String,String>emptyMap()); - return store; - } - - private File createStoreFile(UUID brokerId, Map<String, Object> brokerAttributes) throws IOException, - JsonGenerationException, JsonMappingException - { - return createStoreFile(brokerId, brokerAttributes, true); - } - - private File createStoreFile(UUID brokerId, Map<String, Object> brokerAttributes, boolean setVersion) throws IOException, - JsonGenerationException, JsonMappingException - { - Map<String, Object> brokerObjectMap = new HashMap<String, Object>(); - brokerObjectMap.put(Broker.ID, brokerId); - if (setVersion) - { - brokerObjectMap.put(Broker.STORE_VERSION, MemoryConfigurationEntryStore.STORE_VERSION); - } - brokerObjectMap.put(Broker.NAME, getTestName()); - brokerObjectMap.putAll(brokerAttributes); - - StringWriter sw = new StringWriter(); - _objectMapper.writeValue(sw, brokerObjectMap); - - String brokerJson = sw.toString(); - - return TestFileUtils.createTempFile(this, ".json", brokerJson); - } - - @Override - protected void addConfiguration(UUID id, String type, Map<String, Object> attributes) - { - ConfigurationEntryStore store = getStore(); - store.save(new ConfigurationEntry(id, type, attributes, Collections.<UUID> emptySet(), store)); - } - - public void testAttributeIsResolvedFromSystemProperties() - { - String defaultVhost = getTestName(); - setTestSystemProperty("my.test.property", defaultVhost); - - ConfigurationEntryStore store = getStore(); - ConfigurationEntry brokerConfigEntry = store.getRootEntry(); - Map<String, Object> attributes = new HashMap<String, Object>(brokerConfigEntry.getAttributes()); - attributes.put(Broker.DEFAULT_VIRTUAL_HOST, "${my.test.property}"); - ConfigurationEntry updatedBrokerEntry = new ConfigurationEntry(brokerConfigEntry.getId(), Broker.class.getSimpleName(), - attributes, brokerConfigEntry.getChildrenIds(), store); - store.save(updatedBrokerEntry); - - JsonConfigurationEntryStore store2 = new JsonConfigurationEntryStore(_storeFile.getAbsolutePath(), null, false, Collections.<String,String>emptyMap()); - - assertEquals("Unresolved default virtualhost value", defaultVhost, store2.getRootEntry().getAttributes().get(Broker.DEFAULT_VIRTUAL_HOST)); - } - - public void testCreateEmptyStore() - { - File file = TestFileUtils.createTempFile(this, ".json"); - try - { - new JsonConfigurationEntryStore(file.getAbsolutePath(), null, false, Collections.<String,String>emptyMap()); - fail("Cannot create a new store without initial store"); - } - catch(IllegalConfigurationException e) - { - // pass - } - } - - public void testCreateFromExistingLocation() throws Exception - { - UUID brokerId = UUID.randomUUID(); - Map<String, Object> brokerAttributes = new HashMap<String, Object>(); - brokerAttributes.put(Broker.NAME, getTestName()); - File file = createStoreFile(brokerId, brokerAttributes); - - JsonConfigurationEntryStore store = new JsonConfigurationEntryStore(file.getAbsolutePath(), null, false, Collections.<String,String>emptyMap()); - ConfigurationEntry root = store.getRootEntry(); - assertNotNull("Root entry is not found", root); - assertEquals("Unexpected root entry", brokerId, root.getId()); - Map<String, Object> attributes = root.getAttributes(); - assertNotNull("Attributes not found", attributes); - assertEquals("Unexpected number of attriburtes", 2, attributes.size()); - assertEquals("Unexpected name attribute", getTestName(), attributes.get(Broker.NAME)); - assertEquals("Unexpected version attribute", 1, attributes.get(Broker.STORE_VERSION)); - } - - public void testCreateFromInitialStore() throws Exception - { - UUID brokerId = UUID.randomUUID(); - Map<String, Object> brokerAttributes = new HashMap<String, Object>(); - File initialStoreFile = createStoreFile(brokerId, brokerAttributes); - - JsonConfigurationEntryStore initialStore = new JsonConfigurationEntryStore(initialStoreFile.getAbsolutePath(), null, false, Collections.<String,String>emptyMap()); - - File storeFile = TestFileUtils.createTempFile(this, ".json"); - JsonConfigurationEntryStore store = new JsonConfigurationEntryStore(storeFile.getAbsolutePath(), initialStore, false, Collections.<String,String>emptyMap()); - - ConfigurationEntry root = store.getRootEntry(); - assertNotNull("Root entry is not found", root); - assertEquals("Unexpected root entry", brokerId, root.getId()); - Map<String, Object> attributes = root.getAttributes(); - assertNotNull("Attributes not found", attributes); - assertEquals("Unexpected number of attriburtes", 2, attributes.size()); - assertEquals("Unexpected name attribute", getTestName(), attributes.get(Broker.NAME)); - assertEquals("Unexpected version attribute", 1, attributes.get(Broker.STORE_VERSION)); - } - - public void testGetVersion() - { - assertEquals("Unexpected version", 1, getStore().getVersion()); - } - - public void testGetType() - { - assertEquals("Unexpected type", "json", getStore().getType()); - } - - public void testUnsupportedStoreVersion() throws Exception - { - UUID brokerId = UUID.randomUUID(); - Map<String, Object> brokerAttributes = new HashMap<String, Object>(); - int[] storeVersions = {Integer.MAX_VALUE, 0}; - for (int storeVersion : storeVersions) - { - brokerAttributes.put(Broker.STORE_VERSION, storeVersion); - File storeFile = null; - try - { - storeFile = createStoreFile(brokerId, brokerAttributes); - new JsonConfigurationEntryStore(storeFile.getAbsolutePath(), null, false, Collections.<String, String>emptyMap()); - fail("The store creation should fail due to unsupported store version"); - } - catch (IllegalConfigurationException e) - { - assertEquals("The data of version " + storeVersion - + " can not be loaded by store of version " + MemoryConfigurationEntryStore.STORE_VERSION, e.getMessage()); - } - finally - { - if (storeFile != null) - { - storeFile.delete(); - } - } - } - } - - public void testStoreVersionNotSpecified() throws Exception - { - UUID brokerId = UUID.randomUUID(); - Map<String, Object> brokerAttributes = new HashMap<String, Object>(); - File storeFile = null; - try - { - storeFile = createStoreFile(brokerId, brokerAttributes, false); - new JsonConfigurationEntryStore(storeFile.getAbsolutePath(), null, false, Collections.<String, String>emptyMap()); - fail("The store creation should fail due to unspecified store version"); - } - catch (IllegalConfigurationException e) - { - assertEquals("Broker " + Broker.STORE_VERSION + " attribute must be specified", e.getMessage()); - } - finally - { - if (storeFile != null) - { - storeFile.delete(); - } - } - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/store/ManagementModeStoreHandlerTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/store/ManagementModeStoreHandlerTest.java deleted file mode 100644 index 34b4fbf1ab..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/store/ManagementModeStoreHandlerTest.java +++ /dev/null @@ -1,335 +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.configuration.store; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.any; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.UUID; - -import org.apache.qpid.server.BrokerOptions; -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfigurationEntryStore; -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.Port; -import org.apache.qpid.server.model.Protocol; -import org.apache.qpid.server.model.State; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.test.utils.QpidTestCase; - -public class ManagementModeStoreHandlerTest extends QpidTestCase -{ - private ManagementModeStoreHandler _handler; - private BrokerOptions _options; - private ConfigurationEntryStore _store; - private ConfigurationEntry _root; - private ConfigurationEntry _portEntry; - private UUID _rootId, _portEntryId; - - protected void setUp() throws Exception - { - super.setUp(); - _rootId = UUID.randomUUID(); - _portEntryId = UUID.randomUUID(); - _store = mock(ConfigurationEntryStore.class); - _root = mock(ConfigurationEntry.class); - _portEntry = mock(ConfigurationEntry.class); - when(_store.getRootEntry()).thenReturn(_root); - when(_root.getId()).thenReturn(_rootId); - when(_portEntry.getId()).thenReturn(_portEntryId); - when(_store.getEntry(_portEntryId)).thenReturn(_portEntry); - when(_store.getEntry(_rootId)).thenReturn(_root); - when(_root.getChildrenIds()).thenReturn(Collections.singleton(_portEntryId)); - when(_portEntry.getType()).thenReturn(Port.class.getSimpleName()); - _options = new BrokerOptions(); - _handler = new ManagementModeStoreHandler(_store, _options); - } - - public void testGetRootEntryWithEmptyOptions() - { - ConfigurationEntry root = _handler.getRootEntry(); - assertEquals("Unexpected root id", _rootId, root.getId()); - assertEquals("Unexpected children", Collections.singleton(_portEntryId), root.getChildrenIds()); - } - - public void testGetRootEntryWithHttpPortOverriden() - { - _options.setManagementModeHttpPortOverride(9090); - _handler = new ManagementModeStoreHandler(_store, _options); - ConfigurationEntry root = _handler.getRootEntry(); - assertEquals("Unexpected root id", _rootId, root.getId()); - Collection<UUID> childrenIds = root.getChildrenIds(); - assertEquals("Unexpected children size", 2, childrenIds.size()); - assertTrue("Store port entry id is not found", childrenIds.contains(_portEntryId)); - } - - public void testGetRootEntryWithRmiPortOverriden() - { - _options.setManagementModeRmiPortOverride(9090); - _handler = new ManagementModeStoreHandler(_store, _options); - ConfigurationEntry root = _handler.getRootEntry(); - assertEquals("Unexpected root id", _rootId, root.getId()); - Collection<UUID> childrenIds = root.getChildrenIds(); - assertEquals("Unexpected children size", 3, childrenIds.size()); - assertTrue("Store port entry id is not found", childrenIds.contains(_portEntryId)); - } - - public void testGetRootEntryWithConnectorPortOverriden() - { - _options.setManagementModeJmxPortOverride(9090); - _handler = new ManagementModeStoreHandler(_store, _options); - ConfigurationEntry root = _handler.getRootEntry(); - assertEquals("Unexpected root id", _rootId, root.getId()); - Collection<UUID> childrenIds = root.getChildrenIds(); - assertEquals("Unexpected children size", 2, childrenIds.size()); - assertTrue("Store port entry id is not found", childrenIds.contains(_portEntryId)); - } - - public void testGetRootEntryWithManagementPortsOverriden() - { - _options.setManagementModeHttpPortOverride(1000); - _options.setManagementModeRmiPortOverride(2000); - _options.setManagementModeJmxPortOverride(3000); - _handler = new ManagementModeStoreHandler(_store, _options); - ConfigurationEntry root = _handler.getRootEntry(); - assertEquals("Unexpected root id", _rootId, root.getId()); - Collection<UUID> childrenIds = root.getChildrenIds(); - assertEquals("Unexpected children size", 4, childrenIds.size()); - assertTrue("Store port entry id is not found", childrenIds.contains(_portEntryId)); - } - - public void testGetEntryByRootId() - { - ConfigurationEntry root = _handler.getEntry(_rootId); - assertEquals("Unexpected root id", _rootId, root.getId()); - assertEquals("Unexpected children", Collections.singleton(_portEntryId), root.getChildrenIds()); - } - - public void testGetEntryByPortId() - { - ConfigurationEntry portEntry = _handler.getEntry(_portEntryId); - assertEquals("Unexpected entry id", _portEntryId, portEntry.getId()); - assertTrue("Unexpected children", portEntry.getChildrenIds().isEmpty()); - assertEquals("Unexpected state", State.QUIESCED, portEntry.getAttributes().get(Port.STATE)); - } - - public void testGetEntryByCLIConnectorPortId() - { - _options.setManagementModeJmxPortOverride(9090); - _handler = new ManagementModeStoreHandler(_store, _options); - - UUID optionsPort = getOptionsPortId(); - ConfigurationEntry portEntry = _handler.getEntry(optionsPort); - assertCLIPortEntry(portEntry, optionsPort, Protocol.JMX_RMI); - } - - public void testGetEntryByCLIHttpPortId() - { - _options.setManagementModeHttpPortOverride(9090); - _handler = new ManagementModeStoreHandler(_store, _options); - - UUID optionsPort = getOptionsPortId(); - ConfigurationEntry portEntry = _handler.getEntry(optionsPort); - assertCLIPortEntry(portEntry, optionsPort, Protocol.HTTP); - } - - public void testHttpPortEntryIsQuiesced() - { - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(Port.PROTOCOLS, Collections.singleton(Protocol.HTTP)); - when(_portEntry.getAttributes()).thenReturn(attributes); - _options.setManagementModeHttpPortOverride(9090); - _handler = new ManagementModeStoreHandler(_store, _options); - - ConfigurationEntry portEntry = _handler.getEntry(_portEntryId); - assertEquals("Unexpected state", State.QUIESCED, portEntry.getAttributes().get(Port.STATE)); - } - - public void testRmiPortEntryIsQuiesced() - { - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(Port.PROTOCOLS, Collections.singleton(Protocol.RMI)); - when(_portEntry.getAttributes()).thenReturn(attributes); - _options.setManagementModeRmiPortOverride(9090); - _handler = new ManagementModeStoreHandler(_store, _options); - - ConfigurationEntry portEntry = _handler.getEntry(_portEntryId); - assertEquals("Unexpected state", State.QUIESCED, portEntry.getAttributes().get(Port.STATE)); - } - - public void testConnectorPortEntryIsQuiesced() - { - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(Port.PROTOCOLS, Collections.singleton(Protocol.JMX_RMI)); - when(_portEntry.getAttributes()).thenReturn(attributes); - _options.setManagementModeRmiPortOverride(9090); - _handler = new ManagementModeStoreHandler(_store, _options); - - ConfigurationEntry portEntry = _handler.getEntry(_portEntryId); - assertEquals("Unexpected state", State.QUIESCED, portEntry.getAttributes().get(Port.STATE)); - } - - public void testVirtualHostEntryIsNotQuiescedByDefault() - { - virtualHostEntryQuiescedStatusTestImpl(false); - } - - public void testVirtualHostEntryIsQuiescedWhenRequested() - { - virtualHostEntryQuiescedStatusTestImpl(true); - } - - private void virtualHostEntryQuiescedStatusTestImpl(boolean mmQuiesceVhosts) - { - UUID virtualHostId = UUID.randomUUID(); - ConfigurationEntry virtualHost = mock(ConfigurationEntry.class); - when(virtualHost.getId()).thenReturn(virtualHostId); - when(virtualHost.getType()).thenReturn(VirtualHost.class.getSimpleName()); - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(VirtualHost.CONFIG_PATH, "/path/to/host.xml"); - when(virtualHost.getAttributes()).thenReturn(attributes); - when(_store.getEntry(virtualHostId)).thenReturn(virtualHost); - when(_root.getChildrenIds()).thenReturn(new HashSet<UUID>(Arrays.asList(_portEntryId, virtualHostId))); - - State expectedState = mmQuiesceVhosts ? State.QUIESCED : null; - if(mmQuiesceVhosts) - { - _options.setManagementModeQuiesceVirtualHosts(mmQuiesceVhosts); - } - - _handler = new ManagementModeStoreHandler(_store, _options); - - ConfigurationEntry hostEntry = _handler.getEntry(virtualHostId); - Map<String, Object> hostAttributes = hostEntry.getAttributes(); - assertEquals("Unexpected state", expectedState, hostAttributes.get(VirtualHost.STATE)); - hostAttributes.remove(VirtualHost.STATE); - assertEquals("Unexpected attributes", attributes, hostAttributes); - } - - @SuppressWarnings("unchecked") - private void assertCLIPortEntry(ConfigurationEntry portEntry, UUID optionsPort, Protocol protocol) - { - assertEquals("Unexpected entry id", optionsPort, portEntry.getId()); - assertTrue("Unexpected children", portEntry.getChildrenIds().isEmpty()); - Map<String, Object> attributes = portEntry.getAttributes(); - assertEquals("Unexpected name", "MANAGEMENT-MODE-PORT-" + protocol.name(), attributes.get(Port.NAME)); - assertEquals("Unexpected protocol", Collections.singleton(protocol), new HashSet<Protocol>( - (Collection<Protocol>) attributes.get(Port.PROTOCOLS))); - } - - public void testSavePort() - { - _options.setManagementModeHttpPortOverride(1000); - _options.setManagementModeRmiPortOverride(2000); - _options.setManagementModeJmxPortOverride(3000); - _handler = new ManagementModeStoreHandler(_store, _options); - - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(Port.NAME, "TEST"); - ConfigurationEntry configurationEntry = new ConfigurationEntry(_portEntryId, Port.class.getSimpleName(), attributes, - Collections.<UUID> emptySet(), null); - _handler.save(configurationEntry); - verify(_store).save(any(ConfigurationEntry.class)); - } - - public void testSaveRoot() - { - _options.setManagementModeHttpPortOverride(1000); - _options.setManagementModeRmiPortOverride(2000); - _options.setManagementModeJmxPortOverride(3000); - _handler = new ManagementModeStoreHandler(_store, _options); - - ConfigurationEntry root = _handler.getRootEntry(); - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(Broker.NAME, "TEST"); - ConfigurationEntry configurationEntry = new ConfigurationEntry(_rootId, Broker.class.getSimpleName(), attributes, - root.getChildrenIds(), null); - _handler.save(configurationEntry); - verify(_store).save(any(ConfigurationEntry.class)); - } - - public void testSaveCLIHttpPort() - { - _options.setManagementModeHttpPortOverride(1000); - _handler = new ManagementModeStoreHandler(_store, _options); - - UUID portId = getOptionsPortId(); - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(Port.NAME, "TEST"); - ConfigurationEntry configurationEntry = new ConfigurationEntry(portId, Port.class.getSimpleName(), attributes, - Collections.<UUID> emptySet(), null); - try - { - _handler.save(configurationEntry); - fail("Exception should be thrown on trying to save CLI port"); - } - catch (IllegalConfigurationException e) - { - // pass - } - } - - public void testRemove() - { - _options.setManagementModeHttpPortOverride(1000); - _handler = new ManagementModeStoreHandler(_store, _options); - - _handler.remove(_portEntryId); - verify(_store).remove(_portEntryId); - } - - public void testRemoveCLIPort() - { - _options.setManagementModeHttpPortOverride(1000); - _handler = new ManagementModeStoreHandler(_store, _options); - UUID portId = getOptionsPortId(); - try - { - _handler.remove(portId); - fail("Exception should be thrown on trying to remove CLI port"); - } - catch (IllegalConfigurationException e) - { - // pass - } - } - - private UUID getOptionsPortId() - { - ConfigurationEntry root = _handler.getRootEntry(); - assertEquals("Unexpected root id", _rootId, root.getId()); - Collection<UUID> childrenIds = root.getChildrenIds(); - - childrenIds.remove(_portEntryId); - UUID optionsPort = childrenIds.iterator().next(); - return optionsPort; - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/store/MemoryConfigurationEntryStoreTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/store/MemoryConfigurationEntryStoreTest.java deleted file mode 100644 index d7ecaeafd2..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/store/MemoryConfigurationEntryStoreTest.java +++ /dev/null @@ -1,127 +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.configuration.store; - -import java.io.File; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.apache.qpid.server.BrokerOptions; -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfigurationEntryStore; -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.model.Broker; -import org.codehaus.jackson.map.ObjectMapper; - -public class MemoryConfigurationEntryStoreTest extends ConfigurationEntryStoreTestCase -{ - - @Override - protected ConfigurationEntryStore createStore(UUID brokerId, Map<String, Object> brokerAttributes) throws Exception - { - Map<String, Object> broker = new HashMap<String, Object>(); - broker.put(Broker.ID, brokerId); - broker.putAll(brokerAttributes); - ObjectMapper mapper = new ObjectMapper(); - - return new MemoryConfigurationEntryStore(mapper.writeValueAsString(broker), Collections.<String,String>emptyMap()); - } - - @Override - protected void addConfiguration(UUID id, String type, Map<String, Object> attributes) - { - ConfigurationEntryStore store = getStore(); - store.save(new ConfigurationEntry(id, type, attributes, Collections.<UUID> emptySet(), store)); - } - - public void testCreateWithNullLocationAndNullInitialStore() - { - try - { - new MemoryConfigurationEntryStore(null, null, Collections.<String,String>emptyMap()); - fail("Cannot create a memory store without either initial store or path to an initial store file"); - } - catch(IllegalConfigurationException e) - { - // pass - } - } - - public void testCreateWithNullJson() - { - MemoryConfigurationEntryStore store = new MemoryConfigurationEntryStore(null, Collections.<String,String>emptyMap()); - - ConfigurationEntry root = store.getRootEntry(); - assertNotNull("Root entry is not found", root); - } - - public void testOpenInMemoryWithInitialStore() throws Exception - { - UUID brokerId = UUID.randomUUID(); - Map<String, Object> brokerAttributes = new HashMap<String, Object>(); - brokerAttributes.put(Broker.NAME, getTestName()); - MemoryConfigurationEntryStore initialStoreFile = (MemoryConfigurationEntryStore)createStore(brokerId, brokerAttributes); - MemoryConfigurationEntryStore store = new MemoryConfigurationEntryStore(null, initialStoreFile, Collections.<String,String>emptyMap()); - - ConfigurationEntry root = store.getRootEntry(); - assertNotNull("Root entry is not found", root); - assertEquals("Unexpected root entry", brokerId, root.getId()); - Map<String, Object> attributes = root.getAttributes(); - assertNotNull("Attributes not found", attributes); - assertEquals("Unexpected number of attriburtes", 1, attributes.size()); - assertEquals("Unexpected name attribute", getTestName(), attributes.get(Broker.NAME)); - } - - - public void testOpenWithDefaultInitialStore() throws Exception - { - // check whether QPID_HOME JVM system property is set - if (QPID_HOME == null) - { - // set the properties in order to resolve the defaults store settings - setTestSystemProperty("QPID_HOME", TMP_FOLDER); - setTestSystemProperty("QPID_WORK", TMP_FOLDER + File.separator + "work"); - } - MemoryConfigurationEntryStore initialStore = new MemoryConfigurationEntryStore(BrokerOptions.DEFAULT_INITIAL_CONFIG_LOCATION, null, new BrokerOptions().getConfigProperties()); - ConfigurationEntry initialStoreRoot = initialStore.getRootEntry(); - assertNotNull("Initial store root entry is not found", initialStoreRoot); - - MemoryConfigurationEntryStore store = new MemoryConfigurationEntryStore(null, initialStore, Collections.<String,String>emptyMap()); - - ConfigurationEntry root = store.getRootEntry(); - assertNotNull("Root entry is not found", root); - - assertEquals("Unexpected broker attributes", initialStoreRoot.getAttributes(), root.getAttributes()); - assertEquals("Unexpected broker children", initialStoreRoot.getChildrenIds(), root.getChildrenIds()); - } - - public void testGetVersion() - { - assertEquals("Unexpected version", 1, getStore().getVersion()); - } - - public void testGetType() - { - assertEquals("Unexpected type", "memory", getStore().getType()); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/store/StoreConfigurationChangeListenerTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/store/StoreConfigurationChangeListenerTest.java deleted file mode 100644 index c23c4715e8..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/store/StoreConfigurationChangeListenerTest.java +++ /dev/null @@ -1,103 +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.configuration.store; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.any; -import static org.mockito.Mockito.when; - -import java.util.UUID; - -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfigurationEntryStore; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.model.State; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.test.utils.QpidTestCase; - -public class StoreConfigurationChangeListenerTest extends QpidTestCase -{ - private ConfigurationEntryStore _store; - private StoreConfigurationChangeListener _listener; - - protected void setUp() throws Exception - { - super.setUp(); - _store = mock(ConfigurationEntryStore.class); - _listener = new StoreConfigurationChangeListener(_store); - } - - public void testStateChanged() - { - notifyBrokerStarted(); - UUID id = UUID.randomUUID(); - ConfiguredObject object = mock(VirtualHost.class); - when(object.getId()).thenReturn(id); - _listener.stateChanged(object, State.ACTIVE, State.DELETED); - verify(_store).remove(id); - } - - public void testChildAdded() - { - notifyBrokerStarted(); - Broker broker = mock(Broker.class); - VirtualHost child = mock(VirtualHost.class); - _listener.childAdded(broker, child); - verify(_store).save(any(ConfigurationEntry.class), any(ConfigurationEntry.class)); - } - - public void testChildRemoved() - { - notifyBrokerStarted(); - Broker broker = mock(Broker.class); - VirtualHost child = mock(VirtualHost.class); - _listener.childRemoved(broker, child); - verify(_store).save(any(ConfigurationEntry.class)); - } - - public void testAttributeSet() - { - notifyBrokerStarted(); - Broker broker = mock(Broker.class); - _listener.attributeSet(broker, Broker.QUEUE_FLOW_CONTROL_SIZE_BYTES, null, 1); - verify(_store).save(any(ConfigurationEntry.class)); - } - - public void testChildAddedForVirtualHost() - { - notifyBrokerStarted(); - - VirtualHost object = mock(VirtualHost.class); - Queue queue = mock(Queue.class); - _listener.childAdded(object, queue); - verifyNoMoreInteractions(_store); - } - - private void notifyBrokerStarted() - { - Broker broker = mock(Broker.class); - _listener.stateChanged(broker, State.INITIALISING, State.ACTIVE); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/updater/TaskExecutorTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/updater/TaskExecutorTest.java deleted file mode 100644 index cd6302d55b..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/updater/TaskExecutorTest.java +++ /dev/null @@ -1,296 +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.configuration.updater; - -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.Callable; -import java.util.concurrent.CancellationException; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; - -import javax.security.auth.Subject; - -import junit.framework.TestCase; - -import org.apache.qpid.server.logging.LogActor; -import org.apache.qpid.server.logging.NullRootMessageLogger; -import org.apache.qpid.server.logging.actors.CurrentActor; -import org.apache.qpid.server.logging.actors.TestLogActor; -import org.apache.qpid.server.model.State; -import org.apache.qpid.server.security.SecurityManager; - -public class TaskExecutorTest extends TestCase -{ - private TaskExecutor _executor; - - protected void setUp() throws Exception - { - super.setUp(); - _executor = new TaskExecutor(); - } - - protected void tearDown() throws Exception - { - try - { - _executor.stopImmediately(); - } - finally - { - super.tearDown(); - } - } - - public void testGetState() - { - assertEquals("Unxpected initial state", State.INITIALISING, _executor.getState()); - } - - public void testStart() - { - _executor.start(); - assertEquals("Unxpected started state", State.ACTIVE, _executor.getState()); - } - - public void testStopImmediately() throws Exception - { - _executor.start(); - final CountDownLatch submitLatch = new CountDownLatch(2); - final CountDownLatch waitForCallLatch = new CountDownLatch(1); - final BlockingQueue<Exception> submitExceptions = new LinkedBlockingQueue<Exception>(); - - Runnable runnable = new Runnable() - { - @Override - public void run() - { - try - { - Future<?> f = _executor.submit(new NeverEndingCallable(waitForCallLatch)); - submitLatch.countDown(); - f.get(); - } - catch (Exception e) - { - if (e instanceof ExecutionException) - { - e = (Exception) e.getCause(); - } - submitExceptions.add(e); - } - } - }; - new Thread(runnable).start(); - new Thread(runnable).start(); - assertTrue("Tasks have not been submitted", submitLatch.await(1000, TimeUnit.MILLISECONDS)); - assertTrue("The first task has not been triggered", waitForCallLatch.await(1000, TimeUnit.MILLISECONDS)); - - _executor.stopImmediately(); - assertEquals("Unxpected stopped state", State.STOPPED, _executor.getState()); - - Exception e = submitExceptions.poll(1000l, TimeUnit.MILLISECONDS); - assertNotNull("The task execution was not interrupted or cancelled", e); - Exception e2 = submitExceptions.poll(1000l, TimeUnit.MILLISECONDS); - assertNotNull("The task execution was not interrupted or cancelled", e2); - - assertTrue("One of the exceptions should be CancellationException:", e2 instanceof CancellationException - || e instanceof CancellationException); - assertTrue("One of the exceptions should be InterruptedException:", e2 instanceof InterruptedException - || e instanceof InterruptedException); - } - - public void testStop() - { - _executor.start(); - _executor.stop(); - assertEquals("Unxpected stopped state", State.STOPPED, _executor.getState()); - } - - public void testSubmitAndWait() throws Exception - { - _executor.start(); - Object result = _executor.submitAndWait(new Callable<String>() - { - @Override - public String call() throws Exception - { - return "DONE"; - } - }); - assertEquals("Unexpected task execution result", "DONE", result); - } - - public void testSubmitAndWaitInNotAuthorizedContext() - { - _executor.start(); - Object subject = _executor.submitAndWait(new SubjectRetriever()); - assertNull("Subject must be null", subject); - } - - public void testSubmitAndWaitInAuthorizedContext() - { - _executor.start(); - Subject subject = new Subject(); - Object result = Subject.doAs(subject, new PrivilegedAction<Object>() - { - @Override - public Object run() - { - return _executor.submitAndWait(new SubjectRetriever()); - } - }); - assertEquals("Unexpected subject", subject, result); - } - - public void testSubmitAndWaitInAuthorizedContextWithNullSubject() - { - _executor.start(); - Object result = Subject.doAs(null, new PrivilegedAction<Object>() - { - @Override - public Object run() - { - return _executor.submitAndWait(new SubjectRetriever()); - } - }); - assertEquals("Unexpected subject", null, result); - } - - public void testSubmitAndWaitReThrowsOriginalRuntimeException() - { - final RuntimeException exception = new RuntimeException(); - _executor.start(); - try - { - _executor.submitAndWait(new Callable<Void>() - { - - @Override - public Void call() throws Exception - { - throw exception; - } - }); - fail("Exception is expected"); - } - catch (Exception e) - { - assertEquals("Unexpected exception", exception, e); - } - } - - public void testSubmitAndWaitPassesOriginalCheckedException() - { - final Exception exception = new Exception(); - _executor.start(); - try - { - _executor.submitAndWait(new Callable<Void>() - { - - @Override - public Void call() throws Exception - { - throw exception; - } - }); - fail("Exception is expected"); - } - catch (Exception e) - { - assertEquals("Unexpected exception", exception, e.getCause()); - } - } - - public void testSubmitAndWaitCurrentActorAndSecurityManagerSubjectAreRespected() throws Exception - { - _executor.start(); - LogActor actor = new TestLogActor(new NullRootMessageLogger()); - Subject subject = new Subject(); - Subject currentSecurityManagerSubject = SecurityManager.getThreadSubject(); - final AtomicReference<LogActor> taskLogActor = new AtomicReference<LogActor>(); - final AtomicReference<Subject> taskSubject = new AtomicReference<Subject>(); - try - { - CurrentActor.set(actor); - SecurityManager.setThreadSubject(subject); - _executor.submitAndWait(new Callable<Void>() - { - @Override - public Void call() throws Exception - { - taskLogActor.set(CurrentActor.get()); - taskSubject.set(SecurityManager.getThreadSubject()); - return null; - } - }); - } - finally - { - SecurityManager.setThreadSubject(currentSecurityManagerSubject); - CurrentActor.remove(); - } - assertEquals("Unexpected task log actor", actor, taskLogActor.get()); - assertEquals("Unexpected security manager subject", subject, taskSubject.get()); - } - - private class SubjectRetriever implements Callable<Subject> - { - @Override - public Subject call() throws Exception - { - return Subject.getSubject(AccessController.getContext()); - } - } - - private class NeverEndingCallable implements Callable<Void> - { - private CountDownLatch _waitLatch; - - public NeverEndingCallable(CountDownLatch waitLatch) - { - super(); - _waitLatch = waitLatch; - } - - @Override - public Void call() throws Exception - { - if (_waitLatch != null) - { - _waitLatch.countDown(); - } - - // wait forever - synchronized (this) - { - this.wait(); - } - return null; - } - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/DefaultExchangeFactoryTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/DefaultExchangeFactoryTest.java deleted file mode 100644 index 86ae3e6e9c..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/DefaultExchangeFactoryTest.java +++ /dev/null @@ -1,226 +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 java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.UUID; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.plugin.ExchangeType; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.test.utils.QpidTestCase; - -@SuppressWarnings("rawtypes") -public class DefaultExchangeFactoryTest extends QpidTestCase -{ - private DirectExchangeType _directExchangeType; - private TopicExchangeType _topicExchangeType; - private FanoutExchangeType _fanoutExchangeType; - private HeadersExchangeType _headersExchangeType; - - private List<ExchangeType> _stubbedExchangeTypes; - - protected void setUp() throws Exception - { - super.setUp(); - - _directExchangeType = new DirectExchangeType(); - _topicExchangeType = new TopicExchangeType(); - _fanoutExchangeType = new FanoutExchangeType(); - _headersExchangeType = new HeadersExchangeType(); - _stubbedExchangeTypes = new ArrayList<ExchangeType>(); - } - - public void testCreateDefaultExchangeFactory() - { - _stubbedExchangeTypes.add(_directExchangeType); - _stubbedExchangeTypes.add(_topicExchangeType); - _stubbedExchangeTypes.add(_fanoutExchangeType); - _stubbedExchangeTypes.add(_headersExchangeType); - - DefaultExchangeFactory factory = new TestExchangeFactory(); - - Collection<ExchangeType<? extends Exchange>> registeredTypes = factory.getRegisteredTypes(); - assertEquals("Unexpected number of exchange types", _stubbedExchangeTypes.size(), registeredTypes.size()); - assertTrue("Direct exchange type is not found", registeredTypes.contains(_directExchangeType)); - assertTrue("Fanout exchange type is not found", registeredTypes.contains(_fanoutExchangeType)); - assertTrue("Topic exchange type is not found", registeredTypes.contains(_topicExchangeType)); - assertTrue("Headers exchange type is not found", registeredTypes.contains(_headersExchangeType)); - } - - public void testCreateDefaultExchangeFactoryWithoutAllBaseExchangeTypes() - { - try - { - new TestExchangeFactory(); - fail("Cannot create factory without all base classes"); - } - catch (IllegalStateException e) - { - // pass - } - } - - public void testCreateDefaultExchangeFactoryWithoutDireactExchangeType() - { - _stubbedExchangeTypes.add(_topicExchangeType); - _stubbedExchangeTypes.add(_fanoutExchangeType); - _stubbedExchangeTypes.add(_headersExchangeType); - - try - { - new TestExchangeFactory(); - fail("Cannot create factory without all base classes"); - } - catch (IllegalStateException e) - { - assertEquals("Unexpected exception message", "Did not find expected exchange type: " + _directExchangeType.getType(), e.getMessage()); - } - } - - public void testCreateDefaultExchangeFactoryWithoutTopicExchangeType() - { - _stubbedExchangeTypes.add(_directExchangeType); - _stubbedExchangeTypes.add(_fanoutExchangeType); - _stubbedExchangeTypes.add(_headersExchangeType); - - try - { - new TestExchangeFactory(); - fail("Cannot create factory without all base classes"); - } - catch (IllegalStateException e) - { - assertEquals("Unexpected exception message", "Did not find expected exchange type: " + _topicExchangeType.getType(), e.getMessage()); - } - } - - public void testCreateDefaultExchangeFactoryWithoutFanoutExchangeType() - { - _stubbedExchangeTypes.add(_directExchangeType); - _stubbedExchangeTypes.add(_topicExchangeType); - _stubbedExchangeTypes.add(_headersExchangeType); - - try - { - new TestExchangeFactory(); - fail("Cannot create factory without all base classes"); - } - catch (IllegalStateException e) - { - assertEquals("Unexpected exception message", "Did not find expected exchange type: " + _fanoutExchangeType.getType(), e.getMessage()); - } - } - - public void testCreateDefaultExchangeFactoryWithoutHeadersExchangeType() - { - _stubbedExchangeTypes.add(_directExchangeType); - _stubbedExchangeTypes.add(_topicExchangeType); - _stubbedExchangeTypes.add(_fanoutExchangeType); - - try - { - new TestExchangeFactory(); - fail("Cannot create factory without all base classes"); - } - catch (IllegalStateException e) - { - assertEquals("Unexpected exception message", "Did not find expected exchange type: " + _headersExchangeType.getType(), e.getMessage()); - } - } - - public void testCreateDefaultExchangeFactoryWithDuplicateExchangeTypeName() - { - _stubbedExchangeTypes.add(_directExchangeType); - _stubbedExchangeTypes.add(_directExchangeType); - - try - { - new TestExchangeFactory(); - fail("Cannot create factory with duplicate exchange type names"); - } - catch (IllegalStateException e) - { - assertTrue( "Unexpected exception message", e.getMessage().contains("ExchangeType with type name '" - + _directExchangeType.getType() + "' is already registered using class '" - + DirectExchangeType.class.getName())); - } - } - - public void testCreateDefaultExchangeFactoryWithCustomExchangeType() - { - ExchangeType<?> customExchangeType = new ExchangeType<Exchange>() - { - @Override - public String getType() - { - return "my-custom-exchange"; - } - - @Override - public Exchange newInstance(UUID id, VirtualHost host, String name, boolean durable, - boolean autoDelete) throws AMQException - { - return null; - } - - @Override - public String getDefaultExchangeName() - { - return null; - } - }; - - _stubbedExchangeTypes.add(customExchangeType); - _stubbedExchangeTypes.add(_directExchangeType); - _stubbedExchangeTypes.add(_topicExchangeType); - _stubbedExchangeTypes.add(_fanoutExchangeType); - _stubbedExchangeTypes.add(_headersExchangeType); - - DefaultExchangeFactory factory = new TestExchangeFactory(); - - Collection<ExchangeType<? extends Exchange>> registeredTypes = factory.getRegisteredTypes(); - assertEquals("Unexpected number of exchange types", _stubbedExchangeTypes.size(), registeredTypes.size()); - assertTrue("Direct exchange type is not found", registeredTypes.contains(_directExchangeType)); - assertTrue("Fanout exchange type is not found", registeredTypes.contains(_fanoutExchangeType)); - assertTrue("Topic exchange type is not found", registeredTypes.contains(_topicExchangeType)); - assertTrue("Headers exchange type is not found", registeredTypes.contains(_headersExchangeType)); - assertTrue("Custom exchange type is not found", registeredTypes.contains(customExchangeType)); - } - - private final class TestExchangeFactory extends DefaultExchangeFactory - { - private TestExchangeFactory() - { - super(null); - } - - @Override - protected Iterable<ExchangeType> loadExchangeTypes() - { - return _stubbedExchangeTypes; - } - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/FanoutExchangeTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/FanoutExchangeTest.java deleted file mode 100644 index 7335d43b2e..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/FanoutExchangeTest.java +++ /dev/null @@ -1,194 +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 static org.mockito.Matchers.any; -import static org.mockito.Matchers.anySet; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import junit.framework.TestCase; - -import org.apache.qpid.AMQException; -import org.apache.qpid.AMQInternalException; -import org.apache.qpid.AMQSecurityException; -import org.apache.qpid.common.AMQPFilterTypes; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.server.logging.LogActor; -import org.apache.qpid.server.logging.actors.CurrentActor; -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.message.InboundMessage; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.BaseQueue; -import org.apache.qpid.server.security.SecurityManager; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -public class FanoutExchangeTest extends TestCase -{ - private FanoutExchange _exchange; - private VirtualHost _virtualHost; - - public void setUp() throws AMQException - { - CurrentActor.setDefault(mock(LogActor.class)); - - _exchange = new FanoutExchange(); - _virtualHost = mock(VirtualHost.class); - SecurityManager securityManager = mock(SecurityManager.class); - when(_virtualHost.getSecurityManager()).thenReturn(securityManager); - when(securityManager.authoriseBind(any(Exchange.class), any(AMQQueue.class), anyString())).thenReturn(true); - when(securityManager.authoriseUnbind(any(Exchange.class), anyString(), any(AMQQueue.class))).thenReturn(true); - - _exchange.initialise(UUID.randomUUID(), _virtualHost, "test", false, false); - } - - public void testIsBoundStringMapAMQQueueWhenQueueIsNull() - { - assertFalse("calling isBound(AMQShortString,FieldTable,AMQQueue) with null queue should return false", - _exchange.isBound((String) null, (Map) null, (AMQQueue) null)); - } - - public void testIsBoundStringAMQQueueWhenQueueIsNull() - { - assertFalse("calling isBound(AMQShortString,AMQQueue) with null queue should return false", - _exchange.isBound((String) null, (AMQQueue) null)); - } - - public void testIsBoundAMQQueueWhenQueueIsNull() - { - assertFalse("calling isBound(AMQQueue) with null queue should return false", _exchange.isBound((AMQQueue) null)); - } - - public void testIsBoundStringMapAMQQueue() throws AMQSecurityException, AMQInternalException - { - AMQQueue queue = bindQueue(); - assertTrue("Should return true for a bound queue", - _exchange.isBound("matters", null, queue)); - } - - public void testIsBoundStringAMQQueue() throws AMQSecurityException, AMQInternalException - { - AMQQueue queue = bindQueue(); - assertTrue("Should return true for a bound queue", - _exchange.isBound("matters", queue)); - } - - public void testIsBoundAMQQueue() throws AMQSecurityException, AMQInternalException - { - AMQQueue queue = bindQueue(); - assertTrue("Should return true for a bound queue", - _exchange.isBound(queue)); - } - - private AMQQueue bindQueue() throws AMQSecurityException, AMQInternalException - { - AMQQueue queue = mockQueue(); - _exchange.addBinding("matters", queue, null); - return queue; - } - - private AMQQueue mockQueue() - { - AMQQueue queue = mock(AMQQueue.class); - when(queue.getVirtualHost()).thenReturn(_virtualHost); - return queue; - } - - public void testRoutingWithSelectors() throws Exception - { - AMQQueue queue1 = mockQueue(); - AMQQueue queue2 = mockQueue(); - - _exchange.addBinding("key",queue1, null); - _exchange.addBinding("key",queue2, null); - - - List<? extends BaseQueue> result = _exchange.route(mockMessage(true)); - - assertEquals("Expected message to be routed to both queues", 2, result.size()); - assertTrue("Expected queue1 to be routed to", result.contains(queue1)); - assertTrue("Expected queue2 to be routed to", result.contains(queue2)); - - _exchange.addBinding("key2",queue2, Collections.singletonMap(AMQPFilterTypes.JMS_SELECTOR.toString(),(Object)"select = True")); - - - result = _exchange.route(mockMessage(true)); - - assertEquals("Expected message to be routed to both queues", 2, result.size()); - assertTrue("Expected queue1 to be routed to", result.contains(queue1)); - assertTrue("Expected queue2 to be routed to", result.contains(queue2)); - - _exchange.removeBinding("key",queue2,null); - - result = _exchange.route(mockMessage(true)); - - assertEquals("Expected message to be routed to both queues", 2, result.size()); - assertTrue("Expected queue1 to be routed to", result.contains(queue1)); - assertTrue("Expected queue2 to be routed to", result.contains(queue2)); - - - result = _exchange.route(mockMessage(false)); - - assertEquals("Expected message to be routed to queue1 only", 1, result.size()); - assertTrue("Expected queue1 to be routed to", result.contains(queue1)); - assertFalse("Expected queue2 not to be routed to", result.contains(queue2)); - - _exchange.addBinding("key",queue2, Collections.singletonMap(AMQPFilterTypes.JMS_SELECTOR.toString(),(Object)"select = False")); - - - result = _exchange.route(mockMessage(false)); - assertEquals("Expected message to be routed to both queues", 2, result.size()); - assertTrue("Expected queue1 to be routed to", result.contains(queue1)); - assertTrue("Expected queue2 to be routed to", result.contains(queue2)); - - - } - - private InboundMessage mockMessage(boolean val) - { - final AMQMessageHeader header = mock(AMQMessageHeader.class); - when(header.containsHeader("select")).thenReturn(true); - when(header.getHeader("select")).thenReturn(val); - when(header.getHeaderNames()).thenReturn(Collections.singleton("select")); - when(header.containsHeaders(anySet())).then(new Answer<Object>() - { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable - { - final Set names = (Set) invocation.getArguments()[0]; - return names.size() == 1 && names.contains("select"); - - } - }); - final InboundMessage inboundMessage = mock(InboundMessage.class); - when(inboundMessage.getMessageHeader()).thenReturn(header); - return inboundMessage; - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersBindingTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersBindingTest.java deleted file mode 100644 index 833df34fd8..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersBindingTest.java +++ /dev/null @@ -1,334 +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 java.util.Collection; -import junit.framework.TestCase; - -import org.apache.qpid.server.binding.Binding; -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.queue.MockAMQQueue; - -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -/** - */ -public class HeadersBindingTest extends TestCase -{ - - private class MockHeader implements AMQMessageHeader - { - - private final Map<String, Object> _headers = new HashMap<String, Object>(); - - public String getCorrelationId() - { - return null; - } - - public long getExpiration() - { - return 0; - } - - public String getUserId() - { - return null; - } - - public String getAppId() - { - return null; - } - - public String getMessageId() - { - return null; - } - - public String getMimeType() - { - return null; - } - - public String getEncoding() - { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - public byte getPriority() - { - return 0; - } - - public long getTimestamp() - { - return 0; - } - - public String getType() - { - return null; - } - - public String getReplyTo() - { - return null; - } - - public String getReplyToExchange() - { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - public String getReplyToRoutingKey() - { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - public Object getHeader(String name) - { - return _headers.get(name); - } - - public boolean containsHeaders(Set<String> names) - { - return _headers.keySet().containsAll(names); - } - - @Override - public Collection<String> getHeaderNames() - { - return _headers.keySet(); - } - - public boolean containsHeader(String name) - { - return _headers.containsKey(name); - } - - public void setString(String key, String value) - { - setObject(key,value); - } - - public void setObject(String key, Object value) - { - _headers.put(key,value); - } - } - - private Map<String,Object> bindHeaders = new HashMap<String,Object>(); - 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; - } - - public void testDefault_1() - { - bindHeaders.put("A", "Value of A"); - - matchHeaders.setString("A", "Value of A"); - - Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); - assertTrue(new HeadersBinding(b).matches(matchHeaders)); - } - - public void testDefault_2() - { - bindHeaders.put("A", "Value of A"); - - matchHeaders.setString("A", "Value of A"); - matchHeaders.setString("B", "Value of B"); - - Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); - assertTrue(new HeadersBinding(b).matches(matchHeaders)); - } - - public void testDefault_3() - { - bindHeaders.put("A", "Value of A"); - - matchHeaders.setString("A", "Altered value of A"); - - Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); - assertFalse(new HeadersBinding(b).matches(matchHeaders)); - } - - public void testAll_1() - { - bindHeaders.put("X-match", "all"); - bindHeaders.put("A", "Value of A"); - - matchHeaders.setString("A", "Value of A"); - - Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); - assertTrue(new HeadersBinding(b).matches(matchHeaders)); - } - - public void testAll_2() - { - bindHeaders.put("X-match", "all"); - bindHeaders.put("A", "Value of A"); - bindHeaders.put("B", "Value of B"); - - matchHeaders.setString("A", "Value of A"); - - Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); - assertFalse(new HeadersBinding(b).matches(matchHeaders)); - } - - public void testAll_3() - { - bindHeaders.put("X-match", "all"); - bindHeaders.put("A", "Value of A"); - bindHeaders.put("B", "Value of B"); - - matchHeaders.setString("A", "Value of A"); - matchHeaders.setString("B", "Value of B"); - - Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); - assertTrue(new HeadersBinding(b).matches(matchHeaders)); - } - - public void testAll_4() - { - bindHeaders.put("X-match", "all"); - bindHeaders.put("A", "Value of A"); - bindHeaders.put("B", "Value of B"); - - matchHeaders.setString("A", "Value of A"); - matchHeaders.setString("B", "Value of B"); - matchHeaders.setString("C", "Value of C"); - - Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); - assertTrue(new HeadersBinding(b).matches(matchHeaders)); - } - - public void testAll_5() - { - bindHeaders.put("X-match", "all"); - bindHeaders.put("A", "Value of A"); - bindHeaders.put("B", "Value of B"); - - matchHeaders.setString("A", "Value of A"); - matchHeaders.setString("B", "Altered value of B"); - matchHeaders.setString("C", "Value of C"); - - Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); - assertFalse(new HeadersBinding(b).matches(matchHeaders)); - } - - public void testAny_1() - { - bindHeaders.put("X-match", "any"); - bindHeaders.put("A", "Value of A"); - - matchHeaders.setString("A", "Value of A"); - - Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); - assertTrue(new HeadersBinding(b).matches(matchHeaders)); - } - - public void testAny_2() - { - bindHeaders.put("X-match", "any"); - bindHeaders.put("A", "Value of A"); - bindHeaders.put("B", "Value of B"); - - matchHeaders.setString("A", "Value of A"); - - Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); - assertTrue(new HeadersBinding(b).matches(matchHeaders)); - } - - public void testAny_3() - { - bindHeaders.put("X-match", "any"); - bindHeaders.put("A", "Value of A"); - bindHeaders.put("B", "Value of B"); - - matchHeaders.setString("A", "Value of A"); - matchHeaders.setString("B", "Value of B"); - - Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); - assertTrue(new HeadersBinding(b).matches(matchHeaders)); - } - - public void testAny_4() - { - bindHeaders.put("X-match", "any"); - bindHeaders.put("A", "Value of A"); - bindHeaders.put("B", "Value of B"); - - matchHeaders.setString("A", "Value of A"); - matchHeaders.setString("B", "Value of B"); - matchHeaders.setString("C", "Value of C"); - - Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); - assertTrue(new HeadersBinding(b).matches(matchHeaders)); - } - - public void testAny_5() - { - bindHeaders.put("X-match", "any"); - bindHeaders.put("A", "Value of A"); - bindHeaders.put("B", "Value of B"); - - matchHeaders.setString("A", "Value of A"); - matchHeaders.setString("B", "Altered value of B"); - matchHeaders.setString("C", "Value of C"); - - Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); - assertTrue(new HeadersBinding(b).matches(matchHeaders)); - } - - public void testAny_6() - { - bindHeaders.put("X-match", "any"); - bindHeaders.put("A", "Value of A"); - bindHeaders.put("B", "Value of B"); - - matchHeaders.setString("A", "Altered value of A"); - matchHeaders.setString("B", "Altered value of B"); - matchHeaders.setString("C", "Value of C"); - - Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); - assertFalse(new HeadersBinding(b).matches(matchHeaders)); - } - - public static junit.framework.Test suite() - { - return new junit.framework.TestSuite(HeadersBindingTest.class); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersExchangeTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersExchangeTest.java deleted file mode 100644 index 0f1ab65244..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersExchangeTest.java +++ /dev/null @@ -1,252 +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 java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import junit.framework.TestCase; -import org.apache.qpid.AMQInternalException; -import org.apache.qpid.AMQSecurityException; -import org.apache.qpid.common.AMQPFilterTypes; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.logging.LogActor; -import org.apache.qpid.server.logging.actors.CurrentActor; -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.message.InboundMessage; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.BaseQueue; -import org.apache.qpid.server.security.SecurityManager; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anySet; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class HeadersExchangeTest extends TestCase -{ - private HeadersExchange _exchange; - private VirtualHost _virtualHost; - - @Override - public void setUp() throws Exception - { - super.setUp(); - - CurrentActor.setDefault(mock(LogActor.class)); - _exchange = new HeadersExchange(); - _virtualHost = mock(VirtualHost.class); - SecurityManager securityManager = mock(SecurityManager.class); - when(_virtualHost.getSecurityManager()).thenReturn(securityManager); - when(securityManager.authoriseBind(any(Exchange.class), any(AMQQueue.class), anyString())).thenReturn(true); - when(securityManager.authoriseUnbind(any(Exchange.class), anyString(), any(AMQQueue.class))).thenReturn(true); - - _exchange.initialise(UUID.randomUUID(), _virtualHost, "test", false, false); - - } - - protected void routeAndTest(InboundMessage msg, AMQQueue... expected) throws Exception - { - List<? extends BaseQueue> results = _exchange.route(msg); - List<? extends BaseQueue> unexpected = new ArrayList<BaseQueue>(results); - unexpected.removeAll(Arrays.asList(expected)); - assertTrue("Message delivered to unexpected queues: " + unexpected, unexpected.isEmpty()); - List<? extends BaseQueue> missing = new ArrayList<BaseQueue>(Arrays.asList(expected)); - missing.removeAll(results); - assertTrue("Message not delivered to expected queues: " + missing, missing.isEmpty()); - assertTrue("Duplicates " + results, results.size()==(new HashSet<BaseQueue>(results)).size()); - } - - - private AMQQueue createAndBind(final String name, String... arguments) - throws Exception - { - return createAndBind(name, getArgsMapFromStrings(arguments)); - } - - private Map<String, Object> getArgsMapFromStrings(String... arguments) - { - Map<String, Object> map = new HashMap<String,Object>(); - - for(String arg : arguments) - { - if(arg.contains("=")) - { - String[] keyValue = arg.split("=",2); - map.put(keyValue[0],keyValue[1]); - } - else - { - map.put(arg,null); - } - } - return map; - } - - private AMQQueue createAndBind(final String name, Map<String, Object> arguments) - throws Exception - { - AMQQueue q = create(name); - bind(name, arguments, q); - return q; - } - - private void bind(String bindingKey, Map<String, Object> arguments, AMQQueue q) - throws AMQSecurityException, AMQInternalException - { - _exchange.addBinding(bindingKey,q,arguments); - } - - private AMQQueue create(String name) - { - AMQQueue q = mock(AMQQueue.class); - when(q.toString()).thenReturn(name); - when(q.getVirtualHost()).thenReturn(_virtualHost); - return q; - } - - - public void testSimple() throws Exception - { - AMQQueue q1 = createAndBind("Q1", "F0000"); - AMQQueue q2 = createAndBind("Q2", "F0000=Aardvark"); - AMQQueue q3 = createAndBind("Q3", "F0001"); - AMQQueue q4 = createAndBind("Q4", "F0001=Bear"); - AMQQueue q5 = createAndBind("Q5", "F0000", "F0001"); - AMQQueue q6 = createAndBind("Q6", "F0000=Aardvark", "F0001=Bear"); - AMQQueue q7 = createAndBind("Q7", "F0000", "F0001=Bear"); - AMQQueue q8 = createAndBind("Q8", "F0000=Aardvark", "F0001"); - - routeAndTest(mockMessage(getArgsMapFromStrings("F0000")), q1); - routeAndTest(mockMessage(getArgsMapFromStrings("F0000=Aardvark")), q1, q2); - routeAndTest(mockMessage(getArgsMapFromStrings("F0000=Aardvark", "F0001")), q1, q2, q3, q5, q8); - routeAndTest(mockMessage(getArgsMapFromStrings("F0000", "F0001=Bear")), q1, q3, q4, q5, q7); - routeAndTest(mockMessage(getArgsMapFromStrings("F0000=Aardvark", "F0001=Bear")), - q1, q2, q3, q4, q5, q6, q7, q8); - routeAndTest(mockMessage(getArgsMapFromStrings("F0002"))); - - } - - public void testAny() throws Exception - { - AMQQueue q1 = createAndBind("Q1", "F0000", "F0001", "X-match=any"); - AMQQueue q2 = createAndBind("Q2", "F0000=Aardvark", "F0001=Bear", "X-match=any"); - AMQQueue q3 = createAndBind("Q3", "F0000", "F0001=Bear", "X-match=any"); - AMQQueue q4 = createAndBind("Q4", "F0000=Aardvark", "F0001", "X-match=any"); - AMQQueue q5 = createAndBind("Q5", "F0000=Apple", "F0001", "X-match=any"); - - routeAndTest(mockMessage(getArgsMapFromStrings("F0000")), q1, q3); - routeAndTest(mockMessage(getArgsMapFromStrings("F0000=Aardvark")), q1, q2, q3, q4); - routeAndTest(mockMessage(getArgsMapFromStrings("F0000=Aardvark", "F0001")), q1, q2, q3, q4, q5); - routeAndTest(mockMessage(getArgsMapFromStrings("F0000", "F0001=Bear")), q1, q2, q3, q4, q5); - routeAndTest(mockMessage(getArgsMapFromStrings("F0000=Aardvark", "F0001=Bear")), q1, q2, q3, q4, q5); - routeAndTest(mockMessage(getArgsMapFromStrings("F0002"))); - } - - public void testOnUnbind() throws Exception - { - AMQQueue q1 = createAndBind("Q1", "F0000"); - AMQQueue q2 = createAndBind("Q2", "F0000=Aardvark"); - AMQQueue q3 = createAndBind("Q3", "F0001"); - - routeAndTest(mockMessage(getArgsMapFromStrings("F0000")), q1); - routeAndTest(mockMessage(getArgsMapFromStrings("F0000=Aardvark")), q1, q2); - routeAndTest(mockMessage(getArgsMapFromStrings("F0001")), q3); - - _exchange.removeBinding("Q1",q1,getArgsMapFromStrings("F0000")); - - routeAndTest(mockMessage(getArgsMapFromStrings("F0000"))); - routeAndTest(mockMessage(getArgsMapFromStrings("F0000=Aardvark")), q2); - } - - - public void testWithSelectors() throws Exception - { - AMQQueue q1 = create("Q1"); - AMQQueue q2 = create("Q2"); - bind("q1",getArgsMapFromStrings("F"), q1); - bind("q1select",getArgsMapFromStrings("F", AMQPFilterTypes.JMS_SELECTOR.toString()+"=F='1'"), q1); - bind("q2",getArgsMapFromStrings("F=1"), q2); - - routeAndTest(mockMessage(getArgsMapFromStrings("F")),q1); - - routeAndTest(mockMessage(getArgsMapFromStrings("F=1")),q1,q2); - - - AMQQueue q3 = create("Q3"); - bind("q3select",getArgsMapFromStrings("F", AMQPFilterTypes.JMS_SELECTOR.toString()+"=F='1'"), q3); - routeAndTest(mockMessage(getArgsMapFromStrings("F=1")),q1,q2,q3); - routeAndTest(mockMessage(getArgsMapFromStrings("F=2")),q1); - bind("q3select2",getArgsMapFromStrings("F", AMQPFilterTypes.JMS_SELECTOR.toString()+"=F='2'"), q3); - - routeAndTest(mockMessage(getArgsMapFromStrings("F=2")),q1,q3); - - } - - private InboundMessage mockMessage(final Map<String, Object> headerValues) - { - final AMQMessageHeader header = mock(AMQMessageHeader.class); - when(header.containsHeader(anyString())).then(new Answer<Boolean>() - { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable - { - return headerValues.containsKey((String) invocation.getArguments()[0]); - } - }); - when(header.getHeader(anyString())).then(new Answer<Object>() - { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable - { - return headerValues.get((String) invocation.getArguments()[0]); - } - }); - when(header.getHeaderNames()).thenReturn(headerValues.keySet()); - when(header.containsHeaders(anySet())).then(new Answer<Boolean>() - { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable - { - final Set names = (Set) invocation.getArguments()[0]; - return headerValues.keySet().containsAll(names); - - } - }); - final InboundMessage inboundMessage = mock(InboundMessage.class); - when(inboundMessage.getMessageHeader()).thenReturn(header); - return inboundMessage; - } - - public static junit.framework.Test suite() - { - return new junit.framework.TestSuite(HeadersExchangeTest.class); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/TopicExchangeTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/TopicExchangeTest.java deleted file mode 100644 index a84f5e1ecb..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/TopicExchangeTest.java +++ /dev/null @@ -1,361 +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 java.util.List; -import junit.framework.Assert; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.binding.Binding; -import org.apache.qpid.server.message.InboundMessage; -import org.apache.qpid.server.message.MessageReference; -import org.apache.qpid.server.message.ServerMessage; -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.BaseQueue; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.test.utils.QpidTestCase; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class TopicExchangeTest extends QpidTestCase -{ - - private TopicExchange _exchange; - private VirtualHost _vhost; - - - @Override - public void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - _exchange = new TopicExchange(); - _vhost = BrokerTestHelper.createVirtualHost(getName()); - } - - @Override - public void tearDown() throws Exception - { - try - { - if (_vhost != null) - { - _vhost.close(); - } - } - finally - { - BrokerTestHelper.tearDown(); - super.tearDown(); - } - } - - public void testNoRoute() throws AMQException - { - AMQQueue queue = _vhost.createQueue(UUIDGenerator.generateRandomUUID(), "a*#b", false, null, false, false, - false, null); - _exchange.registerQueue(new Binding(null, "a.*.#.b",queue, _exchange, null)); - - - routeMessage("a.b", 0l); - - Assert.assertEquals(0, queue.getMessageCount()); - } - - public void testDirectMatch() throws AMQException - { - AMQQueue queue = _vhost.createQueue(UUIDGenerator.generateRandomUUID(), "ab", false, null, false, false, - false, null); - _exchange.registerQueue(new Binding(null, "a.b",queue, _exchange, null)); - - - routeMessage("a.b",0l); - - Assert.assertEquals(1, queue.getMessageCount()); - - Assert.assertEquals("Wrong message received", 0l, queue.getMessagesOnTheQueue().get(0).getMessage().getMessageNumber()); - - queue.deleteMessageFromTop(); - Assert.assertEquals(0, queue.getMessageCount()); - - int queueCount = routeMessage("a.c",1l); - Assert.assertEquals("Message should not route to any queues", 0, queueCount); - - Assert.assertEquals(0, queue.getMessageCount()); - } - - - public void testStarMatch() throws AMQException - { - AMQQueue queue = _vhost.createQueue(UUIDGenerator.generateRandomUUID(), "a*", false, null, false, false, false, null); - _exchange.registerQueue(new Binding(null, "a.*",queue, _exchange, null)); - - - routeMessage("a.b",0l); - - Assert.assertEquals(1, queue.getMessageCount()); - - Assert.assertEquals("Wrong message received", 0l, queue.getMessagesOnTheQueue().get(0).getMessage().getMessageNumber()); - - queue.deleteMessageFromTop(); - Assert.assertEquals(0, queue.getMessageCount()); - - - routeMessage("a.c",1l); - - Assert.assertEquals(1, queue.getMessageCount()); - - Assert.assertEquals("Wrong message received", 1l, queue.getMessagesOnTheQueue().get(0).getMessage().getMessageNumber()); - - queue.deleteMessageFromTop(); - Assert.assertEquals(0, queue.getMessageCount()); - - int queueCount = routeMessage("a",2l); - Assert.assertEquals("Message should not route to any queues", 0, queueCount); - - Assert.assertEquals(0, queue.getMessageCount()); - } - - public void testHashMatch() throws AMQException - { - AMQQueue queue = _vhost.createQueue(UUIDGenerator.generateRandomUUID(), "a#", false, null, false, false, false, null); - _exchange.registerQueue(new Binding(null, "a.#",queue, _exchange, null)); - - - routeMessage("a.b.c",0l); - - Assert.assertEquals(1, queue.getMessageCount()); - - Assert.assertEquals("Wrong message received", 0l, queue.getMessagesOnTheQueue().get(0).getMessage().getMessageNumber()); - - queue.deleteMessageFromTop(); - Assert.assertEquals(0, queue.getMessageCount()); - - routeMessage("a.b",1l); - - Assert.assertEquals(1, queue.getMessageCount()); - - Assert.assertEquals("Wrong message received", 1l, queue.getMessagesOnTheQueue().get(0).getMessage().getMessageNumber()); - - queue.deleteMessageFromTop(); - Assert.assertEquals(0, queue.getMessageCount()); - - - routeMessage("a.c",2l); - - Assert.assertEquals(1, queue.getMessageCount()); - - Assert.assertEquals("Wrong message received", 2l, queue.getMessagesOnTheQueue().get(0).getMessage().getMessageNumber()); - - queue.deleteMessageFromTop(); - Assert.assertEquals(0, queue.getMessageCount()); - - routeMessage("a",3l); - - Assert.assertEquals(1, queue.getMessageCount()); - - Assert.assertEquals("Wrong message received", 3l, queue.getMessagesOnTheQueue().get(0).getMessage().getMessageNumber()); - - queue.deleteMessageFromTop(); - Assert.assertEquals(0, queue.getMessageCount()); - - - int queueCount = routeMessage("b", 4l); - Assert.assertEquals("Message should not route to any queues", 0, queueCount); - - Assert.assertEquals(0, queue.getMessageCount()); - } - - - public void testMidHash() throws AMQException - { - AMQQueue queue = _vhost.createQueue(UUIDGenerator.generateRandomUUID(), "a", false, null, false, false, - false, null); - _exchange.registerQueue(new Binding(null, "a.*.#.b",queue, _exchange, null)); - - routeMessage("a.c.d.b",0l); - - Assert.assertEquals(1, queue.getMessageCount()); - - Assert.assertEquals("Wrong message received", 0l, queue.getMessagesOnTheQueue().get(0).getMessage().getMessageNumber()); - - queue.deleteMessageFromTop(); - Assert.assertEquals(0, queue.getMessageCount()); - - routeMessage("a.c.b",1l); - - Assert.assertEquals(1, queue.getMessageCount()); - - Assert.assertEquals("Wrong message received", 1l, queue.getMessagesOnTheQueue().get(0).getMessage().getMessageNumber()); - - queue.deleteMessageFromTop(); - Assert.assertEquals(0, queue.getMessageCount()); - - } - - public void testMatchafterHash() throws AMQException - { - AMQQueue queue = _vhost.createQueue(UUIDGenerator.generateRandomUUID(), "a#", false, null, false, false, - false, null); - _exchange.registerQueue(new Binding(null, "a.*.#.b.c",queue, _exchange, null)); - - - int queueCount = routeMessage("a.c.b.b",0l); - Assert.assertEquals("Message should not route to any queues", 0, queueCount); - - Assert.assertEquals(0, queue.getMessageCount()); - - - routeMessage("a.a.b.c",1l); - - Assert.assertEquals(1, queue.getMessageCount()); - - Assert.assertEquals("Wrong message received", 1l, queue.getMessagesOnTheQueue().get(0).getMessage().getMessageNumber()); - - queue.deleteMessageFromTop(); - Assert.assertEquals(0, queue.getMessageCount()); - - queueCount = routeMessage("a.b.c.b",2l); - Assert.assertEquals("Message should not route to any queues", 0, queueCount); - - Assert.assertEquals(0, queue.getMessageCount()); - - routeMessage("a.b.c.b.c",3l); - - Assert.assertEquals(1, queue.getMessageCount()); - - Assert.assertEquals("Wrong message received", 3l, queue.getMessagesOnTheQueue().get(0).getMessage().getMessageNumber()); - - queue.deleteMessageFromTop(); - Assert.assertEquals(0, queue.getMessageCount()); - - } - - - public void testHashAfterHash() throws AMQException - { - AMQQueue queue = _vhost.createQueue(UUIDGenerator.generateRandomUUID(), "a#", false, null, false, false, - false, null); - _exchange.registerQueue(new Binding(null, "a.*.#.b.c.#.d",queue, _exchange, null)); - - int queueCount = routeMessage("a.c.b.b.c",0l); - Assert.assertEquals("Message should not route to any queues", 0, queueCount); - - Assert.assertEquals(0, queue.getMessageCount()); - - routeMessage("a.a.b.c.d",1l); - - Assert.assertEquals(1, queue.getMessageCount()); - - Assert.assertEquals("Wrong message received", 1l, queue.getMessagesOnTheQueue().get(0).getMessage().getMessageNumber()); - - queue.deleteMessageFromTop(); - Assert.assertEquals(0, queue.getMessageCount()); - - } - - public void testHashHash() throws AMQException - { - AMQQueue queue = _vhost.createQueue(UUIDGenerator.generateRandomUUID(), "a#", false, null, false, false, - false, null); - _exchange.registerQueue(new Binding(null, "a.#.*.#.d",queue, _exchange, null)); - - int queueCount = routeMessage("a.c.b.b.c",0l); - Assert.assertEquals("Message should not route to any queues", 0, queueCount); - - Assert.assertEquals(0, queue.getMessageCount()); - - routeMessage("a.a.b.c.d",1l); - - Assert.assertEquals(1, queue.getMessageCount()); - - Assert.assertEquals("Wrong message received", 1l, queue.getMessagesOnTheQueue().get(0).getMessage().getMessageNumber()); - - queue.deleteMessageFromTop(); - Assert.assertEquals(0, queue.getMessageCount()); - - } - - public void testSubMatchFails() throws AMQException - { - AMQQueue queue = _vhost.createQueue(UUIDGenerator.generateRandomUUID(), "a", false, null, false, false, - false, null); - _exchange.registerQueue(new Binding(null, "a.b.c.d",queue, _exchange, null)); - - int queueCount = routeMessage("a.b.c",0l); - Assert.assertEquals("Message should not route to any queues", 0, queueCount); - - Assert.assertEquals(0, queue.getMessageCount()); - - } - - private int routeMessage(String routingKey, long messageNumber) throws AMQException - { - InboundMessage inboundMessage = mock(InboundMessage.class); - when(inboundMessage.getRoutingKey()).thenReturn(routingKey); - List<? extends BaseQueue> queues = _exchange.route(inboundMessage); - ServerMessage message = mock(ServerMessage.class); - MessageReference ref = mock(MessageReference.class); - when(ref.getMessage()).thenReturn(message); - when(message.newReference()).thenReturn(ref); - when(message.getMessageNumber()).thenReturn(messageNumber); - for(BaseQueue q : queues) - { - q.enqueue(message); - } - - return queues.size(); - } - - public void testMoreRouting() throws AMQException - { - AMQQueue queue = _vhost.createQueue(UUIDGenerator.generateRandomUUID(), "a", false, null, false, false, - false, null); - _exchange.registerQueue(new Binding(null, "a.b",queue, _exchange, null)); - - - int queueCount = routeMessage("a.b.c",0l); - Assert.assertEquals("Message should not route to any queues", 0, queueCount); - - Assert.assertEquals(0, queue.getMessageCount()); - - } - - public void testMoreQueue() throws AMQException - { - AMQQueue queue = _vhost.createQueue(UUIDGenerator.generateRandomUUID(), "a", false, null, false, false, - false, null); - _exchange.registerQueue(new Binding(null, "a.b",queue, _exchange, null)); - - - int queueCount = routeMessage("a",0l); - Assert.assertEquals("Message should not route to any queues", 0, queueCount); - - Assert.assertEquals(0, queue.getMessageCount()); - - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/filter/JMSSelectorFilterTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/filter/JMSSelectorFilterTest.java deleted file mode 100644 index 91002edfc6..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/filter/JMSSelectorFilterTest.java +++ /dev/null @@ -1,56 +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.filter; - -import junit.framework.TestCase; - -public class JMSSelectorFilterTest extends TestCase -{ - public void testEqualsAndHashCodeUsingSelectorString() throws Exception - { - final String selectorString = "1 = 1"; - - JMSSelectorFilter filter1 = new JMSSelectorFilter(new String(selectorString)); - JMSSelectorFilter filter2 = new JMSSelectorFilter(new String(selectorString)); - - assertEquals(filter1 + " should equal itself", filter1, filter1); - assertFalse(filter1 + " should not equal null", filter1.equals(null)); - assertEqualsAndHashcodeMatch(filter1, filter2); - - JMSSelectorFilter differentFilter = new JMSSelectorFilter("2 = 2"); - assertNotEqual(filter1, differentFilter); - } - - private void assertEqualsAndHashcodeMatch(JMSSelectorFilter filter1, JMSSelectorFilter filter2) - { - String message = filter1 + " and " + filter2 + " should be equal"; - - assertEquals(message, filter1, filter2); - assertEquals(message, filter2, filter1); - - assertEquals("Hashcodes of " + filter1 + " and " + filter2 + " should be equal", - filter1.hashCode(), filter2.hashCode()); - } - - private void assertNotEqual(JMSSelectorFilter filter, JMSSelectorFilter differentFilter) - { - assertFalse(filter.equals(differentFilter)); - assertFalse(differentFilter.equals(filter)); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/Log4jMessageLoggerTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/Log4jMessageLoggerTest.java deleted file mode 100644 index e2a6a56ee2..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/Log4jMessageLoggerTest.java +++ /dev/null @@ -1,271 +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; - -import junit.framework.TestCase; -import org.apache.log4j.AppenderSkeleton; -import org.apache.log4j.Level; -import org.apache.log4j.Logger; -import org.apache.log4j.spi.LoggingEvent; - -import org.apache.qpid.server.logging.actors.BrokerActor; - -import java.io.IOException; -import java.util.LinkedList; -import java.util.List; - -/** Test that the Log4jMessageLogger defaults behave as expected */ -public class Log4jMessageLoggerTest extends TestCase -{ - private Level _rootLevel; - private Log4jTestAppender _appender; - - @Override - public void setUp() throws IOException - { - // Setup a file for logging - _appender = new Log4jTestAppender(); - - Logger root = Logger.getRootLogger(); - root.addAppender(_appender); - - _rootLevel = Logger.getRootLogger().getLevel(); - if (_rootLevel != Level.INFO) - { - root.setLevel(Level.INFO); - root.warn("Root Logger set to:" + _rootLevel + " Resetting to INFO for test."); - } - root.warn("Adding Test Appender:" + _appender); - } - - @Override - public void tearDown() - { - Logger root = Logger.getRootLogger(); - root.warn("Removing Test Appender:" + _appender); - root.warn("Resetting Root Level to : " + _rootLevel); - - Logger.getRootLogger().setLevel(_rootLevel); - - Logger.getRootLogger().removeAppender(_appender); - - //Call close on our appender. This will clear the log messages - // from Memory - _appender.close(); - } - - /** - * Verify that the Log4jMessageLogger successfully logs a message. - */ - public void testLoggedMessage() - { - Log4jMessageLogger msgLogger = new Log4jMessageLogger(); - assertTrue("Expected message logger to be enabled", msgLogger.isEnabled()); - - testLoggedMessage(msgLogger, true, getName()); - } - - /** - * Verify that for the given Log4jMessageLogger, after generating a message for the given - * log hierarchy that the outcome is as expected. - */ - private String testLoggedMessage(Log4jMessageLogger logger, boolean logExpected, String hierarchy) - { - //Create Message for test - String message = "testDefaults"; - - // Log the message - logger.rawMessage(message, hierarchy); - - if(logExpected) - { - verifyLogPresent(message); - } - else - { - verifyNoLog(message); - } - - return message; - } - - /** - * Test that specifying different log hierarchies to be used works as expected. - * <p/> - * Test this by using one hierarchy and verifying it succeeds, then disabling it and - * confirming this takes effect, and finally that using another hierarchy still succeeds. - */ - public void testMultipleHierarchyUsage() - { - String loggerName1 = getName() + ".TestLogger1"; - String loggerName2 = getName() + ".TestLogger2"; - - // Create a message logger to test - Log4jMessageLogger msgLogger = new Log4jMessageLogger(); - assertTrue("Expected message logger to be enabled", msgLogger.isEnabled()); - - //verify that using this hierarchy the message gets logged ok - String message = testLoggedMessage(msgLogger, true, loggerName1); - - //now disable that hierarchy in log4j - Logger.getLogger(loggerName1).setLevel(Level.OFF); - - //clear the previous message from the test appender - _appender.close(); - verifyNoLog(message); - - //verify that the hierarchy disabling took effect - testLoggedMessage(msgLogger, false, loggerName1); - - //now ensure that using a new hierarchy results in the message being output - testLoggedMessage(msgLogger, true, loggerName2); - } - - /** - * Test that log4j can be used to manipulate on a per-hierarchy(and thus message) basis - * whether a particular status message is enabled. - * <p/> - * Test this by using two hierarchies, setting one off and one on (info) via log4j directly, - * then confirming this gives the expected isMessageEnabled() result. Then reverse the log4j - * Levels for the Logger's and ensure the results change as expected. - */ - public void testEnablingAndDisablingMessages() - { - String loggerName1 = getName() + ".TestLogger1"; - String loggerName2 = getName() + ".TestLogger2"; - - Logger.getLogger(loggerName1).setLevel(Level.INFO); - Logger.getLogger(loggerName2).setLevel(Level.OFF); - - Log4jMessageLogger msgLogger = new Log4jMessageLogger(); - BrokerActor actor = new BrokerActor(msgLogger); - - assertTrue("Expected message logger to be enabled", msgLogger.isEnabled()); - - assertTrue("Message should be enabled", msgLogger.isMessageEnabled(actor, loggerName1)); - assertFalse("Message should be disabled", msgLogger.isMessageEnabled(actor, loggerName2)); - - Logger.getLogger(loggerName1).setLevel(Level.WARN); - Logger.getLogger(loggerName2).setLevel(Level.INFO); - - assertFalse("Message should be disabled", msgLogger.isMessageEnabled(actor, loggerName1)); - assertTrue("Message should be enabled", msgLogger.isMessageEnabled(actor, loggerName2)); - } - - /** - * Check that the Log Message reached log4j - * @param message the message to search for - */ - private void verifyLogPresent(String message) - { - List<String> results = findMessageInLog(message); - - //Validate we only got one message - assertEquals("The result set was not as expected.", 1, results.size()); - - // Validate message - String line = results.get(0); - - assertNotNull("No Message retrieved from log file", line); - assertTrue("Message not contained in log.:" + line, - line.contains(message)); - } - - /** - * Check that the given Message is not present in the log4j records. - * @param message the message to search for - */ - private void verifyNoLog(String message) - { - List<String> results = findMessageInLog(message); - - if (results.size() > 0) - { - System.err.println("Unexpected Log messages"); - - for (String msg : results) - { - System.err.println(msg); - } - } - - assertEquals("No message was expected.", 0, results.size()); - } - - /** - * Get the appenders list of events and return a list of all the messages - * that contain the given message - * - * @param message the search string - * @return The list of all logged messages that contain the search string. - */ - private List<String> findMessageInLog(String message) - { - List<LoggingEvent> log = _appender.getLog(); - - // Search Results for requested message - List<String> result = new LinkedList<String>(); - - for (LoggingEvent event : log) - { - if (String.valueOf(event.getMessage()).contains(message)) - { - result.add(String.valueOf(event.getMessage())); - } - } - - return result; - } - - - /** - * Log4j Appender that simply records all the Logging Events so we can - * verify that the above logging will make it to log4j in a unit test. - */ - private class Log4jTestAppender extends AppenderSkeleton - { - private List<LoggingEvent> _log = new LinkedList<LoggingEvent>(); - - protected void append(LoggingEvent loggingEvent) - { - _log.add(loggingEvent); - } - - public void close() - { - _log.clear(); - } - - /** - * @return the list of LoggingEvents that have occured in this Appender - */ - public List<LoggingEvent> getLog() - { - return _log; - } - - public boolean requiresLayout() - { - return false; - } - } -} - diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/LogMessageTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/LogMessageTest.java deleted file mode 100644 index b0cb0ca0ab..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/LogMessageTest.java +++ /dev/null @@ -1,170 +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; - -import junit.framework.TestCase; - -import org.apache.qpid.server.logging.messages.BrokerMessages; - -import java.util.Locale; -import java.util.ResourceBundle; - -public class LogMessageTest extends TestCase -{ - - /** - * Test that the US local has a loadable bundle. - * No longer have a specific en_US bundle so cannot verify that that version - * is loaded. Can only verify that we get a ResourceBundle loaded. - */ - public void testBundle() - { - Locale usLocal = Locale.US; - Locale.setDefault(usLocal); - ResourceBundle _messages = ResourceBundle.getBundle("org.apache.qpid.server.logging.messages.Broker_logmessages", - usLocal); - - assertNotNull("Unable to load ResourceBundle", _messages); - } - - /** - * Test that loading an undefined locale will result in loading of the - * default US locale. - */ - public void testUndefinedLocale() - { - Locale japanese = Locale.JAPANESE; - - Locale.setDefault(japanese); - try - { - ResourceBundle _messages = ResourceBundle.getBundle("org.apache.qpid.server.logging.messages.Broker_logmessages", - japanese); - - assertNotNull("Unable to load ResourceBundle", _messages); - - // If we attempt to load an undefined locale it should default to the Root locale. - assertEquals("Loaded bundle has incorrect locale.", Locale.ROOT, _messages.getLocale()); - } - catch (Throwable t) - { - fail(t.getMessage()); - } - } - - /** - * test Simultaneous log message generation. - * QPID-2137 highlighted that log message generation was not thread-safe. - * Test to ensure that simultaneous logging is possible and does not throw an exception. - * @throws InterruptedException if there is a problem joining logging threads. - */ - public void testSimultaneousLogging() throws InterruptedException - { - int LOGGERS = 10; - int LOG_COUNT = 10; - LogGenerator[] logGenerators = new LogGenerator[LOGGERS]; - Thread[] threads = new Thread[LOGGERS]; - - //Create Loggers - for (int i = 0; i < LOGGERS; i++) - { - logGenerators[i] = new LogGenerator(LOG_COUNT); - threads[i] = new Thread(logGenerators[i]); - } - - //Run Loggers - for (int i = 0; i < LOGGERS; i++) - { - threads[i].start(); - } - - //End Loggers - for (int i = 0; i < LOGGERS; i++) - { - threads[i].join(); - Exception e = logGenerators[i].getThrowException(); - // If we have an exception something went wrong. - // Check and see if it was QPID-2137 - if (e != null) - { - // Just log out if we find the usual exception causing QPID-2137 - if (e instanceof StringIndexOutOfBoundsException) - { - System.err.println("Detected QPID-2137"); - } - fail("Exception thrown during log generation:" + e); - } - } - } - - /** - * Inner class used by testSimultaneousLogging. - * - * This class creates a given number of LogMessages using the BrokerMessages package. - * CONFIG and LISTENING messages are both created per count. - * - * This class is run multiple times simultaneously so that we increase the chance of - * reproducing QPID-2137. This is reproduced when the pattern string used in the MessageFormat - * class is changed whilst formatting is taking place. - * - */ - class LogGenerator implements Runnable - { - private Exception _exception = null; - private int _count; - - /** - * @param count The number of Log Messages to generate - */ - LogGenerator(int count) - { - _count = count; - } - - public void run() - { - try - { - // try and generate _count iterations of Config & Listening messages. - for (int i = 0; i < _count; i++) - { - BrokerMessages.CONFIG("Config"); - BrokerMessages.LISTENING("TCP", 1234); - } - } - catch (Exception e) - { - // if something goes wrong recorded it for later analysis. - _exception = e; - } - } - - /** - * Return any exception that was thrown during the log generation. - * @return Exception - */ - public Exception getThrowException() - { - return _exception; - } - } - -}
\ No newline at end of file diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/UnitTestMessageLogger.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/UnitTestMessageLogger.java deleted file mode 100644 index be31f3d039..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/UnitTestMessageLogger.java +++ /dev/null @@ -1,76 +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; - - -import java.util.LinkedList; -import java.util.List; - -public class UnitTestMessageLogger extends AbstractRootMessageLogger -{ - private final List<Object> _log = new LinkedList<Object>(); - - public UnitTestMessageLogger() - { - - } - - public UnitTestMessageLogger(boolean statusUpdatesEnabled) - { - super(statusUpdatesEnabled); - } - - public void rawMessage(String message, String logHierarchy) - { - _log.add(message); - } - - public void rawMessage(String message, Throwable throwable, String logHierarchy) - { - _log.add(message); - - if(throwable != null) - { - _log.add(throwable); - } - } - - - public List<Object> getLogMessages() - { - return _log; - } - - public void clearLogMessages() - { - _log.clear(); - } - - public boolean messageContains(final int index, final String contains) - { - if (index + 1 > _log.size()) - { - throw new IllegalArgumentException("Message with index " + index + " has not been logged"); - } - final String message = _log.get(index).toString(); - return message.contains(contains); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/UnitTestMessageLoggerTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/UnitTestMessageLoggerTest.java deleted file mode 100644 index e2e112be8f..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/UnitTestMessageLoggerTest.java +++ /dev/null @@ -1,103 +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; - -import junit.framework.TestCase; - -import java.util.List; - -/** - * Test: UnitTestMessageLoggerTest - * - * This test verifies that UnitTestMessageLogger adheres to its interface. - * - * Messages are logged, and Throwables recorded in an array that can be - * retrieved and cleared. - * - */ -public class UnitTestMessageLoggerTest extends TestCase -{ - private static final String TEST_MESSAGE = "Test"; - private static final String TEST_THROWABLE = "Test Throwable"; - private static final String TEST_HIERARCHY = "test.hierarchy"; - - public void testRawMessage() - { - UnitTestMessageLogger logger = new UnitTestMessageLogger(); - - assertEquals("Messages logged before test start", 0, - logger.getLogMessages().size()); - - // Log a message - logger.rawMessage(TEST_MESSAGE, TEST_HIERARCHY); - - List<Object> messages = logger.getLogMessages(); - - assertEquals("Expected to have 1 messages logged", 1, messages.size()); - - assertEquals("First message not what was logged", - TEST_MESSAGE, messages.get(0)); - } - - public void testRawMessageWithThrowable() - { - UnitTestMessageLogger logger = new UnitTestMessageLogger(); - - assertEquals("Messages logged before test start", 0, - logger.getLogMessages().size()); - - // Log a message - Throwable throwable = new Throwable(TEST_THROWABLE); - - logger.rawMessage(TEST_MESSAGE, throwable, TEST_HIERARCHY); - - List<Object> messages = logger.getLogMessages(); - - assertEquals("Expected to have 2 entries", 2, messages.size()); - - assertEquals("Message text not what was logged", - TEST_MESSAGE, messages.get(0)); - - assertEquals("Message throwable not what was logged", - TEST_THROWABLE, ((Throwable) messages.get(1)).getMessage()); - - } - - public void testClear() - { - UnitTestMessageLogger logger = new UnitTestMessageLogger(); - - assertEquals("Messages logged before test start", 0, - logger.getLogMessages().size()); - - // Log a message - logger.rawMessage(TEST_MESSAGE, null, TEST_HIERARCHY); - - assertEquals("Expected to have 1 messages logged", - 1, logger.getLogMessages().size()); - - logger.clearLogMessages(); - - assertEquals("Expected to have no messagse after a clear", - 0, logger.getLogMessages().size()); - - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AMQPChannelActorTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AMQPChannelActorTest.java deleted file mode 100644 index 41b42fac78..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AMQPChannelActorTest.java +++ /dev/null @@ -1,106 +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.actors; - -import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.util.BrokerTestHelper; - -import java.util.List; - -/** - * Test : AMQPChannelActorTest - * Validate the AMQPChannelActor class. - * - * The test creates a new AMQPActor and then logs a message using it. - * - * The test then verifies that the logged message was the only one created and - * that the message contains the required message. - */ -public class AMQPChannelActorTest extends BaseConnectionActorTestCase -{ - - public void setUp() - { - // do nothing - } - - private void setUpNow() throws Exception - { - super.setUp(); - AMQSessionModel channel = BrokerTestHelper.createSession(1, getConnection()); - - setAmqpActor(new AMQPChannelActor(channel, getRootLogger())); - } - - - /** - * Test that when logging on behalf of the channel - * The test sends a message then verifies that it entered the logs. - * - * The log message should be fully repalaced (no '{n}' values) and should - * contain the channel id ('/ch:1') identification. - */ - public void testChannel() throws Exception - { - setUpNow(); - - final String message = sendTestLogMessage(getAmqpActor()); - - List<Object> logs = getRawLogger().getLogMessages(); - - assertEquals("Message log size not as expected.", 1, logs.size()); - - // Verify that the logged message is present in the output - assertTrue("Message was not found in log message:" + logs.get(0), - logs.get(0).toString().contains(message)); - - // Verify that the message has the correct type - assertTrue("Message contains the [con: prefix", - logs.get(0).toString().contains("[con:")); - - - // Verify that all the values were presented to the MessageFormatter - // so we will not end up with '{n}' entries in the log. - assertFalse("Verify that the string does not contain any '{'." + logs.get(0), - logs.get(0).toString().contains("{")); - - // Verify that the logged message contains the 'ch:1' marker - assertTrue("Message was not logged as part of channel 1" + logs.get(0), - logs.get(0).toString().contains("/ch:1")); - } - - /** - * Test that if logging is configured to be off via system property that - * no logging is presented - */ - public void testChannelLoggingOFF() throws Exception - { - setStatusUpdatesEnabled(false); - - setUpNow(); - - sendTestLogMessage(getAmqpActor()); - - List<Object> logs = getRawLogger().getLogMessages(); - - assertEquals("Message log size not as expected.", 0, logs.size()); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AMQPConnectionActorTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AMQPConnectionActorTest.java deleted file mode 100644 index d1cf256563..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AMQPConnectionActorTest.java +++ /dev/null @@ -1,122 +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.actors; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.logging.LogMessage; -import org.apache.qpid.server.logging.LogSubject; - -import java.util.List; - -/** - * Test : AMQPConnectionActorTest - * Validate the AMQPConnectionActor class. - * - * The test creates a new AMQPActor and then logs a message using it. - * - * The test then verifies that the logged message was the only one created and - * that the message contains the required message. - */ -public class AMQPConnectionActorTest extends BaseConnectionActorTestCase -{ - @Override - public void setUp() - { - //Prevent logger creation - } - - /** - * Test the AMQPActor logging as a Connection level. - * - * The test sends a message then verifies that it entered the logs. - * - * The log message should be fully repalaced (no '{n}' values) and should - * not contain any channel identification. - */ - public void testConnection() throws Exception - { - super.setUp(); - - final String message = sendLogMessage(); - - List<Object> logs = getRawLogger().getLogMessages(); - - assertEquals("Message log size not as expected.", 1, logs.size()); - - // Verify that the logged message is present in the output - assertTrue("Message was not found in log message", - logs.get(0).toString().contains(message)); - - // Verify that the message has the correct type - assertTrue("Message does not contain the [con: prefix", - logs.get(0).toString().contains("[con:")); - - // Verify that all the values were presented to the MessageFormatter - // so we will not end up with '{n}' entries in the log. - assertFalse("Verify that the string does not contain any '{'.", - logs.get(0).toString().contains("{")); - - // Verify that the logged message does not contains the 'ch:' marker - assertFalse("Message was logged with a channel identifier." + logs.get(0), - logs.get(0).toString().contains("/ch:")); - } - - public void testConnectionLoggingOff() throws Exception, AMQException - { - setStatusUpdatesEnabled(false); - - super.setUp(); - - sendLogMessage(); - - List<Object> logs = getRawLogger().getLogMessages(); - - assertEquals("Message log size not as expected.", 0, logs.size()); - - } - - private String sendLogMessage() - { - final String message = "test logging"; - - getAmqpActor().message(new LogSubject() - { - public String toLogString() - { - return "[AMQPActorTest]"; - } - - }, new LogMessage() - { - public String toString() - { - return message; - } - - public String getLogHierarchy() - { - return "test.hieracrchy"; - } - }); - return message; - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AbstractManagementActorTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AbstractManagementActorTest.java deleted file mode 100644 index bf38bb64bf..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AbstractManagementActorTest.java +++ /dev/null @@ -1,86 +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.actors; - -import java.security.Principal; -import java.security.PrivilegedAction; -import java.util.Collections; - -import javax.security.auth.Subject; - -import org.apache.qpid.server.logging.NullRootMessageLogger; -import org.apache.qpid.server.security.auth.TestPrincipalUtils; -import org.apache.qpid.test.utils.QpidTestCase; - -public class AbstractManagementActorTest extends QpidTestCase -{ - private AbstractManagementActor _logActor; - - @Override - public void setUp() - { - _logActor = new AbstractManagementActor(new NullRootMessageLogger(), AbstractManagementActor.UNKNOWN_PRINCIPAL) - { - @Override - public String getLogMessage() - { - return null; - } - }; - } - - public void testGetPrincipalName() - { - Subject subject = TestPrincipalUtils.createTestSubject("guest"); - - final String principalName = Subject.doAs(subject, - new PrivilegedAction<String>() - { - public String run() - { - return _logActor.getPrincipalName(); - } - }); - - assertEquals("guest", principalName); - } - - public void testGetPrincipalNameUsingSubjectWithoutAuthenticatedPrincipal() - { - Subject subject = new Subject(true, Collections.<Principal>emptySet(), Collections.emptySet(), Collections.emptySet()); - - final String principalName = Subject.doAs(subject, - new PrivilegedAction<String>() - { - public String run() - { - return _logActor.getPrincipalName(); - } - }); - - assertEquals(AbstractManagementActor.UNKNOWN_PRINCIPAL, principalName); - } - - public void testGetPrincipalWithoutSubject() - { - assertEquals(AbstractManagementActor.UNKNOWN_PRINCIPAL, _logActor.getPrincipalName()); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/BaseActorTestCase.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/BaseActorTestCase.java deleted file mode 100644 index 30c3a51604..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/BaseActorTestCase.java +++ /dev/null @@ -1,120 +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.actors; - -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.UnitTestMessageLogger; -import org.apache.qpid.test.utils.QpidTestCase; - -public class BaseActorTestCase extends QpidTestCase -{ - private boolean _statusUpdatesEnabled = true; - private LogActor _amqpActor; - private UnitTestMessageLogger _rawLogger; - private RootMessageLogger _rootLogger; - - @Override - public void setUp() throws Exception - { - super.setUp(); - CurrentActor.removeAll(); - CurrentActor.setDefault(null); - _rawLogger = new UnitTestMessageLogger(_statusUpdatesEnabled); - _rootLogger = _rawLogger; - } - - @Override - public void tearDown() throws Exception - { - if(_rawLogger != null) - { - _rawLogger.clearLogMessages(); - } - CurrentActor.removeAll(); - CurrentActor.setDefault(null); - super.tearDown(); - } - - public String sendTestLogMessage(LogActor actor) - { - String message = "Test logging: " + getName(); - sendTestLogMessage(actor, message); - - return message; - } - - public void sendTestLogMessage(LogActor actor, final String message) - { - actor.message(new LogSubject() - { - public String toLogString() - { - return message; - } - - }, new LogMessage() - { - public String toString() - { - return message; - } - - public String getLogHierarchy() - { - return "test.hierarchy"; - } - }); - } - - public boolean isStatusUpdatesEnabled() - { - return _statusUpdatesEnabled; - } - - public void setStatusUpdatesEnabled(boolean statusUpdatesEnabled) - { - _statusUpdatesEnabled = statusUpdatesEnabled; - } - - public LogActor getAmqpActor() - { - return _amqpActor; - } - - public void setAmqpActor(LogActor amqpActor) - { - _amqpActor = amqpActor; - } - - public UnitTestMessageLogger getRawLogger() - { - return _rawLogger; - } - - public RootMessageLogger getRootLogger() - { - return _rootLogger; - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/BaseConnectionActorTestCase.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/BaseConnectionActorTestCase.java deleted file mode 100644 index 1cb6474e41..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/BaseConnectionActorTestCase.java +++ /dev/null @@ -1,74 +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.actors; - -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.protocol.AMQConnectionModel; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.server.virtualhost.VirtualHost; - -public class BaseConnectionActorTestCase extends BaseActorTestCase -{ - private AMQConnectionModel _session; - private VirtualHost _virtualHost; - - @Override - public void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - _session = BrokerTestHelper.createConnection(); - _virtualHost = BrokerTestHelper.createVirtualHost("test"); - setAmqpActor(new AMQPConnectionActor(_session, getRootLogger())); - } - - public VirtualHost getVirtualHost() - { - return _virtualHost; - } - - @Override - public void tearDown() throws Exception - { - try - { - if(_virtualHost != null) - { - _virtualHost.close(); - } - if (_session != null) - { - _session.close(AMQConstant.CONNECTION_FORCED, ""); - } - } - finally - { - BrokerTestHelper.tearDown(); - super.tearDown(); - } - } - - public AMQConnectionModel getConnection() - { - return _session; - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/CurrentActorTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/CurrentActorTest.java deleted file mode 100644 index 701ccaab47..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/CurrentActorTest.java +++ /dev/null @@ -1,253 +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.actors; - -import org.apache.commons.configuration.ConfigurationException; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.logging.LogActor; -import org.apache.qpid.server.logging.NullRootMessageLogger; -import org.apache.qpid.server.util.BrokerTestHelper; - -/** - * Test : CurrentActorTest - * Summary: - * Validate ThreadLocal operation. - * - * Test creates THREADS number of threads which all then execute the same test - * together ( as close as looping Thread.start() will allow). - * - * Test: - * Test sets the CurrentActor then proceeds to retrieve the value and use it. - * - * The test also validates that it is the same LogActor that this thread set. - * - * Finally the LogActor is removed and tested to make sure that it was - * successfully removed. - * - * By having a higher number of threads than would normally be used in the - * Poolling filter we aim to catch the race condition where a ThreadLocal remove - * is called before one or more threads call get(). This way we can ensure that - * the remove does not affect more than the Thread it was called in. - */ -public class CurrentActorTest extends BaseConnectionActorTestCase -{ - //Set this to be a reasonably large number - private static final int THREADS = 10; - - /** - * Test that CurrentActor behaves as LIFO queue. - * - * Test creates two Actors Connection and Channel and then sets the - * CurrentActor. - * - * The test validates that CurrentActor remembers the Connection actor - * after the Channel actor has been removed. - * - * And then finally validates that removing the Connection actor results - * in there being no actors set. - * - * @throws AMQException - * @throws org.apache.commons.configuration.ConfigurationException - */ - public void testLIFO() throws AMQException, ConfigurationException - { - assertTrue("Unexpected actor: " + CurrentActor.get(), CurrentActor.get() instanceof TestLogActor); - AMQPConnectionActor connectionActor = new AMQPConnectionActor(getConnection(), - new NullRootMessageLogger()); - - /* - * Push the actor on to the stack: - * - * CurrentActor -> Connection - * Stack -> null - */ - CurrentActor.set(connectionActor); - - //Use the Actor to send a simple message - sendTestLogMessage(CurrentActor.get()); - - // Verify it was the same actor as we set earlier - assertEquals("Retrieved actor is not as expected ", - connectionActor, CurrentActor.get()); - - /** - * Set the actor to now be the Channel actor so testing the ability - * to push the actor on to the stack: - * - * CurrentActor -> Channel - * Stack -> Connection, null - * - */ - - AMQSessionModel channel = BrokerTestHelper.createSession(1, getConnection()); - - AMQPChannelActor channelActor = new AMQPChannelActor(channel, - new NullRootMessageLogger()); - - CurrentActor.set(channelActor); - - //Use the Actor to send a simple message - sendTestLogMessage(CurrentActor.get()); - - // Verify it was the same actor as we set earlier - assertEquals("Retrieved actor is not as expected ", - channelActor, CurrentActor.get()); - - // Remove the ChannelActor from the stack - CurrentActor.remove(); - /* - * Pop the actor on to the stack: - * - * CurrentActor -> Connection - * Stack -> null - */ - - - // Verify we now have the same connection actor as we set earlier - assertEquals("Retrieved actor is not as expected ", - connectionActor, CurrentActor.get()); - - // Verify that removing the our last actor it returns us to the test - // default that the ApplicationRegistry sets. - CurrentActor.remove(); - /* - * Pop the actor on to the stack: - * - * CurrentActor -> null - */ - - - assertEquals("CurrentActor not the Test default", TestLogActor.class ,CurrentActor.get().getClass()); - } - - /** - * Test the setting CurrentActor is done correctly as a ThreadLocal. - * - * The test starts 'THREADS' threads that all set the CurrentActor log - * a message then remove the actor. - * - * Checks are done to ensure that there is no set actor after the remove. - * - * If the ThreadLocal was not working then having concurrent actor sets - * would result in more than one actor and so the remove will not result - * in the clearing of the CurrentActor - * - */ - public void testThreadLocal() - { - - // Setup the threads - LogMessagesWithAConnectionActor[] threads = new LogMessagesWithAConnectionActor[THREADS]; - for (int count = 0; count < THREADS; count++) - { - threads[count] = new LogMessagesWithAConnectionActor(); - } - - //Run the threads - for (int count = 0; count < THREADS; count++) - { - threads[count].start(); - } - - // Wait for them to finish - for (int count = 0; count < THREADS; count++) - { - try - { - threads[count].join(); - } - catch (InterruptedException e) - { - //if we are interrupted then we will exit shortly. - } - } - - // Verify that none of the tests threw an exception - for (int count = 0; count < THREADS; count++) - { - if (threads[count].getException() != null) - { - threads[count].getException().printStackTrace(); - fail("Error occured in thread:" + count + "("+threads[count].getException()+")"); - } - } - } - - /** - * Creates a new ConnectionActor and logs the given number of messages - * before removing the actor and validating that there is no set actor. - */ - public class LogMessagesWithAConnectionActor extends Thread - { - private Throwable _exception; - - public LogMessagesWithAConnectionActor() - { - } - - public void run() - { - - // Create a new actor using retrieving the rootMessageLogger from - // the default ApplicationRegistry. - //fixme reminder that we need a better approach for broker testing. - try - { - LogActor defaultActor = CurrentActor.get(); - - AMQPConnectionActor actor = new AMQPConnectionActor(getConnection(), - new NullRootMessageLogger()); - - CurrentActor.set(actor); - - //Use the Actor to send a simple message - sendTestLogMessage(CurrentActor.get()); - - // Verify it was the same actor as we set earlier - if(!actor.equals(CurrentActor.get())) - { - throw new IllegalArgumentException("Retrieved actor is not as expected "); - } - - // Verify that removing the actor works for this thread - CurrentActor.remove(); - - if(CurrentActor.get() != defaultActor) - { - throw new IllegalArgumentException("CurrentActor ("+CurrentActor.get()+") should be default actor" + defaultActor); - } - } - catch (Throwable e) - { - _exception = e; - } - - } - - public Throwable getException() - { - return _exception; - } - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/HttpManagementActorTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/HttpManagementActorTest.java deleted file mode 100644 index 905de4b639..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/HttpManagementActorTest.java +++ /dev/null @@ -1,94 +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.actors; - -import javax.security.auth.Subject; - -import org.apache.qpid.server.security.auth.TestPrincipalUtils; - -import java.security.PrivilegedAction; -import java.util.List; - -public class HttpManagementActorTest extends BaseActorTestCase -{ - private static final String IP = "127.0.0.1"; - private static final int PORT = 1; - private static final String SUFFIX = "(" + IP + ":" + PORT + ")] "; - - @Override - public void setUp() throws Exception - { - super.setUp(); - setAmqpActor(new HttpManagementActor(getRootLogger(), IP, PORT)); - } - - public void testSubjectPrincipalNameAppearance() - { - Subject subject = TestPrincipalUtils.createTestSubject("guest"); - - final String message = Subject.doAs(subject, new PrivilegedAction<String>() - { - public String run() - { - return sendTestLogMessage(getAmqpActor()); - } - }); - - assertNotNull("Test log message is not created!", message); - - List<Object> logs = getRawLogger().getLogMessages(); - assertEquals("Message log size not as expected.", 1, logs.size()); - - String logMessage = logs.get(0).toString(); - assertTrue("Message was not found in log message", logMessage.contains(message)); - assertTrue("Message does not contain expected value: " + logMessage, logMessage.contains("[mng:guest" + SUFFIX)); - } - - /** It's necessary to test successive calls because HttpManagementActor caches - * its log message based on principal name */ - public void testGetLogMessageCaching() - { - assertLogMessageWithoutPrincipal(); - assertLogMessageWithPrincipal("my_principal"); - assertLogMessageWithPrincipal("my_principal2"); - assertLogMessageWithoutPrincipal(); - } - - private void assertLogMessageWithoutPrincipal() - { - String message = getAmqpActor().getLogMessage(); - assertEquals("Unexpected log message", "[mng:" + AbstractManagementActor.UNKNOWN_PRINCIPAL + SUFFIX, message); - } - - private void assertLogMessageWithPrincipal(String principalName) - { - Subject subject = TestPrincipalUtils.createTestSubject(principalName); - final String message = Subject.doAs(subject, new PrivilegedAction<String>() - { - public String run() - { - return getAmqpActor().getLogMessage(); - } - }); - - assertEquals("Unexpected log message", "[mng:" + principalName + SUFFIX, message); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/ManagementActorTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/ManagementActorTest.java deleted file mode 100644 index a0bfa592db..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/ManagementActorTest.java +++ /dev/null @@ -1,186 +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.actors; - -import javax.security.auth.Subject; - -import org.apache.qpid.server.security.auth.TestPrincipalUtils; - -import java.security.PrivilegedAction; -import java.util.List; - -public class ManagementActorTest extends BaseActorTestCase -{ - - private static final String IP = "127.0.0.1"; - private static final String CONNECTION_ID = "1"; - private String _threadName; - - @Override - public void setUp() throws Exception - { - super.setUp(); - setAmqpActor(new ManagementActor(getRootLogger())); - - // Set the thread name to be the same as a RMI JMX Connection would use - _threadName = Thread.currentThread().getName(); - Thread.currentThread().setName("RMI TCP Connection(" + CONNECTION_ID + ")-" + IP); - } - - @Override - public void tearDown() throws Exception - { - Thread.currentThread().setName(_threadName); - super.tearDown(); - } - - /** - * Test the AMQPActor logging as a Connection level. - * - * The test sends a message then verifies that it entered the logs. - * - * The log message should be fully replaced (no '{n}' values) and should - * not contain any channel identification. - */ - public void testConnection() - { - final String message = sendTestLogMessage(getAmqpActor()); - - List<Object> logs = getRawLogger().getLogMessages(); - - assertEquals("Message log size not as expected.", 1, logs.size()); - - // Verify that the logged message is present in the output - assertTrue("Message was not found in log message", - logs.get(0).toString().contains(message)); - - // Verify that all the values were presented to the MessageFormatter - // so we will not end up with '{n}' entries in the log. - assertFalse("Verify that the string does not contain any '{'.", - logs.get(0).toString().contains("{")); - - // Verify that the message has the correct type - assertTrue("Message does not contain the [mng: prefix", - logs.get(0).toString().contains("[mng:")); - - // Verify that the logged message does not contains the 'ch:' marker - assertFalse("Message was logged with a channel identifier." + logs.get(0), - logs.get(0).toString().contains("/ch:")); - - // Verify that the message has the right values - assertTrue("Message contains the [mng: prefix", - logs.get(0).toString().contains("[mng:N/A(" + IP + ")")); - } - - /** - * Tests appearance of principal name in log message - */ - public void testSubjectPrincipalNameAppearance() - { - Subject subject = TestPrincipalUtils.createTestSubject("guest"); - - final String message = Subject.doAs(subject, new PrivilegedAction<String>() - { - public String run() - { - return sendTestLogMessage(getAmqpActor()); - } - }); - - // Verify that the log message was created - assertNotNull("Test log message is not created!", message); - - List<Object> logs = getRawLogger().getLogMessages(); - - // Verify that at least one log message was added to log - assertEquals("Message log size not as expected.", 1, logs.size()); - - String logMessage = logs.get(0).toString(); - - // Verify that the logged message is present in the output - assertTrue("Message was not found in log message", logMessage.contains(message)); - - // Verify that the message has the right principal value - assertTrue("Message contains the [mng: prefix", logMessage.contains("[mng:guest(" + IP + ")")); - } - - public void testGetLogMessageWithSubject() - { - assertLogMessageInRMIThreadWithPrincipal("RMI TCP Connection(" + CONNECTION_ID + ")-" + IP, "my_principal"); - } - - public void testGetLogMessageWithoutSubjectButWithActorPrincipal() - { - String principalName = "my_principal"; - setAmqpActor(new ManagementActor(getRootLogger(), principalName)); - String message = getAmqpActor().getLogMessage(); - assertEquals("Unexpected log message", "[mng:" + principalName + "(" + IP + ")] ", message); - } - - /** It's necessary to test successive calls because ManagementActor caches its log message based on thread and principal name */ - public void testGetLogMessageCaching() - { - String originalThreadName = "RMI TCP Connection(1)-" + IP; - assertLogMessageInRMIThreadWithoutPrincipal(originalThreadName); - assertLogMessageInRMIThreadWithPrincipal(originalThreadName, "my_principal"); - assertLogMessageInRMIThreadWithPrincipal("RMI TCP Connection(2)-" + IP, "my_principal"); - } - - public void testGetLogMessageAfterRemovingSubject() - { - assertLogMessageInRMIThreadWithPrincipal("RMI TCP Connection(1)-" + IP, "my_principal"); - - Thread.currentThread().setName("RMI TCP Connection(2)-" + IP ); - String message = getAmqpActor().getLogMessage(); - assertEquals("Unexpected log message", "[mng:N/A(" + IP + ")] ", message); - - assertLogMessageWithoutPrincipal("TEST"); - } - - private void assertLogMessageInRMIThreadWithoutPrincipal(String threadName) - { - Thread.currentThread().setName(threadName ); - String message = getAmqpActor().getLogMessage(); - assertEquals("Unexpected log message", "[mng:N/A(" + IP + ")] ", message); - } - - private void assertLogMessageWithoutPrincipal(String threadName) - { - Thread.currentThread().setName(threadName ); - String message = getAmqpActor().getLogMessage(); - assertEquals("Unexpected log message", "[" + threadName +"] ", message); - } - - private void assertLogMessageInRMIThreadWithPrincipal(String threadName, String principalName) - { - Thread.currentThread().setName(threadName); - Subject subject = TestPrincipalUtils.createTestSubject(principalName); - final String message = Subject.doAs(subject, new PrivilegedAction<String>() - { - public String run() - { - return getAmqpActor().getLogMessage(); - } - }); - - assertEquals("Unexpected log message", "[mng:" + principalName + "(" + IP + ")] ", message); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/QueueActorTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/QueueActorTest.java deleted file mode 100644 index 55153b7389..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/QueueActorTest.java +++ /dev/null @@ -1,75 +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.actors; - -import java.util.List; - -import org.apache.qpid.server.util.BrokerTestHelper; - -public class QueueActorTest extends BaseConnectionActorTestCase -{ - - @Override - public void setUp() throws Exception - { - super.setUp(); - setAmqpActor(new QueueActor(BrokerTestHelper.createQueue(getName(), getVirtualHost()), getRootLogger())); - } - - /** - * Test the QueueActor as a logger. - * - * The test logs a message then verifies that it entered the logs correctly - * - * The log message should be fully repalaced (no '{n}' values) and should - * contain the correct queue identification. - */ - public void testQueueActor() - { - final String message = sendTestLogMessage(getAmqpActor()); - - List<Object> logs = getRawLogger().getLogMessages(); - - assertEquals("Message log size not as expected.", 1, logs.size()); - - String log = logs.get(0).toString(); - - // Verify that the logged message is present in the output - assertTrue("Message was not found in log message", - log.contains(message)); - - // Verify that all the values were presented to the MessageFormatter - // so we will not end up with '{n}' entries in the log. - assertFalse("Verify that the string does not contain any '{':" + log, - log.contains("{")); - - // Verify that the message has the correct type - assertTrue("Message contains the [vh: prefix:" + log, - log.contains("[vh(")); - - // Verify that the logged message contains the 'qu(' marker - String expected = "qu(" + getName() + ")"; - assertTrue("Message was not logged with a queue identifer '"+expected+"' actual:" + log, - log.contains(expected)); - } - -} - diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/SubscriptionActorTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/SubscriptionActorTest.java deleted file mode 100644 index 92915e7092..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/SubscriptionActorTest.java +++ /dev/null @@ -1,86 +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.actors; - -import org.apache.qpid.server.subscription.MockSubscription; -import org.apache.qpid.server.util.BrokerTestHelper; - -import java.util.List; - -/** - * Test : AMQPConnectionActorTest - * Validate the AMQPConnectionActor class. - * - * The test creates a new AMQPActor and then logs a message using it. - * - * The test then verifies that the logged message was the only one created and - * that the message contains the required message. - */ -public class SubscriptionActorTest extends BaseConnectionActorTestCase -{ - - @Override - public void setUp() throws Exception - { - super.setUp(); - - MockSubscription mockSubscription = new MockSubscription(); - - mockSubscription.setQueue(BrokerTestHelper.createQueue(getName(), getVirtualHost()), false); - - setAmqpActor(new SubscriptionActor(getRootLogger(), mockSubscription)); - } - - /** - * Test the AMQPActor logging as a Subscription logger. - * - * The test sends a message then verifies that it entered the logs. - * - * The log message should be fully repalaced (no '{n}' values) and should - * contain subscription identification. - */ - public void testSubscription() - { - final String message = sendTestLogMessage(getAmqpActor()); - - List<Object> logs = getRawLogger().getLogMessages(); - - assertEquals("Message log size not as expected.", 1, logs.size()); - - // Verify that the logged message is present in the output - assertTrue("Message was not found in log message", - logs.get(0).toString().contains(message)); - - // Verify that all the values were presented to the MessageFormatter - // so we will not end up with '{n}' entries in the log. - assertFalse("Verify that the string does not contain any '{'.", - logs.get(0).toString().contains("{")); - - // Verify that the message has the correct type - assertTrue("Message contains the [sub: prefix", - logs.get(0).toString().contains("[sub:")); - - // Verify that the logged message does not contains the 'ch:' marker - assertFalse("Message was logged with a channel identifier." + logs.get(0), - logs.get(0).toString().contains("/ch:")); - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/TestLogActor.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/TestLogActor.java deleted file mode 100644 index 30f4e16e42..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/TestLogActor.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.logging.actors; - -import org.apache.qpid.server.logging.RootMessageLogger; - -public class TestLogActor extends AbstractActor -{ - public TestLogActor(RootMessageLogger rootLogger) - { - super(rootLogger); - } - - public String getLogMessage() - { - return "[Test Actor] "; - } -} -
\ No newline at end of file diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/log4j/LoggingFacadeTest.log4j.xml b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/log4j/LoggingFacadeTest.log4j.xml deleted file mode 100644 index 62ec877d3d..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/log4j/LoggingFacadeTest.log4j.xml +++ /dev/null @@ -1,41 +0,0 @@ -<?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/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/log4j/LoggingManagementFacadeTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/log4j/LoggingManagementFacadeTest.java deleted file mode 100644 index 72b34868ba..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/log4j/LoggingManagementFacadeTest.java +++ /dev/null @@ -1,243 +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.log4j; - -import java.io.File; -import java.io.InputStream; -import java.util.List; -import java.util.Map; - -import org.apache.log4j.Level; -import org.apache.qpid.test.utils.TestFileUtils; -import org.apache.qpid.util.FileUtils; - -import junit.framework.TestCase; - -public class LoggingManagementFacadeTest extends TestCase -{ - private LoggingManagementFacade _loggingFacade; - private String _log4jXmlFile; - - @Override - protected void setUp() throws Exception - { - super.setUp(); - _log4jXmlFile = createTestLog4jXml(); - _loggingFacade = LoggingManagementFacade.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 - { - return TestFileUtils.createTempFileFromResource(this, "LoggingFacadeTest.log4j.xml").getAbsolutePath(); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/AbstractTestMessages.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/AbstractTestMessages.java deleted file mode 100644 index 229d75c69f..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/AbstractTestMessages.java +++ /dev/null @@ -1,128 +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.messages; - -import org.apache.commons.configuration.Configuration; -import org.apache.commons.configuration.PropertiesConfiguration; - -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.UnitTestMessageLogger; -import org.apache.qpid.server.logging.actors.TestLogActor; -import org.apache.qpid.server.logging.subjects.TestBlankSubject; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.test.utils.QpidTestCase; - -import java.util.List; - -public abstract class AbstractTestMessages extends QpidTestCase -{ - protected Configuration _config = new PropertiesConfiguration(); - protected LogMessage _logMessage = null; - protected LogActor _actor; - protected UnitTestMessageLogger _logger; - protected LogSubject _logSubject = new TestBlankSubject(); - - @Override - public void setUp() throws Exception - { - super.setUp(); - - _logger = new UnitTestMessageLogger(); - - _actor = new TestLogActor(_logger); - BrokerTestHelper.setUp(); - } - - @Override - public void tearDown() throws Exception - { - BrokerTestHelper.tearDown(); - super.tearDown(); - } - - protected List<Object> performLog() - { - if (_logMessage == null) - { - throw new NullPointerException("LogMessage has not been set"); - } - - _actor.message(_logSubject, _logMessage); - - return _logger.getLogMessages(); - } - - protected void validateLogMessage(List<Object> logs, String tag, String[] expected) - { - validateLogMessage(logs, tag, false, expected); - } - - /** - * Validate that only a single log message occurred and that the message - * section starts with the specified tag - * - * @param logs the logs generated during test run - * @param tag the tag to check for - * @param expected the expected log messages - * @param useStringForNull replace a null String reference with "null" - */ - protected void validateLogMessage(List<Object> logs, String tag, boolean useStringForNull, String[] expected) - { - assertEquals("Log has incorrect message count", 1, logs.size()); - - //We trim() here as we don't care about extra white space at the end of the log message - // but we do care about the ability to easily check we don't have unexpected text at - // the end. - String log = String.valueOf(logs.get(0)).trim(); - - // Simple switch to print out all the logged messages - //System.err.println(log); - - int msgIndex = log.indexOf(_logSubject.toLogString())+_logSubject.toLogString().length(); - - assertTrue("Unable to locate Subject:" + log, msgIndex != -1); - - String message = log.substring(msgIndex); - - assertTrue("Message does not start with tag:" + tag + ":" + message, - message.startsWith(tag)); - - // Test that the expected items occur in order. - int index = 0; - for (String text : expected) - { - if(useStringForNull && text == null) - { - text = "null"; - } - index = message.indexOf(text, index); - assertTrue("Message does not contain expected (" + text + ") text :" + message, index != -1); - index = index + text.length(); - } - - //Check there is nothing left on the log message - assertEquals("Message has more text. '" + log.substring(msgIndex + index) + "'", - log.length(), msgIndex + index); - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/BindingMessagesTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/BindingMessagesTest.java deleted file mode 100644 index 22de8349c6..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/BindingMessagesTest.java +++ /dev/null @@ -1,64 +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.messages; - -import java.util.List; - -/** - * Test BND Log Messages - */ -public class BindingMessagesTest extends AbstractTestMessages -{ - - public void testBindCreate_NoArgs() - { - _logMessage = BindingMessages.CREATED(null, false); - List<Object> log = performLog(); - - String[] expected = {"Create"}; - - validateLogMessage(log, "BND-1001", expected); - } - - public void testBindCreate_Args() - { - String arguments = "arguments"; - - _logMessage = BindingMessages.CREATED(arguments, true); - List<Object> log = performLog(); - - String[] expected = {"Create", ": Arguments :", arguments}; - - validateLogMessage(log, "BND-1001", expected); - } - - public void testBindDelete() - { - _logMessage = BindingMessages.DELETED(); - - List<Object> log = performLog(); - - String[] expected = {"Deleted"}; - - validateLogMessage(log, "BND-1002", expected); - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/BrokerMessagesTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/BrokerMessagesTest.java deleted file mode 100644 index 6571d20711..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/BrokerMessagesTest.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.logging.messages; - -import java.text.NumberFormat; -import java.util.List; - -/** - * Test BRK log Messages - */ -public class BrokerMessagesTest extends AbstractTestMessages -{ - public void testBrokerStartup() - { - String version = "Qpid 0.6"; - String build = "796936M"; - - _logMessage = BrokerMessages.STARTUP(version, build); - List<Object> log = performLog(); - - String[] expected = {"Startup :", "Version:", version, "Build:", build}; - - validateLogMessage(log, "BRK-1001", expected); - } - - public void testBrokerListening() - { - String transport = "TCP"; - Integer port = 2765; - - _logMessage = BrokerMessages.LISTENING(transport, port); - - List<Object> log = performLog(); - - String[] expected = {"Starting", "Listening on ", - transport, "port ", String.valueOf(port)}; - - validateLogMessage(log, "BRK-1002", expected); - } - - public void testBrokerShuttingDown() - { - String transport = "TCP"; - Integer port = 2765; - - _logMessage = BrokerMessages.SHUTTING_DOWN(transport, port); - - List<Object> log = performLog(); - - String[] expected = {"Shutting down", transport, "port ", String.valueOf(port)}; - - validateLogMessage(log, "BRK-1003", expected); - } - - public void testBrokerReady() - { - _logMessage = BrokerMessages.READY(); - List<Object> log = performLog(); - - String[] expected = {"Ready"}; - - validateLogMessage(log, "BRK-1004", expected); - } - - public void testBrokerStopped() - { - _logMessage = BrokerMessages.STOPPED(); - List<Object> log = performLog(); - - String[] expected = {"Stopped"}; - - validateLogMessage(log, "BRK-1005", expected); - } - - public void testBrokerConfig() - { - String path = "/file/path/to/configuration.xml"; - - _logMessage = BrokerMessages.CONFIG(path); - List<Object> log = performLog(); - - String[] expected = {"Using configuration :", path}; - - validateLogMessage(log, "BRK-1006", expected); - } - - public void testBrokerLogConfig() - { - String path = "/file/path/to/configuration.xml"; - - _logMessage = BrokerMessages.LOG_CONFIG(path); - List<Object> log = performLog(); - - String[] expected = {"Using logging configuration :", path}; - - validateLogMessage(log, "BRK-1007", expected); - } - - public void testBrokerPlatform() - { - String javaVendor = "jvendor"; - String javaVersion = "j1.0"; - - String osName = "os"; - String osVersion = "o1.0"; - String osArch = "oarch"; - - _logMessage = BrokerMessages.PLATFORM(javaVendor, javaVersion, osName, osVersion, osArch); - List<Object> log = performLog(); - - String[] expected = {"Platform :", "JVM :", javaVendor, " version: ", " OS : ", osName, " version: ", osVersion, " arch: ", osArch}; - - validateLogMessage(log, "BRK-1010", expected); - } - - public void testBrokerMemory() - { - long oneGiga = 1024*1024*1024; - - _logMessage = BrokerMessages.MAX_MEMORY(oneGiga); - List<Object> log = performLog(); - - String[] expected = {"Maximum Memory :", NumberFormat.getNumberInstance().format(oneGiga), "bytes"}; - - validateLogMessage(log, "BRK-1011", expected); - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ChannelMessagesTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ChannelMessagesTest.java deleted file mode 100644 index 2f1276508c..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ChannelMessagesTest.java +++ /dev/null @@ -1,73 +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.messages; - -import java.util.List; - -/** - * Test CHN Log Messges - */ -public class ChannelMessagesTest extends AbstractTestMessages -{ - public void testChannelCreate() - { - _logMessage = ChannelMessages.CREATE(); - List<Object> log = performLog(); - - // We use the MessageFormat here as that is what the ChannelMessage - // will do, this makes the resulting value 12,345 - String[] expected = {"Create"}; - - validateLogMessage(log, "CHN-1001", expected); - } - - public void testChannelFlow() - { - String flow = "ON"; - - _logMessage = ChannelMessages.FLOW(flow); - List<Object> log = performLog(); - - String[] expected = {"Flow", flow}; - - validateLogMessage(log, "CHN-1002", expected); - } - - public void testChannelClose() - { - _logMessage = ChannelMessages.CLOSE(); - List<Object> log = performLog(); - - String[] expected = {"Close"}; - - validateLogMessage(log, "CHN-1003", expected); - } - - public void testChannelCloseForced() - { - _logMessage = ChannelMessages.CLOSE_FORCED(1, "Test"); - List<Object> log = performLog(); - - String[] expected = {"Close : 1 - Test"}; - - validateLogMessage(log, "CHN-1003", expected); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ConnectionMessagesTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ConnectionMessagesTest.java deleted file mode 100644 index b2951ae54a..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ConnectionMessagesTest.java +++ /dev/null @@ -1,114 +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.messages; - -import java.util.List; - -/** - * Test CON Log Messages - */ -public class ConnectionMessagesTest extends AbstractTestMessages -{ - public void testConnectionOpen_WithClientIDProtocolVersionClientVersion() - { - String clientID = "client"; - String protocolVersion = "8-0"; - String clientVersion = "1.2.3_4"; - - _logMessage = ConnectionMessages.OPEN(clientID, protocolVersion, clientVersion, true , true, true); - List<Object> log = performLog(); - - String[] expected = {"Open :", "Client ID", clientID, - ": Protocol Version :", protocolVersion, - ": Client Version :", clientVersion}; - - validateLogMessage(log, "CON-1001", expected); - } - - public void testConnectionOpen_WithClientIDNoProtocolVersionNoClientVersion() - { - String clientID = "client"; - - _logMessage = ConnectionMessages.OPEN(clientID, null, null, true, false, false); - List<Object> log = performLog(); - - String[] expected = {"Open :", "Client ID", clientID}; - - validateLogMessage(log, "CON-1001", expected); - } - - public void testConnectionOpen_WithNOClientIDProtocolVersionNoClientVersion() - { - String protocolVersion = "8-0"; - - _logMessage = ConnectionMessages.OPEN(null, protocolVersion, null, false , true, false); - List<Object> log = performLog(); - - String[] expected = {"Open", ": Protocol Version :", protocolVersion}; - - validateLogMessage(log, "CON-1001", expected); - } - - public void testConnectionOpen_WithNOClientIDNoProtocolVersionClientVersion() - { - String clientVersion = "1.2.3_4"; - - _logMessage = ConnectionMessages.OPEN(null, null, clientVersion, false , false, true); - List<Object> log = performLog(); - - String[] expected = {"Open", ": Client Version :", clientVersion}; - - validateLogMessage(log, "CON-1001", expected); - } - - public void testConnectionOpen_WithNOClientIDNoProtocolVersionNullClientVersion() - { - String clientVersion = null; - - _logMessage = ConnectionMessages.OPEN(null, null, clientVersion , false , false, true); - List<Object> log = performLog(); - - String[] expected = {"Open", ": Client Version :", clientVersion}; - - validateLogMessage(log, "CON-1001", true, expected); - } - - public void testConnectionOpen_WithNoClientIDNoProtocolVersionNoClientVersion() - { - _logMessage = ConnectionMessages.OPEN(null, null, null, false, false, false); - List<Object> log = performLog(); - - String[] expected = {"Open"}; - - validateLogMessage(log, "CON-1001", expected); - } - - public void testConnectionClose() - { - _logMessage = ConnectionMessages.CLOSE(); - List<Object> log = performLog(); - - String[] expected = {"Close"}; - - validateLogMessage(log, "CON-1002", expected); - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ExchangeMessagesTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ExchangeMessagesTest.java deleted file mode 100644 index f1452b8b88..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ExchangeMessagesTest.java +++ /dev/null @@ -1,87 +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.messages; - -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.util.BrokerTestHelper; - -import java.util.List; - -/** - * Test EXH Log Messages - */ -public class ExchangeMessagesTest extends AbstractTestMessages -{ - public void testExchangeCreated_Transient() throws Exception - { - Exchange exchange = BrokerTestHelper.createExchange("test"); - - String type = exchange.getTypeName(); - String name = exchange.getName(); - - _logMessage = ExchangeMessages.CREATED(type, name, false); - List<Object> log = performLog(); - - String[] expected = {"Create :", "Type:", type, "Name:", name}; - - validateLogMessage(log, "EXH-1001", expected); - } - - public void testExchangeCreated_Persistent() throws Exception - { - Exchange exchange = BrokerTestHelper.createExchange("test"); - - String type = exchange.getTypeName(); - String name = exchange.getName(); - - _logMessage = ExchangeMessages.CREATED(type, name, true); - List<Object> log = performLog(); - - String[] expected = {"Create :", "Durable", "Type:", type, "Name:", name}; - - validateLogMessage(log, "EXH-1001", expected); - } - - public void testExchangeDeleted() - { - _logMessage = ExchangeMessages.DELETED(); - List<Object> log = performLog(); - - String[] expected = {"Deleted"}; - - validateLogMessage(log, "EXH-1002", expected); - } - - public void testExchangeDiscardedMessage() throws Exception - { - Exchange exchange = BrokerTestHelper.createExchange("test"); - - final String name = exchange.getName(); - final String routingKey = "routingKey"; - - _logMessage = ExchangeMessages.DISCARDMSG(name, routingKey); - List<Object> log = performLog(); - - String[] expected = {"Discarded Message :","Name:", name, "Routing Key:", routingKey}; - - validateLogMessage(log, "EXH-1003", expected); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ManagementConsoleMessagesTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ManagementConsoleMessagesTest.java deleted file mode 100644 index dfc9357402..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ManagementConsoleMessagesTest.java +++ /dev/null @@ -1,98 +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.messages; - -import java.util.List; - -/** - * Test MNG Log Messages - */ -public class ManagementConsoleMessagesTest extends AbstractTestMessages -{ - public void testManagementStartup() - { - _logMessage = ManagementConsoleMessages.STARTUP("My"); - List<Object> log = performLog(); - - String[] expected = {"My Management Startup"}; - - validateLogMessage(log, "MNG-1001", expected); - } - - public void testManagementListening() - { - String transport = "JMX"; - Integer port = 8889; - - _logMessage = ManagementConsoleMessages.LISTENING(transport, port); - List<Object> log = performLog(); - - String[] expected = {"Starting :", transport, ": Listening on port", String.valueOf(port)}; - - validateLogMessage(log, "MNG-1002", expected); - } - - public void testManagementShuttingDown() - { - String transport = "JMX"; - Integer port = 8889; - - _logMessage = ManagementConsoleMessages.SHUTTING_DOWN(transport, port); - List<Object> log = performLog(); - - String[] expected = {"Shutting down :", transport, ": port", String.valueOf(port)}; - - validateLogMessage(log, "MNG-1003", expected); - } - - public void testManagementReady() - { - _logMessage = ManagementConsoleMessages.READY("My"); - List<Object> log = performLog(); - - String[] expected = {"My Management Ready"}; - - validateLogMessage(log, "MNG-1004", expected); - } - - public void testManagementStopped() - { - _logMessage = ManagementConsoleMessages.STOPPED("My"); - List<Object> log = performLog(); - - String[] expected = {"My Management Stopped"}; - - validateLogMessage(log, "MNG-1005", expected); - } - - public void testManagementSSLKeyStore() - { - String path = "/path/to/the/keystore/files.jks"; - - _logMessage = ManagementConsoleMessages.SSL_KEYSTORE(path); - List<Object> log = performLog(); - - String[] expected = {"Using SSL Keystore :", path}; - - validateLogMessage(log, "MNG-1006", expected); - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/MessageStoreMessagesTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/MessageStoreMessagesTest.java deleted file mode 100644 index 3377573b9d..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/MessageStoreMessagesTest.java +++ /dev/null @@ -1,71 +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.messages; - -import java.util.List; - -/** - * Test MST Log Messages - */ -public class MessageStoreMessagesTest extends AbstractTestMessages -{ - public void testMessageStoreCreated() - { - _logMessage = MessageStoreMessages.CREATED(); - List<Object> log = performLog(); - - String[] expected = {"Created"}; - - validateLogMessage(log, "MST-1001", expected); - } - - public void testMessageStoreStoreLocation() - { - String location = "/path/to/the/message/store.files"; - - _logMessage = MessageStoreMessages.STORE_LOCATION(location); - List<Object> log = performLog(); - - String[] expected = {"Store location :", location}; - - validateLogMessage(log, "MST-1002", expected); - } - - public void testMessageStoreClosed() - { - _logMessage = MessageStoreMessages.CLOSED(); - List<Object> log = performLog(); - - String[] expected = {"Closed"}; - - validateLogMessage(log, "MST-1003", expected); - } - - public void testMessageStoreRecoveryStart() - { - _logMessage = MessageStoreMessages.RECOVERY_START(); - List<Object> log = performLog(); - - String[] expected = {"Recovery Start"}; - - validateLogMessage(log, "MST-1004", expected); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/QueueMessagesTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/QueueMessagesTest.java deleted file mode 100644 index d51e6a6bb7..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/QueueMessagesTest.java +++ /dev/null @@ -1,239 +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.messages; - -import java.util.List; - -/** - * Test QUE Log Messages - */ -public class QueueMessagesTest extends AbstractTestMessages -{ - public void testQueueCreatedALL() - { - String owner = "guest"; - Integer priority = 3; - - _logMessage = QueueMessages.CREATED(owner, priority, true, true, true, true, true); - List<Object> log = performLog(); - - String[] expected = {"Create :", "Owner:", owner, "AutoDelete", - "Durable", "Transient", "Priority:", - String.valueOf(priority)}; - - validateLogMessage(log, "QUE-1001", expected); - } - - public void testQueueCreatedOwnerAutoDelete() - { - String owner = "guest"; - - _logMessage = QueueMessages.CREATED(owner, null, true, true, false, false, false); - List<Object> log = performLog(); - - String[] expected = {"Create :", "Owner:", owner, "AutoDelete"}; - - validateLogMessage(log, "QUE-1001", expected); - } - - public void testQueueCreatedOwnerPriority() - { - String owner = "guest"; - Integer priority = 3; - - _logMessage = QueueMessages.CREATED(owner, priority, true, false, false, false, true); - List<Object> log = performLog(); - - String[] expected = {"Create :", "Owner:", owner, "Priority:", - String.valueOf(priority)}; - - validateLogMessage(log, "QUE-1001", expected); - } - - public void testQueueCreatedOwnerAutoDeletePriority() - { - String owner = "guest"; - Integer priority = 3; - - _logMessage = QueueMessages.CREATED(owner, priority, true, true, false, false, true); - List<Object> log = performLog(); - - String[] expected = {"Create :", "Owner:", owner, "AutoDelete", - "Priority:", - String.valueOf(priority)}; - - validateLogMessage(log, "QUE-1001", expected); - } - - public void testQueueCreatedOwnerAutoDeleteTransient() - { - String owner = "guest"; - - _logMessage = QueueMessages.CREATED(owner, null, true, true, false, true, false); - List<Object> log = performLog(); - - String[] expected = {"Create :", "Owner:", owner, "AutoDelete", - "Transient"}; - - validateLogMessage(log, "QUE-1001", expected); - } - - public void testQueueCreatedOwnerAutoDeleteTransientPriority() - { - String owner = "guest"; - Integer priority = 3; - - _logMessage = QueueMessages.CREATED(owner, priority, true, true, false, true, true); - List<Object> log = performLog(); - - String[] expected = {"Create :", "Owner:", owner, "AutoDelete", - "Transient", "Priority:", - String.valueOf(priority)}; - - validateLogMessage(log, "QUE-1001", expected); - } - - public void testQueueCreatedOwnerAutoDeleteDurable() - { - String owner = "guest"; - - _logMessage = QueueMessages.CREATED(owner, null, true, true, true, false, false); - List<Object> log = performLog(); - - String[] expected = {"Create :", "Owner:", owner, "AutoDelete", - "Durable"}; - - validateLogMessage(log, "QUE-1001", expected); - } - - public void testQueueCreatedOwnerAutoDeleteDurablePriority() - { - String owner = "guest"; - Integer priority = 3; - - _logMessage = QueueMessages.CREATED(owner, priority, true, true, true, false, true); - List<Object> log = performLog(); - - String[] expected = {"Create :", "Owner:", owner, "AutoDelete", - "Durable", "Priority:", - String.valueOf(priority)}; - - validateLogMessage(log, "QUE-1001", expected); - } - - public void testQueueCreatedAutoDelete() - { - _logMessage = QueueMessages.CREATED(null, null, false, true, false, false, false); - List<Object> log = performLog(); - - String[] expected = {"Create :", "AutoDelete"}; - - validateLogMessage(log, "QUE-1001", expected); - } - - public void testQueueCreatedPriority() - { - Integer priority = 3; - - _logMessage = QueueMessages.CREATED(null, priority, false, false, false, false, true); - List<Object> log = performLog(); - - String[] expected = {"Create :", "Priority:", - String.valueOf(priority)}; - - validateLogMessage(log, "QUE-1001", expected); - } - - public void testQueueCreatedAutoDeletePriority() - { - Integer priority = 3; - - _logMessage = QueueMessages.CREATED(null, priority, false, true, false, false, true); - List<Object> log = performLog(); - - String[] expected = {"Create :", "AutoDelete", - "Priority:", - String.valueOf(priority)}; - - validateLogMessage(log, "QUE-1001", expected); - } - - public void testQueueCreatedAutoDeleteTransient() - { - _logMessage = QueueMessages.CREATED(null, null, false, true, false, true, false); - List<Object> log = performLog(); - - String[] expected = {"Create :", "AutoDelete", - "Transient"}; - - validateLogMessage(log, "QUE-1001", expected); - } - - public void testQueueCreatedAutoDeleteTransientPriority() - { - Integer priority = 3; - - _logMessage = QueueMessages.CREATED(null, priority, false, true, false, true, true); - List<Object> log = performLog(); - - String[] expected = {"Create :", "AutoDelete", - "Transient", "Priority:", - String.valueOf(priority)}; - - validateLogMessage(log, "QUE-1001", expected); - } - - public void testQueueCreatedAutoDeleteDurable() - { - _logMessage = QueueMessages.CREATED(null, null, false, true, true, false, false); - List<Object> log = performLog(); - - String[] expected = {"Create :", "AutoDelete", - "Durable"}; - - validateLogMessage(log, "QUE-1001", expected); - } - - public void testQueueCreatedAutoDeleteDurablePriority() - { - Integer priority = 3; - - _logMessage = QueueMessages.CREATED(null, priority, false, true, true, false, true); - List<Object> log = performLog(); - - String[] expected = {"Create :", "AutoDelete", - "Durable", "Priority:", - String.valueOf(priority)}; - - validateLogMessage(log, "QUE-1001", expected); - } - - public void testQueueDeleted() - { - _logMessage = QueueMessages.DELETED(); - List<Object> log = performLog(); - - String[] expected = {"Deleted"}; - - validateLogMessage(log, "QUE-1002", expected); - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/SubscriptionMessagesTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/SubscriptionMessagesTest.java deleted file mode 100644 index b2bc351f8f..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/SubscriptionMessagesTest.java +++ /dev/null @@ -1,86 +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.messages; - -import java.util.List; - -/** - * Test SUB Log Messages - */ -public class SubscriptionMessagesTest extends AbstractTestMessages -{ - public void testSubscriptionCreateALL() - { - String arguments = "arguments"; - - _logMessage = SubscriptionMessages.CREATE(arguments, true, true); - List<Object> log = performLog(); - - String[] expected = {"Create :", "Durable", "Arguments :", arguments}; - - validateLogMessage(log, "SUB-1001", expected); - } - - public void testSubscriptionCreateDurable() - { - _logMessage = SubscriptionMessages.CREATE(null, true, false); - List<Object> log = performLog(); - - String[] expected = {"Create :", "Durable"}; - - validateLogMessage(log, "SUB-1001", expected); - } - - public void testSubscriptionCreateArguments() - { - String arguments = "arguments"; - - _logMessage = SubscriptionMessages.CREATE(arguments, false, true); - List<Object> log = performLog(); - - String[] expected = {"Create :","Arguments :", arguments}; - - validateLogMessage(log, "SUB-1001", expected); - } - - - public void testSubscriptionClose() - { - _logMessage = SubscriptionMessages.CLOSE(); - List<Object> log = performLog(); - - String[] expected = {"Close"}; - - validateLogMessage(log, "SUB-1002", expected); - } - - public void testSubscriptionState() - { - String state = "ACTIVE"; - - _logMessage = SubscriptionMessages.STATE(state); - List<Object> log = performLog(); - - String[] expected = {"State :", state}; - - validateLogMessage(log, "SUB-1003", expected); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/VirtualHostMessagesTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/VirtualHostMessagesTest.java deleted file mode 100644 index 17d68ef7c3..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/VirtualHostMessagesTest.java +++ /dev/null @@ -1,51 +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.messages; - -import java.util.List; - -/** - * Test VHT Log Messages - */ -public class VirtualHostMessagesTest extends AbstractTestMessages -{ - public void testVirtualhostCreated() - { - String name = "test"; - _logMessage = VirtualHostMessages.CREATED(name); - List<Object> log = performLog(); - - String[] expected = {"Created :", name}; - - validateLogMessage(log, "VHT-1001", expected); - } - - public void testSubscriptionClosed() - { - _logMessage = VirtualHostMessages.CLOSED(); - List<Object> log = performLog(); - - String[] expected = {"Closed"}; - - validateLogMessage(log, "VHT-1002", expected); - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/AbstractTestLogSubject.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/AbstractTestLogSubject.java deleted file mode 100644 index cd8f13d52e..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/AbstractTestLogSubject.java +++ /dev/null @@ -1,285 +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.subjects; - - -import org.apache.qpid.server.exchange.Exchange; -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.UnitTestMessageLogger; -import org.apache.qpid.server.logging.actors.CurrentActor; -import org.apache.qpid.server.logging.actors.TestLogActor; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.test.utils.QpidTestCase; - -import java.util.List; - -/** - * Abstract Test for LogSubject testing - * Includes common validation code and two common tests. - * - * Each test class sets up the LogSubject and contains details of how to - * validate this class then performs a log statement with logging enabled and - * logging disabled. - * - * The resulting log file is then validated. - * - */ -public abstract class AbstractTestLogSubject extends QpidTestCase -{ - protected LogSubject _subject = null; - - @Override - public void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - } - - @Override - public void tearDown() throws Exception - { - BrokerTestHelper.tearDown(); - try - { - CurrentActor.removeAll(); - } - finally - { - super.tearDown(); - } - } - - protected List<Object> performLog(boolean statusUpdatesEnabled) - { - if (_subject == null) - { - throw new NullPointerException("LogSubject has not been set"); - } - - UnitTestMessageLogger logger = new UnitTestMessageLogger(statusUpdatesEnabled); - - LogActor actor = new TestLogActor(logger); - - actor.message(_subject, new LogMessage() - { - public String toString() - { - return "<Log Message>"; - } - - public String getLogHierarchy() - { - return "test.hierarchy"; - } - }); - - return logger.getLogMessages(); - } - - /** - * Verify that the connection section has the expected items - * - * @param connectionID - The connection id (int) to check for - * @param user - the Connected username - * @param ipString - the ipString/hostname - * @param vhost - the virtualhost that the user connected to. - * @param message - the message these values should appear in. - */ - protected void verifyConnection(long connectionID, String user, String ipString, String vhost, String message) - { - // This should return us MockProtocolSessionUser@null/test - String connectionSlice = getSlice("con:" + connectionID, message); - - assertNotNull("Unable to find connection 'con:" + connectionID + "' in '"+message+"'", - connectionSlice); - - // Exract the userName - String[] userNameParts = connectionSlice.split("@"); - - assertEquals("Unable to split Username from rest of Connection:" - + connectionSlice, 2, userNameParts.length); - - assertEquals("Username not as expected", userNameParts[0], user); - - // Extract IP. - // The connection will be of the format - guest@/127.0.0.1:1/test - // and so our userNamePart will be '/127.0.0.1:1/test' - String[] ipParts = userNameParts[1].split("/"); - - // We will have three sections - assertEquals("Unable to split IP from rest of Connection:" - + userNameParts[1] + " in '"+message+"'", 3, ipParts.length); - - // We need to skip the first '/' split will be empty so validate 1 as IP - assertEquals("IP not as expected", ipString, ipParts[1]); - - //Finally check vhost which is section 2 - assertEquals("Virtualhost name not as expected.", vhost, ipParts[2]); - } - - /** - * Verify that the RoutingKey is present in the provided message. - * - * @param message The message to check - * @param routingKey The routing key to check against - */ - protected void verifyRoutingKey(String message, String routingKey) - { - String routingKeySlice = getSlice("rk", message); - - assertNotNull("Routing Key not found:" + message, routingKeySlice); - - assertEquals("Routing key not correct", - routingKey, routingKeySlice); - } - - /** - * Verify that the given Queue's name exists in the provided message - * - * @param message The message to check - * @param queue The queue to check against - */ - protected void verifyQueue(String message, AMQQueue queue) - { - String queueSlice = getSlice("qu", message); - - assertNotNull("Queue not found:" + message, queueSlice); - - assertEquals("Queue name not correct", - queue.getName(), queueSlice); - } - - /** - * Verify that the given exchange (name and type) are present in the - * provided message. - * - * @param message The message to check - * @param exchange the exchange to check against - */ - protected void verifyExchange(String message, Exchange exchange) - { - String exchangeSilce = getSlice("ex", message); - - assertNotNull("Exchange not found:" + message, exchangeSilce); - - String[] exchangeParts = exchangeSilce.split("/"); - - assertEquals("Exchange should be in two parts ex(type/name)", 2, - exchangeParts.length); - - assertEquals("Exchange type not correct", - exchange.getType().getType(), exchangeParts[0]); - - assertEquals("Exchange name not correct", - exchange.getName(), exchangeParts[1]); - - } - - /** - * Verify that a VirtualHost with the given name appears in the given - * message. - * - * @param message the message to search - * @param vhost the vhostName to check against - */ - static public void verifyVirtualHost(String message, VirtualHost vhost) - { - String vhostSlice = getSlice("vh", message); - - assertNotNull("Virtualhost not found:" + message, vhostSlice); - - assertEquals("Virtualhost not correct", "/" + vhost.getName(), vhostSlice); - } - - /** - * Parse the log message and return the slice according to the following: - * Given Example: - * con:1(guest@127.0.0.1/test)/ch:2/ex(amq.direct)/qu(myQueue)/rk(myQueue) - * - * Each item (except channel) is of the format <key>(<values>) - * - * So Given an ID to slice on: - * con:1 - Connection 1 - * ex - exchange - * qu - queue - * rk - routing key - * - * @param sliceID the slice to locate - * @param message the message to search in - * - * @return the slice if found otherwise null is returned - */ - static public String getSlice(String sliceID, String message) - { - int indexOfSlice = message.indexOf(sliceID + "("); - - if (indexOfSlice == -1) - { - return null; - } - - int endIndex = message.indexOf(')', indexOfSlice); - - if (endIndex == -1) - { - return null; - } - - return message.substring(indexOfSlice + 1 + sliceID.length(), - endIndex); - } - - /** - * Test that when Logging occurs a single log statement is provided - * - */ - public void testEnabled() - { - List<Object> logs = performLog(true); - - assertEquals("Log has incorrect message count", 1, logs.size()); - - validateLogStatement(String.valueOf(logs.get(0))); - } - - /** - * Call to the individiual tests to validate the message is formatted as - * expected - * - * @param message the message whos format needs validation - */ - protected abstract void validateLogStatement(String message); - - /** - * Ensure that when status updates are off this does not perform logging - */ - public void testDisabled() - { - List<Object> logs = performLog(false); - - assertEquals("Log has incorrect message count", 0, logs.size()); - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/BindingLogSubjectTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/BindingLogSubjectTest.java deleted file mode 100644 index e52ead451e..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/BindingLogSubjectTest.java +++ /dev/null @@ -1,80 +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.subjects; - -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.MockAMQQueue; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.server.virtualhost.VirtualHost; - -/** - * Validate BindingLogSubjects are logged as expected - */ -public class BindingLogSubjectTest extends AbstractTestLogSubject -{ - - private AMQQueue _queue; - private String _routingKey; - private Exchange _exchange; - private VirtualHost _testVhost; - - @Override - public void setUp() throws Exception - { - super.setUp(); - - _testVhost = BrokerTestHelper.createVirtualHost("test"); - _routingKey = "RoutingKey"; - _exchange = _testVhost.getExchange("amq.direct"); - _queue = new MockAMQQueue("BindingLogSubjectTest"); - ((MockAMQQueue) _queue).setVirtualHost(_testVhost); - - _subject = new BindingLogSubject(_routingKey, _exchange, _queue); - } - - @Override - public void tearDown() throws Exception - { - if (_testVhost != null) - { - _testVhost.close(); - } - super.tearDown(); - } - - /** - * Validate that the logged Subject message is as expected: - * MESSAGE [Blank][vh(/test)/ex(direct/<<default>>)/qu(BindingLogSubjectTest)/rk(RoutingKey)] <Log Message> - * @param message the message whos format needs validation - */ - @Override - protected void validateLogStatement(String message) - { - verifyVirtualHost(message, _testVhost); - verifyExchange(message, _exchange); - verifyQueue(message, _queue); - verifyRoutingKey(message, _routingKey); - } - - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ChannelLogSubjectTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ChannelLogSubjectTest.java deleted file mode 100644 index a3d96c6d12..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ChannelLogSubjectTest.java +++ /dev/null @@ -1,62 +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.subjects; - -import org.apache.qpid.server.protocol.AMQSessionModel; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * Validate ChannelLogSubjects are logged as expected - */ -public class ChannelLogSubjectTest extends ConnectionLogSubjectTest -{ - private final int _channelID = 1; - - @Override - public void setUp() throws Exception - { - super.setUp(); - - AMQSessionModel session = mock(AMQSessionModel.class); - when(session.getConnectionModel()).thenReturn(getConnection()); - when(session.getChannelId()).thenReturn(_channelID); - _subject = new ChannelLogSubject(session); - } - - /** - * MESSAGE [Blank][con:0(MockProtocolSessionUser@null/test)/ch:1] <Log Message> - * - * @param message the message whos format needs validation - */ - protected void validateLogStatement(String message) - { - // Use the ConnectionLogSubjectTest to vaildate that the connection - // section is ok - super.validateLogStatement(message); - - // Finally check that the channel identifier is correctly added - assertTrue("Channel 1 identifier not found as part of Subject", - message.contains(")/ch:1]")); - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ConnectionLogSubjectTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ConnectionLogSubjectTest.java deleted file mode 100644 index e9a9317102..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ConnectionLogSubjectTest.java +++ /dev/null @@ -1,69 +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.subjects; - -import org.apache.qpid.server.protocol.AMQConnectionModel; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * Validate ConnectionLogSubjects are logged as expected - */ -public class ConnectionLogSubjectTest extends AbstractTestLogSubject -{ - - private static final long CONNECTION_ID = 456l; - private static final String USER = "InternalTestProtocolSession"; - private static final String IP_STRING = "127.0.0.1:1"; - private static final String VHOST = "test"; - - private AMQConnectionModel _connection; - - @Override - public void setUp() throws Exception - { - super.setUp(); - - _connection = mock(AMQConnectionModel.class); - when(_connection.getConnectionId()).thenReturn(CONNECTION_ID); - when(_connection.getPrincipalAsString()).thenReturn(USER); - when(_connection.getRemoteAddressString()).thenReturn("/"+IP_STRING); - when(_connection.getVirtualHostName()).thenReturn(VHOST); - _subject = new ConnectionLogSubject(_connection); - } - - /** - * MESSAGE [Blank][con:0(MockProtocolSessionUser@null/test)] <Log Message> - * - * @param message the message whos format needs validation - */ - protected void validateLogStatement(String message) - { - verifyConnection(CONNECTION_ID, USER, IP_STRING, VHOST, message); - } - - public AMQConnectionModel getConnection() - { - return _connection; - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ExchangeLogSubjectTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ExchangeLogSubjectTest.java deleted file mode 100644 index b327738797..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ExchangeLogSubjectTest.java +++ /dev/null @@ -1,68 +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.subjects; - -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.server.virtualhost.VirtualHost; - - -/** - * Validate ExchangeLogSubjects are logged as expected - */ -public class ExchangeLogSubjectTest extends AbstractTestLogSubject -{ - private Exchange _exchange; - private VirtualHost _testVhost; - - @Override - public void setUp() throws Exception - { - super.setUp(); - - _testVhost = BrokerTestHelper.createVirtualHost("test"); - - _exchange = _testVhost.getExchange("amq.direct"); - _subject = new ExchangeLogSubject(_exchange,_testVhost); - } - - @Override - public void tearDown() throws Exception - { - if (_testVhost != null) - { - _testVhost.close(); - } - super.tearDown(); - } - - /** - * Validate that the logged Subject message is as expected: - * MESSAGE [Blank][vh(/test)/ex(direct/<<default>>)] <Log Message> - * @param message the message whos format needs validation - */ - @Override - protected void validateLogStatement(String message) - { - verifyVirtualHost(message, _testVhost); - verifyExchange(message, _exchange); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/MessageStoreLogSubjectTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/MessageStoreLogSubjectTest.java deleted file mode 100644 index 3d43ef0f44..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/MessageStoreLogSubjectTest.java +++ /dev/null @@ -1,73 +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.subjects; - -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.server.virtualhost.VirtualHost; - -/** - * Validate MessageStoreLogSubjects are logged as expected - */ -public class MessageStoreLogSubjectTest extends AbstractTestLogSubject -{ - private VirtualHost _testVhost; - - @Override - public void setUp() throws Exception - { - super.setUp(); - - _testVhost = BrokerTestHelper.createVirtualHost("test"); - - _subject = new MessageStoreLogSubject(_testVhost.getName(), - _testVhost.getMessageStore().getClass().getSimpleName()); - } - - @Override - public void tearDown() throws Exception - { - if (_testVhost != null) - { - _testVhost.close(); - } - super.tearDown(); - } - - /** - * Validate that the logged Subject message is as expected: - * MESSAGE [Blank][vh(/test)/ms(MemoryMessageStore)] <Log Message> - * @param message the message who's format needs validation - */ - @Override - protected void validateLogStatement(String message) - { - verifyVirtualHost(message, _testVhost); - - String msSlice = getSlice("ms", message); - - assertNotNull("MessageStore not found:" + message, msSlice); - - assertEquals("MessageStore not correct", - _testVhost.getMessageStore().getClass().getSimpleName(), - msSlice); - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/QueueLogSubjectTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/QueueLogSubjectTest.java deleted file mode 100644 index e2765f338b..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/QueueLogSubjectTest.java +++ /dev/null @@ -1,72 +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.subjects; - -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.MockAMQQueue; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.server.virtualhost.VirtualHost; - -/** - * Validate QueueLogSubjects are logged as expected - */ -public class QueueLogSubjectTest extends AbstractTestLogSubject -{ - - private AMQQueue _queue; - private VirtualHost _testVhost; - - @Override - public void setUp() throws Exception - { - super.setUp(); - - _testVhost = BrokerTestHelper.createVirtualHost("test"); - - _queue = new MockAMQQueue("QueueLogSubjectTest"); - ((MockAMQQueue) _queue).setVirtualHost(_testVhost); - - _subject = new QueueLogSubject(_queue); - } - - @Override - public void tearDown() throws Exception - { - if (_testVhost != null) - { - _testVhost.close(); - } - super.tearDown(); - } - - /** - * Validate that the logged Subject message is as expected: - * MESSAGE [Blank][vh(/test)/qu(QueueLogSubjectTest)] <Log Message> - * - * @param message the message whos format needs validation - */ - @Override - protected void validateLogStatement(String message) - { - verifyVirtualHost(message, _testVhost); - verifyQueue(message, _queue); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/SubscriptionLogSubjectTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/SubscriptionLogSubjectTest.java deleted file mode 100644 index b9efac1ae8..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/SubscriptionLogSubjectTest.java +++ /dev/null @@ -1,105 +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.subjects; - -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.MockAMQQueue; -import org.apache.qpid.server.subscription.Subscription; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.server.virtualhost.VirtualHost; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * Validate SubscriptionLogSubjects are logged as expected - */ -public class SubscriptionLogSubjectTest extends AbstractTestLogSubject -{ - - private static final long SUBSCRIPTION_ID = 1; - private AMQQueue _queue; - private VirtualHost _testVhost; - private Subscription _subscription; - - @Override - public void setUp() throws Exception - { - super.setUp(); - - _testVhost = BrokerTestHelper.createVirtualHost("test"); - - _queue = new MockAMQQueue("SubscriptionLogSubjectTest"); - ((MockAMQQueue) _queue).setVirtualHost(_testVhost); - - _subscription = mock(Subscription.class); - when(_subscription.getQueue()).thenReturn(_queue); - when(_subscription.getSubscriptionID()).thenReturn(SUBSCRIPTION_ID); - - _subject = new SubscriptionLogSubject(_subscription); - } - - @Override - public void tearDown() throws Exception - { - if (_testVhost != null) - { - _testVhost.close(); - } - super.tearDown(); - } - - /** - * Validate that the logged Subject message is as expected: - * MESSAGE [Blank][sub:0(vh(/test)/qu(SubscriptionLogSubjectTest))] <Log Message> - * - * @param message the message whos format needs validation - */ - @Override - protected void validateLogStatement(String message) - { - String subscriptionSlice = getSlice("sub:" - + _subscription.getSubscriptionID(), - message); - - assertNotNull("Unable to locate subscription 'sub:" + - _subscription.getSubscriptionID() + "'"); - - - - // Pull out the qu(..) section from the subscription message - // Split it into three parts - // MESSAGE [Blank][sub:0(vh(/ - // test)/ - // qu(SubscriptionLogSubjectTest))] - // Take the last bit and drop off the extra )] - String[] parts = message.split("/"); - assertEquals("Message part count wrong", 3, parts.length); - String subscription = parts[2].substring(0, parts[2].indexOf(")") + 1); - - // Adding the ')' is a bit ugly but SubscriptionLogSubject is the only - // Subject that nests () and so the simple parser of checking for the - // next ')' falls down. - verifyVirtualHost(subscriptionSlice+ ")", _queue.getVirtualHost()); - - verifyQueue(subscription, _queue); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/TestBlankSubject.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/TestBlankSubject.java deleted file mode 100644 index 7684db0b3d..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/TestBlankSubject.java +++ /dev/null @@ -1,33 +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.subjects; - -/** - * Blank Subject for testing - */ -public class TestBlankSubject extends AbstractLogSubject -{ - public TestBlankSubject() - { - setLogString("[TestBlankSubject]"); - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/model/ConfiguredObjectStateTransitionTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/model/ConfiguredObjectStateTransitionTest.java deleted file mode 100644 index 72cf09585c..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/model/ConfiguredObjectStateTransitionTest.java +++ /dev/null @@ -1,266 +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.model; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.apache.qpid.server.BrokerOptions; -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfigurationEntryStore; -import org.apache.qpid.server.configuration.ConfiguredObjectRecoverer; -import org.apache.qpid.server.configuration.RecovererProvider; -import org.apache.qpid.server.configuration.startup.DefaultRecovererProvider; -import org.apache.qpid.server.configuration.store.StoreConfigurationChangeListener; -import org.apache.qpid.server.configuration.updater.TaskExecutor; -import org.apache.qpid.server.security.auth.manager.AnonymousAuthenticationManagerFactory; -import org.apache.qpid.server.security.group.FileGroupManagerFactory; -import org.apache.qpid.server.stats.StatisticsGatherer; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.test.utils.QpidTestCase; - -public class ConfiguredObjectStateTransitionTest extends QpidTestCase -{ - private Broker _broker; - private RecovererProvider _recovererProvider; - private ConfigurationEntryStore _store; - private File _resourceToDelete; - - @Override - public void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - - _broker = BrokerTestHelper.createBrokerMock(); - StatisticsGatherer statisticsGatherer = mock(StatisticsGatherer.class); - TaskExecutor executor = mock(TaskExecutor.class); - when(executor.isTaskExecutorThread()).thenReturn(true); - when(_broker.getTaskExecutor()).thenReturn(executor); - - _recovererProvider = new DefaultRecovererProvider(statisticsGatherer, _broker.getVirtualHostRegistry(), - _broker.getLogRecorder(), _broker.getRootMessageLogger(), executor, new BrokerOptions(), mock(StoreConfigurationChangeListener.class)); - - _store = mock(ConfigurationEntryStore.class); - - _resourceToDelete = new File(TMP_FOLDER, getTestName()); - } - - @Override - public void tearDown() throws Exception - { - try - { - BrokerTestHelper.tearDown(); - if (_resourceToDelete.exists()) - { - _resourceToDelete.delete(); - } - } - finally - { - super.tearDown(); - } - } - - public void testGroupProviderValidStateTransitions() throws Exception - { - ConfigurationEntry providerEntry = getGroupProviderConfigurationEntry(); - ConfiguredObject provider = createConfiguredObject(providerEntry); - provider.setDesiredState(State.INITIALISING, State.QUIESCED); - assertValidStateTransition(provider, State.QUIESCED, State.STOPPED); - - provider = createConfiguredObject(providerEntry); - assertValidStateTransition(provider, State.INITIALISING, State.DELETED); - - providerEntry = getGroupProviderConfigurationEntry(); - provider = createConfiguredObject(providerEntry); - provider.setDesiredState(State.INITIALISING, State.QUIESCED); - assertValidStateTransition(provider, State.QUIESCED, State.DELETED); - - providerEntry = getGroupProviderConfigurationEntry(); - provider = createConfiguredObject(providerEntry); - provider.setDesiredState(State.INITIALISING, State.ACTIVE); - assertValidStateTransition(provider, State.ACTIVE, State.DELETED); - } - - public void testGroupProviderInvalidStateTransitions() throws Exception - { - ConfigurationEntry providerEntry = getGroupProviderConfigurationEntry(); - assertAllInvalidStateTransitions(providerEntry); - } - - public void testAuthenticationProviderValidStateTransitions() - { - ConfigurationEntry providerEntry = getAuthenticationProviderConfigurationEntry(); - assertAllValidStateTransitions(providerEntry); - } - - public void testAuthenticationProviderInvalidStateTransitions() - { - ConfigurationEntry providerEntry = getAuthenticationProviderConfigurationEntry(); - assertAllInvalidStateTransitions(providerEntry); - } - - public void testPortValidStateTransitions() - { - ConfigurationEntry providerEntry = getPortConfigurationEntry(); - assertAllValidStateTransitions(providerEntry); - } - - public void testPortInvalidStateTransitions() - { - ConfigurationEntry providerEntry = getPortConfigurationEntry(); - assertAllInvalidStateTransitions(providerEntry); - } - - private void assertAllInvalidStateTransitions(ConfigurationEntry providerEntry) - { - ConfiguredObject provider = createConfiguredObject(providerEntry); - assertInvalidStateTransition(provider, State.INITIALISING, State.REPLICA); - - provider.setDesiredState(State.INITIALISING, State.QUIESCED); - assertInvalidStateTransition(provider, State.QUIESCED, State.INITIALISING); - - provider.setDesiredState(State.QUIESCED, State.ACTIVE); - assertInvalidStateTransition(provider, State.ACTIVE, State.INITIALISING); - - provider.setDesiredState(State.ACTIVE, State.DELETED); - assertInvalidStateTransition(provider, State.DELETED, State.INITIALISING); - assertInvalidStateTransition(provider, State.DELETED, State.QUIESCED); - assertInvalidStateTransition(provider, State.DELETED, State.ACTIVE); - assertInvalidStateTransition(provider, State.DELETED, State.REPLICA); - assertInvalidStateTransition(provider, State.DELETED, State.ERRORED); - } - - private void assertAllValidStateTransitions(ConfigurationEntry providerEntry) - { - ConfiguredObject provider = createConfiguredObject(providerEntry); - assertNormalStateTransition(provider); - - provider = createConfiguredObject(providerEntry); - provider.setDesiredState(State.INITIALISING, State.QUIESCED); - assertValidStateTransition(provider, State.QUIESCED, State.STOPPED); - - provider = createConfiguredObject(providerEntry); - assertValidStateTransition(provider, State.INITIALISING, State.DELETED); - - provider = createConfiguredObject(providerEntry); - provider.setDesiredState(State.INITIALISING, State.QUIESCED); - assertValidStateTransition(provider, State.QUIESCED, State.DELETED); - - provider = createConfiguredObject(providerEntry); - provider.setDesiredState(State.INITIALISING, State.ACTIVE); - assertValidStateTransition(provider, State.ACTIVE, State.DELETED); - } - - private void assertInvalidStateTransition(ConfiguredObject object, State initialState, State... invalidStates) - { - assertEquals("Unepxceted state", initialState, object.getActualState()); - for (State state : invalidStates) - { - try - { - object.setDesiredState(initialState, state); - } - catch (IllegalStateException e) - { - // expected - } - assertEquals("Transition from state " + initialState + " into state " + state + " did occur", initialState, - object.getActualState()); - } - } - - private void assertValidStateTransition(ConfiguredObject object, State initialState, State... validStateSequence) - { - assertEquals("Unexpected state", initialState, object.getActualState()); - State currentState = initialState; - for (State state : validStateSequence) - { - object.setDesiredState(currentState, state); - assertEquals("Transition from state " + currentState + " into state " + state + " did not occur", state, - object.getActualState()); - currentState = state; - } - } - - private void assertNormalStateTransition(ConfiguredObject object) - { - assertValidStateTransition(object, State.INITIALISING, State.QUIESCED, State.ACTIVE, State.STOPPED, State.DELETED); - } - - private ConfiguredObject createConfiguredObject(ConfigurationEntry entry) - { - @SuppressWarnings("unchecked") - ConfiguredObjectRecoverer<ConfiguredObject> recoverer = - (ConfiguredObjectRecoverer<ConfiguredObject>)_recovererProvider.getRecoverer(entry.getType()); - return recoverer.create(_recovererProvider, entry, _broker); - } - - private ConfigurationEntry createConfigurationEntry(String type, Map<String, Object> attributes, ConfigurationEntryStore store) - { - return new ConfigurationEntry(UUID.randomUUID(), type, attributes, Collections.<UUID>emptySet(), store); - } - - private ConfigurationEntry getAuthenticationProviderConfigurationEntry() - { - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(AuthenticationProvider.NAME, getTestName()); - attributes.put(AuthenticationProvider.TYPE, AnonymousAuthenticationManagerFactory.PROVIDER_TYPE); - return createConfigurationEntry(AuthenticationProvider.class.getSimpleName(), attributes , _store); - } - - private ConfigurationEntry getGroupProviderConfigurationEntry() throws Exception - { - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(GroupProvider.NAME, getTestName()); - attributes.put(GroupProvider.TYPE, FileGroupManagerFactory.GROUP_FILE_PROVIDER_TYPE); - attributes.put(FileGroupManagerFactory.PATH, _resourceToDelete.getAbsolutePath()); - if (!_resourceToDelete.exists()) - { - _resourceToDelete.createNewFile(); - } - return createConfigurationEntry(GroupProvider.class.getSimpleName(), attributes , _store); - } - - private ConfigurationEntry getPortConfigurationEntry() - { - ConfigurationEntry authProviderEntry = getAuthenticationProviderConfigurationEntry(); - AuthenticationProvider authProvider = (AuthenticationProvider)createConfiguredObject(authProviderEntry); - - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(Port.NAME, getTestName()); - attributes.put(Port.PROTOCOLS, Collections.<Protocol>singleton(Protocol.HTTP)); - attributes.put(Port.AUTHENTICATION_PROVIDER, authProvider.getName()); - attributes.put(Port.PORT, 0); - - when(_broker.findAuthenticationProviderByName(authProvider.getName())).thenReturn(authProvider); - return createConfigurationEntry(Port.class.getSimpleName(), attributes , _store); - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/model/UUIDGeneratorTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/model/UUIDGeneratorTest.java deleted file mode 100644 index c686a24e99..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/model/UUIDGeneratorTest.java +++ /dev/null @@ -1,217 +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.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); - UUID id8 = UUIDGenerator.generateGroupUUID(value, value); - idSet.add(id8); - UUID id9 = UUIDGenerator.generateGroupMemberUUID(value, value, value); - idSet.add(id9); - - assertEquals("The produced UUIDs were not all unique", 9, 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/qpid/java/broker/src/test/java/org/apache/qpid/server/model/VirtualHostTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/model/VirtualHostTest.java deleted file mode 100644 index ce213ee582..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/model/VirtualHostTest.java +++ /dev/null @@ -1,147 +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.model; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import junit.framework.TestCase; - -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.RecovererProvider; -import org.apache.qpid.server.configuration.startup.VirtualHostRecoverer; -import org.apache.qpid.server.configuration.updater.TaskExecutor; -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.stats.StatisticsGatherer; -import org.apache.qpid.server.store.TestMemoryMessageStore; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.server.virtualhost.StandardVirtualHostFactory; - -public class VirtualHostTest extends TestCase -{ - - private Broker _broker; - private StatisticsGatherer _statisticsGatherer; - private RecovererProvider _recovererProvider; - - @Override - protected void setUp() throws Exception - { - super.setUp(); - CurrentActor.set(new TestLogActor(new SystemOutMessageLogger())); - - _broker = BrokerTestHelper.createBrokerMock(); - TaskExecutor taslExecutor = mock(TaskExecutor.class); - when(taslExecutor.isTaskExecutorThread()).thenReturn(true); - when(_broker.getTaskExecutor()).thenReturn(taslExecutor); - - _recovererProvider = mock(RecovererProvider.class); - _statisticsGatherer = mock(StatisticsGatherer.class); - } - - @Override - protected void tearDown() throws Exception - { - super.tearDown(); - CurrentActor.remove(); - } - - public void testInitialisingState() - { - VirtualHost host = createHost(); - - assertEquals("Unexpected state", State.INITIALISING, host.getAttribute(VirtualHost.STATE)); - } - - public void testActiveState() - { - VirtualHost host = createHost(); - - host.setDesiredState(State.INITIALISING, State.ACTIVE); - assertEquals("Unexpected state", State.ACTIVE, host.getAttribute(VirtualHost.STATE)); - } - - public void testQuiescedState() - { - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(VirtualHost.NAME, getName()); - attributes.put(VirtualHost.TYPE, StandardVirtualHostFactory.TYPE); - attributes.put(VirtualHost.STORE_TYPE, TestMemoryMessageStore.TYPE); - attributes.put(VirtualHost.STATE, State.QUIESCED); - - VirtualHost host = createHost(attributes); - - assertEquals("Unexpected state", State.QUIESCED, host.getAttribute(VirtualHost.STATE)); - - host.setDesiredState(State.QUIESCED, State.ACTIVE); - assertEquals("Unexpected state", State.ACTIVE, host.getAttribute(VirtualHost.STATE)); - } - - public void testStoppedState() - { - VirtualHost host = createHost(); - - assertEquals("Unexpected state", State.INITIALISING, host.getAttribute(VirtualHost.STATE)); - - host.setDesiredState(State.INITIALISING, State.ACTIVE); - assertEquals("Unexpected state", State.ACTIVE, host.getAttribute(VirtualHost.STATE)); - - host.setDesiredState(State.ACTIVE, State.STOPPED); - assertEquals("Unexpected state", State.STOPPED, host.getAttribute(VirtualHost.STATE)); - } - - public void testDeletedState() - { - VirtualHost host = createHost(); - - assertEquals("Unexpected state", State.INITIALISING, host.getAttribute(VirtualHost.STATE)); - - host.setDesiredState(State.INITIALISING, State.DELETED); - assertEquals("Unexpected state", State.DELETED, host.getAttribute(VirtualHost.STATE)); - } - - private VirtualHost createHost() - { - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(VirtualHost.NAME, getName()); - attributes.put(VirtualHost.TYPE, StandardVirtualHostFactory.TYPE); - attributes.put(VirtualHost.STORE_TYPE, TestMemoryMessageStore.TYPE); - - VirtualHost host = createHost(attributes); - return host; - } - - private VirtualHost createHost(Map<String, Object> attributes) - { - ConfigurationEntry entry = new ConfigurationEntry(UUID.randomUUID(), VirtualHost.class.getSimpleName(), attributes, - Collections.<UUID> emptySet(), null); - - return new VirtualHostRecoverer(_statisticsGatherer).create(_recovererProvider, entry, _broker); - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/model/adapter/AuthenticationProviderFactoryTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/model/adapter/AuthenticationProviderFactoryTest.java deleted file mode 100644 index ed22843e07..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/model/adapter/AuthenticationProviderFactoryTest.java +++ /dev/null @@ -1,156 +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.model.adapter; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.mockito.Mockito.any; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.never; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import junit.framework.TestCase; - -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.PasswordCredentialManagingAuthenticationProvider; -import org.apache.qpid.server.plugin.AuthenticationManagerFactory; -import org.apache.qpid.server.plugin.QpidServiceLoader; -import org.apache.qpid.server.security.auth.manager.AuthenticationManager; -import org.apache.qpid.server.security.auth.manager.PrincipalDatabaseAuthenticationManager; - -public class AuthenticationProviderFactoryTest extends TestCase -{ - private PreferencesProviderCreator _preferencesProviderCreator = mock(PreferencesProviderCreator.class); - - public void testCreatePasswordCredentialManagingAuthenticationProvider() - { - AuthenticationManager am = mock(PrincipalDatabaseAuthenticationManager.class); - AuthenticationProvider provider = testForFactory(am, true); - assertTrue("The created provider should match the factory's AuthenticationManager type", - provider instanceof PasswordCredentialManagingAuthenticationProvider); - verify(am).onCreate(); - } - - public void testCreateNonPasswordCredentialManagingAuthenticationProvider() - { - AuthenticationManager am = mock(AuthenticationManager.class); - AuthenticationProvider provider = testForFactory(am, true); - assertFalse("The created provider should match the factory's AuthenticationManager type", - provider instanceof PasswordCredentialManagingAuthenticationProvider); - verify(am).onCreate(); - } - - public void testRecoverPasswordCredentialManagingAuthenticationProvider() - { - AuthenticationManager am = mock(PrincipalDatabaseAuthenticationManager.class); - AuthenticationProvider provider = testForFactory(am, false); - assertTrue("The created provider should match the factory's AuthenticationManager type", - provider instanceof PasswordCredentialManagingAuthenticationProvider); - verify(am, never()).onCreate(); - } - - public void testRecoverNonPasswordCredentialManagingAuthenticationProvider() - { - AuthenticationManager am = mock(AuthenticationManager.class); - AuthenticationProvider provider = testForFactory(am, false); - assertFalse("The created provider should match the factory's AuthenticationManager type", - provider instanceof PasswordCredentialManagingAuthenticationProvider); - verify(am, never()).onCreate(); - } - - @SuppressWarnings("unchecked") - private AuthenticationProvider testForFactory(AuthenticationManager authenticationManager, boolean create) - { - UUID id = UUID.randomUUID(); - Map<String, Object> attributes = new HashMap<String, Object>(); - - QpidServiceLoader<AuthenticationManagerFactory> authManagerFactoryServiceLoader = mock(QpidServiceLoader.class); - AuthenticationManagerFactory authenticationManagerFactory = mock(AuthenticationManagerFactory.class); - - Broker broker = mock(Broker.class); - - when(authManagerFactoryServiceLoader.atLeastOneInstanceOf(AuthenticationManagerFactory.class)).thenReturn( - Collections.singleton(authenticationManagerFactory)); - when(authenticationManagerFactory.createInstance(attributes)).thenReturn(authenticationManager); - - AuthenticationProviderFactory providerFactory = new AuthenticationProviderFactory(authManagerFactoryServiceLoader, _preferencesProviderCreator); - - AuthenticationProvider provider = null; - if (create) - { - provider = providerFactory.create(id, broker, attributes); - } - else - { - provider = providerFactory.recover(id, attributes, broker); - } - - assertNotNull("Provider is not created", provider); - assertEquals("Unexpected ID", id, provider.getId()); - - return provider; - } - - public void testCreatePasswordCredentialManagingAuthenticationProviderFailsWhenAnotherOneAlready() - { - Broker broker = mock(Broker.class); - PasswordCredentialManagingAuthenticationProvider anotherProvider = mock(PasswordCredentialManagingAuthenticationProvider.class); - when(broker.getAuthenticationProviders()).thenReturn(Collections.<AuthenticationProvider>singleton(anotherProvider)); - - QpidServiceLoader<AuthenticationManagerFactory> loader = mock(QpidServiceLoader.class); - AuthenticationManagerFactory managerFactory = mock(AuthenticationManagerFactory.class); - when(managerFactory.createInstance(any(Map.class))).thenReturn(mock(PrincipalDatabaseAuthenticationManager.class)); - when(loader.atLeastOneInstanceOf(AuthenticationManagerFactory.class)).thenReturn(Collections.singleton(managerFactory)); - - AuthenticationProviderFactory providerFactory = new AuthenticationProviderFactory(loader, _preferencesProviderCreator); - - UUID randomUUID = UUID.randomUUID(); - AuthenticationProvider provider = providerFactory.create(randomUUID, broker, new HashMap<String, Object>()); - - assertNotNull("Provider is not created", provider); - assertEquals("Unexpected ID", randomUUID, provider.getId()); - } - - @SuppressWarnings("unchecked") - public void testCreateNonPasswordCredentialManagingAuthenticationProviderWhenAnotherOneAlreadyExist() - { - Broker broker = mock(Broker.class); - AuthenticationProvider anotherProvider = mock(AuthenticationProvider.class); - when(broker.getAuthenticationProviders()).thenReturn(Collections.singleton(anotherProvider)); - - QpidServiceLoader<AuthenticationManagerFactory> loader = mock(QpidServiceLoader.class); - AuthenticationManagerFactory managerFactory = mock(AuthenticationManagerFactory.class); - when(managerFactory.createInstance(any(Map.class))).thenReturn(mock(AuthenticationManager.class)); - when(loader.atLeastOneInstanceOf(AuthenticationManagerFactory.class)).thenReturn(Collections.singleton(managerFactory)); - - AuthenticationProviderFactory providerFactory = new AuthenticationProviderFactory(loader, _preferencesProviderCreator); - UUID id = UUID.randomUUID(); - AuthenticationProvider provider = providerFactory.create(id, broker, new HashMap<String, Object>()); - - assertNotNull("Provider is not created", provider); - assertEquals("Unexpected ID", id, provider.getId()); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/model/adapter/FileSystemPreferencesProviderFactoryTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/model/adapter/FileSystemPreferencesProviderFactoryTest.java deleted file mode 100644 index 64dfad94c3..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/model/adapter/FileSystemPreferencesProviderFactoryTest.java +++ /dev/null @@ -1,139 +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.model.adapter; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.PreferencesProvider; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.test.utils.TestFileUtils; - -public class FileSystemPreferencesProviderFactoryTest extends QpidTestCase -{ - private AuthenticationProvider _authenticationProvider; - private Broker _broker; - private FileSystemPreferencesProviderFactory _factory; - - public void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - _authenticationProvider = mock(AuthenticationProvider.class); - _broker = BrokerTestHelper.createBrokerMock(); - when(_authenticationProvider.getParent(Broker.class)).thenReturn(_broker); - _factory = new FileSystemPreferencesProviderFactory(); - } - - public void tearDown() throws Exception - { - try - { - BrokerTestHelper.tearDown(); - } - finally - { - super.tearDown(); - } - } - - public void testGetType() - { - assertEquals(FileSystemPreferencesProvider.PROVIDER_TYPE, _factory.getType()); - } - - public void testCreateInstanceRecovering() - { - Map<String, Object> attributes = new HashMap<String, Object>(); - UUID id = UUID.randomUUID(); - attributes.put(PreferencesProvider.TYPE, FileSystemPreferencesProvider.class); - attributes.put(PreferencesProvider.NAME, "test-provider"); - File file = TestFileUtils.createTempFile(this, ".prefs.json", "{\"test_user\":{\"pref1\": \"pref1Value\", \"pref2\": 1.0} }"); - try - { - attributes.put(FileSystemPreferencesProvider.PATH, file.getAbsolutePath()); - PreferencesProvider provider = _factory.createInstance(id, attributes, _authenticationProvider); - assertNotNull("Preferences provider was not instantiated", provider); - assertEquals("Unexpected name", "test-provider", provider.getName()); - assertEquals("Unexpected id", id, provider.getId()); - assertEquals("Unexpected path", file.getAbsolutePath(), - provider.getAttribute(FileSystemPreferencesProvider.PATH)); - } - finally - { - file.delete(); - } - } - - public void testCreateInstanceRecoveringWhenPrefStoreDoesNotExist() - { - Map<String, Object> attributes = new HashMap<String, Object>(); - UUID id = UUID.randomUUID(); - attributes.put(PreferencesProvider.TYPE, FileSystemPreferencesProvider.class); - attributes.put(PreferencesProvider.NAME, "test-provider"); - File file = new File(TMP_FOLDER, UUID.randomUUID() + "prefs.json"); - assertFalse("Preferences store file should not exist", file.exists()); - try - { - attributes.put(FileSystemPreferencesProvider.PATH, file.getAbsolutePath()); - _factory.createInstance(id, attributes, _authenticationProvider); - } - catch (IllegalConfigurationException e) - { - // exception should be thrown if preferences store does not exist - } - } - - public void testCreateInstanceNotRecovering() - { - Map<String, Object> attributes = new HashMap<String, Object>(); - UUID id = UUID.randomUUID(); - attributes.put(PreferencesProvider.TYPE, FileSystemPreferencesProvider.class); - attributes.put(PreferencesProvider.NAME, "test-provider"); - File file = new File(TMP_FOLDER, UUID.randomUUID() + "prefs.json"); - assertFalse("Preferences store file should not exist", file.exists()); - try - { - attributes.put(FileSystemPreferencesProvider.PATH, file.getAbsolutePath()); - PreferencesProvider provider = _factory.createInstance(id, attributes, _authenticationProvider); - assertNotNull("Preferences provider was not recovered", provider); - assertEquals("Unexpected name", "test-provider", provider.getName()); - assertEquals("Unexpected id", id, provider.getId()); - assertEquals("Unexpected path", file.getAbsolutePath(), provider.getAttribute(FileSystemPreferencesProvider.PATH)); - assertTrue("Preferences store file should exist", file.exists()); - } - finally - { - file.delete(); - } - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/model/adapter/FileSystemPreferencesProviderTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/model/adapter/FileSystemPreferencesProviderTest.java deleted file mode 100644 index 0eab93541f..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/model/adapter/FileSystemPreferencesProviderTest.java +++ /dev/null @@ -1,266 +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.model.adapter; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -import org.apache.qpid.server.configuration.updater.TaskExecutor; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.State; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.test.utils.TestFileUtils; - -public class FileSystemPreferencesProviderTest extends QpidTestCase -{ - private static final String TEST_PREFERENCES = "{\"user1\":{\"pref1\":\"pref1User1Value\", \"pref2\": true, \"pref3\": 1.0, \"pref4\": 2}," - + "\"user2\":{\"pref1\":\"pref1User2Value\", \"pref2\": false, \"pref3\": 2.0, \"pref4\": 3}}"; - private FileSystemPreferencesProvider _preferencesProvider; - private AuthenticationProvider _authenticationProvider; - private Broker _broker; - private String _user1, _user2; - private File _preferencesFile; - - protected void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - _authenticationProvider = mock(AuthenticationProvider.class); - _user1 = "user1"; - _user2 = "user2"; - _preferencesFile = TestFileUtils.createTempFile(this, ".prefs.json", TEST_PREFERENCES); - - _broker = BrokerTestHelper.createBrokerMock(); - TaskExecutor taslExecutor = mock(TaskExecutor.class); - when(taslExecutor.isTaskExecutorThread()).thenReturn(true); - when(_broker.getTaskExecutor()).thenReturn(taslExecutor); - when(_authenticationProvider.getParent(Broker.class)).thenReturn(_broker); - } - - protected void tearDown() throws Exception - { - try - { - BrokerTestHelper.tearDown(); - _preferencesFile.delete(); - } - finally - { - super.tearDown(); - } - } - - public void testConstructionWithExistingFile() - { - _preferencesProvider = createPreferencesProvider(); - assertEquals(State.INITIALISING, _preferencesProvider.getActualState()); - } - - public void testConstructionWithNonExistingFile() - { - File nonExistingFile = new File(TMP_FOLDER, "preferences-" + UUID.randomUUID() + ".json"); - assertFalse("Preferences file exists", nonExistingFile.exists()); - try - { - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(FileSystemPreferencesProvider.PATH, nonExistingFile.getAbsolutePath()); - _preferencesProvider = new FileSystemPreferencesProvider(UUID.randomUUID(), attributes, _authenticationProvider, _broker.getTaskExecutor()); - _preferencesProvider.createStoreIfNotExist(); - assertEquals(State.INITIALISING, _preferencesProvider.getActualState()); - assertTrue("Preferences file was not created", nonExistingFile.exists()); - } - finally - { - nonExistingFile.delete(); - } - } - - public void testConstructionWithEmptyFile() throws Exception - { - File emptyPrefsFile = new File(TMP_FOLDER, "preferences-" + UUID.randomUUID() + ".json"); - emptyPrefsFile.createNewFile(); - assertTrue("Preferences file does notexists", emptyPrefsFile.exists()); - try - { - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(FileSystemPreferencesProvider.PATH, emptyPrefsFile.getAbsolutePath()); - _preferencesProvider = new FileSystemPreferencesProvider(UUID.randomUUID(), attributes, _authenticationProvider, _broker.getTaskExecutor()); - assertEquals(State.INITIALISING, _preferencesProvider.getActualState()); - } - finally - { - emptyPrefsFile.delete(); - } - } - - public void testActivate() - { - _preferencesProvider = createPreferencesProvider(); - _preferencesProvider.setDesiredState(State.INITIALISING, State.ACTIVE); - - assertEquals("Unexpexpected state", State.ACTIVE, _preferencesProvider.getActualState()); - } - - public void testChangeAttributes() - { - _preferencesProvider = createPreferencesProvider(); - _preferencesProvider.setDesiredState(State.INITIALISING, State.ACTIVE); - - File newPrefsFile = TestFileUtils.createTempFile(this, ".prefs.json", "{\"user3\":{\"pref1\":\"pref1User3Value\", \"pref3\": 2.0}}"); - try - { - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(FileSystemPreferencesProvider.PATH, newPrefsFile.getAbsolutePath()); - _preferencesProvider.changeAttributes(attributes); - assertEquals("Unexpected path", newPrefsFile.getAbsolutePath(), - _preferencesProvider.getAttribute(FileSystemPreferencesProvider.PATH)); - - Map<String, Object> preferences1 = _preferencesProvider.getPreferences(_user1); - assertTrue("Unexpected preferences for user1", preferences1.isEmpty()); - - String user3 = "user3"; - Map<String, Object> preferences3 = _preferencesProvider.getPreferences(user3); - assertFalse("No preference found for user3", preferences3.isEmpty()); - assertEquals("Unexpected preference 1 for user 3", "pref1User3Value", preferences3.get("pref1")); - assertEquals("Unexpected preference 3 for user 3", 2.0, ((Number) preferences3.get("pref3")).floatValue(), 0.01); - } - finally - { - newPrefsFile.delete(); - } - } - - public void testGetPreferences() - { - _preferencesProvider = createPreferencesProvider(); - _preferencesProvider.setDesiredState(State.INITIALISING, State.ACTIVE); - - Map<String, Object> preferences1 = _preferencesProvider.getPreferences(_user1); - assertUser1Preferences(preferences1); - - Map<String, Object> preferences2 = _preferencesProvider.getPreferences(_user2); - assertUser2Preferences(preferences2); - - String user3 = "user3"; - Map<String, Object> preferences3 = _preferencesProvider.getPreferences(user3); - assertTrue("No preference found for user3", preferences3.isEmpty()); - } - - public void testSetPrefernces() - { - _preferencesProvider = createPreferencesProvider(); - _preferencesProvider.setDesiredState(State.INITIALISING, State.ACTIVE); - - Map<String, Object> newPreferences = new HashMap<String, Object>(); - newPreferences.put("pref2", false); - newPreferences.put("pref4", 8); - Map<String, Object> pref5 = new HashMap<String, Object>(); - pref5.put("test1", "test1Value"); - pref5.put("test2", 5); - newPreferences.put("pref5", pref5); - - _preferencesProvider.setPreferences(_user1, newPreferences); - - FileSystemPreferencesProvider newProvider = createPreferencesProvider(); - Map<String, Object> preferences1 = newProvider.getPreferences(_user1); - assertNotNull("Preferences should not be null for user 1", preferences1); - assertEquals("Unexpected preference 1 for user 1", "pref1User1Value", preferences1.get("pref1")); - assertEquals("Unexpected preference 2 for user 1", false, preferences1.get("pref2")); - assertEquals("Unexpected preference 3 for user 1", 1.0, ((Number) preferences1.get("pref3")).floatValue(), 0.01); - assertEquals("Unexpected preference 4 for user 1", 8, preferences1.get("pref4")); - assertNotNull("Unexpected preference 5 for user 1", preferences1.get("pref5")); - assertEquals("Unexpected preference 5 for user 1", pref5, preferences1.get("pref5")); - - Map<String, Object> preferences2 = newProvider.getPreferences(_user2); - assertUser2Preferences(preferences2); - - String user3 = "user3"; - Map<String, Object> preferences3 = newProvider.getPreferences(user3); - assertTrue("No preference found for user3", preferences3.isEmpty()); - } - - public void testDeletePrefernces() - { - _preferencesProvider = createPreferencesProvider(); - _preferencesProvider.setDesiredState(State.INITIALISING, State.ACTIVE); - - _preferencesProvider.deletePreferences(_user1); - - FileSystemPreferencesProvider newProvider = createPreferencesProvider(); - Map<String, Object> preferences1 = newProvider.getPreferences(_user1); - assertTrue("Preferences should not be set for user 1", preferences1.isEmpty()); - - Map<String, Object> preferences2 = newProvider.getPreferences(_user2); - assertUser2Preferences(preferences2); - - String user3 = "user3"; - Map<String, Object> preferences3 = newProvider.getPreferences(user3); - assertTrue("No preference found for user3", preferences3.isEmpty()); - } - - public void testListUserNames() - { - _preferencesProvider = createPreferencesProvider(); - _preferencesProvider.setDesiredState(State.INITIALISING, State.ACTIVE); - - Set<String> userNames = _preferencesProvider.listUserIDs(); - - assertEquals("Unexpected user names", new HashSet<String>(Arrays.asList("user1", "user2")), userNames); - } - - private FileSystemPreferencesProvider createPreferencesProvider() - { - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(FileSystemPreferencesProvider.PATH, _preferencesFile.getAbsolutePath()); - attributes.put(FileSystemPreferencesProvider.NAME, "test"); - return _preferencesProvider = new FileSystemPreferencesProvider(UUID.randomUUID(), attributes, _authenticationProvider, _broker.getTaskExecutor()); - } - - private void assertUser1Preferences(Map<String, Object> preferences1) - { - assertNotNull("Preferences should not be null for user 1", preferences1); - assertEquals("Unexpected preference 1 for user 1", "pref1User1Value", preferences1.get("pref1")); - assertEquals("Unexpected preference 2 for user 1", true, preferences1.get("pref2")); - assertEquals("Unexpected preference 3 for user 1", 1.0, ((Number) preferences1.get("pref3")).floatValue(), 0.01); - assertEquals("Unexpected preference 4 for user 1", 2, preferences1.get("pref4")); - assertNull("Unexpected preference 5 for user 1", preferences1.get("pref5")); - } - - private void assertUser2Preferences(Map<String, Object> preferences2) - { - assertNotNull("Preferences should not be null for user 2", preferences2); - assertEquals("Unexpected preference 1 for user 2", "pref1User2Value", preferences2.get("pref1")); - assertEquals("Unexpected preference 2 for user 2", false, preferences2.get("pref2")); - assertEquals("Unexpected preference 2 for user 2", 2.0, ((Number) preferences2.get("pref3")).floatValue(), 0.01); - assertEquals("Unexpected preference 3 for user 2", 3, preferences2.get("pref4")); - assertNull("Unexpected preference 5 for user 2", preferences2.get("pref5")); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/model/adapter/PortFactoryTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/model/adapter/PortFactoryTest.java deleted file mode 100644 index 54826b8c88..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/model/adapter/PortFactoryTest.java +++ /dev/null @@ -1,389 +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.model.adapter; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.mockito.Mockito.any; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -import org.apache.qpid.server.configuration.BrokerProperties; -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.KeyStore; -import org.apache.qpid.server.model.Port; -import org.apache.qpid.server.model.Protocol; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.model.TrustStore; -import org.apache.qpid.test.utils.QpidTestCase; - -public class PortFactoryTest extends QpidTestCase -{ - private UUID _portId = UUID.randomUUID(); - private int _portNumber = 123; - private Set<String> _tcpStringSet = Collections.singleton(Transport.TCP.name()); - private Set<Transport> _tcpTransportSet = Collections.singleton(Transport.TCP); - private Set<String> _sslStringSet = Collections.singleton(Transport.SSL.name()); - private Set<Transport> _sslTransportSet = Collections.singleton(Transport.SSL); - - private Map<String, Object> _attributes = new HashMap<String, Object>(); - - private Broker _broker = mock(Broker.class); - private KeyStore _keyStore = mock(KeyStore.class); - private TrustStore _trustStore = mock(TrustStore.class); - private String _authProviderName = "authProvider"; - private AuthenticationProvider _authProvider = mock(AuthenticationProvider.class); - private PortFactory _portFactory; - - @Override - protected void setUp() throws Exception - { - when(_broker.findAuthenticationProviderByName(_authProviderName)).thenReturn(_authProvider); - - setTestSystemProperty(BrokerProperties.PROPERTY_BROKER_DEFAULT_AMQP_PROTOCOL_EXCLUDES, null); - setTestSystemProperty(BrokerProperties.PROPERTY_BROKER_DEFAULT_AMQP_PROTOCOL_INCLUDES, null); - _portFactory = new PortFactory(); - - _attributes.put(Port.PORT, _portNumber); - _attributes.put(Port.TRANSPORTS, _tcpStringSet); - _attributes.put(Port.AUTHENTICATION_PROVIDER, _authProviderName); - _attributes.put(Port.TCP_NO_DELAY, "true"); - _attributes.put(Port.RECEIVE_BUFFER_SIZE, "1"); - _attributes.put(Port.SEND_BUFFER_SIZE, "2"); - _attributes.put(Port.BINDING_ADDRESS, "127.0.0.1"); - } - - public void testDefaultProtocols() - { - Collection<Protocol> protocols = _portFactory.getDefaultProtocols(); - EnumSet<Protocol> expected = EnumSet.of(Protocol.AMQP_0_8, Protocol.AMQP_0_9, Protocol.AMQP_0_9_1, Protocol.AMQP_0_10, - Protocol.AMQP_1_0); - assertEquals("Unexpected protocols", new HashSet<Protocol>(expected), new HashSet<Protocol>(protocols)); - } - - public void testDefaultProtocolsWhenProtocolExcludeSystemPropertyIsSet() - { - setTestSystemProperty(BrokerProperties.PROPERTY_BROKER_DEFAULT_AMQP_PROTOCOL_EXCLUDES, Protocol.AMQP_1_0.name() + "," - + Protocol.AMQP_0_10.name()); - _portFactory = new PortFactory(); - Collection<Protocol> protocols = _portFactory.getDefaultProtocols(); - EnumSet<Protocol> expected = EnumSet.of(Protocol.AMQP_0_8, Protocol.AMQP_0_9, Protocol.AMQP_0_9_1); - assertEquals("Unexpected protocols", new HashSet<Protocol>(expected), new HashSet<Protocol>(protocols)); - } - - public void testDefaultProtocolsWhenProtocolIncludeSystemPropertyIsSet() - { - setTestSystemProperty(BrokerProperties.PROPERTY_BROKER_DEFAULT_AMQP_PROTOCOL_EXCLUDES, Protocol.AMQP_1_0.name() + "," - + Protocol.AMQP_0_10.name() + "," + Protocol.AMQP_0_9_1.name()); - setTestSystemProperty(BrokerProperties.PROPERTY_BROKER_DEFAULT_AMQP_PROTOCOL_INCLUDES, Protocol.AMQP_0_10.name() + "," - + Protocol.AMQP_0_9_1.name()); - _portFactory = new PortFactory(); - Collection<Protocol> protocols = _portFactory.getDefaultProtocols(); - EnumSet<Protocol> expected = EnumSet.of(Protocol.AMQP_0_8, Protocol.AMQP_0_9, Protocol.AMQP_0_9_1, Protocol.AMQP_0_10); - assertEquals("Unexpected protocols", new HashSet<Protocol>(expected), new HashSet<Protocol>(protocols)); - } - - public void testCreatePortWithMinimumAttributes() - { - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(Port.PORT, 1); - attributes.put(Port.AUTHENTICATION_PROVIDER, _authProviderName); - Port port = _portFactory.createPort(_portId, _broker, attributes); - - assertNotNull(port); - assertTrue(port instanceof AmqpPortAdapter); - assertEquals("Unexpected port", 1, port.getPort()); - assertEquals("Unexpected transports", Collections.singleton(PortFactory.DEFAULT_TRANSPORT), port.getTransports()); - assertEquals("Unexpected protocols", _portFactory.getDefaultProtocols(), port.getProtocols()); - assertEquals("Unexpected send buffer size", PortFactory.DEFAULT_AMQP_SEND_BUFFER_SIZE, - port.getAttribute(Port.SEND_BUFFER_SIZE)); - assertEquals("Unexpected receive buffer size", PortFactory.DEFAULT_AMQP_RECEIVE_BUFFER_SIZE, - port.getAttribute(Port.RECEIVE_BUFFER_SIZE)); - assertEquals("Unexpected need client auth", PortFactory.DEFAULT_AMQP_NEED_CLIENT_AUTH, - port.getAttribute(Port.NEED_CLIENT_AUTH)); - assertEquals("Unexpected want client auth", PortFactory.DEFAULT_AMQP_WANT_CLIENT_AUTH, - port.getAttribute(Port.WANT_CLIENT_AUTH)); - assertEquals("Unexpected tcp no delay", PortFactory.DEFAULT_AMQP_TCP_NO_DELAY, port.getAttribute(Port.TCP_NO_DELAY)); - assertEquals("Unexpected binding", PortFactory.DEFAULT_AMQP_BINDING, port.getAttribute(Port.BINDING_ADDRESS)); - } - - public void testCreateAmqpPort() - { - createAmqpPortTestImpl(false, false, false, null, null); - } - - public void testCreateAmqpPortUsingSslFailsWithoutKeyStore() - { - try - { - createAmqpPortTestImpl(true, false, false, null, null); - fail("expected exception due to lack of SSL keystore"); - } - catch(IllegalConfigurationException e) - { - //expected - } - } - - public void testCreateAmqpPortUsingSslSucceedsWithKeyStore() - { - String keyStoreName = "myKeyStore"; - when(_broker.findKeyStoreByName(keyStoreName)).thenReturn(_keyStore); - - createAmqpPortTestImpl(true, false, false, keyStoreName, null); - } - - public void testCreateAmqpPortNeedingClientAuthFailsWithoutTrustStore() - { - String keyStoreName = "myKeyStore"; - when(_broker.findKeyStoreByName(keyStoreName)).thenReturn(_keyStore); - - when(_broker.findTrustStoreByName(any(String.class))).thenReturn(null); - - try - { - createAmqpPortTestImpl(true, true, false, keyStoreName, null); - fail("expected exception due to lack of SSL truststore"); - } - catch(IllegalConfigurationException e) - { - //expected - } - } - - public void testCreateAmqpPortNeedingClientAuthSucceedsWithTrustStore() - { - String keyStoreName = "myKeyStore"; - when(_broker.findKeyStoreByName(keyStoreName)).thenReturn(_keyStore); - - String trustStoreName = "myTrustStore"; - when(_broker.findTrustStoreByName(trustStoreName)).thenReturn(_trustStore); - - createAmqpPortTestImpl(true, true, false, keyStoreName, new String[]{trustStoreName}); - } - - public void testCreateAmqpPortWantingClientAuthFailsWithoutTrustStore() - { - String keyStoreName = "myKeyStore"; - when(_broker.findKeyStoreByName(keyStoreName)).thenReturn(_keyStore); - - try - { - createAmqpPortTestImpl(true, false, true, keyStoreName, null); - fail("expected exception due to lack of SSL truststore"); - } - catch(IllegalConfigurationException e) - { - //expected - } - } - - public void testCreateAmqpPortWantingClientAuthSucceedsWithTrustStore() - { - String keyStoreName = "myKeyStore"; - when(_broker.findKeyStoreByName(keyStoreName)).thenReturn(_keyStore); - - String trustStoreName = "myTrustStore"; - when(_broker.findTrustStoreByName(trustStoreName)).thenReturn(_trustStore); - - createAmqpPortTestImpl(true, false, true, keyStoreName, new String[]{trustStoreName}); - } - - public void createAmqpPortTestImpl(boolean useSslTransport, boolean needClientAuth, boolean wantClientAuth, - String keystoreName, String[] trustStoreNames) - { - Set<Protocol> amqp010ProtocolSet = Collections.singleton(Protocol.AMQP_0_10); - Set<String> amqp010StringSet = Collections.singleton(Protocol.AMQP_0_10.name()); - _attributes.put(Port.PROTOCOLS, amqp010StringSet); - - if(useSslTransport) - { - _attributes.put(Port.TRANSPORTS, _sslStringSet); - } - - if(needClientAuth) - { - _attributes.put(Port.NEED_CLIENT_AUTH, "true"); - } - - if(wantClientAuth) - { - _attributes.put(Port.WANT_CLIENT_AUTH, "true"); - } - - if(keystoreName != null) - { - _attributes.put(Port.KEY_STORE, keystoreName); - } - - if(trustStoreNames != null) - { - _attributes.put(Port.TRUST_STORES, Arrays.asList(trustStoreNames)); - } - - Port port = _portFactory.createPort(_portId, _broker, _attributes); - - assertNotNull(port); - assertTrue(port instanceof AmqpPortAdapter); - assertEquals(_portId, port.getId()); - assertEquals(_portNumber, port.getPort()); - if(useSslTransport) - { - assertEquals(_sslTransportSet, port.getTransports()); - } - else - { - assertEquals(_tcpTransportSet, port.getTransports()); - } - assertEquals(amqp010ProtocolSet, port.getProtocols()); - assertEquals("Unexpected send buffer size", 2, port.getAttribute(Port.SEND_BUFFER_SIZE)); - assertEquals("Unexpected receive buffer size", 1, port.getAttribute(Port.RECEIVE_BUFFER_SIZE)); - assertEquals("Unexpected need client auth", needClientAuth, port.getAttribute(Port.NEED_CLIENT_AUTH)); - assertEquals("Unexpected want client auth", wantClientAuth, port.getAttribute(Port.WANT_CLIENT_AUTH)); - assertEquals("Unexpected tcp no delay", true, port.getAttribute(Port.TCP_NO_DELAY)); - assertEquals("Unexpected binding", "127.0.0.1", port.getAttribute(Port.BINDING_ADDRESS)); - } - - public void testCreateNonAmqpPort() - { - Set<Protocol> nonAmqpProtocolSet = Collections.singleton(Protocol.JMX_RMI); - Set<String> nonAmqpStringSet = Collections.singleton(Protocol.JMX_RMI.name()); - _attributes = new HashMap<String, Object>(); - _attributes.put(Port.PROTOCOLS, nonAmqpStringSet); - _attributes.put(Port.AUTHENTICATION_PROVIDER, _authProviderName); - _attributes.put(Port.PORT, _portNumber); - _attributes.put(Port.TRANSPORTS, _tcpStringSet); - - Port port = _portFactory.createPort(_portId, _broker, _attributes); - - assertNotNull(port); - assertFalse("Port should be a PortAdapter, not its AMQP-specific subclass", port instanceof AmqpPortAdapter); - assertEquals(_portId, port.getId()); - assertEquals(_portNumber, port.getPort()); - assertEquals(_tcpTransportSet, port.getTransports()); - assertEquals(nonAmqpProtocolSet, port.getProtocols()); - assertNull("Unexpected send buffer size", port.getAttribute(Port.SEND_BUFFER_SIZE)); - assertNull("Unexpected receive buffer size", port.getAttribute(Port.RECEIVE_BUFFER_SIZE)); - assertNull("Unexpected need client auth", port.getAttribute(Port.NEED_CLIENT_AUTH)); - assertNull("Unexpected want client auth", port.getAttribute(Port.WANT_CLIENT_AUTH)); - assertNull("Unexpected tcp no delay", port.getAttribute(Port.TCP_NO_DELAY)); - assertNull("Unexpected binding", port.getAttribute(Port.BINDING_ADDRESS)); - } - - public void testCreateNonAmqpPortWithPartiallySetAttributes() - { - Set<Protocol> nonAmqpProtocolSet = Collections.singleton(Protocol.JMX_RMI); - Set<String> nonAmqpStringSet = Collections.singleton(Protocol.JMX_RMI.name()); - _attributes = new HashMap<String, Object>(); - _attributes.put(Port.PROTOCOLS, nonAmqpStringSet); - _attributes.put(Port.AUTHENTICATION_PROVIDER, _authProviderName); - _attributes.put(Port.PORT, _portNumber); - - Port port = _portFactory.createPort(_portId, _broker, _attributes); - - assertNotNull(port); - assertFalse("Port should be a PortAdapter, not its AMQP-specific subclass", port instanceof AmqpPortAdapter); - assertEquals(_portId, port.getId()); - assertEquals(_portNumber, port.getPort()); - assertEquals(Collections.singleton(PortFactory.DEFAULT_TRANSPORT), port.getTransports()); - assertEquals(nonAmqpProtocolSet, port.getProtocols()); - assertNull("Unexpected send buffer size", port.getAttribute(Port.SEND_BUFFER_SIZE)); - assertNull("Unexpected receive buffer size", port.getAttribute(Port.RECEIVE_BUFFER_SIZE)); - assertNull("Unexpected need client auth", port.getAttribute(Port.NEED_CLIENT_AUTH)); - assertNull("Unexpected want client auth", port.getAttribute(Port.WANT_CLIENT_AUTH)); - assertNull("Unexpected tcp no delay", port.getAttribute(Port.TCP_NO_DELAY)); - assertNull("Unexpected binding", port.getAttribute(Port.BINDING_ADDRESS)); - } - - public void testCreateMixedAmqpAndNonAmqpThrowsException() - { - Set<String> mixedProtocolSet = new HashSet<String>(Arrays.asList(Protocol.AMQP_0_10.name(), Protocol.JMX_RMI.name())); - _attributes.put(Port.PROTOCOLS, mixedProtocolSet); - - try - { - _portFactory.createPort(_portId, _broker, _attributes); - fail("Exception not thrown"); - } - catch (IllegalConfigurationException e) - { - // pass - } - } - - public void testCreateRMIPortWhenAnotherRMIPortAlreadyExists() - { - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(Port.PORT, 1); - attributes.put(Port.NAME, getTestName()); - attributes.put(Port.TRANSPORTS, Collections.singleton(Transport.TCP)); - attributes.put(Port.PROTOCOLS, Collections.singleton(Protocol.RMI)); - - Port rmiPort = mock(Port.class); - when(rmiPort.getProtocols()).thenReturn(Collections.singleton(Protocol.RMI)); - when(_broker.getPorts()).thenReturn(Collections.singletonList(rmiPort)); - - try - { - _portFactory.createPort(_portId, _broker, attributes); - fail("RMI port creation should fail as another one olready exist"); - } - catch(IllegalConfigurationException e) - { - // pass - } - } - - public void testCreateRMIPortRequestingSslFails() - { - String keyStoreName = "myKeyStore"; - - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(Port.PORT, 1); - attributes.put(Port.NAME, getTestName()); - attributes.put(Port.TRANSPORTS, Collections.singleton(Transport.SSL)); - attributes.put(Port.PROTOCOLS, Collections.singleton(Protocol.RMI)); - _attributes.put(Port.KEY_STORE, keyStoreName); - - when(_broker.findKeyStoreByName(keyStoreName)).thenReturn(_keyStore); - - try - { - _portFactory.createPort(_portId, _broker, attributes); - fail("RMI port creation should fail due to requesting SSL"); - } - catch(IllegalConfigurationException e) - { - e.printStackTrace(); - // pass - } - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/model/configuration/ConfigurationEntryTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/model/configuration/ConfigurationEntryTest.java deleted file mode 100644 index dd48d7b56d..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/model/configuration/ConfigurationEntryTest.java +++ /dev/null @@ -1,129 +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.model.configuration; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -import junit.framework.TestCase; - -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfigurationEntryStore; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.Port; -import org.apache.qpid.server.model.VirtualHost; - -public class ConfigurationEntryTest extends TestCase -{ - public void testGetChildren() - { - ConfigurationEntryStore store = mock(ConfigurationEntryStore.class); - - ConfigurationEntry virtualHostEntry1 = new ConfigurationEntry(UUID.randomUUID(), VirtualHost.class.getSimpleName(), - Collections.<String, Object> emptyMap(), Collections.<UUID> emptySet(), store); - ConfigurationEntry virtualHostEntry2 = new ConfigurationEntry(UUID.randomUUID(), VirtualHost.class.getSimpleName(), - Collections.<String, Object> emptyMap(), Collections.<UUID> emptySet(), store); - ConfigurationEntry portEntry = new ConfigurationEntry(UUID.randomUUID(), Port.class.getSimpleName(), - Collections.<String, Object> emptyMap(), Collections.<UUID> emptySet(), store); - - when(store.getEntry(virtualHostEntry1.getId())).thenReturn(virtualHostEntry1); - when(store.getEntry(virtualHostEntry2.getId())).thenReturn(virtualHostEntry2); - when(store.getEntry(portEntry.getId())).thenReturn(portEntry); - - Set<UUID> childrenIds = new HashSet<UUID>(); - childrenIds.add(virtualHostEntry1.getId()); - childrenIds.add(virtualHostEntry2.getId()); - childrenIds.add(portEntry.getId()); - ConfigurationEntry parentEntry = new ConfigurationEntry(UUID.randomUUID(), Broker.class.getSimpleName(), - Collections.<String, Object> emptyMap(), childrenIds, store); - - Map<String, Collection<ConfigurationEntry>> children = parentEntry.getChildren(); - assertNotNull("Null is returned for children", children); - assertEquals("Unexpected size", 2, children.size()); - Collection<ConfigurationEntry> virtualHosts = children.get(VirtualHost.class.getSimpleName()); - Collection<ConfigurationEntry> ports = children.get(Port.class.getSimpleName()); - assertEquals("Unexpected virtual hosts", - new HashSet<ConfigurationEntry>(Arrays.asList(virtualHostEntry1, virtualHostEntry2)), - new HashSet<ConfigurationEntry>(virtualHosts)); - assertEquals("Unexpected ports", new HashSet<ConfigurationEntry>(Arrays.asList(portEntry)), - new HashSet<ConfigurationEntry>(ports)); - } - - public void testHashCode() - { - ConfigurationEntryStore store = mock(ConfigurationEntryStore.class); - - UUID id = UUID.randomUUID(); - ConfigurationEntry entry1 = new ConfigurationEntry(id, VirtualHost.class.getSimpleName(), - Collections.<String, Object> emptyMap(), Collections.singleton(UUID.randomUUID()), store); - ConfigurationEntry entry2 = new ConfigurationEntry(id, VirtualHost.class.getSimpleName(), - Collections.<String, Object> emptyMap(), Collections.singleton(UUID.randomUUID()), store); - ConfigurationEntry entryWithDifferentId = new ConfigurationEntry(UUID.randomUUID(), - VirtualHost.class.getSimpleName(), Collections.<String, Object> emptyMap(), Collections.singleton(UUID.randomUUID()), store); - - assertTrue(entry1.hashCode() == entry2.hashCode()); - assertFalse(entry1.hashCode() == entryWithDifferentId.hashCode()); - } - - public void testEqualsObject() - { - ConfigurationEntryStore store = mock(ConfigurationEntryStore.class); - - UUID id = UUID.randomUUID(); - Map<String, Object> attributes1 = new HashMap<String, Object>(); - attributes1.put(VirtualHost.NAME, "name1"); - Set<UUID> childrenIds = Collections.singleton(UUID.randomUUID()); - ConfigurationEntry entry1 = new ConfigurationEntry(id, VirtualHost.class.getSimpleName(), attributes1, - childrenIds, store); - - Map<String, Object> attributes2 = new HashMap<String, Object>(); - attributes2.put(VirtualHost.NAME, "name2"); - - ConfigurationEntry entry2 = new ConfigurationEntry(id, VirtualHost.class.getSimpleName(), attributes1, - childrenIds, store); - ConfigurationEntry entryWithDifferentId = new ConfigurationEntry(UUID.randomUUID(), - VirtualHost.class.getSimpleName(), attributes1, childrenIds, store); - - assertTrue(entry1.equals(entry2)); - assertFalse("Entries should be diferrent because of diferrent IDs", entry1.equals(entryWithDifferentId)); - - ConfigurationEntry entryWithDifferentChildId = new ConfigurationEntry(id, - VirtualHost.class.getSimpleName(), attributes1, Collections.singleton(UUID.randomUUID()), store); - assertFalse("Entries should be diferrent because of diferrent children", entry1.equals(entryWithDifferentChildId)); - - ConfigurationEntry entryWithDifferentName = new ConfigurationEntry(id, - VirtualHost.class.getSimpleName(), attributes2, childrenIds, store); - assertFalse("Entries should be diferrent because of diferrent attributes", entry1.equals(entryWithDifferentName)); - - ConfigurationEntry entryWithDifferentType = new ConfigurationEntry(id, - Broker.class.getSimpleName(), attributes1, childrenIds, store); - assertFalse("Entries should be diferrent because of diferrent types", entry1.equals(entryWithDifferentType)); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AMQPriorityQueueTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AMQPriorityQueueTest.java deleted file mode 100644 index a468fa072b..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AMQPriorityQueueTest.java +++ /dev/null @@ -1,112 +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 java.util.Collections; -import junit.framework.AssertionFailedError; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.message.ServerMessage; - -import java.util.ArrayList; -import org.apache.qpid.server.model.Queue; - -import static org.mockito.Mockito.when; - -public class AMQPriorityQueueTest extends SimpleAMQQueueTest -{ - - @Override - public void setUp() throws Exception - { - setArguments(Collections.singletonMap(Queue.PRIORITIES,(Object)3)); - super.setUp(); - } - - public void testPriorityOrdering() throws AMQException, InterruptedException - { - - // Enqueue messages in order - SimpleAMQQueue queue = getQueue(); - queue.enqueue(createMessage(1L, (byte) 10)); - queue.enqueue(createMessage(2L, (byte) 4)); - queue.enqueue(createMessage(3L, (byte) 0)); - - // Enqueue messages in reverse order - queue.enqueue(createMessage(4L, (byte) 0)); - queue.enqueue(createMessage(5L, (byte) 4)); - queue.enqueue(createMessage(6L, (byte) 10)); - - // Enqueue messages out of order - queue.enqueue(createMessage(7L, (byte) 4)); - queue.enqueue(createMessage(8L, (byte) 10)); - queue.enqueue(createMessage(9L, (byte) 0)); - - // Register subscriber - queue.registerSubscription(getSubscription(), false); - Thread.sleep(150); - - ArrayList<QueueEntry> msgs = getSubscription().getMessages(); - try - { - assertEquals(1L, msgs.get(0).getMessage().getMessageNumber()); - assertEquals(6L, msgs.get(1).getMessage().getMessageNumber()); - assertEquals(8L, msgs.get(2).getMessage().getMessageNumber()); - - assertEquals(2L, msgs.get(3).getMessage().getMessageNumber()); - assertEquals(5L, msgs.get(4).getMessage().getMessageNumber()); - assertEquals(7L, msgs.get(5).getMessage().getMessageNumber()); - - assertEquals(3L, msgs.get(6).getMessage().getMessageNumber()); - assertEquals(4L, msgs.get(7).getMessage().getMessageNumber()); - assertEquals(9L, msgs.get(8).getMessage().getMessageNumber()); - } - catch (AssertionFailedError afe) - { - // Show message order on failure. - int index = 1; - for (QueueEntry qe : msgs) - { - System.err.println(index + ":" + qe.getMessage().getMessageNumber()); - index++; - } - - throw afe; - } - - } - - protected ServerMessage createMessage(Long id, byte i) throws AMQException - { - - ServerMessage msg = super.createMessage(id); - AMQMessageHeader hdr = msg.getMessageHeader(); - when(hdr.getPriority()).thenReturn(i); - return msg; - } - - protected ServerMessage createMessage(Long id) throws AMQException - { - return createMessage(id, (byte) 0); - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueFactoryTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueFactoryTest.java deleted file mode 100644 index 9a2c5bc166..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueFactoryTest.java +++ /dev/null @@ -1,560 +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 static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyBoolean; -import static org.mockito.Matchers.anyMap; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - - -import org.apache.qpid.AMQException; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.server.configuration.BrokerProperties; -import org.apache.qpid.server.configuration.QueueConfiguration; -import org.apache.qpid.server.configuration.VirtualHostConfiguration; -import org.apache.qpid.server.exchange.DefaultExchangeFactory; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.logging.LogActor; -import org.apache.qpid.server.logging.RootMessageLogger; -import org.apache.qpid.server.logging.actors.CurrentActor; -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.model.UUIDGenerator; -import org.apache.qpid.server.plugin.ExchangeType; -import org.apache.qpid.server.store.DurableConfigurationStore; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.test.utils.QpidTestCase; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -public class AMQQueueFactoryTest extends QpidTestCase -{ - private QueueRegistry _queueRegistry; - private VirtualHost _virtualHost; - private AMQQueueFactory _queueFactory; - private List<AMQQueue> _queues; - private QueueConfiguration _queueConfiguration; - - @Override - public void setUp() throws Exception - { - super.setUp(); - - _queues = new ArrayList<AMQQueue>(); - - _virtualHost = mock(VirtualHost.class); - - VirtualHostConfiguration vhostConfig = mock(VirtualHostConfiguration.class); - when(_virtualHost.getConfiguration()).thenReturn(vhostConfig); - _queueConfiguration = mock(QueueConfiguration.class); - when(vhostConfig.getQueueConfiguration(anyString())).thenReturn(_queueConfiguration); - LogActor logActor = mock(LogActor.class); - CurrentActor.set(logActor); - RootMessageLogger rootLogger = mock(RootMessageLogger.class); - when(logActor.getRootMessageLogger()).thenReturn(rootLogger); - DurableConfigurationStore store = mock(DurableConfigurationStore.class); - when(_virtualHost.getDurableConfigurationStore()).thenReturn(store); - - mockExchangeCreation(); - mockQueueRegistry(); - delegateVhostQueueCreation(); - - when(_virtualHost.getQueues()).thenReturn(_queues); - - - _queueFactory = new AMQQueueFactory(_virtualHost, _queueRegistry); - - - - } - - private void delegateVhostQueueCreation() throws AMQException - { - final ArgumentCaptor<UUID> id = ArgumentCaptor.forClass(UUID.class); - final ArgumentCaptor<String> queueName = ArgumentCaptor.forClass(String.class); - final ArgumentCaptor<Boolean> durable = ArgumentCaptor.forClass(Boolean.class); - final ArgumentCaptor<String> owner = ArgumentCaptor.forClass(String.class); - final ArgumentCaptor<Boolean> autoDelete = ArgumentCaptor.forClass(Boolean.class); - final ArgumentCaptor<Boolean> exclusive = ArgumentCaptor.forClass(Boolean.class); - final ArgumentCaptor<Boolean> deleteOnNoConsumer = ArgumentCaptor.forClass(Boolean.class); - final ArgumentCaptor<Map> arguments = ArgumentCaptor.forClass(Map.class); - - when(_virtualHost.createQueue(id.capture(), queueName.capture(), durable.capture(), owner.capture(), - autoDelete.capture(), exclusive.capture(), deleteOnNoConsumer.capture(), arguments.capture())).then( - new Answer<AMQQueue>() - { - @Override - public AMQQueue answer(InvocationOnMock invocation) throws Throwable - { - return _queueFactory.createQueue(id.getValue(), - queueName.getValue(), - durable.getValue(), - owner.getValue(), - autoDelete.getValue(), - exclusive.getValue(), - deleteOnNoConsumer.getValue(), - arguments.getValue()); - } - } - ); - } - - private void mockQueueRegistry() - { - _queueRegistry = mock(QueueRegistry.class); - - final ArgumentCaptor<AMQQueue> capturedQueue = ArgumentCaptor.forClass(AMQQueue.class); - doAnswer(new Answer() - { - - @Override - public Object answer(final InvocationOnMock invocation) throws Throwable - { - AMQQueue queue = capturedQueue.getValue(); - when(_queueRegistry.getQueue(eq(queue.getId()))).thenReturn(queue); - when(_queueRegistry.getQueue(eq(queue.getName()))).thenReturn(queue); - when(_virtualHost.getQueue(eq(queue.getId()))).thenReturn(queue); - when(_virtualHost.getQueue(eq(queue.getName()))).thenReturn(queue); - _queues.add(queue); - - return null; - } - }).when(_queueRegistry).registerQueue(capturedQueue.capture()); - } - - private void mockExchangeCreation() throws AMQException - { - final ArgumentCaptor<UUID> idCapture = ArgumentCaptor.forClass(UUID.class); - final ArgumentCaptor<String> exchangeNameCapture = ArgumentCaptor.forClass(String.class); - final ArgumentCaptor<String> type = ArgumentCaptor.forClass(String.class); - - when(_virtualHost.createExchange(idCapture.capture(), exchangeNameCapture.capture(), type.capture(), - anyBoolean(), anyBoolean(), anyString())).then( - new Answer<Exchange>() - { - @Override - public Exchange answer(InvocationOnMock invocation) throws Throwable - { - final String name = exchangeNameCapture.getValue(); - final UUID id = idCapture.getValue(); - - final Exchange exchange = mock(Exchange.class); - ExchangeType exType = mock(ExchangeType.class); - - when(exchange.getName()).thenReturn(name); - when(exchange.getId()).thenReturn(id); - when(exchange.getType()).thenReturn(exType); - - final String typeName = type.getValue(); - when(exType.getType()).thenReturn(typeName); - when(exchange.getTypeName()).thenReturn(typeName); - - when(_virtualHost.getExchange(eq(name))).thenReturn(exchange); - when(_virtualHost.getExchange(eq(id))).thenReturn(exchange); - - final ArgumentCaptor<AMQQueue> queue = ArgumentCaptor.forClass(AMQQueue.class); - - when(exchange.addBinding(anyString(),queue.capture(),anyMap())).then(new Answer<Boolean>() { - - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable - { - when(exchange.isBound(eq(queue.getValue()))).thenReturn(true); - return true; - } - }); - - return exchange; - } - } - ); - } - - @Override - public void tearDown() throws Exception - { - super.tearDown(); - } - - private void verifyRegisteredQueueCount(int count) - { - assertEquals("Queue was not registered in virtualhost", count, _virtualHost.getQueues().size()); - } - - - private void verifyQueueRegistered(String queueName) - { - assertNotNull("Queue " + queueName + " was not created", _virtualHost.getQueue(queueName)); - } - - public void testPriorityQueueRegistration() throws Exception - { - Map<String,Object> attributes = Collections.singletonMap(Queue.PRIORITIES, (Object) 5); - - - AMQQueue queue = _queueFactory.createQueue(UUIDGenerator.generateRandomUUID(), - "testPriorityQueue", - false, - "owner", - false, - false, - false, - attributes); - - assertEquals("Queue not a priorty queue", AMQPriorityQueue.class, queue.getClass()); - verifyQueueRegistered("testPriorityQueue"); - verifyRegisteredQueueCount(1); - } - - - public void testSimpleQueueRegistration() throws Exception - { - String queueName = getName(); - String dlQueueName = queueName + AMQQueueFactory.DEFAULT_DLQ_NAME_SUFFIX; - - AMQQueue queue = _queueFactory.createQueue(UUIDGenerator.generateRandomUUID(), queueName, false, "owner", false, - false, - false, - null); - assertEquals("Queue not a simple queue", SimpleAMQQueue.class, queue.getClass()); - verifyQueueRegistered(queueName); - - //verify that no alternate exchange or DLQ were produced - - assertNull("Queue should not have an alternate exchange as DLQ wasnt enabled", queue.getAlternateExchange()); - assertNull("The DLQ should not exist", _virtualHost.getQueue(dlQueueName)); - - verifyRegisteredQueueCount(1); - } - - /** - * Tests that setting the {@link QueueArgumentsConverter#X_QPID_DLQ_ENABLED} argument true does - * cause the alternate exchange to be set and DLQ to be produced. - * @throws AMQException - */ - public void testDeadLetterQueueEnabled() throws AMQException - { - Map<String,Object> attributes = Collections.singletonMap(Queue.CREATE_DLQ_ON_CREATION, (Object) true); - - String queueName = "testDeadLetterQueueEnabled"; - String dlExchangeName = queueName + DefaultExchangeFactory.DEFAULT_DLE_NAME_SUFFIX; - String dlQueueName = queueName + AMQQueueFactory.DEFAULT_DLQ_NAME_SUFFIX; - - assertNull("The DLQ should not yet exist", _virtualHost.getQueue(dlQueueName)); - assertNull("The alternate exchange should not yet exist", _virtualHost.getExchange(dlExchangeName)); - - AMQQueue queue = _queueFactory.createQueue(UUIDGenerator.generateRandomUUID(), - queueName, - false, - "owner", - false, - false, - false, - attributes); - - Exchange altExchange = queue.getAlternateExchange(); - assertNotNull("Queue should have an alternate exchange as DLQ is enabled", altExchange); - assertEquals("Alternate exchange name was not as expected", dlExchangeName, altExchange.getName()); - assertEquals("Alternate exchange type was not as expected", ExchangeDefaults.FANOUT_EXCHANGE_CLASS, altExchange.getTypeName()); - - assertNotNull("The alternate exchange was not registered as expected", _virtualHost.getExchange(dlExchangeName)); - assertEquals("The registered exchange was not the expected exchange instance", altExchange, _virtualHost.getExchange(dlExchangeName)); - - AMQQueue dlQueue = _virtualHost.getQueue(dlQueueName); - assertNotNull("The DLQ was not registered as expected", dlQueue); - assertTrue("DLQ should have been bound to the alternate exchange", altExchange.isBound(dlQueue)); - assertNull("DLQ should have no alternate exchange", dlQueue.getAlternateExchange()); - assertEquals("DLQ should have a zero maximum delivery count", 0, dlQueue.getMaximumDeliveryCount()); - - //2 queues should have been registered - verifyRegisteredQueueCount(2); - } - - /** - * Tests that the deadLetterQueues/maximumDeliveryCount settings from the configuration - * are not applied to the DLQ itself. - * @throws AMQException - */ - public void testDeadLetterQueueDoesNotInheritDLQorMDCSettings() throws Exception - { - - String queueName = "testDeadLetterQueueEnabled"; - String dlExchangeName = queueName + DefaultExchangeFactory.DEFAULT_DLE_NAME_SUFFIX; - String dlQueueName = queueName + AMQQueueFactory.DEFAULT_DLQ_NAME_SUFFIX; - - when(_queueConfiguration.getMaxDeliveryCount()).thenReturn(5); - when(_queueConfiguration.isDeadLetterQueueEnabled()).thenReturn(true); - - assertNull("The DLQ should not yet exist", _virtualHost.getQueue(dlQueueName)); - assertNull("The alternate exchange should not yet exist", _virtualHost.getExchange(dlExchangeName)); - - AMQQueue queue = _queueFactory.createQueue(UUIDGenerator.generateRandomUUID(), - queueName, - false, - "owner", - false, - false, - false, - null); - - assertEquals("Unexpected maximum delivery count", 5, queue.getMaximumDeliveryCount()); - Exchange altExchange = queue.getAlternateExchange(); - assertNotNull("Queue should have an alternate exchange as DLQ is enabled", altExchange); - assertEquals("Alternate exchange name was not as expected", dlExchangeName, altExchange.getName()); - assertEquals("Alternate exchange type was not as expected", ExchangeDefaults.FANOUT_EXCHANGE_CLASS, altExchange.getTypeName()); - - assertNotNull("The alternate exchange was not registered as expected", _virtualHost.getExchange(dlExchangeName)); - assertEquals("The registered exchange was not the expected exchange instance", altExchange, _virtualHost.getExchange(dlExchangeName)); - - AMQQueue dlQueue = _virtualHost.getQueue(dlQueueName); - assertNotNull("The DLQ was not registered as expected", dlQueue); - assertTrue("DLQ should have been bound to the alternate exchange", altExchange.isBound(dlQueue)); - assertNull("DLQ should have no alternate exchange", dlQueue.getAlternateExchange()); - assertEquals("DLQ should have a zero maximum delivery count", 0, dlQueue.getMaximumDeliveryCount()); - - //2 queues should have been registered - verifyRegisteredQueueCount(2); - } - - /** - * Tests that setting the {@link QueueArgumentsConverter#X_QPID_DLQ_ENABLED} argument false does not - * result in the alternate exchange being set and DLQ being created. - * @throws AMQException - */ - public void testDeadLetterQueueDisabled() throws AMQException - { - Map<String,Object> attributes = Collections.singletonMap(Queue.CREATE_DLQ_ON_CREATION, (Object) false); - - String queueName = "testDeadLetterQueueDisabled"; - String dlExchangeName = queueName + DefaultExchangeFactory.DEFAULT_DLE_NAME_SUFFIX; - String dlQueueName = queueName + AMQQueueFactory.DEFAULT_DLQ_NAME_SUFFIX; - - assertNull("The DLQ should not yet exist", _virtualHost.getQueue(dlQueueName)); - assertNull("The alternate exchange should not exist", _virtualHost.getExchange(dlExchangeName)); - - AMQQueue queue = _queueFactory.createQueue(UUIDGenerator.generateRandomUUID(), - queueName, - false, - "owner", - false, - false, - false, - attributes); - - assertNull("Queue should not have an alternate exchange as DLQ is disabled", queue.getAlternateExchange()); - assertNull("The alternate exchange should still not exist", _virtualHost.getExchange(dlExchangeName)); - - assertNull("The DLQ should still not exist", _virtualHost.getQueue(dlQueueName)); - - //only 1 queue should have been registered - verifyRegisteredQueueCount(1); - } - - /** - * Tests that setting the {@link QueueArgumentsConverter#X_QPID_DLQ_ENABLED} argument true but - * creating an auto-delete queue, does not result in the alternate exchange - * being set and DLQ being created. - * @throws AMQException - */ - public void testDeadLetterQueueNotCreatedForAutodeleteQueues() throws AMQException - { - Map<String,Object> attributes = Collections.singletonMap(Queue.CREATE_DLQ_ON_CREATION, (Object) true); - - String queueName = "testDeadLetterQueueNotCreatedForAutodeleteQueues"; - String dlExchangeName = queueName + DefaultExchangeFactory.DEFAULT_DLE_NAME_SUFFIX; - String dlQueueName = queueName + AMQQueueFactory.DEFAULT_DLQ_NAME_SUFFIX; - - assertNull("The DLQ should not yet exist", _virtualHost.getQueue(dlQueueName)); - assertNull("The alternate exchange should not exist", _virtualHost.getExchange(dlExchangeName)); - - //create an autodelete queue - AMQQueue queue = _queueFactory.createQueue(UUIDGenerator.generateRandomUUID(), - queueName, - false, - "owner", - true, - false, - false, - attributes); - assertTrue("Queue should be autodelete", queue.isAutoDelete()); - - //ensure that the autodelete property overrides the request to enable DLQ - assertNull("Queue should not have an alternate exchange as queue is autodelete", queue.getAlternateExchange()); - assertNull("The alternate exchange should not exist as queue is autodelete", _virtualHost.getExchange(dlExchangeName)); - assertNull("The DLQ should not exist as queue is autodelete", _virtualHost.getQueue(dlQueueName)); - - //only 1 queue should have been registered - verifyRegisteredQueueCount(1); - } - - /** - * Tests that setting the {@link QueueArgumentsConverter#X_QPID_MAXIMUM_DELIVERY_COUNT} argument has - * the desired effect. - */ - public void testMaximumDeliveryCount() throws Exception - { - Map<String,Object> attributes = Collections.singletonMap(Queue.MAXIMUM_DELIVERY_ATTEMPTS, (Object) 5); - - final AMQQueue queue = _queueFactory.createQueue(UUIDGenerator.generateRandomUUID(), - "testMaximumDeliveryCount", - false, - "owner", - false, - false, - false, - attributes); - - assertNotNull("The queue was not registered as expected ", queue); - assertEquals("Maximum delivery count not as expected", 5, queue.getMaximumDeliveryCount()); - - verifyRegisteredQueueCount(1); - } - - /** - * Tests that omitting the {@link QueueArgumentsConverter#X_QPID_MAXIMUM_DELIVERY_COUNT} argument means - * that queue is created with a default maximumDeliveryCount of zero (unless set in config). - */ - public void testMaximumDeliveryCountDefault() throws Exception - { - final AMQQueue queue = _queueFactory.createQueue(UUIDGenerator.generateRandomUUID(), - "testMaximumDeliveryCount", - false, - "owner", - false, - false, - false, - null); - - assertNotNull("The queue was not registered as expected ", queue); - assertEquals("Maximum delivery count not as expected", 0, queue.getMaximumDeliveryCount()); - - verifyRegisteredQueueCount(1); - } - - /** - * Tests queue creation with queue name set to null - */ - public void testQueueNameNullValidation() - { - try - { - _queueFactory.createQueue(UUIDGenerator.generateRandomUUID(), null, false, "owner", true, false, - false, - null); - fail("queue with null name can not be created!"); - } - catch (Exception e) - { - assertTrue(e instanceof IllegalArgumentException); - assertEquals("Queue name must not be null", e.getMessage()); - } - } - - /** - * Tests queue creation with queue name length less 255 characters but - * corresponding DLQ name length greater than 255. - */ - public void testQueueNameWithLengthLessThan255ButDLQNameWithLengthGreaterThan255() - { - String queueName = "test-" + generateStringWithLength('a', 245); - try - { - // change DLQ name to make its length bigger than exchange name - setTestSystemProperty(BrokerProperties.PROPERTY_DEAD_LETTER_EXCHANGE_SUFFIX, "_DLE"); - setTestSystemProperty(BrokerProperties.PROPERTY_DEAD_LETTER_QUEUE_SUFFIX, "_DLQUEUE"); - Map<String,Object> attributes = Collections.singletonMap(Queue.CREATE_DLQ_ON_CREATION, (Object) true); - _queueFactory.createQueue(UUIDGenerator.generateRandomUUID(), queueName, false, "owner", - false, false, false, attributes); - fail("queue with DLQ name having more than 255 characters can not be created!"); - } - catch (Exception e) - { - assertTrue("Unexpected exception is thrown!", e instanceof IllegalArgumentException); - assertTrue("Unexpected exception message!", e.getMessage().contains("DLQ queue name") - && e.getMessage().contains("length exceeds limit of 255")); - } - } - - /** - * Tests queue creation with queue name length less 255 characters but - * corresponding DL exchange name length greater than 255. - */ - public void testQueueNameWithLengthLessThan255ButDLExchangeNameWithLengthGreaterThan255() - { - String queueName = "test-" + generateStringWithLength('a', 245); - try - { - // change DLQ name to make its length bigger than exchange name - setTestSystemProperty(BrokerProperties.PROPERTY_DEAD_LETTER_EXCHANGE_SUFFIX, "_DLEXCHANGE"); - setTestSystemProperty(BrokerProperties.PROPERTY_DEAD_LETTER_QUEUE_SUFFIX, "_DLQ"); - Map<String,Object> attributes = Collections.singletonMap(Queue.CREATE_DLQ_ON_CREATION, (Object) true); - _queueFactory.createQueue(UUIDGenerator.generateRandomUUID(), queueName, false, "owner", - false, false, false, attributes); - fail("queue with DLE name having more than 255 characters can not be created!"); - } - catch (Exception e) - { - assertTrue("Unexpected exception is thrown!", e instanceof IllegalArgumentException); - assertTrue("Unexpected exception message!", e.getMessage().contains("DL exchange name") - && e.getMessage().contains("length exceeds limit of 255")); - } - } - - public void testMessageGroupFromConfig() throws Exception - { - - Map<String,String> arguments = new HashMap<String, String>(); - arguments.put("qpid.group_header_key","mykey"); - arguments.put("qpid.shared_msg_group","1"); - - QueueConfiguration qConf = mock(QueueConfiguration.class); - when(qConf.getArguments()).thenReturn(arguments); - when(qConf.getName()).thenReturn("test"); - - AMQQueue queue = _queueFactory.createAMQQueueImpl(qConf); - assertEquals("mykey", queue.getAttribute(Queue.MESSAGE_GROUP_KEY)); - assertEquals(Boolean.TRUE, queue.getAttribute(Queue.MESSAGE_GROUP_SHARED_GROUPS)); - } - - private String generateStringWithLength(char ch, int length) - { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < length; i++) - { - sb.append(ch); - } - return sb.toString(); - } - - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/ConflationQueueListTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/ConflationQueueListTest.java deleted file mode 100644 index 6538724a71..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/ConflationQueueListTest.java +++ /dev/null @@ -1,210 +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 static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import junit.framework.TestCase; - -import org.apache.qpid.server.message.MessageReference; -import org.apache.qpid.server.message.AMQMessageHeader; -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 message = createTestServerMessage(null); - - _list.add(message); - int numberOfEntries = countEntries(_list); - assertEquals(1, numberOfEntries); - } - - public void testAddAndDiscardMessageWithoutConflationKeyValue() - { - ServerMessage message = createTestServerMessage(null); - - QueueEntry addedEntry = _list.add(message); - addedEntry.discard(); - - int numberOfEntries = countEntries(_list); - assertEquals(0, numberOfEntries); - } - - public void testAddMessageWithConflationKeyValue() - { - ServerMessage message = createTestServerMessage(TEST_KEY_VALUE); - - _list.add(message); - int numberOfEntries = countEntries(_list); - assertEquals(1, numberOfEntries); - } - - public void testAddAndRemoveMessageWithConflationKeyValue() - { - ServerMessage message = createTestServerMessage(TEST_KEY_VALUE); - - QueueEntry addedEntry = _list.add(message); - addedEntry.discard(); - - int numberOfEntries = countEntries(_list); - assertEquals(0, numberOfEntries); - } - - public void testAddTwoMessagesWithDifferentConflationKeyValue() - { - ServerMessage message1 = createTestServerMessage(TEST_KEY_VALUE1); - ServerMessage message2 = createTestServerMessage(TEST_KEY_VALUE2); - - _list.add(message1); - _list.add(message2); - - int numberOfEntries = countEntries(_list); - assertEquals(2, numberOfEntries); - } - - public void testAddTwoMessagesWithSameConflationKeyValue() - { - ServerMessage message1 = createTestServerMessage(TEST_KEY_VALUE); - ServerMessage message2 = createTestServerMessage(TEST_KEY_VALUE); - - _list.add(message1); - _list.add(message2); - - int numberOfEntries = countEntries(_list); - assertEquals(1, numberOfEntries); - } - - public void testSupersededEntryIsDiscardedOnRelease() - { - ServerMessage message1 = createTestServerMessage(TEST_KEY_VALUE); - ServerMessage 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 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 message1 = createTestServerMessage(TEST_KEY_VALUE1); - ServerMessage 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 createTestServerMessage(String conflationKeyValue) - { - ServerMessage mockMessage = mock(ServerMessage.class); - - AMQMessageHeader messageHeader = mock(AMQMessageHeader.class); - when(messageHeader.getHeader(CONFLATION_KEY)).thenReturn(conflationKeyValue); - when(mockMessage.getMessageHeader()).thenReturn(messageHeader); - - MessageReference messageReference = mock(MessageReference.class); - when(mockMessage.newReference()).thenReturn(messageReference); - when(messageReference.getMessage()).thenReturn(mockMessage); - - 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/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/InboundMessageAdapterTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/InboundMessageAdapterTest.java deleted file mode 100644 index 584e26d88f..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/InboundMessageAdapterTest.java +++ /dev/null @@ -1,89 +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 static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.test.utils.QpidTestCase; - -public class InboundMessageAdapterTest extends QpidTestCase -{ - private ServerMessage<?> _mockMessage; - private QueueEntry _mockQueueEntry; - private InboundMessageAdapter _inboundMessageAdapter; - - @Override - protected void setUp() throws Exception - { - super.setUp(); - _mockMessage = mock(ServerMessage.class); - _mockQueueEntry = mock(QueueEntry.class); - when(_mockQueueEntry.getMessage()).thenReturn(_mockMessage); - - _inboundMessageAdapter = new InboundMessageAdapter(_mockQueueEntry); - } - - public void testGetRoutingKey() throws Exception - { - String routingKey = getTestName(); - when(_mockMessage.getRoutingKey()).thenReturn(routingKey); - - assertEquals("Unexpected value for routing key", routingKey, _inboundMessageAdapter.getRoutingKey()); - } - - - public void testGetMessageHeader() throws Exception - { - AMQMessageHeader mockMessageHeader = mock(AMQMessageHeader.class); - when(_mockQueueEntry.getMessageHeader()).thenReturn(mockMessageHeader); - - assertSame("unexpected message header", mockMessageHeader, _inboundMessageAdapter.getMessageHeader()); - } - - public void testIsRedelivered() throws Exception - { - when(_mockQueueEntry.isRedelivered()).thenReturn(true); - assertTrue("unexpected isRedelivered value", _inboundMessageAdapter.isRedelivered()); - - when(_mockQueueEntry.isRedelivered()).thenReturn(false); - assertFalse("unexpected isRedelivered value", _inboundMessageAdapter.isRedelivered()); - } - - public void testIsPersistent() throws Exception - { - when(_mockQueueEntry.isPersistent()).thenReturn(true); - assertTrue("unexpected isPersistent value", _inboundMessageAdapter.isPersistent()); - - when(_mockQueueEntry.isPersistent()).thenReturn(false); - assertFalse("unexpected isPersistent value", _inboundMessageAdapter.isPersistent()); - } - - public void testGetSize() throws Exception - { - long size = 32526215; - when(_mockQueueEntry.getSize()).thenReturn(size); - assertEquals("unexpected getSize value", size, _inboundMessageAdapter.getSize()); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/MockAMQQueue.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/MockAMQQueue.java deleted file mode 100644 index 2a0c12ff3e..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/MockAMQQueue.java +++ /dev/null @@ -1,615 +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.server.binding.Binding; -import org.apache.qpid.server.configuration.QueueConfiguration; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.logging.LogSubject; -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; -import java.util.UUID; -import java.util.concurrent.CopyOnWriteArrayList; - -public class MockAMQQueue implements AMQQueue -{ - private boolean _deleted = false; - private String _name; - private VirtualHost _virtualhost; - - private AuthorizationHolder _authorizationHolder; - - private AMQSessionModel _exclusiveOwner; - private List<Binding> _bindings = new CopyOnWriteArrayList<Binding>(); - private boolean _autoDelete; - - public MockAMQQueue(String name) - { - _name = name; - } - - public boolean getDeleteOnNoConsumers() - { - return false; - } - - public void setDeleteOnNoConsumers(boolean b) - { - } - - public void addBinding(final Binding binding) - { - _bindings.add(binding); - } - - public void removeBinding(final Binding binding) - { - _bindings.remove(binding); - } - - public List<Binding> getBindings() - { - return _bindings; - } - - public int getBindingCount() - { - return 0; - } - - public LogSubject getLogSubject() - { - return new LogSubject() - { - public String toLogString() - { - return "[MockAMQQueue]"; - } - - }; - } - - public long getUnackedMessageBytes() - { - return 0; - } - - public long getMessageDequeueCount() - { - return 0; - } - - public long getTotalEnqueueSize() - { - return 0; - } - - public long getTotalDequeueSize() - { - return 0; - } - - public long getTotalDequeueCount() - { - return 0; - } - - public long getTotalEnqueueCount() - { - return 0; - } - - public int getBindingCountHigh() - { - return 0; - } - - public long getPersistentByteEnqueues() - { - return 0; - } - - public long getPersistentByteDequeues() - { - return 0; - } - - public long getPersistentMsgEnqueues() - { - return 0; - } - - public long getPersistentMsgDequeues() - { - return 0; - } - - public void purge(final long request) - { - - } - - public long getCreateTime() - { - return 0; - } - - public void setNoLocal(boolean b) - { - - } - - public UUID getId() - { - return null; - } - - public boolean isDurable() - { - return false; - } - - public boolean isAutoDelete() - { - return _autoDelete; - } - - public void setAutoDelete(boolean autodelete) - { - _autoDelete = autodelete; - } - - - public String getOwner() - { - return null; - } - - public void setVirtualHost(VirtualHost virtualhost) - { - _virtualhost = virtualhost; - } - - public VirtualHost getVirtualHost() - { - return _virtualhost; - } - - public String getName() - { - return _name; - } - - 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() - { - return 0; - } - - public int getActiveConsumerCount() - { - return 0; - } - - public boolean hasExclusiveSubscriber() - { - return false; - } - - public boolean isUnused() - { - return false; - } - - public boolean isEmpty() - { - return false; - } - - public int getMessageCount() - { - return 0; - } - - public int getUndeliveredMessageCount() - { - return 0; - } - - public long getQueueDepth() - { - return 0; - } - - public long getReceivedMessageCount() - { - return 0; - } - - public long getOldestMessageArrivalTime() - { - return 0; - } - - public boolean isDeleted() - { - return _deleted; - } - - public int delete() throws AMQException - { - _deleted = true; - return getMessageCount(); - } - - public void enqueue(ServerMessage message) throws AMQException - { - } - - public void enqueue(ServerMessage message, PostEnqueueAction action) throws AMQException - { - } - - - public void enqueue(ServerMessage message, boolean sync, PostEnqueueAction action) throws AMQException - { - } - - public void requeue(QueueEntry entry) - { - } - - public void requeue(QueueEntryImpl storeContext, Subscription subscription) - { - } - - public void dequeue(QueueEntry entry, Subscription sub) - { - } - - public boolean resend(QueueEntry entry, Subscription subscription) throws AMQException - { - return false; - } - - public void addQueueDeleteTask(Task task) - { - } - - public void removeQueueDeleteTask(final Task task) - { - } - - public List<QueueEntry> getMessagesOnTheQueue() - { - return null; - } - - public List<QueueEntry> getMessagesOnTheQueue(long fromMessageId, long toMessageId) - { - return null; - } - - public List<Long> getMessagesOnTheQueue(int num) - { - return null; - } - - public List<Long> getMessagesOnTheQueue(int num, int offest) - { - return null; - } - - public QueueEntry getMessageOnTheQueue(long messageId) - { - return null; - } - - public List<QueueEntry> getMessagesRangeOnTheQueue(long fromPosition, long toPosition) - { - return null; - } - - public long getMaximumMessageSize() - { - return 0; - } - - public void setMaximumMessageSize(long value) - { - - } - - public long getMaximumMessageCount() - { - return 0; - } - - public void setMaximumMessageCount(long value) - { - - } - - public long getMaximumQueueDepth() - { - return 0; - } - - public void setMaximumQueueDepth(long value) - { - - } - - public long getMaximumMessageAge() - { - return 0; - } - - public void setMaximumMessageAge(long maximumMessageAge) - { - - } - - public long getMinimumAlertRepeatGap() - { - return 0; - } - - public void deleteMessageFromTop() - { - - } - - public long clearQueue() - { - return 0; - } - - - public void checkMessageStatus() throws AMQException - { - - } - - public Set<NotificationCheck> getNotificationChecks() - { - return null; - } - - public void flushSubscription(Subscription sub) throws AMQException - { - - } - - public void deliverAsync(Subscription sub) - { - - } - - public void deliverAsync() - { - - } - - public void stop() - { - - } - - public boolean isExclusive() - { - return false; - } - - public Exchange getAlternateExchange() - { - return null; - } - - public void setAlternateExchange(Exchange exchange) - { - - } - - @Override - public Collection<String> getAvailableAttributes() - { - return null; - } - - @Override - public Object getAttribute(String attrName) - { - return null; - } - - public void checkCapacity(AMQSessionModel channel) - { - } - - public int compareTo(AMQQueue o) - { - return 0; - } - - public void setMinimumAlertRepeatGap(long value) - { - - } - - public long getCapacity() - { - return 0; - } - - public void setCapacity(long capacity) - { - - } - - public long getFlowResumeCapacity() - { - return 0; - } - - public void setFlowResumeCapacity(long flowResumeCapacity) - { - - } - - public void configure(QueueConfiguration config) - { - - } - - public AuthorizationHolder getAuthorizationHolder() - { - return _authorizationHolder; - } - - public void setAuthorizationHolder(final AuthorizationHolder authorizationHolder) - { - _authorizationHolder = authorizationHolder; - } - - public AMQSessionModel getExclusiveOwningSession() - { - return _exclusiveOwner; - } - - public void setExclusiveOwningSession(AMQSessionModel exclusiveOwner) - { - _exclusiveOwner = exclusiveOwner; - } - - public boolean isOverfull() - { - return false; - } - - public int getConsumerCountHigh() - { - return 0; - } - - public long getByteTxnEnqueues() - { - return 0; - } - - public long getMsgTxnEnqueues() - { - return 0; - } - - public long getByteTxnDequeues() - { - return 0; - } - - public long getMsgTxnDequeues() - { - return 0; - } - - public void decrementUnackedMsgCount(QueueEntry queueEntry) - { - - } - - public long getUnackedMessageCount() - { - return 0; - } - - public long getUnackedMessageCountHigh() - { - return 0; - } - - public void setExclusive(boolean exclusive) - { - } - - public int getMaximumDeliveryCount() - { - return 0; - } - - public void setMaximumDeliveryCount(int maximumDeliveryCount) - { - } - - public void visit(final QueueEntryVisitor visitor) - { - } - - @Override - public void setNotificationListener(NotificationListener listener) - { - } - - @Override - public void setDescription(String description) - { - } - - @Override - public String getDescription() - { - return null; - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/MockQueueEntry.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/MockQueueEntry.java deleted file mode 100644 index f5d4f1219d..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/MockQueueEntry.java +++ /dev/null @@ -1,253 +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.server.message.AMQMessageHeader; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.subscription.Subscription; - -public class MockQueueEntry implements QueueEntry -{ - - private ServerMessage _message; - - public boolean acquire() - { - return false; - } - - public boolean acquire(Subscription sub) - { - return false; - } - - public boolean acquiredBySubscription() - { - return false; - } - - public boolean isAcquiredBy(Subscription subscription) - { - return false; - } - - public void addStateChangeListener(StateChangeListener listener) - { - - } - - public boolean delete() - { - return false; - } - - public void dequeue() - { - - } - - public void discard() - { - - } - - public void routeToAlternate() - { - - } - - public void dispose() - { - - } - - public boolean expired() throws AMQException - { - return false; - } - - public boolean isAvailable() - { - return false; - } - - public Subscription getDeliveredSubscription() - { - return null; - } - - public boolean getDeliveredToConsumer() - { - return false; - } - - public ServerMessage getMessage() - { - return _message; - } - - public AMQQueue getQueue() - { - return null; - } - - public long getSize() - { - return 0; - } - - public boolean isAcquired() - { - return false; - } - - public boolean isDeleted() - { - return false; - } - - - public boolean isQueueDeleted() - { - - return false; - } - - - public boolean isRejectedBy(long subscriptionId) - { - - return false; - } - - - public void reject() - { - - - } - - - public void release() - { - - - } - - - public boolean removeStateChangeListener(StateChangeListener listener) - { - - return false; - } - - - public void requeue() - { - - - } - - public void requeue(Subscription subscription) - { - //To change body of implemented methods use File | Settings | File Templates. - } - - - public void setDeliveredToSubscription() - { - - - } - - - public void setRedelivered() - { - - - } - - public AMQMessageHeader getMessageHeader() - { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - public boolean isPersistent() - { - return false; //To change body of implemented methods use File | Settings | File Templates. - } - - public boolean isRedelivered() - { - return false; - } - - - public int compareTo(QueueEntry o) - { - - return 0; - } - - public void setMessage(ServerMessage msg) - { - _message = msg; - } - - public boolean isDequeued() - { - return false; - } - - public boolean isDispensed() - { - return false; - } - - public QueueEntry getNextNode() - { - return null; - } - - public QueueEntry getNextValidEntry() - { - return null; - } - - @Override - public int getDeliveryCount() - { - return 0; - } - - @Override - public void incrementDeliveryCount() - { - } - - @Override - public void decrementDeliveryCount() - { - } - - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/NotificationCheckTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/NotificationCheckTest.java deleted file mode 100644 index df2de7f0e0..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/NotificationCheckTest.java +++ /dev/null @@ -1,106 +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 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/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/PriorityQueueListTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/PriorityQueueListTest.java deleted file mode 100644 index e8c0470915..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/PriorityQueueListTest.java +++ /dev/null @@ -1,117 +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 static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.message.MessageReference; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.test.utils.QpidTestCase; - -public class PriorityQueueListTest extends QpidTestCase -{ - private static final byte[] PRIORITIES = {4, 5, 5, 4}; - PriorityQueueList _list = new PriorityQueueList(null, 10); - - private QueueEntry _priority4message1; - private QueueEntry _priority4message2; - private QueueEntry _priority5message1; - private QueueEntry _priority5message2; - - protected void setUp() - { - QueueEntry[] entries = new QueueEntry[PRIORITIES.length]; - - for (int i = 0; i < PRIORITIES.length; i++) - { - ServerMessage<?> message = mock(ServerMessage.class); - AMQMessageHeader header = mock(AMQMessageHeader.class); - @SuppressWarnings({ "rawtypes", "unchecked" }) - MessageReference<ServerMessage> ref = mock(MessageReference.class); - - when(message.getMessageHeader()).thenReturn(header); - when(message.newReference()).thenReturn(ref); - when(ref.getMessage()).thenReturn(message); - when(header.getPriority()).thenReturn(PRIORITIES[i]); - - entries[i] = _list.add(message); - } - - _priority4message1 = entries[0]; - _priority4message2 = entries[3]; - _priority5message1 = entries[1]; - _priority5message2 = entries[2]; - } - - public void testPriorityQueueEntryCompareToItself() - { - //check messages compare to themselves properly - assertEquals("message should compare 'equal' to itself", - 0, _priority4message1.compareTo(_priority4message1)); - - assertEquals("message should compare 'equal' to itself", - 0, _priority5message2.compareTo(_priority5message2)); - } - - public void testPriorityQueueEntryCompareToSamePriority() - { - //check messages with the same priority are ordered properly - assertEquals("first message should be 'earlier' than second message of the same priority", - -1, _priority4message1.compareTo(_priority4message2)); - - assertEquals("first message should be 'earlier' than second message of the same priority", - -1, _priority5message1.compareTo(_priority5message2)); - - //and in reverse - assertEquals("second message should be 'later' than first message of the same priority", - 1, _priority4message2.compareTo(_priority4message1)); - - assertEquals("second message should be 'later' than first message of the same priority", - 1, _priority5message2.compareTo(_priority5message1)); - } - - public void testPriorityQueueEntryCompareToDifferentPriority() - { - //check messages with higher priority are ordered 'earlier' than those with lower priority - assertEquals("first message with priority 5 should be 'earlier' than first message of priority 4", - -1, _priority5message1.compareTo(_priority4message1)); - assertEquals("first message with priority 5 should be 'earlier' than second message of priority 4", - -1, _priority5message1.compareTo(_priority4message2)); - - assertEquals("second message with priority 5 should be 'earlier' than first message of priority 4", - -1, _priority5message2.compareTo(_priority4message1)); - assertEquals("second message with priority 5 should be 'earlier' than second message of priority 4", - -1, _priority5message2.compareTo(_priority4message2)); - - //and in reverse - assertEquals("first message with priority 4 should be 'later' than first message of priority 5", - 1, _priority4message1.compareTo(_priority5message1)); - assertEquals("first message with priority 4 should be 'later' than second message of priority 5", - 1, _priority4message1.compareTo(_priority5message2)); - - assertEquals("second message with priority 4 should be 'later' than first message of priority 5", - 1, _priority4message2.compareTo(_priority5message1)); - assertEquals("second message with priority 4 should be 'later' than second message of priority 5", - 1, _priority4message2.compareTo(_priority5message2)); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/QueueEntryImplTestBase.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/QueueEntryImplTestBase.java deleted file mode 100644 index d348c3e67b..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/QueueEntryImplTestBase.java +++ /dev/null @@ -1,253 +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 junit.framework.TestCase; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.queue.QueueEntry.EntryState; -import org.apache.qpid.server.subscription.MockSubscription; -import org.apache.qpid.server.subscription.Subscription; - -import java.lang.reflect.Field; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * Tests for {@link QueueEntryImpl} - */ -public abstract class QueueEntryImplTestBase extends TestCase -{ - // tested entry - protected QueueEntryImpl _queueEntry; - protected QueueEntryImpl _queueEntry2; - protected QueueEntryImpl _queueEntry3; - - public abstract QueueEntryImpl getQueueEntryImpl(int msgid) throws AMQException; - - public abstract void testCompareTo(); - - public abstract void testTraverseWithNoDeletedEntries(); - - public abstract void testTraverseWithDeletedEntries(); - - public void setUp() throws Exception - { - _queueEntry = getQueueEntryImpl(1); - _queueEntry2 = getQueueEntryImpl(2); - _queueEntry3 = getQueueEntryImpl(3); - } - - public void testAquire() - { - assertTrue("Queue entry should be in AVAILABLE state before invoking of acquire method", - _queueEntry.isAvailable()); - acquire(); - } - - public void testDequeue() - { - dequeue(); - } - - public void testDelete() - { - delete(); - } - - /** - * Tests release method for entry in acquired state. - * <p> - * Entry in state ACQUIRED should be released and its status should be - * changed to AVAILABLE. - */ - public void testReleaseAquired() - { - acquire(); - _queueEntry.release(); - assertTrue("Queue entry should be in AVAILABLE state after invoking of release method", - _queueEntry.isAvailable()); - } - - /** - * Tests release method for entry in dequeued state. - * <p> - * Invoking release on dequeued entry should not have any effect on its - * state. - */ - public void testReleaseDequeued() - { - dequeue(); - _queueEntry.release(); - EntryState state = getState(); - assertEquals("Invoking of release on entry in DEQUEUED state should not have any effect", - QueueEntry.DEQUEUED_STATE, state); - } - - /** - * Tests release method for entry in deleted state. - * <p> - * Invoking release on deleted entry should not have any effect on its - * state. - */ - public void testReleaseDeleted() - { - delete(); - _queueEntry.release(); - assertTrue("Invoking of release on entry in DELETED state should not have any effect", - _queueEntry.isDeleted()); - } - - /** - * A helper method to put tested object into deleted state and assert the state - */ - private void delete() - { - _queueEntry.delete(); - assertTrue("Queue entry should be in DELETED state after invoking of delete method", - _queueEntry.isDeleted()); - } - - /** - * A helper method to put tested entry into dequeue state and assert the sate - */ - private void dequeue() - { - acquire(); - _queueEntry.dequeue(); - EntryState state = getState(); - assertEquals("Queue entry should be in DEQUEUED state after invoking of dequeue method", - QueueEntry.DEQUEUED_STATE, state); - } - - /** - * A helper method to put tested entry into acquired state and assert the sate - */ - private void acquire() - { - _queueEntry.acquire(new MockSubscription()); - assertTrue("Queue entry should be in ACQUIRED state after invoking of acquire method", - _queueEntry.isAcquired()); - } - - /** - * A helper method to get entry state - * - * @return entry state - */ - private EntryState getState() - { - EntryState state = null; - try - { - Field f = QueueEntryImpl.class.getDeclaredField("_state"); - f.setAccessible(true); - state = (EntryState) f.get(_queueEntry); - } - catch (Exception e) - { - fail("Failure to get a state field: " + e.getMessage()); - } - return state; - } - - /** - * Tests rejecting a queue entry records the Subscription ID - * for later verification by isRejectedBy(subscriptionId). - */ - public void testRejectAndRejectedBy() - { - Subscription sub = new MockSubscription(); - long subId = sub.getSubscriptionID(); - - assertFalse("Queue entry should not yet have been rejected by the subscription", _queueEntry.isRejectedBy(subId)); - assertFalse("Queue entry should not yet have been acquired by a subscription", _queueEntry.isAcquired()); - - //acquire, reject, and release the message using the subscription - assertTrue("Queue entry should have been able to be acquired", _queueEntry.acquire(sub)); - _queueEntry.reject(); - _queueEntry.release(); - - //verify the rejection is recorded - assertTrue("Queue entry should have been rejected by the subscription", _queueEntry.isRejectedBy(subId)); - - //repeat rejection using a second subscription - Subscription sub2 = new MockSubscription(); - long sub2Id = sub2.getSubscriptionID(); - - assertFalse("Queue entry should not yet have been rejected by the subscription", _queueEntry.isRejectedBy(sub2Id)); - assertTrue("Queue entry should have been able to be acquired", _queueEntry.acquire(sub2)); - _queueEntry.reject(); - - //verify it still records being rejected by both subscriptions - assertTrue("Queue entry should have been rejected by the subscription", _queueEntry.isRejectedBy(subId)); - assertTrue("Queue entry should have been rejected by the subscription", _queueEntry.isRejectedBy(sub2Id)); - } - - /** - * Tests if entries in DEQUQUED or DELETED state are not returned by getNext method. - */ - public void testGetNext() - { - int numberOfEntries = 5; - QueueEntryImpl[] entries = new QueueEntryImpl[numberOfEntries]; - SimpleQueueEntryList queueEntryList = new SimpleQueueEntryList(new MockAMQQueue("test")); - - // create test entries - for(int i = 0; i < numberOfEntries ; i++) - { - ServerMessage message = mock(ServerMessage.class); - when(message.getMessageNumber()).thenReturn((long)i); - QueueEntryImpl entry = queueEntryList.add(message); - entries[i] = entry; - } - - // test getNext for not acquired entries - for(int i = 0; i < numberOfEntries ; i++) - { - QueueEntryImpl queueEntry = entries[i]; - QueueEntry next = queueEntry.getNextValidEntry(); - if (i < numberOfEntries - 1) - { - assertEquals("Unexpected entry from QueueEntryImpl#getNext()", entries[i + 1], next); - } - else - { - assertNull("The next entry after the last should be null", next); - } - } - - // delete second - entries[1].acquire(); - entries[1].delete(); - - // dequeue third - entries[2].acquire(); - entries[2].dequeue(); - - QueueEntry next = entries[0].getNextValidEntry(); - assertEquals("expected forth entry",entries[3], next); - next = next.getNextValidEntry(); - assertEquals("expected fifth entry", entries[4], next); - next = next.getNextValidEntry(); - assertNull("The next entry after the last should be null", next); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/QueueEntryListTestBase.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/QueueEntryListTestBase.java deleted file mode 100644 index beb5bda7ff..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/QueueEntryListTestBase.java +++ /dev/null @@ -1,241 +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 junit.framework.TestCase; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.message.MessageReference; -import org.apache.qpid.server.message.ServerMessage; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * Abstract test class for QueueEntryList implementations. - */ -public abstract class QueueEntryListTestBase extends TestCase -{ - protected static final AMQQueue _testQueue = new MockAMQQueue("test"); - public abstract QueueEntryList<QueueEntry> getTestList(); - public abstract QueueEntryList<QueueEntry> getTestList(boolean newList); - public abstract long getExpectedFirstMsgId(); - public abstract int getExpectedListLength(); - public abstract ServerMessage getTestMessageToAdd() throws AMQException; - - public void testGetQueue() - { - assertEquals("Unexpected head entry returned by getHead()", getTestList().getQueue(), _testQueue); - } - - /** - * Test to add a message with properties specific to the queue type. - * @see QueueEntryListTestBase#getTestList() - * @see QueueEntryListTestBase#getTestMessageToAdd() - * @throws AMQException - */ - public void testAddSpecificMessage() throws AMQException - { - final QueueEntryList<QueueEntry> list = getTestList(); - list.add(getTestMessageToAdd()); - - final QueueEntryIterator<?> iter = list.iterator(); - int count = 0; - while(iter.advance()) - { - iter.getNode(); - count++; - } - assertEquals("List did not grow by one entry after an add", getExpectedListLength() + 1, count); - } - - /** - * Test to add a generic mock message. - * @see QueueEntryListTestBase#getTestList() - * @see QueueEntryListTestBase#getExpectedListLength() - * @throws AMQException - */ - public void testAddGenericMessage() throws AMQException - { - final QueueEntryList<QueueEntry> list = getTestList(); - final ServerMessage message = createServerMessage(666l); - list.add(message); - - final QueueEntryIterator<?> iter = list.iterator(); - int count = 0; - while(iter.advance()) - { - iter.getNode(); - count++; - } - assertEquals("List did not grow by one entry after a generic message added", getExpectedListLength() + 1, count); - - } - - private ServerMessage createServerMessage(long number) - { - final ServerMessage message = mock(ServerMessage.class); - when(message.getMessageNumber()).thenReturn(number); - MessageReference ref = mock(MessageReference.class); - AMQMessageHeader hdr = mock(AMQMessageHeader.class); - when(ref.getMessage()).thenReturn(message); - when(message.newReference()).thenReturn(ref); - when(message.getMessageHeader()).thenReturn(hdr); - return message; - } - - /** - * Test for getting the next element in a queue list. - * @see QueueEntryListTestBase#getTestList() - * @see QueueEntryListTestBase#getExpectedListLength() - */ - public void testListNext() - { - final QueueEntryList<QueueEntry> entryList = getTestList(); - QueueEntry entry = entryList.getHead(); - int count = 0; - while(entryList.next(entry) != null) - { - entry = entryList.next(entry); - count++; - } - assertEquals("Get next didnt get all the list entries", getExpectedListLength(), count); - } - - /** - * Basic test for the associated QueueEntryIterator implementation. - * @see QueueEntryListTestBase#getTestList() - * @see QueueEntryListTestBase#getExpectedListLength() - */ - public void testIterator() - { - final QueueEntryIterator<?> iter = getTestList().iterator(); - int count = 0; - while(iter.advance()) - { - iter.getNode(); - count++; - } - assertEquals("Iterator invalid", getExpectedListLength(), count); - } - - /** - * Test for associated QueueEntryIterator implementation that checks it handles "removed" messages. - * @see QueueEntryListTestBase#getTestList() - * @see QueueEntryListTestBase#getExpectedListLength() - */ - public void testDequedMessagedNotPresentInIterator() throws Exception - { - final int numberOfMessages = getExpectedListLength(); - final QueueEntryList<QueueEntry> entryList = getTestList(); - - // dequeue all even messages - final QueueEntryIterator<?> it1 = entryList.iterator(); - int counter = 0; - while (it1.advance()) - { - final QueueEntry queueEntry = it1.getNode(); - if(counter++ % 2 == 0) - { - queueEntry.acquire(); - queueEntry.dequeue(); - } - } - - // iterate and check that dequeued messages are not returned by iterator - final QueueEntryIterator<?> it2 = entryList.iterator(); - int counter2 = 0; - while(it2.advance()) - { - it2.getNode(); - counter2++; - } - final int expectedNumber = numberOfMessages / 2; - assertEquals("Expected " + expectedNumber + " number of entries in iterator but got " + counter2, - expectedNumber, counter2); - } - - /** - * Test to verify the head of the queue list is returned as expected. - * @see QueueEntryListTestBase#getTestList() - * @see QueueEntryListTestBase#getExpectedFirstMsgId() - */ - public void testGetHead() - { - final QueueEntry head = getTestList().getHead(); - assertNull("Head entry should not contain an actual message", head.getMessage()); - assertEquals("Unexpected message id for first list entry", getExpectedFirstMsgId(), getTestList().next(head) - .getMessage().getMessageNumber()); - } - - /** - * Test to verify the entry deletion handled correctly. - * @see QueueEntryListTestBase#getTestList() - */ - public void testEntryDeleted() - { - final QueueEntry head = getTestList().getHead(); - - final QueueEntry first = getTestList().next(head); - first.delete(); - - final QueueEntry second = getTestList().next(head); - assertNotSame("After deletion the next entry should be different", first.getMessage().getMessageNumber(), second - .getMessage().getMessageNumber()); - - final QueueEntry third = getTestList().next(first); - assertEquals("After deletion the deleted nodes next node should be the same as the next from head", second - .getMessage().getMessageNumber(), third.getMessage().getMessageNumber()); - } - - /** - * Tests that after the last node of the list is marked deleted but has not yet been removed, - * the iterator still ignores it and returns that it is 'atTail()' and can't 'advance()' - * - * @see QueueEntryListTestBase#getTestList() - * @see QueueEntryListTestBase#getExpectedListLength() - */ - public void testIteratorIgnoresDeletedFinalNode() throws Exception - { - QueueEntryList<QueueEntry> list = getTestList(true); - int i = 0; - - QueueEntry queueEntry1 = list.add(createServerMessage(i++)); - QueueEntry queueEntry2 = list.add(createServerMessage(i++)); - - assertSame(queueEntry2, list.next(queueEntry1)); - assertNull(list.next(queueEntry2)); - - //'delete' the 2nd QueueEntry - assertTrue("Deleting node should have succeeded", queueEntry2.delete()); - - QueueEntryIterator<QueueEntry> iter = list.iterator(); - - //verify the iterator isn't 'atTail', can advance, and returns the 1st QueueEntry - assertFalse("Iterator should not have been 'atTail'", iter.atTail()); - assertTrue("Iterator should have been able to advance", iter.advance()); - assertSame("Iterator returned unexpected QueueEntry", queueEntry1, iter.getNode()); - - //verify the iterator is atTail() and can't advance - assertTrue("Iterator should have been 'atTail'", iter.atTail()); - assertFalse("Iterator should not have been able to advance", iter.advance()); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SelfValidatingSortedQueueEntryList.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SelfValidatingSortedQueueEntryList.java deleted file mode 100644 index 674af36b77..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SelfValidatingSortedQueueEntryList.java +++ /dev/null @@ -1,161 +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 junit.framework.Assert; - -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.queue.SortedQueueEntryImpl.Colour; - -/** - * Test extension of SortedQueueEntryList that provides data structure validation tests. - * @see SortedQueueEntryList - */ -public class SelfValidatingSortedQueueEntryList extends SortedQueueEntryList -{ - public SelfValidatingSortedQueueEntryList(AMQQueue queue, String propertyName) - { - super(queue, propertyName); - } - - @Override /** Overridden to automatically check queue properties before and after. */ - public SortedQueueEntryImpl add(final ServerMessage message) - { - assertQueueProperties(); //before add - final SortedQueueEntryImpl result = super.add(message); - assertQueueProperties(); //after add - return result; - } - - @Override /** Overridden to automatically check queue properties before and after. */ - public void entryDeleted(SortedQueueEntryImpl entry) - { - assertQueueProperties(); //before delete - super.entryDeleted(entry); - assertQueueProperties(); //after delete - } - - public void assertQueueProperties() - { - assertRootIsBlack(); - assertTreeIntegrity(); - assertChildrenOfRedAreBlack(); - assertLeavesSameBlackPath(); - } - - public void assertRootIsBlack() - { - if(!isNodeColour(getRoot(), Colour.BLACK)) - { - Assert.fail("Root Not Black"); - } - } - - public void assertTreeIntegrity() - { - assertTreeIntegrity(getRoot()); - } - - public void assertTreeIntegrity(final SortedQueueEntryImpl node) - { - if(node == null) - { - return; - } - if(node.getLeft() != null) - { - if(node.getLeft().getParent() == node) - { - assertTreeIntegrity(node.getLeft()); - } - else - { - Assert.fail("Tree integrity compromised"); - } - } - if(node.getRight() != null) - { - if(node.getRight().getParent() == node) - { - assertTreeIntegrity(node.getRight()); - } - else - { - Assert.fail("Tree integrity compromised"); - } - - } - } - - public void assertLeavesSameBlackPath() - { - assertLeavesSameBlackPath(getRoot()); - } - - public int assertLeavesSameBlackPath(final SortedQueueEntryImpl node) - { - if(node == null) - { - return 1; - } - final int left = assertLeavesSameBlackPath(node.getLeft()); - final int right = assertLeavesSameBlackPath(node.getLeft()); - if(left == right) - { - return isNodeColour(node, Colour.BLACK) ? 1 + left : left; - } - else - { - Assert.fail("Unequal paths to leaves"); - return 1; //compiler - } - } - - public void assertChildrenOfRedAreBlack() - { - assertChildrenOfRedAreBlack(getRoot()); - } - - public void assertChildrenOfRedAreBlack(final SortedQueueEntryImpl node) - { - if(node == null) - { - return; - } - else if(node.getColour() == Colour.BLACK) - { - assertChildrenOfRedAreBlack(node.getLeft()); - assertChildrenOfRedAreBlack(node.getRight()); - } - else - { - if(isNodeColour(node.getLeft(), Colour.BLACK) - && isNodeColour(node.getRight(), Colour.BLACK)) - { - assertChildrenOfRedAreBlack(node.getLeft()); - assertChildrenOfRedAreBlack(node.getRight()); - } - else - { - Assert.fail("Children of Red are not both black"); - } - } - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueTest.java deleted file mode 100644 index 3a41bb9c72..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueTest.java +++ /dev/null @@ -1,1248 +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 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 static org.mockito.Mockito.when; - -import java.util.Map; -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.framing.abstraction.MessagePublishInfo; -import org.apache.qpid.server.exchange.DirectExchange; -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.message.MessageReference; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.model.UUIDGenerator; -import org.apache.qpid.server.queue.BaseQueue.PostEnqueueAction; -import org.apache.qpid.server.queue.SimpleAMQQueue.QueueEntryFilter; -import org.apache.qpid.server.subscription.MockSubscription; -import org.apache.qpid.server.subscription.Subscription; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.test.utils.QpidTestCase; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -public class SimpleAMQQueueTest extends QpidTestCase -{ - - private SimpleAMQQueue _queue; - private VirtualHost _virtualHost; - private String _qname = "qname"; - private String _owner = "owner"; - private String _routingKey = "routing key"; - private DirectExchange _exchange; - private MockSubscription _subscription = new MockSubscription(); - private Map<String,Object> _arguments = null; - - @Override - public void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - - _virtualHost = BrokerTestHelper.createVirtualHost(getClass().getName()); - - _queue = (SimpleAMQQueue) _virtualHost.createQueue(UUIDGenerator.generateRandomUUID(), _qname, false, _owner, - false, false, false, _arguments); - - _exchange = (DirectExchange) _virtualHost.getExchange(ExchangeDefaults.DIRECT_EXCHANGE_NAME); - } - - @Override - public void tearDown() throws Exception - { - try - { - _queue.stop(); - _virtualHost.close(); - } - finally - { - BrokerTestHelper.tearDown(); - super.tearDown(); - } - } - - public void testCreateQueue() throws AMQException - { - _queue.stop(); - try - { - _queue = (SimpleAMQQueue) _virtualHost.createQueue(UUIDGenerator.generateRandomUUID(), null, - false, _owner, false, - false, false, _arguments); - assertNull("Queue was created", _queue); - } - catch (IllegalArgumentException e) - { - assertTrue("Exception was not about missing name", - e.getMessage().contains("name")); - } - - try - { - _queue = new SimpleAMQQueue(UUIDGenerator.generateRandomUUID(), _qname, false, _owner, false,false, null, Collections.EMPTY_MAP); - assertNull("Queue was created", _queue); - } - catch (IllegalArgumentException e) - { - assertTrue("Exception was not about missing vhost", - e.getMessage().contains("Host")); - } - - _queue = (SimpleAMQQueue) _virtualHost.createQueue(UUIDGenerator.generateRandomUUID(), - "differentName", false, - _owner, false, - false, false, _arguments); - assertNotNull("Queue was not created", _queue); - } - - public void testGetVirtualHost() - { - assertEquals("Virtual host was wrong", _virtualHost, _queue.getVirtualHost()); - } - - public void testBinding() throws AMQSecurityException, AMQInternalException - { - _exchange.addBinding(_routingKey, _queue, Collections.EMPTY_MAP); - - assertTrue("Routing key was not bound", - _exchange.isBound(_routingKey)); - assertTrue("Queue was not bound to key", - _exchange.isBound(_routingKey,_queue)); - assertEquals("Exchange binding count", 1, - _queue.getBindings().size()); - assertEquals("Wrong exchange bound", _routingKey, - _queue.getBindings().get(0).getBindingKey()); - assertEquals("Wrong exchange bound", _exchange, - _queue.getBindings().get(0).getExchange()); - - _exchange.removeBinding(_routingKey, _queue, Collections.EMPTY_MAP); - assertFalse("Routing key was still bound", - _exchange.isBound(_routingKey)); - - } - - public void testRegisterSubscriptionThenEnqueueMessage() throws AMQException - { - // Check adding a subscription adds it to the queue - _queue.registerSubscription(_subscription, false); - assertEquals("Subscription did not get queue", _queue, - _subscription.getQueue()); - assertEquals("Queue does not have consumer", 1, - _queue.getConsumerCount()); - assertEquals("Queue does not have active consumer", 1, - _queue.getActiveConsumerCount()); - - // Check sending a message ends up with the subscriber - ServerMessage messageA = createMessage(new Long(24)); - _queue.enqueue(messageA); - try - { - Thread.sleep(2000L); - } - catch(InterruptedException e) - { - } - assertEquals(messageA, _subscription.getQueueContext().getLastSeenEntry().getMessage()); - assertNull(((QueueContext)_subscription.getQueueContext()).getReleasedEntry()); - - // Check removing the subscription removes it's information from the queue - _queue.unregisterSubscription(_subscription); - assertTrue("Subscription still had queue", _subscription.isClosed()); - assertFalse("Queue still has consumer", 1 == _queue.getConsumerCount()); - assertFalse("Queue still has active consumer", - 1 == _queue.getActiveConsumerCount()); - - ServerMessage messageB = createMessage(new Long (25)); - _queue.enqueue(messageB); - assertNull(_subscription.getQueueContext()); - - } - - public void testEnqueueMessageThenRegisterSubscription() throws AMQException, InterruptedException - { - ServerMessage messageA = createMessage(new Long(24)); - _queue.enqueue(messageA); - _queue.registerSubscription(_subscription, false); - Thread.sleep(150); - assertEquals(messageA, _subscription.getQueueContext().getLastSeenEntry().getMessage()); - assertNull("There should be no releasedEntry after an enqueue", ((QueueContext)_subscription.getQueueContext()).getReleasedEntry()); - } - - /** - * Tests enqueuing two messages. - */ - public void testEnqueueTwoMessagesThenRegisterSubscription() throws Exception - { - ServerMessage messageA = createMessage(new Long(24)); - ServerMessage messageB = createMessage(new Long(25)); - _queue.enqueue(messageA); - _queue.enqueue(messageB); - _queue.registerSubscription(_subscription, false); - Thread.sleep(150); - assertEquals(messageB, _subscription.getQueueContext().getLastSeenEntry().getMessage()); - assertNull("There should be no releasedEntry after enqueues", ((QueueContext)_subscription.getQueueContext()).getReleasedEntry()); - } - - /** - * Tests that a released queue entry is resent to the subscriber. Verifies also that the - * QueueContext._releasedEntry is reset to null after the entry has been reset. - */ - public void testReleasedMessageIsResentToSubscriber() throws Exception - { - _queue.registerSubscription(_subscription, false); - - final ArrayList<QueueEntry> queueEntries = new ArrayList<QueueEntry>(); - PostEnqueueAction postEnqueueAction = new PostEnqueueAction() - { - public void onEnqueue(QueueEntry entry) - { - queueEntries.add(entry); - } - }; - - ServerMessage messageA = createMessage(new Long(24)); - ServerMessage messageB = createMessage(new Long(25)); - ServerMessage messageC = createMessage(new Long(26)); - - /* Enqueue three messages */ - - _queue.enqueue(messageA, postEnqueueAction); - _queue.enqueue(messageB, postEnqueueAction); - _queue.enqueue(messageC, postEnqueueAction); - - Thread.sleep(150); // Work done by SubFlushRunner/QueueRunner Threads - - assertEquals("Unexpected total number of messages sent to subscription", 3, _subscription.getMessages().size()); - assertFalse("Redelivery flag should not be set", queueEntries.get(0).isRedelivered()); - assertFalse("Redelivery flag should not be set", queueEntries.get(1).isRedelivered()); - assertFalse("Redelivery flag should not be set", queueEntries.get(2).isRedelivered()); - - /* Now release the first message only, causing it to be requeued */ - - queueEntries.get(0).release(); - - Thread.sleep(150); // Work done by SubFlushRunner/QueueRunner Threads - - assertEquals("Unexpected total number of messages sent to subscription", 4, _subscription.getMessages().size()); - assertTrue("Redelivery flag should now be set", queueEntries.get(0).isRedelivered()); - assertFalse("Redelivery flag should remain be unset", queueEntries.get(1).isRedelivered()); - assertFalse("Redelivery flag should remain be unset",queueEntries.get(2).isRedelivered()); - assertNull("releasedEntry should be cleared after requeue processed", ((QueueContext)_subscription.getQueueContext()).getReleasedEntry()); - } - - /** - * Tests that a released message that becomes expired is not resent to the subscriber. - * This tests ensures that SimpleAMQQueueEntry.getNextAvailableEntry avoids expired entries. - * Verifies also that the QueueContext._releasedEntry is reset to null after the entry has been reset. - */ - public void testReleaseMessageThatBecomesExpiredIsNotRedelivered() throws Exception - { - _queue.registerSubscription(_subscription, false); - - final ArrayList<QueueEntry> queueEntries = new ArrayList<QueueEntry>(); - PostEnqueueAction postEnqueueAction = new PostEnqueueAction() - { - public void onEnqueue(QueueEntry entry) - { - queueEntries.add(entry); - } - }; - - /* Enqueue one message with expiration set for a short time in the future */ - - ServerMessage messageA = createMessage(new Long(24)); - int messageExpirationOffset = 200; - final long expiration = System.currentTimeMillis() + messageExpirationOffset; - when(messageA.getExpiration()).thenReturn(expiration); - - _queue.enqueue(messageA, postEnqueueAction); - - int subFlushWaitTime = 150; - Thread.sleep(subFlushWaitTime); // Work done by SubFlushRunner/QueueRunner Threads - - assertEquals("Unexpected total number of messages sent to subscription", 1, _subscription.getMessages().size()); - assertFalse("Redelivery flag should not be set", queueEntries.get(0).isRedelivered()); - - /* Wait a little more to be sure that message will have expired, then release the first message only, causing it to be requeued */ - Thread.sleep(messageExpirationOffset - subFlushWaitTime + 10); - queueEntries.get(0).release(); - - Thread.sleep(subFlushWaitTime); // Work done by SubFlushRunner/QueueRunner Threads - - assertTrue("Expecting the queue entry to be now expired", queueEntries.get(0).expired()); - assertEquals("Total number of messages sent should not have changed", 1, _subscription.getMessages().size()); - assertFalse("Redelivery flag should not be set", queueEntries.get(0).isRedelivered()); - assertNull("releasedEntry should be cleared after requeue processed", ((QueueContext)_subscription.getQueueContext()).getReleasedEntry()); - - } - - /** - * Tests that if a client releases entries 'out of order' (the order - * used by QueueEntryImpl.compareTo) that messages are still resent - * successfully. Specifically this test ensures the {@see SimpleAMQQueue#requeue()} - * can correctly move the _releasedEntry to an earlier position in the QueueEntry list. - */ - public void testReleasedOutOfComparableOrderAreRedelivered() throws Exception - { - _queue.registerSubscription(_subscription, false); - - final ArrayList<QueueEntry> queueEntries = new ArrayList<QueueEntry>(); - PostEnqueueAction postEnqueueAction = new PostEnqueueAction() - { - public void onEnqueue(QueueEntry entry) - { - queueEntries.add(entry); - } - }; - - ServerMessage messageA = createMessage(new Long(24)); - ServerMessage messageB = createMessage(new Long(25)); - ServerMessage messageC = createMessage(new Long(26)); - - /* Enqueue three messages */ - - _queue.enqueue(messageA, postEnqueueAction); - _queue.enqueue(messageB, postEnqueueAction); - _queue.enqueue(messageC, postEnqueueAction); - - Thread.sleep(150); // Work done by SubFlushRunner/QueueRunner Threads - - assertEquals("Unexpected total number of messages sent to subscription", 3, _subscription.getMessages().size()); - assertFalse("Redelivery flag should not be set", queueEntries.get(0).isRedelivered()); - assertFalse("Redelivery flag should not be set", queueEntries.get(1).isRedelivered()); - assertFalse("Redelivery flag should not be set", queueEntries.get(2).isRedelivered()); - - /* Now release the third and first message only, causing it to be requeued */ - - queueEntries.get(2).release(); - queueEntries.get(0).release(); - - Thread.sleep(150); // Work done by SubFlushRunner/QueueRunner Threads - - assertEquals("Unexpected total number of messages sent to subscription", 5, _subscription.getMessages().size()); - assertTrue("Redelivery flag should now be set", queueEntries.get(0).isRedelivered()); - assertFalse("Redelivery flag should remain be unset", queueEntries.get(1).isRedelivered()); - assertTrue("Redelivery flag should now be set",queueEntries.get(2).isRedelivered()); - assertNull("releasedEntry should be cleared after requeue processed", ((QueueContext)_subscription.getQueueContext()).getReleasedEntry()); - } - - - /** - * Tests that a release requeues an entry for a queue with multiple subscriptions. Verifies that a - * requeue resends a message to a <i>single</i> subscriber. - */ - public void testReleaseForQueueWithMultipleSubscriptions() throws Exception - { - MockSubscription subscription1 = new MockSubscription(); - MockSubscription subscription2 = new MockSubscription(); - - _queue.registerSubscription(subscription1, false); - _queue.registerSubscription(subscription2, false); - - final ArrayList<QueueEntry> queueEntries = new ArrayList<QueueEntry>(); - PostEnqueueAction postEnqueueAction = new PostEnqueueAction() - { - public void onEnqueue(QueueEntry entry) - { - queueEntries.add(entry); - } - }; - - ServerMessage messageA = createMessage(new Long(24)); - ServerMessage messageB = createMessage(new Long(25)); - - /* Enqueue two messages */ - - _queue.enqueue(messageA, postEnqueueAction); - _queue.enqueue(messageB, postEnqueueAction); - - Thread.sleep(150); // Work done by SubFlushRunner/QueueRunner Threads - - assertEquals("Unexpected total number of messages sent to both after enqueue", 2, subscription1.getMessages().size() + subscription2.getMessages().size()); - - /* Now release the first message only, causing it to be requeued */ - queueEntries.get(0).release(); - - Thread.sleep(150); // Work done by SubFlushRunner/QueueRunner Threads - - assertEquals("Unexpected total number of messages sent to both subscriptions after release", 3, subscription1.getMessages().size() + subscription2.getMessages().size()); - assertNull("releasedEntry should be cleared after requeue processed", ((QueueContext)subscription1.getQueueContext()).getReleasedEntry()); - assertNull("releasedEntry should be cleared after requeue processed", ((QueueContext)subscription2.getQueueContext()).getReleasedEntry()); - } - - public void testExclusiveConsumer() throws AMQException - { - // Check adding an exclusive subscription adds it to the queue - _queue.registerSubscription(_subscription, true); - assertEquals("Subscription did not get queue", _queue, - _subscription.getQueue()); - assertEquals("Queue does not have consumer", 1, - _queue.getConsumerCount()); - assertEquals("Queue does not have active consumer", 1, - _queue.getActiveConsumerCount()); - - // Check sending a message ends up with the subscriber - ServerMessage messageA = createMessage(new Long(24)); - _queue.enqueue(messageA); - try - { - Thread.sleep(2000L); - } - catch (InterruptedException e) - { - } - assertEquals(messageA, _subscription.getQueueContext().getLastSeenEntry().getMessage()); - - // Check we cannot add a second subscriber to the queue - Subscription subB = new MockSubscription(); - Exception ex = null; - try - { - _queue.registerSubscription(subB, false); - } - catch (AMQException e) - { - ex = e; - } - assertNotNull(ex); - - // Check we cannot add an exclusive subscriber to a queue with an - // existing subscription - _queue.unregisterSubscription(_subscription); - _queue.registerSubscription(_subscription, false); - try - { - _queue.registerSubscription(subB, true); - } - catch (AMQException e) - { - ex = e; - } - assertNotNull(ex); - } - - public void testAutoDeleteQueue() throws Exception - { - _queue.stop(); - _queue = new SimpleAMQQueue(UUIDGenerator.generateRandomUUID(), _qname, false, null, true, false, _virtualHost, Collections.EMPTY_MAP); - _queue.setDeleteOnNoConsumers(true); - _queue.registerSubscription(_subscription, false); - ServerMessage message = createMessage(new Long(25)); - _queue.enqueue(message); - _queue.unregisterSubscription(_subscription); - assertTrue("Queue was not deleted when subscription was removed", - _queue.isDeleted()); - } - - public void testResend() throws Exception - { - _queue.registerSubscription(_subscription, false); - Long id = new Long(26); - ServerMessage message = createMessage(id); - _queue.enqueue(message); - QueueEntry entry = _subscription.getQueueContext().getLastSeenEntry(); - entry.setRedelivered(); - _queue.resend(entry, _subscription); - - } - - public void testGetFirstMessageId() throws Exception - { - // Create message - Long messageId = new Long(23); - ServerMessage message = createMessage(messageId); - - // Put message on queue - _queue.enqueue(message); - // Get message id - Long testmsgid = _queue.getMessagesOnTheQueue(1).get(0); - - // Check message id - assertEquals("Message ID was wrong", messageId, testmsgid); - } - - public void testGetFirstFiveMessageIds() throws Exception - { - for (int i = 0 ; i < 5; i++) - { - // Create message - Long messageId = new Long(i); - ServerMessage message = createMessage(messageId); - // Put message on queue - _queue.enqueue(message); - } - // Get message ids - List<Long> msgids = _queue.getMessagesOnTheQueue(5); - - // Check message id - for (int i = 0; i < 5; i++) - { - Long messageId = new Long(i); - assertEquals("Message ID was wrong", messageId, msgids.get(i)); - } - } - - public void testGetLastFiveMessageIds() throws Exception - { - for (int i = 0 ; i < 10; i++) - { - // Create message - Long messageId = new Long(i); - ServerMessage message = createMessage(messageId); - // Put message on queue - _queue.enqueue(message); - } - // Get message ids - List<Long> msgids = _queue.getMessagesOnTheQueue(5, 5); - - // Check message id - for (int i = 0; i < 5; i++) - { - Long messageId = new Long(i+5); - assertEquals("Message ID was wrong", messageId, msgids.get(i)); - } - } - - public void testGetMessagesRangeOnTheQueue() throws Exception - { - for (int i = 1 ; i <= 10; i++) - { - // Create message - Long messageId = new Long(i); - ServerMessage message = createMessage(messageId); - // Put message on queue - _queue.enqueue(message); - } - - // Get non-existent 0th QueueEntry & check returned list was empty - // (the position parameters in this method are indexed from 1) - List<QueueEntry> entries = _queue.getMessagesRangeOnTheQueue(0, 0); - assertTrue(entries.size() == 0); - - // Check that when 'from' is 0 it is ignored and the range continues from 1 - entries = _queue.getMessagesRangeOnTheQueue(0, 2); - assertTrue(entries.size() == 2); - long msgID = entries.get(0).getMessage().getMessageNumber(); - assertEquals("Message ID was wrong", msgID, 1L); - msgID = entries.get(1).getMessage().getMessageNumber(); - assertEquals("Message ID was wrong", msgID, 2L); - - // Check that when 'from' is greater than 'to' the returned list is empty - entries = _queue.getMessagesRangeOnTheQueue(5, 4); - assertTrue(entries.size() == 0); - - // Get first QueueEntry & check id - entries = _queue.getMessagesRangeOnTheQueue(1, 1); - assertTrue(entries.size() == 1); - msgID = entries.get(0).getMessage().getMessageNumber(); - assertEquals("Message ID was wrong", msgID, 1L); - - // Get 5th,6th,7th entries and check id's - entries = _queue.getMessagesRangeOnTheQueue(5, 7); - assertTrue(entries.size() == 3); - msgID = entries.get(0).getMessage().getMessageNumber(); - assertEquals("Message ID was wrong", msgID, 5L); - msgID = entries.get(1).getMessage().getMessageNumber(); - assertEquals("Message ID was wrong", msgID, 6L); - msgID = entries.get(2).getMessage().getMessageNumber(); - assertEquals("Message ID was wrong", msgID, 7L); - - // Get 10th QueueEntry & check id - entries = _queue.getMessagesRangeOnTheQueue(10, 10); - assertTrue(entries.size() == 1); - msgID = entries.get(0).getMessage().getMessageNumber(); - assertEquals("Message ID was wrong", msgID, 10L); - - // Get non-existent 11th QueueEntry & check returned set was empty - entries = _queue.getMessagesRangeOnTheQueue(11, 11); - assertTrue(entries.size() == 0); - - // Get 9th,10th, and non-existent 11th entries & check result is of size 2 with correct IDs - entries = _queue.getMessagesRangeOnTheQueue(9, 11); - assertTrue(entries.size() == 2); - msgID = entries.get(0).getMessage().getMessageNumber(); - assertEquals("Message ID was wrong", msgID, 9L); - msgID = entries.get(1).getMessage().getMessageNumber(); - assertEquals("Message ID was wrong", msgID, 10L); - } - - - /** - * processQueue() is used when asynchronously delivering messages to - * subscriptions which could not be delivered immediately during the - * enqueue() operation. - * - * A defect within the method would mean that delivery of these messages may - * not occur should the Runner stop before all messages have been processed. - * Such a defect was discovered when Selectors were used such that one and - * only one subscription can/will accept any given messages, but multiple - * subscriptions are present, and one of the earlier subscriptions receives - * more messages than the others. - * - * This test is to validate that the processQueue() method is able to - * correctly deliver all of the messages present for asynchronous delivery - * to subscriptions in such a scenario. - */ - public void testProcessQueueWithUniqueSelectors() throws Exception - { - TestSimpleQueueEntryListFactory factory = new TestSimpleQueueEntryListFactory(); - SimpleAMQQueue testQueue = new SimpleAMQQueue(UUIDGenerator.generateRandomUUID(), "testQueue", false,"testOwner", - false, false, _virtualHost, factory, null) - { - @Override - public void deliverAsync(Subscription sub) - { - // do nothing, i.e prevent deliveries by the SubFlushRunner - // when registering the new subscriptions - } - }; - - // retrieve the QueueEntryList the queue creates and insert the test - // messages, thus avoiding straight-through delivery attempts during - //enqueue() process. - QueueEntryList list = factory.getQueueEntryList(); - assertNotNull("QueueEntryList should have been created", list); - - QueueEntry msg1 = list.add(createMessage(1L)); - QueueEntry msg2 = list.add(createMessage(2L)); - QueueEntry msg3 = list.add(createMessage(3L)); - QueueEntry msg4 = list.add(createMessage(4L)); - QueueEntry msg5 = list.add(createMessage(5L)); - - // Create lists of the entries each subscription should be interested - // in.Bias over 50% of the messages to the first subscription so that - // the later subscriptions reject them and report being done before - // the first subscription as the processQueue method proceeds. - List<QueueEntry> msgListSub1 = createEntriesList(msg1, msg2, msg3); - List<QueueEntry> msgListSub2 = createEntriesList(msg4); - List<QueueEntry> msgListSub3 = createEntriesList(msg5); - - MockSubscription sub1 = new MockSubscription(msgListSub1); - MockSubscription sub2 = new MockSubscription(msgListSub2); - MockSubscription sub3 = new MockSubscription(msgListSub3); - - // register the subscriptions - testQueue.registerSubscription(sub1, false); - testQueue.registerSubscription(sub2, false); - testQueue.registerSubscription(sub3, false); - - //check that no messages have been delivered to the - //subscriptions during registration - assertEquals("No messages should have been delivered yet", 0, sub1.getMessages().size()); - assertEquals("No messages should have been delivered yet", 0, sub2.getMessages().size()); - assertEquals("No messages should have been delivered yet", 0, sub3.getMessages().size()); - - // call processQueue to deliver the messages - testQueue.processQueue(new QueueRunner(testQueue) - { - @Override - public void run() - { - // we dont actually want/need this runner to do any work - // because we we are already doing it! - } - }); - - // check expected messages delivered to correct consumers - verifyRecievedMessages(msgListSub1, sub1.getMessages()); - verifyRecievedMessages(msgListSub2, sub2.getMessages()); - verifyRecievedMessages(msgListSub3, sub3.getMessages()); - } - - /** - * Tests that dequeued message is not present in the list returned form - * {@link SimpleAMQQueue#getMessagesOnTheQueue()} - */ - public void testGetMessagesOnTheQueueWithDequeuedEntry() - { - int messageNumber = 4; - int dequeueMessageIndex = 1; - - // send test messages into a test queue - enqueueGivenNumberOfMessages(_queue, messageNumber); - - // dequeue message - dequeueMessage(_queue, dequeueMessageIndex); - - // get messages on the queue - List<QueueEntry> entries = _queue.getMessagesOnTheQueue(); - - // assert queue entries - assertEquals(messageNumber - 1, entries.size()); - int expectedId = 0; - for (int i = 0; i < messageNumber - 1; i++) - { - Long id = ( entries.get(i).getMessage()).getMessageNumber(); - if (i == dequeueMessageIndex) - { - assertFalse("Message with id " + dequeueMessageIndex - + " was dequeued and should not be returned by method getMessagesOnTheQueue!", - 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 present in the list returned form - * {@link SimpleAMQQueue#getMessagesOnTheQueue(QueueEntryFilter)} - */ - public void testGetMessagesOnTheQueueByQueueEntryFilterWithDequeuedEntry() - { - int messageNumber = 4; - int dequeueMessageIndex = 1; - - // send test messages into a test queue - enqueueGivenNumberOfMessages(_queue, messageNumber); - - // dequeue message - dequeueMessage(_queue, dequeueMessageIndex); - - // get messages on the queue with filter accepting all available messages - List<QueueEntry> entries = _queue.getMessagesOnTheQueue(new QueueEntryFilter() - { - public boolean accept(QueueEntry entry) - { - return true; - } - - public boolean filterComplete() - { - return false; - } - }); - - // assert entries on the queue - assertEquals(messageNumber - 1, entries.size()); - int expectedId = 0; - for (int i = 0; i < messageNumber - 1; i++) - { - Long id = (entries.get(i).getMessage()).getMessageNumber(); - if (i == dequeueMessageIndex) - { - assertFalse("Message with id " + dequeueMessageIndex - + " was dequeued and should not be returned by method getMessagesOnTheQueue!", - 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 on the top is not accounted and next message - * is deleted from the queue on invocation of - * {@link SimpleAMQQueue#deleteMessageFromTop()} - */ - public void testDeleteMessageFromTopWithDequeuedEntryOnTop() - { - int messageNumber = 4; - int dequeueMessageIndex = 0; - - // put messages into a test queue - enqueueGivenNumberOfMessages(_queue, messageNumber); - - // dequeue message on top - dequeueMessage(_queue, dequeueMessageIndex); - - //delete message from top - _queue.deleteMessageFromTop(); - - //get queue netries - List<QueueEntry> entries = _queue.getMessagesOnTheQueue(); - - // assert queue entries - assertNotNull("Null is returned from getMessagesOnTheQueue", entries); - assertEquals("Expected " + (messageNumber - 2) + " number of messages but recieved " + entries.size(), - messageNumber - 2, entries.size()); - assertEquals("Expected first entry with id 2", 2l, - (entries.get(0).getMessage()).getMessageNumber()); - } - - /** - * Tests that all messages including dequeued one are deleted from the queue - * on invocation of {@link SimpleAMQQueue#clearQueue()} - */ - public void testClearQueueWithDequeuedEntry() - { - int messageNumber = 4; - int dequeueMessageIndex = 1; - - // put messages into a test queue - enqueueGivenNumberOfMessages(_queue, messageNumber); - - // dequeue message on a test queue - dequeueMessage(_queue, dequeueMessageIndex); - - // clean queue - try - { - _queue.clearQueue(); - } - catch (AMQException e) - { - fail("Failure to clear queue:" + e.getMessage()); - } - - // get queue entries - List<QueueEntry> entries = _queue.getMessagesOnTheQueue(); - - // assert queue entries - assertNotNull(entries); - assertEquals(0, entries.size()); - } - - /** - * Tests whether dequeued entry is sent to subscriber in result of - * invocation of {@link SimpleAMQQueue#processQueue(QueueRunner)} - */ - public void testProcessQueueWithDequeuedEntry() - { - // total number of messages to send - int messageNumber = 4; - int dequeueMessageIndex = 1; - - // create queue with overridden method deliverAsync - SimpleAMQQueue testQueue = new SimpleAMQQueue(UUIDGenerator.generateRandomUUID(), "test", - false, "testOwner", false, false, _virtualHost, null) - { - @Override - public void deliverAsync(Subscription sub) - { - // do nothing - } - }; - - // put messages - List<QueueEntry> entries = enqueueGivenNumberOfMessages(testQueue, messageNumber); - - // dequeue message - dequeueMessage(testQueue, dequeueMessageIndex); - - // latch to wait for message receipt - final CountDownLatch latch = new CountDownLatch(messageNumber -1); - - // create a subscription - MockSubscription subscription = new MockSubscription() - { - /** - * Send a message and decrement latch - * @param entry - * @param batch - */ - public void send(QueueEntry entry, boolean batch) throws AMQException - { - super.send(entry, batch); - latch.countDown(); - } - }; - - try - { - // subscribe - testQueue.registerSubscription(subscription, false); - - // process queue - testQueue.processQueue(new QueueRunner(testQueue) - { - public void run() - { - // do nothing - } - }); - } - catch (AMQException e) - { - fail("Failure to process queue:" + e.getMessage()); - } - // wait up to 1 minute for message receipt - try - { - latch.await(1, TimeUnit.MINUTES); - } - catch (InterruptedException e1) - { - Thread.currentThread().interrupt(); - } - List<QueueEntry> expected = createEntriesList(entries.get(0), entries.get(2), entries.get(3)); - verifyRecievedMessages(expected, subscription.getMessages()); - } - - /** - * Tests that entry in dequeued state are not enqueued and not delivered to subscription - */ - public void testEnqueueDequeuedEntry() - { - // create a queue where each even entry is considered a dequeued - SimpleAMQQueue queue = new SimpleAMQQueue(UUIDGenerator.generateRandomUUID(), "test", false, - "testOwner", false, false, _virtualHost, new QueueEntryListFactory() - { - public QueueEntryList createQueueEntryList(AMQQueue queue) - { - /** - * Override SimpleQueueEntryList to create a dequeued - * entries for messages with even id - */ - return new SimpleQueueEntryList(queue) - { - /** - * Entries with even message id are considered - * dequeued! - */ - protected SimpleQueueEntryImpl createQueueEntry(final ServerMessage message) - { - return new SimpleQueueEntryImpl(this, message) - { - public boolean isDequeued() - { - return (message.getMessageNumber() % 2 == 0); - } - - public boolean isDispensed() - { - return (message.getMessageNumber() % 2 == 0); - } - - public boolean isAvailable() - { - return !(message.getMessageNumber() % 2 == 0); - } - - @Override - public boolean acquire(Subscription sub) - { - if(message.getMessageNumber() % 2 == 0) - { - return false; - } - else - { - return super.acquire(sub); - } - } - }; - } - }; - } - }, null); - // create a subscription - MockSubscription subscription = new MockSubscription(); - - // register subscription - try - { - queue.registerSubscription(subscription, false); - } - catch (AMQException e) - { - fail("Failure to register subscription:" + e.getMessage()); - } - - // put test messages into a queue - putGivenNumberOfMessages(queue, 4); - - // assert received messages - List<QueueEntry> messages = subscription.getMessages(); - assertEquals("Only 2 messages should be returned", 2, messages.size()); - assertEquals("ID of first message should be 1", 1l, - (messages.get(0).getMessage()).getMessageNumber()); - assertEquals("ID of second message should be 3", 3l, - (messages.get(1).getMessage()).getMessageNumber()); - } - - public void testActiveConsumerCount() throws Exception - { - final SimpleAMQQueue queue = new SimpleAMQQueue(UUIDGenerator.generateRandomUUID(), "testActiveConsumerCount", false, - "testOwner", false, false, _virtualHost, new SimpleQueueEntryList.Factory(), null); - - //verify adding an active subscription increases the count - final MockSubscription subscription1 = new MockSubscription(); - subscription1.setActive(true); - assertEquals("Unexpected active consumer count", 0, queue.getActiveConsumerCount()); - queue.registerSubscription(subscription1, false); - assertEquals("Unexpected active consumer count", 1, queue.getActiveConsumerCount()); - - //verify adding an inactive subscription doesn't increase the count - final MockSubscription subscription2 = new MockSubscription(); - subscription2.setActive(false); - assertEquals("Unexpected active consumer count", 1, queue.getActiveConsumerCount()); - queue.registerSubscription(subscription2, false); - assertEquals("Unexpected active consumer count", 1, queue.getActiveConsumerCount()); - - //verify behaviour in face of expected state changes: - - //verify a subscription going suspended->active increases the count - queue.stateChange(subscription2, Subscription.State.SUSPENDED, Subscription.State.ACTIVE); - assertEquals("Unexpected active consumer count", 2, queue.getActiveConsumerCount()); - - //verify a subscription going active->suspended decreases the count - queue.stateChange(subscription2, Subscription.State.ACTIVE, Subscription.State.SUSPENDED); - assertEquals("Unexpected active consumer count", 1, queue.getActiveConsumerCount()); - - //verify a subscription going suspended->closed doesn't change the count - queue.stateChange(subscription2, Subscription.State.SUSPENDED, Subscription.State.CLOSED); - assertEquals("Unexpected active consumer count", 1, queue.getActiveConsumerCount()); - - //verify a subscription going active->closed decreases the count - queue.stateChange(subscription2, Subscription.State.ACTIVE, Subscription.State.CLOSED); - assertEquals("Unexpected active consumer count", 0, queue.getActiveConsumerCount()); - - //verify behaviour in face of unexpected state changes: - - //verify a subscription going closed->active increases the count - queue.stateChange(subscription2, Subscription.State.CLOSED, Subscription.State.ACTIVE); - assertEquals("Unexpected active consumer count", 1, queue.getActiveConsumerCount()); - - //verify a subscription going active->active doesn't change the count - queue.stateChange(subscription2, Subscription.State.ACTIVE, Subscription.State.ACTIVE); - assertEquals("Unexpected active consumer count", 1, queue.getActiveConsumerCount()); - - //verify a subscription going closed->suspended doesn't change the count - queue.stateChange(subscription2, Subscription.State.CLOSED, Subscription.State.SUSPENDED); - assertEquals("Unexpected active consumer count", 1, queue.getActiveConsumerCount()); - - //verify a subscription going suspended->suspended doesn't change the count - queue.stateChange(subscription2, Subscription.State.SUSPENDED, Subscription.State.SUSPENDED); - assertEquals("Unexpected active consumer count", 1, queue.getActiveConsumerCount()); - } - - public void testNotificationFiredOnEnqueue() throws Exception - { - 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")); - } - - /** - * A helper method to put given number of messages into queue - * <p> - * All messages are asserted that they are present on queue - * - * @param queue - * queue to put messages into - * @param messageNumber - * number of messages to put into queue - */ - private List<QueueEntry> enqueueGivenNumberOfMessages(AMQQueue queue, int messageNumber) - { - putGivenNumberOfMessages(queue, messageNumber); - - // make sure that all enqueued messages are on the queue - List<QueueEntry> entries = queue.getMessagesOnTheQueue(); - assertEquals(messageNumber, entries.size()); - for (int i = 0; i < messageNumber; i++) - { - assertEquals((long)i, (entries.get(i).getMessage()).getMessageNumber()); - } - return entries; - } - - /** - * A helper method to put given number of messages into queue - * <p> - * Queue is not checked if messages are added into queue - * - * @param queue - * queue to put messages into - * @param messageNumber - * number of messages to put into queue - * @param queue - * @param messageNumber - */ - private void putGivenNumberOfMessages(AMQQueue queue, int messageNumber) - { - for (int i = 0; i < messageNumber; i++) - { - // Create message - Long messageId = new Long(i); - ServerMessage message = null; - try - { - message = createMessage(messageId); - } - catch (AMQException e) - { - fail("Failure to create a test message:" + e.getMessage()); - } - // Put message on queue - try - { - queue.enqueue(message); - } - catch (AMQException e) - { - fail("Failure to put message on queue:" + e.getMessage()); - } - } - try - { - Thread.sleep(2000L); - } - catch (InterruptedException e) - { - e.printStackTrace(); - } - } - - /** - * A helper method to dequeue an entry on queue with given index - * - * @param queue - * queue to dequeue message on - * @param dequeueMessageIndex - * entry index to dequeue. - */ - private QueueEntry dequeueMessage(AMQQueue queue, int dequeueMessageIndex) - { - List<QueueEntry> entries = queue.getMessagesOnTheQueue(); - QueueEntry entry = entries.get(dequeueMessageIndex); - entry.acquire(); - entry.dequeue(); - assertTrue(entry.isDequeued()); - return entry; - } - - private List<QueueEntry> createEntriesList(QueueEntry... entries) - { - ArrayList<QueueEntry> entriesList = new ArrayList<QueueEntry>(); - for (QueueEntry entry : entries) - { - entriesList.add(entry); - } - return entriesList; - } - - private void verifyRecievedMessages(List<QueueEntry> expected, - List<QueueEntry> delivered) - { - assertEquals("Consumer did not receive the expected number of messages", - expected.size(), delivered.size()); - - for (QueueEntry msg : expected) - { - assertTrue("Consumer did not recieve msg: " - + msg.getMessage().getMessageNumber(), delivered.contains(msg)); - } - } - - public SimpleAMQQueue getQueue() - { - return _queue; - } - - public MockSubscription getSubscription() - { - return _subscription; - } - - public Map<String,Object> getArguments() - { - return _arguments; - } - - public void setArguments(Map<String,Object> arguments) - { - _arguments = arguments; - } - - - protected ServerMessage createMessage(Long id) throws AMQException - { - ServerMessage message = mock(ServerMessage.class); - when(message.getMessageNumber()).thenReturn(id); - - MessageReference ref = mock(MessageReference.class); - when(ref.getMessage()).thenReturn(message); - - AMQMessageHeader hdr = mock(AMQMessageHeader.class); - when(message.getMessageHeader()).thenReturn(hdr); - - when(message.newReference()).thenReturn(ref); - - return message; - } - - class TestSimpleQueueEntryListFactory implements QueueEntryListFactory - { - QueueEntryList _list; - - public QueueEntryList createQueueEntryList(AMQQueue queue) - { - _list = new SimpleQueueEntryList(queue); - return _list; - } - - public QueueEntryList getQueueEntryList() - { - return _list; - } - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueThreadPoolTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueThreadPoolTest.java deleted file mode 100644 index c115af5a38..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueThreadPoolTest.java +++ /dev/null @@ -1,69 +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.pool.ReferenceCountingExecutorService; -import org.apache.qpid.server.model.UUIDGenerator; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.test.utils.QpidTestCase; - -public class SimpleAMQQueueThreadPoolTest extends QpidTestCase -{ - - @Override - public void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - } - - @Override - public void tearDown() throws Exception - { - BrokerTestHelper.tearDown(); - super.tearDown(); - } - - public void test() throws Exception - { - int initialCount = ReferenceCountingExecutorService.getInstance().getReferenceCount(); - VirtualHost test = BrokerTestHelper.createVirtualHost("test"); - - try - { - SimpleAMQQueue queue = (SimpleAMQQueue) - test.createQueue(UUIDGenerator.generateRandomUUID(), "test", false, "owner", false, false, false, null); - - assertFalse("Creation did not start Pool.", ReferenceCountingExecutorService.getInstance().getPool().isShutdown()); - - assertEquals("References not increased", initialCount + 1, ReferenceCountingExecutorService.getInstance().getReferenceCount()); - - queue.stop(); - - assertEquals("References not decreased", initialCount , ReferenceCountingExecutorService.getInstance().getReferenceCount()); - } - finally - { - test.close(); - } - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleQueueEntryImplTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleQueueEntryImplTest.java deleted file mode 100644 index c2c2fc4b98..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleQueueEntryImplTest.java +++ /dev/null @@ -1,83 +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.server.message.ServerMessage; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class SimpleQueueEntryImplTest extends QueueEntryImplTestBase { - - private SimpleQueueEntryList queueEntryList = new SimpleQueueEntryList(new MockAMQQueue("test")); - - public QueueEntryImpl getQueueEntryImpl(int msgId) throws AMQException { - ServerMessage message = mock(ServerMessage.class); - when(message.getMessageNumber()).thenReturn((long)msgId); - return queueEntryList.add(message); - } - - public void testCompareTo() - { - assertTrue(_queueEntry.compareTo(_queueEntry2) < 0); - assertTrue(_queueEntry2.compareTo(_queueEntry3) < 0); - assertTrue(_queueEntry.compareTo(_queueEntry3) < 0); - - assertTrue(_queueEntry2.compareTo(_queueEntry) > 0); - assertTrue(_queueEntry3.compareTo(_queueEntry2) > 0); - assertTrue(_queueEntry3.compareTo(_queueEntry) > 0); - - assertTrue(_queueEntry.compareTo(_queueEntry) == 0); - assertTrue(_queueEntry2.compareTo(_queueEntry2) == 0); - assertTrue(_queueEntry3.compareTo(_queueEntry3) == 0); - } - - public void testTraverseWithNoDeletedEntries() - { - QueueEntry current = _queueEntry; - - current = current.getNextValidEntry(); - assertSame("Unexpected current entry",_queueEntry2, current); - - current = current.getNextValidEntry(); - assertSame("Unexpected current entry",_queueEntry3, current); - - current = current.getNextValidEntry(); - assertNull(current); - - } - - public void testTraverseWithDeletedEntries() - { - // Delete 2nd queue entry - _queueEntry2.delete(); - assertTrue(_queueEntry2.isDeleted()); - - QueueEntry current = _queueEntry; - - current = current.getNextValidEntry(); - assertSame("Unexpected current entry",_queueEntry3, current); - - current = current.getNextValidEntry(); - assertNull(current); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleQueueEntryListTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleQueueEntryListTest.java deleted file mode 100644 index 63b3a7d165..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleQueueEntryListTest.java +++ /dev/null @@ -1,247 +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.server.message.MessageReference; -import org.apache.qpid.server.message.ServerMessage; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class SimpleQueueEntryListTest extends QueueEntryListTestBase -{ - private SimpleQueueEntryList _sqel; - - private static final String SCAVENGE_PROP = "qpid.queue.scavenge_count"; - private String oldScavengeValue = null; - - @Override - protected void setUp() - { - oldScavengeValue = System.setProperty(SCAVENGE_PROP, "9"); - _sqel = new SimpleQueueEntryList(_testQueue); - for(int i = 1; i <= 100; i++) - { - final ServerMessage message = mock(ServerMessage.class); - when(message.getMessageNumber()).thenReturn((long) i); - MessageReference ref = mock(MessageReference.class); - when(ref.getMessage()).thenReturn(message); - when(message.newReference()).thenReturn(ref); - - final QueueEntry bleh = _sqel.add(message); - assertNotNull("QE should not have been null", bleh); - } - } - - @Override - protected void tearDown() - { - if(oldScavengeValue != null) - { - System.setProperty(SCAVENGE_PROP, oldScavengeValue); - } - else - { - System.clearProperty(SCAVENGE_PROP); - } - } - - @Override - public QueueEntryList getTestList() - { - return getTestList(false); - } - - @Override - public QueueEntryList getTestList(boolean newList) - { - if(newList) - { - return new SimpleQueueEntryList(_testQueue); - } - else - { - return _sqel; - } - } - - @Override - public long getExpectedFirstMsgId() - { - return 1; - } - - @Override - public int getExpectedListLength() - { - return 100; - } - - @Override - public ServerMessage getTestMessageToAdd() throws AMQException - { - ServerMessage msg = mock(ServerMessage.class); - when(msg.getMessageNumber()).thenReturn(1l); - return msg; - } - - public void testScavenge() throws Exception - { - SimpleQueueEntryList sqel = new SimpleQueueEntryList(null); - ConcurrentHashMap<Integer,QueueEntry> entriesMap = new ConcurrentHashMap<Integer,QueueEntry>(); - - - //Add messages to generate QueueEntry's - for(int i = 1; i <= 100 ; i++) - { - ServerMessage message = mock(ServerMessage.class); - when(message.getMessageNumber()).thenReturn((long) i); - MessageReference ref = mock(MessageReference.class); - when(ref.getMessage()).thenReturn(message); - when(message.newReference()).thenReturn(ref); - QueueEntry bleh = sqel.add(message); - assertNotNull("QE should not have been null", bleh); - entriesMap.put(i,bleh); - } - - SimpleQueueEntryImpl head = sqel.getHead(); - - //We shall now delete some specific messages mid-queue that will lead to - //requiring a scavenge once the requested threshold of 9 deletes is passed - - //Delete the 2nd message only - assertTrue("Failed to delete QueueEntry", entriesMap.remove(2).delete()); - verifyDeletedButPresentBeforeScavenge(head, 2); - - //Delete messages 12 to 14 - assertTrue("Failed to delete QueueEntry", entriesMap.remove(12).delete()); - verifyDeletedButPresentBeforeScavenge(head, 12); - assertTrue("Failed to delete QueueEntry", entriesMap.remove(13).delete()); - verifyDeletedButPresentBeforeScavenge(head, 13); - assertTrue("Failed to delete QueueEntry", entriesMap.remove(14).delete()); - verifyDeletedButPresentBeforeScavenge(head, 14); - - //Delete message 20 only - assertTrue("Failed to delete QueueEntry", entriesMap.remove(20).delete()); - verifyDeletedButPresentBeforeScavenge(head, 20); - - //Delete messages 81 to 84 - assertTrue("Failed to delete QueueEntry", entriesMap.remove(81).delete()); - verifyDeletedButPresentBeforeScavenge(head, 81); - assertTrue("Failed to delete QueueEntry", entriesMap.remove(82).delete()); - verifyDeletedButPresentBeforeScavenge(head, 82); - assertTrue("Failed to delete QueueEntry", entriesMap.remove(83).delete()); - verifyDeletedButPresentBeforeScavenge(head, 83); - assertTrue("Failed to delete QueueEntry", entriesMap.remove(84).delete()); - verifyDeletedButPresentBeforeScavenge(head, 84); - - //Delete message 99 - this is the 10th message deleted that is after the queue head - //and so will invoke the scavenge() which is set to go after 9 previous deletions - assertTrue("Failed to delete QueueEntry", entriesMap.remove(99).delete()); - - verifyAllDeletedMessagedNotPresent(head, entriesMap); - } - - private void verifyDeletedButPresentBeforeScavenge(SimpleQueueEntryImpl head, long messageId) - { - //Use the head to get the initial entry in the queue - SimpleQueueEntryImpl entry = head.getNextNode(); - - for(long i = 1; i < messageId ; i++) - { - assertEquals("Expected QueueEntry was not found in the list", i, (long) entry.getMessage().getMessageNumber()); - entry = entry.getNextNode(); - } - - assertTrue("Entry should have been deleted", entry.isDeleted()); - } - - private void verifyAllDeletedMessagedNotPresent(SimpleQueueEntryImpl head, Map<Integer,QueueEntry> remainingMessages) - { - //Use the head to get the initial entry in the queue - SimpleQueueEntryImpl entry = head.getNextNode(); - - assertNotNull("Initial entry should not have been null", entry); - - int count = 0; - - while (entry != null) - { - assertFalse("Entry " + entry.getMessage().getMessageNumber() + " should not have been deleted", entry.isDeleted()); - assertNotNull("QueueEntry "+entry.getMessage().getMessageNumber()+" was not found in the list of remaining entries " + remainingMessages, - remainingMessages.get((int)(entry.getMessage().getMessageNumber()))); - - count++; - entry = entry.getNextNode(); - } - - assertEquals("Count should have been equal",count,remainingMessages.size()); - } - - public void testGettingNextElement() - { - final int numberOfEntries = 5; - final SimpleQueueEntryImpl[] entries = new SimpleQueueEntryImpl[numberOfEntries]; - final SimpleQueueEntryList queueEntryList = new SimpleQueueEntryList(new MockAMQQueue("test")); - - // create test entries - for(int i = 0; i < numberOfEntries; i++) - { - ServerMessage message = mock(ServerMessage.class); - when(message.getMessageNumber()).thenReturn((long)i); - entries[i] = queueEntryList.add(message); - } - - // test getNext for not acquired entries - for(int i = 0; i < numberOfEntries; i++) - { - final SimpleQueueEntryImpl next = entries[i].getNextValidEntry(); - - if(i < numberOfEntries - 1) - { - assertEquals("Unexpected entry from QueueEntryImpl#getNext()", entries[i + 1], next); - } - else - { - assertNull("The next entry after the last should be null", next); - } - } - - // delete second - entries[1].acquire(); - entries[1].delete(); - - // dequeue third - entries[2].acquire(); - entries[2].dequeue(); - - SimpleQueueEntryImpl next = entries[2].getNextValidEntry(); - assertEquals("expected forth entry", entries[3], next); - next = next.getNextValidEntry(); - assertEquals("expected fifth entry", entries[4], next); - next = next.getNextValidEntry(); - assertNull("The next entry after the last should be null", next); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SortedQueueEntryImplTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SortedQueueEntryImplTest.java deleted file mode 100644 index acd0ccbdeb..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SortedQueueEntryImplTest.java +++ /dev/null @@ -1,93 +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 java.util.Collections; -import org.apache.qpid.AMQException; -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.message.ServerMessage; - -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class SortedQueueEntryImplTest extends QueueEntryImplTestBase { - - public final static String keys[] = { "CCC", "AAA", "BBB" }; - - private SelfValidatingSortedQueueEntryList queueEntryList = new SelfValidatingSortedQueueEntryList(new MockAMQQueue("test"),"KEY"); - - public QueueEntryImpl getQueueEntryImpl(int msgId) throws AMQException { - final ServerMessage message = mock(ServerMessage.class); - AMQMessageHeader hdr = mock(AMQMessageHeader.class); - when(message.getMessageHeader()).thenReturn(hdr); - when(hdr.getHeader(eq("KEY"))).thenReturn(keys[msgId-1]); - when(hdr.containsHeader(eq("KEY"))).thenReturn(true); - when(hdr.getHeaderNames()).thenReturn(Collections.singleton("KEY")); - - return queueEntryList.add(message); - } - - public void testCompareTo() - { - assertTrue(_queueEntry.compareTo(_queueEntry2) > 0); - assertTrue(_queueEntry.compareTo(_queueEntry3) > 0); - - assertTrue(_queueEntry2.compareTo(_queueEntry3) < 0); - assertTrue(_queueEntry2.compareTo(_queueEntry) < 0); - - assertTrue(_queueEntry3.compareTo(_queueEntry2) > 0); - assertTrue(_queueEntry3.compareTo(_queueEntry) < 0); - - assertTrue(_queueEntry.compareTo(_queueEntry) == 0); - assertTrue(_queueEntry2.compareTo(_queueEntry2) == 0); - assertTrue(_queueEntry3.compareTo(_queueEntry3) == 0); - } - - public void testTraverseWithNoDeletedEntries() - { - QueueEntry current = _queueEntry2; - - current = current.getNextValidEntry(); - assertSame("Unexpected current entry",_queueEntry3, current); - - current = current.getNextValidEntry(); - assertSame("Unexpected current entry",_queueEntry, current); - - current = current.getNextValidEntry(); - assertNull(current); - - } - - public void testTraverseWithDeletedEntries() - { - // Delete 2nd queue entry - _queueEntry3.delete(); - assertTrue(_queueEntry3.isDeleted()); - - QueueEntry current = _queueEntry2; - - current = current.getNextValidEntry(); - assertSame("Unexpected current entry",_queueEntry, current); - - current = current.getNextValidEntry(); - assertNull(current); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SortedQueueEntryListTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SortedQueueEntryListTest.java deleted file mode 100644 index 7add2d4d43..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SortedQueueEntryListTest.java +++ /dev/null @@ -1,373 +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 java.util.Collections; -import org.apache.qpid.AMQException; -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.message.MessageReference; -import org.apache.qpid.server.message.ServerMessage; - -import java.util.Arrays; - -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class SortedQueueEntryListTest extends QueueEntryListTestBase -{ - private static SelfValidatingSortedQueueEntryList _sqel; - - public final static String keys[] = { " 73", " 18", " 11", "127", "166", "163", " 69", " 60", "191", "144", - " 17", "161", "145", "140", "157", " 47", "136", " 56", "176", " 81", - "195", " 96", " 2", " 68", "101", "141", "159", "187", "149", " 45", - " 64", "100", " 83", " 51", " 79", " 82", "180", " 26", " 61", " 62", - " 78", " 46", "147", " 91", "120", "164", " 92", "172", "188", " 50", - "111", " 89", " 4", " 8", " 16", "151", "122", "178", " 33", "124", - "171", "165", "116", "113", "155", "148", " 29", " 0", " 37", "131", - "146", " 57", "112", " 97", " 23", "108", "123", "117", "167", " 52", - " 98", " 6", "160", " 25", " 49", " 34", "182", "185", " 30", " 66", - "152", " 58", " 86", "118", "189", " 84", " 36", "104", " 7", " 76", - " 87", " 1", " 80", " 10", "142", " 59", "137", " 12", " 67", " 22", - " 9", "106", " 75", "109", " 93", " 42", "177", "134", " 77", " 88", - "114", " 43", "143", "135", " 55", "181", " 32", "174", "175", "184", - "133", "107", " 28", "126", "103", " 85", " 38", "158", " 39", "162", - "129", "194", " 15", " 24", " 19", " 35", "186", " 31", " 65", " 99", - "192", " 74", "156", " 27", " 95", " 54", " 70", " 13", "110", " 41", - " 90", "173", "125", "196", "130", "183", "102", "190", "132", "105", - " 21", " 53", "139", " 94", "115", " 48", " 44", "179", "128", " 14", - " 72", "119", "153", "168", "197", " 40", "150", "138", " 5", "154", - "169", " 71", "199", "198", "170", " 3", "121", " 20", " 63", "193" }; - - public final static String textkeys[] = { "AAA", "BBB", "CCC", "DDD", "EEE", "FFF", "GGG", "HHH", "III", "JJJ", - "KKK", "LLL", "MMM", "NNN", "OOO", "PPP", "QQQ", "RRR", "SSS", "TTT", - "UUU", "VVV", "XXX", "YYY", "ZZZ"}; - - private final static String keysSorted[] = keys.clone(); - - @Override - protected void setUp() throws Exception - { - super.setUp(); - - // Create result array - Arrays.sort(keysSorted); - - // Create test list - _sqel = new SelfValidatingSortedQueueEntryList(_testQueue, "KEY"); - - // Build test list - long messageId = 0L; - for(final String key : keys) - { - final ServerMessage msg = generateTestMessage(messageId++, key); - _sqel.add(msg); - } - - } - - @Override - public QueueEntryList getTestList() - { - return getTestList(false); - } - - @Override - public QueueEntryList getTestList(boolean newList) - { - if(newList) - { - return new SelfValidatingSortedQueueEntryList(_testQueue, "KEY"); - } - else - { - return _sqel; - } - } - - public int getExpectedListLength() - { - return keys.length; - } - - public long getExpectedFirstMsgId() - { - return 67L; - } - - public ServerMessage getTestMessageToAdd() throws AMQException - { - return generateTestMessage(1, "test value"); - } - - private ServerMessage generateTestMessage(final long id, final String keyValue) throws AMQException - { - final ServerMessage message = mock(ServerMessage.class); - AMQMessageHeader hdr = mock(AMQMessageHeader.class); - when(message.getMessageHeader()).thenReturn(hdr); - when(hdr.getHeader(eq("KEY"))).thenReturn(keyValue); - when(hdr.containsHeader(eq("KEY"))).thenReturn(true); - when(hdr.getHeaderNames()).thenReturn(Collections.singleton("KEY")); - MessageReference ref = mock(MessageReference.class); - when(ref.getMessage()).thenReturn(message); - when(message.newReference()).thenReturn(ref); - when(message.getMessageNumber()).thenReturn(id); - - return message; - } - - public void testIterator() - { - super.testIterator(); - - // Test sorted order of list - final QueueEntryIterator<?> iter = getTestList().iterator(); - int count = 0; - while(iter.advance()) - { - assertEquals("Sorted queue entry value does not match sorted key array", - keysSorted[count++], getSortedKeyValue(iter)); - } - } - - private Object getSortedKeyValue(QueueEntryIterator<?> iter) - { - return (iter.getNode()).getMessage().getMessageHeader().getHeader("KEY"); - } - - private Long getMessageId(QueueEntryIterator<?> iter) - { - return (iter.getNode()).getMessage().getMessageNumber(); - } - - public void testNonUniqueSortKeys() throws Exception - { - _sqel = new SelfValidatingSortedQueueEntryList(_testQueue, "KEY"); - - // Build test list - long messageId = 0L; - while(messageId < 200) - { - final ServerMessage msg = generateTestMessage(messageId++, "samekey"); - _sqel.add(msg); - } - - final QueueEntryIterator<?> iter = getTestList().iterator(); - int count=0; - while(iter.advance()) - { - assertEquals("Sorted queue entry value is not as expected", "samekey", getSortedKeyValue(iter)); - assertEquals("Message id not as expected", Long.valueOf(count++), getMessageId(iter)); - } - } - - public void testNullSortKeys() throws Exception - { - _sqel = new SelfValidatingSortedQueueEntryList(_testQueue, "KEY"); - - // Build test list - long messageId = 0L; - while(messageId < 200) - { - final ServerMessage msg = generateTestMessage(messageId++, null); - _sqel.add(msg); - } - - final QueueEntryIterator<?> iter = getTestList().iterator(); - int count=0; - while(iter.advance()) - { - assertNull("Sorted queue entry value is not as expected", getSortedKeyValue(iter)); - assertEquals("Message id not as expected", Long.valueOf(count++), getMessageId(iter)); } - } - - public void testAscendingSortKeys() throws Exception - { - _sqel = new SelfValidatingSortedQueueEntryList(_testQueue, "KEY"); - - // Build test list - long messageId = 0L; - for(String textKey : textkeys) - { - final ServerMessage msg = generateTestMessage(messageId, textKey); - messageId++; - _sqel.add(msg); - } - - final QueueEntryIterator<?> iter = getTestList().iterator(); - int count=0; - while(iter.advance()) - { - assertEquals("Sorted queue entry value is not as expected", textkeys[count], getSortedKeyValue(iter)); - assertEquals("Message id not as expected", Long.valueOf(count), getMessageId(iter)); - count++; - } - } - - public void testDescendingSortKeys() throws Exception - { - _sqel = new SelfValidatingSortedQueueEntryList(_testQueue, "KEY"); - - // Build test list - long messageId = 0L; - for(int i=textkeys.length-1; i >=0; i--) - { - final ServerMessage msg = generateTestMessage(messageId, textkeys[i]); - messageId++; - _sqel.add(msg); - } - - final QueueEntryIterator<?> iter = getTestList().iterator(); - int count=0; - while(iter.advance()) - { - assertEquals("Sorted queue entry value is not as expected", textkeys[count], getSortedKeyValue(iter)); - assertEquals("Message id not as expected", Long.valueOf(textkeys.length-count-1), getMessageId(iter)); - count++; - } - } - - public void testInsertAfter() throws Exception - { - _sqel = new SelfValidatingSortedQueueEntryList(_testQueue, "KEY"); - - ServerMessage msg = generateTestMessage(1, "A"); - _sqel.add(msg); - - SortedQueueEntryImpl entry = _sqel.next(_sqel.getHead()); - validateEntry(entry, "A", 1); - - msg = generateTestMessage(2, "B"); - _sqel.add(msg); - - entry = _sqel.next(_sqel.getHead()); - validateEntry(entry, "A", 1); - - entry = _sqel.next(entry); - validateEntry(entry, "B", 2); - } - - public void testInsertBefore() throws Exception - { - _sqel = new SelfValidatingSortedQueueEntryList(_testQueue, "KEY"); - - ServerMessage msg = generateTestMessage(1, "B"); - _sqel.add(msg); - - SortedQueueEntryImpl entry = _sqel.next(_sqel.getHead()); - validateEntry(entry, "B", 1); - - msg = generateTestMessage(2, "A"); - _sqel.add(msg); - - entry = _sqel.next(_sqel.getHead()); - validateEntry(entry, "A", 2); - - entry = _sqel.next(entry); - validateEntry(entry, "B", 1); - } - - public void testInsertInbetween() throws Exception - { - _sqel = new SelfValidatingSortedQueueEntryList(_testQueue, "KEY"); - - ServerMessage msg = generateTestMessage(1, "A"); - _sqel.add(msg); - SortedQueueEntryImpl entry = _sqel.next(_sqel.getHead()); - validateEntry(entry, "A", 1); - - msg = generateTestMessage(2, "C"); - _sqel.add(msg); - - entry = _sqel.next(_sqel.getHead()); - validateEntry(entry, "A", 1); - - entry = _sqel.next(entry); - validateEntry(entry, "C", 2); - - msg = generateTestMessage(3, "B"); - _sqel.add(msg); - - entry = _sqel.next(_sqel.getHead()); - validateEntry(entry, "A", 1); - - entry = _sqel.next(entry); - validateEntry(entry, "B", 3); - - entry = _sqel.next(entry); - validateEntry(entry, "C", 2); - } - - public void testInsertAtHead() throws Exception - { - _sqel = new SelfValidatingSortedQueueEntryList(_testQueue, "KEY"); - - ServerMessage msg = generateTestMessage(1, "B"); - _sqel.add(msg); - - SortedQueueEntryImpl entry = _sqel.next(_sqel.getHead()); - validateEntry(entry, "B", 1); - - msg = generateTestMessage(2, "D"); - _sqel.add(msg); - - entry = _sqel.next(_sqel.getHead()); - validateEntry(entry, "B", 1); - - entry = _sqel.next(entry); - validateEntry(entry, "D", 2); - - msg = generateTestMessage(3, "C"); - _sqel.add(msg); - - entry = _sqel.next(_sqel.getHead()); - validateEntry(entry, "B", 1); - - entry = _sqel.next(entry); - validateEntry(entry, "C", 3); - - entry = _sqel.next(entry); - validateEntry(entry, "D", 2); - - msg = generateTestMessage(4, "A"); - _sqel.add(msg); - - entry = _sqel.next(_sqel.getHead()); - validateEntry(entry, "A", 4); - - entry = _sqel.next(entry); - validateEntry(entry, "B", 1); - - entry = _sqel.next(entry); - validateEntry(entry, "C", 3); - - entry = _sqel.next(entry); - validateEntry(entry, "D", 2); - } - - private void validateEntry(final SortedQueueEntryImpl entry, final String expectedSortKey, final long expectedMessageId) - { - assertEquals("Sorted queue entry value is not as expected", - expectedSortKey, entry.getMessage().getMessageHeader().getHeader("KEY")); - assertEquals("Sorted queue entry id is not as expected", - expectedMessageId, entry.getMessage().getMessageNumber()); - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/SubjectCreatorTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/SubjectCreatorTest.java deleted file mode 100644 index 9edd345360..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/SubjectCreatorTest.java +++ /dev/null @@ -1,169 +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.security; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.security.Principal; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - -import javax.security.auth.Subject; -import javax.security.sasl.SaslServer; - -import junit.framework.TestCase; - -import org.apache.qpid.server.model.GroupProvider; -import org.apache.qpid.server.security.auth.AuthenticatedPrincipal; -import org.apache.qpid.server.security.auth.AuthenticationResult; -import org.apache.qpid.server.security.auth.AuthenticationResult.AuthenticationStatus; -import org.apache.qpid.server.security.auth.SubjectAuthenticationResult; -import org.apache.qpid.server.security.auth.manager.AuthenticationManager; - -public class SubjectCreatorTest extends TestCase -{ - private static final String USERNAME = "username"; - private static final String PASSWORD = "password"; - - private AuthenticationManager _authenticationManager = mock(AuthenticationManager.class); - - private GroupProvider _groupManager1 = mock(GroupProvider.class); - private GroupProvider _groupManager2 = mock(GroupProvider.class); - - private Principal _userPrincipal = mock(Principal.class); - private Principal _group1 = mock(Principal.class); - private Principal _group2 = mock(Principal.class); - - private SubjectCreator _subjectCreator; - private AuthenticationResult _authenticationResult; - private SaslServer _testSaslServer = mock(SaslServer.class); - private byte[] _saslResponseBytes = PASSWORD.getBytes(); - - @Override - public void setUp() - { - when(_groupManager1.getGroupPrincipalsForUser(USERNAME)).thenReturn(Collections.singleton(_group1)); - when(_groupManager2.getGroupPrincipalsForUser(USERNAME)).thenReturn(Collections.singleton(_group2)); - - _subjectCreator = new SubjectCreator(_authenticationManager, new HashSet<GroupProvider>(Arrays.asList(_groupManager1, _groupManager2))); - _authenticationResult = new AuthenticationResult(_userPrincipal); - when(_authenticationManager.authenticate(USERNAME, PASSWORD)).thenReturn(_authenticationResult); - } - - public void testAuthenticateUsernameAndPasswordReturnsSubjectWithUserAndGroupPrincipals() - { - final SubjectAuthenticationResult actualResult = _subjectCreator.authenticate(USERNAME, PASSWORD); - - assertEquals(AuthenticationStatus.SUCCESS, actualResult.getStatus()); - - final Subject actualSubject = actualResult.getSubject(); - - assertEquals("Should contain one user principal and two groups ", 3, actualSubject.getPrincipals().size()); - - assertTrue(actualSubject.getPrincipals().contains(new AuthenticatedPrincipal(_userPrincipal))); - assertTrue(actualSubject.getPrincipals().contains(_group1)); - assertTrue(actualSubject.getPrincipals().contains(_group2)); - - assertTrue(actualSubject.isReadOnly()); - } - - public void testSaslAuthenticationSuccessReturnsSubjectWithUserAndGroupPrincipals() throws Exception - { - when(_authenticationManager.authenticate(_testSaslServer, _saslResponseBytes)).thenReturn(_authenticationResult); - when(_testSaslServer.isComplete()).thenReturn(true); - when(_testSaslServer.getAuthorizationID()).thenReturn(USERNAME); - - SubjectAuthenticationResult result = _subjectCreator.authenticate(_testSaslServer, _saslResponseBytes); - - final Subject actualSubject = result.getSubject(); - assertEquals("Should contain one user principal and two groups ", 3, actualSubject.getPrincipals().size()); - - assertTrue(actualSubject.getPrincipals().contains(new AuthenticatedPrincipal(_userPrincipal))); - assertTrue(actualSubject.getPrincipals().contains(_group1)); - assertTrue(actualSubject.getPrincipals().contains(_group2)); - - assertTrue(actualSubject.isReadOnly()); - } - - public void testAuthenticateUnsuccessfulWithUsernameReturnsNullSubjectAndCorrectStatus() - { - testUnsuccessfulAuthentication(AuthenticationResult.AuthenticationStatus.CONTINUE); - testUnsuccessfulAuthentication(AuthenticationResult.AuthenticationStatus.ERROR); - } - - private void testUnsuccessfulAuthentication(AuthenticationStatus expectedStatus) - { - AuthenticationResult failedAuthenticationResult = new AuthenticationResult(expectedStatus); - - when(_authenticationManager.authenticate(USERNAME, PASSWORD)).thenReturn(failedAuthenticationResult); - - SubjectAuthenticationResult subjectAuthenticationResult = _subjectCreator.authenticate(USERNAME, PASSWORD); - - assertSame(expectedStatus, subjectAuthenticationResult.getStatus()); - assertNull(subjectAuthenticationResult.getSubject()); - } - - public void testAuthenticateUnsuccessfulWithSaslServerReturnsNullSubjectAndCorrectStatus() - { - testUnsuccessfulAuthenticationWithSaslServer(AuthenticationResult.AuthenticationStatus.CONTINUE); - testUnsuccessfulAuthenticationWithSaslServer(AuthenticationResult.AuthenticationStatus.ERROR); - } - - private void testUnsuccessfulAuthenticationWithSaslServer(AuthenticationStatus expectedStatus) - { - AuthenticationResult failedAuthenticationResult = new AuthenticationResult(expectedStatus); - - when(_authenticationManager.authenticate(_testSaslServer, _saslResponseBytes)).thenReturn(failedAuthenticationResult); - when(_testSaslServer.isComplete()).thenReturn(false); - - SubjectAuthenticationResult subjectAuthenticationResult = _subjectCreator.authenticate(_testSaslServer, _saslResponseBytes); - - assertSame(expectedStatus, subjectAuthenticationResult.getStatus()); - assertNull(subjectAuthenticationResult.getSubject()); - } - - public void testGetGroupPrincipals() - { - getAndAssertGroupPrincipals(_group1, _group2); - } - - public void testGetGroupPrincipalsWhenAGroupManagerReturnsNull() - { - when(_groupManager1.getGroupPrincipalsForUser(USERNAME)).thenReturn(null); - - getAndAssertGroupPrincipals(_group2); - } - - public void testGetGroupPrincipalsWhenAGroupManagerReturnsEmptySet() - { - when(_groupManager2.getGroupPrincipalsForUser(USERNAME)).thenReturn(new HashSet<Principal>()); - - getAndAssertGroupPrincipals(_group1); - } - - private void getAndAssertGroupPrincipals(Principal... expectedGroups) - { - Set<Principal> actualGroupPrincipals = _subjectCreator.getGroupPrincipals(USERNAME); - Set<Principal> expectedGroupPrincipals = new HashSet<Principal>(Arrays.asList(expectedGroups)); - assertEquals(expectedGroupPrincipals, actualGroupPrincipals); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/AuthenticatedPrincipalTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/AuthenticatedPrincipalTest.java deleted file mode 100644 index cd5791952f..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/AuthenticatedPrincipalTest.java +++ /dev/null @@ -1,147 +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.security.auth; - -import java.security.Principal; - -import javax.security.auth.Subject; - -import org.apache.qpid.server.security.auth.UsernamePrincipal; - -import junit.framework.TestCase; - -public class AuthenticatedPrincipalTest extends TestCase -{ - - private AuthenticatedPrincipal _authenticatedPrincipal = new AuthenticatedPrincipal(new UsernamePrincipal("name")); - - public void testGetAuthenticatedPrincipalFromSubject() - { - final Subject subject = createSubjectContainingAuthenticatedPrincipal(); - final AuthenticatedPrincipal actual = AuthenticatedPrincipal.getAuthenticatedPrincipalFromSubject(subject); - assertSame(_authenticatedPrincipal, actual); - } - - public void testAuthenticatedPrincipalNotInSubject() - { - try - { - AuthenticatedPrincipal.getAuthenticatedPrincipalFromSubject(new Subject()); - fail("Exception not thrown"); - } - catch (IllegalArgumentException iae) - { - // PASS - } - } - - public void testGetOptionalAuthenticatedPrincipalFromSubject() - { - final Subject subject = createSubjectContainingAuthenticatedPrincipal(); - final AuthenticatedPrincipal actual = AuthenticatedPrincipal.getOptionalAuthenticatedPrincipalFromSubject(subject); - assertSame(_authenticatedPrincipal, actual); - } - - public void testGetOptionalAuthenticatedPrincipalFromSubjectReturnsNullIfMissing() - { - Subject subjectWithNoPrincipals = new Subject(); - assertNull(AuthenticatedPrincipal.getOptionalAuthenticatedPrincipalFromSubject(subjectWithNoPrincipals)); - - Subject subjectWithoutAuthenticatedPrincipal = new Subject(); - subjectWithoutAuthenticatedPrincipal.getPrincipals().add(new UsernamePrincipal("name1")); - assertNull("Should return null for a subject containing a principal that isn't an AuthenticatedPrincipal", - AuthenticatedPrincipal.getOptionalAuthenticatedPrincipalFromSubject(subjectWithoutAuthenticatedPrincipal)); - } - - public void testTooManyAuthenticatedPrincipalsInSubject() - { - final Subject subject = new Subject(); - subject.getPrincipals().add(new AuthenticatedPrincipal(new UsernamePrincipal("name1"))); - subject.getPrincipals().add(new AuthenticatedPrincipal(new UsernamePrincipal("name2"))); - - try - { - AuthenticatedPrincipal.getAuthenticatedPrincipalFromSubject(subject); - fail("Exception not thrown"); - } - catch (IllegalArgumentException iae) - { - // PASS - } - } - - private Subject createSubjectContainingAuthenticatedPrincipal() - { - final Principal other = new Principal() - { - public String getName() - { - return "otherprincipal"; - } - }; - - final Subject subject = new Subject(); - subject.getPrincipals().add(_authenticatedPrincipal); - subject.getPrincipals().add(other); - return subject; - } - - public void testEqualsAndHashcode() - { - AuthenticatedPrincipal user1principal1 = new AuthenticatedPrincipal(new UsernamePrincipal("user1")); - AuthenticatedPrincipal user1principal2 = new AuthenticatedPrincipal(new UsernamePrincipal("user1")); - - assertTrue(user1principal1.equals(user1principal1)); - assertTrue(user1principal1.equals(user1principal2)); - assertTrue(user1principal2.equals(user1principal1)); - - assertEquals(user1principal1.hashCode(), user1principal2.hashCode()); - } - - public void testEqualsAndHashcodeWithSameWrappedObject() - { - UsernamePrincipal wrappedPrincipal = new UsernamePrincipal("user1"); - AuthenticatedPrincipal user1principal1 = new AuthenticatedPrincipal(wrappedPrincipal); - AuthenticatedPrincipal user1principal2 = new AuthenticatedPrincipal(wrappedPrincipal); - - assertTrue(user1principal1.equals(user1principal1)); - assertTrue(user1principal1.equals(user1principal2)); - assertTrue(user1principal2.equals(user1principal1)); - - assertEquals(user1principal1.hashCode(), user1principal2.hashCode()); - } - - public void testEqualsWithDifferentUsernames() - { - AuthenticatedPrincipal user1principal1 = new AuthenticatedPrincipal(new UsernamePrincipal("user1")); - AuthenticatedPrincipal user1principal2 = new AuthenticatedPrincipal(new UsernamePrincipal("user2")); - - assertFalse(user1principal1.equals(user1principal2)); - assertFalse(user1principal2.equals(user1principal1)); - } - - public void testEqualsWithDisimilarObjects() - { - UsernamePrincipal wrappedPrincipal = new UsernamePrincipal("user1"); - AuthenticatedPrincipal authenticatedPrincipal = new AuthenticatedPrincipal(wrappedPrincipal); - - assertFalse(authenticatedPrincipal.equals(wrappedPrincipal)); - assertFalse(wrappedPrincipal.equals(authenticatedPrincipal)); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/AuthenticatedPrincipalTestHelper.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/AuthenticatedPrincipalTestHelper.java deleted file mode 100644 index e9d8d16fce..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/AuthenticatedPrincipalTestHelper.java +++ /dev/null @@ -1,54 +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.security.auth; - -import java.security.Principal; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - -import junit.framework.Assert; - -/** - * Helper class for testing that sets of principals contain {@link AuthenticatedPrincipal}'s that wrap - * expected {@link Principal}'s. - */ -public class AuthenticatedPrincipalTestHelper -{ - public static void assertOnlyContainsWrapped(Principal wrappedPrincipal, Set<Principal> principals) - { - assertOnlyContainsWrappedAndSecondaryPrincipals(wrappedPrincipal, Collections.<Principal>emptySet(), principals); - } - - - public static void assertOnlyContainsWrappedAndSecondaryPrincipals( - Principal expectedWrappedPrincipal, - Set<Principal> expectedSecondaryPrincipals, - Set<Principal> actualPrincipals) - { - Assert.assertEquals("Principal set should contain one principal " + "but the principal set is: " + actualPrincipals, - 1 + expectedSecondaryPrincipals.size(), - actualPrincipals.size()); - - Set<Principal> expectedSet = new HashSet<Principal>(expectedSecondaryPrincipals); - expectedSet.add(new AuthenticatedPrincipal(expectedWrappedPrincipal)); - - Assert.assertEquals(expectedSet, actualPrincipals); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/AuthenticationResultTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/AuthenticationResultTest.java deleted file mode 100644 index a023cbdbb2..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/AuthenticationResultTest.java +++ /dev/null @@ -1,112 +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.security.auth; - -import static org.apache.qpid.server.security.auth.AuthenticatedPrincipalTestHelper.assertOnlyContainsWrapped; -import static org.apache.qpid.server.security.auth.AuthenticatedPrincipalTestHelper.assertOnlyContainsWrappedAndSecondaryPrincipals; -import static org.mockito.Mockito.mock; - -import java.security.Principal; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - -import junit.framework.TestCase; - -public class AuthenticationResultTest extends TestCase -{ - public void testConstructWithAuthenticationStatusContinue() - { - AuthenticationResult authenticationResult = new AuthenticationResult(AuthenticationResult.AuthenticationStatus.CONTINUE); - assertSame(AuthenticationResult.AuthenticationStatus.CONTINUE, authenticationResult.getStatus()); - assertTrue(authenticationResult.getPrincipals().isEmpty()); - } - - public void testConstructWithAuthenticationStatusError() - { - AuthenticationResult authenticationResult = new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR); - assertSame(AuthenticationResult.AuthenticationStatus.ERROR, authenticationResult.getStatus()); - assertTrue(authenticationResult.getPrincipals().isEmpty()); - } - - public void testConstructWithAuthenticationStatusSuccessThrowsException() - { - try - { - new AuthenticationResult(AuthenticationResult.AuthenticationStatus.SUCCESS); - fail("Exception not thrown"); - } - catch(IllegalArgumentException e) - { - // PASS - } - } - - public void testConstructWithPrincipal() - { - Principal mainPrincipal = mock(Principal.class); - AuthenticationResult authenticationResult = new AuthenticationResult(mainPrincipal); - - assertOnlyContainsWrapped(mainPrincipal, authenticationResult.getPrincipals()); - assertSame(AuthenticationResult.AuthenticationStatus.SUCCESS, authenticationResult.getStatus()); - } - - public void testConstructWithNullPrincipalThrowsException() - { - try - { - new AuthenticationResult((Principal)null); - fail("Exception not thrown"); - } - catch(IllegalArgumentException e) - { - // pass - } - } - - public void testConstructWithSetOfPrincipals() - { - Principal mainPrincipal = mock(Principal.class); - Principal secondaryPrincipal = mock(Principal.class); - Set<Principal> secondaryPrincipals = Collections.singleton(secondaryPrincipal); - - AuthenticationResult authenticationResult = new AuthenticationResult(mainPrincipal, secondaryPrincipals); - - assertOnlyContainsWrappedAndSecondaryPrincipals(mainPrincipal, secondaryPrincipals, authenticationResult.getPrincipals()); - assertSame(AuthenticationResult.AuthenticationStatus.SUCCESS, authenticationResult.getStatus()); - } - - public void testConstructWithSetOfPrincipalsDeDuplicatesMainPrincipal() - { - Principal mainPrincipal = mock(Principal.class); - Principal secondaryPrincipal = mock(Principal.class); - - Set<Principal> secondaryPrincipalsContainingDuplicateOfMainPrincipal = new HashSet<Principal>( - Arrays.asList(secondaryPrincipal, mainPrincipal)); - Set<Principal> deDuplicatedSecondaryPrincipals = Collections.singleton(secondaryPrincipal); - - AuthenticationResult authenticationResult = new AuthenticationResult( - mainPrincipal, secondaryPrincipalsContainingDuplicateOfMainPrincipal); - - assertOnlyContainsWrappedAndSecondaryPrincipals(mainPrincipal, deDuplicatedSecondaryPrincipals, authenticationResult.getPrincipals()); - - assertSame(AuthenticationResult.AuthenticationStatus.SUCCESS, authenticationResult.getStatus()); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/TestPrincipalUtils.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/TestPrincipalUtils.java deleted file mode 100644 index ea6b40e3de..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/TestPrincipalUtils.java +++ /dev/null @@ -1,49 +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.security.auth; - -import javax.security.auth.Subject; - -import org.apache.qpid.server.security.group.GroupPrincipal; - -import java.security.Principal; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - -public class TestPrincipalUtils -{ - /** - * Creates a test subject, with exactly one {@link AuthenticatedPrincipal} and zero or more GroupPrincipals. - */ - public static Subject createTestSubject(final String username, final String... groups) - { - final Set<Principal> principals = new HashSet<Principal>(1 + groups.length); - principals.add(new AuthenticatedPrincipal(username)); - for (String group : groups) - { - principals.add(new GroupPrincipal(group)); - } - - return new Subject(true, principals, Collections.EMPTY_SET, Collections.EMPTY_SET); - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/UsernamePrincipalTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/UsernamePrincipalTest.java deleted file mode 100644 index 5e025d3ca8..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/UsernamePrincipalTest.java +++ /dev/null @@ -1,70 +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.security.auth; - -import junit.framework.TestCase; - -/** - * Tests the UsernamePrincipal. - * - */ -public class UsernamePrincipalTest extends TestCase -{ - public void testEqualitySameObject() - { - final UsernamePrincipal principal = new UsernamePrincipal("string"); - assertTrue(principal.equals(principal)); - } - - public void testEqualitySameName() - { - final String string = "string"; - final UsernamePrincipal principal1 = new UsernamePrincipal(string); - final UsernamePrincipal principal2 = new UsernamePrincipal(string); - assertTrue(principal1.equals(principal2)); - } - - public void testEqualityEqualName() - { - final UsernamePrincipal principal1 = new UsernamePrincipal(new String("string")); - final UsernamePrincipal principal2 = new UsernamePrincipal(new String("string")); - assertTrue(principal1.equals(principal2)); - } - - public void testInequalityDifferentUserPrincipals() - { - UsernamePrincipal principal1 = new UsernamePrincipal("string1"); - UsernamePrincipal principal2 = new UsernamePrincipal("string2"); - assertFalse(principal1.equals(principal2)); - } - - public void testInequalityNonUserPrincipal() - { - UsernamePrincipal principal = new UsernamePrincipal("string"); - assertFalse(principal.equals(new String("string"))); - } - - public void testInequalityNull() - { - UsernamePrincipal principal = new UsernamePrincipal("string"); - assertFalse(principal.equals(null)); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabaseTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabaseTest.java deleted file mode 100644 index 4102a1fc68..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabaseTest.java +++ /dev/null @@ -1,465 +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.security.auth.database; - -import junit.framework.TestCase; -import org.apache.commons.codec.binary.Base64; - -import org.apache.qpid.server.security.auth.UsernamePrincipal; - -import javax.security.auth.callback.PasswordCallback; -import javax.security.auth.login.AccountNotFoundException; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.security.Principal; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.regex.Pattern; - -public class Base64MD5PasswordFilePrincipalDatabaseTest extends TestCase -{ - - private static final String TEST_COMMENT = "# Test Comment"; - - private static final String USERNAME = "testUser"; - private static final String PASSWORD = "guest"; - private static final String PASSWORD_B64MD5HASHED = "CE4DQ6BIb/BVMN9scFyLtA=="; - private static char[] PASSWORD_MD5_CHARS; - private static final String PRINCIPAL_USERNAME = "testUserPrincipal"; - private static final Principal PRINCIPAL = new UsernamePrincipal(PRINCIPAL_USERNAME); - private Base64MD5PasswordFilePrincipalDatabase _database; - private File _pwdFile; - private List<File> _testPwdFiles = new ArrayList<File>(); - - static - { - try - { - Base64 b64 = new Base64(); - byte[] md5passBytes = PASSWORD_B64MD5HASHED.getBytes(Base64MD5PasswordFilePrincipalDatabase.DEFAULT_ENCODING); - byte[] decoded = b64.decode(md5passBytes); - - PASSWORD_MD5_CHARS = new char[decoded.length]; - - int index = 0; - for (byte c : decoded) - { - PASSWORD_MD5_CHARS[index++] = (char) c; - } - } - catch (UnsupportedEncodingException e) - { - fail("Unable to perform B64 decode to get the md5 char[] password"); - } - } - - - public void setUp() throws Exception - { - _database = new Base64MD5PasswordFilePrincipalDatabase(); - _pwdFile = File.createTempFile(this.getClass().getName(), "pwd"); - _pwdFile.deleteOnExit(); - _database.open(_pwdFile); - _testPwdFiles.clear(); - } - - public void tearDown() throws Exception - { - //clean up the created default password file and any backup - File oldPwdFile = new File(_pwdFile.getAbsolutePath() + ".old"); - if(oldPwdFile.exists()) - { - oldPwdFile.delete(); - } - - _pwdFile.delete(); - - //clean up any additional files and their backups - for(File f : _testPwdFiles) - { - oldPwdFile = new File(f.getAbsolutePath() + ".old"); - if(oldPwdFile.exists()) - { - oldPwdFile.delete(); - } - - f.delete(); - } - } - - private File createPasswordFile(int commentLines, int users) - { - try - { - File testFile = File.createTempFile("Base64MD5PDPDTest","tmp"); - testFile.deleteOnExit(); - - BufferedWriter writer = new BufferedWriter(new FileWriter(testFile)); - - for (int i = 0; i < commentLines; i++) - { - writer.write(TEST_COMMENT); - writer.newLine(); - } - - for (int i = 0; i < users; i++) - { - writer.write(USERNAME + i + ":Password"); - writer.newLine(); - } - - writer.flush(); - writer.close(); - - _testPwdFiles.add(testFile); - - return testFile; - - } - catch (IOException e) - { - fail("Unable to create test password file." + e.getMessage()); - } - - return null; - } - - private void loadPasswordFile(File file) - { - try - { - _database.open(file); - } - catch (IOException e) - { - fail("Password File was not created." + e.getMessage()); - } - } - - /** **** Test Methods ************** */ - - public void testCreatePrincipal() - { - File testFile = createPasswordFile(1, 0); - - loadPasswordFile(testFile); - - - Principal principal = new Principal() - { - public String getName() - { - return USERNAME; - } - }; - - assertTrue("New user not created.", _database.createPrincipal(principal, PASSWORD.toCharArray())); - - PasswordCallback callback = new PasswordCallback("prompt",false); - try - { - _database.setPassword(principal, callback); - } - catch (AccountNotFoundException e) - { - fail("user account did not exist"); - } - assertTrue("Password returned was incorrect.", Arrays.equals(PASSWORD_MD5_CHARS, callback.getPassword())); - - loadPasswordFile(testFile); - - try - { - _database.setPassword(principal, callback); - } - catch (AccountNotFoundException e) - { - fail("user account did not exist"); - } - assertTrue("Password returned was incorrect.", Arrays.equals(PASSWORD_MD5_CHARS, callback.getPassword())); - - assertNotNull("Created User was not saved", _database.getUser(USERNAME)); - - assertFalse("Duplicate user created.", _database.createPrincipal(principal, PASSWORD.toCharArray())); - } - - public void testCreatePrincipalIsSavedToFile() - { - - File testFile = createPasswordFile(1, 0); - - loadPasswordFile(testFile); - - final String CREATED_PASSWORD = "guest"; - final String CREATED_B64MD5HASHED_PASSWORD = "CE4DQ6BIb/BVMN9scFyLtA=="; - final String CREATED_USERNAME = "createdUser"; - - Principal principal = new Principal() - { - public String getName() - { - return CREATED_USERNAME; - } - }; - - _database.createPrincipal(principal, CREATED_PASSWORD.toCharArray()); - - try - { - BufferedReader reader = new BufferedReader(new FileReader(testFile)); - - assertTrue("File has no content", reader.ready()); - - assertEquals("Comment line has been corrupted.", TEST_COMMENT, reader.readLine()); - - assertTrue("File is missing user data.", reader.ready()); - - String userLine = reader.readLine(); - - String[] result = Pattern.compile(":").split(userLine); - - assertEquals("User line not complete '" + userLine + "'", 2, result.length); - - assertEquals("Username not correct,", CREATED_USERNAME, result[0]); - assertEquals("Password not correct,", CREATED_B64MD5HASHED_PASSWORD, result[1]); - - assertFalse("File has more content", reader.ready()); - - } - catch (IOException e) - { - fail("Unable to valdate file contents due to:" + e.getMessage()); - } - } - - - public void testDeletePrincipal() - { - File testFile = createPasswordFile(1, 1); - - loadPasswordFile(testFile); - - Principal user = _database.getUser(USERNAME + "0"); - assertNotNull("Generated user not present.", user); - - try - { - _database.deletePrincipal(user); - } - catch (AccountNotFoundException e) - { - fail("User should be present" + e.getMessage()); - } - - try - { - _database.deletePrincipal(user); - fail("User should not be present"); - } - catch (AccountNotFoundException e) - { - //pass - } - - loadPasswordFile(testFile); - - try - { - _database.deletePrincipal(user); - fail("User should not be present"); - } - catch (AccountNotFoundException e) - { - //pass - } - - assertNull("Deleted user still present.", _database.getUser(USERNAME + "0")); - } - - public void testGetUsers() - { - int USER_COUNT = 10; - File testFile = createPasswordFile(1, USER_COUNT); - - loadPasswordFile(testFile); - - Principal user = _database.getUser("MISSING_USERNAME"); - assertNull("Missing user present.", user); - - List<Principal> users = _database.getUsers(); - - assertNotNull("Users list is null.", users); - - assertEquals(USER_COUNT, users.size()); - - boolean[] verify = new boolean[USER_COUNT]; - for (int i = 0; i < USER_COUNT; i++) - { - Principal principal = users.get(i); - - assertNotNull("Generated user not present.", principal); - - String name = principal.getName(); - - int id = Integer.parseInt(name.substring(USERNAME.length())); - - assertFalse("Duplicated username retrieve", verify[id]); - verify[id] = true; - } - - for (int i = 0; i < USER_COUNT; i++) - { - assertTrue("User " + i + " missing", verify[i]); - } - } - - public void testUpdatePasswordIsSavedToFile() - { - - File testFile = createPasswordFile(1, 1); - - loadPasswordFile(testFile); - - Principal testUser = _database.getUser(USERNAME + "0"); - - assertNotNull(testUser); - - String NEW_PASSWORD = "guest"; - String NEW_PASSWORD_HASH = "CE4DQ6BIb/BVMN9scFyLtA=="; - try - { - _database.updatePassword(testUser, NEW_PASSWORD.toCharArray()); - } - catch (AccountNotFoundException e) - { - fail(e.toString()); - } - - try - { - BufferedReader reader = new BufferedReader(new FileReader(testFile)); - - assertTrue("File has no content", reader.ready()); - - assertEquals("Comment line has been corrupted.", TEST_COMMENT, reader.readLine()); - - assertTrue("File is missing user data.", reader.ready()); - - String userLine = reader.readLine(); - - String[] result = Pattern.compile(":").split(userLine); - - assertEquals("User line not complete '" + userLine + "'", 2, result.length); - - assertEquals("Username not correct,", USERNAME + "0", result[0]); - assertEquals("New Password not correct,", NEW_PASSWORD_HASH, result[1]); - - assertFalse("File has more content", reader.ready()); - - } - catch (IOException e) - { - fail("Unable to valdate file contents due to:" + e.getMessage()); - } - } - - public void testSetPasswordFileWithMissingFile() - { - try - { - _database.open(new File("DoesntExist")); - } - catch (FileNotFoundException fnfe) - { - assertTrue(fnfe.getMessage(), fnfe.getMessage().startsWith("Cannot find password file")); - } - catch (IOException e) - { - fail("Password File was not created." + e.getMessage()); - } - - } - - public void testSetPasswordFileWithReadOnlyFile() - { - - File testFile = createPasswordFile(0, 0); - - testFile.setReadOnly(); - - try - { - _database.open(testFile); - } - catch (FileNotFoundException fnfe) - { - assertTrue(fnfe.getMessage().startsWith("Cannot read password file ")); - } - catch (IOException e) - { - fail("Password File was not created." + e.getMessage()); - } - } - - public void testCreateUserPrincipal() throws IOException - { - _database.createPrincipal(PRINCIPAL, PASSWORD.toCharArray()); - Principal newPrincipal = _database.getUser(PRINCIPAL_USERNAME); - assertNotNull(newPrincipal); - assertEquals(PRINCIPAL.getName(), newPrincipal.getName()); - } - - public void testVerifyPassword() throws IOException, AccountNotFoundException - { - testCreateUserPrincipal(); - //assertFalse(_pwdDB.verifyPassword(_username, null)); - assertFalse(_database.verifyPassword(PRINCIPAL_USERNAME, new char[]{})); - assertFalse(_database.verifyPassword(PRINCIPAL_USERNAME, (PASSWORD+"z").toCharArray())); - assertTrue(_database.verifyPassword(PRINCIPAL_USERNAME, PASSWORD.toCharArray())); - - try - { - _database.verifyPassword("made.up.username", PASSWORD.toCharArray()); - fail("Should not have been able to verify this non-existant users password."); - } - catch (AccountNotFoundException e) - { - // pass - } - } - - public void testUpdatePassword() throws IOException, AccountNotFoundException - { - testCreateUserPrincipal(); - char[] newPwd = "newpassword".toCharArray(); - _database.updatePassword(PRINCIPAL, newPwd); - assertFalse(_database.verifyPassword(PRINCIPAL_USERNAME, PASSWORD.toCharArray())); - assertTrue(_database.verifyPassword(PRINCIPAL_USERNAME, newPwd)); - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/HashedUserTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/HashedUserTest.java deleted file mode 100644 index abb0b15a76..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/HashedUserTest.java +++ /dev/null @@ -1,83 +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.security.auth.database; - -import junit.framework.TestCase; - -import java.io.UnsupportedEncodingException; - -/* - Note User is mainly tested by Base64MD5PFPDTest this is just to catch the extra methods - */ -public class HashedUserTest extends TestCase -{ - - private String USERNAME = "username"; - private String PASSWORD = "password"; - private String B64_ENCODED_PASSWORD = "cGFzc3dvcmQ="; - - public void testToLongArrayConstructor() - { - try - { - HashedUser user = new HashedUser(new String[]{USERNAME, PASSWORD, USERNAME}); - fail("Error expected"); - } - catch (IllegalArgumentException e) - { - assertEquals("User Data should be length 2, username, password", e.getMessage()); - } - - } - - public void testArrayConstructor() - { - HashedUser user = new HashedUser(new String[]{USERNAME, B64_ENCODED_PASSWORD}); - assertEquals("Username incorrect", USERNAME, user.getName()); - int index = 0; - - char[] hash = B64_ENCODED_PASSWORD.toCharArray(); - - try - { - for (byte c : user.getEncodedPassword()) - { - assertEquals("Password incorrect", hash[index], (char) c); - index++; - } - } - catch (Exception e) - { - fail(e.getMessage()); - } - - hash = PASSWORD.toCharArray(); - - index=0; - for (char c : user.getPassword()) - { - assertEquals("Password incorrect", hash[index], c); - index++; - } - - } -} - diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PlainPasswordFilePrincipalDatabaseTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PlainPasswordFilePrincipalDatabaseTest.java deleted file mode 100644 index eecbcdf38d..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PlainPasswordFilePrincipalDatabaseTest.java +++ /dev/null @@ -1,415 +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.security.auth.database; - -import junit.framework.TestCase; - -import org.apache.qpid.server.security.auth.UsernamePrincipal; - -import javax.security.auth.login.AccountNotFoundException; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.security.Principal; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Pattern; - -public class PlainPasswordFilePrincipalDatabaseTest extends TestCase -{ - - private static final String TEST_COMMENT = "# Test Comment"; - private static final String TEST_PASSWORD = "testPassword"; - private static final char[] TEST_PASSWORD_CHARS = TEST_PASSWORD.toCharArray(); - private static final String TEST_USERNAME = "testUser"; - - private Principal _principal = new UsernamePrincipal(TEST_USERNAME); - private PlainPasswordFilePrincipalDatabase _database; - private List<File> _testPwdFiles = new ArrayList<File>(); - - public void setUp() throws Exception - { - _database = new PlainPasswordFilePrincipalDatabase(); - _testPwdFiles.clear(); - } - - public void tearDown() throws Exception - { - //clean up any additional files and their backups - for(File f : _testPwdFiles) - { - File oldPwdFile = new File(f.getAbsolutePath() + ".old"); - if(oldPwdFile.exists()) - { - oldPwdFile.delete(); - } - - f.delete(); - } - } - - // ******* Test Methods ********** // - - public void testCreatePrincipal() - { - File testFile = createPasswordFile(1, 0); - - loadPasswordFile(testFile); - - final String CREATED_PASSWORD = "guest"; - final String CREATED_USERNAME = "createdUser"; - - Principal principal = new Principal() - { - public String getName() - { - return CREATED_USERNAME; - } - }; - - assertTrue("New user not created.", _database.createPrincipal(principal, CREATED_PASSWORD.toCharArray())); - - loadPasswordFile(testFile); - - assertNotNull("Created User was not saved", _database.getUser(CREATED_USERNAME)); - - assertFalse("Duplicate user created.", _database.createPrincipal(principal, CREATED_PASSWORD.toCharArray())); - - testFile.delete(); - } - - public void testCreatePrincipalIsSavedToFile() - { - - File testFile = createPasswordFile(1, 0); - - loadPasswordFile(testFile); - - Principal principal = new Principal() - { - public String getName() - { - return TEST_USERNAME; - } - }; - - _database.createPrincipal(principal, TEST_PASSWORD_CHARS); - - try - { - BufferedReader reader = new BufferedReader(new FileReader(testFile)); - - assertTrue("File has no content", reader.ready()); - - assertEquals("Comment line has been corrupted.", TEST_COMMENT, reader.readLine()); - - assertTrue("File is missing user data.", reader.ready()); - - String userLine = reader.readLine(); - - String[] result = Pattern.compile(":").split(userLine); - - assertEquals("User line not complete '" + userLine + "'", 2, result.length); - - assertEquals("Username not correct,", TEST_USERNAME, result[0]); - assertEquals("Password not correct,", TEST_PASSWORD, result[1]); - - assertFalse("File has more content", reader.ready()); - - } - catch (IOException e) - { - fail("Unable to valdate file contents due to:" + e.getMessage()); - } - testFile.delete(); - } - - public void testDeletePrincipal() - { - File testFile = createPasswordFile(1, 1); - - loadPasswordFile(testFile); - - Principal user = _database.getUser(TEST_USERNAME + "0"); - assertNotNull("Generated user not present.", user); - - try - { - _database.deletePrincipal(user); - } - catch (AccountNotFoundException e) - { - fail("User should be present" + e.getMessage()); - } - - try - { - _database.deletePrincipal(user); - fail("User should not be present"); - } - catch (AccountNotFoundException e) - { - //pass - } - - loadPasswordFile(testFile); - - try - { - _database.deletePrincipal(user); - fail("User should not be present"); - } - catch (AccountNotFoundException e) - { - //pass - } - - assertNull("Deleted user still present.", _database.getUser(TEST_USERNAME + "0")); - - testFile.delete(); - } - - public void testGetUsers() - { - int USER_COUNT = 10; - File testFile = createPasswordFile(1, USER_COUNT); - - loadPasswordFile(testFile); - - Principal user = _database.getUser("MISSING_USERNAME"); - assertNull("Missing user present.", user); - - List<Principal> users = _database.getUsers(); - - assertNotNull("Users list is null.", users); - - assertEquals(USER_COUNT, users.size()); - - boolean[] verify = new boolean[USER_COUNT]; - for (int i = 0; i < USER_COUNT; i++) - { - Principal principal = users.get(i); - - assertNotNull("Generated user not present.", principal); - - String name = principal.getName(); - - int id = Integer.parseInt(name.substring(TEST_USERNAME.length())); - - assertFalse("Duplicated username retrieve", verify[id]); - verify[id] = true; - } - - for (int i = 0; i < USER_COUNT; i++) - { - assertTrue("User " + i + " missing", verify[i]); - } - - testFile.delete(); - } - - public void testUpdatePasswordIsSavedToFile() - { - - File testFile = createPasswordFile(1, 1); - - loadPasswordFile(testFile); - - Principal testUser = _database.getUser(TEST_USERNAME + "0"); - - assertNotNull(testUser); - - String NEW_PASSWORD = "NewPassword"; - try - { - _database.updatePassword(testUser, NEW_PASSWORD.toCharArray()); - } - catch (AccountNotFoundException e) - { - fail(e.toString()); - } - - try - { - BufferedReader reader = new BufferedReader(new FileReader(testFile)); - - assertTrue("File has no content", reader.ready()); - - assertEquals("Comment line has been corrupted.", TEST_COMMENT, reader.readLine()); - - assertTrue("File is missing user data.", reader.ready()); - - String userLine = reader.readLine(); - - String[] result = Pattern.compile(":").split(userLine); - - assertEquals("User line not complete '" + userLine + "'", 2, result.length); - - assertEquals("Username not correct,", TEST_USERNAME + "0", result[0]); - assertEquals("New Password not correct,", NEW_PASSWORD, result[1]); - - assertFalse("File has more content", reader.ready()); - - } - catch (IOException e) - { - fail("Unable to valdate file contents due to:" + e.getMessage()); - } - testFile.delete(); - } - - public void testSetPasswordFileWithMissingFile() - { - try - { - _database.open(new File("DoesntExist")); - } - catch (FileNotFoundException fnfe) - { - assertTrue(fnfe.getMessage(), fnfe.getMessage().startsWith("Cannot find password file")); - } - catch (IOException e) - { - fail("Password File was not created." + e.getMessage()); - } - - } - - public void testSetPasswordFileWithReadOnlyFile() - { - - File testFile = createPasswordFile(0, 0); - - testFile.setReadOnly(); - - try - { - _database.open(testFile); - } - catch (FileNotFoundException fnfe) - { - assertTrue(fnfe.getMessage().startsWith("Cannot read password file ")); - } - catch (IOException e) - { - fail("Password File was not created." + e.getMessage()); - } - - testFile.delete(); - } - - private void createUserPrincipal() throws IOException - { - File testFile = createPasswordFile(0, 0); - loadPasswordFile(testFile); - - _database.createPrincipal(_principal, TEST_PASSWORD_CHARS); - Principal newPrincipal = _database.getUser(TEST_USERNAME); - assertNotNull(newPrincipal); - assertEquals(_principal.getName(), newPrincipal.getName()); - } - - public void testVerifyPassword() throws IOException, AccountNotFoundException - { - createUserPrincipal(); - assertFalse(_database.verifyPassword(TEST_USERNAME, new char[]{})); - assertFalse(_database.verifyPassword(TEST_USERNAME, "massword".toCharArray())); - assertTrue(_database.verifyPassword(TEST_USERNAME, TEST_PASSWORD_CHARS)); - - try - { - _database.verifyPassword("made.up.username", TEST_PASSWORD_CHARS); - fail("Should not have been able to verify this non-existant users password."); - } - catch (AccountNotFoundException e) - { - // pass - } - } - - public void testUpdatePassword() throws IOException, AccountNotFoundException - { - createUserPrincipal(); - char[] newPwd = "newpassword".toCharArray(); - _database.updatePassword(_principal, newPwd); - assertFalse(_database.verifyPassword(TEST_USERNAME, TEST_PASSWORD_CHARS)); - assertTrue(_database.verifyPassword(TEST_USERNAME, newPwd)); - } - - - - // *********** Utility Methods ******** // - - private File createPasswordFile(int commentLines, int users) - { - try - { - File testFile = File.createTempFile(this.getClass().getName(),"tmp"); - testFile.deleteOnExit(); - - BufferedWriter writer = new BufferedWriter(new FileWriter(testFile)); - - for (int i = 0; i < commentLines; i++) - { - writer.write(TEST_COMMENT); - writer.newLine(); - } - - for (int i = 0; i < users; i++) - { - writer.write(TEST_USERNAME + i + ":" + TEST_PASSWORD); - writer.newLine(); - } - - writer.flush(); - writer.close(); - - _testPwdFiles.add(testFile); - - return testFile; - - } - catch (IOException e) - { - fail("Unable to create test password file." + e.getMessage()); - } - - return null; - } - - private void loadPasswordFile(File file) - { - try - { - _database.open(file); - } - catch (IOException e) - { - fail("Password File was not created." + e.getMessage()); - } - } - - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PlainUserTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PlainUserTest.java deleted file mode 100644 index 44faa57dbe..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PlainUserTest.java +++ /dev/null @@ -1,78 +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.security.auth.database; - -import junit.framework.TestCase; - -/* - Note PlainUser is mainly tested by PlainPFPDTest, this is just to catch the extra methods - */ -public class PlainUserTest extends TestCase -{ - - private String USERNAME = "username"; - private String PASSWORD = "password"; - - public void testTooLongArrayConstructor() - { - try - { - PlainUser user = new PlainUser(new String[]{USERNAME, PASSWORD, USERNAME}); - fail("Error expected"); - } - catch (IllegalArgumentException e) - { - assertEquals("User Data should be length 2, username, password", e.getMessage()); - } - } - - public void testStringArrayConstructor() - { - PlainUser user = new PlainUser(new String[]{USERNAME, PASSWORD}); - assertEquals("Username incorrect", USERNAME, user.getName()); - int index = 0; - - char[] password = PASSWORD.toCharArray(); - - try - { - for (byte c : user.getEncodedPassword()) - { - assertEquals("Password incorrect", password[index], (char) c); - index++; - } - } - catch (Exception e) - { - fail(e.getMessage()); - } - - password = PASSWORD.toCharArray(); - - index=0; - for (char c : user.getPassword()) - { - assertEquals("Password incorrect", password[index], c); - index++; - } - } -} - diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/jmx/JMXPasswordAuthenticatorTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/jmx/JMXPasswordAuthenticatorTest.java deleted file mode 100644 index a4dd97e6a1..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/jmx/JMXPasswordAuthenticatorTest.java +++ /dev/null @@ -1,259 +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.security.auth.jmx; - -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.security.Principal; -import java.util.regex.Pattern; - -import javax.security.auth.Subject; - -import junit.framework.TestCase; - -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.security.SubjectCreator; -import org.apache.qpid.server.security.auth.AuthenticationResult; -import org.apache.qpid.server.security.auth.AuthenticationResult.AuthenticationStatus; -import org.apache.qpid.server.security.auth.jmx.JMXPasswordAuthenticator; -import org.apache.qpid.server.security.auth.SubjectAuthenticationResult; -import org.apache.qpid.server.security.SecurityManager; - -/** - * Tests the JMXPasswordAuthenticator and its collaboration with the AuthenticationManager. - * - */ -public class JMXPasswordAuthenticatorTest extends TestCase -{ - private static final String USERNAME = "guest"; - private static final String PASSWORD = "password"; - - private final Broker _broker = mock(Broker.class); - private final SecurityManager _securityManager = mock(SecurityManager.class); - private final Subject _loginSubject = new Subject(); - private final String[] _credentials = new String[] {USERNAME, PASSWORD}; - - private JMXPasswordAuthenticator _rmipa; - - private SubjectCreator _usernamePasswordOkaySuvjectCreator = createMockSubjectCreator(true, null); - private SubjectCreator _badPasswordSubjectCreator = createMockSubjectCreator(false, null); - - protected void setUp() throws Exception - { - when(_broker.getSecurityManager()).thenReturn(_securityManager); - _rmipa = new JMXPasswordAuthenticator(_broker, new InetSocketAddress(8999)); - } - - /** - * Tests a successful authentication. Ensures that the expected subject is returned. - */ - public void testAuthenticationSuccess() - { - when(_broker.getSubjectCreator(any(SocketAddress.class))).thenReturn(_usernamePasswordOkaySuvjectCreator); - when(_securityManager.accessManagement()).thenReturn(true); - - Subject newSubject = _rmipa.authenticate(_credentials); - assertSame("Subject must be unchanged", _loginSubject, newSubject); - } - - /** - * Tests a unsuccessful authentication. - */ - public void testUsernameOrPasswordInvalid() - { - when(_broker.getSubjectCreator(any(SocketAddress.class))).thenReturn(_badPasswordSubjectCreator); - - try - { - _rmipa.authenticate(_credentials); - fail("Exception not thrown"); - } - catch (SecurityException se) - { - assertEquals("Unexpected exception message", - JMXPasswordAuthenticator.INVALID_CREDENTIALS, se.getMessage()); - } - } - - public void testAuthorisationFailure() - { - when(_broker.getSubjectCreator(any(SocketAddress.class))).thenReturn(_usernamePasswordOkaySuvjectCreator); - when(_securityManager.accessManagement()).thenReturn(false); - - try - { - _rmipa.authenticate(_credentials); - fail("Exception not thrown"); - } - catch (SecurityException se) - { - assertEquals("Unexpected exception message", - JMXPasswordAuthenticator.USER_NOT_AUTHORISED_FOR_MANAGEMENT, se.getMessage()); - } - } - - public void testSubjectCreatorInternalFailure() - { - final Exception mockAuthException = new Exception("Mock Auth system failure"); - SubjectCreator subjectCreator = createMockSubjectCreator(false, mockAuthException); - when(_broker.getSubjectCreator(any(SocketAddress.class))).thenReturn(subjectCreator); - - try - { - _rmipa.authenticate(_credentials); - fail("Exception not thrown"); - } - catch (SecurityException se) - { - assertEquals("Initial cause not found", mockAuthException, se.getCause()); - } - } - - /** - * Tests case where authentication manager is not set. - */ - public void testNullSubjectCreator() throws Exception - { - when(_broker.getSubjectCreator(any(SocketAddress.class))).thenReturn(null); - - try - { - _rmipa.authenticate(_credentials); - fail("SecurityException expected due to lack of authentication manager"); - } - catch (SecurityException se) - { - assertTrue("Unexpected exception message", Pattern.matches("Can't get subject creator for .*:8999", se.getMessage())); - } - } - - /** - * Tests case where arguments are non-Strings.. - */ - public void testWithNonStringArrayArgument() - { - // Test handling of non-string credential's - final Object[] objCredentials = new Object[]{USERNAME, PASSWORD}; - try - { - _rmipa.authenticate(objCredentials); - fail("SecurityException expected due to non string[] credentials"); - } - catch (SecurityException se) - { - assertEquals("Unexpected exception message", - JMXPasswordAuthenticator.SHOULD_BE_STRING_ARRAY, se.getMessage()); - } - } - - /** - * Tests case where there are too many, too few or null arguments. - */ - public void testWithIllegalNumberOfArguments() - { - String[] credentials; - - // Test handling of incorrect number of credentials - try - { - credentials = new String[]{USERNAME, PASSWORD, PASSWORD}; - _rmipa.authenticate(credentials); - fail("SecurityException expected due to supplying wrong number of credentials"); - } - catch (SecurityException se) - { - assertEquals("Unexpected exception message", - JMXPasswordAuthenticator.SHOULD_HAVE_2_ELEMENTS, se.getMessage()); - } - - // Test handling of null credentials - try - { - //send a null array - credentials = null; - _rmipa.authenticate(credentials); - fail("SecurityException expected due to not supplying an array of credentials"); - } - catch (SecurityException se) - { - assertEquals("Unexpected exception message", - JMXPasswordAuthenticator.CREDENTIALS_REQUIRED, se.getMessage()); - } - - try - { - //send a null password - credentials = new String[]{USERNAME, null}; - _rmipa.authenticate(credentials); - fail("SecurityException expected due to sending a null password"); - } - catch (SecurityException se) - { - assertEquals("Unexpected exception message", - JMXPasswordAuthenticator.SHOULD_BE_NON_NULL, se.getMessage()); - } - - try - { - //send a null username - credentials = new String[]{null, PASSWORD}; - _rmipa.authenticate(credentials); - fail("SecurityException expected due to sending a null username"); - } - catch (SecurityException se) - { - assertEquals("Unexpected exception message", - JMXPasswordAuthenticator.SHOULD_BE_NON_NULL, se.getMessage()); - } - } - - private SubjectCreator createMockSubjectCreator(final boolean successfulAuth, final Exception exception) - { - SubjectCreator subjectCreator = mock(SubjectCreator.class); - - SubjectAuthenticationResult subjectAuthenticationResult; - - if (exception != null) { - - subjectAuthenticationResult = new SubjectAuthenticationResult( - new AuthenticationResult(AuthenticationStatus.ERROR, exception)); - } - else if (successfulAuth) - { - - subjectAuthenticationResult = new SubjectAuthenticationResult( - new AuthenticationResult(mock(Principal.class)), _loginSubject); - } - else - { - subjectAuthenticationResult = new SubjectAuthenticationResult(new AuthenticationResult(AuthenticationStatus.CONTINUE)); - } - - when(subjectCreator.authenticate(anyString(), anyString())).thenReturn(subjectAuthenticationResult); - - return subjectCreator; - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/AnonymousAuthenticationManagerTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/AnonymousAuthenticationManagerTest.java deleted file mode 100644 index cfeb7c525b..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/AnonymousAuthenticationManagerTest.java +++ /dev/null @@ -1,78 +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.security.auth.manager; - -import static org.apache.qpid.server.security.auth.AuthenticatedPrincipalTestHelper.assertOnlyContainsWrapped; - -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; - -import org.apache.qpid.server.security.auth.AuthenticationResult; -import org.apache.qpid.test.utils.QpidTestCase; - -public class AnonymousAuthenticationManagerTest extends QpidTestCase -{ - private AuthenticationManager _manager = new AnonymousAuthenticationManager(); - - public void tearDown() throws Exception - { - if(_manager != null) - { - _manager = null; - } - } - - 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()); - - assertOnlyContainsWrapped(AnonymousAuthenticationManager.ANONYMOUS_PRINCIPAL, result.getPrincipals()); - } - - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/Base64MD5PasswordFileAuthenticationManagerFactoryTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/Base64MD5PasswordFileAuthenticationManagerFactoryTest.java deleted file mode 100644 index 04e09e073f..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/Base64MD5PasswordFileAuthenticationManagerFactoryTest.java +++ /dev/null @@ -1,111 +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.security.auth.manager; - -import java.io.File; -import java.io.FileNotFoundException; -import java.util.HashMap; -import java.util.Map; - -import junit.framework.TestCase; - -import org.apache.qpid.server.plugin.AuthenticationManagerFactory; -import org.apache.qpid.server.security.auth.database.Base64MD5PasswordFilePrincipalDatabase; - -public class Base64MD5PasswordFileAuthenticationManagerFactoryTest extends TestCase -{ - AuthenticationManagerFactory _factory = new Base64MD5PasswordFileAuthenticationManagerFactory(); - private Map<String, Object> _configuration = new HashMap<String, Object>(); - private File _emptyPasswordFile; - - @Override - protected void setUp() throws Exception - { - super.setUp(); - _emptyPasswordFile = File.createTempFile(getName(), "passwd"); - _emptyPasswordFile.deleteOnExit(); - } - - public void testBase64MD5InstanceCreated() throws Exception - { - _configuration.put(AbstractPrincipalDatabaseAuthManagerFactory.ATTRIBUTE_TYPE, Base64MD5PasswordFileAuthenticationManagerFactory.PROVIDER_TYPE); - _configuration.put(AbstractPrincipalDatabaseAuthManagerFactory.ATTRIBUTE_PATH, _emptyPasswordFile.getAbsolutePath()); - - AuthenticationManager manager = _factory.createInstance(_configuration); - assertNotNull(manager); - assertTrue(manager instanceof PrincipalDatabaseAuthenticationManager); - assertTrue(((PrincipalDatabaseAuthenticationManager)manager).getPrincipalDatabase() instanceof Base64MD5PasswordFilePrincipalDatabase); - } - - public void testPasswordFileNotFound() throws Exception - { - //delete the file - _emptyPasswordFile.delete(); - - _configuration.put(AbstractPrincipalDatabaseAuthManagerFactory.ATTRIBUTE_TYPE, Base64MD5PasswordFileAuthenticationManagerFactory.PROVIDER_TYPE); - _configuration.put(AbstractPrincipalDatabaseAuthManagerFactory.ATTRIBUTE_PATH, _emptyPasswordFile.getAbsolutePath()); - - try - { - _factory.createInstance(_configuration); - } - catch (RuntimeException re) - { - assertTrue(re.getCause() instanceof FileNotFoundException); - } - } - - public void testReturnsNullWhenNoConfig() throws Exception - { - AuthenticationManager manager = _factory.createInstance(_configuration); - assertNull(manager); - } - - public void testReturnsNullWhenConfigForOtherAuthManagerType() throws Exception - { - _configuration.put(AbstractPrincipalDatabaseAuthManagerFactory.ATTRIBUTE_TYPE, "other-auth-manager"); - AuthenticationManager manager = _factory.createInstance(_configuration); - assertNull(manager); - } - - public void testReturnsNullWhenConfigForPlainPDImplementationNoPasswordFileValueSpecified() throws Exception - { - _configuration.put(AbstractPrincipalDatabaseAuthManagerFactory.ATTRIBUTE_TYPE, Base64MD5PasswordFileAuthenticationManagerFactory.PROVIDER_TYPE); - - AuthenticationManager manager = _factory.createInstance(_configuration); - assertNull(manager); - } - - @Override - protected void tearDown() throws Exception - { - try - { - if (_emptyPasswordFile == null && _emptyPasswordFile.exists()) - { - _emptyPasswordFile.delete(); - } - } - finally - { - super.tearDown(); - } - } -}
\ No newline at end of file diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/ExternalAuthenticationManagerTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/ExternalAuthenticationManagerTest.java deleted file mode 100644 index 61506777c5..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/ExternalAuthenticationManagerTest.java +++ /dev/null @@ -1,183 +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.security.auth.manager; - -import static org.apache.qpid.server.security.auth.AuthenticatedPrincipalTestHelper.assertOnlyContainsWrapped; - -import javax.security.auth.x500.X500Principal; -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; - -import org.apache.qpid.server.security.auth.AuthenticationResult; -import org.apache.qpid.server.security.auth.UsernamePrincipal; -import org.apache.qpid.test.utils.QpidTestCase; - -public class ExternalAuthenticationManagerTest extends QpidTestCase -{ - private AuthenticationManager _manager = new ExternalAuthenticationManager(false); - private AuthenticationManager _managerUsingFullDN = new ExternalAuthenticationManager(true); - - public void testGetMechanisms() throws Exception - { - assertEquals("EXTERNAL", _manager.getMechanisms()); - } - - public void testCreateSaslServer() throws Exception - { - createSaslServerTestImpl(_manager); - } - - public void testCreateSaslServerUsingFullDN() throws Exception - { - createSaslServerTestImpl(_managerUsingFullDN); - } - - public void createSaslServerTestImpl(AuthenticationManager manager) 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 - } - } - - /** - * Test behaviour of the authentication when the useFullDN attribute is set true - * and the username is taken directly as the externally supplied Principal - */ - public void testAuthenticateWithFullDN() throws Exception - { - X500Principal principal = new X500Principal("CN=person, DC=example, DC=com"); - SaslServer saslServer = _managerUsingFullDN.createSaslServer("EXTERNAL", "example.example.com", principal); - - AuthenticationResult result = _managerUsingFullDN.authenticate(saslServer, new byte[0]); - assertNotNull(result); - assertEquals("Expected authentication to be successful", - AuthenticationResult.AuthenticationStatus.SUCCESS, - result.getStatus()); - - assertOnlyContainsWrapped(principal, result.getPrincipals()); - - saslServer = _managerUsingFullDN.createSaslServer("EXTERNAL", "example.example.com", null); - result = _managerUsingFullDN.authenticate(saslServer, new byte[0]); - - assertNotNull(result); - assertEquals("Expected authentication to be unsuccessful", - AuthenticationResult.AuthenticationStatus.ERROR, - result.getStatus()); - } - - /** - * Test behaviour of the authentication when parsing the username from - * the Principals DN as <CN>@<DC1>.<DC2>.<DC3>....<DCN> - */ - public void testAuthenticateWithUsernameBasedOnCNAndDC() throws Exception - { - X500Principal principal; - SaslServer saslServer; - AuthenticationResult result; - UsernamePrincipal expectedPrincipal; - - // DN contains only CN - principal = new X500Principal("CN=person"); - expectedPrincipal = new UsernamePrincipal("person"); - saslServer = _manager.createSaslServer("EXTERNAL", "example.example.com", principal); - - result = _manager.authenticate(saslServer, new byte[0]); - assertNotNull(result); - assertEquals("Expected authentication to be successful", - AuthenticationResult.AuthenticationStatus.SUCCESS, - result.getStatus()); - assertOnlyContainsWrapped(expectedPrincipal, result.getPrincipals()); - - // Null principal - 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()); - - // DN doesn't contain CN - principal = new X500Principal("DC=example, DC=com, O=My Company Ltd, L=Newbury, ST=Berkshire, C=GB"); - saslServer = _manager.createSaslServer("EXTERNAL", "example.example.com", principal); - result = _manager.authenticate(saslServer, new byte[0]); - - assertNotNull(result); - assertEquals("Expected authentication to be unsuccessful", - AuthenticationResult.AuthenticationStatus.ERROR, - result.getStatus()); - - // DN contains empty CN - principal = new X500Principal("CN=, DC=example, DC=com, O=My Company Ltd, L=Newbury, ST=Berkshire, C=GB"); - saslServer = _manager.createSaslServer("EXTERNAL", "example.example.com", principal); - result = _manager.authenticate(saslServer, new byte[0]); - - assertNotNull(result); - assertEquals("Expected authentication to be unsuccessful", - AuthenticationResult.AuthenticationStatus.ERROR, - result.getStatus()); - - // DN contains CN and DC - principal = new X500Principal("CN=person, DC=example, DC=com"); - expectedPrincipal = new UsernamePrincipal("person@example.com"); - saslServer = _manager.createSaslServer("EXTERNAL", "example.example.com", principal); - - result = _manager.authenticate(saslServer, new byte[0]); - assertNotNull(result); - assertEquals("Expected authentication to be successful", - AuthenticationResult.AuthenticationStatus.SUCCESS, - result.getStatus()); - assertOnlyContainsWrapped(expectedPrincipal, result.getPrincipals()); - - // DN contains CN and DC and other components - principal = new X500Principal("CN=person, DC=example, DC=com, O=My Company Ltd, L=Newbury, ST=Berkshire, C=GB"); - expectedPrincipal = new UsernamePrincipal("person@example.com"); - saslServer = _manager.createSaslServer("EXTERNAL", "example.example.com", principal); - - result = _manager.authenticate(saslServer, new byte[0]); - assertNotNull(result); - assertEquals("Expected authentication to be successful", - AuthenticationResult.AuthenticationStatus.SUCCESS, - result.getStatus()); - assertOnlyContainsWrapped(expectedPrincipal, result.getPrincipals()); - - // DN contains CN and DC and other components - principal = new X500Principal("CN=person, O=My Company Ltd, L=Newbury, ST=Berkshire, C=GB"); - expectedPrincipal = new UsernamePrincipal("person"); - saslServer = _manager.createSaslServer("EXTERNAL", "example.example.com", principal); - - result = _manager.authenticate(saslServer, new byte[0]); - assertNotNull(result); - assertEquals("Expected authentication to be successful", - AuthenticationResult.AuthenticationStatus.SUCCESS, - result.getStatus()); - assertOnlyContainsWrapped(expectedPrincipal, result.getPrincipals()); - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/PlainPasswordFileAuthenticationManagerFactoryTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/PlainPasswordFileAuthenticationManagerFactoryTest.java deleted file mode 100644 index cc11a94db8..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/PlainPasswordFileAuthenticationManagerFactoryTest.java +++ /dev/null @@ -1,107 +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.security.auth.manager; - -import java.io.File; -import java.util.HashMap; -import java.util.Map; - -import junit.framework.TestCase; - -import org.apache.qpid.server.plugin.AuthenticationManagerFactory; -import org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase; - -public class PlainPasswordFileAuthenticationManagerFactoryTest extends TestCase -{ - AuthenticationManagerFactory _factory = new PlainPasswordFileAuthenticationManagerFactory(); - private Map<String, Object> _configuration = new HashMap<String, Object>(); - private File _emptyPasswordFile; - - @Override - protected void setUp() throws Exception - { - super.setUp(); - _emptyPasswordFile = File.createTempFile(getName(), "passwd"); - _emptyPasswordFile.deleteOnExit(); - } - - public void testPlainInstanceCreated() throws Exception - { - _configuration.put(AbstractPrincipalDatabaseAuthManagerFactory.ATTRIBUTE_TYPE, PlainPasswordFileAuthenticationManagerFactory.PROVIDER_TYPE); - _configuration.put(AbstractPrincipalDatabaseAuthManagerFactory.ATTRIBUTE_PATH, _emptyPasswordFile.getAbsolutePath()); - - AuthenticationManager manager = _factory.createInstance(_configuration); - assertNotNull(manager); - assertTrue(manager instanceof PrincipalDatabaseAuthenticationManager); - assertTrue(((PrincipalDatabaseAuthenticationManager)manager).getPrincipalDatabase() instanceof PlainPasswordFilePrincipalDatabase); - } - - public void testPasswordFileNotFound() throws Exception - { - //delete the file - _emptyPasswordFile.delete(); - - _configuration.put(AbstractPrincipalDatabaseAuthManagerFactory.ATTRIBUTE_TYPE, PlainPasswordFileAuthenticationManagerFactory.PROVIDER_TYPE); - _configuration.put(AbstractPrincipalDatabaseAuthManagerFactory.ATTRIBUTE_PATH, _emptyPasswordFile.getAbsolutePath()); - - AuthenticationManager manager = _factory.createInstance(_configuration); - - assertNotNull(manager); - assertTrue(manager instanceof PrincipalDatabaseAuthenticationManager); - assertTrue(((PrincipalDatabaseAuthenticationManager)manager).getPrincipalDatabase() instanceof PlainPasswordFilePrincipalDatabase); - } - - public void testReturnsNullWhenNoConfig() throws Exception - { - AuthenticationManager manager = _factory.createInstance(_configuration); - assertNull(manager); - } - - public void testReturnsNullWhenConfigForOtherAuthManagerType() throws Exception - { - _configuration.put(AbstractPrincipalDatabaseAuthManagerFactory.ATTRIBUTE_TYPE, "other-auth-manager"); - AuthenticationManager manager = _factory.createInstance(_configuration); - assertNull(manager); - } - - public void testReturnsNullWhenConfigForPlainPDImplementationNoPasswordFileValueSpecified() throws Exception - { - _configuration.put(AbstractPrincipalDatabaseAuthManagerFactory.ATTRIBUTE_TYPE, PlainPasswordFileAuthenticationManagerFactory.PROVIDER_TYPE); - - AuthenticationManager manager = _factory.createInstance(_configuration); - assertNull(manager); - } - - @Override - protected void tearDown() throws Exception - { - try - { - if (_emptyPasswordFile == null && _emptyPasswordFile.exists()) - { - _emptyPasswordFile.delete(); - } - } - finally - { - super.tearDown(); - } - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManagerTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManagerTest.java deleted file mode 100644 index cba6058426..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManagerTest.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.security.auth.manager; - -import static org.apache.qpid.server.security.auth.AuthenticatedPrincipalTestHelper.assertOnlyContainsWrapped; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.security.Principal; -import java.util.List; -import java.util.Map; - -import javax.security.auth.callback.CallbackHandler; -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; -import javax.security.sasl.SaslServerFactory; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.security.auth.AuthenticationResult; -import org.apache.qpid.server.security.auth.AuthenticationResult.AuthenticationStatus; -import org.apache.qpid.server.security.auth.UsernamePrincipal; -import org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase; -import org.apache.qpid.server.security.auth.database.PrincipalDatabase; -import org.apache.qpid.server.security.auth.sasl.UsernamePasswordInitialiser; -import org.apache.qpid.test.utils.QpidTestCase; - -/** - * Tests the public methods of PrincipalDatabaseAuthenticationManager. - * - */ -public class PrincipalDatabaseAuthenticationManagerTest extends QpidTestCase -{ - private static final String LOCALHOST = "localhost"; - private static final String MOCK_MECH_NAME = "MOCK-MECH-NAME"; - private static final UsernamePrincipal PRINCIPAL = new UsernamePrincipal("guest"); - - private AuthenticationManager _manager = null; // Class under test - private PrincipalDatabase _principalDatabase; - private String _passwordFileLocation; - - @Override - public void setUp() throws Exception - { - super.setUp(); - _passwordFileLocation = TMP_FOLDER + File.separator + PrincipalDatabaseAuthenticationManagerTest.class.getSimpleName() + "-" + getName(); - deletePasswordFileIfExists(); - } - - @Override - public void tearDown() throws Exception - { - try - { - if (_manager != null) - { - _manager.close(); - } - } - finally - { - deletePasswordFileIfExists(); - } - super.tearDown(); - } - - private void setupMocks() throws Exception - { - _principalDatabase = mock(PrincipalDatabase.class); - - when(_principalDatabase.getMechanisms()).thenReturn(MOCK_MECH_NAME); - when(_principalDatabase.createSaslServer(MOCK_MECH_NAME, LOCALHOST, null)).thenReturn(new MySaslServer(false, true)); - - _manager = new PrincipalDatabaseAuthenticationManager(_principalDatabase, _passwordFileLocation); - _manager.initialise(); - } - - public void testInitialiseWhenPasswordFileNotFound() throws Exception - { - _principalDatabase = new PlainPasswordFilePrincipalDatabase(); - _manager = new PrincipalDatabaseAuthenticationManager(_principalDatabase, _passwordFileLocation); - - try - { - _manager.initialise(); - fail("Initialisiation should fail when users file does not exist"); - } - catch (IllegalConfigurationException e) - { - assertTrue(e.getCause() instanceof FileNotFoundException); - } - } - - public void testInitialiseWhenPasswordFileExists() throws Exception - { - _principalDatabase = new PlainPasswordFilePrincipalDatabase(); - _manager = new PrincipalDatabaseAuthenticationManager(_principalDatabase, _passwordFileLocation); - - File f = new File(_passwordFileLocation); - f.createNewFile(); - FileOutputStream fos = null; - try - { - fos = new FileOutputStream(f); - fos.write("admin:admin".getBytes()); - } - finally - { - if (fos != null) - { - fos.close(); - } - } - _manager.initialise(); - List<Principal> users = _principalDatabase.getUsers(); - assertEquals("Unexpected uses size", 1, users.size()); - Principal p = _principalDatabase.getUser("admin"); - assertEquals("Unexpected principal name", "admin", p.getName()); - } - - /** - * Tests that the SASL factory method createSaslServer correctly - * returns a non-null implementation. - */ - public void testSaslMechanismCreation() throws Exception - { - setupMocks(); - - SaslServer server = _manager.createSaslServer(MOCK_MECH_NAME, LOCALHOST, null); - assertNotNull(server); - // Merely tests the creation of the mechanism. Mechanisms themselves are tested - // by their own tests. - } - - /** - * Tests that the authenticate method correctly interprets an - * authentication success. - * - */ - public void testSaslAuthenticationSuccess() throws Exception - { - setupMocks(); - - SaslServer testServer = createTestSaslServer(true, false); - - AuthenticationResult result = _manager.authenticate(testServer, "12345".getBytes()); - - assertOnlyContainsWrapped(PRINCIPAL, result.getPrincipals()); - assertEquals(AuthenticationStatus.SUCCESS, result.getStatus()); - } - - /** - * - * Tests that the authenticate method correctly interprets an - * authentication not complete. - * - */ - public void testSaslAuthenticationNotCompleted() throws Exception - { - setupMocks(); - - SaslServer testServer = createTestSaslServer(false, false); - - AuthenticationResult result = _manager.authenticate(testServer, "12345".getBytes()); - assertEquals("Principals was not expected size", 0, result.getPrincipals().size()); - - assertEquals(AuthenticationStatus.CONTINUE, result.getStatus()); - } - - /** - * - * Tests that the authenticate method correctly interprets an - * authentication error. - * - */ - public void testSaslAuthenticationError() throws Exception - { - setupMocks(); - - SaslServer testServer = createTestSaslServer(false, true); - - AuthenticationResult result = _manager.authenticate(testServer, "12345".getBytes()); - assertEquals("Principals was not expected size", 0, result.getPrincipals().size()); - assertEquals(AuthenticationStatus.ERROR, result.getStatus()); - } - - public void testNonSaslAuthenticationSuccess() throws Exception - { - setupMocks(); - - when(_principalDatabase.verifyPassword("guest", "guest".toCharArray())).thenReturn(true); - - AuthenticationResult result = _manager.authenticate("guest", "guest"); - assertOnlyContainsWrapped(PRINCIPAL, result.getPrincipals()); - assertEquals(AuthenticationStatus.SUCCESS, result.getStatus()); - } - - public void testNonSaslAuthenticationNotCompleted() throws Exception - { - setupMocks(); - - when(_principalDatabase.verifyPassword("guest", "wrongpassword".toCharArray())).thenReturn(false); - - AuthenticationResult result = _manager.authenticate("guest", "wrongpassword"); - assertEquals("Principals was not expected size", 0, result.getPrincipals().size()); - assertEquals(AuthenticationStatus.CONTINUE, result.getStatus()); - } - - public void testOnCreate() throws Exception - { - setupMocks(); - - _manager.onCreate(); - assertTrue("Password file was not created", new File(_passwordFileLocation).exists()); - } - - public void testOnDelete() throws Exception - { - setupMocks(); - - _manager.onCreate(); - assertTrue("Password file was not created", new File(_passwordFileLocation).exists()); - - _manager.onDelete(); - assertFalse("Password file was not deleted", new File(_passwordFileLocation).exists()); - } - - private void deletePasswordFileIfExists() - { - File passwordFile = new File(_passwordFileLocation); - if (passwordFile.exists()) - { - passwordFile.delete(); - } - } - - /** - * Test SASL implementation used to test the authenticate() method. - */ - private SaslServer createTestSaslServer(final boolean complete, final boolean throwSaslException) - { - return new MySaslServer(throwSaslException, complete); - } - - public static final class MySaslServer implements SaslServer - { - private final boolean _throwSaslException; - private final boolean _complete; - - public MySaslServer() - { - this(false, true); - } - - private MySaslServer(boolean throwSaslException, boolean complete) - { - _throwSaslException = throwSaslException; - _complete = complete; - } - - public String getMechanismName() - { - return null; - } - - public byte[] evaluateResponse(byte[] response) throws SaslException - { - if (_throwSaslException) - { - throw new SaslException("Mocked exception"); - } - return null; - } - - public boolean isComplete() - { - return _complete; - } - - public String getAuthorizationID() - { - return _complete ? "guest" : null; - } - - public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException - { - return null; - } - - public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException - { - return null; - } - - public Object getNegotiatedProperty(String propName) - { - return null; - } - - public void dispose() throws SaslException - { - } - } - - public static class MySaslServerFactory implements SaslServerFactory - { - @Override - public SaslServer createSaslServer(String mechanism, String protocol, - String serverName, Map<String, ?> props, CallbackHandler cbh) - throws SaslException - { - if (MOCK_MECH_NAME.equals(mechanism)) - { - return new MySaslServer(); - } - else - { - return null; - } - } - - @Override - public String[] getMechanismNames(Map<String, ?> props) - { - return new String[]{MOCK_MECH_NAME}; - } - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/SimpleAuthenticationManagerTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/SimpleAuthenticationManagerTest.java deleted file mode 100644 index 110206a83d..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/SimpleAuthenticationManagerTest.java +++ /dev/null @@ -1,160 +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.security.auth.manager; - -import java.security.Principal; -import java.util.Set; - -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; - -import org.apache.qpid.server.security.auth.AuthenticationResult; -import org.apache.qpid.server.security.auth.AuthenticationResult.AuthenticationStatus; -import org.apache.qpid.server.security.auth.sasl.SaslUtil; -import org.apache.qpid.server.security.auth.sasl.plain.PlainSaslServer; -import org.apache.qpid.test.utils.QpidTestCase; - -public class SimpleAuthenticationManagerTest extends QpidTestCase -{ - private static final String TEST_USER = "testUser"; - private static final String TEST_PASSWORD = "testPassword"; - private AuthenticationManager _authenticationManager; - - public void setUp() throws Exception - { - super.setUp(); - _authenticationManager = new SimpleAuthenticationManager(TEST_USER, TEST_PASSWORD); - } - - public void testGetMechanisms() - { - assertEquals("Unexpected mechanisms", "PLAIN CRAM-MD5", _authenticationManager.getMechanisms()); - } - - public void testCreateSaslServerForUnsupportedMechanisms() throws Exception - { - String[] unsupported = new String[] { "EXTERNAL", "CRAM-MD5-HEX", "CRAM-MD5-HASHED", "ANONYMOUS", "GSSAPI"}; - for (int i = 0; i < unsupported.length; i++) - { - String mechanism = unsupported[i]; - try - { - _authenticationManager.createSaslServer(mechanism, "test", null); - fail("Mechanism " + mechanism + " should not be supported by SimpleAuthenticationManager"); - } - catch (SaslException e) - { - // pass - } - } - } - - public void testAuthenticateWithPlainSaslServer() throws Exception - { - AuthenticationResult result = authenticatePlain(TEST_USER, TEST_PASSWORD); - assertAuthenticated(result); - } - - public void testAuthenticateWithPlainSaslServerInvalidPassword() throws Exception - { - AuthenticationResult result = authenticatePlain(TEST_USER, "wrong-password"); - assertUnauthenticated(result); - } - - public void testAuthenticateWithPlainSaslServerInvalidUsername() throws Exception - { - AuthenticationResult result = authenticatePlain("wrong-user", TEST_PASSWORD); - assertUnauthenticated(result); - } - - public void testAuthenticateWithCramMd5SaslServer() throws Exception - { - AuthenticationResult result = authenticateCramMd5(TEST_USER, TEST_PASSWORD); - assertAuthenticated(result); - } - - public void testAuthenticateWithCramMd5SaslServerInvalidPassword() throws Exception - { - AuthenticationResult result = authenticateCramMd5(TEST_USER, "wrong-password"); - assertUnauthenticated(result); - } - - public void testAuthenticateWithCramMd5SaslServerInvalidUsername() throws Exception - { - AuthenticationResult result = authenticateCramMd5("wrong-user", TEST_PASSWORD); - assertUnauthenticated(result); - } - - public void testAuthenticateValidCredentials() - { - AuthenticationResult result = _authenticationManager.authenticate(TEST_USER, TEST_PASSWORD); - assertEquals("Unexpected authentication result", AuthenticationStatus.SUCCESS, result.getStatus()); - assertAuthenticated(result); - } - - public void testAuthenticateInvalidPassword() - { - AuthenticationResult result = _authenticationManager.authenticate(TEST_USER, "invalid"); - assertUnauthenticated(result); - } - - public void testAuthenticateInvalidUserName() - { - AuthenticationResult result = _authenticationManager.authenticate("invalid", TEST_PASSWORD); - assertUnauthenticated(result); - } - - private void assertAuthenticated(AuthenticationResult result) - { - assertEquals("Unexpected authentication result", AuthenticationStatus.SUCCESS, result.getStatus()); - Principal principal = result.getMainPrincipal(); - assertEquals("Unexpected principal name", TEST_USER, principal.getName()); - Set<Principal> principals = result.getPrincipals(); - assertEquals("Unexpected principals size", 1, principals.size()); - assertEquals("Unexpected principal name", TEST_USER, principals.iterator().next().getName()); - } - - private void assertUnauthenticated(AuthenticationResult result) - { - assertEquals("Unexpected authentication result", AuthenticationStatus.ERROR, result.getStatus()); - assertNull("Unexpected principal", result.getMainPrincipal()); - Set<Principal> principals = result.getPrincipals(); - assertEquals("Unexpected principals size", 0, principals.size()); - } - - private AuthenticationResult authenticatePlain(String userName, String userPassword) throws SaslException, Exception - { - PlainSaslServer ss = (PlainSaslServer) _authenticationManager.createSaslServer("PLAIN", "test", null); - byte[] response = SaslUtil.generatePlainClientResponse(userName, userPassword); - - return _authenticationManager.authenticate(ss, response); - } - - private AuthenticationResult authenticateCramMd5(String userName, String userPassword) throws SaslException, Exception - { - SaslServer ss = _authenticationManager.createSaslServer("CRAM-MD5", "test", null); - byte[] challenge = ss.evaluateResponse(new byte[0]); - byte[] response = SaslUtil.generateCramMD5ClientResponse(userName, userPassword, challenge); - - AuthenticationResult result = _authenticationManager.authenticate(ss, response); - return result; - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/SimpleLDAPAuthenticationManagerFactoryTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/SimpleLDAPAuthenticationManagerFactoryTest.java deleted file mode 100644 index 1424bee611..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/SimpleLDAPAuthenticationManagerFactoryTest.java +++ /dev/null @@ -1,48 +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.security.auth.manager; - -import java.util.HashMap; -import java.util.Map; - - -import junit.framework.TestCase; - -public class SimpleLDAPAuthenticationManagerFactoryTest extends TestCase -{ - private SimpleLDAPAuthenticationManagerFactory _factory = new SimpleLDAPAuthenticationManagerFactory(); - private Map<String, Object> _configuration = new HashMap<String, Object>(); - - public void testInstanceCreated() throws Exception - { - _configuration.put(SimpleLDAPAuthenticationManagerFactory.ATTRIBUTE_TYPE, SimpleLDAPAuthenticationManagerFactory.PROVIDER_TYPE); - _configuration.put("providerUrl", "ldaps://example.com:636/"); - _configuration.put("searchContext", "dc=example"); - - AuthenticationManager manager = _factory.createInstance(_configuration); - assertNotNull(manager); - } - - public void testReturnsNullWhenNoConfig() throws Exception - { - AuthenticationManager manager = _factory.createInstance(_configuration); - assertNull(manager); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/CRAMMD5HexInitialiserTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/CRAMMD5HexInitialiserTest.java deleted file mode 100644 index 3079222b1c..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/CRAMMD5HexInitialiserTest.java +++ /dev/null @@ -1,145 +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.security.auth.sasl; - -import java.io.File; -import java.io.UnsupportedEncodingException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; - -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.NameCallback; -import javax.security.auth.callback.PasswordCallback; - -import junit.framework.TestCase; - -import org.apache.qpid.server.security.auth.database.Base64MD5PasswordFilePrincipalDatabase; -import org.apache.qpid.server.security.auth.database.PrincipalDatabase; -import org.apache.qpid.server.security.auth.sasl.crammd5.CRAMMD5HexInitialiser; -import org.apache.qpid.test.utils.TestFileUtils; -import org.apache.qpid.tools.security.Passwd; - -/** - * These tests ensure that the Hex wrapping that the initialiser performs does actually operate when the handle method is called. - */ -public class CRAMMD5HexInitialiserTest extends TestCase -{ - private static final String TEST_PASSWORD = "testPassword"; - private static final String TEST_USER = "testUser"; - private File _file; - - public void testHashedHex() throws Exception - { - perform(TEST_USER, getHash(TEST_PASSWORD)); - } - - public void perform(String user, char[] password) throws Exception - { - CRAMMD5HexInitialiser initialiser = new CRAMMD5HexInitialiser(); - - PrincipalDatabase db = new Base64MD5PasswordFilePrincipalDatabase(); - db.open(_file); - initialiser.initialise(db); - - PasswordCallback passwordCallback = new PasswordCallback("password:", false); - NameCallback usernameCallback = new NameCallback("user:", user); - - Callback[] callbacks = new Callback[]{usernameCallback, passwordCallback}; - - assertNull("The password was not null before the handle call.", passwordCallback.getPassword()); - initialiser.getCallbackHandler().handle(callbacks); - - assertArrayEquals(toHex(password), passwordCallback.getPassword()); - } - - public void setUp() throws Exception - { - super.setUp(); - _file = TestFileUtils.createTempFile(this, "password-file", new Passwd().getOutput(TEST_USER , TEST_PASSWORD)); - } - - public void tearDown() throws Exception - { - if (_file != null) - { - _file.delete(); - } - super.tearDown(); - } - - private char[] getHash(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException - { - - byte[] data = text.getBytes("utf-8"); - - MessageDigest md = MessageDigest.getInstance("MD5"); - - for (byte b : data) - { - md.update(b); - } - - byte[] digest = md.digest(); - - char[] hash = new char[digest.length]; - - int index = 0; - for (byte b : digest) - { - hash[index++] = (char) b; - } - - return hash; - } - - private void assertArrayEquals(char[] expected, char[] actual) - { - assertEquals("Arrays are not the same length", expected.length, actual.length); - - for (int index = 0; index < expected.length; index++) - { - assertEquals("Characters are not equal", expected[index], actual[index]); - } - } - - private char[] toHex(char[] password) - { - StringBuilder sb = new StringBuilder(); - for (char c : password) - { - //toHexString does not prepend 0 so we have to - if (((byte) c > -1) && (byte) c < 10) - { - sb.append(0); - } - - sb.append(Integer.toHexString(c & 0xFF)); - } - - //Extract the hex string as char[] - char[] hex = new char[sb.length()]; - - sb.getChars(0, sb.length(), hex, 0); - - return hex; - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/CRAMMD5HexServerTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/CRAMMD5HexServerTest.java deleted file mode 100644 index b3e929dd6c..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/CRAMMD5HexServerTest.java +++ /dev/null @@ -1,227 +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.security.auth.sasl; - -import junit.framework.TestCase; -import org.apache.commons.codec.binary.Hex; - -import org.apache.qpid.server.security.auth.database.Base64MD5PasswordFilePrincipalDatabase; -import org.apache.qpid.server.security.auth.sasl.crammd5.CRAMMD5HexInitialiser; -import org.apache.qpid.server.security.auth.sasl.crammd5.CRAMMD5HexSaslServer; -import org.apache.qpid.server.security.auth.sasl.crammd5.CRAMMD5HexServerFactory; - -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; -import javax.security.auth.login.AccountNotFoundException; -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; -import java.io.File; -import java.io.IOException; -import java.security.MessageDigest; -import java.security.Principal; - -/** - * Test for the CRAM-MD5-HEX SASL mechanism. - * - * This test case focuses on testing {@link CRAMMD5HexSaslServer} but also exercises - * collaborators {@link CRAMMD5HexInitialiser} and {@link Base64MD5PasswordFilePrincipalDatabase} - */ -public class CRAMMD5HexServerTest extends TestCase -{ - - private SaslServer _saslServer; // Class under test - private CRAMMD5HexServerFactory _saslFactory; - - @Override - protected void setUp() throws Exception - { - super.setUp(); - - CRAMMD5HexInitialiser _initializer = new CRAMMD5HexInitialiser(); - - //Use properties to create a PrincipalDatabase - Base64MD5PasswordFilePrincipalDatabase db = createTestPrincipalDatabase(); - assertEquals("Unexpected number of test users in the db", 2, db.getUsers().size()); - - _initializer.initialise(db); - - _saslFactory = new CRAMMD5HexServerFactory(); - - _saslServer = _saslFactory.createSaslServer(CRAMMD5HexSaslServer.MECHANISM, - "AMQP", - "localhost", - null, - _initializer.getCallbackHandler()); - assertNotNull("Unable to create saslServer with mechanism type " + CRAMMD5HexSaslServer.MECHANISM, _saslServer); - - } - - public void testSuccessfulAuth() throws Exception - { - - final byte[] serverChallenge = _saslServer.evaluateResponse(new byte[0]); - - // Generate client response - final byte[] clientResponse = generateClientResponse("knownuser", "guest", serverChallenge); - - - byte[] nextServerChallenge = _saslServer.evaluateResponse(clientResponse); - assertTrue("Exchange must be flagged as complete after successful authentication", _saslServer.isComplete()); - assertNull("Next server challenge must be null after successful authentication", nextServerChallenge); - - } - - public void testKnownUserPresentsWrongPassword() throws Exception - { - byte[] serverChallenge = _saslServer.evaluateResponse(new byte[0]); - - - final byte[] clientResponse = generateClientResponse("knownuser", "wrong!", serverChallenge); - try - { - _saslServer.evaluateResponse(clientResponse); - fail("Exception not thrown"); - } - catch (SaslException se) - { - // PASS - } - assertFalse("Exchange must not be flagged as complete after unsuccessful authentication", _saslServer.isComplete()); - } - - public void testUnknownUser() throws Exception - { - final byte[] serverChallenge = _saslServer.evaluateResponse(new byte[0]); - - - final byte[] clientResponse = generateClientResponse("unknownuser", "guest", serverChallenge); - - try - { - _saslServer.evaluateResponse(clientResponse); - fail("Exception not thrown"); - } - catch (SaslException se) - { - assertExceptionHasUnderlyingAsCause(AccountNotFoundException.class, se); - // PASS - } - assertFalse("Exchange must not be flagged as complete after unsuccessful authentication", _saslServer.isComplete()); - } - - /** - * - * Demonstrates QPID-3158. A defect meant that users with some valid password were failing to - * authenticate when using the .NET 0-8 client (uses this SASL mechanism). - * It so happens that password "guest2" was one of the affected passwords. - * - * @throws Exception - */ - public void testSuccessfulAuthReproducingQpid3158() throws Exception - { - byte[] serverChallenge = _saslServer.evaluateResponse(new byte[0]); - - // Generate client response - byte[] resp = generateClientResponse("qpid3158user", "guest2", serverChallenge); - - byte[] nextServerChallenge = _saslServer.evaluateResponse(resp); - assertTrue("Exchange must be flagged as complete after successful authentication", _saslServer.isComplete()); - assertNull("Next server challenge must be null after successful authentication", nextServerChallenge); - } - - /** - * Since we don't have a CRAM-MD5-HEX implementation client implementation in Java, this method - * provides the implementation for first principals. - * - * @param userId user id - * @param clearTextPassword clear text password - * @param serverChallenge challenge from server - * - * @return challenge response - */ - private byte[] generateClientResponse(final String userId, final String clearTextPassword, final byte[] serverChallenge) throws Exception - { - byte[] digestedPasswordBytes = MessageDigest.getInstance("MD5").digest(clearTextPassword.getBytes()); - char[] hexEncodedDigestedPassword = Hex.encodeHex(digestedPasswordBytes); - byte[] hexEncodedDigestedPasswordBytes = new String(hexEncodedDigestedPassword).getBytes(); - - - Mac hmacMd5 = Mac.getInstance("HmacMD5"); - hmacMd5.init(new SecretKeySpec(hexEncodedDigestedPasswordBytes, "HmacMD5")); - final byte[] messageAuthenticationCode = hmacMd5.doFinal(serverChallenge); - - // Build client response - String responseAsString = userId + " " + new String(Hex.encodeHex(messageAuthenticationCode)); - byte[] resp = responseAsString.getBytes(); - return resp; - } - - /** - * Creates a test principal database. - * - * @return - * @throws IOException - */ - private Base64MD5PasswordFilePrincipalDatabase createTestPrincipalDatabase() throws IOException - { - Base64MD5PasswordFilePrincipalDatabase db = new Base64MD5PasswordFilePrincipalDatabase(); - File file = File.createTempFile("passwd", "db"); - file.deleteOnExit(); - db.open(file); - db.createPrincipal( createTestPrincipal("knownuser"), "guest".toCharArray()); - db.createPrincipal( createTestPrincipal("qpid3158user"), "guest2".toCharArray()); - return db; - } - - private Principal createTestPrincipal(final String name) - { - return new Principal() - { - public String getName() - { - return name; - } - }; - } - - private void assertExceptionHasUnderlyingAsCause(final Class<? extends Throwable> expectedUnderlying, Throwable e) - { - assertNotNull(e); - int infiniteLoopGuard = 0; // Guard against loops in the cause chain - boolean foundExpectedUnderlying = false; - while (e.getCause() != null && infiniteLoopGuard++ < 10) - { - if (expectedUnderlying.equals(e.getCause().getClass())) - { - foundExpectedUnderlying = true; - break; - } - e = e.getCause(); - } - - if (!foundExpectedUnderlying) - { - fail("Not found expected underlying exception " + expectedUnderlying + " as underlying cause of " + e.getClass()); - } - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/SaslServerTestCase.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/SaslServerTestCase.java deleted file mode 100644 index f5247634ac..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/SaslServerTestCase.java +++ /dev/null @@ -1,66 +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.security.auth.sasl; - -import junit.framework.TestCase; - -import org.apache.qpid.server.security.auth.database.PrincipalDatabase; - -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; - -public abstract class SaslServerTestCase extends TestCase -{ - protected SaslServer server; - protected String username = "u"; - protected String password = "p"; - protected String notpassword = "a"; - protected PrincipalDatabase db = new TestPrincipalDatabase(); - - protected byte[] correctresponse; - protected byte[] wrongresponse; - - public void testSucessfulAuth() throws SaslException - { - byte[] resp = this.server.evaluateResponse(correctresponse); - assertNull(resp); - } - - public void testFailAuth() - { - boolean exceptionCaught = false; - try - { - byte[] resp = this.server.evaluateResponse(wrongresponse); - } - catch (SaslException e) - { - assertTrue(e.getMessage().contains("Authentication failed")); - exceptionCaught = true; - } - if (!exceptionCaught) - { - fail("Should have thrown SaslException"); - } - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/SaslUtil.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/SaslUtil.java deleted file mode 100644 index 251ebc4c81..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/SaslUtil.java +++ /dev/null @@ -1,85 +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.security.auth.sasl; - -import java.security.MessageDigest; - -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; - -public class SaslUtil -{ - - private static byte SEPARATOR = 0; - - public static byte[] generatePlainClientResponse(String userName, String userPassword) throws Exception - { - byte[] password = userPassword.getBytes("UTF8"); - byte user[] = userName.getBytes("UTF8"); - byte response[] = new byte[password.length + user.length + 2]; - int size = 0; - response[size++] = SEPARATOR; - System.arraycopy(user, 0, response, size, user.length); - size += user.length; - response[size++] = SEPARATOR; - System.arraycopy(password, 0, response, size, password.length); - return response; - } - - public static byte[] generateCramMD5HexClientResponse(String userName, String userPassword, byte[] challengeBytes) - throws Exception - { - String macAlgorithm = "HmacMD5"; - byte[] digestedPasswordBytes = MessageDigest.getInstance("MD5").digest(userPassword.getBytes("UTF-8")); - byte[] hexEncodedDigestedPasswordBytes = toHex(digestedPasswordBytes).getBytes("UTF-8"); - Mac mac = Mac.getInstance(macAlgorithm); - mac.init(new SecretKeySpec(hexEncodedDigestedPasswordBytes, macAlgorithm)); - final byte[] messageAuthenticationCode = mac.doFinal(challengeBytes); - String responseAsString = userName + " " + toHex(messageAuthenticationCode); - return responseAsString.getBytes(); - } - - public static byte[] generateCramMD5ClientResponse(String userName, String userPassword, byte[] challengeBytes) - throws Exception - { - String macAlgorithm = "HmacMD5"; - Mac mac = Mac.getInstance(macAlgorithm); - mac.init(new SecretKeySpec(userPassword.getBytes("UTF-8"), macAlgorithm)); - final byte[] messageAuthenticationCode = mac.doFinal(challengeBytes); - String responseAsString = userName + " " + toHex(messageAuthenticationCode); - return responseAsString.getBytes(); - } - - public static String toHex(byte[] data) - { - StringBuffer hash = new StringBuffer(); - for (int i = 0; i < data.length; i++) - { - String hex = Integer.toHexString(0xFF & data[i]); - if (hex.length() == 1) - { - hash.append('0'); - } - hash.append(hex); - } - return hash.toString(); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/TestPrincipalDatabase.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/TestPrincipalDatabase.java deleted file mode 100644 index 17c63d738c..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/TestPrincipalDatabase.java +++ /dev/null @@ -1,107 +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.security.auth.sasl; - -import java.io.File; -import java.io.IOException; -import java.security.Principal; -import java.util.List; - -import javax.security.auth.callback.PasswordCallback; -import javax.security.auth.login.AccountNotFoundException; -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; - -import org.apache.qpid.server.security.auth.database.PrincipalDatabase; - -public class TestPrincipalDatabase implements PrincipalDatabase -{ - - public boolean createPrincipal(Principal principal, char[] password) - { - // TODO Auto-generated method stub - return false; - } - - public boolean deletePrincipal(Principal principal) throws AccountNotFoundException - { - // TODO Auto-generated method stub - return false; - } - - public Principal getUser(String username) - { - // TODO Auto-generated method stub - return null; - } - - public List<Principal> getUsers() - { - // TODO Auto-generated method stub - return null; - } - - public void setPassword(Principal principal, PasswordCallback callback) throws IOException, - AccountNotFoundException - { - callback.setPassword("p".toCharArray()); - } - - public boolean updatePassword(Principal principal, char[] password) throws AccountNotFoundException - { - // TODO Auto-generated method stub - return false; - } - - public boolean verifyPassword(String principal, char[] password) throws AccountNotFoundException - { - // TODO Auto-generated method stub - return false; - } - - public void reload() throws IOException - { - // TODO Auto-generated method stub - } - - @Override - public void open(File passwordFile) throws IOException - { - // TODO Auto-generated method stub - } - - @Override - public String getMechanisms() - { - // TODO Auto-generated method stub - return null; - } - - @Override - public SaslServer createSaslServer(String mechanism, String localFQDN, - Principal externalPrincipal) throws SaslException - { - // TODO Auto-generated method stub - return null; - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/amqplain/AMQPlainSaslServerTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/amqplain/AMQPlainSaslServerTest.java deleted file mode 100644 index 6245064bf7..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/amqplain/AMQPlainSaslServerTest.java +++ /dev/null @@ -1,43 +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.security.auth.sasl.amqplain; - -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.FieldTableFactory; -import org.apache.qpid.server.security.auth.sasl.SaslServerTestCase; -import org.apache.qpid.server.security.auth.sasl.UsernamePasswordInitialiser; - -public class AMQPlainSaslServerTest extends SaslServerTestCase -{ - protected void setUp() throws Exception - { - UsernamePasswordInitialiser handler = new AmqPlainInitialiser(); - handler.initialise(db); - this.server = new AmqPlainSaslServer(handler.getCallbackHandler()); - FieldTable table = FieldTableFactory.newFieldTable(); - table.setString("LOGIN", username); - table.setString("PASSWORD", password); - correctresponse = table.getDataAsBytes(); - table.setString("PASSWORD", notpassword); - wrongresponse = table.getDataAsBytes(); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServerTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServerTest.java deleted file mode 100644 index 5dd51250dc..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServerTest.java +++ /dev/null @@ -1,39 +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.security.auth.sasl.plain; - -import org.apache.qpid.server.security.auth.sasl.SaslServerTestCase; -import org.apache.qpid.server.security.auth.sasl.UsernamePasswordInitialiser; - -public class PlainSaslServerTest extends SaslServerTestCase -{ - - protected void setUp() throws Exception - { - UsernamePasswordInitialiser handler = new PlainInitialiser(); - handler.initialise(db); - this.server = new PlainSaslServer(handler.getCallbackHandler()); - correctresponse = new byte[]{0x0, (byte) username.charAt(0), 0x0, (byte) password.charAt(0)}; - wrongresponse = new byte[]{0x0,(byte) username.charAt(0), 0x0, (byte) notpassword.charAt(0)}; - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/group/FileGroupDatabaseTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/group/FileGroupDatabaseTest.java deleted file mode 100644 index b020c1655a..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/group/FileGroupDatabaseTest.java +++ /dev/null @@ -1,456 +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.security.group; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Properties; -import java.util.Set; - -import org.apache.qpid.server.security.group.FileGroupDatabase; - -import junit.framework.TestCase; - -public class FileGroupDatabaseTest extends TestCase -{ - private static final String USER1 = "user1"; - private static final String USER2 = "user2"; - private static final String USER3 = "user3"; - - private static final String MY_GROUP = "myGroup"; - private static final String MY_GROUP2 = "myGroup2"; - private static final String MY_GROUP1 = "myGroup1"; - - private FileGroupDatabase _groupDatabase = new FileGroupDatabase(); - private String _groupFile; - - public void testGetAllGroups() throws Exception - { - writeAndSetGroupFile("myGroup.users", USER1); - - Set<String> groups = _groupDatabase.getAllGroups(); - assertEquals(1, groups.size()); - assertTrue(groups.contains(MY_GROUP)); - } - - public void testGetAllGroupsWhenGroupFileEmpty() throws Exception - { - _groupDatabase.setGroupFile(_groupFile); - - Set<String> groups = _groupDatabase.getAllGroups(); - assertEquals(0, groups.size()); - } - - public void testMissingGroupFile() throws Exception - { - try - { - _groupDatabase.setGroupFile("/not/a/file"); - fail("Exception not thrown"); - } - catch (FileNotFoundException fnfe) - { - // PASS - } - } - - public void testInvalidFormat() throws Exception - { - writeGroupFile("name.notvalid", USER1); - - try - { - _groupDatabase.setGroupFile(_groupFile); - fail("Exception not thrown"); - } - catch (IllegalArgumentException gde) - { - // PASS - } - } - - public void testGetUsersInGroup() throws Exception - { - writeGroupFile("myGroup.users", "user1,user2,user3"); - - _groupDatabase.setGroupFile(_groupFile); - - Set<String> users = _groupDatabase.getUsersInGroup(MY_GROUP); - assertNotNull(users); - assertEquals(3, users.size()); - } - - public void testDuplicateUsersInGroupAreConflated() throws Exception - { - writeAndSetGroupFile("myGroup.users", "user1,user1,user3,user1"); - - Set<String> users = _groupDatabase.getUsersInGroup(MY_GROUP); - assertNotNull(users); - assertEquals(2, users.size()); - } - - public void testGetUsersWithEmptyGroup() throws Exception - { - writeAndSetGroupFile("myGroup.users", ""); - - Set<String> users = _groupDatabase.getUsersInGroup(MY_GROUP); - assertNotNull(users); - assertTrue(users.isEmpty()); - } - - public void testGetUsersInNonExistentGroup() throws Exception - { - writeAndSetGroupFile("myGroup.users", "user1,user2,user3"); - - Set<String> users = _groupDatabase.getUsersInGroup("groupDoesntExist"); - assertNotNull(users); - assertTrue(users.isEmpty()); - } - - public void testGetUsersInNullGroup() throws Exception - { - writeAndSetGroupFile(); - assertTrue(_groupDatabase.getUsersInGroup(null).isEmpty()); - } - - public void testGetGroupPrincipalsForUserWhenUserBelongsToOneGroup() throws Exception - { - writeAndSetGroupFile("myGroup.users", "user1,user2"); - Set<String> groups = _groupDatabase.getGroupsForUser(USER1); - assertEquals(1, groups.size()); - assertTrue(groups.contains(MY_GROUP)); - } - - public void testGetGroupPrincipalsForUserWhenUserBelongsToTwoGroup() throws Exception - { - writeAndSetGroupFile("myGroup1.users", "user1,user2", - "myGroup2.users", "user1,user3"); - Set<String> groups = _groupDatabase.getGroupsForUser(USER1); - assertEquals(2, groups.size()); - assertTrue(groups.contains(MY_GROUP1)); - assertTrue(groups.contains(MY_GROUP2)); - } - - public void testGetGroupPrincipalsForUserWhenUserAddedToGroup() throws Exception - { - writeAndSetGroupFile("myGroup1.users", "user1,user2", - "myGroup2.users", USER2); - Set<String> groups = _groupDatabase.getGroupsForUser(USER1); - assertEquals(1, groups.size()); - assertTrue(groups.contains(MY_GROUP1)); - - _groupDatabase.addUserToGroup(USER1, MY_GROUP2); - - groups = _groupDatabase.getGroupsForUser(USER1); - assertEquals(2, groups.size()); - assertTrue(groups.contains(MY_GROUP1)); - assertTrue(groups.contains(MY_GROUP2)); - - Set<String> users = _groupDatabase.getUsersInGroup(MY_GROUP2); - assertEquals(2, users.size()); - assertTrue(users.contains(USER1)); - assertTrue(users.contains(USER2)); - } - - public void testGetGroupPrincipalsForUserWhenUserRemovedFromGroup() throws Exception - { - writeAndSetGroupFile("myGroup1.users", "user1,user2", - "myGroup2.users", "user1,user2"); - Set<String> groups = _groupDatabase.getGroupsForUser(USER1); - assertEquals(2, groups.size()); - assertTrue(groups.contains(MY_GROUP1)); - assertTrue(groups.contains(MY_GROUP2)); - - _groupDatabase.removeUserFromGroup(USER1, MY_GROUP2); - - groups = _groupDatabase.getGroupsForUser(USER1); - assertEquals(1, groups.size()); - assertTrue(groups.contains(MY_GROUP1)); - } - - public void testGetGroupPrincipalsForUserWhenUserAdddedToGroupTheyAreAlreadyIn() throws Exception - { - writeAndSetGroupFile("myGroup.users", USER1); - _groupDatabase.addUserToGroup(USER1, MY_GROUP); - - Set<String> groups = _groupDatabase.getGroupsForUser(USER1); - - assertEquals(1, groups.size()); - assertTrue(groups.contains(MY_GROUP)); - - Set<String> users = _groupDatabase.getUsersInGroup(MY_GROUP); - assertEquals(1, users.size()); - assertTrue(users.contains(USER1)); - } - - public void testGetGroupPrincipalsForUserWhenUserNotKnown() throws Exception - { - writeAndSetGroupFile("myGroup.users", "user1,user2"); - Set<String> groups = _groupDatabase.getGroupsForUser(USER3); - assertEquals(0, groups.size()); - } - - public void testGetGroupPrincipalsForNullUser() throws Exception - { - writeAndSetGroupFile(); - assertTrue(_groupDatabase.getGroupsForUser(null).isEmpty()); - } - - public void testAddUserToExistingGroup() throws Exception - { - writeAndSetGroupFile("myGroup.users", "user1,user2"); - - Set<String> users = _groupDatabase.getUsersInGroup(MY_GROUP); - assertNotNull(users); - assertEquals(2, users.size()); - - _groupDatabase.addUserToGroup(USER3, MY_GROUP); - - users = _groupDatabase.getUsersInGroup(MY_GROUP); - assertNotNull(users); - assertEquals(3, users.size()); - } - - public void testAddUserToEmptyGroup() throws Exception - { - writeAndSetGroupFile("myGroup.users", ""); - - Set<String> users = _groupDatabase.getUsersInGroup(MY_GROUP); - assertNotNull(users); - assertEquals(0, users.size()); - - _groupDatabase.addUserToGroup(USER3, MY_GROUP); - - users = _groupDatabase.getUsersInGroup(MY_GROUP); - assertNotNull(users); - assertEquals(1, users.size()); - } - - public void testAddUserToNonExistentGroup() throws Exception - { - writeAndSetGroupFile(); - - Set<String> users = _groupDatabase.getUsersInGroup(MY_GROUP); - assertNotNull(users); - assertEquals(0, users.size()); - - try - { - _groupDatabase.addUserToGroup(USER3, MY_GROUP); - fail("Expected exception not thrown"); - } - catch(IllegalArgumentException e) - { - // pass - } - - users = _groupDatabase.getUsersInGroup(MY_GROUP); - assertNotNull(users); - assertEquals(0, users.size()); - } - - public void testRemoveUserFromExistingGroup() throws Exception - { - writeAndSetGroupFile("myGroup.users", "user1,user2"); - - Set<String> users = _groupDatabase.getUsersInGroup(MY_GROUP); - assertNotNull(users); - assertEquals(2, users.size()); - - _groupDatabase.removeUserFromGroup(USER2, MY_GROUP); - - users = _groupDatabase.getUsersInGroup(MY_GROUP); - assertNotNull(users); - assertEquals(1, users.size()); - } - - public void testRemoveUserFromNonexistentGroup() throws Exception - { - writeAndSetGroupFile(); - - try - { - _groupDatabase.removeUserFromGroup(USER1, MY_GROUP); - fail("Expected exception not thrown"); - } - catch(IllegalArgumentException e) - { - // pass - } - - assertTrue(_groupDatabase.getUsersInGroup(MY_GROUP).isEmpty()); - } - - public void testRemoveUserFromGroupTwice() throws Exception - { - writeAndSetGroupFile("myGroup.users", USER1); - assertTrue(_groupDatabase.getUsersInGroup(MY_GROUP).contains(USER1)); - - _groupDatabase.removeUserFromGroup(USER1, MY_GROUP); - assertTrue(_groupDatabase.getUsersInGroup(MY_GROUP).isEmpty()); - - _groupDatabase.removeUserFromGroup(USER1, MY_GROUP); - assertTrue(_groupDatabase.getUsersInGroup(MY_GROUP).isEmpty()); - } - - public void testAddUserPersistedToFile() throws Exception - { - writeAndSetGroupFile("myGroup.users", "user1,user2"); - - Set<String> users = _groupDatabase.getUsersInGroup(MY_GROUP); - assertEquals(2, users.size()); - - _groupDatabase.addUserToGroup(USER3, MY_GROUP); - assertEquals(3, users.size()); - - FileGroupDatabase newGroupDatabase = new FileGroupDatabase(); - newGroupDatabase.setGroupFile(_groupFile); - - Set<String> newUsers = newGroupDatabase.getUsersInGroup(MY_GROUP); - assertEquals(users.size(), newUsers.size()); - } - - public void testRemoveUserPersistedToFile() throws Exception - { - writeAndSetGroupFile("myGroup.users", "user1,user2"); - - Set<String> users = _groupDatabase.getUsersInGroup(MY_GROUP); - assertEquals(2, users.size()); - - _groupDatabase.removeUserFromGroup(USER2, MY_GROUP); - assertEquals(1, users.size()); - - FileGroupDatabase newGroupDatabase = new FileGroupDatabase(); - newGroupDatabase.setGroupFile(_groupFile); - - Set<String> newUsers = newGroupDatabase.getUsersInGroup(MY_GROUP); - assertEquals(users.size(), newUsers.size()); - } - - public void testCreateGroupPersistedToFile() throws Exception - { - writeAndSetGroupFile(); - - Set<String> groups = _groupDatabase.getAllGroups(); - assertEquals(0, groups.size()); - - _groupDatabase.createGroup(MY_GROUP); - - groups = _groupDatabase.getAllGroups(); - assertEquals(1, groups.size()); - assertTrue(groups.contains(MY_GROUP)); - - FileGroupDatabase newGroupDatabase = new FileGroupDatabase(); - newGroupDatabase.setGroupFile(_groupFile); - - Set<String> newGroups = newGroupDatabase.getAllGroups(); - assertEquals(1, newGroups.size()); - assertTrue(newGroups.contains(MY_GROUP)); - } - - public void testRemoveGroupPersistedToFile() throws Exception - { - writeAndSetGroupFile("myGroup1.users", "user1,user2", - "myGroup2.users", "user1,user2"); - - Set<String> groups = _groupDatabase.getAllGroups(); - assertEquals(2, groups.size()); - - Set<String> groupsForUser1 = _groupDatabase.getGroupsForUser(USER1); - assertEquals(2, groupsForUser1.size()); - - _groupDatabase.removeGroup(MY_GROUP1); - - groups = _groupDatabase.getAllGroups(); - assertEquals(1, groups.size()); - assertTrue(groups.contains(MY_GROUP2)); - - groupsForUser1 = _groupDatabase.getGroupsForUser(USER1); - assertEquals(1, groupsForUser1.size()); - - FileGroupDatabase newGroupDatabase = new FileGroupDatabase(); - newGroupDatabase.setGroupFile(_groupFile); - - Set<String> newGroups = newGroupDatabase.getAllGroups(); - assertEquals(1, newGroups.size()); - assertTrue(newGroups.contains(MY_GROUP2)); - - Set<String> newGroupsForUser1 = newGroupDatabase.getGroupsForUser(USER1); - assertEquals(1, newGroupsForUser1.size()); - assertTrue(newGroupsForUser1.contains(MY_GROUP2)); -} - - @Override - protected void setUp() throws Exception - { - super.setUp(); - _groupFile = createEmptyTestGroupFile(); - } - - private void writeAndSetGroupFile(String... groupAndUsers) throws Exception - { - writeGroupFile(groupAndUsers); - _groupDatabase.setGroupFile(_groupFile); - } - - private void writeGroupFile(String... groupAndUsers) throws Exception - { - if (groupAndUsers.length % 2 != 0) - { - throw new IllegalArgumentException("Number of groupAndUsers must be even"); - } - - Properties props = new Properties(); - for (int i = 0 ; i < groupAndUsers.length; i=i+2) - { - String group = groupAndUsers[i]; - String users = groupAndUsers[i+1]; - props.put(group, users); - } - - props.store(new FileOutputStream(_groupFile), "test group file"); - } - - private String createEmptyTestGroupFile() throws IOException - { - File tmpGroupFile = File.createTempFile("groups", "grp"); - tmpGroupFile.deleteOnExit(); - - return tmpGroupFile.getAbsolutePath(); - } - - @Override - protected void tearDown() throws Exception - { - super.tearDown(); - - if (_groupFile != null) - { - File groupFile = new File(_groupFile); - if (groupFile.exists()) - { - groupFile.delete(); - } - } - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/group/FileGroupManagerFactoryTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/group/FileGroupManagerFactoryTest.java deleted file mode 100644 index 90308d316b..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/group/FileGroupManagerFactoryTest.java +++ /dev/null @@ -1,77 +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.security.group; - -import java.util.HashMap; -import java.util.Map; - -import junit.framework.TestCase; - -import org.apache.qpid.server.model.GroupProvider; -import org.apache.qpid.test.utils.TestFileUtils; - -public class FileGroupManagerFactoryTest extends TestCase -{ - - private FileGroupManagerFactory _factory = new FileGroupManagerFactory(); - private Map<String, Object> _configuration = new HashMap<String, Object>(); - private String _emptyButValidGroupFile = TestFileUtils.createTempFile(this).getAbsolutePath(); - - public void testInstanceCreated() throws Exception - { - _configuration.put(GroupProvider.TYPE, FileGroupManagerFactory.GROUP_FILE_PROVIDER_TYPE); - _configuration.put(FileGroupManagerFactory.PATH, _emptyButValidGroupFile); - - GroupManager manager = _factory.createInstance(_configuration); - assertNotNull(manager); - assertTrue(manager instanceof FileGroupManager); - } - - public void testReturnsNullWhenNoConfig() throws Exception - { - GroupManager manager = _factory.createInstance(_configuration); - assertNull(manager); - } - - public void testReturnsNullWhenConfigNotForThisPlugin() throws Exception - { - _configuration.put(GroupProvider.TYPE, "other-group-manager"); - - GroupManager manager = _factory.createInstance(_configuration); - assertNull(manager); - } - - - public void testRejectsConfigThatIsMissingAttributeValue() throws Exception - { - _configuration.put(GroupProvider.TYPE, FileGroupManagerFactory.GROUP_FILE_PROVIDER_TYPE); - _configuration.put(FileGroupManagerFactory.PATH, null); - - try - { - _factory.createInstance(_configuration); - fail("Exception not thrown"); - } - catch (RuntimeException re) - { - // PASS - } - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/group/FileGroupManagerTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/group/FileGroupManagerTest.java deleted file mode 100644 index 152703d548..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/group/FileGroupManagerTest.java +++ /dev/null @@ -1,204 +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.security.group; - -import java.io.File; -import java.io.FileOutputStream; -import java.security.Principal; -import java.util.Properties; -import java.util.Set; - -import org.apache.qpid.server.security.auth.UsernamePrincipal; -import org.apache.qpid.test.utils.QpidTestCase; - -public class FileGroupManagerTest extends QpidTestCase -{ - private static final String MYGROUP_USERS = "user1"; - private static final String MY_GROUP = "myGroup.users"; - private static final String MY_GROUP2 = "myGroup2.users"; - private File _tmpGroupFile; - private FileGroupManager _manager; - - @Override - public void tearDown() throws Exception - { - super.tearDown(); - - if (_tmpGroupFile != null) - { - if (_tmpGroupFile.exists()) - { - _tmpGroupFile.delete(); - } - } - } - - public void testValidGroupFile() throws Exception - { - final String groupFileName = writeGroupFile(); - - _manager = new FileGroupManager(groupFileName); - assertNotNull(_manager); - } - - public void testNonExistentGroupFile() throws Exception - { - final String filePath = TMP_FOLDER + File.separator + "non.existing"; - File file = new File(filePath); - if (file.exists()) - { - file.delete(); - } - assertFalse("File should not exist", file.exists()); - try - { - _manager = new FileGroupManager(filePath); - assertFalse("File should be created", file.exists()); - _manager.onCreate(); - assertTrue("File should be created", file.exists()); - _manager.open(); - Set<Principal> groups = _manager.getGroupPrincipals(); - assertTrue("No group should exist", groups.isEmpty()); - } - finally - { - file.delete(); - } - } - - public void testGetGroupPrincipalsForUser() throws Exception - { - final String groupFileName = writeGroupFile(); - _manager = new FileGroupManager(groupFileName); - _manager.open(); - Set<Principal> principals = _manager.getGroupPrincipalsForUser("user1"); - assertEquals(1, principals.size()); - assertTrue(principals.contains(new GroupPrincipal("myGroup"))); - } - - public void testGetUserPrincipalsForGroup() throws Exception - { - final String groupFileName = writeGroupFile(); - _manager = new FileGroupManager(groupFileName); - _manager.open(); - Set<Principal> principals = _manager.getUserPrincipalsForGroup("myGroup"); - assertEquals(1, principals.size()); - assertTrue(principals.contains(new UsernamePrincipal("user1"))); - } - - public void testGetGroupPrincipals() throws Exception - { - final String groupFileName = writeGroupFile(MY_GROUP, MYGROUP_USERS, MY_GROUP2, MYGROUP_USERS); - _manager = new FileGroupManager(groupFileName); - _manager.open(); - Set<Principal> principals = _manager.getGroupPrincipals(); - assertEquals(2, principals.size()); - assertTrue(principals.contains(new GroupPrincipal("myGroup"))); - assertTrue(principals.contains(new GroupPrincipal("myGroup2"))); - } - - public void testCreateGroup() throws Exception - { - final String groupFileName = writeGroupFile(); - _manager = new FileGroupManager(groupFileName); - _manager.open(); - Set<Principal> principals = _manager.getGroupPrincipals(); - assertEquals(1, principals.size()); - - _manager.createGroup("myGroup2"); - - principals = _manager.getGroupPrincipals(); - assertEquals(2, principals.size()); - assertTrue(principals.contains(new GroupPrincipal("myGroup2"))); - } - - public void testRemoveGroup() throws Exception - { - final String groupFileName = writeGroupFile(MY_GROUP, MYGROUP_USERS); - _manager = new FileGroupManager(groupFileName); - _manager.open(); - Set<Principal> principals = _manager.getGroupPrincipals(); - assertEquals(1, principals.size()); - - _manager.removeGroup("myGroup"); - - principals = _manager.getGroupPrincipals(); - assertEquals(0, principals.size()); - } - - public void testAddUserToGroup() throws Exception - { - final String groupFileName = writeGroupFile(MY_GROUP, MYGROUP_USERS); - _manager = new FileGroupManager(groupFileName); - _manager.open(); - Set<Principal> principals = _manager.getUserPrincipalsForGroup("myGroup"); - assertEquals(1, principals.size()); - assertFalse(principals.contains(new UsernamePrincipal("user2"))); - - _manager.addUserToGroup("user2", "myGroup"); - - principals = _manager.getUserPrincipalsForGroup("myGroup"); - assertEquals(2, principals.size()); - assertTrue(principals.contains(new UsernamePrincipal("user2"))); - } - - public void testRemoveUserInGroup() throws Exception - { - final String groupFileName = writeGroupFile(MY_GROUP, MYGROUP_USERS); - _manager = new FileGroupManager(groupFileName); - _manager.open(); - Set<Principal> principals = _manager.getUserPrincipalsForGroup("myGroup"); - assertEquals(1, principals.size()); - assertTrue(principals.contains(new UsernamePrincipal("user1"))); - - _manager.removeUserFromGroup("user1", "myGroup"); - - principals = _manager.getUserPrincipalsForGroup("myGroup"); - assertEquals(0, principals.size()); - } - - private String writeGroupFile() throws Exception - { - return writeGroupFile(MY_GROUP, MYGROUP_USERS); - } - - private String writeGroupFile(String... groupAndUsers) throws Exception - { - if (groupAndUsers.length % 2 != 0) - { - throw new IllegalArgumentException("Number of groupAndUsers must be even"); - } - - _tmpGroupFile = File.createTempFile("groups", "grp"); - _tmpGroupFile.deleteOnExit(); - - Properties props = new Properties(); - for (int i = 0 ; i < groupAndUsers.length; i=i+2) - { - String group = groupAndUsers[i]; - String users = groupAndUsers[i+1]; - props.put(group, users); - } - - props.store(new FileOutputStream(_tmpGroupFile), "test group file"); - - return _tmpGroupFile.getCanonicalPath(); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/group/GroupPrincipalTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/group/GroupPrincipalTest.java deleted file mode 100644 index d285a0797a..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/group/GroupPrincipalTest.java +++ /dev/null @@ -1,88 +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.security.group; - -import org.apache.qpid.server.security.auth.UsernamePrincipal; - -import junit.framework.TestCase; - -public class GroupPrincipalTest extends TestCase -{ - public void testGetName() - { - final GroupPrincipal principal = new GroupPrincipal("group"); - assertEquals("group", principal.getName()); - } - - public void testAddRejected() - { - final GroupPrincipal principal = new GroupPrincipal("group"); - final UsernamePrincipal user = new UsernamePrincipal("name"); - - try - { - principal.addMember(user); - fail("Exception not thrown"); - } - catch (UnsupportedOperationException uso) - { - // PASS - } - } - - public void testEqualitySameName() - { - final String string = "string"; - final GroupPrincipal principal1 = new GroupPrincipal(string); - final GroupPrincipal principal2 = new GroupPrincipal(string); - assertTrue(principal1.equals(principal2)); - } - - public void testEqualityEqualName() - { - final GroupPrincipal principal1 = new GroupPrincipal(new String("string")); - final GroupPrincipal principal2 = new GroupPrincipal(new String("string")); - assertTrue(principal1.equals(principal2)); - } - - public void testInequalityDifferentGroupPrincipals() - { - GroupPrincipal principal1 = new GroupPrincipal("string1"); - GroupPrincipal principal2 = new GroupPrincipal("string2"); - assertFalse(principal1.equals(principal2)); - } - - public void testInequalityNonGroupPrincipal() - { - GroupPrincipal principal = new GroupPrincipal("string"); - assertFalse(principal.equals(new UsernamePrincipal("string"))); - } - - public void testInequalityNull() - { - GroupPrincipal principal = new GroupPrincipal("string"); - assertFalse(principal.equals(null)); - } - - - - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/stats/StatisticsCounterTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/stats/StatisticsCounterTest.java deleted file mode 100644 index 147879f5e8..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/stats/StatisticsCounterTest.java +++ /dev/null @@ -1,149 +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.stats; - -import junit.framework.TestCase; - -/** - * Unit tests for the {@link StatisticsCounter} class. - */ -public class StatisticsCounterTest extends TestCase -{ - /** - * Check that statistics counters are created correctly. - */ - public void testCreate() - { - long before = System.currentTimeMillis(); - StatisticsCounter counter = new StatisticsCounter("name", 1234L); - long after = System.currentTimeMillis(); - - assertTrue(before <= counter.getStart()); - assertTrue(after >= counter.getStart()); - assertTrue(counter.getName().startsWith("name-")); - assertEquals(1234L, counter.getPeriod()); - } - - /** - * Check that totals add up correctly. - */ - public void testTotal() - { - StatisticsCounter counter = new StatisticsCounter("test", 1000L); - long start = counter.getStart(); - for (int i = 0; i < 100; i++) - { - counter.registerEvent(i, start + i); - } - assertEquals(99 * 50, counter.getTotal()); // cf. Gauss - } - - /** - * Test totals add up correctly even when messages are delivered - * out-of-order. - */ - public void testTotalOutOfOrder() - { - StatisticsCounter counter = new StatisticsCounter("test", 1000L); - long start = counter.getStart(); - assertEquals(0, counter.getTotal()); - counter.registerEvent(10, start + 2500); - assertEquals(10, counter.getTotal()); - counter.registerEvent(20, start + 1500); - assertEquals(30, counter.getTotal()); - counter.registerEvent(10, start + 500); - assertEquals(40, counter.getTotal()); - } - - /** - * Test that the peak rate is reported correctly. - */ - public void testPeak() throws Exception - { - StatisticsCounter counter = new StatisticsCounter("test", 1000L); - long start = counter.getStart(); - assertEquals(0.0, counter.getPeak()); - Thread.sleep(500); - counter.registerEvent(1000, start + 500); - Thread.sleep(1000); - assertEquals(1000.0, counter.getPeak()); - counter.registerEvent(2000, start + 1500); - Thread.sleep(1000); - assertEquals(2000.0, counter.getPeak()); - counter.registerEvent(1000, start + 2500); - Thread.sleep(1000); - assertEquals(2000.0, counter.getPeak()); - } - - /** - * Test that peak rate is reported correctly for out-of-order messages, - * and the total is also unaffected. - */ - public void testPeakOutOfOrder() throws Exception - { - StatisticsCounter counter = new StatisticsCounter("test", 1000L); - long start = counter.getStart(); - assertEquals(0.0, counter.getPeak()); - counter.registerEvent(1000, start + 2500); - Thread.sleep(1500); - assertEquals(0.0, counter.getPeak()); - counter.registerEvent(2000, start + 1500); - - // make sure, that getPeak invocation occurs at "start + 2500" - // if test thread over-sleeps for 500+ mls - // the peak value can be incremented and test will fail - long sleep = start + 2500 - System.currentTimeMillis(); - Thread.sleep(sleep < 0 ? 0 : sleep); - assertEquals(0.0, counter.getPeak()); - counter.registerEvent(1000, start + 500); - Thread.sleep(1500); - assertEquals(4000.0, counter.getPeak()); - Thread.sleep(2000); - assertEquals(4000.0, counter.getPeak()); - counter.registerEvent(1000, start + 500); - assertEquals(4000.0, counter.getPeak()); - Thread.sleep(2000); - counter.registerEvent(1000); - assertEquals(4000.0, counter.getPeak()); - assertEquals(6000, counter.getTotal()); - } - - /** - * Test the current rate is generated correctly. - */ - public void testRate() throws Exception - { - StatisticsCounter counter = new StatisticsCounter("test", 1000L); - assertEquals(0.0, counter.getRate()); - Thread.sleep(500); - counter.registerEvent(1000); - Thread.sleep(1000); - assertEquals(1000.0, counter.getRate()); - counter.registerEvent(2000); - Thread.sleep(1000); - assertEquals(2000.0, counter.getRate()); - counter.registerEvent(1000); - Thread.sleep(1000); - assertEquals(1000.0, counter.getRate()); - Thread.sleep(1000); - assertEquals(0.0, counter.getRate()); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/store/AbstractDurableConfigurationStoreTestCase.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/store/AbstractDurableConfigurationStoreTestCase.java deleted file mode 100644 index fd8148f2ce..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/store/AbstractDurableConfigurationStoreTestCase.java +++ /dev/null @@ -1,520 +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; - -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyMap; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.mockito.Mockito.times; - -import java.io.File; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.apache.commons.configuration.Configuration; -import org.apache.qpid.AMQStoreException; -import org.apache.qpid.common.AMQPFilterTypes; -import org.apache.qpid.server.binding.Binding; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.message.EnqueableMessage; -import org.apache.qpid.server.model.LifetimePolicy; -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.model.UUIDGenerator; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.store.MessageStoreRecoveryHandler.StoredMessageRecoveryHandler; -import org.apache.qpid.server.store.Transaction.Record; -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.util.FileUtils; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -public abstract class AbstractDurableConfigurationStoreTestCase extends QpidTestCase -{ - private static final String EXCHANGE_NAME = "exchangeName"; - - private static final String EXCHANGE = org.apache.qpid.server.model.Exchange.class.getSimpleName(); - private static final String BINDING = org.apache.qpid.server.model.Binding.class.getSimpleName(); - private static final String QUEUE = Queue.class.getSimpleName(); - - private String _storePath; - private String _storeName; - private MessageStore _messageStore; - private Configuration _configuration; - private VirtualHost _virtualHost; - - private ConfigurationRecoveryHandler _recoveryHandler; - private MessageStoreRecoveryHandler _messageStoreRecoveryHandler; - private StoredMessageRecoveryHandler _storedMessageRecoveryHandler; - private TransactionLogRecoveryHandler _logRecoveryHandler; - private TransactionLogRecoveryHandler.QueueEntryRecoveryHandler _queueEntryRecoveryHandler; - private TransactionLogRecoveryHandler.DtxRecordRecoveryHandler _dtxRecordRecoveryHandler; - - private Exchange _exchange = mock(Exchange.class); - private static final String ROUTING_KEY = "routingKey"; - private static final String QUEUE_NAME = "queueName"; - private Map<String,Object> _bindingArgs; - private UUID _queueId; - private UUID _exchangeId; - private DurableConfigurationStore _configStore; - - public void setUp() throws Exception - { - super.setUp(); - - _queueId = UUIDGenerator.generateRandomUUID(); - _exchangeId = UUIDGenerator.generateRandomUUID(); - - _storeName = getName(); - _storePath = TMP_FOLDER + File.separator + _storeName; - FileUtils.delete(new File(_storePath), true); - setTestSystemProperty("QPID_WORK", TMP_FOLDER); - _configuration = mock(Configuration.class); - _recoveryHandler = mock(ConfigurationRecoveryHandler.class); - _storedMessageRecoveryHandler = mock(StoredMessageRecoveryHandler.class); - _logRecoveryHandler = mock(TransactionLogRecoveryHandler.class); - _messageStoreRecoveryHandler = mock(MessageStoreRecoveryHandler.class); - _queueEntryRecoveryHandler = mock(TransactionLogRecoveryHandler.QueueEntryRecoveryHandler.class); - _dtxRecordRecoveryHandler = mock(TransactionLogRecoveryHandler.DtxRecordRecoveryHandler.class); - _virtualHost = mock(VirtualHost.class); - - when(_messageStoreRecoveryHandler.begin()).thenReturn(_storedMessageRecoveryHandler); - when(_logRecoveryHandler.begin(any(MessageStore.class))).thenReturn(_queueEntryRecoveryHandler); - when(_queueEntryRecoveryHandler.completeQueueEntryRecovery()).thenReturn(_dtxRecordRecoveryHandler); - when(_exchange.getName()).thenReturn(EXCHANGE_NAME); - - when(_exchange.getId()).thenReturn(_exchangeId); - when(_configuration.getString(eq(MessageStoreConstants.ENVIRONMENT_PATH_PROPERTY), anyString())).thenReturn( - _storePath); - when(_virtualHost.getAttribute(eq(VirtualHost.STORE_PATH))).thenReturn(_storePath); - - _bindingArgs = new HashMap<String, Object>(); - String argKey = AMQPFilterTypes.JMS_SELECTOR.toString(); - String argValue = "some selector expression"; - _bindingArgs.put(argKey, argValue); - - reopenStore(); - } - - public void tearDown() throws Exception - { - try - { - closeMessageStore(); - closeConfigStore(); - FileUtils.delete(new File(_storePath), true); - } - finally - { - super.tearDown(); - } - } - - public void testCreateExchange() throws Exception - { - Exchange exchange = createTestExchange(); - DurableConfigurationStoreHelper.createExchange(_configStore, exchange); - - reopenStore(); - verify(_recoveryHandler).configuredObject(eq(_exchangeId), eq(EXCHANGE), - eq(map( org.apache.qpid.server.model.Exchange.NAME, getName(), - org.apache.qpid.server.model.Exchange.TYPE, getName()+"Type", - org.apache.qpid.server.model.Exchange.LIFETIME_POLICY, LifetimePolicy.AUTO_DELETE.toString()))); - } - - private Map<String,Object> map(Object... vals) - { - Map<String,Object> map = new HashMap<String, Object>(); - boolean isValue = false; - String key = null; - for(Object obj : vals) - { - if(isValue) - { - map.put(key,obj); - } - else - { - key = (String) obj; - } - isValue = !isValue; - } - return map; - } - - public void testRemoveExchange() throws Exception - { - Exchange exchange = createTestExchange(); - DurableConfigurationStoreHelper.createExchange(_configStore, exchange); - - DurableConfigurationStoreHelper.removeExchange(_configStore, exchange); - - reopenStore(); - verify(_recoveryHandler, never()).configuredObject(any(UUID.class), anyString(), anyMap()); - } - - public void testBindQueue() throws Exception - { - AMQQueue queue = createTestQueue(QUEUE_NAME, "queueOwner", false, null); - Binding binding = new Binding(UUIDGenerator.generateRandomUUID(), ROUTING_KEY, queue, - _exchange, _bindingArgs); - DurableConfigurationStoreHelper.createBinding(_configStore, binding); - - reopenStore(); - - Map<String,Object> map = new HashMap<String, Object>(); - map.put(org.apache.qpid.server.model.Binding.EXCHANGE, _exchange.getId().toString()); - map.put(org.apache.qpid.server.model.Binding.QUEUE, queue.getId().toString()); - map.put(org.apache.qpid.server.model.Binding.NAME, ROUTING_KEY); - map.put(org.apache.qpid.server.model.Binding.ARGUMENTS,_bindingArgs); - - verify(_recoveryHandler).configuredObject(eq(binding.getId()), eq(BINDING), - eq(map)); - } - - public void testUnbindQueue() throws Exception - { - AMQQueue queue = createTestQueue(QUEUE_NAME, "queueOwner", false, null); - Binding binding = new Binding(UUIDGenerator.generateRandomUUID(), ROUTING_KEY, queue, - _exchange, _bindingArgs); - DurableConfigurationStoreHelper.createBinding(_configStore, binding); - - DurableConfigurationStoreHelper.removeBinding(_configStore, binding); - reopenStore(); - - verify(_recoveryHandler, never()).configuredObject(any(UUID.class), - eq(BINDING), - anyMap()); - } - - public void testCreateQueueAMQQueue() throws Exception - { - AMQQueue queue = createTestQueue(getName(), getName() + "Owner", true, null); - DurableConfigurationStoreHelper.createQueue(_configStore, queue); - - reopenStore(); - Map<String, Object> queueAttributes = new HashMap<String, Object>(); - queueAttributes.put(Queue.NAME, getName()); - queueAttributes.put(Queue.OWNER, getName()+"Owner"); - queueAttributes.put(Queue.EXCLUSIVE, Boolean.TRUE); - verify(_recoveryHandler).configuredObject(eq(_queueId), eq(QUEUE), eq(queueAttributes)); - } - - public void testCreateQueueAMQQueueFieldTable() throws Exception - { - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(Queue.CREATE_DLQ_ON_CREATION, Boolean.TRUE); - attributes.put(Queue.MAXIMUM_DELIVERY_ATTEMPTS, 10); - AMQQueue queue = createTestQueue(getName(), getName() + "Owner", true, attributes); - - DurableConfigurationStoreHelper.createQueue(_configStore, queue); - - reopenStore(); - - - Map<String,Object> queueAttributes = new HashMap<String, Object>(); - - queueAttributes.put(Queue.NAME, getName()); - queueAttributes.put(Queue.OWNER, getName()+"Owner"); - queueAttributes.put(Queue.EXCLUSIVE, Boolean.TRUE); - queueAttributes.putAll(attributes); - - verify(_recoveryHandler).configuredObject(eq(_queueId), eq(QUEUE), eq(queueAttributes)); - } - - public void testCreateQueueAMQQueueWithAlternateExchange() throws Exception - { - Exchange alternateExchange = createTestAlternateExchange(); - - AMQQueue queue = createTestQueue(getName(), getName() + "Owner", true, alternateExchange, null); - DurableConfigurationStoreHelper.createQueue(_configStore, queue); - - reopenStore(); - - Map<String, Object> queueAttributes = new HashMap<String, Object>(); - queueAttributes.put(Queue.NAME, getName()); - queueAttributes.put(Queue.OWNER, getName()+"Owner"); - queueAttributes.put(Queue.EXCLUSIVE, Boolean.TRUE); - queueAttributes.put(Queue.ALTERNATE_EXCHANGE, alternateExchange.getId().toString()); - - verify(_recoveryHandler).configuredObject(eq(_queueId), eq(QUEUE), eq(queueAttributes)); - } - - 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 - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(Queue.CREATE_DLQ_ON_CREATION, Boolean.TRUE); - attributes.put(Queue.MAXIMUM_DELIVERY_ATTEMPTS, 10); - AMQQueue queue = createTestQueue(getName(), getName() + "Owner", true, attributes); - - DurableConfigurationStoreHelper.createQueue(_configStore, queue); - - // update the queue to have exclusive=false - queue = createTestQueue(getName(), getName() + "Owner", false, attributes); - - DurableConfigurationStoreHelper.updateQueue(_configStore, queue); - - reopenStore(); - - Map<String,Object> queueAttributes = new HashMap<String, Object>(); - - queueAttributes.put(Queue.NAME, getName()); - queueAttributes.put(Queue.OWNER, getName()+"Owner"); - queueAttributes.put(Queue.EXCLUSIVE, Boolean.FALSE); - queueAttributes.putAll(attributes); - - verify(_recoveryHandler).configuredObject(eq(_queueId), eq(QUEUE), eq(queueAttributes)); - - } - - public void testUpdateQueueAlternateExchange() throws Exception - { - // create queue - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(Queue.CREATE_DLQ_ON_CREATION, Boolean.TRUE); - attributes.put(Queue.MAXIMUM_DELIVERY_ATTEMPTS, 10); - AMQQueue queue = createTestQueue(getName(), getName() + "Owner", true, attributes); - DurableConfigurationStoreHelper.createQueue(_configStore, queue); - - // update the queue to have exclusive=false - Exchange alternateExchange = createTestAlternateExchange(); - queue = createTestQueue(getName(), getName() + "Owner", false, alternateExchange, attributes); - - DurableConfigurationStoreHelper.updateQueue(_configStore, queue); - - reopenStore(); - - Map<String,Object> queueAttributes = new HashMap<String, Object>(); - - queueAttributes.put(Queue.NAME, getName()); - queueAttributes.put(Queue.OWNER, getName()+"Owner"); - queueAttributes.put(Queue.EXCLUSIVE, Boolean.FALSE); - queueAttributes.putAll(attributes); - queueAttributes.put(Queue.ALTERNATE_EXCHANGE, alternateExchange.getId().toString()); - - verify(_recoveryHandler).configuredObject(eq(_queueId), eq(QUEUE), eq(queueAttributes)); - } - - public void testRemoveQueue() throws Exception - { - // create queue - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(Queue.CREATE_DLQ_ON_CREATION, Boolean.TRUE); - attributes.put(Queue.MAXIMUM_DELIVERY_ATTEMPTS, 10); - AMQQueue queue = createTestQueue(getName(), getName() + "Owner", true, attributes); - DurableConfigurationStoreHelper.createQueue(_configStore, queue); - - // remove queue - DurableConfigurationStoreHelper.removeQueue(_configStore,queue); - reopenStore(); - verify(_recoveryHandler, never()).configuredObject(any(UUID.class), - eq(org.apache.qpid.server.model.Queue.class.getName()), - anyMap()); - } - - private AMQQueue createTestQueue(String queueName, - String queueOwner, - boolean exclusive, - final Map<String, Object> arguments) throws AMQStoreException - { - return createTestQueue(queueName, queueOwner, exclusive, null, arguments); - } - - private AMQQueue createTestQueue(String queueName, - String queueOwner, - boolean exclusive, - Exchange alternateExchange, - final Map<String, Object> arguments) throws AMQStoreException - { - AMQQueue queue = mock(AMQQueue.class); - when(queue.getName()).thenReturn(queueName); - when(queue.getOwner()).thenReturn(queueOwner); - when(queue.isExclusive()).thenReturn(exclusive); - when(queue.getId()).thenReturn(_queueId); - when(queue.getAlternateExchange()).thenReturn(alternateExchange); - if(arguments != null && !arguments.isEmpty()) - { - when(queue.getAvailableAttributes()).thenReturn(arguments.keySet()); - final ArgumentCaptor<String> requestedAttribute = ArgumentCaptor.forClass(String.class); - when(queue.getAttribute(requestedAttribute.capture())).then( - new Answer() - { - - @Override - public Object answer(final InvocationOnMock invocation) throws Throwable - { - String attrName = requestedAttribute.getValue(); - return arguments.get(attrName); - } - }); - } - - return queue; - } - - private Exchange createTestExchange() - { - Exchange exchange = mock(Exchange.class); - when(exchange.getName()).thenReturn(getName()); - when(exchange.getTypeName()).thenReturn(getName() + "Type"); - when(exchange.isAutoDelete()).thenReturn(true); - when(exchange.getId()).thenReturn(_exchangeId); - return exchange; - } - - private void reopenStore() throws Exception - { - closeMessageStore(); - closeConfigStore(); - _messageStore = createMessageStore(); - _configStore = createConfigStore(); - - _configStore.configureConfigStore(_virtualHost, _recoveryHandler); - _messageStore.configureMessageStore(_virtualHost, _messageStoreRecoveryHandler, _logRecoveryHandler); - _messageStore.activate(); - } - - protected abstract MessageStore createMessageStore() throws Exception; - protected abstract DurableConfigurationStore createConfigStore() throws Exception; - protected abstract void closeMessageStore() throws Exception; - protected abstract void closeConfigStore() throws Exception; - - public void testRecordXid() throws Exception - { - Record enqueueRecord = getTestRecord(1); - Record dequeueRecord = getTestRecord(2); - Record[] enqueues = { enqueueRecord }; - Record[] dequeues = { dequeueRecord }; - byte[] globalId = new byte[] { 1 }; - byte[] branchId = new byte[] { 2 }; - - Transaction transaction = _messageStore.newTransaction(); - transaction.recordXid(1l, globalId, branchId, enqueues, dequeues); - transaction.commitTran(); - reopenStore(); - verify(_dtxRecordRecoveryHandler).dtxRecord(1l, globalId, branchId, enqueues, dequeues); - - transaction = _messageStore.newTransaction(); - transaction.removeXid(1l, globalId, branchId); - transaction.commitTran(); - - reopenStore(); - verify(_dtxRecordRecoveryHandler, times(1)).dtxRecord(1l, globalId, branchId, enqueues, dequeues); - } - - private Record getTestRecord(long messageNumber) - { - UUID queueId1 = UUIDGenerator.generateRandomUUID(); - TransactionLogResource queue1 = mock(TransactionLogResource.class); - when(queue1.getId()).thenReturn(queueId1); - EnqueableMessage message1 = mock(EnqueableMessage.class); - when(message1.isPersistent()).thenReturn(true); - when(message1.getMessageNumber()).thenReturn(messageNumber); - final StoredMessage storedMessage = mock(StoredMessage.class); - when(storedMessage.getMessageNumber()).thenReturn(messageNumber); - when(message1.getStoredMessage()).thenReturn(storedMessage); - Record enqueueRecord = new TestRecord(queue1, message1); - return enqueueRecord; - } - - private static class TestRecord implements Record - { - private TransactionLogResource _queue; - private EnqueableMessage _message; - - public TestRecord(TransactionLogResource queue, EnqueableMessage message) - { - super(); - _queue = queue; - _message = message; - } - - @Override - public TransactionLogResource getQueue() - { - return _queue; - } - - @Override - public EnqueableMessage getMessage() - { - return _message; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + ((_message == null) ? 0 : new Long(_message.getMessageNumber()).hashCode()); - result = prime * result + ((_queue == null) ? 0 : _queue.getId().hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) - { - if (this == obj) - { - return true; - } - if (obj == null) - { - return false; - } - if (!(obj instanceof Record)) - { - return false; - } - Record other = (Record) obj; - if (_message == null && other.getMessage() != null) - { - return false; - } - if (_queue == null && other.getQueue() != null) - { - return false; - } - if (_message.getMessageNumber() != other.getMessage().getMessageNumber()) - { - return false; - } - return _queue.getId().equals(other.getQueue().getId()); - } - - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/store/EventManagerTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/store/EventManagerTest.java deleted file mode 100644 index 2be79c5839..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/store/EventManagerTest.java +++ /dev/null @@ -1,72 +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; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.apache.qpid.server.store.Event.AFTER_ACTIVATE; -import static org.apache.qpid.server.store.Event.BEFORE_ACTIVATE; -import junit.framework.TestCase; - -public class EventManagerTest extends TestCase -{ - private EventManager _eventManager = new EventManager(); - private EventListener _mockListener = mock(EventListener.class); - - public void testEventListenerFires() - { - _eventManager.addEventListener(_mockListener, BEFORE_ACTIVATE); - _eventManager.notifyEvent(BEFORE_ACTIVATE); - verify(_mockListener).event(BEFORE_ACTIVATE); - } - - public void testEventListenerDoesntFire() - { - _eventManager.addEventListener(_mockListener, BEFORE_ACTIVATE); - _eventManager.notifyEvent(AFTER_ACTIVATE); - verifyZeroInteractions(_mockListener); - } - - public void testEventListenerFiresMulitpleTimes() - { - _eventManager.addEventListener(_mockListener, BEFORE_ACTIVATE); - _eventManager.addEventListener(_mockListener, AFTER_ACTIVATE); - - _eventManager.notifyEvent(BEFORE_ACTIVATE); - verify(_mockListener).event(BEFORE_ACTIVATE); - - _eventManager.notifyEvent(AFTER_ACTIVATE); - verify(_mockListener).event(AFTER_ACTIVATE); - } - - public void testMultipleListenersFireForSameEvent() - { - final EventListener mockListener1 = mock(EventListener.class); - final EventListener mockListener2 = mock(EventListener.class); - - _eventManager.addEventListener(mockListener1, BEFORE_ACTIVATE); - _eventManager.addEventListener(mockListener2, BEFORE_ACTIVATE); - _eventManager.notifyEvent(BEFORE_ACTIVATE); - - verify(mockListener1).event(BEFORE_ACTIVATE); - verify(mockListener2).event(BEFORE_ACTIVATE); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/store/JsonFileConfigStoreTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/store/JsonFileConfigStoreTest.java deleted file mode 100644 index b6300e6f48..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/store/JsonFileConfigStoreTest.java +++ /dev/null @@ -1,299 +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; - -import java.io.File; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; -import org.apache.qpid.AMQStoreException; -import org.apache.qpid.server.model.Binding; -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.test.utils.QpidTestCase; -import org.mockito.InOrder; - -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyMap; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class JsonFileConfigStoreTest extends QpidTestCase -{ - private final ConfigurationRecoveryHandler _recoveryHandler = mock(ConfigurationRecoveryHandler.class); - private VirtualHost _virtualHost; - private JsonFileConfigStore _store; - - @Override - public void setUp() throws Exception - { - super.setUp(); - removeStoreFile(); - _virtualHost = mock(VirtualHost.class); - when(_virtualHost.getName()).thenReturn(getName()); - when(_virtualHost.getAttribute(VirtualHost.CONFIG_STORE_PATH)).thenReturn(TMP_FOLDER); - _store = new JsonFileConfigStore(); - } - - @Override - public void tearDown() throws Exception - { - removeStoreFile(); - } - - private void removeStoreFile() - { - File file = new File(TMP_FOLDER, getName() + ".json"); - if(file.exists()) - { - file.delete(); - } - } - - public void testNoStorePath() throws Exception - { - when(_virtualHost.getAttribute(VirtualHost.CONFIG_STORE_PATH)).thenReturn(null); - try - { - _store.configureConfigStore(_virtualHost, _recoveryHandler); - fail("Store should not successfully configure if there is no path set"); - } - catch (AMQStoreException e) - { - // pass - } - } - - - public void testInvalidStorePath() throws Exception - { - when(_virtualHost.getAttribute(VirtualHost.CONFIG_STORE_PATH)).thenReturn(System.getProperty("file.separator")); - try - { - _store.configureConfigStore(_virtualHost, _recoveryHandler); - fail("Store should not successfully configure if there is an invalid path set"); - } - catch (AMQStoreException e) - { - // pass - } - } - - public void testStartFromNoStore() throws Exception - { - _store.configureConfigStore(_virtualHost, _recoveryHandler); - InOrder inorder = inOrder(_recoveryHandler); - inorder.verify(_recoveryHandler).beginConfigurationRecovery(eq(_store), eq(0)); - inorder.verify(_recoveryHandler,never()).configuredObject(any(UUID.class),anyString(),anyMap()); - inorder.verify(_recoveryHandler).completeConfigurationRecovery(); - _store.close(); - } - - public void testUpdatedConfigVersionIsRetained() throws Exception - { - final int NEW_CONFIG_VERSION = 42; - when(_recoveryHandler.completeConfigurationRecovery()).thenReturn(NEW_CONFIG_VERSION); - - _store.configureConfigStore(_virtualHost, _recoveryHandler); - _store.close(); - - _store.configureConfigStore(_virtualHost, _recoveryHandler); - InOrder inorder = inOrder(_recoveryHandler); - - // first time the config version should be the initial version - 0 - inorder.verify(_recoveryHandler).beginConfigurationRecovery(eq(_store), eq(0)); - - // second time the config version should be the updated version - inorder.verify(_recoveryHandler).beginConfigurationRecovery(eq(_store), eq(NEW_CONFIG_VERSION)); - - _store.close(); - } - - public void testCreateObject() throws Exception - { - _store.configureConfigStore(_virtualHost, _recoveryHandler); - final UUID queueId = new UUID(0, 1); - final String queueType = Queue.class.getSimpleName(); - final Map<String,Object> queueAttr = Collections.singletonMap("name", (Object) "q1"); - - _store.create(queueId, queueType, queueAttr); - _store.close(); - - _store.configureConfigStore(_virtualHost, _recoveryHandler); - verify(_recoveryHandler).configuredObject(eq(queueId), eq(queueType), eq(queueAttr)); - _store.close(); - } - - public void testCreateAndUpdateObject() throws Exception - { - _store.configureConfigStore(_virtualHost, _recoveryHandler); - final UUID queueId = new UUID(0, 1); - final String queueType = Queue.class.getSimpleName(); - Map<String,Object> queueAttr = Collections.singletonMap("name", (Object) "q1"); - - _store.create(queueId, queueType, queueAttr); - - - queueAttr = new HashMap<String,Object>(queueAttr); - queueAttr.put("owner", "theowner"); - _store.update(queueId, queueType, queueAttr); - - _store.close(); - - _store.configureConfigStore(_virtualHost, _recoveryHandler); - verify(_recoveryHandler).configuredObject(eq(queueId), eq(queueType), eq(queueAttr)); - _store.close(); - } - - - public void testCreateAndRemoveObject() throws Exception - { - _store.configureConfigStore(_virtualHost, _recoveryHandler); - final UUID queueId = new UUID(0, 1); - final String queueType = Queue.class.getSimpleName(); - Map<String,Object> queueAttr = Collections.singletonMap("name", (Object) "q1"); - - _store.create(queueId, queueType, queueAttr); - - - _store.remove(queueId, queueType); - - _store.close(); - - _store.configureConfigStore(_virtualHost, _recoveryHandler); - verify(_recoveryHandler, never()).configuredObject(any(UUID.class), anyString(), anyMap()); - _store.close(); - } - - public void testCreateUnknownObjectType() throws Exception - { - _store.configureConfigStore(_virtualHost, _recoveryHandler); - try - { - _store.create(UUID.randomUUID(), "wibble", Collections.<String, Object>emptyMap()); - fail("Should not be able to create instance of type wibble"); - } - catch (AMQStoreException e) - { - // pass - } - } - - public void testTwoObjectsWithSameId() throws Exception - { - _store.configureConfigStore(_virtualHost, _recoveryHandler); - final UUID id = UUID.randomUUID(); - _store.create(id, "Queue", Collections.<String, Object>emptyMap()); - try - { - _store.create(id, "Exchange", Collections.<String, Object>emptyMap()); - fail("Should not be able to create two objects with same id"); - } - catch (AMQStoreException e) - { - // pass - } - } - - - public void testChangeTypeOfObject() throws Exception - { - _store.configureConfigStore(_virtualHost, _recoveryHandler); - final UUID id = UUID.randomUUID(); - _store.create(id, "Queue", Collections.<String, Object>emptyMap()); - _store.close(); - _store.configureConfigStore(_virtualHost, _recoveryHandler); - - try - { - _store.update(id, "Exchange", Collections.<String, Object>emptyMap()); - fail("Should not be able to update object to different type"); - } - catch (AMQStoreException e) - { - // pass - } - } - - public void testLockFileGuaranteesExclusiveAccess() throws Exception - { - _store.configureConfigStore(_virtualHost, _recoveryHandler); - - JsonFileConfigStore secondStore = new JsonFileConfigStore(); - - try - { - secondStore.configureConfigStore(_virtualHost, _recoveryHandler); - fail("Should not be able to open a second store with the same path"); - } - catch(AMQStoreException e) - { - // pass - } - _store.close(); - secondStore.configureConfigStore(_virtualHost, _recoveryHandler); - - - } - - public void testCreatedNestedObjects() throws Exception - { - - _store.configureConfigStore(_virtualHost, _recoveryHandler); - final UUID queueId = new UUID(0, 1); - final UUID queue2Id = new UUID(1, 1); - - final Map<String, Object> EMPTY_ATTR = Collections.emptyMap(); - final UUID exchangeId = new UUID(0, 2); - final Map<String, Object> bindingAttributes = new HashMap<String, Object>(); - bindingAttributes.put(Binding.EXCHANGE, exchangeId); - bindingAttributes.put(Binding.QUEUE, queueId); - final Map<String, Object> binding2Attributes = new HashMap<String, Object>(); - binding2Attributes.put(Binding.EXCHANGE, exchangeId); - binding2Attributes.put(Binding.QUEUE, queue2Id); - - final UUID bindingId = new UUID(0, 3); - final UUID binding2Id = new UUID(1, 3); - - _store.create(queueId, "Queue", EMPTY_ATTR); - _store.create(queue2Id, "Queue", EMPTY_ATTR); - _store.create(exchangeId, "Exchange", EMPTY_ATTR); - _store.update(true, - new ConfiguredObjectRecord(bindingId, "Binding", bindingAttributes), - new ConfiguredObjectRecord(binding2Id, "Binding", binding2Attributes)); - _store.close(); - _store.configureConfigStore(_virtualHost, _recoveryHandler); - verify(_recoveryHandler).configuredObject(eq(queueId), eq("Queue"), eq(EMPTY_ATTR)); - verify(_recoveryHandler).configuredObject(eq(queue2Id), eq("Queue"), eq(EMPTY_ATTR)); - verify(_recoveryHandler).configuredObject(eq(exchangeId), eq("Exchange"), eq(EMPTY_ATTR)); - verify(_recoveryHandler).configuredObject(eq(bindingId),eq("Binding"), eq(bindingAttributes)); - verify(_recoveryHandler).configuredObject(eq(binding2Id),eq("Binding"), eq(binding2Attributes)); - _store.close(); - - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreQuotaEventsTestBase.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreQuotaEventsTestBase.java deleted file mode 100644 index b23890b10c..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreQuotaEventsTestBase.java +++ /dev/null @@ -1,191 +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; - -import java.io.File; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -import org.apache.log4j.Logger; -import org.apache.qpid.server.message.EnqueableMessage; -import org.apache.qpid.server.plugin.MessageMetaDataType; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.util.FileUtils; - -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -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(VirtualHost virtualHost); - - protected abstract int getNumberOfMessagesToFillStore(); - - @Override - public void setUp() throws Exception - { - super.setUp(); - - _storeLocation = new File(new File(TMP_FOLDER), getTestName()); - FileUtils.delete(_storeLocation, true); - - - VirtualHost vhost = mock(VirtualHost.class); - when(vhost.getAttribute(eq(VirtualHost.STORE_PATH))).thenReturn(_storeLocation.getAbsolutePath()); - when(vhost.getName()).thenReturn("test"); - - applyStoreSpecificConfiguration(vhost); - - _store = createStore(); - ((DurableConfigurationStore)_store).configureConfigStore(vhost, null); - _store.configureMessageStore(vhost, null, null); - - _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 - { - try - { - super.tearDown(); - } - finally - { - if (_store != null) - { - _store.close(); - } - 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) - { - StorableMessageMetaData metaData = createMetaData(id, MESSAGE_DATA.length); - StoredMessage handle = _store.addMessage(metaData); - handle.addContent(0, ByteBuffer.wrap(MESSAGE_DATA)); - TestMessage message = new TestMessage(id, handle); - return message; - } - - private StorableMessageMetaData createMetaData(long id, int length) - { - StorableMessageMetaData metaData = mock(StorableMessageMetaData.class); - when(metaData.isPersistent()).thenReturn(true); - when(metaData.getContentSize()).thenReturn(length); - when(metaData.getStorableSize()).thenReturn(0); - MessageMetaDataType type = mock(MessageMetaDataType.class); - when(type.ordinal()).thenReturn(-1); - when(metaData.getType()).thenReturn(type); - return metaData; - } - - @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/qpid/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreTestCase.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreTestCase.java deleted file mode 100644 index 7ebfd54df6..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreTestCase.java +++ /dev/null @@ -1,78 +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; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.store.MessageStoreRecoveryHandler.StoredMessageRecoveryHandler; -import org.apache.qpid.test.utils.QpidTestCase; - -public abstract class MessageStoreTestCase extends QpidTestCase -{ - private ConfigurationRecoveryHandler _recoveryHandler; - private MessageStoreRecoveryHandler _messageStoreRecoveryHandler; - private StoredMessageRecoveryHandler _storedMessageRecoveryHandler; - private TransactionLogRecoveryHandler _logRecoveryHandler; - private TransactionLogRecoveryHandler.QueueEntryRecoveryHandler _queueEntryRecoveryHandler; - private TransactionLogRecoveryHandler.DtxRecordRecoveryHandler _dtxRecordRecoveryHandler; - private VirtualHost _virtualHost; - - private MessageStore _store; - - public void setUp() throws Exception - { - super.setUp(); - - _recoveryHandler = mock(ConfigurationRecoveryHandler.class); - _storedMessageRecoveryHandler = mock(StoredMessageRecoveryHandler.class); - _logRecoveryHandler = mock(TransactionLogRecoveryHandler.class); - _messageStoreRecoveryHandler = mock(MessageStoreRecoveryHandler.class); - _queueEntryRecoveryHandler = mock(TransactionLogRecoveryHandler.QueueEntryRecoveryHandler.class); - _dtxRecordRecoveryHandler = mock(TransactionLogRecoveryHandler.DtxRecordRecoveryHandler.class); - _virtualHost = mock(VirtualHost.class); - - - when(_messageStoreRecoveryHandler.begin()).thenReturn(_storedMessageRecoveryHandler); - when(_logRecoveryHandler.begin(any(MessageStore.class))).thenReturn(_queueEntryRecoveryHandler); - when(_queueEntryRecoveryHandler.completeQueueEntryRecovery()).thenReturn(_dtxRecordRecoveryHandler); - - setUpStoreConfiguration(_virtualHost); - when(_virtualHost.getName()).thenReturn(getTestName()); - - _store = createMessageStore(); - ((DurableConfigurationStore)_store).configureConfigStore(_virtualHost, _recoveryHandler); - - _store.configureMessageStore(_virtualHost, _messageStoreRecoveryHandler, _logRecoveryHandler); - } - - protected abstract void setUpStoreConfiguration(VirtualHost virtualHost) throws Exception; - - protected abstract MessageStore createMessageStore(); - - public MessageStore getStore() - { - return _store; - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/store/OperationalLoggingListenerTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/store/OperationalLoggingListenerTest.java deleted file mode 100644 index c309dad5eb..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/store/OperationalLoggingListenerTest.java +++ /dev/null @@ -1,187 +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; - -import java.util.ArrayList; -import java.util.List; -import junit.framework.TestCase; -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.server.logging.messages.ConfigStoreMessages; -import org.apache.qpid.server.logging.messages.MessageStoreMessages; -import org.apache.qpid.server.logging.messages.TransactionLogMessages; - -public class OperationalLoggingListenerTest extends TestCase -{ - - - public static final String STORE_LOCATION = "The moon!"; - - protected void setUp() throws Exception - { - super.setUp(); - - } - - public void testOperationalLoggingWithStoreLocation() throws Exception - { - TestMessageStore messageStore = new TestMessageStore(); - LogSubject logSubject = LOG_SUBJECT; - - OperationalLoggingListener.listen(messageStore, logSubject); - - performTests(messageStore, true); - - } - - public void testOperationalLogging() throws Exception - { - TestMessageStore messageStore = new TestMessageStore(); - LogSubject logSubject = LOG_SUBJECT; - - OperationalLoggingListener.listen(messageStore, logSubject); - - performTests(messageStore, false); - } - - private void performTests(TestMessageStore messageStore, boolean setStoreLocation) - { - final List<LogMessage> messages = new ArrayList<LogMessage>(); - - CurrentActor.set(new TestActor(messages)); - - if(setStoreLocation) - { - messageStore.setStoreLocation(STORE_LOCATION); - } - - - 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.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()); - if(setStoreLocation) - { - assertEquals(messages.remove(0).toString(), MessageStoreMessages.STORE_LOCATION(STORE_LOCATION).toString()); - } - - 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()); - - - messageStore.attainState(State.ACTIVE); - assertEquals("Unexpected number of operational log messages on ACTIVE", 1, messages.size()); - assertEquals(messages.remove(0).toString(), MessageStoreMessages.RECOVERY_COMPLETE().toString()); - - messageStore.attainState(State.CLOSING); - assertEquals("Unexpected number of operational log messages on CLOSING", 0, messages.size()); - - messageStore.attainState(State.CLOSED); - assertEquals("Unexpected number of operational log messages on CLOSED", 1, messages.size()); - assertEquals(messages.remove(0).toString(), MessageStoreMessages.CLOSED().toString()); - } - - @Override - protected void tearDown() throws Exception - { - super.tearDown(); - CurrentActor.remove(); - } - - - private static final LogSubject LOG_SUBJECT = new LogSubject() - { - public String toLogString() - { - return ""; - } - }; - - private static final class TestMessageStore extends NullMessageStore - { - - private final EventManager _eventManager = new EventManager(); - private final StateManager _stateManager = new StateManager(_eventManager); - private String _storeLocation; - - public void attainState(State state) - { - _stateManager.attainState(state); - } - - @Override - public String getStoreLocation() - { - return _storeLocation; - } - - public void setStoreLocation(String storeLocation) - { - _storeLocation = storeLocation; - } - - @Override - public void addEventListener(EventListener eventListener, Event... events) - { - _eventManager.addEventListener(eventListener, events); - } - - @Override - public String getStoreType() - { - return "TEST"; - } - } - - private static class TestActor implements LogActor - { - private final List<LogMessage> _messages; - - public TestActor(List<LogMessage> messages) - { - _messages = messages; - } - - public void message(LogSubject subject, LogMessage message) - { - _messages.add(message); - } - - public void message(LogMessage message) - { - _messages.add(message); - } - - public RootMessageLogger getRootMessageLogger() - { - return null; - } - - public String getLogMessage() - { - return null; - } - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/store/StateManagerTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/store/StateManagerTest.java deleted file mode 100644 index 18efb976eb..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/store/StateManagerTest.java +++ /dev/null @@ -1,199 +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; - - -import java.util.EnumSet; -import junit.framework.TestCase; - -public class StateManagerTest extends TestCase implements EventListener -{ - - private StateManager _manager; - private Event _event; - - public void setUp() throws Exception - { - super.setUp(); - _manager = new StateManager(this); - } - - public void testInitialState() - { - assertEquals(State.INITIAL, _manager.getState()); - } - - public void testStateTransitionAllowed() - { - assertEquals(State.INITIAL, _manager.getState()); - - _manager.attainState(State.INITIALISING); - assertEquals(State.INITIALISING, _manager.getState()); - } - - public void testStateTransitionDisallowed() - { - assertEquals(State.INITIAL, _manager.getState()); - - try - { - _manager.attainState(State.CLOSING); - fail("Exception not thrown"); - } - catch (IllegalStateException e) - { - // PASS - } - assertEquals(State.INITIAL, _manager.getState()); - } - - public void testIsInState() - { - assertEquals(State.INITIAL, _manager.getState()); - assertFalse(_manager.isInState(State.ACTIVE)); - assertTrue(_manager.isInState(State.INITIAL)); - } - - public void testIsNotInState() - { - assertEquals(State.INITIAL, _manager.getState()); - assertTrue(_manager.isNotInState(State.ACTIVE)); - assertFalse(_manager.isNotInState(State.INITIAL)); - } - - public void testCheckInState() - { - assertEquals(State.INITIAL, _manager.getState()); - - try - { - _manager.checkInState(State.ACTIVE); - fail("Exception not thrown"); - } - catch (IllegalStateException e) - { - // PASS - } - assertEquals(State.INITIAL, _manager.getState()); - } - - public void testValidStateTransitions() - { - assertEquals(State.INITIAL, _manager.getState()); - 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_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.INITIALISE); - performValidTransition(StateManager.INITALISE_COMPLETE); - performValidTransition(StateManager.ACTIVATE); - performValidTransition(StateManager.ACTIVATE_COMPLETE); - performValidTransition(StateManager.QUIESCE); - performValidTransition(StateManager.QUIESCE_COMPLETE); - performValidTransition(StateManager.CLOSE_QUIESCED); - performValidTransition(StateManager.CLOSE_COMPLETE); - } - - private void performValidTransition(StateManager.Transition transition) - { - _manager.attainState(transition.getEndState()); - assertEquals("Unexpected end state", transition.getEndState(), _manager.getState()); - assertEquals("Unexpected event", transition.getEvent(), _event); - _event = null; - } - - public void testInvalidStateTransitions() - { - assertEquals(State.INITIAL, _manager.getState()); - - 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.ACTIVATING, State.CLOSING); - performInvalidTransitions(StateManager.CLOSE_QUIESCED, State.CLOSED); - performInvalidTransitions(StateManager.CLOSE_COMPLETE); - - } - - private void performInvalidTransitions(StateManager.Transition preTransition, State... validEndStates) - { - if(preTransition != null) - { - performValidTransition(preTransition); - } - - EnumSet<State> endStates = EnumSet.allOf(State.class); - - if(validEndStates != null) - { - for(State state: validEndStates) - { - endStates.remove(state); - } - } - - for(State invalidEndState : endStates) - { - performInvalidStateTransition(invalidEndState); - } - - - } - - private void performInvalidStateTransition(State invalidEndState) - { - try - { - _event = null; - State startState = _manager.getState(); - _manager.attainState(invalidEndState); - fail("Invalid state transition performed: " + startState + " to " + invalidEndState); - } - catch(IllegalStateException e) - { - // pass - } - assertNull("No event should have be fired", _event); - } - - @Override - public void event(Event event) - { - _event = event; - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/store/TestMemoryMessageStore.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/store/TestMemoryMessageStore.java deleted file mode 100644 index 32df355c07..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/store/TestMemoryMessageStore.java +++ /dev/null @@ -1,34 +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; - - -/** A simple message store that stores the messages in a thread-safe structure in memory. */ -public class TestMemoryMessageStore extends AbstractMemoryMessageStore -{ - public static final String TYPE = "TestMemory"; - - @Override - public String getStoreType() - { - return TYPE; - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/store/TestMemoryMessageStoreFactory.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/store/TestMemoryMessageStoreFactory.java deleted file mode 100644 index fd2d4215ab..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/store/TestMemoryMessageStoreFactory.java +++ /dev/null @@ -1,54 +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; - -import java.util.Collections; -import java.util.Map; -import org.apache.commons.configuration.Configuration; -import org.apache.qpid.server.plugin.MessageStoreFactory; - -public class TestMemoryMessageStoreFactory implements MessageStoreFactory -{ - - @Override - public String getType() - { - return TestMemoryMessageStore.TYPE; - } - - @Override - public MessageStore createMessageStore() - { - return new TestMemoryMessageStore(); - } - - @Override - public Map<String, Object> convertStoreConfiguration(Configuration configuration) - { - return Collections.emptyMap(); - } - - @Override - public void validateAttributes(Map<String, Object> attributes) - { - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/store/TestableMemoryMessageStore.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/store/TestableMemoryMessageStore.java deleted file mode 100644 index bb3c0cf535..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/store/TestableMemoryMessageStore.java +++ /dev/null @@ -1,149 +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; - -import org.apache.qpid.AMQStoreException; -import org.apache.qpid.server.message.EnqueableMessage; -import org.apache.qpid.server.queue.AMQQueue; - -import java.nio.ByteBuffer; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * Adds some extra methods to the memory message store for testing purposes. - */ -public class TestableMemoryMessageStore extends TestMemoryMessageStore -{ - private final Map<Long, AMQQueue> _messages = new HashMap<Long, AMQQueue>(); - private final AtomicInteger _messageCount = new AtomicInteger(0); - - @Override - public StoredMessage addMessage(StorableMessageMetaData metaData) - { - return new TestableStoredMessage(super.addMessage(metaData)); - } - - public int getMessageCount() - { - return _messageCount.get(); - } - - public Map<Long, AMQQueue> getMessages() - { - return _messages; - } - - private class TestableTransaction implements Transaction - { - @Override - public void enqueueMessage(TransactionLogResource queue, EnqueableMessage message) throws AMQStoreException - { - getMessages().put(message.getMessageNumber(), (AMQQueue)queue); - } - - @Override - public void dequeueMessage(TransactionLogResource queue, EnqueableMessage message) throws AMQStoreException - { - getMessages().remove(message.getMessageNumber()); - } - - @Override - public void commitTran() throws AMQStoreException - { - } - - @Override - public StoreFuture commitTranAsync() throws AMQStoreException - { - return StoreFuture.IMMEDIATE_FUTURE; - } - - public void abortTran() throws AMQStoreException - { - } - - public void removeXid(long format, byte[] globalId, byte[] branchId) - { - } - - public void recordXid(long format, byte[] globalId, byte[] branchId, Record[] enqueues, Record[] dequeues) - { - } - } - - - @Override - public Transaction newTransaction() - { - return new TestableTransaction(); - } - - - private class TestableStoredMessage implements StoredMessage - { - private final StoredMessage _storedMessage; - - public TestableStoredMessage(StoredMessage storedMessage) - { - _messageCount.incrementAndGet(); - _storedMessage = storedMessage; - } - - public StorableMessageMetaData getMetaData() - { - return _storedMessage.getMetaData(); - } - - public long getMessageNumber() - { - return _storedMessage.getMessageNumber(); - } - - public void addContent(int offsetInMessage, ByteBuffer src) - { - _storedMessage.addContent(offsetInMessage, src); - } - - public int getContent(int offsetInMessage, ByteBuffer dst) - { - return _storedMessage.getContent(offsetInMessage, dst); - } - - - public ByteBuffer getContent(int offsetInMessage, int size) - { - return _storedMessage.getContent(offsetInMessage, size); - } - - public StoreFuture flushToStore() - { - return _storedMessage.flushToStore(); - } - - public void remove() - { - _storedMessage.remove(); - _messageCount.decrementAndGet(); - } - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/subscription/MockSubscription.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/subscription/MockSubscription.java deleted file mode 100644 index b26d7530aa..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/subscription/MockSubscription.java +++ /dev/null @@ -1,579 +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.subscription; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -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.model.Port; -import org.apache.qpid.server.model.Transport; -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; - -public class MockSubscription implements Subscription -{ - - private boolean _closed = false; - private String tag = "mocktag"; - private AMQQueue queue = null; - private StateListener _listener = 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(); - private List<QueueEntry> _acceptEntries = null; - - private final QueueEntry.SubscriptionAcquiredState _owningState = new QueueEntry.SubscriptionAcquiredState(this); - - private static final AtomicLong idGenerator = new AtomicLong(0); - // Create a simple ID that increments for ever new Subscription - private final long _subscriptionID = idGenerator.getAndIncrement(); - private boolean _isActive = true; - - public MockSubscription() - { - } - - public MockSubscription(List<QueueEntry> acceptEntries) - { - _acceptEntries = acceptEntries; - } - - public void close() - { - _closed = true; - if (_listener != null) - { - _listener.stateChange(this, _state, State.CLOSED); - } - _state = State.CLOSED; - } - - public String getConsumerName() - { - return tag; - } - - public long getSubscriptionID() - { - return _subscriptionID; - } - - public AMQQueue.Context getQueueContext() - { - return _queueContext; - } - - public SubscriptionAcquiredState getOwningState() - { - return _owningState; - } - - public LogActor getLogActor() - { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - public boolean isTransient() - { - 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(); - } - - - public void getSendLock() - { - _stateChangeLock.lock(); - } - - public boolean hasInterest(QueueEntry entry) - { - if(_acceptEntries != null) - { - //simulate selector behaviour, only signal - //interest in the dictated queue entries - return _acceptEntries.contains(entry); - } - - return true; - } - - public boolean isActive() - { - return _isActive ; - } - - public void set(String key, Object value) - { - } - - public Object get(String key) - { - return null; - } - - public boolean isAutoClose() - { - return false; - } - - public boolean isClosed() - { - return _closed; - } - - public boolean acquires() - { - return true; - } - - public boolean seesRequeues() - { - return true; - } - - public boolean isSuspended() - { - return false; - } - - public void queueDeleted(AMQQueue queue) - { - } - - public void releaseSendLock() - { - _stateChangeLock.unlock(); - } - - public void onDequeue(QueueEntry queueEntry) - { - } - - public void restoreCredit(QueueEntry queueEntry) - { - } - - public void releaseQueueEntry(QueueEntry queueEntry) - { - } - - public void send(QueueEntry entry, boolean batch) throws AMQException - { - if (messages.contains(entry)) - { - entry.setRedelivered(); - } - messages.add(entry); - } - - public void flushBatched() - { - - } - - public void setQueueContext(AMQQueue.Context queueContext) - { - _queueContext = queueContext; - } - - public void setQueue(AMQQueue queue, boolean exclusive) - { - this.queue = queue; - } - - public void setNoLocal(boolean noLocal) - { - } - - public void setStateListener(StateListener listener) - { - this._listener = listener; - } - - public State getState() - { - return _state; - } - - public boolean wouldSuspend(QueueEntry msg) - { - return false; - } - - public ArrayList<QueueEntry> getMessages() - { - return messages; - } - - public boolean isSessionTransactional() - { - return false; - } - - public void queueEmpty() throws AMQException - { - } - - public void setActive(final boolean isActive) - { - _isActive = isActive; - } - - private static class MockSessionModel implements AMQSessionModel - { - private final UUID _id = UUID.randomUUID(); - - @Override - public UUID getId() - { - return _id; - } - - @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; - } - - @Override - public int compareTo(AMQSessionModel o) - { - return getId().compareTo(o.getId()); - } - - @Override - public void close(AMQConstant cause, String message) throws AMQException - { - } - } - - 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; - } - - @Override - public Port getPort() - { - return null; - } - - @Override - public Transport getTransport() - { - return null; - } - - @Override - public void stop() - { - } - - @Override - public boolean isStopped() - { - return false; - } - - @Override - public String getVirtualHostName() - { - return null; - } - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/subscription/SubscriptionListTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/subscription/SubscriptionListTest.java deleted file mode 100644 index c4d1a1e614..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/subscription/SubscriptionListTest.java +++ /dev/null @@ -1,429 +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.subscription; - -import org.apache.qpid.server.subscription.SubscriptionList.SubscriptionNode; -import org.apache.qpid.server.subscription.SubscriptionList.SubscriptionNodeIterator; -import org.apache.qpid.test.utils.QpidTestCase; - -public class SubscriptionListTest extends QpidTestCase -{ - private SubscriptionList _subList; - private MockSubscription _sub1; - private MockSubscription _sub2; - private MockSubscription _sub3; - private SubscriptionNode _node; - - protected void setUp() - { - _subList = new SubscriptionList(); - - _sub1 = new MockSubscription(); - _sub2 = new MockSubscription(); - _sub3 = new MockSubscription(); - - _subList.add(_sub1); - _subList.add(_sub2); - _subList.add(_sub3); - - _node = _subList.getHead(); - } - - /** - * Test that if the first (non-head) node in the list is deleted (but is still present), - * it is not returned when searching through the list for the next viable node, and the - * subsequent viable node is returned instead. - */ - public void testFindNextSkipsFirstDeletedNode() - { - assertTrue("Deleting subscription node should have succeeded", - getNodeForSubscription(_subList, _sub1).delete()); - - assertNotNull("Returned node should not be null", _node = _node.findNext()); - assertEquals("Should have returned node for 2nd subscription", _sub2, _node.getSubscription()); - - assertNotNull("Returned node should not be null", _node = _node.findNext()); - assertEquals("Should have returned node for 3rd subscription", _sub3, _node.getSubscription()); - } - - /** - * Test that if a central node in the list is deleted (but is still present), - * it is not returned when searching through the list for the next viable node, - * and the subsequent viable node is returned instead. - */ - public void testFindNextSkipsCentralDeletedNode() - { - assertNotNull("Returned node should not be null", _node = _node.findNext()); - - assertTrue("Deleting subscription node should have succeeded", - getNodeForSubscription(_subList, _sub2).delete()); - - assertNotNull("Returned node should not be null", _node = _node.findNext()); - assertEquals("Should have returned node for 3rd subscription", _sub3, _node.getSubscription()); - } - - /** - * Test that if the last node in the list is deleted (but is still present), - * it is not returned when searching through the list for the next viable node, - * and null is returned instead. - */ - public void testFindNextSkipsLastDeletedNode() - { - assertNotNull("Returned node should not be null", _node = _node.findNext()); - assertEquals("Should have returned node for 1st subscription", _sub1, _node.getSubscription()); - - assertNotNull("Returned node should not be null", _node = _node.findNext()); - assertEquals("Should have returned node for 2nd subscription", _sub2, _node.getSubscription()); - - assertTrue("Deleting subscription node should have succeeded", - getNodeForSubscription(_subList, _sub3).delete()); - - assertNull("Returned node should be null", _node = _node.findNext()); - } - - /** - * Test that if multiple nodes in the list are deleted (but still present), they - * are not returned when searching through the list for the next viable node, - * and the subsequent viable node is returned instead. - */ - public void testFindNextSkipsMultipleDeletedNode() - { - assertTrue("Deleting subscription node should have succeeded", - getNodeForSubscription(_subList, _sub1).delete()); - assertTrue("Deleting subscription node should have succeeded", - getNodeForSubscription(_subList, _sub2).delete()); - - assertNotNull("Returned node should not be null", _node = _node.findNext()); - assertEquals("Should have returned node for 3rd subscription", _sub3, _node.getSubscription()); - } - - /** - * Test that if a node in the list is marked 'deleted' it is still present in the list - * until actually removed. counter-test to verify above testing of getNext() method. - */ - public void testDeletedNodeStillPresent() - { - assertTrue("Deleting subscription node should have succeeded", - getNodeForSubscription(_subList, _sub1).delete()); - - assertNotNull("Node marked deleted should still be present", getNodeForSubscription(_subList, _sub1)); - assertEquals("All 3 nodes are still expected to be present", 3, countNodes(_subList)); - } - - /** - * Traverses the list nodes in a non-mutating fashion, returning the first node which matches the given - * Subscription, or null if none is found. - */ - private SubscriptionNode getNodeForSubscription(final SubscriptionList list, final Subscription sub) - { - SubscriptionNode node = list.getHead(); - while (node != null && node.getSubscription() != sub) - { - node = node.nextNode(); - } - - return node; - } - - /** - * Counts the number of (non-head) nodes in the list. - */ - private int countNodes(final SubscriptionList list) - { - SubscriptionNode node = list.getHead(); - int count; - for(count = -1; node != null; count++) - { - node = node.nextNode(); - } - - return count; - } - - /** - * Tests that the head is returned as expected, and isn't the node for the first subscription. - */ - public void testGetHead() - { - assertNotNull("List head should be non null", _node); - assertNotSame("Head should not be node for first subscription", - _node, getNodeForSubscription(_subList, _sub1)); - } - - /** - * Tests that the size is returned correctly in the face of additions and removals. - */ - public void testGetSize() - { - SubscriptionList subList = new SubscriptionList(); - - assertEquals("Unexpected size result", 0, subList.size()); - - Subscription sub1 = new MockSubscription(); - Subscription sub2 = new MockSubscription(); - Subscription sub3 = new MockSubscription(); - - subList.add(sub1); - assertEquals("Unexpected size result", 1, subList.size()); - - subList.add(sub2); - assertEquals("Unexpected size result", 2, subList.size()); - - subList.add(sub3); - assertEquals("Unexpected size result", 3, subList.size()); - - assertTrue("Removing subscription from list should have succeeded", subList.remove(sub1)); - assertEquals("Unexpected size result", 2, subList.size()); - - assertTrue("Removing subscription from list should have succeeded", subList.remove(sub2)); - assertEquals("Unexpected size result", 1, subList.size()); - - assertTrue("Removing subscription from list should have succeeded", subList.remove(sub3)); - assertEquals("Unexpected size result", 0, subList.size()); - } - - /** - * Test that if the first (non-head) node in the list is removed it is no longer - * present in the node structure of the list at all. - */ - public void testRemoveFirstNode() - { - assertNotNull("Should have been a node present for the subscription", getNodeForSubscription(_subList, _sub1)); - assertTrue("Removing subscription node should have succeeded", _subList.remove(_sub1)); - assertNull("Should not have been a node present for the removed subscription", getNodeForSubscription(_subList, _sub1)); - assertEquals("Unexpected number of nodes", 2, countNodes(_subList)); - assertNotNull("Should have been a node present for the subscription", getNodeForSubscription(_subList, _sub2)); - assertNotNull("Should have been a node present for the subscription", getNodeForSubscription(_subList, _sub3)); - } - - /** - * Test that if a central node in the list is removed it is no longer - * present in the node structure of the list at all. - */ - public void testRemoveCentralNode() - { - assertNotNull("Should have been a node present for the subscription", getNodeForSubscription(_subList, _sub2)); - assertTrue("Removing subscription node should have succeeded", _subList.remove(_sub2)); - assertNull("Should not have been a node present for the removed subscription", getNodeForSubscription(_subList, _sub2)); - assertEquals("Unexpected number of nodes", 2, countNodes(_subList)); - assertNotNull("Should have been a node present for the subscription", getNodeForSubscription(_subList, _sub1)); - assertNotNull("Should have been a node present for the subscription", getNodeForSubscription(_subList, _sub3)); - } - - /** - * Test that if the subscription contained in the last node of the list is removed - * it is no longer present in the node structure of the list at all. However, - * as the last node in the structure can't actually be removed a dummy will instead - * be present. - */ - public void testRemoveLastNode() - { - assertNotNull("Should have been a node present for the subscription", getNodeForSubscription(_subList, _sub3)); - assertTrue("Removing subscription node should have succeeded", _subList.remove(_sub3)); - assertNull("Should not have been a node present for the removed subscription", getNodeForSubscription(_subList, _sub3)); - - //We actually expect 3 nodes to remain this time, because the last node cant be removed for thread safety reasons, - //however a dummy final node can be used as substitute to allow removal of the subscription node. - assertEquals("Unexpected number of nodes", 2 + 1, countNodes(_subList)); - assertNotNull("Should have been a node present for the subscription", getNodeForSubscription(_subList, _sub1)); - assertNotNull("Should have been a node present for the subscription", getNodeForSubscription(_subList, _sub2)); - } - - /** - * Test that if the subscription not contained in the list is requested to be removed - * that the removal fails - */ - public void testRemoveNonExistantNode() - { - Subscription sub4 = new MockSubscription(); - assertNull("Should not have been a node present for the subscription", getNodeForSubscription(_subList, sub4)); - assertFalse("Removing subscription node should not have succeeded", _subList.remove(sub4)); - assertEquals("Unexpected number of nodes", 3, countNodes(_subList)); - } - - /** - * Test that if a subscription node which occurs later in the main list than the marked node is - * removed from the list after the marked node is also removed, then the marker node doesn't - * serve to retain the subsequent nodes in the list structure (and thus memory) despite their - * removal. - */ - public void testDeletedMarkedNodeDoesntLeakSubsequentlyDeletedNodes() - { - //get the nodes out the list for the 1st and 3rd subscriptions - SubscriptionNode sub1Node = getNodeForSubscription(_subList, _sub1); - assertNotNull("Should have been a node present for the subscription", sub1Node); - SubscriptionNode sub3Node = getNodeForSubscription(_subList, _sub3); - assertNotNull("Should have been a node present for the subscription", sub3Node); - - //mark the first subscription node - assertTrue("should have succeeded in updating the marked node", - _subList.updateMarkedNode(_subList.getMarkedNode(), sub1Node)); - - //remove the 1st subscription from the list - assertTrue("Removing subscription node should have succeeded", _subList.remove(_sub1)); - //verify the 1st subscription is no longer the marker node (replaced by a dummy), or in the main list structure - assertNotSame("Unexpected marker node", sub1Node, _subList.getMarkedNode()); - assertNull("Should not have been a node present in the list structure for the marked-but-removed sub1 node", - getNodeForSubscription(_subList, _sub1)); - - //remove the 2nd subscription from the list - assertTrue("Removing subscription node should have succeeded", _subList.remove(_sub2)); - - //verify the marker node isn't leaking subsequently removed nodes, by ensuring the very next node - //in its list structure is now the 3rd subscription (since the 2nd was removed too) - assertEquals("Unexpected next node", sub3Node, _subList.getMarkedNode().nextNode()); - - //remove the 3rd and final/tail subscription - assertTrue("Removing subscription node should have succeeded", _subList.remove(_sub3)); - - //verify the marker node isn't leaking subsequently removed nodes, by ensuring the very next node - //in its list structure is now the dummy tail (since the 3rd subscription was removed, and a dummy - //tail was inserted) and NOT the 3rd sub node. - assertNotSame("Unexpected next node", sub3Node, _subList.getMarkedNode().nextNode()); - assertTrue("Unexpected next node", _subList.getMarkedNode().nextNode().isDeleted()); - assertNull("Next non-deleted node from the marker should now be the list end, i.e. null", _subList.getMarkedNode().findNext()); - } - - /** - * Test that the marked node 'findNext' behaviour is as expected after a subscription is added - * to the list following the tail subscription node being removed while it is the marked node. - * That is, that the new subscriptions node is returned by getMarkedNode().findNext(). - */ - public void testMarkedNodeFindsNewSubscriptionAfterRemovingTailWhilstMarked() - { - //get the node out the list for the 3rd subscription - SubscriptionNode sub3Node = getNodeForSubscription(_subList, _sub3); - assertNotNull("Should have been a node present for the subscription", sub3Node); - - //mark the 3rd subscription node - assertTrue("should have succeeded in updating the marked node", - _subList.updateMarkedNode(_subList.getMarkedNode(), sub3Node)); - - //verify calling findNext on the marked node returns null, i.e. the end of the list has been reached - assertEquals("Unexpected node after marked node", null, _subList.getMarkedNode().findNext()); - - //remove the 3rd(marked) subscription from the list - assertTrue("Removing subscription node should have succeeded", _subList.remove(_sub3)); - - //add a new 4th subscription to the list - Subscription sub4 = new MockSubscription(); - _subList.add(sub4); - - //get the node out the list for the 4th subscription - SubscriptionNode sub4Node = getNodeForSubscription(_subList, sub4); - assertNotNull("Should have been a node present for the subscription", sub4Node); - - //verify the marked node (which is now a dummy substitute for the 3rd subscription) returns - //the 4th subscriptions node as the next non-deleted node. - assertEquals("Unexpected next node", sub4Node, _subList.getMarkedNode().findNext()); - } - - /** - * Test that setting the marked node to null doesn't cause problems during remove operations - */ - public void testRemoveWithNullMarkedNode() - { - //set the marker to null - assertTrue("should have succeeded in updating the marked node", - _subList.updateMarkedNode(_subList.getMarkedNode(), null)); - - //remove the 1st subscription from the main list - assertTrue("Removing subscription node should have succeeded", _subList.remove(_sub1)); - - //verify the 1st subscription is no longer in the main list structure - assertNull("Should not have been a node present in the main list structure for sub1", - getNodeForSubscription(_subList, _sub1)); - assertEquals("Unexpected number of nodes", 2, countNodes(_subList)); - } - - /** - * Tests that after the first (non-head) node of the list is marked deleted but has not - * yet been removed, the iterator still skips it. - */ - public void testIteratorSkipsFirstDeletedNode() - { - //'delete' but dont remove the node for the 1st subscription - assertTrue("Deleting subscription node should have succeeded", - getNodeForSubscription(_subList, _sub1).delete()); - assertNotNull("Should still have been a node present for the deleted subscription", - getNodeForSubscription(_subList, _sub1)); - - SubscriptionNodeIterator iter = _subList.iterator(); - - //verify the iterator returns the 2nd subscriptions node - assertTrue("Iterator should have been able to advance", iter.advance()); - assertEquals("Iterator returned unexpected SubscriptionNode", _sub2, iter.getNode().getSubscription()); - - //verify the iterator returns the 3rd subscriptions node and not the 2nd. - assertTrue("Iterator should have been able to advance", iter.advance()); - assertEquals("Iterator returned unexpected SubscriptionNode", _sub3, iter.getNode().getSubscription()); - } - - /** - * Tests that after a central node of the list is marked deleted but has not yet been removed, - * the iterator still skips it. - */ - public void testIteratorSkipsCentralDeletedNode() - { - //'delete' but dont remove the node for the 2nd subscription - assertTrue("Deleting subscription node should have succeeded", - getNodeForSubscription(_subList, _sub2).delete()); - assertNotNull("Should still have been a node present for the deleted subscription", - getNodeForSubscription(_subList, _sub2)); - - SubscriptionNodeIterator iter = _subList.iterator(); - - //verify the iterator returns the 1st subscriptions node - assertTrue("Iterator should have been able to advance", iter.advance()); - assertEquals("Iterator returned unexpected SubscriptionNode", _sub1, iter.getNode().getSubscription()); - - //verify the iterator returns the 3rd subscriptions node and not the 2nd. - assertTrue("Iterator should have been able to advance", iter.advance()); - assertEquals("Iterator returned unexpected SubscriptionNode", _sub3, iter.getNode().getSubscription()); - } - - /** - * Tests that after the last node of the list is marked deleted but has not yet been removed, - * the iterator still skips it. - */ - public void testIteratorSkipsDeletedFinalNode() - { - //'delete' but dont remove the node for the 3rd subscription - assertTrue("Deleting subscription node should have succeeded", - getNodeForSubscription(_subList, _sub3).delete()); - assertNotNull("Should still have been a node present for the deleted 3rd subscription", - getNodeForSubscription(_subList, _sub3)); - - SubscriptionNodeIterator iter = _subList.iterator(); - - //verify the iterator returns the 1st subscriptions node - assertTrue("Iterator should have been able to advance", iter.advance()); - assertEquals("Iterator returned unexpected SubscriptionNode", _sub1, iter.getNode().getSubscription()); - - //verify the iterator returns the 2nd subscriptions node - assertTrue("Iterator should have been able to advance", iter.advance()); - assertEquals("Iterator returned unexpected SubscriptionNode", _sub2, iter.getNode().getSubscription()); - - //verify the iterator can no longer advance and does not return a subscription node - assertFalse("Iterator should not have been able to advance", iter.advance()); - assertEquals("Iterator returned unexpected SubscriptionNode", null, iter.getNode()); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/AsyncAutoCommitTransactionTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/AsyncAutoCommitTransactionTest.java deleted file mode 100644 index 5c1012d50b..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/AsyncAutoCommitTransactionTest.java +++ /dev/null @@ -1,140 +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.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); - - 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/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/AutoCommitTransactionTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/AutoCommitTransactionTest.java deleted file mode 100644 index 06b8539eb1..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/AutoCommitTransactionTest.java +++ /dev/null @@ -1,442 +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.txn; - -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.MockAMQQueue; -import org.apache.qpid.server.queue.MockQueueEntry; -import org.apache.qpid.server.queue.QueueEntry; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.txn.MockStoreTransaction.TransactionState; -import org.apache.qpid.test.utils.QpidTestCase; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/** - * A unit test ensuring that AutoCommitTransaction creates a separate transaction for - * each dequeue/enqueue operation that involves enlistable messages. Verifies - * that the transaction is properly committed (or rolled-back in the case of exception), - * and that post transaction actions are correctly fired. - * - */ -public class AutoCommitTransactionTest extends QpidTestCase -{ - private ServerTransaction _transaction = null; // Class under test - - private MessageStore _transactionLog; - private AMQQueue _queue; - private List<AMQQueue> _queues; - private Collection<QueueEntry> _queueEntries; - private ServerMessage _message; - private MockAction _action; - private MockStoreTransaction _storeTransaction; - - - @Override - protected void setUp() throws Exception - { - super.setUp(); - - _storeTransaction = createTestStoreTransaction(false); - _transactionLog = MockStoreTransaction.createTestTransactionLog(_storeTransaction); - _action = new MockAction(); - - _transaction = new AutoCommitTransaction(_transactionLog); - } - - /** - * Tests the enqueue of a non persistent message to a single non durable queue. - * Asserts that a store transaction has not been started and commit action fired. - */ - public void testEnqueueToNonDurableQueueOfNonPersistentMessage() throws Exception - { - _message = createTestMessage(false); - _queue = createTestAMQQueue(false); - - _transaction.enqueue(_queue, _message, _action); - - assertEquals("Enqueue of non-persistent message must not cause message to be enqueued", 0, _storeTransaction.getNumberOfEnqueuedMessages()); - assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); - assertFalse("Rollback action must not be fired", _action.isRollbackActionFired()); - assertTrue("Post commit action must be fired", _action.isPostCommitActionFired()); - - } - - /** - * Tests the enqueue of a persistent message to a durable queue. - * Asserts that a store transaction has been committed and commit action fired. - */ - public void testEnqueueToDurableQueueOfPersistentMessage() throws Exception - { - _message = createTestMessage(true); - _queue = createTestAMQQueue(true); - - _transaction.enqueue(_queue, _message, _action); - - assertEquals("Enqueue of persistent message to durable queue must cause message to be enqueued", 1, _storeTransaction.getNumberOfEnqueuedMessages()); - assertEquals("Unexpected transaction state", TransactionState.COMMITTED, _storeTransaction.getState()); - assertFalse("Rollback action must not be fired", _action.isRollbackActionFired()); - assertTrue("Post commit action must be fired", _action.isPostCommitActionFired()); - } - - /** - * Tests the case where the store operation throws an exception. - * Asserts that the transaction is aborted and rollback action is fired. - */ - public void testStoreEnqueueCausesException() throws Exception - { - _message = createTestMessage(true); - _queue = createTestAMQQueue(true); - - _storeTransaction = createTestStoreTransaction(true); - _transactionLog = MockStoreTransaction.createTestTransactionLog(_storeTransaction); - _transaction = new AutoCommitTransaction(_transactionLog); - - try - { - _transaction.enqueue(_queue, _message, _action); - fail("Exception not thrown"); - } - catch (RuntimeException re) - { - // PASS - } - - assertEquals("Unexpected transaction state", TransactionState.ABORTED, _storeTransaction.getState()); - assertTrue("Rollback action must be fired", _action.isRollbackActionFired()); - assertFalse("Post commit action must be fired", _action.isPostCommitActionFired()); - } - - /** - * Tests the enqueue of a non persistent message to a many non durable queues. - * Asserts that a store transaction has not been started and post commit action fired. - */ - public void testEnqueueToManyNonDurableQueuesOfNonPersistentMessage() throws Exception - { - _message = createTestMessage(false); - _queues = createTestBaseQueues(new boolean[] {false, false, false}); - - _transaction.enqueue(_queues, _message, _action); - - assertEquals("Enqueue of non-persistent message must not cause message to be enqueued", 0, _storeTransaction.getNumberOfEnqueuedMessages()); - assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); - assertFalse("Rollback action must not be fired", _action.isRollbackActionFired()); - assertTrue("Post commit action must be fired", _action.isPostCommitActionFired()); - - } - - - /** - * Tests the enqueue of a persistent message to a many non durable queues. - * Asserts that a store transaction has not been started and post commit action - * fired. - */ - public void testEnqueueToManyNonDurableQueuesOfPersistentMessage() throws Exception - { - _message = createTestMessage(true); - _queues = createTestBaseQueues(new boolean[] {false, false, false}); - - _transaction.enqueue(_queues, _message, _action); - - assertEquals("Enqueue of persistent message to non-durable queues must not cause message to be enqueued", 0, _storeTransaction.getNumberOfEnqueuedMessages()); - assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); - assertFalse("Rollback action must not be fired", _action.isRollbackActionFired()); - assertTrue("Post commit action must be fired", _action.isPostCommitActionFired()); - - } - - /** - * Tests the enqueue of a persistent message to many queues, some durable others not. - * Asserts that a store transaction has been committed and post commit action fired. - */ - public void testEnqueueToDurableAndNonDurableQueuesOfPersistentMessage() throws Exception - { - _message = createTestMessage(true); - _queues = createTestBaseQueues(new boolean[] {false, true, false, true}); - - _transaction.enqueue(_queues, _message, _action); - - assertEquals("Enqueue of persistent message to durable/non-durable queues must cause messages to be enqueued", 2, _storeTransaction.getNumberOfEnqueuedMessages()); - assertEquals("Unexpected transaction state", TransactionState.COMMITTED, _storeTransaction.getState()); - assertFalse("Rollback action must not be fired", _action.isRollbackActionFired()); - assertTrue("Post commit action must be fired", _action.isPostCommitActionFired()); - } - - /** - * Tests the case where the store operation throws an exception. - * Asserts that the transaction is aborted and rollback action fired. - */ - public void testStoreEnqueuesCausesExceptions() throws Exception - { - _message = createTestMessage(true); - _queues = createTestBaseQueues(new boolean[] {true, true}); - - _storeTransaction = createTestStoreTransaction(true); - _transactionLog = MockStoreTransaction.createTestTransactionLog(_storeTransaction); - _transaction = new AutoCommitTransaction(_transactionLog); - - try - { - _transaction.enqueue(_queues, _message, _action); - fail("Exception not thrown"); - } - catch (RuntimeException re) - { - // PASS - } - - assertEquals("Unexpected transaction state", TransactionState.ABORTED, _storeTransaction.getState()); - assertTrue("Rollback action must be fired", _action.isRollbackActionFired()); - assertFalse("Post commit action must not be fired", _action.isPostCommitActionFired()); - } - - /** - * Tests the dequeue of a non persistent message from a single non durable queue. - * Asserts that a store transaction has not been started and post commit action - * fired. - */ - public void testDequeueFromNonDurableQueueOfNonPersistentMessage() throws Exception - { - _message = createTestMessage(false); - _queue = createTestAMQQueue(false); - - _transaction.dequeue(_queue, _message, _action); - - assertEquals("Dequeue of non-persistent message must not cause message to be dequeued", 0, _storeTransaction.getNumberOfDequeuedMessages()); - assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); - assertFalse("Rollback action must not be fired", _action.isRollbackActionFired()); - assertTrue("Post commit action must be fired", _action.isPostCommitActionFired()); - - } - - /** - * Tests the dequeue of a persistent message from a single non durable queue. - * Asserts that a store transaction has not been started and post commit - * action fired. - */ - public void testDequeueFromDurableQueueOfPersistentMessage() throws Exception - { - _message = createTestMessage(true); - _queue = createTestAMQQueue(true); - - _transaction.dequeue(_queue, _message, _action); - - assertEquals("Dequeue of persistent message to durable queue must cause message to be dequeued",1, _storeTransaction.getNumberOfDequeuedMessages()); - assertEquals("Unexpected transaction state", TransactionState.COMMITTED, _storeTransaction.getState()); - assertFalse("Rollback action must not be fired", _action.isRollbackActionFired()); - assertTrue("Post commit action must be fired", _action.isPostCommitActionFired()); - } - - /** - * Tests the case where the store operation throws an exception. - * Asserts that the transaction is aborted and post rollback action - * fired. - */ - public void testStoreDequeueCausesException() throws Exception - { - _message = createTestMessage(true); - _queue = createTestAMQQueue(true); - - _storeTransaction = createTestStoreTransaction(true); - _transactionLog = MockStoreTransaction.createTestTransactionLog(_storeTransaction); - _transaction = new AutoCommitTransaction(_transactionLog); - - try - { - _transaction.dequeue(_queue, _message, _action); - fail("Exception not thrown"); - } - catch (RuntimeException re) - { - // PASS - } - - assertEquals("Unexpected transaction state", TransactionState.ABORTED, _storeTransaction.getState()); - - assertTrue("Rollback action must be fired", _action.isRollbackActionFired()); - assertFalse("Post commit action must not be fired", _action.isPostCommitActionFired()); - } - - /** - * Tests the dequeue of a non persistent message from many non durable queues. - * Asserts that a store transaction has not been started and post commit action - * fired. - */ - public void testDequeueFromManyNonDurableQueuesOfNonPersistentMessage() throws Exception - { - _queueEntries = createTestQueueEntries(new boolean[] {false, false, false}, new boolean[] {false, false, false}); - - _transaction.dequeue(_queueEntries, _action); - - assertEquals("Dequeue of non-persistent messages must not cause message to be dequeued", 0, _storeTransaction.getNumberOfDequeuedMessages()); - assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); - assertEquals("Rollback action must not be fired", false, _action.isRollbackActionFired()); - assertEquals("Post commit action must be fired", true, _action.isPostCommitActionFired()); - - } - - - /** - * Tests the dequeue of a persistent message from a many non durable queues. - * Asserts that a store transaction has not been started and post commit action - * fired. - */ - public void testDequeueFromManyNonDurableQueuesOfPersistentMessage() throws Exception - { - _queueEntries = createTestQueueEntries(new boolean[] {false, false, false}, new boolean[] {true, true, true}); - - _transaction.dequeue(_queueEntries, _action); - - assertEquals("Dequeue of persistent message from non-durable queues must not cause message to be enqueued", 0, _storeTransaction.getNumberOfDequeuedMessages()); - assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); - assertFalse("Rollback action must not be fired", _action.isRollbackActionFired()); - assertTrue("Post commit action must be fired", _action.isPostCommitActionFired()); - } - - /** - * Tests the dequeue of a persistent message from many queues, some durable others not. - * Asserts that a store transaction has not been started and post commit action fired. - */ - public void testDequeueFromDurableAndNonDurableQueuesOfPersistentMessage() throws Exception - { - // A transaction will exist owing to the 1st and 3rd. - _queueEntries = createTestQueueEntries(new boolean[] {true, false, true, true}, new boolean[] {true, true, true, false}); - - _transaction.dequeue(_queueEntries, _action); - - assertEquals("Dequeue of persistent messages from durable/non-durable queues must cause messages to be dequeued", 2, _storeTransaction.getNumberOfDequeuedMessages()); - assertEquals("Unexpected transaction state", TransactionState.COMMITTED, _storeTransaction.getState()); - assertFalse("Rollback action must not be fired", _action.isRollbackActionFired()); - assertTrue("Post commit action must be fired", _action.isPostCommitActionFired()); - } - - /** - * Tests the case where the store operation throws an exception. - * Asserts that the transaction is aborted and post rollback action fired. - */ - public void testStoreDequeuesCauseExceptions() throws Exception - { - // Transactions will exist owing to the 1st and 3rd queue entries in the collection - _queueEntries = createTestQueueEntries(new boolean[] {true}, new boolean[] {true}); - - _storeTransaction = createTestStoreTransaction(true); - _transactionLog = MockStoreTransaction.createTestTransactionLog(_storeTransaction); - _transaction = new AutoCommitTransaction(_transactionLog); - - try - { - _transaction.dequeue(_queueEntries, _action); - fail("Exception not thrown"); - } - catch (RuntimeException re) - { - // PASS - } - - assertEquals("Unexpected transaction state", TransactionState.ABORTED, _storeTransaction.getState()); - - assertTrue("Rollback action must be fired", _action.isRollbackActionFired()); - assertFalse("Post commit action must not be fired", _action.isPostCommitActionFired()); - } - - /** - * Tests the add of a post-commit action. Since AutoCommitTranctions - * have no long lived transactions, the post commit action is fired immediately. - */ - public void testPostCommitActionFiredImmediately() throws Exception - { - - _transaction.addPostTransactionAction(_action); - - assertTrue("Post commit action must be fired", _action.isPostCommitActionFired()); - assertFalse("Rollback action must be fired", _action.isRollbackActionFired()); - } - - private Collection<QueueEntry> createTestQueueEntries(boolean[] queueDurableFlags, boolean[] messagePersistentFlags) - { - Collection<QueueEntry> queueEntries = new ArrayList<QueueEntry>(); - - assertTrue("Boolean arrays must be the same length", queueDurableFlags.length == messagePersistentFlags.length); - - for(int i = 0; i < queueDurableFlags.length; i++) - { - final AMQQueue queue = createTestAMQQueue(queueDurableFlags[i]); - final ServerMessage message = createTestMessage(messagePersistentFlags[i]); - - queueEntries.add(new MockQueueEntry() - { - - @Override - public ServerMessage getMessage() - { - return message; - } - - @Override - public AMQQueue getQueue() - { - return queue; - } - - }); - } - - return queueEntries; - } - - private MockStoreTransaction createTestStoreTransaction(boolean throwException) - { - return new MockStoreTransaction(throwException); - } - - private List<AMQQueue> createTestBaseQueues(boolean[] durableFlags) - { - List<AMQQueue> queues = new ArrayList<AMQQueue>(); - for (boolean b: durableFlags) - { - queues.add(createTestAMQQueue(b)); - } - - return queues; - } - - private AMQQueue createTestAMQQueue(final boolean durable) - { - return new MockAMQQueue("mockQueue") - { - @Override - public boolean isDurable() - { - return durable; - } - - }; - } - - private ServerMessage createTestMessage(final boolean persistent) - { - return new MockServerMessage(persistent); - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/LocalTransactionTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/LocalTransactionTest.java deleted file mode 100644 index 4904cbc6fb..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/LocalTransactionTest.java +++ /dev/null @@ -1,672 +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.txn; - -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.MockAMQQueue; -import org.apache.qpid.server.queue.MockQueueEntry; -import org.apache.qpid.server.queue.QueueEntry; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.txn.MockStoreTransaction.TransactionState; -import org.apache.qpid.test.utils.QpidTestCase; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/** - * A unit test ensuring that LocalTransactionTest creates a long-lived store transaction - * that spans many dequeue/enqueue operations of enlistable messages. Verifies - * that the long-lived transaction is properly committed and rolled back, and that - * post transaction actions are correctly fired. - * - */ -public class LocalTransactionTest extends QpidTestCase -{ - private ServerTransaction _transaction = null; // Class under test - - private AMQQueue _queue; - private List<AMQQueue> _queues; - private Collection<QueueEntry> _queueEntries; - private ServerMessage _message; - private MockAction _action1; - private MockAction _action2; - private MockStoreTransaction _storeTransaction; - private MessageStore _transactionLog; - - - @Override - protected void setUp() throws Exception - { - super.setUp(); - - _storeTransaction = createTestStoreTransaction(false); - _transactionLog = MockStoreTransaction.createTestTransactionLog(_storeTransaction); - _action1 = new MockAction(); - _action2 = new MockAction(); - - _transaction = new LocalTransaction(_transactionLog); - - } - - - /** - * Tests the enqueue of a non persistent message to a single non durable queue. - * Asserts that a store transaction has not been started. - */ - public void testEnqueueToNonDurableQueueOfNonPersistentMessage() throws Exception - { - _message = createTestMessage(false); - _queue = createTestAMQQueue(false); - - _transaction.enqueue(_queue, _message, _action1); - - assertEquals("Enqueue of non-persistent message must not cause message to be enqueued", 0, _storeTransaction.getNumberOfEnqueuedMessages()); - assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); - assertNotFired(_action1); - } - - /** - * Tests the enqueue of a persistent message to a durable queue. - * Asserts that a store transaction has been started. - */ - public void testEnqueueToDurableQueueOfPersistentMessage() throws Exception - { - _message = createTestMessage(true); - _queue = createTestAMQQueue(true); - - _transaction.enqueue(_queue, _message, _action1); - - assertEquals("Enqueue of persistent message to durable queue must cause message to be enqueued", 1, _storeTransaction.getNumberOfEnqueuedMessages()); - assertEquals("Unexpected transaction state", TransactionState.STARTED, _storeTransaction.getState()); - assertNotFired(_action1); - } - - /** - * Tests the case where the store operation throws an exception. - * Asserts that the transaction is aborted. - */ - public void testStoreEnqueueCausesException() throws Exception - { - _message = createTestMessage(true); - _queue = createTestAMQQueue(true); - - _storeTransaction = createTestStoreTransaction(true); - _transactionLog = MockStoreTransaction.createTestTransactionLog(_storeTransaction); - _transaction = new LocalTransaction(_transactionLog); - - try - { - _transaction.enqueue(_queue, _message, _action1); - fail("Exception not thrown"); - } - catch (RuntimeException re) - { - // PASS - } - - assertTrue("Rollback action must be fired", _action1.isRollbackActionFired()); - assertEquals("Unexpected transaction state", TransactionState.ABORTED, _storeTransaction.getState()); - - assertFalse("Post commit action must not be fired", _action1.isPostCommitActionFired()); - - } - - /** - * Tests the enqueue of a non persistent message to a many non durable queues. - * Asserts that a store transaction has not been started. - */ - public void testEnqueueToManyNonDurableQueuesOfNonPersistentMessage() throws Exception - { - _message = createTestMessage(false); - _queues = createTestBaseQueues(new boolean[] {false, false, false}); - - _transaction.enqueue(_queues, _message, _action1); - - assertEquals("Enqueue of non-persistent message must not cause message to be enqueued", 0, _storeTransaction.getNumberOfEnqueuedMessages()); - assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); - assertNotFired(_action1); - } - - /** - * Tests the enqueue of a persistent message to a many non durable queues. - * Asserts that a store transaction has not been started. - */ - public void testEnqueueToManyNonDurableQueuesOfPersistentMessage() throws Exception - { - _message = createTestMessage(true); - _queues = createTestBaseQueues(new boolean[] {false, false, false}); - - _transaction.enqueue(_queues, _message, _action1); - - assertEquals("Enqueue of persistent message to non-durable queues must not cause message to be enqueued", 0, _storeTransaction.getNumberOfEnqueuedMessages()); - assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); - assertNotFired(_action1); - - } - - /** - * Tests the enqueue of a persistent message to many queues, some durable others not. - * Asserts that a store transaction has been started. - */ - public void testEnqueueToDurableAndNonDurableQueuesOfPersistentMessage() throws Exception - { - _message = createTestMessage(true); - _queues = createTestBaseQueues(new boolean[] {false, true, false, true}); - - _transaction.enqueue(_queues, _message, _action1); - - assertEquals("Enqueue of persistent message to durable/non-durable queues must cause messages to be enqueued", 2, _storeTransaction.getNumberOfEnqueuedMessages()); - assertEquals("Unexpected transaction state", TransactionState.STARTED, _storeTransaction.getState()); - assertNotFired(_action1); - - } - - /** - * Tests the case where the store operation throws an exception. - * Asserts that the transaction is aborted. - */ - public void testStoreEnqueuesCausesExceptions() throws Exception - { - _message = createTestMessage(true); - _queues = createTestBaseQueues(new boolean[] {true, true}); - - _storeTransaction = createTestStoreTransaction(true); - _transactionLog = MockStoreTransaction.createTestTransactionLog(_storeTransaction); - _transaction = new LocalTransaction(_transactionLog); - - try - { - _transaction.enqueue(_queues, _message, _action1); - fail("Exception not thrown"); - } - catch (RuntimeException re) - { - // PASS - } - - assertTrue("Rollback action must be fired", _action1.isRollbackActionFired()); - assertEquals("Unexpected transaction state", TransactionState.ABORTED, _storeTransaction.getState()); - assertFalse("Post commit action must not be fired", _action1.isPostCommitActionFired()); - } - - /** - * Tests the dequeue of a non persistent message from a single non durable queue. - * Asserts that a store transaction has not been started. - */ - public void testDequeueFromNonDurableQueueOfNonPersistentMessage() throws Exception - { - _message = createTestMessage(false); - _queue = createTestAMQQueue(false); - - _transaction.dequeue(_queue, _message, _action1); - - assertEquals("Dequeue of non-persistent message must not cause message to be enqueued", 0, _storeTransaction.getNumberOfEnqueuedMessages()); - assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); - assertNotFired(_action1); - - } - - /** - * Tests the dequeue of a persistent message from a single non durable queue. - * Asserts that a store transaction has not been started. - */ - public void testDequeueFromDurableQueueOfPersistentMessage() throws Exception - { - _message = createTestMessage(true); - _queue = createTestAMQQueue(true); - - _transaction.dequeue(_queue, _message, _action1); - - assertEquals("Dequeue of non-persistent message must cause message to be dequeued", 1, _storeTransaction.getNumberOfDequeuedMessages()); - assertEquals("Unexpected transaction state", TransactionState.STARTED, _storeTransaction.getState()); - assertNotFired(_action1); - } - - /** - * Tests the case where the store operation throws an exception. - * Asserts that the transaction is aborted. - */ - public void testStoreDequeueCausesException() throws Exception - { - _message = createTestMessage(true); - _queue = createTestAMQQueue(true); - - _storeTransaction = createTestStoreTransaction(true); - _transactionLog = MockStoreTransaction.createTestTransactionLog(_storeTransaction); - _transaction = new LocalTransaction(_transactionLog); - - try - { - _transaction.dequeue(_queue, _message, _action1); - fail("Exception not thrown"); - } - catch (RuntimeException re) - { - // PASS - } - - assertTrue("Rollback action must be fired", _action1.isRollbackActionFired()); - assertEquals("Unexpected transaction state", TransactionState.ABORTED, _storeTransaction.getState()); - assertFalse("Post commit action must not be fired", _action1.isPostCommitActionFired()); - - } - - /** - * Tests the dequeue of a non persistent message from many non durable queues. - * Asserts that a store transaction has not been started. - */ - public void testDequeueFromManyNonDurableQueuesOfNonPersistentMessage() throws Exception - { - _queueEntries = createTestQueueEntries(new boolean[] {false, false, false}, new boolean[] {false, false, false}); - - _transaction.dequeue(_queueEntries, _action1); - - assertEquals("Dequeue of non-persistent messages must not cause message to be dequeued", 0, _storeTransaction.getNumberOfDequeuedMessages()); - assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); - assertNotFired(_action1); - - } - - /** - * Tests the dequeue of a persistent message from a many non durable queues. - * Asserts that a store transaction has not been started. - */ - public void testDequeueFromManyNonDurableQueuesOfPersistentMessage() throws Exception - { - _queueEntries = createTestQueueEntries(new boolean[] {false, false, false}, new boolean[] {true, true, true}); - - _transaction.dequeue(_queueEntries, _action1); - - assertEquals("Dequeue of persistent message from non-durable queues must not cause message to be enqueued", 0, _storeTransaction.getNumberOfDequeuedMessages()); - assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); - assertNotFired(_action1); - } - - /** - * Tests the dequeue of a persistent message from many queues, some durable others not. - * Asserts that a store transaction has not been started. - */ - public void testDequeueFromDurableAndNonDurableQueuesOfPersistentMessage() throws Exception - { - // A transaction will exist owing to the 1st and 3rd. - _queueEntries = createTestQueueEntries(new boolean[] {true, false, true, true}, new boolean[] {true, true, true, false}); - - _transaction.dequeue(_queueEntries, _action1); - - assertEquals("Dequeue of persistent messages from durable/non-durable queues must cause messages to be dequeued", 2, _storeTransaction.getNumberOfDequeuedMessages()); - assertEquals("Unexpected transaction state", TransactionState.STARTED, _storeTransaction.getState()); - assertNotFired(_action1); - } - - /** - * Tests the case where the store operation throws an exception. - * Asserts that the transaction is aborted. - */ - public void testStoreDequeuesCauseExceptions() throws Exception - { - // Transactions will exist owing to the 1st and 3rd queue entries in the collection - _queueEntries = createTestQueueEntries(new boolean[] {true}, new boolean[] {true}); - - _storeTransaction = createTestStoreTransaction(true); - _transactionLog = MockStoreTransaction.createTestTransactionLog(_storeTransaction); - _transaction = new LocalTransaction(_transactionLog); - - try - { - _transaction.dequeue(_queueEntries, _action1); - fail("Exception not thrown"); - } - catch (RuntimeException re) - { - // PASS - } - - assertEquals("Unexpected transaction state", TransactionState.ABORTED, _storeTransaction.getState()); - assertTrue("Rollback action must be fired", _action1.isRollbackActionFired()); - assertFalse("Post commit action must not be fired", _action1.isPostCommitActionFired()); - } - - /** - * Tests the add of a post-commit action. Unlike AutoCommitTranctions, the post transaction actions - * is added to a list to be fired on commit or rollback. - */ - public void testAddingPostCommitActionNotFiredImmediately() throws Exception - { - - _transaction.addPostTransactionAction(_action1); - - assertNotFired(_action1); - } - - - /** - * Tests committing a transaction without work accepted without error and without causing store - * enqueues or dequeues. - */ - public void testCommitNoWork() throws Exception - { - - _transaction.commit(); - - assertEquals("Unexpected number of store dequeues", 0, _storeTransaction.getNumberOfDequeuedMessages()); - assertEquals("Unexpected number of store enqueues", 0, _storeTransaction.getNumberOfEnqueuedMessages()); - assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); - } - - /** - * Tests rolling back a transaction without work accepted without error and without causing store - * enqueues or dequeues. - */ - public void testRollbackNoWork() throws Exception - { - - _transaction.rollback(); - - assertEquals("Unexpected number of store dequeues", 0, _storeTransaction.getNumberOfDequeuedMessages()); - assertEquals("Unexpected number of store enqueues", 0, _storeTransaction.getNumberOfEnqueuedMessages()); - assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); - } - - /** - * Tests the dequeuing of a message with a commit. Test ensures that the underlying store transaction is - * correctly controlled and the post commit action is fired. - */ - public void testCommitWork() throws Exception - { - - _message = createTestMessage(true); - _queue = createTestAMQQueue(true); - - assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); - assertFalse("Post commit action must not be fired yet", _action1.isPostCommitActionFired()); - - _transaction.dequeue(_queue, _message, _action1); - assertEquals("Unexpected transaction state", TransactionState.STARTED, _storeTransaction.getState()); - assertFalse("Post commit action must not be fired yet", _action1.isPostCommitActionFired()); - - _transaction.commit(); - - assertEquals("Unexpected transaction state", TransactionState.COMMITTED, _storeTransaction.getState()); - assertTrue("Post commit action must be fired", _action1.isPostCommitActionFired()); - } - - /** - * Tests the dequeuing of a message with a rollback. Test ensures that the underlying store transaction is - * correctly controlled and the post rollback action is fired. - */ - public void testRollbackWork() throws Exception - { - - _message = createTestMessage(true); - _queue = createTestAMQQueue(true); - - - assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); - assertFalse("Rollback action must not be fired yet", _action1.isRollbackActionFired()); - - _transaction.dequeue(_queue, _message, _action1); - - assertEquals("Unexpected transaction state", TransactionState.STARTED, _storeTransaction.getState()); - assertFalse("Rollback action must not be fired yet", _action1.isRollbackActionFired()); - - _transaction.rollback(); - - assertEquals("Unexpected transaction state", TransactionState.ABORTED, _storeTransaction.getState()); - assertTrue("Rollback action must be fired", _action1.isRollbackActionFired()); - - } - - /** - * Variation of testCommitWork with an additional post transaction action. - * - */ - public void testCommitWorkWithAdditionalPostAction() throws Exception - { - - _message = createTestMessage(true); - _queue = createTestAMQQueue(true); - - _transaction.addPostTransactionAction(_action1); - _transaction.dequeue(_queue, _message, _action2); - _transaction.commit(); - - assertEquals("Unexpected transaction state", TransactionState.COMMITTED, _storeTransaction.getState()); - - assertTrue("Post commit action1 must be fired", _action1.isPostCommitActionFired()); - assertTrue("Post commit action2 must be fired", _action2.isPostCommitActionFired()); - - assertFalse("Rollback action1 must not be fired", _action1.isRollbackActionFired()); - assertFalse("Rollback action2 must not be fired", _action1.isRollbackActionFired()); - } - - /** - * Variation of testRollbackWork with an additional post transaction action. - * - */ - public void testRollbackWorkWithAdditionalPostAction() throws Exception - { - _message = createTestMessage(true); - _queue = createTestAMQQueue(true); - - _transaction.addPostTransactionAction(_action1); - _transaction.dequeue(_queue, _message, _action2); - _transaction.rollback(); - - assertEquals("Unexpected transaction state", TransactionState.ABORTED, _storeTransaction.getState()); - - assertFalse("Post commit action1 must not be fired", _action1.isPostCommitActionFired()); - assertFalse("Post commit action2 must not be fired", _action2.isPostCommitActionFired()); - - assertTrue("Rollback action1 must be fired", _action1.isRollbackActionFired()); - assertTrue("Rollback action2 must be fired", _action1.isRollbackActionFired()); - } - - public void testFirstEnqueueRecordsTransactionStartAndUpdateTime() throws Exception - { - assertEquals("Unexpected transaction start time before test", 0, _transaction.getTransactionStartTime()); - assertEquals("Unexpected transaction update time before test", 0, _transaction.getTransactionUpdateTime()); - - _message = createTestMessage(true); - _queue = createTestAMQQueue(true); - - long startTime = System.currentTimeMillis(); - _transaction.enqueue(_queue, _message, _action1); - - assertTrue("Transaction start time should have been recorded", _transaction.getTransactionStartTime() >= startTime); - assertEquals("Transaction update time should be the same as transaction start time", _transaction.getTransactionStartTime(), _transaction.getTransactionUpdateTime()); - } - - public void testSubsequentEnqueueAdvancesTransactionUpdateTimeOnly() throws Exception - { - assertEquals("Unexpected transaction start time before test", 0, _transaction.getTransactionStartTime()); - assertEquals("Unexpected transaction update time before test", 0, _transaction.getTransactionUpdateTime()); - - _message = createTestMessage(true); - _queue = createTestAMQQueue(true); - - _transaction.enqueue(_queue, _message, _action1); - - final long transactionStartTimeAfterFirstEnqueue = _transaction.getTransactionStartTime(); - final long transactionUpdateTimeAfterFirstEnqueue = _transaction.getTransactionUpdateTime(); - - Thread.sleep(1); - _transaction.enqueue(_queue, _message, _action2); - - final long transactionStartTimeAfterSecondEnqueue = _transaction.getTransactionStartTime(); - final long transactionUpdateTimeAfterSecondEnqueue = _transaction.getTransactionUpdateTime(); - - assertEquals("Transaction start time after second enqueue should be unchanged", transactionStartTimeAfterFirstEnqueue, transactionStartTimeAfterSecondEnqueue); - assertTrue("Transaction update time after second enqueue should be greater than first update time", transactionUpdateTimeAfterSecondEnqueue > transactionUpdateTimeAfterFirstEnqueue); - } - - public void testFirstDequeueRecordsTransactionStartAndUpdateTime() throws Exception - { - assertEquals("Unexpected transaction start time before test", 0, _transaction.getTransactionStartTime()); - assertEquals("Unexpected transaction update time before test", 0, _transaction.getTransactionUpdateTime()); - - _message = createTestMessage(true); - _queue = createTestAMQQueue(true); - - long startTime = System.currentTimeMillis(); - _transaction.dequeue(_queue, _message, _action1); - - assertTrue("Transaction start time should have been recorded", _transaction.getTransactionStartTime() >= startTime); - assertEquals("Transaction update time should be the same as transaction start time", _transaction.getTransactionStartTime(), _transaction.getTransactionUpdateTime()); - } - - public void testMixedEnqueuesAndDequeuesAdvancesTransactionUpdateTimeOnly() throws Exception - { - assertEquals("Unexpected transaction start time before test", 0, _transaction.getTransactionStartTime()); - assertEquals("Unexpected transaction update time before test", 0, _transaction.getTransactionUpdateTime()); - - _message = createTestMessage(true); - _queue = createTestAMQQueue(true); - - _transaction.enqueue(_queue, _message, _action1); - - final long transactionStartTimeAfterFirstEnqueue = _transaction.getTransactionStartTime(); - final long transactionUpdateTimeAfterFirstEnqueue = _transaction.getTransactionUpdateTime(); - - Thread.sleep(1); - _transaction.dequeue(_queue, _message, _action2); - - final long transactionStartTimeAfterFirstDequeue = _transaction.getTransactionStartTime(); - final long transactionUpdateTimeAfterFirstDequeue = _transaction.getTransactionUpdateTime(); - - assertEquals("Transaction start time after first dequeue should be unchanged", transactionStartTimeAfterFirstEnqueue, transactionStartTimeAfterFirstDequeue); - assertTrue("Transaction update time after first dequeue should be greater than first update time", transactionUpdateTimeAfterFirstDequeue > transactionUpdateTimeAfterFirstEnqueue); - } - - public void testCommitResetsTransactionStartAndUpdateTime() throws Exception - { - assertEquals("Unexpected transaction start time before test", 0, _transaction.getTransactionStartTime()); - assertEquals("Unexpected transaction update time before test", 0, _transaction.getTransactionUpdateTime()); - - _message = createTestMessage(true); - _queue = createTestAMQQueue(true); - - long startTime = System.currentTimeMillis(); - _transaction.enqueue(_queue, _message, _action1); - - assertTrue(_transaction.getTransactionStartTime() >= startTime); - assertTrue(_transaction.getTransactionUpdateTime() >= startTime); - - _transaction.commit(); - - assertEquals("Transaction start time should be reset after commit", 0, _transaction.getTransactionStartTime()); - assertEquals("Transaction update time should be reset after commit", 0, _transaction.getTransactionUpdateTime()); - } - - public void testRollbackResetsTransactionStartAndUpdateTime() throws Exception - { - assertEquals("Unexpected transaction start time before test", 0, _transaction.getTransactionStartTime()); - assertEquals("Unexpected transaction update time before test", 0, _transaction.getTransactionUpdateTime()); - - _message = createTestMessage(true); - _queue = createTestAMQQueue(true); - - long startTime = System.currentTimeMillis(); - _transaction.enqueue(_queue, _message, _action1); - - assertTrue(_transaction.getTransactionStartTime() >= startTime); - assertTrue(_transaction.getTransactionUpdateTime() >= startTime); - - _transaction.rollback(); - - assertEquals("Transaction start time should be reset after rollback", 0, _transaction.getTransactionStartTime()); - assertEquals("Transaction update time should be reset after rollback", 0, _transaction.getTransactionUpdateTime()); - } - - private Collection<QueueEntry> createTestQueueEntries(boolean[] queueDurableFlags, boolean[] messagePersistentFlags) - { - Collection<QueueEntry> queueEntries = new ArrayList<QueueEntry>(); - - assertTrue("Boolean arrays must be the same length", queueDurableFlags.length == messagePersistentFlags.length); - - for(int i = 0; i < queueDurableFlags.length; i++) - { - final AMQQueue queue = createTestAMQQueue(queueDurableFlags[i]); - final ServerMessage message = createTestMessage(messagePersistentFlags[i]); - - queueEntries.add(new MockQueueEntry() - { - - @Override - public ServerMessage getMessage() - { - return message; - } - - @Override - public AMQQueue getQueue() - { - return queue; - } - - }); - } - - return queueEntries; - } - - private MockStoreTransaction createTestStoreTransaction(boolean throwException) - { - return new MockStoreTransaction(throwException); - } - - private List<AMQQueue> createTestBaseQueues(boolean[] durableFlags) - { - List<AMQQueue> queues = new ArrayList<AMQQueue>(); - for (boolean b: durableFlags) - { - queues.add(createTestAMQQueue(b)); - } - - return queues; - } - - private AMQQueue createTestAMQQueue(final boolean durable) - { - return new MockAMQQueue("mockQueue") - { - @Override - public boolean isDurable() - { - return durable; - } - - }; - } - - private ServerMessage createTestMessage(final boolean persistent) - { - return new MockServerMessage(persistent); - } - - private void assertNotFired(MockAction action) - { - assertFalse("Rollback action must not be fired", action.isRollbackActionFired()); - assertFalse("Post commit action must not be fired", action.isPostCommitActionFired()); - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/MockAction.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/MockAction.java deleted file mode 100644 index 15c135ea2c..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/MockAction.java +++ /dev/null @@ -1,54 +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.txn; - -import org.apache.qpid.server.txn.ServerTransaction.Action; - -/** - * Mock implementation of a ServerTranaction Action - * allowing its state to be observed. - * - */ -class MockAction implements Action -{ - private boolean _rollbackFired = false; - private boolean _postCommitFired = false; - - public void postCommit() - { - _postCommitFired = true; - } - - public void onRollback() - { - _rollbackFired = true; - } - - public boolean isRollbackActionFired() - { - return _rollbackFired; - } - - public boolean isPostCommitActionFired() - { - return _postCommitFired; - } -}
\ No newline at end of file diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/MockServerMessage.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/MockServerMessage.java deleted file mode 100644 index aa5b555b3b..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/MockServerMessage.java +++ /dev/null @@ -1,110 +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.txn; - -import org.apache.commons.lang.NotImplementedException; - -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.message.MessageReference; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.store.StoredMessage; - -import java.nio.ByteBuffer; - -/** - * Mock Server Message allowing its persistent flag to be controlled from test. - */ -class MockServerMessage implements ServerMessage -{ - /** - * - */ - private final boolean persistent; - - /** - * @param persistent - */ - MockServerMessage(boolean persistent) - { - this.persistent = persistent; - } - - public boolean isPersistent() - { - return persistent; - } - - public MessageReference newReference() - { - throw new NotImplementedException(); - } - - public boolean isImmediate() - { - throw new NotImplementedException(); - } - - public long getSize() - { - throw new NotImplementedException(); - } - - public String getRoutingKey() - { - throw new NotImplementedException(); - } - - public AMQMessageHeader getMessageHeader() - { - throw new NotImplementedException(); - } - - public StoredMessage getStoredMessage() - { - throw new NotImplementedException(); - } - - public long getExpiration() - { - throw new NotImplementedException(); - } - - public int getContent(ByteBuffer buf, int offset) - { - throw new NotImplementedException(); - } - - - public ByteBuffer getContent(int offset, int size) - { - throw new NotImplementedException(); - } - - public long getArrivalTime() - { - throw new NotImplementedException(); - } - - public long getMessageNumber() - { - return 0L; - } -}
\ No newline at end of file diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/MockStoreTransaction.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/MockStoreTransaction.java deleted file mode 100644 index 0221f3d509..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/MockStoreTransaction.java +++ /dev/null @@ -1,135 +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.txn; - -import org.apache.commons.lang.NotImplementedException; -import org.apache.qpid.AMQStoreException; -import org.apache.qpid.server.message.EnqueableMessage; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.NullMessageStore; -import org.apache.qpid.server.store.StoreFuture; -import org.apache.qpid.server.store.Transaction; -import org.apache.qpid.server.store.TransactionLogResource; - -/** - * Mock implementation of a (Store) Transaction allow its state to be observed. - * Also provide a factory method to produce TestTransactionLog objects suitable - * for unit test use. - * - */ -class MockStoreTransaction implements Transaction -{ - enum TransactionState {NOT_STARTED, STARTED, COMMITTED, ABORTED}; - - private TransactionState _state = TransactionState.NOT_STARTED; - - private int _numberOfEnqueuedMessages = 0; - private int _numberOfDequeuedMessages = 0; - private boolean _throwExceptionOnQueueOp; - - public MockStoreTransaction(boolean throwExceptionOnQueueOp) - { - _throwExceptionOnQueueOp = throwExceptionOnQueueOp; - } - - public void setState(TransactionState state) - { - _state = state; - } - - public TransactionState getState() - { - return _state; - } - - public void enqueueMessage(TransactionLogResource queue, EnqueableMessage message) throws AMQStoreException - { - if (_throwExceptionOnQueueOp) - { - - throw new AMQStoreException("Mocked exception"); - } - - _numberOfEnqueuedMessages++; - } - - public int getNumberOfDequeuedMessages() - { - return _numberOfDequeuedMessages; - } - - public int getNumberOfEnqueuedMessages() - { - return _numberOfEnqueuedMessages; - } - - public void dequeueMessage(TransactionLogResource queue, EnqueableMessage message) throws AMQStoreException - { - if (_throwExceptionOnQueueOp) - { - throw new AMQStoreException("Mocked exception"); - } - - _numberOfDequeuedMessages++; - } - - public void commitTran() throws AMQStoreException - { - _state = TransactionState.COMMITTED; - } - - public StoreFuture commitTranAsync() throws AMQStoreException - { - throw new NotImplementedException(); - } - - public void abortTran() throws AMQStoreException - { - _state = TransactionState.ABORTED; - } - - public void removeXid(long format, byte[] globalId, byte[] branchId) - { - } - - public void recordXid(long format, byte[] globalId, byte[] branchId, Record[] enqueues, Record[] dequeues) - { - } - - public static MessageStore createTestTransactionLog(final MockStoreTransaction storeTransaction) - { - return new NullMessageStore() - { - @Override - public Transaction newTransaction() - { - storeTransaction.setState(TransactionState.STARTED); - return storeTransaction; - } - - @Override - public String getStoreType() - { - return "TEST"; - } - }; - } -}
\ No newline at end of file diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/util/BrokerTestHelper.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/util/BrokerTestHelper.java deleted file mode 100644 index cb1fc2737d..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/util/BrokerTestHelper.java +++ /dev/null @@ -1,190 +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.util; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.net.SocketAddress; -import java.util.Collections; -import java.util.UUID; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.configuration.PropertiesConfiguration; -import org.apache.qpid.AMQException; -import org.apache.qpid.server.protocol.AMQConnectionModel; -import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.configuration.VirtualHostConfiguration; -import org.apache.qpid.server.configuration.store.JsonConfigurationEntryStore; -import org.apache.qpid.server.exchange.DefaultExchangeFactory; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.logging.RootMessageLogger; -import org.apache.qpid.server.logging.SystemOutMessageLogger; -import org.apache.qpid.server.logging.actors.CurrentActor; -import org.apache.qpid.server.logging.actors.GenericActor; -import org.apache.qpid.server.logging.actors.TestLogActor; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.UUIDGenerator; -import org.apache.qpid.server.queue.AMQQueueFactory; -import org.apache.qpid.server.queue.SimpleAMQQueue; -import org.apache.qpid.server.security.SecurityManager; -import org.apache.qpid.server.security.SubjectCreator; -import org.apache.qpid.server.stats.StatisticsGatherer; -import org.apache.qpid.server.store.TestableMemoryMessageStore; -import org.apache.qpid.server.virtualhost.StandardVirtualHostFactory; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.plugin.VirtualHostFactory; -import org.apache.qpid.server.virtualhost.VirtualHostRegistry; - -public class BrokerTestHelper -{ - - protected static final String BROKER_STORE_CLASS_NAME_KEY = "brokerstore.class.name"; - protected static final String JSON_BROKER_STORE_CLASS_NAME = JsonConfigurationEntryStore.class.getName(); - - public static Broker createBrokerMock() - { - SubjectCreator subjectCreator = mock(SubjectCreator.class); - when(subjectCreator.getMechanisms()).thenReturn(""); - Broker broker = mock(Broker.class); - when(broker.getAttribute(Broker.CONNECTION_SESSION_COUNT_LIMIT)).thenReturn(1); - when(broker.getAttribute(Broker.CONNECTION_CLOSE_WHEN_NO_ROUTE)).thenReturn(false); - when(broker.getAttribute(Broker.VIRTUALHOST_HOUSEKEEPING_CHECK_PERIOD)).thenReturn(10000l); - when(broker.getId()).thenReturn(UUID.randomUUID()); - when(broker.getSubjectCreator(any(SocketAddress.class))).thenReturn(subjectCreator); - RootMessageLogger rootMessageLogger = CurrentActor.get().getRootMessageLogger(); - when(broker.getRootMessageLogger()).thenReturn(rootMessageLogger); - when(broker.getVirtualHostRegistry()).thenReturn(new VirtualHostRegistry()); - when(broker.getSecurityManager()).thenReturn(new SecurityManager(mock(Broker.class), false)); - GenericActor.setDefaultMessageLogger(rootMessageLogger); - return broker; - } - - public static void setUp() - { - CurrentActor.set(new TestLogActor(new SystemOutMessageLogger())); - } - - public static void tearDown() - { - CurrentActor.remove(); - } - - public static VirtualHost createVirtualHost(VirtualHostConfiguration virtualHostConfiguration, VirtualHostRegistry virtualHostRegistry) - throws Exception - { - return createVirtualHost(virtualHostConfiguration, virtualHostRegistry, mock(org.apache.qpid.server.model.VirtualHost.class)); - } - - public static VirtualHost createVirtualHost(VirtualHostConfiguration virtualHostConfiguration, VirtualHostRegistry virtualHostRegistry, org.apache.qpid.server.model.VirtualHost modelVHost) - throws Exception - { - StatisticsGatherer statisticsGatherer = mock(StatisticsGatherer.class); - final VirtualHostFactory factory = - virtualHostConfiguration == null ? new StandardVirtualHostFactory() - : VirtualHostFactory.FACTORIES.get(virtualHostConfiguration.getType()); - VirtualHost host = factory.createVirtualHost(virtualHostRegistry, - statisticsGatherer, - new SecurityManager(mock(Broker.class), false), - virtualHostConfiguration, - modelVHost); - if(virtualHostRegistry != null) - { - virtualHostRegistry.registerVirtualHost(host); - } - return host; - } - - public static VirtualHost createVirtualHost(VirtualHostConfiguration virtualHostConfiguration) throws Exception - { - return createVirtualHost(virtualHostConfiguration, null); - } - - public static VirtualHost createVirtualHost(String name, VirtualHostRegistry virtualHostRegistry) throws Exception - { - VirtualHostConfiguration vhostConfig = createVirtualHostConfiguration(name); - return createVirtualHost(vhostConfig, virtualHostRegistry); - } - - public static VirtualHost createVirtualHost(String name) throws Exception - { - VirtualHostConfiguration configuration = createVirtualHostConfiguration(name); - return createVirtualHost(configuration); - } - - private static VirtualHostConfiguration createVirtualHostConfiguration(String name) throws ConfigurationException - { - VirtualHostConfiguration vhostConfig = new VirtualHostConfiguration(name, new PropertiesConfiguration(), createBrokerMock()); - vhostConfig.setMessageStoreClass(TestableMemoryMessageStore.class.getName()); - return vhostConfig; - } - - public static AMQSessionModel createSession(int channelId, AMQConnectionModel connection) throws AMQException - { - AMQSessionModel session = mock(AMQSessionModel.class); - when(session.getConnectionModel()).thenReturn(connection); - when(session.getChannelId()).thenReturn(channelId); - return session; - } - - public static AMQSessionModel createSession(int channelId) throws Exception - { - AMQConnectionModel session = createConnection(); - return createSession(channelId, session); - } - - public static AMQSessionModel createSession() throws Exception - { - return createSession(1); - } - - public static AMQConnectionModel createConnection() throws Exception - { - return createConnection("test"); - } - - public static AMQConnectionModel createConnection(String hostName) throws Exception - { - VirtualHost virtualHost = createVirtualHost(hostName); - AMQConnectionModel connection = mock(AMQConnectionModel.class); - return connection; - } - - public static Exchange createExchange(String hostName) throws Exception - { - SecurityManager securityManager = new SecurityManager(mock(Broker.class), false); - VirtualHost virtualHost = mock(VirtualHost.class); - when(virtualHost.getName()).thenReturn(hostName); - when(virtualHost.getSecurityManager()).thenReturn(securityManager); - DefaultExchangeFactory factory = new DefaultExchangeFactory(virtualHost); - return factory.createExchange("amp.direct", "direct", false, false); - } - - public static SimpleAMQQueue createQueue(String queueName, VirtualHost virtualHost) throws AMQException - { - SimpleAMQQueue queue = (SimpleAMQQueue) virtualHost.createQueue(UUIDGenerator.generateRandomUUID(), queueName, false, null, - false, false, false, Collections.<String, Object>emptyMap()); - return queue; - } - - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/util/MapJsonSerializerTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/util/MapJsonSerializerTest.java deleted file mode 100644 index 56567523df..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/util/MapJsonSerializerTest.java +++ /dev/null @@ -1,53 +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.util; - -import java.util.HashMap; -import java.util.Map; - -import junit.framework.TestCase; - -public class MapJsonSerializerTest extends TestCase -{ - private MapJsonSerializer _serializer; - - protected void setUp() throws Exception - { - super.setUp(); - _serializer = new MapJsonSerializer(); - - } - - public void testSerializeDeserialize() - { - Map<String, Object> testMap = new HashMap<String, Object>(); - testMap.put("string", "Test String"); - testMap.put("integer", new Integer(10)); - testMap.put("long", new Long(Long.MAX_VALUE)); - testMap.put("boolean", Boolean.TRUE); - - String jsonString = _serializer.serialize(testMap); - Map<String, Object> deserializedMap = _serializer.deserialize(jsonString); - - assertEquals(deserializedMap, testMap); - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/util/StringUtilTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/util/StringUtilTest.java deleted file mode 100644 index 29dc54a8f8..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/util/StringUtilTest.java +++ /dev/null @@ -1,58 +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.util; - -import org.apache.qpid.server.util.StringUtil; -import org.apache.qpid.test.utils.QpidTestCase; - -public class StringUtilTest extends QpidTestCase -{ - private StringUtil _util; - - @Override - public void setUp() throws Exception - { - super.setUp(); - _util = new StringUtil(); - } - - public void testRandomAlphaNumericStringInt() - { - String password = _util.randomAlphaNumericString(10); - assertEquals("Unexpected password string length", 10, password.length()); - assertCharacters(password); - } - - private void assertCharacters(String password) - { - String numbers = "0123456789"; - String letters = "abcdefghijklmnopqrstuvwxwy"; - String others = "_-"; - String expectedCharacters = (numbers + letters + letters.toUpperCase() + others); - char[] chars = password.toCharArray(); - for (int i = 0; i < chars.length; i++) - { - char ch = chars[i]; - assertTrue("Unexpected character " + ch, expectedCharacters.indexOf(ch) != -1); - } - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/DurableConfigurationRecovererTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/DurableConfigurationRecovererTest.java deleted file mode 100644 index 987a541d05..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/DurableConfigurationRecovererTest.java +++ /dev/null @@ -1,479 +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.virtualhost; - -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.UUID; -import org.apache.qpid.AMQStoreException; -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.exchange.DirectExchange; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.exchange.ExchangeFactory; -import org.apache.qpid.server.exchange.ExchangeRegistry; -import org.apache.qpid.server.exchange.HeadersExchange; -import org.apache.qpid.server.exchange.TopicExchange; -import org.apache.qpid.server.logging.LogActor; -import org.apache.qpid.server.logging.actors.CurrentActor; -import org.apache.qpid.server.model.Binding; -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.plugin.ExchangeType; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.QueueFactory; -import org.apache.qpid.server.store.ConfiguredObjectRecord; -import org.apache.qpid.server.store.DurableConfigurationRecoverer; -import org.apache.qpid.server.store.DurableConfigurationStore; -import org.apache.qpid.server.store.DurableConfiguredObjectRecoverer; -import org.apache.qpid.test.utils.QpidTestCase; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyBoolean; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import static org.apache.qpid.server.model.VirtualHost.CURRENT_CONFIG_VERSION; - -public class DurableConfigurationRecovererTest extends QpidTestCase -{ - private static final UUID QUEUE_ID = new UUID(0,0); - private static final UUID TOPIC_EXCHANGE_ID = new UUID(0,1); - private static final UUID DIRECT_EXCHANGE_ID = new UUID(0,2); - private static final String CUSTOM_EXCHANGE_NAME = "customExchange"; - - private DurableConfigurationRecoverer _durableConfigurationRecoverer; - private Exchange _directExchange; - private Exchange _topicExchange; - private VirtualHost _vhost; - private DurableConfigurationStore _store; - private ExchangeFactory _exchangeFactory; - private ExchangeRegistry _exchangeRegistry; - private QueueFactory _queueFactory; - - @Override - public void setUp() throws Exception - { - super.setUp(); - - - _directExchange = mock(Exchange.class); - when(_directExchange.getType()).thenReturn(DirectExchange.TYPE); - - - _topicExchange = mock(Exchange.class); - when(_topicExchange.getType()).thenReturn(TopicExchange.TYPE); - - AMQQueue queue = mock(AMQQueue.class); - - _vhost = mock(VirtualHost.class); - - _exchangeRegistry = mock(ExchangeRegistry.class); - when(_exchangeRegistry.getExchange(eq(DIRECT_EXCHANGE_ID))).thenReturn(_directExchange); - when(_exchangeRegistry.getExchange(eq(TOPIC_EXCHANGE_ID))).thenReturn(_topicExchange); - - when(_vhost.getQueue(eq(QUEUE_ID))).thenReturn(queue); - - final ArgumentCaptor<Exchange> registeredExchange = ArgumentCaptor.forClass(Exchange.class); - doAnswer(new Answer() - { - - @Override - public Object answer(final InvocationOnMock invocation) throws Throwable - { - Exchange exchange = registeredExchange.getValue(); - when(_exchangeRegistry.getExchange(eq(exchange.getId()))).thenReturn(exchange); - when(_exchangeRegistry.getExchange(eq(exchange.getName()))).thenReturn(exchange); - return null; - } - }).when(_exchangeRegistry).registerExchange(registeredExchange.capture()); - - - - final ArgumentCaptor<UUID> idArg = ArgumentCaptor.forClass(UUID.class); - final ArgumentCaptor<String> queueArg = ArgumentCaptor.forClass(String.class); - final ArgumentCaptor<Map> argsArg = ArgumentCaptor.forClass(Map.class); - - _queueFactory = mock(QueueFactory.class); - - when(_queueFactory.restoreQueue(idArg.capture(), queueArg.capture(), - anyString(), anyBoolean(), anyBoolean(), anyBoolean(), argsArg.capture())).then( - new Answer() - { - - @Override - public Object answer(final InvocationOnMock invocation) throws Throwable - { - final AMQQueue queue = mock(AMQQueue.class); - - final String queueName = queueArg.getValue(); - final UUID queueId = idArg.getValue(); - - when(queue.getName()).thenReturn(queueName); - when(queue.getId()).thenReturn(queueId); - when(_vhost.getQueue(eq(queueName))).thenReturn(queue); - when(_vhost.getQueue(eq(queueId))).thenReturn(queue); - - final ArgumentCaptor<Exchange> altExchangeArg = ArgumentCaptor.forClass(Exchange.class); - doAnswer( - new Answer() - { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable - { - final Exchange value = altExchangeArg.getValue(); - when(queue.getAlternateExchange()).thenReturn(value); - return null; - } - } - ).when(queue).setAlternateExchange(altExchangeArg.capture()); - - Map args = argsArg.getValue(); - if(args.containsKey(Queue.ALTERNATE_EXCHANGE)) - { - final UUID exchangeId = UUID.fromString(args.get(Queue.ALTERNATE_EXCHANGE).toString()); - final Exchange exchange = _exchangeRegistry.getExchange(exchangeId); - queue.setAlternateExchange(exchange); - } - return queue; - } - }); - - _exchangeFactory = mock(ExchangeFactory.class); - - - DurableConfiguredObjectRecoverer[] recoverers = { - new QueueRecoverer(_vhost, _exchangeRegistry, _queueFactory), - new ExchangeRecoverer(_exchangeRegistry, _exchangeFactory), - new BindingRecoverer(_vhost, _exchangeRegistry) - }; - - final Map<String, DurableConfiguredObjectRecoverer> recovererMap= new HashMap<String, DurableConfiguredObjectRecoverer>(); - for(DurableConfiguredObjectRecoverer recoverer : recoverers) - { - recovererMap.put(recoverer.getType(), recoverer); - } - _durableConfigurationRecoverer = - new DurableConfigurationRecoverer(_vhost.getName(), recovererMap, - new DefaultUpgraderProvider(_vhost, _exchangeRegistry)); - - _store = mock(DurableConfigurationStore.class); - - CurrentActor.set(mock(LogActor.class)); - } - - public void testUpgradeEmptyStore() throws Exception - { - _durableConfigurationRecoverer.beginConfigurationRecovery(_store, 0); - assertEquals("Did not upgrade to the expected version", - CURRENT_CONFIG_VERSION, - _durableConfigurationRecoverer.completeConfigurationRecovery()); - } - - public void testUpgradeNewerStoreFails() throws Exception - { - try - { - _durableConfigurationRecoverer.beginConfigurationRecovery(_store, CURRENT_CONFIG_VERSION + 1); - _durableConfigurationRecoverer.completeConfigurationRecovery(); - fail("Should not be able to start when config model is newer than current"); - } - catch (IllegalStateException e) - { - // pass - } - } - - public void testUpgradeRemovesBindingsToNonTopicExchanges() throws Exception - { - - _durableConfigurationRecoverer.beginConfigurationRecovery(_store, 0); - - _durableConfigurationRecoverer.configuredObject(new UUID(1, 0), - "org.apache.qpid.server.model.Binding", - createBinding("key", - DIRECT_EXCHANGE_ID, - QUEUE_ID, - "x-filter-jms-selector", - "wibble")); - - final ConfiguredObjectRecord[] expected = { - new ConfiguredObjectRecord(new UUID(1, 0), "Binding", - createBinding("key", DIRECT_EXCHANGE_ID, QUEUE_ID)) - }; - - verifyCorrectUpdates(expected); - - _durableConfigurationRecoverer.completeConfigurationRecovery(); - } - - - - public void testUpgradeOnlyRemovesSelectorBindings() throws Exception - { - - _durableConfigurationRecoverer.beginConfigurationRecovery(_store, 0); - - _durableConfigurationRecoverer.configuredObject(new UUID(1, 0), - "org.apache.qpid.server.model.Binding", - createBinding("key", - DIRECT_EXCHANGE_ID, - QUEUE_ID, - "x-filter-jms-selector", - "wibble", - "not-a-selector", - "moo")); - - - final UUID customExchangeId = new UUID(3,0); - - _durableConfigurationRecoverer.configuredObject(new UUID(2, 0), - "org.apache.qpid.server.model.Binding", - createBinding("key", - customExchangeId, - QUEUE_ID, - "x-filter-jms-selector", - "wibble", - "not-a-selector", - "moo")); - - _durableConfigurationRecoverer.configuredObject(customExchangeId, - "org.apache.qpid.server.model.Exchange", - createExchange(CUSTOM_EXCHANGE_NAME, HeadersExchange.TYPE)); - - final Exchange customExchange = mock(Exchange.class); - - when(_exchangeFactory.restoreExchange(eq(customExchangeId), - eq(CUSTOM_EXCHANGE_NAME), - eq(HeadersExchange.TYPE.getType()), - anyBoolean())).thenReturn(customExchange); - - final ConfiguredObjectRecord[] expected = { - new ConfiguredObjectRecord(new UUID(1, 0), "org.apache.qpid.server.model.Binding", - createBinding("key", DIRECT_EXCHANGE_ID, QUEUE_ID, "not-a-selector", "moo")), - new ConfiguredObjectRecord(new UUID(2, 0), "org.apache.qpid.server.model.Binding", - createBinding("key", customExchangeId, QUEUE_ID, "not-a-selector", "moo")) - }; - - verifyCorrectUpdates(expected); - - _durableConfigurationRecoverer.completeConfigurationRecovery(); - } - - - public void testUpgradeKeepsBindingsToTopicExchanges() throws Exception - { - - _durableConfigurationRecoverer.beginConfigurationRecovery(_store, 0); - - _durableConfigurationRecoverer.configuredObject(new UUID(1, 0), - "org.apache.qpid.server.model.Binding", - createBinding("key", - TOPIC_EXCHANGE_ID, - QUEUE_ID, - "x-filter-jms-selector", - "wibble")); - - final ConfiguredObjectRecord[] expected = { - new ConfiguredObjectRecord(new UUID(1, 0), "Binding", - createBinding("key", TOPIC_EXCHANGE_ID, QUEUE_ID, "x-filter-jms-selector", "wibble")) - }; - - verifyCorrectUpdates(expected); - - _durableConfigurationRecoverer.completeConfigurationRecovery(); - } - - public void testUpgradeDoesNotRecur() throws Exception - { - - _durableConfigurationRecoverer.beginConfigurationRecovery(_store, 2); - - _durableConfigurationRecoverer.configuredObject(new UUID(1, 0), - "Binding", - createBinding("key", - DIRECT_EXCHANGE_ID, - QUEUE_ID, - "x-filter-jms-selector", - "wibble")); - - doThrow(new RuntimeException("Update Should not be called")).when(_store).update(any(ConfiguredObjectRecord[].class)); - - _durableConfigurationRecoverer.completeConfigurationRecovery(); - } - - public void testFailsWithUnresolvedObjects() - { - _durableConfigurationRecoverer.beginConfigurationRecovery(_store, 2); - - - _durableConfigurationRecoverer.configuredObject(new UUID(1, 0), - "Binding", - createBinding("key", - new UUID(3,0), - QUEUE_ID, - "x-filter-jms-selector", - "wibble")); - - try - { - _durableConfigurationRecoverer.completeConfigurationRecovery(); - fail("Expected resolution to fail due to unknown object"); - } - catch(IllegalConfigurationException e) - { - assertEquals("Durable configuration has unresolved dependencies", e.getMessage()); - } - - } - - public void testFailsWithUnknownObjectType() - { - _durableConfigurationRecoverer.beginConfigurationRecovery(_store, 2); - - - try - { - final Map<String, Object> emptyArguments = Collections.emptyMap(); - _durableConfigurationRecoverer.configuredObject(new UUID(1, 0), - "Wibble", emptyArguments); - _durableConfigurationRecoverer.completeConfigurationRecovery(); - fail("Expected resolution to fail due to unknown object type"); - } - catch(IllegalConfigurationException e) - { - assertEquals("Unkown type for configured object: Wibble", e.getMessage()); - } - - - } - - public void testRecoveryOfQueueAlternateExchange() throws Exception - { - - final UUID queueId = new UUID(1, 0); - final UUID exchangeId = new UUID(2, 0); - - final Exchange customExchange = mock(Exchange.class); - - when(customExchange.getId()).thenReturn(exchangeId); - when(customExchange.getName()).thenReturn(CUSTOM_EXCHANGE_NAME); - - when(_exchangeFactory.restoreExchange(eq(exchangeId), - eq(CUSTOM_EXCHANGE_NAME), - eq(HeadersExchange.TYPE.getType()), - anyBoolean())).thenReturn(customExchange); - - _durableConfigurationRecoverer.beginConfigurationRecovery(_store, 2); - - _durableConfigurationRecoverer.configuredObject(queueId, Queue.class.getSimpleName(), - createQueue("testQueue", exchangeId)); - _durableConfigurationRecoverer.configuredObject(exchangeId, - org.apache.qpid.server.model.Exchange.class.getSimpleName(), - createExchange(CUSTOM_EXCHANGE_NAME, HeadersExchange.TYPE)); - - _durableConfigurationRecoverer.completeConfigurationRecovery(); - - assertEquals(customExchange, _vhost.getQueue(queueId).getAlternateExchange()); - } - - private void verifyCorrectUpdates(final ConfiguredObjectRecord[] expected) throws AMQStoreException - { - doAnswer(new Answer() - { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable - { - Object[] args = invocation.getArguments(); - assertEquals("Updated records are not as expected", new HashSet(Arrays.asList( - expected)), new HashSet(Arrays.asList(args))); - - return null; - } - }).when(_store).update(any(ConfiguredObjectRecord[].class)); - } - - private Map<String,Object> createBinding(String bindingKey, UUID exchangeId, UUID queueId, String... args) - { - Map<String, Object> binding = new LinkedHashMap<String, Object>(); - - binding.put("name", bindingKey); - binding.put(Binding.EXCHANGE, exchangeId.toString()); - binding.put(Binding.QUEUE, queueId.toString()); - Map<String,String> argumentMap = new LinkedHashMap<String, String>(); - if(args != null && args.length != 0) - { - String key = null; - for(String arg : args) - { - if(key == null) - { - key = arg; - } - else - { - argumentMap.put(key, arg); - key = null; - } - } - } - binding.put(Binding.ARGUMENTS, argumentMap); - return binding; - } - - - private Map<String, Object> createExchange(String name, ExchangeType<HeadersExchange> type) - { - Map<String, Object> exchange = new LinkedHashMap<String, Object>(); - - exchange.put(org.apache.qpid.server.model.Exchange.NAME, name); - exchange.put(org.apache.qpid.server.model.Exchange.TYPE, type.getType()); - - return exchange; - - } - - - private Map<String, Object> createQueue(String name, UUID alternateExchangeId) - { - Map<String, Object> queue = new LinkedHashMap<String, Object>(); - - queue.put(Queue.NAME, name); - if(alternateExchangeId != null) - { - queue.put(Queue.ALTERNATE_EXCHANGE, alternateExchangeId.toString()); - } - queue.put(Queue.EXCLUSIVE, false); - - return queue; - - } - -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/HouseKeepingTaskTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/HouseKeepingTaskTest.java deleted file mode 100644 index 8b4a52bb79..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/HouseKeepingTaskTest.java +++ /dev/null @@ -1,113 +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.virtualhost; - -import org.apache.qpid.server.logging.LogActor; -import org.apache.qpid.server.logging.NullRootMessageLogger; -import org.apache.qpid.server.logging.actors.CurrentActor; -import org.apache.qpid.server.logging.actors.TestLogActor; -import org.apache.qpid.test.utils.QpidTestCase; - -import java.util.concurrent.CountDownLatch; - -public class HouseKeepingTaskTest extends QpidTestCase -{ - /** - * Tests that the abstract HouseKeepingTask properly cleans up any LogActor - * it adds to the CurrentActor stack by verifying the CurrentActor set - * before task execution is the CurrentActor after execution. - */ - public void testCurrentActorStackBalance() throws Exception - { - //create and set a test actor - LogActor testActor = new TestLogActor(new NullRootMessageLogger()); - CurrentActor.set(testActor); - - //verify it is returned correctly before executing a HouseKeepingTask - assertEquals("Expected LogActor was not returned", testActor, CurrentActor.get()); - - final CountDownLatch latch = new CountDownLatch(1); - HouseKeepingTask testTask = new HouseKeepingTask(new MockVirtualHost("HouseKeepingTaskTestVhost")) - { - @Override - public void execute() - { - latch.countDown(); - } - }; - - //run the test HouseKeepingTask using the current Thread to influence its CurrentActor stack - testTask.run(); - - assertEquals("The expected LogActor was not returned, the CurrentActor stack has become unbalanced", - testActor, CurrentActor.get()); - assertEquals("HouseKeepingTask execute() method was not run", 0, latch.getCount()); - - //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/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/MockVirtualHost.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/MockVirtualHost.java deleted file mode 100644 index 1ca7ff1b65..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/MockVirtualHost.java +++ /dev/null @@ -1,304 +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.virtualhost; - -import java.util.Collection; -import java.util.Map; -import java.util.concurrent.ScheduledFuture; -import org.apache.qpid.AMQException; -import org.apache.qpid.server.configuration.VirtualHostConfiguration; -import org.apache.qpid.server.connection.IConnectionRegistry; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.plugin.ExchangeType; -import org.apache.qpid.server.protocol.LinkRegistry; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.QueueRegistry; -import org.apache.qpid.server.security.SecurityManager; -import org.apache.qpid.server.security.auth.manager.AuthenticationManager; -import org.apache.qpid.server.stats.StatisticsCounter; -import org.apache.qpid.server.store.DurableConfigurationStore; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.txn.DtxRegistry; - -import java.util.UUID; - -public class MockVirtualHost implements VirtualHost -{ - private String _name; - - public MockVirtualHost(String name) - { - _name = name; - } - - public void close() - { - - } - - @Override - public VirtualHostRegistry getVirtualHostRegistry() - { - return null; - } - - public AuthenticationManager getAuthenticationManager() - { - return null; - } - - public DtxRegistry getDtxRegistry() - { - return null; - } - - public VirtualHostConfiguration getConfiguration() - { - return null; - } - - public IConnectionRegistry getConnectionRegistry() - { - return null; - } - - public int getHouseKeepingActiveCount() - { - return 0; - } - - public long getHouseKeepingCompletedTaskCount() - { - return 0; - } - - public int getHouseKeepingPoolSize() - { - return 0; - } - - public long getHouseKeepingTaskCount() - { - return 0; - } - - public MessageStore getMessageStore() - { - return null; - } - - public DurableConfigurationStore getDurableConfigurationStore() - { - return null; - } - - public String getName() - { - return _name; - } - - public QueueRegistry getQueueRegistry() - { - return null; - } - - @Override - public AMQQueue getQueue(String name) - { - return null; - } - - @Override - public AMQQueue getQueue(UUID id) - { - return null; - } - - @Override - public Collection<AMQQueue> getQueues() - { - return null; - } - - @Override - public int removeQueue(AMQQueue queue) throws AMQException - { - return 0; - } - - @Override - public AMQQueue createQueue(UUID id, - String queueName, - boolean durable, - String owner, - boolean autoDelete, - boolean exclusive, - boolean deleteOnNoConsumer, - Map<String, Object> arguments) throws AMQException - { - return null; - } - - @Override - public Exchange createExchange(UUID id, - String exchange, - String type, - boolean durable, - boolean autoDelete, - String alternateExchange) throws AMQException - { - return null; - } - - @Override - public void removeExchange(Exchange exchange, boolean force) throws AMQException - { - } - - @Override - public Exchange getExchange(String name) - { - return null; - } - - @Override - public Exchange getExchange(UUID id) - { - return null; - } - - @Override - public Exchange getDefaultExchange() - { - return null; - } - - @Override - public Collection<Exchange> getExchanges() - { - return null; - } - - @Override - public Collection<ExchangeType<? extends Exchange>> getExchangeTypes() - { - return null; - } - - public SecurityManager getSecurityManager() - { - return null; - } - - @Override - public void addVirtualHostListener(VirtualHostListener listener) - { - } - - public LinkRegistry getLinkRegistry(String remoteContainerId) - { - return null; - } - - public ScheduledFuture<?> scheduleTask(long delay, Runnable timeoutTask) - { - return null; - } - - public void scheduleHouseKeepingTask(long period, HouseKeepingTask task) - { - - } - - public void setHouseKeepingPoolSize(int newSize) - { - - } - - - public long getCreateTime() - { - return 0; - } - - public UUID getId() - { - return null; - } - - public boolean isDurable() - { - return false; - } - - public StatisticsCounter getDataDeliveryStatistics() - { - return null; - } - - public StatisticsCounter getDataReceiptStatistics() - { - return null; - } - - public StatisticsCounter getMessageDeliveryStatistics() - { - return null; - } - - public StatisticsCounter getMessageReceiptStatistics() - { - return null; - } - - public void initialiseStatistics() - { - - } - - public void registerMessageDelivered(long messageSize) - { - - } - - public void registerMessageReceived(long messageSize, long timestamp) - { - - } - - public void resetStatistics() - { - - } - - public State getState() - { - return State.ACTIVE; - } - - public void block() - { - } - - public void unblock() - { - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/StandardVirtualHostTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/StandardVirtualHostTest.java deleted file mode 100644 index 03cb483e40..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/StandardVirtualHostTest.java +++ /dev/null @@ -1,376 +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.virtualhost; - -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.apache.commons.configuration.Configuration; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.configuration.PropertiesConfiguration; - -import org.apache.qpid.server.binding.Binding; -import org.apache.qpid.server.configuration.VirtualHostConfiguration; - -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.security.SecurityManager; -import org.apache.qpid.server.stats.StatisticsGatherer; -import org.apache.qpid.server.store.TestMemoryMessageStore; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.test.utils.QpidTestCase; - -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 StandardVirtualHostTest extends QpidTestCase -{ - private VirtualHostRegistry _virtualHostRegistry; - - @Override - public void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - } - - @Override - public void tearDown() throws Exception - { - try - { - if (_virtualHostRegistry != null) - { - _virtualHostRegistry.close(); - } - } - finally - { - BrokerTestHelper.tearDown(); - super.tearDown(); - } - - } - - /** - * Tests that custom routing keys for the queue specified in the configuration - * file are correctly bound to the exchange (in addition to the queue name) - */ - public void testSpecifyingCustomBindings() throws Exception - { - customBindingTestImpl(new String[]{"custom1","custom2"}); - } - - /** - * Tests that a queue specified in the configuration file to be bound to a - * specified(non-default) direct exchange is a correctly bound to the exchange - * and the default exchange using the queue name. - */ - public void testQueueSpecifiedInConfigurationIsBoundToDefaultExchange() throws Exception - { - customBindingTestImpl(new String[0]); - } - - /** - * Tests that specifying custom routing keys for a queue in the configuration file results in failure - * to create the vhost (since this is illegal, only queue names are used with the default exchange) - */ - public void testSpecifyingCustomBindingForDefaultExchangeThrowsException() throws Exception - { - final String queueName = getName(); - final String customBinding = "custom-binding"; - File config = writeConfigFile(queueName, queueName, null, false, new String[]{customBinding}); - - try - { - createVirtualHost(queueName, config); - fail("virtualhost creation should have failed due to illegal configuration"); - } - catch (ConfigurationException e) - { - assertEquals("Illegal attempt to bind queue '" + queueName + "' to the default exchange with a key other than the queue name: " + customBinding, e.getMessage()); - } - } - - public void testVirtualHostBecomesActive() throws Exception - { - File config = writeConfigFile(getName(), getName(), getName() +".direct", false, new String[0]); - VirtualHost vhost = createVirtualHost(getName(), config); - assertNotNull(vhost); - assertEquals(State.ACTIVE, vhost.getState()); - } - - public void testVirtualHostHavingStoreSetAsTypeBecomesActive() throws Exception - { - String virtualHostName = getName(); - VirtualHost host = createVirtualHostUsingStoreType(virtualHostName); - assertNotNull(host); - assertEquals(State.ACTIVE, host.getState()); - } - - public void testVirtualHostBecomesStoppedOnClose() throws Exception - { - File config = writeConfigFile(getName(), getName(), getName() +".direct", false, new String[0]); - VirtualHost vhost = createVirtualHost(getName(), config); - assertNotNull(vhost); - assertEquals(State.ACTIVE, vhost.getState()); - vhost.close(); - assertEquals(State.STOPPED, vhost.getState()); - assertEquals(0, vhost.getHouseKeepingActiveCount()); - } - - public void testVirtualHostHavingStoreSetAsTypeBecomesStoppedOnClose() throws Exception - { - String virtualHostName = getName(); - VirtualHost host = createVirtualHostUsingStoreType(virtualHostName); - assertNotNull(host); - assertEquals(State.ACTIVE, host.getState()); - host.close(); - assertEquals(State.STOPPED, host.getState()); - assertEquals(0, host.getHouseKeepingActiveCount()); - } - - /** - * Tests that specifying an unknown exchange to bind the queue to results in failure to create the vhost - */ - public void testSpecifyingUnknownExchangeThrowsException() throws Exception - { - final String queueName = getName(); - final String exchangeName = "made-up-exchange"; - File config = writeConfigFile(queueName, queueName, exchangeName, true, new String[0]); - - try - { - createVirtualHost(queueName, config); - fail("virtualhost creation should have failed due to illegal configuration"); - } - catch (ConfigurationException e) - { - assertEquals("Attempt to bind queue '" + queueName + "' to unknown exchange:" + exchangeName, e.getMessage()); - } - } - - public void testCreateVirtualHostWithoutConfigurationInConfigFile() throws Exception - { - File config = writeConfigFile(getName(), getName(), getName() +".direct", false, new String[0]); - String hostName = getName() + "-not-existing"; - try - { - createVirtualHost(hostName, config); - fail("virtualhost creation should have failed due to illegal configuration"); - } - catch (RuntimeException e) - { - assertEquals("No configuration found for virtual host '" + hostName + "' in " + config.getAbsolutePath(), e.getMessage()); - } - } - - public void testBindingArguments() throws Exception - { - String exchangeName = getName() +".direct"; - String vhostName = getName(); - String queueName = getName(); - - Map<String, String[]> bindingArguments = new HashMap<String, String[]>(); - bindingArguments.put("ping", new String[]{"x-filter-jms-selector=select=1", "x-qpid-no-local"}); - bindingArguments.put("pong", new String[]{"x-filter-jms-selector=select='pong'"}); - File config = writeConfigFile(vhostName, queueName, exchangeName, false, new String[]{"ping","pong"}, bindingArguments); - VirtualHost vhost = createVirtualHost(vhostName, config); - - Exchange exch = vhost.getExchange(getName() +".direct"); - Collection<Binding> bindings = exch.getBindings(); - assertNotNull("Bindings cannot be null", bindings); - assertEquals("Unexpected number of bindings", 3, bindings.size()); - - boolean foundPong = false; - boolean foundPing = false; - for (Binding binding : bindings) - { - String qn = binding.getQueue().getName(); - assertEquals("Unexpected queue name", getName(), qn); - Map<String, Object> arguments = binding.getArguments(); - - if ("ping".equals(binding.getBindingKey())) - { - foundPing = true; - assertEquals("Unexpected number of binding arguments for ping", 2, arguments.size()); - assertEquals("Unexpected x-filter-jms-selector for ping", "select=1", arguments.get("x-filter-jms-selector")); - assertTrue("Unexpected x-qpid-no-local for ping", arguments.containsKey("x-qpid-no-local")); - } - else if ("pong".equals(binding.getBindingKey())) - { - foundPong = true; - assertEquals("Unexpected number of binding arguments for pong", 1, arguments.size()); - assertEquals("Unexpected x-filter-jms-selector for pong", "select='pong'", arguments.get("x-filter-jms-selector")); - } - } - - assertTrue("Pong binding is not found", foundPong); - assertTrue("Ping binding is not found", foundPing); - } - - private void customBindingTestImpl(final String[] routingKeys) throws Exception - { - String exchangeName = getName() +".direct"; - String vhostName = getName(); - String queueName = getName(); - - File config = writeConfigFile(vhostName, queueName, exchangeName, false, routingKeys); - VirtualHost vhost = createVirtualHost(vhostName, config); - assertNotNull("virtualhost should exist", vhost); - - AMQQueue queue = vhost.getQueue(queueName); - assertNotNull("queue should exist", queue); - - Exchange defaultExch = vhost.getDefaultExchange(); - assertTrue("queue should have been bound to default exchange with its name", defaultExch.isBound(queueName, queue)); - - Exchange exch = vhost.getExchange(exchangeName); - assertTrue("queue should have been bound to " + exchangeName + " with its name", exch.isBound(queueName, queue)); - - for(String key: routingKeys) - { - assertTrue("queue should have been bound to " + exchangeName + " with key " + key, exch.isBound(key, queue)); - } - } - - - private VirtualHost createVirtualHost(String vhostName, File config) throws Exception - { - Broker broker = BrokerTestHelper.createBrokerMock(); - _virtualHostRegistry = broker.getVirtualHostRegistry(); - - VirtualHostConfiguration configuration = new VirtualHostConfiguration(vhostName, config, broker); - VirtualHost host = new StandardVirtualHostFactory().createVirtualHost(_virtualHostRegistry, mock(StatisticsGatherer.class), new SecurityManager(mock(Broker.class), false), configuration, - mock(org.apache.qpid.server.model.VirtualHost.class)); - _virtualHostRegistry.registerVirtualHost(host); - - return host; - } - - /** - * Create a configuration file for testing virtualhost creation - * - * @param vhostName name of the virtualhost - * @param queueName name of the queue - * @param exchangeName name of a direct exchange to declare (unless dontDeclare = true) and bind the queue to (null = none) - * @param dontDeclare if true then dont declare the exchange, even if its name is non-null - * @param routingKeys routingKeys to bind the queue with (empty array = none) - * @return - */ - private File writeConfigFile(String vhostName, String queueName, String exchangeName, boolean dontDeclare, String[] routingKeys) - { - return writeConfigFile(vhostName, queueName, exchangeName, dontDeclare, routingKeys, null); - } - - private File writeConfigFile(String vhostName, String queueName, String exchangeName, boolean dontDeclare, String[] routingKeys, Map<String, String[]> bindingArguments) - { - File tmpFile = null; - try - { - tmpFile = File.createTempFile(getName(), ".tmp"); - tmpFile.deleteOnExit(); - - FileWriter fstream = new FileWriter(tmpFile); - BufferedWriter writer = new BufferedWriter(fstream); - - //extra outer tag to please Commons Configuration - - writer.write("<virtualhosts>"); - writer.write(" <default>" + vhostName + "</default>"); - writer.write(" <virtualhost>"); - writer.write(" <name>" + vhostName + "</name>"); - writer.write(" <" + vhostName + ">"); - writer.write(" <type>" + StandardVirtualHostFactory.TYPE + "</type>"); - writer.write(" <store>"); - writer.write(" <class>" + TestMemoryMessageStore.class.getName() + "</class>"); - writer.write(" </store>"); - if(exchangeName != null && !dontDeclare) - { - writer.write(" <exchanges>"); - writer.write(" <exchange>"); - writer.write(" <type>direct</type>"); - writer.write(" <name>" + exchangeName + "</name>"); - writer.write(" </exchange>"); - writer.write(" </exchanges>"); - } - writer.write(" <queues>"); - writer.write(" <queue>"); - writer.write(" <name>" + queueName + "</name>"); - writer.write(" <" + queueName + ">"); - if(exchangeName != null) - { - writer.write(" <exchange>" + exchangeName + "</exchange>"); - } - for(String routingKey: routingKeys) - { - writer.write(" <routingKey>" + routingKey + "</routingKey>\n"); - if (bindingArguments!= null && bindingArguments.containsKey(routingKey)) - { - writer.write(" <" + routingKey + ">\n"); - String[] arguments = (String[])bindingArguments.get(routingKey); - for (String argument : arguments) - { - writer.write(" <bindingArgument>" + argument + "</bindingArgument>\n"); - } - writer.write(" </" + routingKey + ">\n"); - } - } - writer.write(" </" + queueName + ">"); - writer.write(" </queue>"); - writer.write(" </queues>"); - writer.write(" </" + vhostName + ">"); - writer.write(" </virtualhost>"); - writer.write("</virtualhosts>"); - - writer.flush(); - writer.close(); - } - catch (IOException e) - { - fail("Unable to create virtualhost configuration"); - } - - return tmpFile; - } - - private VirtualHost createVirtualHostUsingStoreType(String virtualHostName) throws ConfigurationException, Exception - { - Broker broker = BrokerTestHelper.createBrokerMock(); - _virtualHostRegistry = broker.getVirtualHostRegistry(); - - Configuration config = new PropertiesConfiguration(); - VirtualHostConfiguration configuration = new VirtualHostConfiguration(virtualHostName, config, broker); - final org.apache.qpid.server.model.VirtualHost virtualHost = mock(org.apache.qpid.server.model.VirtualHost.class); - when(virtualHost.getAttribute(eq(org.apache.qpid.server.model.VirtualHost.STORE_TYPE))).thenReturn(TestMemoryMessageStore.TYPE); - VirtualHost host = new StandardVirtualHostFactory().createVirtualHost(_virtualHostRegistry, mock(StatisticsGatherer.class), new SecurityManager(mock(Broker.class), false), configuration, - virtualHost); - _virtualHostRegistry.registerVirtualHost(host); - return host; - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/tools/security/PasswdTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/tools/security/PasswdTest.java deleted file mode 100644 index b2a7234c8a..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/tools/security/PasswdTest.java +++ /dev/null @@ -1,38 +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.tools.security; - -import junit.framework.TestCase; - -public class PasswdTest extends TestCase -{ - public void testUserGuestAndPasswordGuest() throws Exception - { - Passwd passwd = new Passwd(); - String output = passwd.getOutput("guest", "guest"); - assertEquals("guest:CE4DQ6BIb/BVMN9scFyLtA==", output); - } - - public void testUser1AndPasswordFoo() throws Exception - { - Passwd passwd = new Passwd(); - String output = passwd.getOutput("user1", "foo"); - assertEquals("user1:rL0Y20zC+Fzt72VPzMSk2A==", output); - } -} diff --git a/qpid/java/broker/src/test/resources/META-INF/services/org.apache.qpid.server.plugin.MessageStoreFactory b/qpid/java/broker/src/test/resources/META-INF/services/org.apache.qpid.server.plugin.MessageStoreFactory deleted file mode 100644 index 9512fb8117..0000000000 --- a/qpid/java/broker/src/test/resources/META-INF/services/org.apache.qpid.server.plugin.MessageStoreFactory +++ /dev/null @@ -1,19 +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. -# -org.apache.qpid.server.store.TestMemoryMessageStoreFactory |
