diff options
author | Kim van der Riet <kpvdr@apache.org> | 2013-02-28 16:14:30 +0000 |
---|---|---|
committer | Kim van der Riet <kpvdr@apache.org> | 2013-02-28 16:14:30 +0000 |
commit | 9c73ef7a5ac10acd6a50d5d52bd721fc2faa5919 (patch) | |
tree | 2a890e1df09e5b896a9b4168a7b22648f559a1f2 /java/broker/src/test | |
parent | 172d9b2a16cfb817bbe632d050acba7e31401cd2 (diff) | |
download | qpid-python-asyncstore.tar.gz |
Update from trunk r1375509 through r1450773asyncstore
git-svn-id: https://svn.apache.org/repos/asf/qpid/branches/asyncstore@1451244 13f79535-47bb-0310-9956-ffa450edef68
Diffstat (limited to 'java/broker/src/test')
117 files changed, 7565 insertions, 5811 deletions
diff --git a/java/broker/src/test/java/org/apache/qpid/server/AMQChannelTest.java b/java/broker/src/test/java/org/apache/qpid/server/AMQChannelTest.java index fc6cbcb248..e10bdbbb35 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/AMQChannelTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/AMQChannelTest.java @@ -20,23 +20,69 @@ */ package org.apache.qpid.server; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.qpid.AMQException; +import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.framing.BasicContentHeaderProperties; +import org.apache.qpid.framing.ContentHeaderBody; +import org.apache.qpid.framing.abstraction.MessagePublishInfo; +import org.apache.qpid.server.configuration.BrokerProperties; +import org.apache.qpid.server.exchange.Exchange; +import org.apache.qpid.server.message.MessageContentSource; +import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.protocol.AMQProtocolSession; import org.apache.qpid.server.protocol.InternalTestProtocolSession; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.util.InternalBrokerBaseCase; +import org.apache.qpid.server.util.BrokerTestHelper; import org.apache.qpid.server.virtualhost.VirtualHost; +import org.apache.qpid.test.utils.QpidTestCase; -public class AMQChannelTest extends InternalBrokerBaseCase +public class AMQChannelTest extends QpidTestCase { private VirtualHost _virtualHost; private AMQProtocolSession _protocolSession; + private Map<Integer,String> _replies; + private Broker _broker; @Override public void setUp() throws Exception { super.setUp(); - _virtualHost = ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHosts().iterator().next(); - _protocolSession = new InternalTestProtocolSession(_virtualHost); + BrokerTestHelper.setUp(); + _virtualHost = BrokerTestHelper.createVirtualHost(getTestName()); + _broker = BrokerTestHelper.createBrokerMock(); + _protocolSession = new InternalTestProtocolSession(_virtualHost, _broker) + { + @Override + public void writeReturn(MessagePublishInfo messagePublishInfo, + ContentHeaderBody header, + MessageContentSource msgContent, + int channelId, + int replyCode, + AMQShortString replyText) throws AMQException + { + _replies.put(replyCode, replyText.asString()); + } + }; + _replies = new HashMap<Integer, String>(); + } + + @Override + public void tearDown() throws Exception + { + try + { + _virtualHost.close(); + } + finally + { + BrokerTestHelper.tearDown(); + super.tearDown(); + } } public void testCompareTo() throws Exception @@ -44,9 +90,54 @@ public class AMQChannelTest extends InternalBrokerBaseCase AMQChannel channel1 = new AMQChannel(_protocolSession, 1, _virtualHost.getMessageStore()); // create a channel with the same channelId but on a different session - AMQChannel channel2 = new AMQChannel(new InternalTestProtocolSession(_virtualHost), 1, _virtualHost.getMessageStore()); + AMQChannel channel2 = new AMQChannel(new InternalTestProtocolSession(_virtualHost, _broker), 1, _virtualHost.getMessageStore()); assertFalse("Unexpected compare result", channel1.compareTo(channel2) == 0); assertEquals("Unexpected compare result", 0, channel1.compareTo(channel1)); } + public void testPublishContentHeaderWhenMessageAuthorizationFails() throws Exception + { + setTestSystemProperty(BrokerProperties.PROPERTY_MSG_AUTH, "true"); + AMQChannel channel = new AMQChannel(_protocolSession, 1, _virtualHost.getMessageStore()); + channel.setLocalTransactional(); + + MessagePublishInfo info = mock(MessagePublishInfo.class); + Exchange e = mock(Exchange.class); + ContentHeaderBody contentHeaderBody= mock(ContentHeaderBody.class); + BasicContentHeaderProperties properties = mock(BasicContentHeaderProperties.class); + + when(contentHeaderBody.getProperties()).thenReturn(properties); + when(info.getExchange()).thenReturn(new AMQShortString("test")); + when(properties.getUserId()).thenReturn(new AMQShortString(_protocolSession.getAuthorizedPrincipal().getName() + "_incorrect")); + + channel.setPublishFrame(info, e); + channel.publishContentHeader(contentHeaderBody); + channel.commit(); + + assertEquals("Unexpected number of replies", 1, _replies.size()); + assertEquals("Message authorization passed", "Access Refused", _replies.get(403)); + } + + public void testPublishContentHeaderWhenMessageAuthorizationPasses() throws Exception + { + setTestSystemProperty(BrokerProperties.PROPERTY_MSG_AUTH, "true"); + AMQChannel channel = new AMQChannel(_protocolSession, 1, _virtualHost.getMessageStore()); + channel.setLocalTransactional(); + + MessagePublishInfo info = mock(MessagePublishInfo.class); + Exchange e = mock(Exchange.class); + ContentHeaderBody contentHeaderBody= mock(ContentHeaderBody.class); + BasicContentHeaderProperties properties = mock(BasicContentHeaderProperties.class); + + when(contentHeaderBody.getProperties()).thenReturn(properties); + when(info.getExchange()).thenReturn(new AMQShortString("test")); + when(properties.getUserId()).thenReturn(new AMQShortString(_protocolSession.getAuthorizedPrincipal().getName())); + + channel.setPublishFrame(info, e); + channel.publishContentHeader(contentHeaderBody); + channel.commit(); + + assertEquals("Unexpected number of replies", 0, _replies.size()); + } + } diff --git a/java/broker/src/test/java/org/apache/qpid/server/BrokerOptionsTest.java b/java/broker/src/test/java/org/apache/qpid/server/BrokerOptionsTest.java index 43824e713f..16b459b5d4 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/BrokerOptionsTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/BrokerOptionsTest.java @@ -22,91 +22,36 @@ package org.apache.qpid.server; import org.apache.qpid.test.utils.QpidTestCase; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - - public class BrokerOptionsTest extends QpidTestCase { private BrokerOptions _options; - - private static final int TEST_PORT1 = 6789; - private static final int TEST_PORT2 = 6790; - protected void setUp() { _options = new BrokerOptions(); } - - public void testDefaultPort() - { - assertEquals(Collections.<Integer>emptySet(), _options.getPorts()); - } - public void testOverriddenPort() + public void testDefaultConfigurationStoreType() { - _options.addPort(TEST_PORT1); - assertEquals(Collections.singleton(TEST_PORT1), _options.getPorts()); + assertEquals("json", _options.getConfigurationStoreType()); } - public void testManyOverriddenPorts() + public void testOverriddenConfigurationStoreType() { - _options.addPort(TEST_PORT1); - _options.addPort(TEST_PORT2); - final Set<Integer> expectedPorts = new HashSet<Integer>(Arrays.asList(new Integer[] {TEST_PORT1, TEST_PORT2})); - assertEquals(expectedPorts, _options.getPorts()); + _options.setConfigurationStoreType("dby"); + assertEquals("dby", _options.getConfigurationStoreType()); } - public void testDuplicateOverriddenPortsAreSilentlyIgnored() + public void testDefaultConfigurationStoreLocation() { - _options.addPort(TEST_PORT1); - _options.addPort(TEST_PORT2); - _options.addPort(TEST_PORT1); // duplicate - should be silently ignored - final Set<Integer> expectedPorts = new HashSet<Integer>(Arrays.asList(new Integer[] {TEST_PORT1, TEST_PORT2})); - assertEquals(expectedPorts, _options.getPorts()); + assertNull(_options.getConfigurationStoreLocation()); } - public void testDefaultSSLPort() - { - assertEquals(Collections.<Integer>emptySet(), _options.getSSLPorts()); - } - - public void testOverriddenSSLPort() - { - _options.addSSLPort(TEST_PORT1); - assertEquals(Collections.singleton(TEST_PORT1), _options.getSSLPorts()); - } - - public void testManyOverriddenSSLPorts() - { - _options.addSSLPort(TEST_PORT1); - _options.addSSLPort(TEST_PORT2); - final Set<Integer> expectedPorts = new HashSet<Integer>(Arrays.asList(new Integer[] {TEST_PORT1, TEST_PORT2})); - assertEquals(expectedPorts, _options.getSSLPorts()); - } - - public void testDuplicateOverriddenSSLPortsAreSilentlyIgnored() - { - _options.addSSLPort(TEST_PORT1); - _options.addSSLPort(TEST_PORT2); - _options.addSSLPort(TEST_PORT1); // duplicate - should be silently ignored - final Set<Integer> expectedPorts = new HashSet<Integer>(Arrays.asList(new Integer[] {TEST_PORT1, TEST_PORT2})); - assertEquals(expectedPorts, _options.getSSLPorts()); - } - - public void testDefaultConfigFile() - { - assertNull(_options.getConfigFile()); - } - - public void testOverriddenConfigFile() + public void testOverriddenConfigurationStoreLocation() { final String testConfigFile = "etc/mytestconfig.xml"; - _options.setConfigFile(testConfigFile); - assertEquals(testConfigFile, _options.getConfigFile()); + _options.setConfigurationStoreLocation(testConfigFile); + assertEquals(testConfigFile, _options.getConfigurationStoreLocation()); } public void testDefaultLogConfigFile() @@ -121,109 +66,85 @@ public class BrokerOptionsTest extends QpidTestCase assertEquals(testLogConfigFile, _options.getLogConfigFile()); } - public void testDefaultJmxPortRegistryServer() + public void testDefaultLogWatchFrequency() { - assertNull(_options.getJmxPortRegistryServer()); + assertEquals(0L, _options.getLogWatchFrequency()); } - public void testJmxPortRegistryServer() + public void testOverridenLogWatchFrequency() { - _options.setJmxPortRegistryServer(TEST_PORT1); - assertEquals(Integer.valueOf(TEST_PORT1), _options.getJmxPortRegistryServer()); + final int myFreq = 10 * 1000; + + _options.setLogWatchFrequency(myFreq); + assertEquals(myFreq, _options.getLogWatchFrequency()); } - public void testDefaultJmxPortConnectorServer() - { - assertNull(_options.getJmxPortConnectorServer()); - } - public void testJmxPortConnectorServer() + public void testDefaultInitialConfigurationStoreType() { - _options.setJmxPortConnectorServer(TEST_PORT1); - assertEquals(Integer.valueOf(TEST_PORT1), _options.getJmxPortConnectorServer()); + assertEquals("json", _options.getInitialConfigurationStoreType()); } - public void testQpidHomeExposesSysProperty() + public void testOverriddenInitialConfigurationStoreType() { - assertEquals(System.getProperty("QPID_HOME"), _options.getQpidHome()); - } - - public void testDefaultExcludesPortFor0_10() - { - assertEquals(Collections.EMPTY_SET, _options.getExcludedPorts(ProtocolExclusion.v0_10)); - } - - public void testOverriddenExcludesPortFor0_10() - { - _options.addExcludedPort(ProtocolExclusion.v0_10, TEST_PORT1); - assertEquals(Collections.singleton(TEST_PORT1), _options.getExcludedPorts(ProtocolExclusion.v0_10)); + _options.setInitialConfigurationStoreType("dby"); + assertEquals("dby", _options.getInitialConfigurationStoreType()); } - public void testManyOverriddenExcludedPortFor0_10() + public void testDefaultInitialConfigurationStoreLocation() { - _options.addExcludedPort(ProtocolExclusion.v0_10, TEST_PORT1); - _options.addExcludedPort(ProtocolExclusion.v0_10, TEST_PORT2); - final Set<Integer> expectedPorts = new HashSet<Integer>(Arrays.asList(new Integer[] {TEST_PORT1, TEST_PORT2})); - assertEquals(expectedPorts, _options.getExcludedPorts(ProtocolExclusion.v0_10)); + assertNull(_options.getInitialConfigurationStoreLocation()); } - public void testDuplicatedOverriddenExcludedPortFor0_10AreSilentlyIgnored() + public void testOverriddenInitialConfigurationStoreLocation() { - _options.addExcludedPort(ProtocolExclusion.v0_10, TEST_PORT1); - _options.addExcludedPort(ProtocolExclusion.v0_10, TEST_PORT2); - final Set<Integer> expectedPorts = new HashSet<Integer>(Arrays.asList(new Integer[] {TEST_PORT1, TEST_PORT2})); - assertEquals(expectedPorts, _options.getExcludedPorts(ProtocolExclusion.v0_10)); + final String testConfigFile = "etc/mytestconfig.xml"; + _options.setInitialConfigurationStoreLocation(testConfigFile); + assertEquals(testConfigFile, _options.getInitialConfigurationStoreLocation()); } - - public void testDefaultBind() + + public void testDefaultManagementMode() { - assertNull(_options.getBind()); + assertEquals(false, _options.isManagementMode()); } - - public void testOverriddenBind() + + public void testOverriddenDefaultManagementMode() { - final String bind = "192.168.0.1"; - _options.setBind(bind); - assertEquals(bind, _options.getBind()); + _options.setManagementMode(true); + assertEquals(true, _options.isManagementMode()); } - public void testDefaultLogWatchFrequency() + public void testDefaultManagementModeRmiPort() { - assertEquals(0L, _options.getLogWatchFrequency()); + assertEquals(0, _options.getManagementModeRmiPort()); } - public void testOverridenLogWatchFrequency() + public void testOverriddenDefaultManagementModeRmiPort() { - final int myFreq = 10 * 1000; - - _options.setLogWatchFrequency(myFreq); - assertEquals(myFreq, _options.getLogWatchFrequency()); + _options.setManagementModeRmiPort(5555); + assertEquals(5555, _options.getManagementModeRmiPort()); } - public void testDefaultIncludesPortFor0_10() + public void testDefaultManagementModeConnectorPort() { - assertEquals(Collections.EMPTY_SET, _options.getIncludedPorts(ProtocolInclusion.v0_10)); + assertEquals(0, _options.getManagementModeConnectorPort()); } - public void testOverriddenIncludesPortFor0_10() + public void testOverriddenDefaultManagementModeConnectorPort() { - _options.addIncludedPort(ProtocolInclusion.v0_10, TEST_PORT1); - assertEquals(Collections.singleton(TEST_PORT1), _options.getIncludedPorts(ProtocolInclusion.v0_10)); + _options.setManagementModeConnectorPort(5555); + assertEquals(5555, _options.getManagementModeConnectorPort()); } - public void testManyOverriddenIncludedPortFor0_10() + public void testDefaultManagementModeHttpPort() { - _options.addIncludedPort(ProtocolInclusion.v0_10, TEST_PORT1); - _options.addIncludedPort(ProtocolInclusion.v0_10, TEST_PORT2); - final Set<Integer> expectedPorts = new HashSet<Integer>(Arrays.asList(new Integer[] {TEST_PORT1, TEST_PORT2})); - assertEquals(expectedPorts, _options.getIncludedPorts(ProtocolInclusion.v0_10)); + assertEquals(0, _options.getManagementModeHttpPort()); } - public void testDuplicatedOverriddenIncludedPortFor0_10AreSilentlyIgnored() + public void testOverriddenDefaultManagementModeHttpPort() { - _options.addIncludedPort(ProtocolInclusion.v0_10, TEST_PORT1); - _options.addIncludedPort(ProtocolInclusion.v0_10, TEST_PORT2); - final Set<Integer> expectedPorts = new HashSet<Integer>(Arrays.asList(new Integer[] {TEST_PORT1, TEST_PORT2})); - assertEquals(expectedPorts, _options.getIncludedPorts(ProtocolInclusion.v0_10)); + _options.setManagementModeHttpPort(5555); + assertEquals(5555, _options.getManagementModeHttpPort()); } + } diff --git a/java/broker/src/test/java/org/apache/qpid/server/MainTest.java b/java/broker/src/test/java/org/apache/qpid/server/MainTest.java index ffd607574e..cab54b1310 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/MainTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/MainTest.java @@ -23,8 +23,6 @@ package org.apache.qpid.server; import org.apache.commons.cli.CommandLine; import org.apache.qpid.test.utils.QpidTestCase; -import java.util.EnumSet; - /** * Test to verify the command line parsing within the Main class, by * providing it a series of command line arguments and verifying the @@ -36,149 +34,135 @@ public class MainTest extends QpidTestCase { BrokerOptions options = startDummyMain(""); - assertTrue(options.getPorts().isEmpty()); - assertTrue(options.getSSLPorts().isEmpty()); - assertEquals(null, options.getJmxPortRegistryServer()); - assertEquals(null, options.getConfigFile()); + assertEquals("json", options.getConfigurationStoreType()); + assertEquals(null, options.getConfigurationStoreLocation()); assertEquals(null, options.getLogConfigFile()); - assertEquals(null, options.getBind()); - - for(ProtocolExclusion pe : EnumSet.allOf(ProtocolExclusion.class)) - { - assertEquals(0, options.getExcludedPorts(pe).size()); - } + assertEquals(0, options.getLogWatchFrequency()); + assertEquals("json", options.getInitialConfigurationStoreType()); + assertEquals(null, options.getInitialConfigurationStoreLocation()); - for(ProtocolInclusion pe : EnumSet.allOf(ProtocolInclusion.class)) - { - assertEquals(0, options.getIncludedPorts(pe).size()); - } + assertFalse(options.isManagementMode()); + assertEquals(0, options.getManagementModeConnectorPort()); + assertEquals(0, options.getManagementModeRmiPort()); + assertEquals(0, options.getManagementModeHttpPort()); } - public void testPortOverriddenSingle() + public void testConfigurationStoreLocation() { - BrokerOptions options = startDummyMain("-p 1234"); + BrokerOptions options = startDummyMain("-sp abcd/config.xml"); + assertEquals("abcd/config.xml", options.getConfigurationStoreLocation()); - assertTrue(options.getPorts().contains(1234)); - assertEquals(1, options.getPorts().size()); - assertTrue(options.getSSLPorts().isEmpty()); + options = startDummyMain("-store-path abcd/config2.xml"); + assertEquals("abcd/config2.xml", options.getConfigurationStoreLocation()); } - public void testPortOverriddenMultiple() + public void testConfigurationStoreType() { - BrokerOptions options = startDummyMain("-p 1234 -p 4321"); + BrokerOptions options = startDummyMain("-st dby"); + assertEquals("dby", options.getConfigurationStoreType()); - assertTrue(options.getPorts().contains(1234)); - assertTrue(options.getPorts().contains(4321)); - assertEquals(2, options.getPorts().size()); - assertTrue(options.getSSLPorts().isEmpty()); + options = startDummyMain("-store-type bdb"); + assertEquals("bdb", options.getConfigurationStoreType()); } - public void testSSLPortOverriddenSingle() + public void testLogConfig() { - BrokerOptions options = startDummyMain("-s 5678"); + BrokerOptions options = startDummyMain("-l wxyz/log4j.xml"); - assertTrue(options.getSSLPorts().contains(5678)); - assertEquals(1, options.getSSLPorts().size()); - assertTrue(options.getPorts().isEmpty()); + assertEquals("wxyz/log4j.xml", options.getLogConfigFile()); } - public void testSSLPortOverriddenMultiple() + public void testLogWatch() { - BrokerOptions options = startDummyMain("-s 5678 -s 8765"); + BrokerOptions options = startDummyMain("-w 9"); - assertTrue(options.getSSLPorts().contains(5678)); - assertTrue(options.getSSLPorts().contains(8765)); - assertEquals(2, options.getSSLPorts().size()); - assertTrue(options.getPorts().isEmpty()); + assertEquals(9, options.getLogWatchFrequency()); } - public void testNonSSLandSSLPortsOverridden() + public void testVersion() { - BrokerOptions options = startDummyMain("-p 5678 -s 8765"); + final TestMain main = new TestMain("-v".split("\\s")); - assertTrue(options.getPorts().contains(5678)); - assertTrue(options.getSSLPorts().contains(8765)); - assertEquals(1, options.getPorts().size()); - assertEquals(1, options.getSSLPorts().size()); + assertNotNull("Command line not parsed correctly", main.getCommandLine()); + assertTrue("Parsed command line didnt pick up version option", main.getCommandLine().hasOption("v")); } - public void testJmxPortRegistryServerOverridden() + public void testHelp() { - BrokerOptions options = startDummyMain("--jmxregistryport 3456"); - - assertEquals(Integer.valueOf(3456), options.getJmxPortRegistryServer()); + final TestMain main = new TestMain("-h".split("\\s")); - options = startDummyMain("-m 3457"); - assertEquals(Integer.valueOf(3457), options.getJmxPortRegistryServer()); + assertNotNull("Command line not parsed correctly", main.getCommandLine()); + assertTrue("Parsed command line didnt pick up help option", main.getCommandLine().hasOption("h")); } - public void testJmxPortConnectorServerOverridden() + public void testInitailConfigurationStoreLocation() { - BrokerOptions options = startDummyMain("--jmxconnectorport 3456"); + BrokerOptions options = startDummyMain("-isp abcd/config.xml"); + assertEquals("abcd/config.xml", options.getInitialConfigurationStoreLocation()); - assertEquals(Integer.valueOf(3456), options.getJmxPortConnectorServer()); + options = startDummyMain("-initial-store-path abcd/config.xml"); + assertEquals("abcd/config.xml", options.getInitialConfigurationStoreLocation()); } - public void testExclude0_10() + public void testInitialConfigurationStoreType() { - BrokerOptions options = startDummyMain("-p 3456 --exclude-0-10 3456"); + BrokerOptions options = startDummyMain("-ist dby"); + assertEquals("dby", options.getInitialConfigurationStoreType()); - assertTrue(options.getPorts().contains(3456)); - assertEquals(1, options.getPorts().size()); - assertTrue(options.getExcludedPorts(ProtocolExclusion.v0_10).contains(3456)); - assertEquals(1, options.getExcludedPorts(ProtocolExclusion.v0_10).size()); - assertEquals(0, options.getExcludedPorts(ProtocolExclusion.v0_9_1).size()); - } - - public void testConfig() - { - BrokerOptions options = startDummyMain("-c abcd/config.xml"); + options = startDummyMain("-initial-store-type bdb"); + assertEquals("bdb", options.getInitialConfigurationStoreType()); - assertEquals("abcd/config.xml", options.getConfigFile()); } - public void testLogConfig() + public void testManagementMode() { - BrokerOptions options = startDummyMain("-l wxyz/log4j.xml"); + BrokerOptions options = startDummyMain("-mm"); + assertTrue(options.isManagementMode()); - assertEquals("wxyz/log4j.xml", options.getLogConfigFile()); + options = startDummyMain("--management-mode"); + assertTrue(options.isManagementMode()); } - public void testLogWatch() + public void testManagementModeRmiPort() { - BrokerOptions options = startDummyMain("-w 9"); + BrokerOptions options = startDummyMain("-mm -rmi 7777"); + assertTrue(options.isManagementMode()); + assertEquals(7777, options.getManagementModeRmiPort()); - assertEquals(9, options.getLogWatchFrequency()); + options = startDummyMain("-mm --jmxregistryport 7777"); + assertTrue(options.isManagementMode()); + assertEquals(7777, options.getManagementModeRmiPort()); + + options = startDummyMain("-rmi 7777"); + assertEquals(0, options.getManagementModeRmiPort()); } - public void testVersion() + public void testManagementModeConnectorPort() { - final TestMain main = new TestMain("-v".split("\\s")); + BrokerOptions options = startDummyMain("-mm -jmxrmi 8888"); + assertTrue(options.isManagementMode()); + assertEquals(8888, options.getManagementModeConnectorPort()); - assertNotNull("Command line not parsed correctly", main.getCommandLine()); - assertTrue("Parsed command line didnt pick up version option", main.getCommandLine().hasOption("v")); + options = startDummyMain("-mm --jmxconnectorport 8888"); + assertTrue(options.isManagementMode()); + assertEquals(8888, options.getManagementModeConnectorPort()); + + options = startDummyMain("-jmxrmi 8888"); + assertEquals(0, options.getManagementModeConnectorPort()); } - public void testHelp() + public void testManagementModeHttpPort() { - final TestMain main = new TestMain("-h".split("\\s")); + BrokerOptions options = startDummyMain("-mm -http 9999"); + assertTrue(options.isManagementMode()); + assertEquals(9999, options.getManagementModeHttpPort()); - assertNotNull("Command line not parsed correctly", main.getCommandLine()); - assertTrue("Parsed command line didnt pick up help option", main.getCommandLine().hasOption("h")); - } + options = startDummyMain("-mm --httpport 9999"); + assertTrue(options.isManagementMode()); + assertEquals(9999, options.getManagementModeHttpPort()); - public void testInclude010() - { - BrokerOptions options = startDummyMain("-p 5678 --include-0-10 5678"); - - assertTrue(options.getPorts().contains(5678)); - assertEquals(1, options.getPorts().size()); - assertTrue(options.getIncludedPorts(ProtocolInclusion.v0_10).contains(5678)); - assertEquals(1, options.getIncludedPorts(ProtocolInclusion.v0_10).size()); - assertEquals(0, options.getIncludedPorts(ProtocolInclusion.v0_9_1).size()); - assertEquals(0, options.getIncludedPorts(ProtocolInclusion.v0_9).size()); - assertEquals(0, options.getIncludedPorts(ProtocolInclusion.v0_8).size()); - assertEquals(0, options.getIncludedPorts(ProtocolInclusion.v1_0).size()); + options = startDummyMain("-http 9999"); + assertEquals(0, options.getManagementModeHttpPort()); } private BrokerOptions startDummyMain(String commandLine) diff --git a/java/broker/src/test/java/org/apache/qpid/server/TransactionTimeoutHelperTest.java b/java/broker/src/test/java/org/apache/qpid/server/TransactionTimeoutHelperTest.java index 9081dc49d6..96078d766c 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/TransactionTimeoutHelperTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/TransactionTimeoutHelperTest.java @@ -18,67 +18,131 @@ */ package org.apache.qpid.server; -import static org.mockito.Matchers.any; +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.never; 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.RootMessageLogger; 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 LogMessage _logMessage = mock(LogMessage.class); 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 RootMessageLogger _rootMessageLogger; + private long _now; - public void testLogIfNecessary() + public void testNotTransactional() throws Exception { - _transactionTimeoutHelper.logIfNecessary(99, 100, _logMessage, ""); - verifyZeroInteractions(_logActor, _logMessage); + when(_transaction.isTransactional()).thenReturn(false); - _transactionTimeoutHelper.logIfNecessary(101, 100, _logMessage, ""); - verify(_logActor).message(_logSubject, _logMessage); + _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 testLogIfNecessaryWhenOperationalLoggingDisabled() + public void testOpenTransactionProducesWarningAndTimeoutAction() throws Exception { - //disable the operational logging - when(_rootMessageLogger.isMessageEnabled( - same(_logActor), any(LogSubject.class), any(String.class))) - .thenReturn(false); - - //verify the actor is never asked to log a message - _transactionTimeoutHelper.logIfNecessary(101, 100, _logMessage, ""); - verify(_logActor, never()).message(any(LogMessage.class)); - verify(_logActor, never()).message(any(LogSubject.class), any(LogMessage.class)); + 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 testIsTimedOut() + public void testIdleTransactionProducesWarningOnly() throws Exception { - assertFalse("Shouldn't have timed out", _transactionTimeoutHelper.isTimedOut(199,200)); - assertTrue("Should have timed out", _transactionTimeoutHelper.isTimedOut(201,200)); + 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); } - /** - * If TransactionTimeout is disabled, the timeout will be 0. This test verifies - * that the helper methods respond negatively in this scenario. - */ - public void testTransactionTimeoutDisabled() + public void testIdleTransactionProducesTimeoutActionOnly() throws Exception { - assertFalse("Shouldn't have timed out", _transactionTimeoutHelper.isTimedOut(201,0)); + final long sixtyOneSecondsAgo = _now - SECONDS.toMillis(61); + final long thrityOneSecondsAgo = _now - SECONDS.toMillis(31); + + configureMockTransaction(sixtyOneSecondsAgo, thrityOneSecondsAgo); - _transactionTimeoutHelper.logIfNecessary(99, 0, _logMessage, ""); - verifyZeroInteractions(_logActor, _logMessage); + _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 @@ -88,14 +152,79 @@ public class TransactionTimeoutHelperTest extends QpidTestCase CurrentActor.set(_logActor); - _rootMessageLogger = mock(RootMessageLogger.class); - when(_logActor.getRootMessageLogger()).thenReturn(_rootMessageLogger); + _transactionTimeoutHelper = new TransactionTimeoutHelper(_logSubject, _closeAction); + _now = System.currentTimeMillis(); + } + + @Override + protected void tearDown() throws Exception + { + try + { + super.tearDown(); + } + finally + { + CurrentActor.remove(); + } + } - when(_rootMessageLogger.isMessageEnabled( - same(_logActor), any(LogSubject.class), any(String.class))) - .thenReturn(true); + private void configureMockTransaction(final long startTime, final long updateTime) + { + when(_transaction.isTransactional()).thenReturn(true); + when(_transaction.getTransactionStartTime()).thenReturn(startTime); + when(_transaction.getTransactionUpdateTime()).thenReturn(updateTime); + } - _transactionTimeoutHelper = new TransactionTimeoutHelper(_logSubject); + 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/java/broker/src/test/java/org/apache/qpid/server/ack/AcknowledgeTest.java b/java/broker/src/test/java/org/apache/qpid/server/ack/AcknowledgeTest.java index b3223f16c4..4d6d60906d 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/ack/AcknowledgeTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/ack/AcknowledgeTest.java @@ -22,14 +22,72 @@ package org.apache.qpid.server.ack; import org.apache.qpid.AMQException; +import org.apache.qpid.exchange.ExchangeDefaults; import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.server.AMQChannel; +import org.apache.qpid.server.exchange.Exchange; import org.apache.qpid.server.protocol.InternalTestProtocolSession; -import org.apache.qpid.server.util.InternalBrokerBaseCase; +import org.apache.qpid.server.queue.SimpleAMQQueue; +import org.apache.qpid.server.store.MessageStore; +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.test.utils.QpidTestCase; import java.util.List; -public class AcknowledgeTest extends InternalBrokerBaseCase +public class AcknowledgeTest extends QpidTestCase { + private AMQChannel _channel; + private SimpleAMQQueue _queue; + private MessageStore _messageStore; + private String _queueName; + + @Override + public void setUp() throws Exception + { + super.setUp(); + BrokerTestHelper.setUp(); + _channel = BrokerTestHelper.createChannel(); + VirtualHost virtualHost = _channel.getVirtualHost(); + _queueName = getTestName(); + _queue = BrokerTestHelper.createQueue(_queueName, virtualHost); + _messageStore = virtualHost.getMessageStore(); + Exchange defaultExchange = virtualHost.getExchangeRegistry().getDefaultExchange(); + virtualHost.getBindingFactory().addBinding(_queueName, _queue, defaultExchange, null); + } + + @Override + public void tearDown() throws Exception + { + try + { + if (_channel != null) + { + _channel.getVirtualHost().close(); + } + } + finally + { + BrokerTestHelper.tearDown(); + super.tearDown(); + } + } + + private AMQChannel getChannel() + { + return _channel; + } + + private InternalTestProtocolSession getSession() + { + return (InternalTestProtocolSession)_channel.getProtocolSession(); + } + + private SimpleAMQQueue getQueue() + { + return _queue; + } public void testTransactionalSingleAck() throws AMQException { @@ -70,7 +128,7 @@ public class AcknowledgeTest extends InternalBrokerBaseCase checkStoreContents(0); //Send required messsages to the queue - publishMessages(getSession(), getChannel(), sendMessageCount); + BrokerTestHelper.publishMessages(getChannel(), sendMessageCount, _queueName, ExchangeDefaults.DEFAULT_EXCHANGE_NAME.asString()); if (getChannel().isTransactional()) { @@ -84,7 +142,7 @@ public class AcknowledgeTest extends InternalBrokerBaseCase assertEquals("Channel should have no unacked msgs ", 0, getChannel().getUnacknowledgedMessageMap().size()); //Subscribe to the queue - AMQShortString subscriber = subscribe(getSession(), getChannel(), getQueue()); + AMQShortString subscriber = _channel.subscribeToQueue(null, _queue, true, null, false, true); getQueue().deliverAsync(); @@ -117,4 +175,9 @@ public class AcknowledgeTest extends InternalBrokerBaseCase checkStoreContents(remainingUnackedMessages); } + private void checkStoreContents(int messageCount) + { + assertEquals("Message header count incorrect in the MetaDataMap", messageCount, ((TestableMemoryMessageStore) _messageStore).getMessageCount()); + } + } diff --git a/java/broker/src/test/java/org/apache/qpid/server/configuration/BrokerConfigurationStoreCreatorTest.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/BrokerConfigurationStoreCreatorTest.java new file mode 100644 index 0000000000..fa1bd966a7 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/configuration/BrokerConfigurationStoreCreatorTest.java @@ -0,0 +1,144 @@ +/* + * + * 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.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +import org.apache.qpid.server.configuration.store.JsonConfigurationEntryStore; +import org.apache.qpid.server.model.Broker; +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); + } + _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", null, null); + 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(); + jsonStore.open(_userStoreLocation.getAbsolutePath()); + Set<UUID> childrenIds = jsonStore.getRootEntry().getChildrenIds(); + assertFalse("Unexpected children: " + childrenIds, childrenIds.isEmpty()); + } + + public void testCreateJsonStoreFromInitialStore() throws Exception + { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); + + Map<String, Object> brokerObjectMap = new HashMap<String, Object>(); + UUID brokerId = UUID.randomUUID(); + brokerObjectMap.put(Broker.ID, brokerId); + brokerObjectMap.put("name", "Test"); + + StringWriter sw = new StringWriter(); + objectMapper.writeValue(sw, brokerObjectMap); + + String brokerJson = sw.toString(); + + File _storeFile = TestFileUtils.createTempFile(this, ".json", brokerJson); + + ConfigurationEntryStore store = _storeCreator.createStore(_userStoreLocation.getAbsolutePath(), "json", _storeFile.getAbsolutePath(), "json"); + 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(); + jsonStore.open(_userStoreLocation.getAbsolutePath()); + ConfigurationEntry entry = jsonStore.getRootEntry(); + assertEquals("Unexpected root id", brokerId, entry.getId()); + Map<String, Object> attributes = entry.getAttributes(); + assertNotNull("Unexpected attributes: " + attributes, attributes); + assertEquals("Unexpected attributes size: " + attributes.size(), 1, attributes.size()); + assertEquals("Unexpected attribute name: " + attributes.get("name"), "Test", attributes.get("name")); + Set<UUID> childrenIds = entry.getChildrenIds(); + assertTrue("Unexpected children: " + childrenIds, childrenIds.isEmpty()); + } + + public void testCreateDerbyStore() + { + //TODO: Implement DERBY store + try + { + _storeCreator.createStore(_userStoreLocation.getAbsolutePath(), "derby", null, null); + fail("Store is not yet supported"); + } + catch(IllegalConfigurationException e) + { + // pass + } + } + + public void testCreateXmlStore() throws Exception + { + try + { + _storeCreator.createStore(_userStoreLocation.getAbsolutePath(), "xml", null, null); + fail("Store is not yet supported"); + } + catch(IllegalConfigurationException e) + { + // pass + } + } + +} diff --git a/java/broker/src/test/java/org/apache/qpid/server/configuration/BrokerPropertiesTest.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/BrokerPropertiesTest.java new file mode 100644 index 0000000000..5e9e19ffaf --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/configuration/BrokerPropertiesTest.java @@ -0,0 +1,51 @@ +/* + * + * 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/java/broker/src/test/java/org/apache/qpid/server/configuration/MockConnectionConfig.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/MockConnectionConfig.java deleted file mode 100644 index 00e5cd1222..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/configuration/MockConnectionConfig.java +++ /dev/null @@ -1,171 +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.UUID; - -public class MockConnectionConfig implements ConnectionConfig -{ - - public MockConnectionConfig(UUID _qmfId, ConnectionConfigType _configType, - ConfiguredObject<ConnectionConfigType, ConnectionConfig> _parent, boolean _durable, - long _createTime, VirtualHostConfig _virtualHost, String _address, Boolean _incoming, - Boolean _systemConnection, Boolean _federationLink, String _authId, String _remoteProcessName, - Integer _remotePID, Integer _remoteParentPID, ConfigStore _configStore, Boolean _shadow) - { - super(); - this._qmfId = _qmfId; - this._configType = _configType; - this._parent = _parent; - this._durable = _durable; - this._createTime = _createTime; - this._virtualHost = _virtualHost; - this._address = _address; - this._incoming = _incoming; - this._systemConnection = _systemConnection; - this._federationLink = _federationLink; - this._authId = _authId; - this._remoteProcessName = _remoteProcessName; - this._remotePID = _remotePID; - this._remoteParentPID = _remoteParentPID; - this._configStore = _configStore; - this._shadow = _shadow; - } - - private UUID _qmfId; - private ConnectionConfigType _configType; - private ConfiguredObject<ConnectionConfigType, ConnectionConfig> _parent; - private boolean _durable; - private long _createTime; - private VirtualHostConfig _virtualHost; - private String _address; - private Boolean _incoming; - private Boolean _systemConnection; - private Boolean _federationLink; - private String _authId; - private String _remoteProcessName; - private Integer _remotePID; - private Integer _remoteParentPID; - private ConfigStore _configStore; - private Boolean _shadow; - - @Override - public UUID getQMFId() - { - return _qmfId; - } - - @Override - public ConnectionConfigType getConfigType() - { - return _configType; - } - - @Override - public ConfiguredObject<ConnectionConfigType, ConnectionConfig> getParent() - { - return _parent; - } - - @Override - public boolean isDurable() - { - return _durable; - } - - @Override - public long getCreateTime() - { - return _createTime; - } - - @Override - public VirtualHostConfig getVirtualHost() - { - return _virtualHost; - } - - @Override - public String getAddress() - { - return _address; - } - - @Override - public Boolean isIncoming() - { - return _incoming; - } - - @Override - public Boolean isSystemConnection() - { - return _systemConnection; - } - - @Override - public Boolean isFederationLink() - { - return _federationLink; - } - - @Override - public String getAuthId() - { - return _authId; - } - - @Override - public String getRemoteProcessName() - { - return _remoteProcessName; - } - - @Override - public Integer getRemotePID() - { - return _remotePID; - } - - @Override - public Integer getRemoteParentPID() - { - return _remoteParentPID; - } - - @Override - public ConfigStore getConfigStore() - { - return _configStore; - } - - @Override - public Boolean isShadow() - { - return _shadow; - } - - @Override - public void mgmtClose() - { - } - -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/configuration/QueueConfigurationTest.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/QueueConfigurationTest.java index 3c5b85cd90..0bb65479ce 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/configuration/QueueConfigurationTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/configuration/QueueConfigurationTest.java @@ -20,25 +20,31 @@ */ package org.apache.qpid.server.configuration; +import static org.mockito.Mockito.when; + 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.registry.ApplicationRegistry; -import org.apache.qpid.server.util.TestApplicationRegistry; +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); + _emptyConf = new VirtualHostConfiguration("test", _env, _broker); PropertiesConfiguration fullEnv = new PropertiesConfiguration(); fullEnv.setProperty("queues.maximumMessageAge", 1); @@ -49,35 +55,41 @@ public class QueueConfigurationTest extends TestCase fullEnv.setProperty("queues.deadLetterQueues", true); fullEnv.setProperty("queues.maximumDeliveryCount", 5); - _fullHostConf = new VirtualHostConfiguration("test", fullEnv); + _fullHostConf = new VirtualHostConfiguration("test", fullEnv, _broker); } + @Override + public void tearDown() throws Exception + { + BrokerTestHelper.tearDown(); + super.tearDown(); + } + public void testMaxDeliveryCount() throws Exception { - try - { - ApplicationRegistry registry = new TestApplicationRegistry(new ServerConfiguration(_env)); - ApplicationRegistry.initialise(registry); - - // Check default value - QueueConfiguration qConf = new QueueConfiguration("test", _emptyConf); - assertEquals("Unexpected default server configuration for max delivery count ", 0, 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()); - - } - finally - { - ApplicationRegistry.remove(); - } + // broker MAXIMUM_DELIVERY_ATTEMPTS attribute is not set + when(_broker.getAttribute(Broker.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.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()); } /** @@ -87,28 +99,28 @@ public class QueueConfigurationTest extends TestCase */ public void testIsDeadLetterQueueEnabled() throws Exception { - try - { - ApplicationRegistry registry = new TestApplicationRegistry(new ServerConfiguration(_env)); - ApplicationRegistry.initialise(registry); - - // Check default value - QueueConfiguration 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()); - } - finally - { - ApplicationRegistry.remove(); - } + // enable dead letter queues broker wide + when(_broker.getAttribute(Broker.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.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 @@ -178,27 +190,28 @@ public class QueueConfigurationTest extends TestCase public void testGetMinimumAlertRepeatGap() throws Exception { - try - { - ApplicationRegistry registry = new TestApplicationRegistry(new ServerConfiguration(_env)); - ApplicationRegistry.initialise(registry); - // Check default value - QueueConfiguration qConf = new QueueConfiguration("test", _emptyConf); - assertEquals(ServerConfiguration.DEFAULT_MINIMUM_ALERT_REPEAT_GAP, qConf.getMinimumAlertRepeatGap()); - - // Check explicit value - VirtualHostConfiguration vhostConfig = overrideConfiguration("minimumAlertRepeatGap", 2); - qConf = new QueueConfiguration("test", vhostConfig); - assertEquals(2, qConf.getMinimumAlertRepeatGap()); - - // Check inherited value - qConf = new QueueConfiguration("test", _fullHostConf); - assertEquals(1, qConf.getMinimumAlertRepeatGap()); - } - finally - { - ApplicationRegistry.remove(); - } + // set broker attribute ALERT_REPEAT_GAP to 10 + when(_broker.getAttribute(Broker.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.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 @@ -235,6 +248,6 @@ public class QueueConfigurationTest extends TestCase config.addConfiguration(_fullHostConf.getConfig()); config.addConfiguration(queueConfig); - return new VirtualHostConfiguration("test", config); + return new VirtualHostConfiguration("test", config, _broker); } } diff --git a/java/broker/src/test/java/org/apache/qpid/server/configuration/ServerConfigurationTest.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/ServerConfigurationTest.java deleted file mode 100644 index 660ff5e7d4..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/configuration/ServerConfigurationTest.java +++ /dev/null @@ -1,1766 +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 org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.configuration.XMLConfiguration; - -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.protocol.AmqpProtocolVersion; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.registry.ConfigurationFileApplicationRegistry; -import org.apache.qpid.server.util.TestApplicationRegistry; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.virtualhost.VirtualHostRegistry; -import org.apache.qpid.test.utils.QpidTestCase; - -import static org.apache.qpid.transport.ConnectionSettings.WILDCARD_ADDRESS; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.Writer; -import java.util.Locale; - -import javax.net.ssl.KeyManagerFactory; - -public class ServerConfigurationTest extends QpidTestCase -{ - private XMLConfiguration _config = new XMLConfiguration(); - private ServerConfiguration _serverConfig = null; - - @Override - protected void setUp() throws Exception - { - super.setUp(); - _serverConfig = new ServerConfiguration(_config); - ApplicationRegistry.initialise(new TestApplicationRegistry(_serverConfig)); - } - - @Override - protected void tearDown() throws Exception - { - super.tearDown(); - ApplicationRegistry.remove(); - } - - public void testSetJMXPortRegistryServer() throws ConfigurationException - { - _serverConfig.initialise(); - _serverConfig.setJMXPortRegistryServer(23); - assertEquals(23, _serverConfig.getJMXPortRegistryServer()); - } - - public void testGetJMXPortRegistryServer() throws ConfigurationException - { - _config.setProperty(ServerConfiguration.MGMT_JMXPORT_REGISTRYSERVER, 42); - _serverConfig.initialise(); - assertEquals(42, _serverConfig.getJMXPortRegistryServer()); - } - - public void testDefaultJMXPortRegistryServer() throws ConfigurationException - { - _serverConfig.initialise(); - assertEquals(8999, _serverConfig.getJMXPortRegistryServer()); - } - - public void testSetJMXPortConnectorServer() throws ConfigurationException - { - ServerConfiguration serverConfig = new ServerConfiguration(_config); - serverConfig.setJMXPortConnectorServer(67); - assertEquals(67, serverConfig.getJMXConnectorServerPort()); - } - - public void testGetJMXPortConnectorServer() throws ConfigurationException - { - _config.setProperty(ServerConfiguration.MGMT_JMXPORT_CONNECTORSERVER, 67); - ServerConfiguration serverConfig = new ServerConfiguration(_config); - assertEquals(67, serverConfig.getJMXConnectorServerPort()); - } - - public void testDefaultJMXPortConnectorServer() throws ConfigurationException - { - ServerConfiguration serverConfig = new ServerConfiguration(_config); - assertEquals(ServerConfiguration.DEFAULT_JMXPORT_REGISTRYSERVER + ServerConfiguration.JMXPORT_CONNECTORSERVER_OFFSET, - serverConfig.getJMXConnectorServerPort()); - } - - public void testGetPlatformMbeanserver() throws ConfigurationException - { - _serverConfig.initialise(); - assertEquals(true, _serverConfig.getPlatformMbeanserver()); - - // Check value we set - _config.setProperty("management.platform-mbeanserver", false); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(false, _serverConfig.getPlatformMbeanserver()); - } - - public void testGetPluginDirectory() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(null, _serverConfig.getPluginDirectory()); - - // Check value we set - _config.setProperty("plugin-directory", "/path/to/plugins"); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals("/path/to/plugins", _serverConfig.getPluginDirectory()); - } - - public void testGetCacheDirectory() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(null, _serverConfig.getCacheDirectory()); - - // Check value we set - _config.setProperty("cache-directory", "/path/to/cache"); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals("/path/to/cache", _serverConfig.getCacheDirectory()); - } - - public void testGetFrameSize() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(65536, _serverConfig.getFrameSize()); - - // Check value we set - _config.setProperty("advanced.framesize", "23"); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(23, _serverConfig.getFrameSize()); - } - - public void testGetStatusEnabled() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(ServerConfiguration.DEFAULT_STATUS_UPDATES.equalsIgnoreCase("on"), - _serverConfig.getStatusUpdatesEnabled()); - - // Check disabling we set - _config.setProperty(ServerConfiguration.STATUS_UPDATES, "off"); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(false, _serverConfig.getStatusUpdatesEnabled()); - - // Check invalid values don't cause error but result in disabled - _config.setProperty(ServerConfiguration.STATUS_UPDATES, "Yes Please"); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(false, _serverConfig.getStatusUpdatesEnabled()); - - } - public void testGetSynchedClocks() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(false, _serverConfig.getSynchedClocks()); - - // Check value we set - _config.setProperty("advanced.synced-clocks", true); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(true, _serverConfig.getSynchedClocks()); - } - - public void testGetLocale() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - - // The Default is what ever the VMs default is - Locale defaultLocale = Locale.getDefault(); - - assertEquals(defaultLocale, _serverConfig.getLocale()); - - - //Test Language only - Locale update = new Locale("es"); - _config.setProperty(ServerConfiguration.ADVANCED_LOCALE, "es"); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(update, _serverConfig.getLocale()); - - //Test Language and Country - update = new Locale("es","ES"); - _config.setProperty(ServerConfiguration.ADVANCED_LOCALE, "es_ES"); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(update, _serverConfig.getLocale()); - - //Test Language and Country and Variant - update = new Locale("es","ES", "Traditional_WIN"); - _config.setProperty(ServerConfiguration.ADVANCED_LOCALE, "es_ES_Traditional_WIN"); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(update, _serverConfig.getLocale()); - } - - - public void testGetMsgAuth() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(false, _serverConfig.getMsgAuth()); - - // Check value we set - _config.setProperty("security.msg-auth", true); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(true, _serverConfig.getMsgAuth()); - } - - public void testGetManagementKeyStorePath() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(null, _serverConfig.getManagementKeyStorePath()); - - // Check value we set - _config.setProperty("management.ssl.keyStorePath", "a"); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals("a", _serverConfig.getManagementKeyStorePath()); - } - - public void testGetManagementSSLEnabled() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(false, _serverConfig.getManagementSSLEnabled()); - - // Check value we set - _config.setProperty("management.ssl.enabled", true); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(true, _serverConfig.getManagementSSLEnabled()); - } - - public void testGetManagementKeystorePassword() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(null, _serverConfig.getManagementKeyStorePassword()); - - // Check value we set - _config.setProperty("management.ssl.keyStorePassword", "a"); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals("a", _serverConfig.getManagementKeyStorePassword()); - } - - public void testGetQueueAutoRegister() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(true, _serverConfig.getQueueAutoRegister()); - - // Check value we set - _config.setProperty("queue.auto_register", false); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(false, _serverConfig.getQueueAutoRegister()); - } - - public void testGetJMXManagementEnabled() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(true, _serverConfig.getJMXManagementEnabled()); - - // Check value we set - _config.setProperty("management.enabled", false); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(false, _serverConfig.getJMXManagementEnabled()); - } - - public void testGetManagementRightsInferAllAccess() throws Exception - { - _serverConfig.initialise(); - - //check default - assertTrue("default should be true", _serverConfig.getManagementRightsInferAllAccess()); - - //update it - _config.setProperty("management.managementRightsInferAllAccess", "false"); - assertFalse("New value should be false", _serverConfig.getManagementRightsInferAllAccess()); - } - - public void testGetHeartBeatDelay() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(5, _serverConfig.getHeartBeatDelay()); - - // Check value we set - _config.setProperty("heartbeat.delay", 23); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(23, _serverConfig.getHeartBeatDelay()); - } - - public void testGetHeartBeatTimeout() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(2.0, _serverConfig.getHeartBeatTimeout()); - - // Check value we set - _config.setProperty("heartbeat.timeoutFactor", 2.3); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(2.3, _serverConfig.getHeartBeatTimeout()); - } - - public void testGetMaximumMessageAge() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(0, _serverConfig.getMaximumMessageAge()); - - // Check value we set - _config.setProperty("maximumMessageAge", 10L); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(10, _serverConfig.getMaximumMessageAge()); - } - - public void testGetMaximumMessageCount() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(0, _serverConfig.getMaximumMessageCount()); - - // Check value we set - _config.setProperty("maximumMessageCount", 10L); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(10, _serverConfig.getMaximumMessageCount()); - } - - public void testGetMaximumQueueDepth() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(0, _serverConfig.getMaximumQueueDepth()); - - // Check value we set - _config.setProperty("maximumQueueDepth", 10L); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(10, _serverConfig.getMaximumQueueDepth()); - } - - public void testGetMaximumMessageSize() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(0, _serverConfig.getMaximumMessageSize()); - - // Check value we set - _config.setProperty("maximumMessageSize", 10L); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(10, _serverConfig.getMaximumMessageSize()); - } - - public void testGetMinimumAlertRepeatGap() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(30000l, _serverConfig.getMinimumAlertRepeatGap()); - - // Check value we set - _config.setProperty("minimumAlertRepeatGap", 10L); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(10, _serverConfig.getMinimumAlertRepeatGap()); - } - - public void testGetProcessors() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(4, _serverConfig.getConnectorProcessors()); - - // Check value we set - _config.setProperty("connector.processors", 10); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(10, _serverConfig.getConnectorProcessors()); - } - - public void testGetPorts() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertNotNull(_serverConfig.getPorts()); - assertEquals(1, _serverConfig.getPorts().size()); - assertEquals(5672, _serverConfig.getPorts().get(0)); - - - // Check value we set - _config.setProperty("connector.port", "10"); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertNotNull(_serverConfig.getPorts()); - assertEquals(1, _serverConfig.getPorts().size()); - assertEquals("10", _serverConfig.getPorts().get(0)); - } - - public void testGetBind() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(WILDCARD_ADDRESS, _serverConfig.getBind()); - - // Check value we set - _config.setProperty("connector.bind", "a"); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals("a", _serverConfig.getBind()); - } - - public void testGetReceiveBufferSize() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(ServerConfiguration.DEFAULT_BUFFER_SIZE, _serverConfig.getReceiveBufferSize()); - - // Check value we set - _config.setProperty("connector.socketReceiveBuffer", "23"); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(23, _serverConfig.getReceiveBufferSize()); - } - - public void testGetWriteBufferSize() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(ServerConfiguration.DEFAULT_BUFFER_SIZE, _serverConfig.getWriteBufferSize()); - - // Check value we set - _config.setProperty("connector.socketWriteBuffer", "23"); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(23, _serverConfig.getWriteBufferSize()); - } - - public void testGetTcpNoDelay() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(true, _serverConfig.getTcpNoDelay()); - - // Check value we set - _config.setProperty("connector.tcpNoDelay", false); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(false, _serverConfig.getTcpNoDelay()); - } - - public void testGetEnableSSL() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(false, _serverConfig.getEnableSSL()); - - // Check value we set - _config.setProperty("connector.ssl.enabled", true); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(true, _serverConfig.getEnableSSL()); - } - - public void testGetSSLOnly() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(false, _serverConfig.getSSLOnly()); - - // Check value we set - _config.setProperty("connector.ssl.sslOnly", true); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(true, _serverConfig.getSSLOnly()); - } - - public void testGetSSLPorts() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertNotNull(_serverConfig.getSSLPorts()); - assertEquals(1, _serverConfig.getSSLPorts().size()); - assertEquals(ServerConfiguration.DEFAULT_SSL_PORT, _serverConfig.getSSLPorts().get(0)); - - - // Check value we set - _config.setProperty("connector.ssl.port", "10"); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertNotNull(_serverConfig.getSSLPorts()); - assertEquals(1, _serverConfig.getSSLPorts().size()); - assertEquals("10", _serverConfig.getSSLPorts().get(0)); - } - - public void testGetConnectorKeystorePath() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertNull(_serverConfig.getConnectorKeyStorePath()); - - // Check value we set - _config.setProperty("connector.ssl.keyStorePath", "a"); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals("a", _serverConfig.getConnectorKeyStorePath()); - - // Ensure we continue to support the old name keystorePath - _config.clearProperty("connector.ssl.keyStorePath"); - _config.setProperty("connector.ssl.keystorePath", "b"); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals("b", _serverConfig.getConnectorKeyStorePath()); - } - - public void testGetConnectorKeystorePassword() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertNull(_serverConfig.getConnectorKeyStorePassword()); - - // Check value we set - _config.setProperty("connector.ssl.keyStorePassword", "a"); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals("a", _serverConfig.getConnectorKeyStorePassword()); - - // Ensure we continue to support the old name keystorePassword - _config.clearProperty("connector.ssl.keyStorePassword"); - _config.setProperty("connector.ssl.keystorePassword", "b"); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals("b", _serverConfig.getConnectorKeyStorePassword()); - } - - public void testConnectorGetKeyManagerAlgorithm() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(KeyManagerFactory.getDefaultAlgorithm(), _serverConfig.getConnectorKeyManagerFactoryAlgorithm()); - - // Check value we set - _config.setProperty("connector.ssl.keyManagerFactoryAlgorithm", "a"); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals("a", _serverConfig.getConnectorKeyManagerFactoryAlgorithm()); - - // Ensure we continue to support the old name certType - _config.clearProperty("connector.ssl.keyManagerFactoryAlgorithm"); - _config.setProperty("connector.ssl.certType", "b"); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals("b", _serverConfig.getConnectorKeyManagerFactoryAlgorithm()); - } - - public void testGetHousekeepingCheckPeriod() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(30000, _serverConfig.getHousekeepingCheckPeriod()); - - // Check value we set - _config.setProperty("housekeeping.checkPeriod", 23L); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - _serverConfig.setHousekeepingCheckPeriod(42L); - assertEquals(42, _serverConfig.getHousekeepingCheckPeriod()); - } - - public void testSingleConfiguration() throws IOException, ConfigurationException - { - File fileA = File.createTempFile(getClass().getName(), null); - fileA.deleteOnExit(); - FileWriter out = new FileWriter(fileA); - out.write("<broker><connector><port>2342</port><ssl><port>4235</port></ssl></connector></broker>"); - out.close(); - ServerConfiguration conf = new ServerConfiguration(fileA); - conf.initialise(); - assertEquals("4235", conf.getSSLPorts().get(0)); - } - - public void testCombinedConfiguration() throws IOException, ConfigurationException - { - File mainFile = File.createTempFile(getClass().getName(), null); - File fileA = File.createTempFile(getClass().getName(), null); - File fileB = File.createTempFile(getClass().getName(), null); - - mainFile.deleteOnExit(); - fileA.deleteOnExit(); - fileB.deleteOnExit(); - - FileWriter out = new FileWriter(mainFile); - out.write("<configuration><system/>"); - out.write("<xml fileName=\"" + fileA.getAbsolutePath() + "\"/>"); - out.write("<xml fileName=\"" + fileB.getAbsolutePath() + "\"/>"); - out.write("</configuration>"); - out.close(); - - out = new FileWriter(fileA); - out.write("<broker><connector><port>2342</port><ssl><port>4235</port></ssl></connector></broker>"); - out.close(); - - out = new FileWriter(fileB); - out.write("<broker><connector><ssl><port>2345</port></ssl></connector></broker>"); - out.close(); - - ServerConfiguration config = new ServerConfiguration(mainFile.getAbsoluteFile()); - config.initialise(); - assertEquals("4235", config.getSSLPorts().get(0)); // From first file, not - // overriden by second - assertNotNull(config.getPorts()); - assertEquals(1, config.getPorts().size()); - assertEquals("2342", config.getPorts().get(0)); // From the first file, not - // present in the second - } - - public void testVariableInterpolation() throws Exception - { - File mainFile = File.createTempFile(getClass().getName(), null); - - mainFile.deleteOnExit(); - - FileWriter out = new FileWriter(mainFile); - out.write("<broker>\n"); - out.write("\t<work>foo</work>\n"); - out.write("\t<management><ssl><keyStorePath>${work}</keyStorePath></ssl></management>\n"); - out.write("</broker>\n"); - out.close(); - - ServerConfiguration config = new ServerConfiguration(mainFile.getAbsoluteFile()); - config.initialise(); - assertEquals("Did not get correct interpolated value", - "foo", config.getManagementKeyStorePath()); - } - - private void writeConfigFile(File mainFile, boolean allow) throws IOException { - writeConfigFile(mainFile, allow, true, null, "test"); - } - - private void writeConfigFile(File mainFile, boolean allow, boolean includeVhosts, File vhostsFile, String name) throws IOException { - FileWriter out = new FileWriter(mainFile); - out.write("<broker>\n"); - out.write("\t<management><enabled>false</enabled></management>\n"); - out.write("\t<security>\n"); - out.write("\t\t<pd-auth-manager>\n"); - out.write("\t\t\t<principal-database>\n"); - out.write("\t\t\t\t<class>org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase</class>\n"); - out.write("\t\t\t\t<attributes>\n"); - out.write("\t\t\t\t\t<attribute>\n"); - out.write("\t\t\t\t\t\t<name>passwordFile</name>\n"); - out.write("\t\t\t\t\t\t<value>/dev/null</value>\n"); - out.write("\t\t\t\t\t</attribute>\n"); - out.write("\t\t\t\t</attributes>\n"); - out.write("\t\t\t</principal-database>\n"); - out.write("\t\t</pd-auth-manager>\n"); - out.write("\t\t<firewall>\n"); - out.write("\t\t\t<rule access=\""+ ((allow) ? "allow" : "deny") +"\" network=\"127.0.0.1\"/>"); - out.write("\t\t</firewall>\n"); - out.write("\t</security>\n"); - if (includeVhosts) - { - out.write("\t<virtualhosts>\n"); - out.write("\t\t<default>test</default>\n"); - out.write("\t\t<virtualhost>\n"); - out.write(String.format("\t\t\t<name>%s</name>\n", name)); - out.write(String.format("\t\t<%s> \n", name)); - out.write("\t\t\t<exchanges>\n"); - out.write("\t\t\t\t<exchange>\n"); - out.write("\t\t\t\t\t<type>topic</type>\n"); - out.write(String.format("\t\t\t\t\t<name>%s.topic</name>\n", name)); - out.write("\t\t\t\t\t<durable>true</durable>\n"); - out.write("\t\t\t\t</exchange>\n"); - out.write("\t\tt</exchanges>\n"); - out.write(String.format("\t\t</%s> \n", name)); - out.write("\t\t</virtualhost>\n"); - out.write("\t</virtualhosts>\n"); - } - if (vhostsFile != null) - { - out.write("\t<virtualhosts>"+vhostsFile.getAbsolutePath()+"</virtualhosts>\n"); - } - out.write("</broker>\n"); - out.close(); - } - - private void writeTestFishConfigFile(File mainFile) throws IOException { - FileWriter out = new FileWriter(mainFile); - out.write("<broker>\n"); - out.write("\t<management><enabled>false</enabled></management>\n"); - out.write("\t<security>\n"); - out.write("\t\t<pd-auth-manager>\n"); - out.write("\t\t\t<principal-database>\n"); - out.write("\t\t\t\t<class>org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase</class>\n"); - out.write("\t\t\t\t<attributes>\n"); - out.write("\t\t\t\t\t<attribute>\n"); - out.write("\t\t\t\t\t\t<name>passwordFile</name>\n"); - out.write("\t\t\t\t\t\t<value>/dev/null</value>\n"); - out.write("\t\t\t\t\t</attribute>\n"); - out.write("\t\t\t\t</attributes>\n"); - out.write("\t\t\t</principal-database>\n"); - out.write("\t\t</pd-auth-manager>\n"); - out.write("\t\t<firewall>\n"); - out.write("\t\t\t<rule access=\"allow\" network=\"127.0.0.1\"/>"); - out.write("\t\t</firewall>\n"); - out.write("\t</security>\n"); - out.write("\t<virtualhosts>\n"); - out.write("\t\t<virtualhost>\n"); - out.write("\t\t\t<name>test</name>\n"); - out.write("\t\t<test> \n"); - out.write("\t\t\t<exchanges>\n"); - out.write("\t\t\t\t<exchange>\n"); - out.write("\t\t\t\t\t<type>topic</type>\n"); - out.write("\t\t\t\t\t<name>test.topic</name>\n"); - out.write("\t\t\t\t\t<durable>true</durable>\n"); - out.write("\t\t\t\t</exchange>\n"); - out.write("\t\tt</exchanges>\n"); - out.write("\t\t</test> \n"); - out.write("\t\t</virtualhost>\n"); - out.write("\t\t<virtualhost>\n"); - out.write("\t\t\t<name>fish</name>\n"); - out.write("\t\t<fish> \n"); - out.write("\t\t\t<exchanges>\n"); - out.write("\t\t\t\t<exchange>\n"); - out.write("\t\t\t\t\t<type>topic</type>\n"); - out.write("\t\t\t\t\t<name>fish.topic</name>\n"); - out.write("\t\t\t\t\t<durable>false</durable>\n"); - out.write("\t\t\t\t</exchange>\n"); - out.write("\t\tt</exchanges>\n"); - out.write("\t\t</fish> \n"); - out.write("\t\t</virtualhost>\n"); - out.write("\t</virtualhosts>\n"); - out.write("</broker>\n"); - out.close(); - } - - private void writeVirtualHostsFile(File vhostsFile, String name) throws IOException { - FileWriter out = new FileWriter(vhostsFile); - out.write("<virtualhosts>\n"); - out.write(String.format("\t\t<default>%s</default>\n", name)); - out.write("\t<virtualhost>\n"); - out.write(String.format("\t\t<name>%s</name>\n", name)); - out.write(String.format("\t\t<%s>\n", name)); - out.write("\t\t\t<exchanges>\n"); - out.write("\t\t\t\t<exchange>\n"); - out.write("\t\t\t\t\t<type>topic</type>\n"); - out.write("\t\t\t\t\t<name>test.topic</name>\n"); - out.write("\t\t\t\t\t<durable>true</durable>\n"); - out.write("\t\t\t\t</exchange>\n"); - out.write("\t\tt</exchanges>\n"); - out.write(String.format("\t\t</%s>\n", name)); - out.write("\t</virtualhost>\n"); - out.write("</virtualhosts>\n"); - out.close(); - } - - private void writeMultiVirtualHostsFile(File vhostsFile) throws IOException { - FileWriter out = new FileWriter(vhostsFile); - out.write("<virtualhosts>\n"); - out.write("\t<virtualhost>\n"); - out.write("\t\t<name>topic</name>\n"); - out.write("\t\t<topic>\n"); - out.write("\t\t\t<exchanges>\n"); - out.write("\t\t\t\t<exchange>\n"); - out.write("\t\t\t\t\t<type>topic</type>\n"); - out.write("\t\t\t\t\t<name>test.topic</name>\n"); - out.write("\t\t\t\t\t<durable>true</durable>\n"); - out.write("\t\t\t\t</exchange>\n"); - out.write("\t\tt</exchanges>\n"); - out.write("\t\t</topic>\n"); - out.write("\t</virtualhost>\n"); - out.write("\t<virtualhost>\n"); - out.write("\t\t<name>fanout</name>\n"); - out.write("\t\t<fanout>\n"); - out.write("\t\t\t<exchanges>\n"); - out.write("\t\t\t\t<exchange>\n"); - out.write("\t\t\t\t\t<type>fanout</type>\n"); - out.write("\t\t\t\t\t<name>test.fanout</name>\n"); - out.write("\t\t\t\t\t<durable>true</durable>\n"); - out.write("\t\t\t\t</exchange>\n"); - out.write("\t\tt</exchanges>\n"); - out.write("\t\t</fanout>\n"); - out.write("\t</virtualhost>\n"); - out.write("</virtualhosts>\n"); - out.close(); - } - - private void writeMultipleVhostsConfigFile(File mainFile, File[] vhostsFileArray) throws IOException { - FileWriter out = new FileWriter(mainFile); - out.write("<broker>\n"); - out.write("\t<management><enabled>false</enabled></management>\n"); - out.write("\t<security>\n"); - out.write("\t\t<pd-auth-manager>\n"); - out.write("\t\t\t<principal-database>\n"); - out.write("\t\t\t\t<class>org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase</class>\n"); - out.write("\t\t\t\t<attributes>\n"); - out.write("\t\t\t\t\t<attribute>\n"); - out.write("\t\t\t\t\t\t<name>passwordFile</name>\n"); - out.write("\t\t\t\t\t\t<value>/dev/null</value>\n"); - out.write("\t\t\t\t\t</attribute>\n"); - out.write("\t\t\t\t</attributes>\n"); - out.write("\t\t\t</principal-database>\n"); - out.write("\t\t</pd-auth-manager>\n"); - out.write("\t\t<firewall>\n"); - out.write("\t\t\t<rule access=\"allow\" network=\"127.0.0.1\"/>"); - out.write("\t\t</firewall>\n"); - out.write("\t</security>\n"); - for (File vhostsFile : vhostsFileArray) - { - out.write("\t<virtualhosts>"+vhostsFile.getAbsolutePath()+"</virtualhosts>\n"); - } - out.write("</broker>\n"); - out.close(); - } - - private void writeCombinedConfigFile(File mainFile, File fileA, File fileB) throws Exception - { - FileWriter out = new FileWriter(mainFile); - out.write("<configuration><system/>"); - out.write("<xml fileName=\"" + fileA.getAbsolutePath() + "\"/>"); - out.write("<xml fileName=\"" + fileB.getAbsolutePath() + "\"/>"); - out.write("</configuration>"); - out.close(); - } - - /** - * Test that configuration loads correctly when virtual hosts are specified in the main - * configuration file only. - * <p> - * Test for QPID-2361 - */ - public void testInternalVirtualhostConfigFile() throws Exception - { - // Write out config - File mainFile = File.createTempFile(getClass().getName(), "config"); - mainFile.deleteOnExit(); - writeConfigFile(mainFile, false, true, null, "test"); - - // Load config - ApplicationRegistry.remove(); - ApplicationRegistry reg = new ConfigurationFileApplicationRegistry(mainFile); - ApplicationRegistry.initialise(reg); - - // Test config - VirtualHostRegistry virtualHostRegistry = reg.getVirtualHostRegistry(); - String defaultVirtualHost = reg.getConfiguration().getDefaultVirtualHost(); - VirtualHost virtualHost = virtualHostRegistry.getVirtualHost("test"); - Exchange exchange = virtualHost.getExchangeRegistry().getExchange(new AMQShortString("test.topic")); - - assertEquals("Incorrect default host", "test", defaultVirtualHost); - assertEquals("Incorrect virtualhost count", 1, virtualHostRegistry.getVirtualHosts().size()); - assertEquals("Incorrect virtualhost name", "test", virtualHost.getName()); - assertEquals("Incorrect exchange type", "topic", exchange.getType().getName().toString()); - } - - /** - * Test that configuration loads correctly when virtual hosts are specified in an external - * configuration file only. - * <p> - * Test for QPID-2361 - */ - public void testExternalVirtualhostXMLFile() throws Exception - { - // Write out config - File mainFile = File.createTempFile(getClass().getName(), "config"); - mainFile.deleteOnExit(); - File vhostsFile = File.createTempFile(getClass().getName(), "vhosts"); - vhostsFile.deleteOnExit(); - writeConfigFile(mainFile, false, false, vhostsFile, null); - writeVirtualHostsFile(vhostsFile, "test"); - - // Load config - ApplicationRegistry.remove(); - ApplicationRegistry reg = new ConfigurationFileApplicationRegistry(mainFile); - ApplicationRegistry.initialise(reg); - - // Test config - VirtualHostRegistry virtualHostRegistry = reg.getVirtualHostRegistry(); - String defaultVirtualHost = reg.getConfiguration().getDefaultVirtualHost(); - VirtualHost virtualHost = virtualHostRegistry.getVirtualHost("test"); - Exchange exchange = virtualHost.getExchangeRegistry().getExchange(new AMQShortString("test.topic")); - - assertEquals("Incorrect default host", "test", defaultVirtualHost); - assertEquals("Incorrect virtualhost count", 1, virtualHostRegistry.getVirtualHosts().size()); - assertEquals("Incorrect virtualhost name", "test", virtualHost.getName()); - assertEquals("Incorrect exchange type", "topic", exchange.getType().getName().toString()); - } - - /** - * Test that configuration loads correctly when virtual hosts are specified in an external - * configuration file only, with two vhosts that have different properties. - * <p> - * Test for QPID-2361 - */ - public void testExternalMultiVirtualhostXMLFile() throws Exception - { - // Write out vhosts - File vhostsFile = File.createTempFile(getClass().getName(), "vhosts-multi"); - vhostsFile.deleteOnExit(); - writeMultiVirtualHostsFile(vhostsFile); - - // Write out config - File mainFile = File.createTempFile(getClass().getName(), "config"); - mainFile.deleteOnExit(); - writeConfigFile(mainFile, false, false, vhostsFile, null); - - // Load config - ApplicationRegistry.remove(); - ApplicationRegistry reg = new ConfigurationFileApplicationRegistry(mainFile); - ApplicationRegistry.initialise(reg); - - // Test config - VirtualHostRegistry virtualHostRegistry = reg.getVirtualHostRegistry(); - - assertEquals("Incorrect virtualhost count", 2, virtualHostRegistry.getVirtualHosts().size()); - - // test topic host - VirtualHost topicVirtualHost = virtualHostRegistry.getVirtualHost("topic"); - Exchange topicExchange = topicVirtualHost.getExchangeRegistry().getExchange(new AMQShortString("test.topic")); - - assertEquals("Incorrect topic virtualhost name", "topic", topicVirtualHost.getName()); - assertEquals("Incorrect topic exchange type", "topic", topicExchange.getType().getName().toString()); - - // Test fanout host - VirtualHost fanoutVirtualHost = virtualHostRegistry.getVirtualHost("fanout"); - Exchange fanoutExchange = fanoutVirtualHost.getExchangeRegistry().getExchange(new AMQShortString("test.fanout")); - - assertEquals("Incorrect fanout virtualhost name", "fanout", fanoutVirtualHost.getName()); - assertEquals("Incorrect fanout exchange type", "fanout", fanoutExchange.getType().getName().toString()); - } - - /** - * Test that configuration does not load when virtual hosts are specified in both the main - * configuration file and an external file. Should throw a {@link ConfigurationException}. - * <p> - * Test for QPID-2361 - */ - public void testInternalAndExternalVirtualhostXMLFile() throws Exception - { - // Write out vhosts - File vhostsFile = File.createTempFile(getClass().getName(), "vhosts"); - vhostsFile.deleteOnExit(); - writeVirtualHostsFile(vhostsFile, "test"); - - // Write out config - File mainFile = File.createTempFile(getClass().getName(), "config"); - mainFile.deleteOnExit(); - writeConfigFile(mainFile, false, true, vhostsFile, "test"); - - // Load config - try - { - ApplicationRegistry.remove(); - ApplicationRegistry reg = new ConfigurationFileApplicationRegistry(mainFile); - ApplicationRegistry.initialise(reg); - fail("Different virtualhost XML configurations not allowed"); - } - catch (ConfigurationException ce) - { - assertEquals("Incorrect error message", "Only one of external or embedded virtualhosts configuration allowed.", ce.getMessage()); - } - } - - /** - * Test that configuration does not load when virtual hosts are specified in multiple external - * files. Should throw a {@link ConfigurationException}. - * <p> - * Test for QPID-2361 - */ - public void testMultipleInternalVirtualhostXMLFile() throws Exception - { - // Write out vhosts - File vhostsFileOne = File.createTempFile(getClass().getName(), "vhosts-one"); - vhostsFileOne.deleteOnExit(); - writeVirtualHostsFile(vhostsFileOne, "one"); - File vhostsFileTwo = File.createTempFile(getClass().getName(), "vhosts-two"); - vhostsFileTwo.deleteOnExit(); - writeVirtualHostsFile(vhostsFileTwo, "two"); - - // Write out config - File mainFile = File.createTempFile(getClass().getName(), "config"); - mainFile.deleteOnExit(); - writeMultipleVhostsConfigFile(mainFile, new File[] { vhostsFileOne, vhostsFileTwo }); - - // Load config - try - { - ApplicationRegistry.remove(); - ApplicationRegistry reg = new ConfigurationFileApplicationRegistry(mainFile); - ApplicationRegistry.initialise(reg); - fail("Multiple virtualhost XML configurations not allowed"); - } - catch (ConfigurationException ce) - { - assertEquals("Incorrect error message", - "Only one external virtualhosts configuration file allowed, multiple filenames found.", - ce.getMessage()); - } - } - - /** - * Test that configuration loads correctly when virtual hosts are specified in an external - * configuration file in the first of two configurations and embedded in the second. This - * will throe a {@link ConfigurationException} since the configurations have different - * types. - * <p> - * Test for QPID-2361 - */ - public void testCombinedDifferentVirtualhostConfig() throws Exception - { - // Write out vhosts config - File vhostsFile = File.createTempFile(getClass().getName(), "vhosts"); - vhostsFile.deleteOnExit(); - writeVirtualHostsFile(vhostsFile, "external"); - - // Write out combined config file - File mainFile = File.createTempFile(getClass().getName(), "main"); - File fileA = File.createTempFile(getClass().getName(), "a"); - File fileB = File.createTempFile(getClass().getName(), "b"); - mainFile.deleteOnExit(); - fileA.deleteOnExit(); - fileB.deleteOnExit(); - writeCombinedConfigFile(mainFile, fileA, fileB); - writeConfigFile(fileA, false, false, vhostsFile, null); - writeConfigFile(fileB, false); - - // Load config - try - { - ServerConfiguration config = new ServerConfiguration(mainFile.getAbsoluteFile()); - config.initialise(); - fail("Different virtualhost XML configurations not allowed"); - } - catch (ConfigurationException ce) - { - assertEquals("Incorrect error message", "Only one of external or embedded virtualhosts configuration allowed.", ce.getMessage()); - } - } - - /** - * Test that configuration loads correctly when virtual hosts are specified two overriding configurations - * each with an embedded virtualhost section. The first configuration section should be used. - * <p> - * Test for QPID-2361 - */ - public void testCombinedConfigEmbeddedVirtualhost() throws Exception - { - // Write out combined config file - File mainFile = File.createTempFile(getClass().getName(), "main"); - File fileA = File.createTempFile(getClass().getName(), "a"); - File fileB = File.createTempFile(getClass().getName(), "b"); - mainFile.deleteOnExit(); - fileA.deleteOnExit(); - fileB.deleteOnExit(); - writeCombinedConfigFile(mainFile, fileA, fileB); - writeConfigFile(fileA, false, true, null, "a"); - writeConfigFile(fileB, false, true, null, "b"); - - // Load config - ServerConfiguration config = new ServerConfiguration(mainFile.getAbsoluteFile()); - config.initialise(); - - // Test config - VirtualHostConfiguration virtualHost = config.getVirtualHostConfig("a"); - - assertEquals("Incorrect virtualhost count", 1, config.getVirtualHosts().length); - assertEquals("Incorrect virtualhost name", "a", virtualHost.getName()); - } - - /** - * Test that configuration loads correctly when virtual hosts are specified two overriding configurations - * each with an external virtualhost XML file. The first configuration file should be used. - * <p> - * Test for QPID-2361 - */ - public void testCombinedConfigExternalVirtualhost() throws Exception - { - // Write out vhosts config - File vhostsOne = File.createTempFile(getClass().getName(), "vhosts-one"); - vhostsOne.deleteOnExit(); - writeVirtualHostsFile(vhostsOne, "one"); - File vhostsTwo = File.createTempFile(getClass().getName(), "vhosts-two"); - vhostsTwo.deleteOnExit(); - writeVirtualHostsFile(vhostsTwo, "two"); - - // Write out combined config file - File mainFile = File.createTempFile(getClass().getName(), "main"); - File fileA = File.createTempFile(getClass().getName(), "a"); - File fileB = File.createTempFile(getClass().getName(), "b"); - mainFile.deleteOnExit(); - fileA.deleteOnExit(); - fileB.deleteOnExit(); - writeCombinedConfigFile(mainFile, fileA, fileB); - writeConfigFile(fileA, false, false, vhostsOne, null); - writeConfigFile(fileB, false, false, vhostsTwo, null); - - // Load config - ServerConfiguration config = new ServerConfiguration(mainFile.getAbsoluteFile()); - config.initialise(); - - // Test config - VirtualHostConfiguration virtualHost = config.getVirtualHostConfig("one"); - - assertEquals("Incorrect virtualhost count", 1, config.getVirtualHosts().length); - assertEquals("Incorrect virtualhost name", "one", virtualHost.getName()); - } - - /** - * Test that configuration loads correctly when an overriding virtualhost configuration resets - * a property of an embedded virtualhost section. The overriding configuration property value - * should be used. - * <p> - * Test for QPID-2361 - */ - public void testCombinedConfigEmbeddedVirtualhostOverride() throws Exception - { - // Write out combined config file - File mainFile = File.createTempFile(getClass().getName(), "main"); - File fileA = File.createTempFile(getClass().getName(), "override"); - File fileB = File.createTempFile(getClass().getName(), "config"); - mainFile.deleteOnExit(); - fileA.deleteOnExit(); - fileB.deleteOnExit(); - writeCombinedConfigFile(mainFile, fileA, fileB); - writeTestFishConfigFile(fileB); - - // Write out overriding virtualhosts section - FileWriter out = new FileWriter(fileA); - out.write("<broker>\n"); - out.write("<virtualhosts>\n"); - out.write("\t<virtualhost>\n"); - out.write("\t\t<test>\n"); - out.write("\t\t\t<exchanges>\n"); - out.write("\t\t\t\t<exchange>\n"); - out.write("\t\t\t\t\t<durable>false</durable>\n"); - out.write("\t\t\t\t</exchange>\n"); - out.write("\t\tt</exchanges>\n"); - out.write("\t\t</test>\n"); - out.write("\t\t<fish>\n"); - out.write("\t\t\t<exchanges>\n"); - out.write("\t\t\t\t<exchange>\n"); - out.write("\t\t\t\t\t<durable>true</durable>\n"); - out.write("\t\t\t\t</exchange>\n"); - out.write("\t\tt</exchanges>\n"); - out.write("\t\t</fish>\n"); - out.write("\t</virtualhost>\n"); - out.write("</virtualhosts>\n"); - out.write("</broker>\n"); - out.close(); - - // Load config - ServerConfiguration config = new ServerConfiguration(mainFile.getAbsoluteFile()); - config.initialise(); - - // Test config - VirtualHostConfiguration testHost = config.getVirtualHostConfig("test"); - ExchangeConfiguration testExchange = testHost.getExchangeConfiguration("test.topic"); - VirtualHostConfiguration fishHost = config.getVirtualHostConfig("fish"); - ExchangeConfiguration fishExchange = fishHost.getExchangeConfiguration("fish.topic"); - - assertEquals("Incorrect virtualhost count", 2, config.getVirtualHosts().length); - assertEquals("Incorrect virtualhost name", "test", testHost.getName()); - assertFalse("Incorrect exchange durable property", testExchange.getDurable()); - assertEquals("Incorrect virtualhost name", "fish", fishHost.getName()); - assertTrue("Incorrect exchange durable property", fishExchange.getDurable()); - } - - /** - * Test that configuration loads correctly when the virtualhost configuration is a set of overriding - * configuration files that resets a property of a virtualhost. The opmost overriding configuration - * property value should be used. - * <p> - * Test for QPID-2361 - */ - public void testCombinedVirtualhostOverride() throws Exception - { - // Write out combined config file - File mainFile = File.createTempFile(getClass().getName(), "main"); - File vhostsFile = File.createTempFile(getClass().getName(), "vhosts"); - File fileA = File.createTempFile(getClass().getName(), "vhosts-override"); - File fileB = File.createTempFile(getClass().getName(), "vhosts-base"); - mainFile.deleteOnExit(); - vhostsFile.deleteOnExit(); - fileA.deleteOnExit(); - fileB.deleteOnExit(); - writeConfigFile(mainFile, true, false, vhostsFile, null); - writeCombinedConfigFile(vhostsFile, fileA, fileB); - - // Write out overriding virtualhosts sections - FileWriter out = new FileWriter(fileA); - out.write("<virtualhosts>\n"); - out.write("\t<virtualhost>\n"); - out.write("\t\t<test>\n"); - out.write("\t\t\t<exchanges>\n"); - out.write("\t\t\t\t<exchange>\n"); - out.write("\t\t\t\t\t<durable>false</durable>\n"); - out.write("\t\t\t\t</exchange>\n"); - out.write("\t\tt</exchanges>\n"); - out.write("\t\t</test>\n"); - out.write("\t</virtualhost>\n"); - out.write("</virtualhosts>\n"); - out.close(); - writeVirtualHostsFile(fileB, "test"); - - // Load config - ServerConfiguration config = new ServerConfiguration(mainFile.getAbsoluteFile()); - config.initialise(); - - // Test config - VirtualHostConfiguration testHost = config.getVirtualHostConfig("test"); - ExchangeConfiguration testExchange = testHost.getExchangeConfiguration("test.topic"); - - assertEquals("Incorrect virtualhost count", 1, config.getVirtualHosts().length); - assertEquals("Incorrect virtualhost name", "test", testHost.getName()); - assertFalse("Incorrect exchange durable property", testExchange.getDurable()); - } - - /** - * Test that configuration loads correctly when the virtualhost configuration is a set of overriding - * configuration files that define multiple virtualhosts, one per file. Only the virtualhosts defined in - * the topmost file should be used. - * <p> - * Test for QPID-2361 - */ - public void testCombinedMultipleVirtualhosts() throws Exception - { - // Write out combined config file - File mainFile = File.createTempFile(getClass().getName(), "main"); - File vhostsFile = File.createTempFile(getClass().getName(), "vhosts"); - File fileA = File.createTempFile(getClass().getName(), "vhosts-one"); - File fileB = File.createTempFile(getClass().getName(), "vhosts-two"); - mainFile.deleteOnExit(); - vhostsFile.deleteOnExit(); - fileA.deleteOnExit(); - fileB.deleteOnExit(); - writeConfigFile(mainFile, true, false, vhostsFile, null); - writeCombinedConfigFile(vhostsFile, fileA, fileB); - - // Write both virtualhosts definitions - writeVirtualHostsFile(fileA, "test-one"); - writeVirtualHostsFile(fileB, "test-two"); - - // Load config - ServerConfiguration config = new ServerConfiguration(mainFile.getAbsoluteFile()); - config.initialise(); - - // Test config - VirtualHostConfiguration oneHost = config.getVirtualHostConfig("test-one"); - - assertEquals("Incorrect virtualhost count", 1, config.getVirtualHosts().length); - assertEquals("Incorrect virtualhost name", "test-one", oneHost.getName()); - } - - /** - * Test that a non-existent virtualhost file throws a {@link ConfigurationException}. - * <p> - * Test for QPID-2624 - */ - public void testNonExistantVirtualhosts() throws Exception - { - // Write out combined config file - File mainFile = File.createTempFile(getClass().getName(), "main"); - File vhostsFile = new File("doesnotexist"); - mainFile.deleteOnExit(); - writeConfigFile(mainFile, true, false, vhostsFile, null); - - // Load config - try - { - ServerConfiguration config = new ServerConfiguration(mainFile.getAbsoluteFile()); - config.initialise(); - } - catch (ConfigurationException ce) - { - assertEquals("Virtualhosts file does not exist", ce.getMessage()); - } - catch (Exception e) - { - fail("Should throw a ConfigurationException"); - } - } - - /** - * Tests that element disabledFeatures allows features that would - * otherwise be advertised by the broker to be turned off. - */ - public void testDisabledFeatures() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - _serverConfig = new ServerConfiguration(_config); - assertEquals("Unexpected size", 0, _serverConfig.getDisabledFeatures().size()); - - // Check value we set - _config.addProperty("disabledFeatures", "qpid.feature1"); - _config.addProperty("disabledFeatures", "qpid.feature2"); - _serverConfig = new ServerConfiguration(_config); - - assertEquals("Unexpected size",2, _serverConfig.getDisabledFeatures().size()); - assertTrue("Unexpected contents", _serverConfig.getDisabledFeatures().contains("qpid.feature1")); - } - - /** - * Tests that the old element security.jmx.access (that used to be used - * to define JMX access rights) is rejected. - */ - public void testManagementAccessRejected() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - - // Check value we set - _config.setProperty("security.jmx.access(0)", "jmxremote.access"); - _serverConfig = new ServerConfiguration(_config); - - try - { - _serverConfig.initialise(); - fail("Exception not thrown"); - } - catch (ConfigurationException ce) - { - assertEquals("Incorrect error message", - "Validation error : security/jmx/access is no longer a supported element within the configuration xml.", - ce.getMessage()); - } - } - - /** - * Tests that the old element security.jmx.principal-database (that used to define the - * principal database used for JMX authentication) is rejected. - */ - public void testManagementPrincipalDatabaseRejected() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - - // Check value we set - _config.setProperty("security.jmx.principal-database(0)", "mydb"); - _serverConfig = new ServerConfiguration(_config); - - try - { - _serverConfig.initialise(); - fail("Exception not thrown"); - } - catch (ConfigurationException ce) - { - assertEquals("Incorrect error message", - "Validation error : security/jmx/principal-database is no longer a supported element within the configuration xml.", - ce.getMessage()); - } - } - - /** - * Tests that the old element security.principal-databases. ... (that used to define - * principal databases) is rejected. - */ - public void testPrincipalDatabasesRejected() throws ConfigurationException - { - _serverConfig.initialise(); - - // Check value we set - _config.setProperty("security.principal-databases.principal-database.class", "myclass"); - _serverConfig = new ServerConfiguration(_config); - - try - { - _serverConfig.initialise(); - fail("Exception not thrown"); - } - catch (ConfigurationException ce) - { - assertEquals("Incorrect error message", - "Validation error : security/principal-databases is no longer supported within the configuration xml.", - ce.getMessage()); - } - } - - /** - * Tests that the old element housekeeping.expiredMessageCheckPeriod. ... (that was - * replaced by housekeeping.checkPeriod) is rejected. - */ - public void testExpiredMessageCheckPeriodRejected() throws ConfigurationException - { - _serverConfig.initialise(); - - // Check value we set - _config.setProperty("housekeeping.expiredMessageCheckPeriod", 23L); - _serverConfig = new ServerConfiguration(_config); - - try - { - _serverConfig.initialise(); - fail("Exception not thrown"); - } - catch (ConfigurationException ce) - { - assertEquals("Incorrect error message", - "Validation error : housekeeping/expiredMessageCheckPeriod must be replaced by housekeeping/checkPeriod.", - ce.getMessage()); - } - } - - public void testMaxDeliveryCountDefault() throws Exception - { - final ServerConfiguration serverConfig = new ServerConfiguration(_config); - assertEquals(0, serverConfig.getMaxDeliveryCount()); - } - - public void testMaxDeliveryCount() throws Exception - { - _config.setProperty("maximumDeliveryCount", 5); - final ServerConfiguration serverConfig = new ServerConfiguration(_config); - assertEquals(5, serverConfig.getMaxDeliveryCount()); - } - - /** - * Test XML configuration file correctly enables dead letter queues - */ - public void testDeadLetterQueueConfigurationFile() throws Exception - { - // Write config - File xml = File.createTempFile(getClass().getName(), "xml"); - xml.deleteOnExit(); - FileWriter config = new FileWriter(xml); - config.write("<broker>\n"); - writeSecurity(config); - config.write("<deadLetterQueues>true</deadLetterQueues>\n"); - config.write("<virtualhosts>\n"); - config.write("<virtualhost>\n"); - config.write("<name>test</name>\n"); - config.write("<test>\n"); - config.write("<queues>\n"); - config.write("<deadLetterQueues>false</deadLetterQueues>\n"); - config.write("<queue>\n"); - config.write("<name>biggles</name>\n"); - config.write("<biggles>\n"); - config.write("<deadLetterQueues>true</deadLetterQueues>\n"); - config.write("</biggles>\n"); - config.write("</queue>\n"); - config.write("<queue>\n"); - config.write("<name>beetle</name>\n"); - config.write("<beetle />\n"); - config.write("</queue>\n"); - config.write("</queues>\n"); - config.write("</test>\n"); - config.write("</virtualhost>\n"); - config.write("<virtualhost>\n"); - config.write("<name>extra</name>\n"); - config.write("<extra>\n"); - config.write("<queues>\n"); - config.write("<queue>\n"); - config.write("<name>r2d2</name>\n"); - config.write("<r2d2>\n"); - config.write("<deadLetterQueues>false</deadLetterQueues>\n"); - config.write("</r2d2>\n"); - config.write("</queue>\n"); - config.write("<queue>\n"); - config.write("<name>c3p0</name>\n"); - config.write("<c3p0 />\n"); - config.write("</queue>\n"); - config.write("</queues>\n"); - config.write("</extra>\n"); - config.write("</virtualhost>\n"); - config.write("</virtualhosts>\n"); - config.write("</broker>\n"); - config.close(); - - // Load config - ApplicationRegistry.remove(); - ApplicationRegistry registry = new ConfigurationFileApplicationRegistry(xml); - ApplicationRegistry.initialise(registry); - ServerConfiguration serverConfiguration = ApplicationRegistry.getInstance().getConfiguration(); - - VirtualHostConfiguration test = serverConfiguration.getVirtualHostConfig("test"); - assertNotNull("Host 'test' is not found", test); - VirtualHostConfiguration extra = serverConfiguration.getVirtualHostConfig("extra"); - assertNotNull("Host 'extra' is not found", test); - - QueueConfiguration biggles = test.getQueueConfiguration("biggles"); - QueueConfiguration beetle = test.getQueueConfiguration("beetle"); - QueueConfiguration r2d2 = extra.getQueueConfiguration("r2d2"); - QueueConfiguration c3p0 = extra.getQueueConfiguration("c3p0"); - - // Validate config - assertTrue("Broker DLQ should be configured as enabled", serverConfiguration.isDeadLetterQueueEnabled()); - assertFalse("Test vhost DLQ should be configured as disabled", test.isDeadLetterQueueEnabled()); - assertTrue("Extra vhost DLQ should be enabled, using broker default", extra.isDeadLetterQueueEnabled()); - assertTrue("Biggles queue DLQ should be configured as enabled", biggles.isDeadLetterQueueEnabled()); - assertFalse("Beetle queue DLQ should be disabled, using test vhost default", beetle.isDeadLetterQueueEnabled()); - assertFalse("R2D2 queue DLQ should be configured as disabled", r2d2.isDeadLetterQueueEnabled()); - assertTrue("C3P0 queue DLQ should be enabled, using broker default", c3p0.isDeadLetterQueueEnabled()); - } - - public void testIsAmqp010enabled() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(true, _serverConfig.isAmqp010enabled()); - - // Check value we set - _config.setProperty(ServerConfiguration.CONNECTOR_AMQP010ENABLED, false); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(false, _serverConfig.isAmqp010enabled()); - } - - public void testIsAmqp091enabled() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(true, _serverConfig.isAmqp091enabled()); - - // Check value we set - _config.setProperty(ServerConfiguration.CONNECTOR_AMQP091ENABLED, false); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(false, _serverConfig.isAmqp091enabled()); - } - - public void testIsAmqp09enabled() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(true, _serverConfig.isAmqp09enabled()); - - // Check value we set - _config.setProperty(ServerConfiguration.CONNECTOR_AMQP09ENABLED, false); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(false, _serverConfig.isAmqp09enabled()); - } - - public void testIsAmqp08enabled() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(true, _serverConfig.isAmqp08enabled()); - - // Check value we set - _config.setProperty(ServerConfiguration.CONNECTOR_AMQP08ENABLED, false); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(false, _serverConfig.isAmqp08enabled()); - } - - public void testPortInclude08() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(true, _serverConfig.getPortInclude08().isEmpty()); - - // Check values we set - _config.addProperty(ServerConfiguration.CONNECTOR_INCLUDE_08, "1"); - _config.addProperty(ServerConfiguration.CONNECTOR_INCLUDE_08, "2"); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(2, _serverConfig.getPortInclude08().size()); - assertTrue(_serverConfig.getPortInclude08().contains("1")); - assertTrue(_serverConfig.getPortInclude08().contains("2")); - } - - public void testPortInclude09() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(true, _serverConfig.getPortInclude09().isEmpty()); - - // Check values we set - _config.addProperty(ServerConfiguration.CONNECTOR_INCLUDE_09, "3"); - _config.addProperty(ServerConfiguration.CONNECTOR_INCLUDE_09, "4"); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(2, _serverConfig.getPortInclude09().size()); - assertTrue(_serverConfig.getPortInclude09().contains("3")); - assertTrue(_serverConfig.getPortInclude09().contains("4")); - } - - public void testPortInclude091() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(true, _serverConfig.getPortInclude091().isEmpty()); - - // Check values we set - _config.addProperty(ServerConfiguration.CONNECTOR_INCLUDE_091, "5"); - _config.addProperty(ServerConfiguration.CONNECTOR_INCLUDE_091, "6"); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(2, _serverConfig.getPortInclude091().size()); - assertTrue(_serverConfig.getPortInclude091().contains("5")); - assertTrue(_serverConfig.getPortInclude091().contains("6")); - } - - public void testPortInclude010() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(true, _serverConfig.getPortInclude010().isEmpty()); - - // Check values we set - _config.addProperty(ServerConfiguration.CONNECTOR_INCLUDE_010, "7"); - _config.addProperty(ServerConfiguration.CONNECTOR_INCLUDE_010, "8"); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(2, _serverConfig.getPortInclude010().size()); - assertTrue(_serverConfig.getPortInclude010().contains("7")); - assertTrue(_serverConfig.getPortInclude010().contains("8")); - } - - public void testPortInclude10() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(true, _serverConfig.getPortInclude10().isEmpty()); - - // Check values we set - _config.addProperty(ServerConfiguration.CONNECTOR_INCLUDE_10, "9"); - _config.addProperty(ServerConfiguration.CONNECTOR_INCLUDE_10, "10"); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(2, _serverConfig.getPortInclude10().size()); - assertTrue(_serverConfig.getPortInclude10().contains("9")); - assertTrue(_serverConfig.getPortInclude10().contains("10")); - } - - public void testGetDefaultSupportedProtocolReply() throws Exception - { - // Check default - _serverConfig.initialise(); - assertNull("unexpected default value", _serverConfig.getDefaultSupportedProtocolReply()); - - // Check values we set - _config.addProperty(ServerConfiguration.CONNECTOR_AMQP_SUPPORTED_REPLY, "v0_10"); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(AmqpProtocolVersion.v0_10, _serverConfig.getDefaultSupportedProtocolReply()); - } - - public void testDefaultAuthenticationManager() throws Exception - { - // Check default - _serverConfig.initialise(); - assertNull("unexpected default value", _serverConfig.getDefaultAuthenticationManager()); - - // Check values we set - String testAuthManager = "myauthmanager"; - _config.addProperty("security.default-auth-manager", testAuthManager); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(testAuthManager, _serverConfig.getDefaultAuthenticationManager()); - } - - public void testPortAuthenticationMappingsDefault() throws Exception - { - _serverConfig.initialise(); - assertEquals("unexpected default number of port/authmanager mappings", 0, _serverConfig.getPortAuthenticationMappings().size()); - } - - public void testPortAuthenticationMappingsWithSingleMapping() throws Exception - { - String testAuthManager = "myauthmanager"; - _config.addProperty("security.port-mappings.port-mapping.port", 1234); - _config.addProperty("security.port-mappings.port-mapping.auth-manager", testAuthManager); - - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals("unexpected number of port/authmanager mappings", 1, _serverConfig.getPortAuthenticationMappings().size()); - assertEquals("unexpected mapping for port", testAuthManager, _serverConfig.getPortAuthenticationMappings().get(1234)); - } - - public void testPortAuthenticationMappingsWithManyMapping() throws Exception - { - String testAuthManager1 = "myauthmanager1"; - String testAuthManager2 = "myauthmanager2"; - _config.addProperty("security.port-mappings.port-mapping(-1).port", 1234); - _config.addProperty("security.port-mappings.port-mapping.auth-manager", testAuthManager1); - - _config.addProperty("security.port-mappings.port-mapping(-1).port", 2345); - _config.addProperty("security.port-mappings.port-mapping.auth-manager", testAuthManager2); - - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - - assertEquals("unexpected number of port/authmanager mappings", 2, _serverConfig.getPortAuthenticationMappings().size()); - assertEquals("unexpected mapping for port", testAuthManager1, _serverConfig.getPortAuthenticationMappings().get(1234)); - assertEquals("unexpected mapping for port", testAuthManager2, _serverConfig.getPortAuthenticationMappings().get(2345)); - } - - public void testPortAuthenticationMappingWithMissingAuthManager() throws Exception - { - _config.addProperty("security.port-mappings.port-mapping(-1).port", 1234); - // no auth manager defined for port - _serverConfig = new ServerConfiguration(_config); - try - { - _serverConfig.initialise(); - fail("Exception not thrown"); - } - catch(ConfigurationException ce) - { - // PASS - assertEquals("Incorrect error message", - "Validation error: Each port-mapping must have exactly one port and exactly one auth-manager.", - ce.getMessage()); - } - } - - /** - * Convenience method to output required security preamble for broker config - */ - private void writeSecurity(Writer out) throws Exception - { - out.write("\t<management><enabled>false</enabled></management>\n"); - out.write("\t<security>\n"); - out.write("\t\t<pd-auth-manager>\n"); - out.write("\t\t\t<principal-database>\n"); - out.write("\t\t\t\t<class>org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase</class>\n"); - out.write("\t\t\t\t<attributes>\n"); - out.write("\t\t\t\t\t<attribute>\n"); - out.write("\t\t\t\t\t\t<name>passwordFile</name>\n"); - out.write("\t\t\t\t\t\t<value>/dev/null</value>\n"); - out.write("\t\t\t\t\t</attribute>\n"); - out.write("\t\t\t\t</attributes>\n"); - out.write("\t\t\t</principal-database>\n"); - out.write("\t\t</pd-auth-manager>\n"); - out.write("\t</security>\n"); - } -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/configuration/TopicConfigurationTest.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/TopicConfigurationTest.java deleted file mode 100644 index caf74a89ec..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/configuration/TopicConfigurationTest.java +++ /dev/null @@ -1,131 +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 org.apache.commons.configuration.ConfigurationException; - -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.server.exchange.Exchange; -import org.apache.qpid.server.model.UUIDGenerator; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.AMQQueueFactory; -import org.apache.qpid.server.util.InternalBrokerBaseCase; - -/** - * Test of the new Topic configuration processing - */ -public class TopicConfigurationTest extends InternalBrokerBaseCase -{ - - @Override - public void configure() - { - getConfigXml().addProperty("virtualhosts.virtualhost.test.topics.topic.name", "stocks.nyse.appl"); - - getConfigXml().addProperty("virtualhosts.virtualhost.test.topics.topic(1).subscriptionName", getName()+":stockSubscription"); - - getConfigXml().addProperty("virtualhosts.virtualhost.test.topics.topic(2).name", "stocks.nyse.orcl"); - getConfigXml().addProperty("virtualhosts.virtualhost.test.topics.topic(2).subscriptionName", getName()+":stockSubscription"); - } - - /** - * Test that a TopicConfig object is created and attached to the queue when it is bound to the topic exchange. - * - - * @throws ConfigurationException - * @throws AMQSecurityException - */ - public void testTopicCreation() throws ConfigurationException, AMQSecurityException, AMQInternalException - { - Exchange topicExchange = getVirtualHost().getExchangeRegistry().getExchange(ExchangeDefaults.TOPIC_EXCHANGE_NAME); - getVirtualHost().getBindingFactory().addBinding("stocks.nyse.appl", getQueue(), topicExchange, null); - - TopicConfig config = getQueue().getConfiguration().getConfiguration(TopicConfig.class.getName()); - - assertNotNull("Queue should have topic configuration bound to it.", config); - assertEquals("Configuration name not correct", "stocks.nyse.appl", config.getName()); - } - - /** - * Test that a queue created for a subscription correctly has topic - * configuration selected based on the subscription and topic name. - * - * @throws ConfigurationException - * @throws AMQException - */ - public void testSubscriptionWithTopicCreation() throws ConfigurationException, AMQException - { - - AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), getName()+":stockSubscription", false, "testowner", - false, false, getVirtualHost(), null); - - getVirtualHost().getQueueRegistry().registerQueue(queue); - Exchange defaultExchange = getVirtualHost().getExchangeRegistry().getDefaultExchange(); - getVirtualHost().getBindingFactory().addBinding(getName(), queue, defaultExchange, null); - - - Exchange topicExchange = getVirtualHost().getExchangeRegistry().getExchange(ExchangeDefaults.TOPIC_EXCHANGE_NAME); - getVirtualHost().getBindingFactory().addBinding("stocks.nyse.orcl", queue, topicExchange, null); - - TopicConfig config = queue.getConfiguration().getConfiguration(TopicConfig.class.getName()); - - assertNotNull("Queue should have topic configuration bound to it.", config); - assertEquals("Configuration subscription name not correct", getName() + ":stockSubscription", config.getSubscriptionName()); - assertEquals("Configuration name not correct", "stocks.nyse.orcl", config.getName()); - - } - - /** - * Test that a queue created for a subscription correctly has topic - * configuration attached here this should be the generic topic section - * with just the subscriptionName - * - * @throws ConfigurationException - * @throws AMQException - */ - public void testSubscriptionCreation() throws ConfigurationException, AMQException - { - - AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID() ,getName()+":stockSubscription", false, "testowner", - false, false, getVirtualHost(), null); - - getVirtualHost().getQueueRegistry().registerQueue(queue); - Exchange defaultExchange = getVirtualHost().getExchangeRegistry().getDefaultExchange(); - getVirtualHost().getBindingFactory().addBinding(getName(), queue, defaultExchange, null); - - - Exchange topicExchange = getVirtualHost().getExchangeRegistry().getExchange(ExchangeDefaults.TOPIC_EXCHANGE_NAME); - getVirtualHost().getBindingFactory().addBinding("stocks.nyse.ibm", queue, topicExchange, null); - - TopicConfig config = queue.getConfiguration().getConfiguration(TopicConfig.class.getName()); - - assertNotNull("Queue should have topic configuration bound to it.", config); - assertEquals("Configuration subscription name not correct", getName() + ":stockSubscription", config.getSubscriptionName()); - assertEquals("Configuration name not correct", "#", config.getName()); - - } - - - -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/configuration/VirtualHostConfigurationTest.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/VirtualHostConfigurationTest.java index 50e7f0588b..570bd004c5 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/configuration/VirtualHostConfigurationTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/configuration/VirtualHostConfigurationTest.java @@ -19,24 +19,69 @@ */ 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.registry.ApplicationRegistry; import org.apache.qpid.server.store.TestableMemoryMessageStore; -import org.apache.qpid.server.util.InternalBrokerBaseCase; +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 InternalBrokerBaseCase +public class VirtualHostConfigurationTest extends QpidTestCase { + private VirtualHostRegistry _virtualHostRegistry; + private XMLConfiguration _configXml; + private Broker _broker; @Override - public void createBroker() + public void setUp() throws Exception { - // Prevent auto broker startup + 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.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 @@ -65,11 +110,7 @@ public class VirtualHostConfigurationTest extends InternalBrokerBaseCase getConfigXml().addProperty("virtualhosts.virtualhost.testQueuePriority.queues.queue.ntest.priority", "false"); - // Start the broker now. - super.createBroker(); - - VirtualHost vhost = - ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost(getName()); + VirtualHost vhost = createVirtualHost(getName()); // Check that atest was a priority queue with 5 priorities AMQQueue atest = vhost.getQueueRegistry().getQueue(new AMQShortString("atest")); @@ -102,11 +143,7 @@ public class VirtualHostConfigurationTest extends InternalBrokerBaseCase getConfigXml().addProperty("virtualhosts.virtualhost.testQueueAlerts.queues(-1).queue(-1).name(-1)", "btest"); - // Start the broker now. - super.createBroker(); - - VirtualHost vhost = - ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost(getName()); + VirtualHost vhost = createVirtualHost(getName()); // Check specifically configured values AMQQueue aTest = vhost.getQueueRegistry().getQueue(new AMQShortString("atest")); @@ -129,11 +166,7 @@ public class VirtualHostConfigurationTest extends InternalBrokerBaseCase getConfigXml().addProperty("virtualhosts.virtualhost." + getName() + ".queues.queue.biggles.maximumDeliveryCount", 4); getConfigXml().addProperty("virtualhosts.virtualhost." + getName() + ".queues(-1).queue(-1).name", "beetle"); - // Start the broker now. - super.createBroker(); - - // Get vhosts - VirtualHost test = ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost(getName()); + VirtualHost test = createVirtualHost(getName()); // Enabled specifically assertEquals("Test vhost MDC was configured as enabled", 5 ,test.getConfiguration().getMaxDeliveryCount()); @@ -163,12 +196,8 @@ public class VirtualHostConfigurationTest extends InternalBrokerBaseCase getConfigXml().addProperty("virtualhosts.virtualhost." + getName() + "Extra.queues(-1).queue(-1).name", "c3p0"); getConfigXml().addProperty("virtualhosts.virtualhost." + getName() + "Extra.store.class", TestableMemoryMessageStore.class.getName()); - // Start the broker now. - super.createBroker(); - - // Get vhosts - VirtualHost test = ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost(getName()); - VirtualHost extra = ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost(getName() + "Extra"); + VirtualHost test = createVirtualHost(getName()); + VirtualHost extra = createVirtualHost(getName() + "Extra"); // Enabled specifically assertTrue("Test vhost DLQ was configured as enabled", test.getConfiguration().isDeadLetterQueueEnabled()); @@ -215,38 +244,13 @@ public class VirtualHostConfigurationTest extends InternalBrokerBaseCase getConfigXml().addProperty("virtualhosts.virtualhost.testHouseKeepingThreadCount.housekeeping.poolSize", initialPoolSize); - // Start the broker now. - super.createBroker(); - - VirtualHost vhost = - ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost(getName()); + VirtualHost vhost = createVirtualHost(getName()); assertEquals("HouseKeeping PoolSize not set correctly.", initialPoolSize, vhost.getHouseKeepingPoolSize()); } /** - * Test default house keeping tasks - * - * @throws Exception - */ - public void testDefaultHouseKeepingTasks() throws Exception - { - // Start the broker now. - super.createBroker(); - - VirtualHost vhost = - ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost(getName()); - - assertEquals("Default houseKeeping task count incorrect.", 2, - vhost.getHouseKeepingTaskCount()); - - // Currently the two are tasks: - // ExpiredMessageTask from VirtualHost - // UpdateTask from the QMF ManagementExchange - } - - /** * Test that we can dynamically change the thread pool size * * @throws Exception @@ -258,11 +262,7 @@ public class VirtualHostConfigurationTest extends InternalBrokerBaseCase getConfigXml().addProperty("virtualhosts.virtualhost.testDynamicHouseKeepingPoolSizeChange.housekeeping.poolSize", initialPoolSize); - // Start the broker now. - super.createBroker(); - - VirtualHost vhost = - ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost(getName()); + VirtualHost vhost = createVirtualHost(getName()); assertEquals("HouseKeeping PoolSize not set correctly.", initialPoolSize, vhost.getHouseKeepingPoolSize()); @@ -286,7 +286,7 @@ public class VirtualHostConfigurationTest extends InternalBrokerBaseCase try { - super.createBroker(); + createVirtualHost(getName()); fail("Exception not thrown"); } catch(ConfigurationException ce) @@ -309,7 +309,7 @@ public class VirtualHostConfigurationTest extends InternalBrokerBaseCase try { - super.createBroker(); + createVirtualHost(getName()); fail("Exception not thrown"); } catch (ConfigurationException ce) @@ -320,4 +320,41 @@ public class VirtualHostConfigurationTest extends InternalBrokerBaseCase 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()); + } } diff --git a/java/broker/src/test/java/org/apache/qpid/server/configuration/plugins/ConfigurationPluginTest.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/plugins/AbstractConfigurationTest.java index 14c7b8cb20..674abbfeb7 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/configuration/plugins/ConfigurationPluginTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/configuration/plugins/AbstractConfigurationTest.java @@ -24,7 +24,7 @@ import org.apache.commons.configuration.CompositeConfiguration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; -import org.apache.qpid.server.util.InternalBrokerBaseCase; +import org.apache.qpid.test.utils.QpidTestCase; import java.util.List; @@ -32,14 +32,14 @@ import java.util.List; * Test that verifies that given a Configuration a ConfigurationPlugin can * process and validate that data. */ -public class ConfigurationPluginTest extends InternalBrokerBaseCase +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 ConfigPlugin extends ConfigurationPlugin + class TestConfigPlugin extends AbstractConfiguration { @Override public String[] getElementsProcessed() @@ -68,7 +68,7 @@ public class ConfigurationPluginTest extends InternalBrokerBaseCase } - private ConfigPlugin _plugin; + private TestConfigPlugin _plugin; @Override public void setUp() throws Exception @@ -93,7 +93,7 @@ public class ConfigurationPluginTest extends InternalBrokerBaseCase CompositeConfiguration composite = new CompositeConfiguration(); composite.addConfiguration(xmlconfig); - _plugin = new ConfigPlugin(); + _plugin = new TestConfigPlugin(); try { @@ -110,7 +110,7 @@ public class ConfigurationPluginTest extends InternalBrokerBaseCase public void testHasConfiguration() { assertTrue("Plugin has no configuration ", _plugin.hasConfiguration()); - _plugin = new ConfigPlugin(); + _plugin = new TestConfigPlugin(); assertFalse("Plugins has configuration", _plugin.hasConfiguration()); } @@ -142,7 +142,7 @@ public class ConfigurationPluginTest extends InternalBrokerBaseCase catch (ConfigurationException e) { assertEquals("negativeLong should not be reported as positive", - "ConfigPlugin: unable to configure invalid negativeLong:" + NEGATIVE_LONG, e.getMessage()); + "TestConfigPlugin: unable to configure invalid negativeLong:" + NEGATIVE_LONG, e.getMessage()); } } diff --git a/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/BrokerRecovererTest.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/BrokerRecovererTest.java new file mode 100644 index 0000000000..c1ebe26f52 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/BrokerRecovererTest.java @@ -0,0 +1,405 @@ +/* + * + * 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.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.verify; + +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.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.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.model.adapter.AuthenticationProviderFactory; +import org.apache.qpid.server.model.adapter.PortFactory; +import org.apache.qpid.server.configuration.updater.TaskExecutor; +import org.apache.qpid.server.security.group.GroupPrincipalAccessor; +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; + + @Override + protected void setUp() throws Exception + { + super.setUp(); + + _brokerRecoverer = new BrokerRecoverer(mock(AuthenticationProviderFactory.class), mock(PortFactory.class), mock(StatisticsGatherer.class), + mock(VirtualHostRegistry.class), mock(LogRecorder.class), mock(RootMessageLogger.class), mock(TaskExecutor.class)); + when(_brokerEntry.getId()).thenReturn(_brokerId); + when(_brokerEntry.getChildren()).thenReturn(_brokerEntryChildren); + + //Add a base AuthenticationProvider for all tests + _authenticationProvider1 = mock(AuthenticationProvider.class); + when(_authenticationProvider1.getName()).thenReturn("authenticationProvider1"); + _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.DEFAULT_AUTHENTICATION_PROVIDER, "authenticationProvider1"); + attributes.put(Broker.ALERT_THRESHOLD_MESSAGE_AGE, 9l); + attributes.put(Broker.ALERT_THRESHOLD_MESSAGE_COUNT, 8l); + attributes.put(Broker.ALERT_THRESHOLD_QUEUE_DEPTH, 7l); + attributes.put(Broker.ALERT_THRESHOLD_MESSAGE_SIZE, 6l); + attributes.put(Broker.ALERT_REPEAT_GAP, 5l); + attributes.put(Broker.FLOW_CONTROL_SIZE_BYTES, 5l); + attributes.put(Broker.FLOW_CONTROL_RESUME_SIZE_BYTES, 3l); + attributes.put(Broker.MAXIMUM_DELIVERY_ATTEMPTS, 2); + attributes.put(Broker.DEAD_LETTER_QUEUE_ENABLED, true); + attributes.put(Broker.HOUSEKEEPING_CHECK_PERIOD, 1l); + attributes.put(Broker.ACL_FILE, "/path/to/acl"); + attributes.put(Broker.SESSION_COUNT_LIMIT, 1000); + attributes.put(Broker.HEART_BEAT_DELAY, 2000); + attributes.put(Broker.STATISTICS_REPORTING_PERIOD, 4000); + attributes.put(Broker.STATISTICS_REPORTING_RESET_ENABLED, true); + + 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 testCreateBrokerWithoutAuthenticationProviderThrowsException() + { + assertNotNull("expected to remove the base entry", _brokerEntryChildren.remove(AuthenticationProvider.class.getSimpleName())); + assertTrue("should be empty", _brokerEntryChildren.isEmpty()); + + RecovererProvider recovererProvider = createRecoveryProvider(new ConfigurationEntry[0], new ConfiguredObject[0]); + + try + { + _brokerRecoverer.create(recovererProvider, _brokerEntry); + fail("should have thrown an exception due to missing authentication provider configuration"); + } + catch(IllegalConfigurationException e) + { + //expected + } + } + + 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 testCreateBrokerWithMultipleAuthenticationProvidersAndNoDefaultThrowsException() + { + AuthenticationProvider authenticationProvider2 = mock(AuthenticationProvider.class); + when(authenticationProvider2.getName()).thenReturn("authenticationProvider2"); + ConfigurationEntry authenticationProviderEntry2 = mock(ConfigurationEntry.class); + _brokerEntryChildren.put(AuthenticationProvider.class.getSimpleName(), Arrays.asList(_authenticationProviderEntry1, authenticationProviderEntry2)); + + Map<String,Object> emptyBrokerAttributes = new HashMap<String,Object>(); + when(_brokerEntry.getAttributes()).thenReturn(emptyBrokerAttributes); + + RecovererProvider recovererProvider = createRecoveryProvider(new ConfigurationEntry[]{authenticationProviderEntry2, _authenticationProviderEntry1}, + new ConfiguredObject[]{authenticationProvider2, _authenticationProvider1}); + try + { + _brokerRecoverer.create(recovererProvider, _brokerEntry); + fail("should have thrown an exception due to missing authentication provider default"); + } + catch(IllegalConfigurationException e) + { + //expected + } + } + + 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)); + + //Set the default authentication provider + Map<String,Object> brokerAtttributes = new HashMap<String,Object>(); + when(_brokerEntry.getAttributes()).thenReturn(brokerAtttributes); + brokerAtttributes.put(Broker.DEFAULT_AUTHENTICATION_PROVIDER, "authenticationProvider2"); + + //Add a couple ports, one with a defined authentication provider and + //one without (which should then use the default) + ConfigurationEntry portEntry1 = mock(ConfigurationEntry.class); + Port port1 = mock(Port.class); + when(port1.getName()).thenReturn("port1"); + when(port1.getPort()).thenReturn(5671); + when(port1.getAttribute(Port.AUTHENTICATION_MANAGER)).thenReturn("authenticationProvider1"); + ConfigurationEntry portEntry2 = mock(ConfigurationEntry.class); + Port port2 = mock(Port.class); + when(port2.getName()).thenReturn("port2"); + when(port2.getPort()).thenReturn(5672); + _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)); + + verify(port1).setAuthenticationProvider(any(AuthenticationProvider.class)); + verify(port1).setAuthenticationProvider(_authenticationProvider1); + + verify(port2).setAuthenticationProvider(any(AuthenticationProvider.class)); + verify(port2).setAuthenticationProvider(authenticationProvider2); + } + + public void testCreateBrokerAssignsGroupAccessorToAuthenticationProviders() + { + //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)); + + //Set the default authentication provider + Map<String,Object> brokerAtttributes = new HashMap<String,Object>(); + when(_brokerEntry.getAttributes()).thenReturn(brokerAtttributes); + brokerAtttributes.put(Broker.DEFAULT_AUTHENTICATION_PROVIDER, "authenticationProvider2"); + + //Create a group provider + ConfigurationEntry groupProviderEntry = mock(ConfigurationEntry.class); + GroupProvider groupProvider = mock(GroupProvider.class); + _brokerEntryChildren.put(GroupProvider.class.getSimpleName(), Arrays.asList(groupProviderEntry)); + + RecovererProvider recovererProvider = createRecoveryProvider( + new ConfigurationEntry[]{groupProviderEntry, authenticationProviderEntry2, _authenticationProviderEntry1}, + new ConfiguredObject[]{groupProvider, authenticationProvider2, _authenticationProvider1}); + + Broker broker = _brokerRecoverer.create(recovererProvider, _brokerEntry); + + assertNotNull(broker); + assertEquals("Unexpected number of authentication providers", 2, broker.getAuthenticationProviders().size()); + + //verify that a GroupAcessor was added to the AuthenticationProviders + verify(_authenticationProvider1).setGroupAccessor(any(GroupPrincipalAccessor.class)); + verify(authenticationProvider2).setGroupAccessor(any(GroupPrincipalAccessor.class)); + } + + 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))); + } + + 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/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/DefaultRecovererProviderTest.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/DefaultRecovererProviderTest.java new file mode 100644 index 0000000000..c95f67beb9 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/DefaultRecovererProviderTest.java @@ -0,0 +1,62 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.configuration.startup; + +import static org.mockito.Mockito.mock; +import junit.framework.TestCase; + +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.Plugin; +import org.apache.qpid.server.model.Port; +import org.apache.qpid.server.model.VirtualHost; +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()}; + + // 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); + for (String configuredObjectType : supportedTypes) + { + ConfiguredObjectRecoverer<?> recovever = provider.getRecoverer(configuredObjectType); + assertNotNull("Null recoverer for type: " + configuredObjectType, recovever); + } + } + +} diff --git a/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/GroupProviderRecovererTest.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/GroupProviderRecovererTest.java new file mode 100644 index 0000000000..6713574e4b --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/GroupProviderRecovererTest.java @@ -0,0 +1,97 @@ +/* + * + * 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.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; + + @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 )); + + _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(); + when(_factory.createInstance(_attributes)).thenReturn(groupManager); + GroupProviderRecoverer groupProviderRecoverer = new GroupProviderRecoverer(_groupManagerServiceLoader); + 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(_groupManagerServiceLoader); + 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/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/KeyStoreRecovererTest.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/KeyStoreRecovererTest.java new file mode 100644 index 0000000000..0d7dc1bb06 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/KeyStoreRecovererTest.java @@ -0,0 +1,111 @@ +/* + * + * 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 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.TrustStore; + +import junit.framework.TestCase; + +public class KeyStoreRecovererTest extends TestCase +{ + + public void testCreateWithAllAttributesProvided() + { + Map<String, Object> attributes = getKeyStoreAttributes(); + + 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()); + assertEquals("my-secret-password", KeyStore.getPassword()); + + assertNull("Password was unexpectedly returned from configured object", KeyStore.getAttribute(TrustStore.PASSWORD)); + + // password attribute should not be exposed by a key store configured object + // so, we should set password value to null in the map being used to create the key store configured object + attributes.put(KeyStore.PASSWORD, null); + for (Map.Entry<String, Object> attribute : attributes.entrySet()) + { + Object attributeValue = KeyStore.getAttribute(attribute.getKey()); + assertEquals("Unexpected value of attribute '" + attribute.getKey() + "'", attribute.getValue(), attributeValue); + } + } + + private Map<String, Object> getKeyStoreAttributes() + { + Map<String, Object> attributes = new HashMap<String, Object>(); + attributes.put(KeyStore.NAME, getName()); + attributes.put(KeyStore.PATH, "/path/to/KeyStore"); + 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.CERTIFICATE_ALIAS, "my-cert-alias"); + attributes.put(KeyStore.DESCRIPTION, "description"); + return attributes; + } + + 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 + } + } + } + +} diff --git a/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/PluginRecovererTest.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/PluginRecovererTest.java new file mode 100644 index 0000000000..42fd742407 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/PluginRecovererTest.java @@ -0,0 +1,117 @@ +/* + * + * 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/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/TrustStoreRecovererTest.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/TrustStoreRecovererTest.java new file mode 100644 index 0000000000..3b64f45c80 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/TrustStoreRecovererTest.java @@ -0,0 +1,108 @@ +/* + * + * 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 org.apache.qpid.server.configuration.ConfigurationEntry; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.TrustStore; +import org.apache.qpid.test.utils.QpidTestCase; + +public class TrustStoreRecovererTest extends QpidTestCase +{ + public void testCreateWithAllAttributesProvided() + { + 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(); + + TrustStore trustStore = recovever.create(null, entry, broker); + assertNotNull("Trust store configured object is not created", trustStore); + assertEquals(id, trustStore.getId()); + assertEquals("my-secret-password", trustStore.getPassword()); + + assertNull("Password was unexpectedly returned from configured object", trustStore.getAttribute(TrustStore.PASSWORD)); + + // password attribute should not be exposed by a trust store configured object + // so, we should set password value to null in the map being used to create the trust store configured object + attributes.put(TrustStore.PASSWORD, null); + for (Map.Entry<String, Object> attribute : attributes.entrySet()) + { + Object attributeValue = trustStore.getAttribute(attribute.getKey()); + assertEquals("Unexpected value of attribute '" + attribute.getKey() + "'", attribute.getValue(), attributeValue); + } + } + + private Map<String, Object> getTrustStoreAttributes() + { + 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.KEY_MANAGER_FACTORY_ALGORITHM, "NON-STANDARD"); + attributes.put(TrustStore.DESCRIPTION, "Description"); + return attributes; + } + + 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 + } + } + } + +} diff --git a/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/VirtualHostRecovererTest.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/VirtualHostRecovererTest.java new file mode 100644 index 0000000000..57d219f85f --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/configuration/startup/VirtualHostRecovererTest.java @@ -0,0 +1,124 @@ +/* + * + * 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 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; + +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.getSecurityManager()).thenReturn(securityManager); + + VirtualHostRecoverer recoverer = new VirtualHostRecoverer(statisticsGatherer); + Map<String, Object> attributes = new HashMap<String, Object>(); + attributes.put(VirtualHost.NAME, getName()); + attributes.put(VirtualHost.CONFIG_PATH, "/path/to/virtualhost.xml"); + 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.getSecurityManager()).thenReturn(securityManager); + + VirtualHostRecoverer recoverer = new VirtualHostRecoverer(statisticsGatherer); + Map<String, Object> attributes = new HashMap<String, Object>(); + attributes.put(VirtualHost.NAME, getName()); + attributes.put(VirtualHost.STORE_PATH, "/path/to/virtualhost/store"); + attributes.put(VirtualHost.STORE_TYPE, "DERBY"); + 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_PATH, "/path/to/store"); + attributes.put(VirtualHost.STORE_TYPE, "DERBY"); + mandatoryAttributes = new String[]{VirtualHost.NAME, VirtualHost.STORE_PATH, 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/java/broker/src/test/java/org/apache/qpid/server/configuration/store/ConfigurationEntryStoreTestCase.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/store/ConfigurationEntryStoreTestCase.java new file mode 100644 index 0000000000..b357c0b8e9 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/configuration/store/ConfigurationEntryStoreTestCase.java @@ -0,0 +1,392 @@ +/* + * + * 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.DEFAULT_AUTHENTICATION_PROVIDER, "authenticationProvider1"); + _brokerAttributes.put(Broker.ALERT_THRESHOLD_MESSAGE_AGE, 9); + _brokerAttributes.put(Broker.ALERT_THRESHOLD_MESSAGE_COUNT, 8); + _brokerAttributes.put(Broker.ALERT_THRESHOLD_QUEUE_DEPTH, 7); + _brokerAttributes.put(Broker.ALERT_THRESHOLD_MESSAGE_SIZE, 6); + _brokerAttributes.put(Broker.ALERT_REPEAT_GAP, 5); + _brokerAttributes.put(Broker.FLOW_CONTROL_SIZE_BYTES, 5); + _brokerAttributes.put(Broker.FLOW_CONTROL_RESUME_SIZE_BYTES, 3); + _brokerAttributes.put(Broker.MAXIMUM_DELIVERY_ATTEMPTS, 2); + _brokerAttributes.put(Broker.DEAD_LETTER_QUEUE_ENABLED, true); + _brokerAttributes.put(Broker.HOUSEKEEPING_CHECK_PERIOD, 1); + _brokerAttributes.put(Broker.ACL_FILE, "/path/to/acl"); + _brokerAttributes.put(Broker.SESSION_COUNT_LIMIT, 1000); + _brokerAttributes.put(Broker.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); + assertEquals("Unexpected attributes", _brokerAttributes, attributes); + } + + 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.DEFAULT_AUTHENTICATION_PROVIDER, "authenticationProvider1"); + attributes.put(Broker.ALERT_THRESHOLD_MESSAGE_AGE, 19); + attributes.put(Broker.ALERT_THRESHOLD_MESSAGE_COUNT, 18); + attributes.put(Broker.ALERT_THRESHOLD_QUEUE_DEPTH, 17); + attributes.put(Broker.ALERT_THRESHOLD_MESSAGE_SIZE, 16); + attributes.put(Broker.ALERT_REPEAT_GAP, 15); + attributes.put(Broker.FLOW_CONTROL_SIZE_BYTES, 15); + attributes.put(Broker.FLOW_CONTROL_RESUME_SIZE_BYTES, 13); + attributes.put(Broker.MAXIMUM_DELIVERY_ATTEMPTS, 12); + attributes.put(Broker.DEAD_LETTER_QUEUE_ENABLED, false); + attributes.put(Broker.HOUSEKEEPING_CHECK_PERIOD, 11); + attributes.put(Broker.ACL_FILE, "/path/to/acl1"); + attributes.put(Broker.SESSION_COUNT_LIMIT, 11000); + attributes.put(Broker.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.KEY_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/java/broker/src/test/java/org/apache/qpid/server/configuration/store/JsonConfigurationEntryStoreTest.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/store/JsonConfigurationEntryStoreTest.java new file mode 100644 index 0000000000..7c9f4889f8 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/configuration/store/JsonConfigurationEntryStoreTest.java @@ -0,0 +1,216 @@ +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.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(); + store.open(_storeFile.getAbsolutePath()); + return store; + } + + private File createStoreFile(UUID brokerId, Map<String, Object> brokerAttributes) throws IOException, + JsonGenerationException, JsonMappingException + { + Map<String, Object> brokerObjectMap = new HashMap<String, Object>(); + brokerObjectMap.put(Broker.ID, brokerId); + brokerObjectMap.put("@type", Broker.class.getSimpleName()); + 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 aclLocation = "path/to/acl/" + getTestName(); + setTestSystemProperty("my.test.property", aclLocation); + + ConfigurationEntryStore store = getStore(); + ConfigurationEntry brokerConfigEntry = store.getRootEntry(); + Map<String, Object> attributes = new HashMap<String, Object>(brokerConfigEntry.getAttributes()); + attributes.put(Broker.ACL_FILE, "${my.test.property}"); + ConfigurationEntry updatedBrokerEntry = new ConfigurationEntry(brokerConfigEntry.getId(), Broker.class.getSimpleName(), + attributes, brokerConfigEntry.getChildrenIds(), store); + store.save(updatedBrokerEntry); + + JsonConfigurationEntryStore store2 = new JsonConfigurationEntryStore(); + store2.open(_storeFile.getAbsolutePath()); + + assertEquals("Unresolved ACL value", aclLocation, store2.getRootEntry().getAttributes().get(Broker.ACL_FILE)); + } + + public void testOpenEmpty() + { + File file = TestFileUtils.createTempFile(this, ".json"); + JsonConfigurationEntryStore store = new JsonConfigurationEntryStore(); + store.open(file.getAbsolutePath()); + ConfigurationEntry root = store.getRootEntry(); + assertNotNull("Root entry is not found", root); + store.copyTo(file.getAbsolutePath()); + + JsonConfigurationEntryStore store2 = new JsonConfigurationEntryStore(); + store2.open(file.getAbsolutePath()); + ConfigurationEntry root2 = store.getRootEntry(); + assertEquals("Unexpected root entry", root.getId(), root2.getId()); + } + + public void testOpenNotEmpty() 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(); + store.open(file.getAbsolutePath()); + 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 testOpenInMemoryEmpty() + { + JsonConfigurationEntryStore store = new JsonConfigurationEntryStore(); + store.open(JsonConfigurationEntryStore.IN_MEMORY); + + ConfigurationEntry root = store.getRootEntry(); + assertNotNull("Root entry is not found", root); + } + + public void testOpenWithInitialStoreLocation() throws Exception + { + UUID brokerId = UUID.randomUUID(); + Map<String, Object> brokerAttributes = new HashMap<String, Object>(); + brokerAttributes.put(Broker.NAME, getTestName()); + File initialStoreFile = createStoreFile(brokerId, brokerAttributes); + + File storeFile = TestFileUtils.createTempFile(this, ".json"); + JsonConfigurationEntryStore store = new JsonConfigurationEntryStore(); + store.open(storeFile.getAbsolutePath(), initialStoreFile.getAbsolutePath()); + + 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 testOpenInMemoryWithInitialStoreLocation() throws Exception + { + UUID brokerId = UUID.randomUUID(); + Map<String, Object> brokerAttributes = new HashMap<String, Object>(); + brokerAttributes.put(Broker.NAME, getTestName()); + File initialStoreFile = createStoreFile(brokerId, brokerAttributes); + + JsonConfigurationEntryStore store = new JsonConfigurationEntryStore(); + store.open(JsonConfigurationEntryStore.IN_MEMORY, initialStoreFile.getAbsolutePath()); + + 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 testOpenWithInitialStore() throws Exception + { + UUID brokerId = UUID.randomUUID(); + Map<String, Object> brokerAttributes = new HashMap<String, Object>(); + brokerAttributes.put(Broker.NAME, getTestName()); + File initialStoreFile = createStoreFile(brokerId, brokerAttributes); + + JsonConfigurationEntryStore initialStore = new JsonConfigurationEntryStore(); + initialStore.open(initialStoreFile.getAbsolutePath()); + + File storeFile = TestFileUtils.createTempFile(this, ".json"); + JsonConfigurationEntryStore store = new JsonConfigurationEntryStore(); + store.open(storeFile.getAbsolutePath(), initialStore); + + 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 testOpenInMemoryWithInitialStore() throws Exception + { + UUID brokerId = UUID.randomUUID(); + Map<String, Object> brokerAttributes = new HashMap<String, Object>(); + brokerAttributes.put(Broker.NAME, getTestName()); + File initialStoreFile = createStoreFile(brokerId, brokerAttributes); + + JsonConfigurationEntryStore initialStore = new JsonConfigurationEntryStore(); + initialStore.open(initialStoreFile.getAbsolutePath()); + + JsonConfigurationEntryStore store = new JsonConfigurationEntryStore(); + store.open(JsonConfigurationEntryStore.IN_MEMORY, initialStore); + + 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)); + } +} diff --git a/java/broker/src/test/java/org/apache/qpid/server/configuration/store/ManagementModeStoreHandlerTest.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/store/ManagementModeStoreHandlerTest.java new file mode 100644 index 0000000000..a67daac610 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/configuration/store/ManagementModeStoreHandlerTest.java @@ -0,0 +1,341 @@ +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.io.File; +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.BrokerConfigurationStoreCreator; +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 testOpenString() + { + try + { + _handler.open(TMP_FOLDER + File.separator + getTestName()); + fail("Exception should be thrown on attempt to call open method on a handler"); + } + catch (IllegalStateException e) + { + // pass + } + } + + public void testOpenStringString() + { + try + { + _handler.open(TMP_FOLDER + File.separator + getTestName(), + BrokerConfigurationStoreCreator.DEFAULT_INITIAL_STORE_LOCATION); + fail("Exception should be thrown on attempt to call open method on a handler"); + } + catch (IllegalStateException e) + { + // pass + } + } + + public void testOpenStringConfigurationEntryStore() + { + try + { + _handler.open(TMP_FOLDER + File.separator + getTestName(), _store); + fail("Exception should be thrown on attempt to call open method on a handler"); + } + catch (IllegalStateException e) + { + // pass + } + } + + 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.setManagementModeHttpPort(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.setManagementModeRmiPort(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.setManagementModeConnectorPort(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.setManagementModeHttpPort(1000); + _options.setManagementModeRmiPort(2000); + _options.setManagementModeConnectorPort(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.setManagementModeConnectorPort(9090); + _handler = new ManagementModeStoreHandler(_store, _options); + + UUID optionsPort = getOptionsPortId(); + ConfigurationEntry portEntry = _handler.getEntry(optionsPort); + assertCLIPortEntry(portEntry, optionsPort, Protocol.JMX_RMI); + } + + public void testGetEntryByCLIHttpPortId() + { + _options.setManagementModeHttpPort(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.setManagementModeHttpPort(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.setManagementModeRmiPort(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.setManagementModeRmiPort(9090); + _handler = new ManagementModeStoreHandler(_store, _options); + + ConfigurationEntry portEntry = _handler.getEntry(_portEntryId); + assertEquals("Unexpected state", State.QUIESCED, portEntry.getAttributes().get(Port.STATE)); + } + + public void testVirtualHostEntryIsQuiesced() + { + 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))); + + _handler = new ManagementModeStoreHandler(_store, _options); + + ConfigurationEntry hostEntry = _handler.getEntry(virtualHostId); + Map<String, Object> hostAttributes = hostEntry.getAttributes(); + assertEquals("Unexpected state", State.QUIESCED, 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.setManagementModeHttpPort(1000); + _options.setManagementModeRmiPort(2000); + _options.setManagementModeConnectorPort(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.setManagementModeHttpPort(1000); + _options.setManagementModeRmiPort(2000); + _options.setManagementModeConnectorPort(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.setManagementModeHttpPort(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.setManagementModeHttpPort(1000); + _handler = new ManagementModeStoreHandler(_store, _options); + + _handler.remove(_portEntryId); + verify(_store).remove(_portEntryId); + } + + public void testRemoveCLIPort() + { + _options.setManagementModeHttpPort(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/java/broker/src/test/java/org/apache/qpid/server/configuration/store/StoreConfigurationChangeListenerTest.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/store/StoreConfigurationChangeListenerTest.java new file mode 100644 index 0000000000..a77a0e9fcc --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/configuration/store/StoreConfigurationChangeListenerTest.java @@ -0,0 +1,83 @@ +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.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/java/broker/src/test/java/org/apache/qpid/server/configuration/updater/TaskExecutorTest.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/updater/TaskExecutorTest.java new file mode 100644 index 0000000000..cd6302d55b --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/configuration/updater/TaskExecutorTest.java @@ -0,0 +1,296 @@ +/* + * + * 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/java/broker/src/test/java/org/apache/qpid/server/exchange/AbstractHeadersExchangeTestBase.java b/java/broker/src/test/java/org/apache/qpid/server/exchange/AbstractHeadersExchangeTestBase.java index 4befd26ece..0bb698a46c 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/exchange/AbstractHeadersExchangeTestBase.java +++ b/java/broker/src/test/java/org/apache/qpid/server/exchange/AbstractHeadersExchangeTestBase.java @@ -29,7 +29,6 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.UUID; import java.util.concurrent.atomic.AtomicLong; import org.apache.log4j.Logger; @@ -54,25 +53,56 @@ import org.apache.qpid.server.queue.IncomingMessage; import org.apache.qpid.server.queue.MockStoredMessage; import org.apache.qpid.server.queue.QueueEntry; import org.apache.qpid.server.queue.SimpleAMQQueue; -import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.store.StoredMessage; import org.apache.qpid.server.subscription.Subscription; -import org.apache.qpid.server.util.InternalBrokerBaseCase; +import org.apache.qpid.server.util.BrokerTestHelper; +import org.apache.qpid.server.virtualhost.VirtualHost; +import org.apache.qpid.test.utils.QpidTestCase; -public class AbstractHeadersExchangeTestBase extends InternalBrokerBaseCase +public class AbstractHeadersExchangeTestBase extends QpidTestCase { private static final Logger _log = Logger.getLogger(AbstractHeadersExchangeTestBase.class); private final HeadersExchange exchange = new HeadersExchange(); - protected final Set<TestQueue> queues = new HashSet<TestQueue>(); - + private final Set<TestQueue> queues = new HashSet<TestQueue>(); + private VirtualHost _virtualHost; private int count; + @Override + public void setUp() throws Exception + { + super.setUp(); + BrokerTestHelper.setUp(); + _virtualHost = BrokerTestHelper.createVirtualHost(getClass().getName()); + } + + @Override + public void tearDown() throws Exception + { + try + { + if (_virtualHost != null) + { + _virtualHost.close(); + } + } + finally + { + BrokerTestHelper.tearDown(); + super.tearDown(); + } + } + public void testDoNothing() { // this is here only to make junit under Eclipse happy } + public VirtualHost getVirtualHost() + { + return _virtualHost; + } + protected TestQueue bindDefault(String... bindings) throws AMQException { String queueName = "Queue" + (++count); @@ -83,7 +113,7 @@ public class AbstractHeadersExchangeTestBase extends InternalBrokerBaseCase protected void unbind(TestQueue queue, String... bindings) throws AMQException { String queueName = queue.getName(); - exchange.onUnbind(new Binding(null, null, queueName, queue, exchange, getHeadersMap(bindings))); + exchange.onUnbind(new Binding(null, queueName, queue, exchange, getHeadersMap(bindings))); } protected int getCount() @@ -93,9 +123,9 @@ public class AbstractHeadersExchangeTestBase extends InternalBrokerBaseCase private TestQueue bind(String key, String queueName, Map<String,Object> args) throws AMQException { - TestQueue queue = new TestQueue(new AMQShortString(queueName)); + TestQueue queue = new TestQueue(new AMQShortString(queueName), _virtualHost); queues.add(queue); - exchange.onBind(new Binding(null, null, key, queue, exchange, args)); + exchange.onBind(new Binding(null, key, queue, exchange, args)); return queue; } @@ -274,10 +304,10 @@ public class AbstractHeadersExchangeTestBase extends InternalBrokerBaseCase return getNameShortString().toString(); } - public TestQueue(AMQShortString name) throws AMQException + public TestQueue(AMQShortString name, VirtualHost host) throws AMQException { - super(UUIDGenerator.generateRandomUUID(), name, false, new AMQShortString("test"), true, false,ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost("test"), Collections.EMPTY_MAP); - ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost("test").getQueueRegistry().registerQueue(this); + super(UUIDGenerator.generateRandomUUID(), name, false, new AMQShortString("test"), true, false, host, Collections.EMPTY_MAP); + host.getQueueRegistry().registerQueue(this); } diff --git a/java/broker/src/test/java/org/apache/qpid/server/exchange/DefaultExchangeFactoryTest.java b/java/broker/src/test/java/org/apache/qpid/server/exchange/DefaultExchangeFactoryTest.java new file mode 100644 index 0000000000..341ab1b372 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/exchange/DefaultExchangeFactoryTest.java @@ -0,0 +1,226 @@ +/* + * + * 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.getName(), 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.getName(), 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.getName(), 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.getName(), 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.getName() + "' is already registered using class '" + + DirectExchangeType.class.getName())); + } + } + + public void testCreateDefaultExchangeFactoryWithCustomExchangeType() + { + ExchangeType<?> customeExchangeType = new ExchangeType<Exchange>() + { + @Override + public AMQShortString getName() + { + return new AMQShortString("my-custom-exchange"); + } + + @Override + public Exchange newInstance(UUID id, VirtualHost host, AMQShortString name, boolean durable, int ticket, + boolean autoDelete) throws AMQException + { + return null; + } + + @Override + public AMQShortString getDefaultExchangeName() + { + return null; + } + }; + + _stubbedExchangeTypes.add(customeExchangeType); + _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(customeExchangeType)); + } + + private final class TestExchangeFactory extends DefaultExchangeFactory + { + private TestExchangeFactory() + { + super(null); + } + + @Override + protected Iterable<ExchangeType> loadExchangeTypes() + { + return _stubbedExchangeTypes; + } + } + +} diff --git a/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersBindingTest.java b/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersBindingTest.java index 3988edcb3c..833df34fd8 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersBindingTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersBindingTest.java @@ -160,7 +160,7 @@ public class HeadersBindingTest extends TestCase matchHeaders.setString("A", "Value of A"); - Binding b = new Binding(null, null, getQueueName(), _queue, null, bindHeaders); + Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); assertTrue(new HeadersBinding(b).matches(matchHeaders)); } @@ -171,7 +171,7 @@ public class HeadersBindingTest extends TestCase matchHeaders.setString("A", "Value of A"); matchHeaders.setString("B", "Value of B"); - Binding b = new Binding(null, null, getQueueName(), _queue, null, bindHeaders); + Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); assertTrue(new HeadersBinding(b).matches(matchHeaders)); } @@ -181,7 +181,7 @@ public class HeadersBindingTest extends TestCase matchHeaders.setString("A", "Altered value of A"); - Binding b = new Binding(null, null, getQueueName(), _queue, null, bindHeaders); + Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); assertFalse(new HeadersBinding(b).matches(matchHeaders)); } @@ -192,7 +192,7 @@ public class HeadersBindingTest extends TestCase matchHeaders.setString("A", "Value of A"); - Binding b = new Binding(null, null, getQueueName(), _queue, null, bindHeaders); + Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); assertTrue(new HeadersBinding(b).matches(matchHeaders)); } @@ -204,7 +204,7 @@ public class HeadersBindingTest extends TestCase matchHeaders.setString("A", "Value of A"); - Binding b = new Binding(null, null, getQueueName(), _queue, null, bindHeaders); + Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); assertFalse(new HeadersBinding(b).matches(matchHeaders)); } @@ -217,7 +217,7 @@ public class HeadersBindingTest extends TestCase matchHeaders.setString("A", "Value of A"); matchHeaders.setString("B", "Value of B"); - Binding b = new Binding(null, null, getQueueName(), _queue, null, bindHeaders); + Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); assertTrue(new HeadersBinding(b).matches(matchHeaders)); } @@ -231,7 +231,7 @@ public class HeadersBindingTest extends TestCase matchHeaders.setString("B", "Value of B"); matchHeaders.setString("C", "Value of C"); - Binding b = new Binding(null, null, getQueueName(), _queue, null, bindHeaders); + Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); assertTrue(new HeadersBinding(b).matches(matchHeaders)); } @@ -245,7 +245,7 @@ public class HeadersBindingTest extends TestCase matchHeaders.setString("B", "Altered value of B"); matchHeaders.setString("C", "Value of C"); - Binding b = new Binding(null, null, getQueueName(), _queue, null, bindHeaders); + Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); assertFalse(new HeadersBinding(b).matches(matchHeaders)); } @@ -256,7 +256,7 @@ public class HeadersBindingTest extends TestCase matchHeaders.setString("A", "Value of A"); - Binding b = new Binding(null, null, getQueueName(), _queue, null, bindHeaders); + Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); assertTrue(new HeadersBinding(b).matches(matchHeaders)); } @@ -268,7 +268,7 @@ public class HeadersBindingTest extends TestCase matchHeaders.setString("A", "Value of A"); - Binding b = new Binding(null, null, getQueueName(), _queue, null, bindHeaders); + Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); assertTrue(new HeadersBinding(b).matches(matchHeaders)); } @@ -281,7 +281,7 @@ public class HeadersBindingTest extends TestCase matchHeaders.setString("A", "Value of A"); matchHeaders.setString("B", "Value of B"); - Binding b = new Binding(null, null, getQueueName(), _queue, null, bindHeaders); + Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); assertTrue(new HeadersBinding(b).matches(matchHeaders)); } @@ -295,7 +295,7 @@ public class HeadersBindingTest extends TestCase matchHeaders.setString("B", "Value of B"); matchHeaders.setString("C", "Value of C"); - Binding b = new Binding(null, null, getQueueName(), _queue, null, bindHeaders); + Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); assertTrue(new HeadersBinding(b).matches(matchHeaders)); } @@ -309,7 +309,7 @@ public class HeadersBindingTest extends TestCase matchHeaders.setString("B", "Altered value of B"); matchHeaders.setString("C", "Value of C"); - Binding b = new Binding(null, null, getQueueName(), _queue, null, bindHeaders); + Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); assertTrue(new HeadersBinding(b).matches(matchHeaders)); } @@ -323,7 +323,7 @@ public class HeadersBindingTest extends TestCase matchHeaders.setString("B", "Altered value of B"); matchHeaders.setString("C", "Value of C"); - Binding b = new Binding(null, null, getQueueName(), _queue, null, bindHeaders); + Binding b = new Binding(null, getQueueName(), _queue, null, bindHeaders); assertFalse(new HeadersBinding(b).matches(matchHeaders)); } diff --git a/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersExchangeTest.java b/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersExchangeTest.java index 326d36df05..bd6a02d69b 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersExchangeTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersExchangeTest.java @@ -23,8 +23,7 @@ package org.apache.qpid.server.exchange; import org.apache.qpid.AMQException; import org.apache.qpid.server.protocol.AMQProtocolSession; import org.apache.qpid.server.protocol.InternalTestProtocolSession; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.virtualhost.VirtualHost; +import org.apache.qpid.server.util.BrokerTestHelper; public class HeadersExchangeTest extends AbstractHeadersExchangeTestBase { @@ -34,10 +33,15 @@ public class HeadersExchangeTest extends AbstractHeadersExchangeTestBase public void setUp() throws Exception { super.setUp(); - // Just use the first vhost. - VirtualHost - virtualHost = ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHosts().iterator().next(); - _protocolSession = new InternalTestProtocolSession(virtualHost); + BrokerTestHelper.setUp(); + _protocolSession = new InternalTestProtocolSession(getVirtualHost(), BrokerTestHelper.createBrokerMock()); + } + + @Override + public void tearDown() throws Exception + { + BrokerTestHelper.tearDown(); + super.tearDown(); } public void testSimple() throws AMQException diff --git a/java/broker/src/test/java/org/apache/qpid/server/exchange/TopicExchangeTest.java b/java/broker/src/test/java/org/apache/qpid/server/exchange/TopicExchangeTest.java index 92274afece..f1bf632235 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/exchange/TopicExchangeTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/exchange/TopicExchangeTest.java @@ -31,42 +31,55 @@ import org.apache.qpid.server.binding.Binding; import org.apache.qpid.server.message.AMQMessage; import org.apache.qpid.server.message.MessageMetaData; import org.apache.qpid.server.model.UUIDGenerator; -import org.apache.qpid.server.protocol.InternalTestProtocolSession; import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.queue.AMQQueueFactory; import org.apache.qpid.server.queue.BaseQueue; import org.apache.qpid.server.queue.IncomingMessage; -import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.store.MemoryMessageStore; import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.util.InternalBrokerBaseCase; +import org.apache.qpid.server.util.BrokerTestHelper; import org.apache.qpid.server.virtualhost.VirtualHost; +import org.apache.qpid.test.utils.QpidTestCase; -public class TopicExchangeTest extends InternalBrokerBaseCase +public class TopicExchangeTest extends QpidTestCase { private TopicExchange _exchange; - private VirtualHost _vhost; private MessageStore _store; - private InternalTestProtocolSession _protocolSession; - @Override public void setUp() throws Exception { super.setUp(); + BrokerTestHelper.setUp(); _exchange = new TopicExchange(); - _vhost = ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHosts().iterator().next(); + _vhost = BrokerTestHelper.createVirtualHost(getName()); _store = new MemoryMessageStore(); - _protocolSession = new InternalTestProtocolSession(_vhost); + } + + @Override + public void tearDown() throws Exception + { + try + { + if (_vhost != null) + { + _vhost.close(); + } + } + finally + { + BrokerTestHelper.tearDown(); + super.tearDown(); + } } public void testNoRoute() throws AMQException { AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), "a*#b", false, null, false, false, _vhost, null); - _exchange.registerQueue(new Binding(null, null, "a.*.#.b",queue, _exchange, null)); + _exchange.registerQueue(new Binding(null, "a.*.#.b",queue, _exchange, null)); IncomingMessage message = createMessage("a.b"); @@ -78,7 +91,7 @@ public class TopicExchangeTest extends InternalBrokerBaseCase public void testDirectMatch() throws AMQException { AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), "ab", false, null, false, false, _vhost, null); - _exchange.registerQueue(new Binding(null, null, "a.b",queue, _exchange, null)); + _exchange.registerQueue(new Binding(null, "a.b",queue, _exchange, null)); IncomingMessage message = createMessage("a.b"); @@ -105,7 +118,7 @@ public class TopicExchangeTest extends InternalBrokerBaseCase public void testStarMatch() throws AMQException { AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), "a*", false, null, false, false, _vhost, null); - _exchange.registerQueue(new Binding(null, null, "a.*",queue, _exchange, null)); + _exchange.registerQueue(new Binding(null, "a.*",queue, _exchange, null)); IncomingMessage message = createMessage("a.b"); @@ -144,7 +157,7 @@ public class TopicExchangeTest extends InternalBrokerBaseCase public void testHashMatch() throws AMQException { AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), "a#", false, null, false, false, _vhost, null); - _exchange.registerQueue(new Binding(null, null, "a.#",queue, _exchange, null)); + _exchange.registerQueue(new Binding(null, "a.#",queue, _exchange, null)); IncomingMessage message = createMessage("a.b.c"); @@ -207,7 +220,7 @@ public class TopicExchangeTest extends InternalBrokerBaseCase public void testMidHash() throws AMQException { AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), "a", false, null, false, false, _vhost, null); - _exchange.registerQueue(new Binding(null, null, "a.*.#.b",queue, _exchange, null)); + _exchange.registerQueue(new Binding(null, "a.*.#.b",queue, _exchange, null)); IncomingMessage message = createMessage("a.c.d.b"); @@ -237,7 +250,7 @@ public class TopicExchangeTest extends InternalBrokerBaseCase public void testMatchafterHash() throws AMQException { AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), "a#", false, null, false, false, _vhost, null); - _exchange.registerQueue(new Binding(null, null, "a.*.#.b.c",queue, _exchange, null)); + _exchange.registerQueue(new Binding(null, "a.*.#.b.c",queue, _exchange, null)); IncomingMessage message = createMessage("a.c.b.b"); @@ -283,7 +296,7 @@ public class TopicExchangeTest extends InternalBrokerBaseCase public void testHashAfterHash() throws AMQException { AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), "a#", false, null, false, false, _vhost, null); - _exchange.registerQueue(new Binding(null, null, "a.*.#.b.c.#.d",queue, _exchange, null)); + _exchange.registerQueue(new Binding(null, "a.*.#.b.c.#.d",queue, _exchange, null)); IncomingMessage message = createMessage("a.c.b.b.c"); @@ -310,7 +323,7 @@ public class TopicExchangeTest extends InternalBrokerBaseCase public void testHashHash() throws AMQException { AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), "a#", false, null, false, false, _vhost, null); - _exchange.registerQueue(new Binding(null, null, "a.#.*.#.d",queue, _exchange, null)); + _exchange.registerQueue(new Binding(null, "a.#.*.#.d",queue, _exchange, null)); IncomingMessage message = createMessage("a.c.b.b.c"); @@ -336,7 +349,7 @@ public class TopicExchangeTest extends InternalBrokerBaseCase public void testSubMatchFails() throws AMQException { AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), "a", false, null, false, false, _vhost, null); - _exchange.registerQueue(new Binding(null, null, "a.b.c.d",queue, _exchange, null)); + _exchange.registerQueue(new Binding(null, "a.b.c.d",queue, _exchange, null)); IncomingMessage message = createMessage("a.b.c"); @@ -366,7 +379,7 @@ public class TopicExchangeTest extends InternalBrokerBaseCase public void testMoreRouting() throws AMQException { AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), "a", false, null, false, false, _vhost, null); - _exchange.registerQueue(new Binding(null, null, "a.b",queue, _exchange, null)); + _exchange.registerQueue(new Binding(null, "a.b",queue, _exchange, null)); IncomingMessage message = createMessage("a.b.c"); @@ -381,7 +394,7 @@ public class TopicExchangeTest extends InternalBrokerBaseCase public void testMoreQueue() throws AMQException { AMQQueue queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), "a", false, null, false, false, _vhost, null); - _exchange.registerQueue(new Binding(null, null, "a.b",queue, _exchange, null)); + _exchange.registerQueue(new Binding(null, "a.b",queue, _exchange, null)); IncomingMessage message = createMessage("a"); diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/UnitTestMessageLogger.java b/java/broker/src/test/java/org/apache/qpid/server/logging/UnitTestMessageLogger.java index fabbe8640e..be31f3d039 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/logging/UnitTestMessageLogger.java +++ b/java/broker/src/test/java/org/apache/qpid/server/logging/UnitTestMessageLogger.java @@ -20,7 +20,6 @@ */ package org.apache.qpid.server.logging; -import org.apache.qpid.server.configuration.ServerConfiguration; import java.util.LinkedList; import java.util.List; @@ -34,9 +33,9 @@ public class UnitTestMessageLogger extends AbstractRootMessageLogger } - public UnitTestMessageLogger(ServerConfiguration config) + public UnitTestMessageLogger(boolean statusUpdatesEnabled) { - super(config); + super(statusUpdatesEnabled); } public void rawMessage(String message, String logHierarchy) diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AMQPChannelActorTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AMQPChannelActorTest.java index f739d3fcb9..e2472dbf01 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AMQPChannelActorTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AMQPChannelActorTest.java @@ -20,9 +20,8 @@ */ package org.apache.qpid.server.logging.actors; -import org.apache.commons.configuration.ConfigurationException; - -import org.apache.qpid.AMQException; +import org.apache.qpid.server.AMQChannel; +import org.apache.qpid.server.util.BrokerTestHelper; import java.util.List; @@ -38,24 +37,17 @@ import java.util.List; public class AMQPChannelActorTest extends BaseConnectionActorTestCase { - @Override - public void configure() + public void setUp() { - // Prevent defaulting Logging to ON + // do nothing } - - @Override - public void createBroker() throws Exception + private void setUpNow() throws Exception { - //prevent auto-broker startup - } + super.setUp(); + AMQChannel channel = BrokerTestHelper.createChannel(1, getSession()); - private void startBrokerNow() throws Exception - { - super.createBroker(); - - _amqpActor = new AMQPChannelActor(getChannel(), _rootLogger); + setAmqpActor(new AMQPChannelActor(channel, getRootLogger())); } @@ -68,13 +60,11 @@ public class AMQPChannelActorTest extends BaseConnectionActorTestCase */ public void testChannel() throws Exception { - getConfigXml().setProperty("status-updates", "ON"); - - startBrokerNow(); + setUpNow(); - final String message = sendTestLogMessage(_amqpActor); + final String message = sendTestLogMessage(getAmqpActor()); - List<Object> logs = _rawLogger.getLogMessages(); + List<Object> logs = getRawLogger().getLogMessages(); assertEquals("Message log size not as expected.", 1, logs.size()); @@ -95,128 +85,22 @@ public class AMQPChannelActorTest extends BaseConnectionActorTestCase // 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 in the configuration that - * no logging is presented - * @throws ConfigurationException - * @throws AMQException - */ - public void testChannelLoggingOFF() throws Exception, AMQException - { - getConfigXml().setProperty("status-updates", "OFF"); - - // Start the broker now. - startBrokerNow(); - - sendTestLogMessage(_amqpActor); - - List<Object> logs = _rawLogger.getLogMessages(); - - assertEquals("Message log size not as expected.", 0, logs.size()); - - } - - /** - * Test that if logging is configured to be off in the configuration that - * no logging is presented - * @throws ConfigurationException - * @throws AMQException - */ - public void testChannelLoggingOfF() throws Exception, AMQException - { - getConfigXml().setProperty("status-updates", "OfF"); - - startBrokerNow(); - - sendTestLogMessage(_amqpActor); - - List<Object> logs = _rawLogger.getLogMessages(); - - assertEquals("Message log size not as expected.", 0, logs.size()); - - } - - /** - * Test that if logging is configured to be off in the configuration that - * no logging is presented - * @throws ConfigurationException - * @throws AMQException - */ - public void testChannelLoggingOff() throws Exception, AMQException - { - getConfigXml().setProperty("status-updates", "Off"); - - startBrokerNow(); - - sendTestLogMessage(_amqpActor); - - List<Object> logs = _rawLogger.getLogMessages(); - - assertEquals("Message log size not as expected.", 0, logs.size()); - } /** - * Test that if logging is configured to be off in the configuration that + * Test that if logging is configured to be off via system property that * no logging is presented - * @throws ConfigurationException - * @throws AMQException */ - public void testChannelLoggingofF() throws Exception, AMQException + public void testChannelLoggingOFF() throws Exception { - getConfigXml().setProperty("status-updates", "ofF"); + setStatusUpdatesEnabled(false); - startBrokerNow(); + setUpNow(); - sendTestLogMessage(_amqpActor); + sendTestLogMessage(getAmqpActor()); - List<Object> logs = _rawLogger.getLogMessages(); + List<Object> logs = getRawLogger().getLogMessages(); assertEquals("Message log size not as expected.", 0, logs.size()); - } - - /** - * Test that if logging is configured to be off in the configuration that - * no logging is presented - * @throws ConfigurationException - * @throws AMQException - */ - public void testChannelLoggingoff() throws Exception, AMQException - { - getConfigXml().setProperty("status-updates", "off"); - - startBrokerNow(); - - sendTestLogMessage(_amqpActor); - - List<Object> logs = _rawLogger.getLogMessages(); - - assertEquals("Message log size not as expected.", 0, logs.size()); - - } - - /** - * Test that if logging is configured to be off in the configuration that - * no logging is presented - * @throws ConfigurationException - * @throws AMQException - */ - public void testChannelLoggingoFf() throws Exception, AMQException - { - getConfigXml().setProperty("status-updates", "oFf"); - - startBrokerNow(); - - sendTestLogMessage(_amqpActor); - - List<Object> logs = _rawLogger.getLogMessages(); - - assertEquals("Message log size not as expected.", 0, logs.size()); - - } - } diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AMQPConnectionActorTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AMQPConnectionActorTest.java index 4eda9e9da1..d1cf256563 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AMQPConnectionActorTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AMQPConnectionActorTest.java @@ -38,16 +38,9 @@ import java.util.List; public class AMQPConnectionActorTest extends BaseConnectionActorTestCase { @Override - public void configure() + public void setUp() { - // Prevent defaulting Logging to ON - } - - - @Override - public void createBroker() - { - //Prevent auto-broker startup + //Prevent logger creation } /** @@ -60,13 +53,11 @@ public class AMQPConnectionActorTest extends BaseConnectionActorTestCase */ public void testConnection() throws Exception { - getConfigXml().setProperty("status-updates", "ON"); - - super.createBroker(); + super.setUp(); final String message = sendLogMessage(); - List<Object> logs = _rawLogger.getLogMessages(); + List<Object> logs = getRawLogger().getLogMessages(); assertEquals("Message log size not as expected.", 1, logs.size()); @@ -90,14 +81,13 @@ public class AMQPConnectionActorTest extends BaseConnectionActorTestCase public void testConnectionLoggingOff() throws Exception, AMQException { - getConfigXml().setProperty("status-updates", "OFF"); + setStatusUpdatesEnabled(false); - // Start the broker now. - super.createBroker(); + super.setUp(); sendLogMessage(); - List<Object> logs = _rawLogger.getLogMessages(); + List<Object> logs = getRawLogger().getLogMessages(); assertEquals("Message log size not as expected.", 0, logs.size()); @@ -107,7 +97,7 @@ public class AMQPConnectionActorTest extends BaseConnectionActorTestCase { final String message = "test logging"; - _amqpActor.message(new LogSubject() + getAmqpActor().message(new LogSubject() { public String toLogString() { diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AbstractManagementActorTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AbstractManagementActorTest.java new file mode 100644 index 0000000000..bf38bb64bf --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AbstractManagementActorTest.java @@ -0,0 +1,86 @@ +/* + * + * 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/java/broker/src/test/java/org/apache/qpid/server/logging/actors/BaseActorTestCase.java b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/BaseActorTestCase.java index ec2cdd5585..30c3a51604 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/BaseActorTestCase.java +++ b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/BaseActorTestCase.java @@ -20,39 +20,39 @@ */ package org.apache.qpid.server.logging.actors; -import org.apache.qpid.server.configuration.ServerConfiguration; 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.server.util.InternalBrokerBaseCase; +import org.apache.qpid.test.utils.QpidTestCase; -public class BaseActorTestCase extends InternalBrokerBaseCase +public class BaseActorTestCase extends QpidTestCase { - protected LogActor _amqpActor; - protected UnitTestMessageLogger _rawLogger; - protected RootMessageLogger _rootLogger; + private boolean _statusUpdatesEnabled = true; + private LogActor _amqpActor; + private UnitTestMessageLogger _rawLogger; + private RootMessageLogger _rootLogger; @Override - public void configure() + public void setUp() throws Exception { - getConfiguration().getConfig().setProperty(ServerConfiguration.STATUS_UPDATES, "on"); - } - - @Override - public void createBroker() throws Exception - { - super.createBroker(); - - _rawLogger = new UnitTestMessageLogger(getConfiguration()); + super.setUp(); + CurrentActor.removeAll(); + CurrentActor.setDefault(null); + _rawLogger = new UnitTestMessageLogger(_statusUpdatesEnabled); _rootLogger = _rawLogger; } + @Override public void tearDown() throws Exception { - _rawLogger.clearLogMessages(); - + if(_rawLogger != null) + { + _rawLogger.clearLogMessages(); + } + CurrentActor.removeAll(); + CurrentActor.setDefault(null); super.tearDown(); } @@ -87,4 +87,34 @@ public class BaseActorTestCase extends InternalBrokerBaseCase }); } + 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/java/broker/src/test/java/org/apache/qpid/server/logging/actors/BaseConnectionActorTestCase.java b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/BaseConnectionActorTestCase.java index 956d296dce..09dd48e4d3 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/BaseConnectionActorTestCase.java +++ b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/BaseConnectionActorTestCase.java @@ -20,14 +20,43 @@ */ package org.apache.qpid.server.logging.actors; +import org.apache.qpid.server.protocol.AMQProtocolSession; +import org.apache.qpid.server.util.BrokerTestHelper; + public class BaseConnectionActorTestCase extends BaseActorTestCase { + private AMQProtocolSession _session; @Override - public void createBroker() throws Exception + public void setUp() throws Exception { - super.createBroker(); + super.setUp(); + BrokerTestHelper.setUp(); + _session = BrokerTestHelper.createSession(); + + setAmqpActor(new AMQPConnectionActor(_session, getRootLogger())); + } - _amqpActor = new AMQPConnectionActor(getSession(), _rootLogger); + @Override + public void tearDown() throws Exception + { + try + { + if (_session != null) + { + _session.getVirtualHost().close(); + } + } + finally + { + BrokerTestHelper.tearDown(); + super.tearDown(); + } } + + public AMQProtocolSession getSession() + { + return _session; + } + } diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/CurrentActorTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/CurrentActorTest.java index f73765f5aa..8ea5510ce6 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/CurrentActorTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/CurrentActorTest.java @@ -70,12 +70,7 @@ public class CurrentActorTest extends BaseConnectionActorTestCase */ public void testLIFO() throws AMQException, ConfigurationException { - // This test only needs the local objects created, _session etc. - // So stopping the broker and making them useless will not affect the - // test, but the extra actors the test broker adds will so by stopping - // we remove the session actor and so all is good. - stopBroker(); - + assertTrue("Unexpected actor: " + CurrentActor.get(), CurrentActor.get() instanceof TestLogActor); AMQPConnectionActor connectionActor = new AMQPConnectionActor(getSession(), new NullRootMessageLogger()); diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/HttpManagementActorTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/HttpManagementActorTest.java new file mode 100644 index 0000000000..905de4b639 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/HttpManagementActorTest.java @@ -0,0 +1,94 @@ +/* + * + * 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/java/broker/src/test/java/org/apache/qpid/server/logging/actors/ManagementActorTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/ManagementActorTest.java index cb866245f0..a0bfa592db 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/ManagementActorTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/ManagementActorTest.java @@ -20,10 +20,11 @@ */ package org.apache.qpid.server.logging.actors; -import javax.management.remote.JMXPrincipal; import javax.security.auth.Subject; + +import org.apache.qpid.server.security.auth.TestPrincipalUtils; + import java.security.PrivilegedAction; -import java.util.Collections; import java.util.List; public class ManagementActorTest extends BaseActorTestCase @@ -34,10 +35,10 @@ public class ManagementActorTest extends BaseActorTestCase private String _threadName; @Override - public void createBroker() throws Exception + public void setUp() throws Exception { - super.createBroker(); - _amqpActor = new ManagementActor(_rootLogger); + 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(); @@ -56,14 +57,14 @@ public class ManagementActorTest extends BaseActorTestCase * * The test sends a message then verifies that it entered the logs. * - * The log message should be fully repalaced (no '{n}' values) and should + * The log message should be fully replaced (no '{n}' values) and should * not contain any channel identification. */ public void testConnection() { - final String message = sendTestLogMessage(_amqpActor); + final String message = sendTestLogMessage(getAmqpActor()); - List<Object> logs = _rawLogger.getLogMessages(); + List<Object> logs = getRawLogger().getLogMessages(); assertEquals("Message log size not as expected.", 1, logs.size()); @@ -94,21 +95,20 @@ public class ManagementActorTest extends BaseActorTestCase */ public void testSubjectPrincipalNameAppearance() { - Subject subject = new Subject(true, Collections.singleton(new JMXPrincipal("guest")), Collections.EMPTY_SET, - Collections.EMPTY_SET); + Subject subject = TestPrincipalUtils.createTestSubject("guest"); final String message = Subject.doAs(subject, new PrivilegedAction<String>() { public String run() { - return sendTestLogMessage(_amqpActor); + return sendTestLogMessage(getAmqpActor()); } }); // Verify that the log message was created assertNotNull("Test log message is not created!", message); - List<Object> logs = _rawLogger.getLogMessages(); + 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()); @@ -130,8 +130,8 @@ public class ManagementActorTest extends BaseActorTestCase public void testGetLogMessageWithoutSubjectButWithActorPrincipal() { String principalName = "my_principal"; - _amqpActor = new ManagementActor(_rootLogger, principalName); - String message = _amqpActor.getLogMessage(); + setAmqpActor(new ManagementActor(getRootLogger(), principalName)); + String message = getAmqpActor().getLogMessage(); assertEquals("Unexpected log message", "[mng:" + principalName + "(" + IP + ")] ", message); } @@ -149,7 +149,7 @@ public class ManagementActorTest extends BaseActorTestCase assertLogMessageInRMIThreadWithPrincipal("RMI TCP Connection(1)-" + IP, "my_principal"); Thread.currentThread().setName("RMI TCP Connection(2)-" + IP ); - String message = _amqpActor.getLogMessage(); + String message = getAmqpActor().getLogMessage(); assertEquals("Unexpected log message", "[mng:N/A(" + IP + ")] ", message); assertLogMessageWithoutPrincipal("TEST"); @@ -158,28 +158,26 @@ public class ManagementActorTest extends BaseActorTestCase private void assertLogMessageInRMIThreadWithoutPrincipal(String threadName) { Thread.currentThread().setName(threadName ); - String message = _amqpActor.getLogMessage(); + String message = getAmqpActor().getLogMessage(); assertEquals("Unexpected log message", "[mng:N/A(" + IP + ")] ", message); } private void assertLogMessageWithoutPrincipal(String threadName) { Thread.currentThread().setName(threadName ); - String message = _amqpActor.getLogMessage(); + String message = getAmqpActor().getLogMessage(); assertEquals("Unexpected log message", "[" + threadName +"] ", message); } private void assertLogMessageInRMIThreadWithPrincipal(String threadName, String principalName) { Thread.currentThread().setName(threadName); - Subject subject = new Subject(true, Collections.singleton(new JMXPrincipal(principalName)), Collections.EMPTY_SET, - Collections.EMPTY_SET); - + Subject subject = TestPrincipalUtils.createTestSubject(principalName); final String message = Subject.doAs(subject, new PrivilegedAction<String>() { public String run() { - return _amqpActor.getLogMessage(); + return getAmqpActor().getLogMessage(); } }); diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/QueueActorTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/QueueActorTest.java index 409f7c84b7..2dc44c58ce 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/QueueActorTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/QueueActorTest.java @@ -22,14 +22,16 @@ 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 createBroker() throws Exception + public void setUp() throws Exception { - super.createBroker(); - _amqpActor = new QueueActor(getQueue(), _rootLogger); + super.setUp(); + setAmqpActor(new QueueActor(BrokerTestHelper.createQueue(getName(), getSession().getVirtualHost()), getRootLogger())); } /** @@ -42,9 +44,9 @@ public class QueueActorTest extends BaseConnectionActorTestCase */ public void testQueueActor() { - final String message = sendTestLogMessage(_amqpActor); + final String message = sendTestLogMessage(getAmqpActor()); - List<Object> logs = _rawLogger.getLogMessages(); + List<Object> logs = getRawLogger().getLogMessages(); assertEquals("Message log size not as expected.", 1, logs.size()); diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/SubscriptionActorTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/SubscriptionActorTest.java index 8eaa165853..58fca488c4 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/logging/actors/SubscriptionActorTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/logging/actors/SubscriptionActorTest.java @@ -21,6 +21,7 @@ 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; @@ -37,15 +38,15 @@ public class SubscriptionActorTest extends BaseConnectionActorTestCase { @Override - public void createBroker() throws Exception + public void setUp() throws Exception { - super.createBroker(); + super.setUp(); MockSubscription mockSubscription = new MockSubscription(); - mockSubscription.setQueue(getQueue(), false); + mockSubscription.setQueue(BrokerTestHelper.createQueue(getName(), getSession().getVirtualHost()), false); - _amqpActor = new SubscriptionActor(_rootLogger, mockSubscription); + setAmqpActor(new SubscriptionActor(getRootLogger(), mockSubscription)); } /** @@ -58,9 +59,9 @@ public class SubscriptionActorTest extends BaseConnectionActorTestCase */ public void testSubscription() { - final String message = sendTestLogMessage(_amqpActor); + final String message = sendTestLogMessage(getAmqpActor()); - List<Object> logs = _rawLogger.getLogMessages(); + List<Object> logs = getRawLogger().getLogMessages(); assertEquals("Message log size not as expected.", 1, logs.size()); diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/log4j/LoggingFacadeTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/log4j/LoggingManagementFacadeTest.java index f871baffe6..72b34868ba 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/logging/log4j/LoggingFacadeTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/logging/log4j/LoggingManagementFacadeTest.java @@ -20,17 +20,19 @@ 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 LoggingFacadeTest extends TestCase +public class LoggingManagementFacadeTest extends TestCase { - private LoggingFacade _loggingFacade; + private LoggingManagementFacade _loggingFacade; private String _log4jXmlFile; @Override @@ -38,7 +40,7 @@ public class LoggingFacadeTest extends TestCase { super.setUp(); _log4jXmlFile = createTestLog4jXml(); - _loggingFacade = LoggingFacade.configure(_log4jXmlFile); + _loggingFacade = LoggingManagementFacade.configure(_log4jXmlFile); } public void testGetAvailableLoggerLevels() throws Exception @@ -236,10 +238,6 @@ public class LoggingFacadeTest extends TestCase private String createTestLog4jXml() throws Exception { - File dst = File.createTempFile("log4j." + getName(), "xml"); - File filename = new File(getClass().getResource("LoggingFacadeTest.log4j.xml").toURI()); - FileUtils.copy(filename, dst); - dst.deleteOnExit(); - return dst.getAbsolutePath(); + return TestFileUtils.createTempFileFromResource(this, "LoggingFacadeTest.log4j.xml").getAbsolutePath(); } } diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/AbstractTestMessages.java b/java/broker/src/test/java/org/apache/qpid/server/logging/messages/AbstractTestMessages.java index 24e7225d82..229d75c69f 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/AbstractTestMessages.java +++ b/java/broker/src/test/java/org/apache/qpid/server/logging/messages/AbstractTestMessages.java @@ -29,11 +29,12 @@ 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.InternalBrokerBaseCase; +import org.apache.qpid.server.util.BrokerTestHelper; +import org.apache.qpid.test.utils.QpidTestCase; import java.util.List; -public abstract class AbstractTestMessages extends InternalBrokerBaseCase +public abstract class AbstractTestMessages extends QpidTestCase { protected Configuration _config = new PropertiesConfiguration(); protected LogMessage _logMessage = null; @@ -49,6 +50,14 @@ public abstract class AbstractTestMessages extends InternalBrokerBaseCase _logger = new UnitTestMessageLogger(); _actor = new TestLogActor(_logger); + BrokerTestHelper.setUp(); + } + + @Override + public void tearDown() throws Exception + { + BrokerTestHelper.tearDown(); + super.tearDown(); } protected List<Object> performLog() diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ExchangeMessagesTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ExchangeMessagesTest.java index 4364376000..1cb4da55c3 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ExchangeMessagesTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ExchangeMessagesTest.java @@ -21,7 +21,7 @@ package org.apache.qpid.server.logging.messages; import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.registry.ApplicationRegistry; +import org.apache.qpid.server.util.BrokerTestHelper; import java.util.List; @@ -30,12 +30,9 @@ import java.util.List; */ public class ExchangeMessagesTest extends AbstractTestMessages { - public void testExchangeCreated_Transient() + public void testExchangeCreated_Transient() throws Exception { - // Get the Default Exchange on the Test Vhost for testing - Exchange exchange = ApplicationRegistry.getInstance(). - getVirtualHostRegistry().getVirtualHost("test"). - getExchangeRegistry().getDefaultExchange(); + Exchange exchange = BrokerTestHelper.createExchange("test"); String type = exchange.getTypeShortString().toString(); String name = exchange.getNameShortString().toString(); @@ -48,12 +45,9 @@ public class ExchangeMessagesTest extends AbstractTestMessages validateLogMessage(log, "EXH-1001", expected); } - public void testExchangeCreated_Persistent() + public void testExchangeCreated_Persistent() throws Exception { - // Get the Default Exchange on the Test Vhost for testing - Exchange exchange = ApplicationRegistry.getInstance(). - getVirtualHostRegistry().getVirtualHost("test"). - getExchangeRegistry().getDefaultExchange(); + Exchange exchange = BrokerTestHelper.createExchange("test"); String type = exchange.getTypeShortString().toString(); String name = exchange.getNameShortString().toString(); @@ -76,12 +70,9 @@ public class ExchangeMessagesTest extends AbstractTestMessages validateLogMessage(log, "EXH-1002", expected); } - public void testExchangeDiscardedMessage() + public void testExchangeDiscardedMessage() throws Exception { - // Get the Default Exchange on the Test Vhost for testing - final Exchange exchange = ApplicationRegistry.getInstance(). - getVirtualHostRegistry().getVirtualHost("test"). - getExchangeRegistry().getDefaultExchange(); + Exchange exchange = BrokerTestHelper.createExchange("test"); final String name = exchange.getNameShortString().toString(); final String routingKey = "routingKey"; diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ManagementConsoleMessagesTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ManagementConsoleMessagesTest.java index 4bfbae44ac..dfc9357402 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ManagementConsoleMessagesTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ManagementConsoleMessagesTest.java @@ -29,10 +29,10 @@ public class ManagementConsoleMessagesTest extends AbstractTestMessages { public void testManagementStartup() { - _logMessage = ManagementConsoleMessages.STARTUP(); + _logMessage = ManagementConsoleMessages.STARTUP("My"); List<Object> log = performLog(); - String[] expected = {"Startup"}; + String[] expected = {"My Management Startup"}; validateLogMessage(log, "MNG-1001", expected); } @@ -65,29 +65,20 @@ public class ManagementConsoleMessagesTest extends AbstractTestMessages public void testManagementReady() { - _logMessage = ManagementConsoleMessages.READY(false); + _logMessage = ManagementConsoleMessages.READY("My"); List<Object> log = performLog(); - String[] expected = {"Ready"}; - - validateLogMessage(log, "MNG-1004", expected); - - _logger.clearLogMessages(); - - _logMessage = ManagementConsoleMessages.READY(true); - log = performLog(); - - expected = new String[]{"Ready : Using the platform JMX Agent"}; + String[] expected = {"My Management Ready"}; validateLogMessage(log, "MNG-1004", expected); } public void testManagementStopped() { - _logMessage = ManagementConsoleMessages.STOPPED(); + _logMessage = ManagementConsoleMessages.STOPPED("My"); List<Object> log = performLog(); - String[] expected = {"Stopped"}; + String[] expected = {"My Management Stopped"}; validateLogMessage(log, "MNG-1005", expected); } diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/AbstractTestLogSubject.java b/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/AbstractTestLogSubject.java index c2558d2d1b..193e8a490d 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/AbstractTestLogSubject.java +++ b/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/AbstractTestLogSubject.java @@ -20,21 +20,19 @@ */ package org.apache.qpid.server.logging.subjects; -import org.apache.commons.configuration.Configuration; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.configuration.ServerConfiguration; 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.InternalBrokerBaseCase; +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; @@ -49,29 +47,39 @@ import java.util.List; * The resulting log file is then validated. * */ -public abstract class AbstractTestLogSubject extends InternalBrokerBaseCase +public abstract class AbstractTestLogSubject extends QpidTestCase { - protected Configuration _config = new PropertiesConfiguration(); protected LogSubject _subject = null; @Override public void setUp() throws Exception { super.setUp(); - - _config.setProperty(ServerConfiguration.STATUS_UPDATES, "ON"); + BrokerTestHelper.setUp(); } + @Override + public void tearDown() throws Exception + { + BrokerTestHelper.tearDown(); + try + { + CurrentActor.removeAll(); + } + finally + { + super.tearDown(); + } + } - protected List<Object> performLog() throws ConfigurationException + protected List<Object> performLog(boolean statusUpdatesEnabled) { if (_subject == null) { throw new NullPointerException("LogSubject has not been set"); } - ServerConfiguration serverConfig = new ServerConfiguration(_config); - UnitTestMessageLogger logger = new UnitTestMessageLogger(serverConfig); + UnitTestMessageLogger logger = new UnitTestMessageLogger(statusUpdatesEnabled); LogActor actor = new TestLogActor(logger); @@ -247,11 +255,10 @@ public abstract class AbstractTestLogSubject extends InternalBrokerBaseCase /** * Test that when Logging occurs a single log statement is provided * - * @throws ConfigurationException */ - public void testEnabled() throws ConfigurationException + public void testEnabled() { - List<Object> logs = performLog(); + List<Object> logs = performLog(true); assertEquals("Log has incorrect message count", 1, logs.size()); @@ -267,15 +274,11 @@ public abstract class AbstractTestLogSubject extends InternalBrokerBaseCase protected abstract void validateLogStatement(String message); /** - * Ensure that when status-updates are off this does not perform logging - * - * @throws ConfigurationException + * Ensure that when status updates are off this does not perform logging */ - public void testDisabled() throws ConfigurationException + public void testDisabled() { - _config.setProperty(ServerConfiguration.STATUS_UPDATES, "OFF"); - - List<Object> logs = performLog(); + List<Object> logs = performLog(false); assertEquals("Log has incorrect message count", 0, logs.size()); } diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/BindingLogSubjectTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/BindingLogSubjectTest.java index e80c4c4679..dd8d28e836 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/BindingLogSubjectTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/BindingLogSubjectTest.java @@ -24,7 +24,7 @@ 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.registry.ApplicationRegistry; +import org.apache.qpid.server.util.BrokerTestHelper; import org.apache.qpid.server.virtualhost.VirtualHost; /** @@ -38,13 +38,12 @@ public class BindingLogSubjectTest extends AbstractTestLogSubject private Exchange _exchange; private VirtualHost _testVhost; + @Override public void setUp() throws Exception { super.setUp(); - _testVhost = ApplicationRegistry.getInstance().getVirtualHostRegistry(). - getVirtualHost("test"); - // Configure items for subjectCreation + _testVhost = BrokerTestHelper.createVirtualHost("test"); _routingKey = new AMQShortString("RoutingKey"); _exchange = _testVhost.getExchangeRegistry().getDefaultExchange(); _queue = new MockAMQQueue("BindingLogSubjectTest"); @@ -53,6 +52,16 @@ public class BindingLogSubjectTest extends AbstractTestLogSubject _subject = new BindingLogSubject(String.valueOf(_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> diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ChannelLogSubjectTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ChannelLogSubjectTest.java index 6bc5effa05..d75e033739 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ChannelLogSubjectTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ChannelLogSubjectTest.java @@ -34,6 +34,7 @@ public class ChannelLogSubjectTest extends ConnectionLogSubjectTest { super.setUp(); + AMQChannel channel = new AMQChannel(getSession(), _channelID, getSession().getVirtualHost().getMessageStore()); _subject = new ChannelLogSubject(channel); diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ConnectionLogSubjectTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ConnectionLogSubjectTest.java index c246fff2a8..7dc4c443ba 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ConnectionLogSubjectTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ConnectionLogSubjectTest.java @@ -20,17 +20,34 @@ */ package org.apache.qpid.server.logging.subjects; +import org.apache.qpid.server.protocol.InternalTestProtocolSession; +import org.apache.qpid.server.util.BrokerTestHelper; + /** * Validate ConnectionLogSubjects are logged as expected */ public class ConnectionLogSubjectTest extends AbstractTestLogSubject { + private InternalTestProtocolSession _session; + + @Override public void setUp() throws Exception { super.setUp(); - _subject = new ConnectionLogSubject(getSession()); + _session = BrokerTestHelper.createSession("test"); + _subject = new ConnectionLogSubject(_session); + } + + @Override + public void tearDown() throws Exception + { + if (_session != null) + { + _session.getVirtualHost().close(); + } + super.tearDown(); } /** @@ -40,7 +57,12 @@ public class ConnectionLogSubjectTest extends AbstractTestLogSubject */ protected void validateLogStatement(String message) { - verifyConnection(getSession().getSessionID(), "InternalTestProtocolSession", "127.0.0.1:1", "test", message); + verifyConnection(_session.getSessionID(), "InternalTestProtocolSession", "127.0.0.1:1", "test", message); + } + + public InternalTestProtocolSession getSession() + { + return _session; } } diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ExchangeLogSubjectTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ExchangeLogSubjectTest.java index cc06b05bf6..8d1b89bf3c 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ExchangeLogSubjectTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ExchangeLogSubjectTest.java @@ -21,7 +21,7 @@ package org.apache.qpid.server.logging.subjects; import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.registry.ApplicationRegistry; +import org.apache.qpid.server.util.BrokerTestHelper; import org.apache.qpid.server.virtualhost.VirtualHost; @@ -33,17 +33,27 @@ public class ExchangeLogSubjectTest extends AbstractTestLogSubject private Exchange _exchange; private VirtualHost _testVhost; + @Override public void setUp() throws Exception { super.setUp(); - _testVhost = ApplicationRegistry.getInstance().getVirtualHostRegistry(). - getVirtualHost("test"); + _testVhost = BrokerTestHelper.createVirtualHost("test"); _exchange = _testVhost.getExchangeRegistry().getDefaultExchange(); _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> diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/MessageStoreLogSubjectTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/MessageStoreLogSubjectTest.java index c62b24c3b9..65fd249d03 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/MessageStoreLogSubjectTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/MessageStoreLogSubjectTest.java @@ -20,7 +20,7 @@ */ package org.apache.qpid.server.logging.subjects; -import org.apache.qpid.server.registry.ApplicationRegistry; +import org.apache.qpid.server.util.BrokerTestHelper; import org.apache.qpid.server.virtualhost.VirtualHost; /** @@ -30,16 +30,26 @@ public class MessageStoreLogSubjectTest extends AbstractTestLogSubject { private VirtualHost _testVhost; + @Override public void setUp() throws Exception { super.setUp(); - _testVhost = ApplicationRegistry.getInstance().getVirtualHostRegistry(). - getVirtualHost("test"); + _testVhost = BrokerTestHelper.createVirtualHost("test"); _subject = new MessageStoreLogSubject(_testVhost, _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> diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/QueueLogSubjectTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/QueueLogSubjectTest.java index 1f432be57a..e2765f338b 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/QueueLogSubjectTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/QueueLogSubjectTest.java @@ -22,7 +22,7 @@ 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.registry.ApplicationRegistry; +import org.apache.qpid.server.util.BrokerTestHelper; import org.apache.qpid.server.virtualhost.VirtualHost; /** @@ -39,8 +39,7 @@ public class QueueLogSubjectTest extends AbstractTestLogSubject { super.setUp(); - _testVhost = ApplicationRegistry.getInstance().getVirtualHostRegistry(). - getVirtualHost("test"); + _testVhost = BrokerTestHelper.createVirtualHost("test"); _queue = new MockAMQQueue("QueueLogSubjectTest"); ((MockAMQQueue) _queue).setVirtualHost(_testVhost); @@ -48,6 +47,16 @@ public class QueueLogSubjectTest extends AbstractTestLogSubject _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> diff --git a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/SubscriptionLogSubjectTest.java b/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/SubscriptionLogSubjectTest.java index 0c356e1838..153d01f355 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/SubscriptionLogSubjectTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/SubscriptionLogSubjectTest.java @@ -23,12 +23,13 @@ package org.apache.qpid.server.logging.subjects; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.server.AMQChannel; import org.apache.qpid.server.flow.LimitlessCreditManager; +import org.apache.qpid.server.protocol.InternalTestProtocolSession; import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.queue.MockAMQQueue; -import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.subscription.Subscription; import org.apache.qpid.server.subscription.SubscriptionFactory; import org.apache.qpid.server.subscription.SubscriptionFactoryImpl; +import org.apache.qpid.server.util.BrokerTestHelper; import org.apache.qpid.server.virtualhost.VirtualHost; /** @@ -42,23 +43,24 @@ public class SubscriptionLogSubjectTest extends AbstractTestLogSubject private int _channelID = 1; private Subscription _subscription; + @Override public void setUp() throws Exception { super.setUp(); - _testVhost = ApplicationRegistry.getInstance().getVirtualHostRegistry(). - getVirtualHost("test"); + InternalTestProtocolSession session = BrokerTestHelper.createSession(); + _testVhost = session.getVirtualHost(); _queue = new MockAMQQueue("SubscriptionLogSubjectTest"); ((MockAMQQueue) _queue).setVirtualHost(_testVhost); - AMQChannel channel = new AMQChannel(getSession(), _channelID, getSession().getVirtualHost().getMessageStore()); + AMQChannel channel = new AMQChannel(session, _channelID, _testVhost.getMessageStore()); - getSession().addChannel(channel); + session.addChannel(channel); SubscriptionFactory factory = new SubscriptionFactoryImpl(); - _subscription = factory.createSubscription(_channelID, getSession(), new AMQShortString("cTag"), + _subscription = factory.createSubscription(_channelID, session, new AMQShortString("cTag"), false, null, false, new LimitlessCreditManager()); @@ -67,6 +69,16 @@ public class SubscriptionLogSubjectTest extends AbstractTestLogSubject _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> diff --git a/java/broker/src/test/java/org/apache/qpid/server/model/BrokerShutdownTest.java b/java/broker/src/test/java/org/apache/qpid/server/model/BrokerShutdownTest.java new file mode 100644 index 0000000000..7c1db6348b --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/model/BrokerShutdownTest.java @@ -0,0 +1,189 @@ +/* + * + * 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 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.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.State; +import org.apache.qpid.server.configuration.updater.TaskExecutor; +import org.apache.qpid.server.plugin.AuthenticationManagerFactory; +import org.apache.qpid.server.security.auth.manager.PlainPasswordFileAuthenticationManagerFactory; +import org.apache.qpid.server.stats.StatisticsGatherer; +import org.apache.qpid.server.virtualhost.VirtualHostRegistry; +import org.apache.qpid.test.utils.QpidTestCase; +import org.apache.qpid.test.utils.TestFileUtils; + +import java.io.File; +import java.security.Provider; +import java.security.Security; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** + * QPID-1390 : Test to validate that the AuthenticationManger can successfully unregister any new SASL providers when + * the broker is stopped. + */ +public class BrokerShutdownTest extends QpidTestCase +{ + private Provider[] _defaultProviders; + private Broker _broker; + private TaskExecutor _taskExecutor; + + @Override + public void setUp() throws Exception + { + // Get default providers + _defaultProviders = Security.getProviders(); + + super.setUp(); + + _taskExecutor = new TaskExecutor(); + _taskExecutor.start(); + + // Startup the new broker and register the new providers + _broker = startBroker(); + } + + @Override + public void tearDown() throws Exception + { + try + { + super.tearDown(); + } + finally + { + if (_taskExecutor != null) + { + _taskExecutor.stopImmediately(); + } + } + + } + + private Broker startBroker() throws Exception + { + ConfigurationEntryStore store = mock(ConfigurationEntryStore.class); + UUID brokerId = UUID.randomUUID(); + UUID authenticationProviderId = UUID.randomUUID(); + + ConfigurationEntry root = new ConfigurationEntry(brokerId, Broker.class.getSimpleName(), Collections.<String, Object> emptyMap(), + Collections.singleton(authenticationProviderId), store); + + File file = TestFileUtils.createTempFile(BrokerShutdownTest.this, ".db.users"); + Map<String, Object> attributes = new HashMap<String, Object>(); + attributes.put(AuthenticationManagerFactory.ATTRIBUTE_TYPE, PlainPasswordFileAuthenticationManagerFactory.PROVIDER_TYPE); + attributes.put(PlainPasswordFileAuthenticationManagerFactory.ATTRIBUTE_PATH, file.getAbsolutePath()); + ConfigurationEntry authenticationProviderEntry = new ConfigurationEntry(authenticationProviderId, AuthenticationProvider.class.getSimpleName(), attributes, + Collections.<UUID> emptySet(), store); + + when(store.getRootEntry()).thenReturn(root); + when(store.getEntry(brokerId)).thenReturn(root); + when(store.getEntry(authenticationProviderId)).thenReturn(authenticationProviderEntry); + + // mocking the required object + StatisticsGatherer statisticsGatherer = mock(StatisticsGatherer.class); + VirtualHostRegistry virtualHostRegistry = mock(VirtualHostRegistry.class); + LogRecorder logRecorder = mock(LogRecorder.class); + RootMessageLogger rootMessageLogger = mock(RootMessageLogger.class); + + // recover the broker from the store + RecovererProvider provider = new DefaultRecovererProvider(statisticsGatherer, virtualHostRegistry, logRecorder, rootMessageLogger, _taskExecutor); + ConfiguredObjectRecoverer<? extends ConfiguredObject> brokerRecoverer = provider.getRecoverer(Broker.class.getSimpleName()); + + Broker broker = (Broker) brokerRecoverer.create(provider, store.getRootEntry()); + + // start broker + broker.setDesiredState(State.INITIALISING, State.ACTIVE); + return broker; + } + + private void stopBroker() + { + _broker.setDesiredState(State.ACTIVE, State.STOPPED); + } + + /** + * QPID-1399 : Ensure that the Authentication manager unregisters any SASL providers created during + * broker start-up. + * + */ + public void testAuthenticationMangerCleansUp() throws Exception + { + + // Get the providers after initialisation + Provider[] providersAfterInitialisation = Security.getProviders(); + + // Find the additions + List<Provider> additions = new LinkedList<Provider>(); + for (Provider afterInit : providersAfterInitialisation) + { + boolean found = false; + for (Provider defaultProvider : _defaultProviders) + { + if (defaultProvider == afterInit) + { + found = true; + break; + } + } + + // Record added registies + if (!found) + { + additions.add(afterInit); + } + } + + assertFalse("No new SASL mechanisms added by initialisation.", additions.isEmpty()); + + // Close the registry which will perform the close the + // AuthenticationManager + stopBroker(); + + // Validate that the SASL plugins have been removed. + Provider[] providersAfterClose = Security.getProviders(); + + assertTrue("No providers unregistered", providersAfterInitialisation.length > providersAfterClose.length); + + // Ensure that the additions are not still present after close(). + for (Provider afterClose : providersAfterClose) + { + assertFalse("Added provider not unregistered", additions.contains(afterClose)); + } + } + +} diff --git a/java/broker/src/test/java/org/apache/qpid/server/model/UUIDGeneratorTest.java b/java/broker/src/test/java/org/apache/qpid/server/model/UUIDGeneratorTest.java index 643132d371..c686a24e99 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/model/UUIDGeneratorTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/model/UUIDGeneratorTest.java @@ -70,8 +70,12 @@ public class UUIDGeneratorTest extends QpidTestCase 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", 7, idSet.size()); + assertEquals("The produced UUIDs were not all unique", 9, idSet.size()); } public void testQueueIdGeneration() throws Exception diff --git a/java/broker/src/test/java/org/apache/qpid/server/model/adapter/AuthenticationProviderFactoryTest.java b/java/broker/src/test/java/org/apache/qpid/server/model/adapter/AuthenticationProviderFactoryTest.java new file mode 100644 index 0000000000..585fecae83 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/model/adapter/AuthenticationProviderFactoryTest.java @@ -0,0 +1,85 @@ +/* + * + * 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.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.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 +{ + + public void testCreatePasswordCredentialManagingAuthenticationProvider() + { + AuthenticationProvider provider = testForFactory(mock(PrincipalDatabaseAuthenticationManager.class)); + assertTrue("The created provider should match the factory's AuthenticationManager type", + provider instanceof PasswordCredentialManagingAuthenticationProvider); + } + + public void testCreateNonPasswordCredentialManagingAuthenticationProvider() + { + AuthenticationProvider provider = testForFactory(mock(AuthenticationManager.class)); + assertFalse("The created provider should match the factory's AuthenticationManager type", + provider instanceof PasswordCredentialManagingAuthenticationProvider); + } + + @SuppressWarnings("unchecked") + private AuthenticationProvider testForFactory(AuthenticationManager authenticationManager) + { + UUID id = UUID.randomUUID(); + Map<String, Object> attributes = new HashMap<String, Object>(); + + QpidServiceLoader<AuthenticationManagerFactory> authManagerFactoryServiceLoader = mock(QpidServiceLoader.class); + AuthenticationManagerFactory authenticationManagerFactory = mock(AuthenticationManagerFactory.class); + ConfigurationEntry configurationEntry = mock(ConfigurationEntry.class); + + when(configurationEntry.getId()).thenReturn(id); + 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); + AuthenticationProvider provider = providerFactory.create(id, broker, attributes, null); + + assertNotNull("Provider is not created", provider); + assertEquals("Unexpected ID", id, provider.getId()); + + return provider; + } + +} diff --git a/java/broker/src/test/java/org/apache/qpid/server/model/adapter/PortFactoryTest.java b/java/broker/src/test/java/org/apache/qpid/server/model/adapter/PortFactoryTest.java new file mode 100644 index 0000000000..14c5c265c9 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/model/adapter/PortFactoryTest.java @@ -0,0 +1,212 @@ +/* + * + * 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 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.Broker; +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.test.utils.QpidTestCase; + +public class PortFactoryTest extends QpidTestCase +{ + private UUID _portId = UUID.randomUUID(); + private int _portNumber = 123; + private Set<String> _tcpStringSet = Collections.singleton(Transport.SSL.name()); + private Set<Transport> _tcpTransportSet = Collections.singleton(Transport.SSL); + + private Map<String, Object> _attributes = new HashMap<String, Object>(); + + private Broker _broker = mock(Broker.class); + private PortFactory _portFactory; + + @Override + protected void setUp() throws Exception + { + 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.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"); + _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); + 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() + { + Set<Protocol> amqp010ProtocolSet = Collections.singleton(Protocol.AMQP_0_10); + Set<String> amqp010StringSet = Collections.singleton(Protocol.AMQP_0_10.name()); + _attributes.put(Port.PROTOCOLS, amqp010StringSet); + + Port port = _portFactory.createPort(_portId, _broker, _attributes); + + assertNotNull(port); + assertTrue(port instanceof AmqpPortAdapter); + assertEquals(_portId, port.getId()); + assertEquals(_portNumber, port.getPort()); + 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", true, port.getAttribute(Port.NEED_CLIENT_AUTH)); + assertEquals("Unexpected want client auth", true, 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.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.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 + } + } +} diff --git a/java/broker/src/test/java/org/apache/qpid/server/model/configuration/ConfigurationEntryTest.java b/java/broker/src/test/java/org/apache/qpid/server/model/configuration/ConfigurationEntryTest.java new file mode 100644 index 0000000000..dd48d7b56d --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/model/configuration/ConfigurationEntryTest.java @@ -0,0 +1,129 @@ +/* + * + * 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/java/broker/src/test/java/org/apache/qpid/server/plugins/OsgiSystemPackageUtilTest.java b/java/broker/src/test/java/org/apache/qpid/server/plugins/OsgiSystemPackageUtilTest.java deleted file mode 100644 index 20abdd48cd..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/plugins/OsgiSystemPackageUtilTest.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.plugins; - -import org.osgi.framework.Version; - -import org.apache.qpid.test.utils.QpidTestCase; - -import java.util.Map; -import java.util.TreeMap; - -/** - * - */ -public class OsgiSystemPackageUtilTest extends QpidTestCase -{ - private OsgiSystemPackageUtil _util = null; // Object under test - - private Map<String, String> _map = new TreeMap<String, String>(); // Use a TreeMap for unit test in order for determinstic results. - - public void testWithOnePackage() throws Exception - { - _map.put("org.xyz", "1.0.0"); - - _util = new OsgiSystemPackageUtil(null, _map); - - final String systemPackageString = _util.getFormattedSystemPackageString(); - - assertEquals("org.xyz; version=1.0.0", systemPackageString); - } - - public void testWithTwoPackages() throws Exception - { - _map.put("org.xyz", "1.0.0"); - _map.put("org.abc", "1.2.3"); - - _util = new OsgiSystemPackageUtil(null, _map); - - final String systemPackageString = _util.getFormattedSystemPackageString(); - - assertEquals("org.abc; version=1.2.3, org.xyz; version=1.0.0", systemPackageString); - } - - public void testWithNoPackages() throws Exception - { - _util = new OsgiSystemPackageUtil(null, _map); - - final String systemPackageString = _util.getFormattedSystemPackageString(); - - assertNull(systemPackageString); - } - - public void testWithQpidPackageWithQpidReleaseNumberSet() throws Exception - { - _map.put("org.apache.qpid.xyz", "1.0.0"); - _map.put("org.abc", "1.2.3"); - - _util = new OsgiSystemPackageUtil(new Version("0.19"), _map); - - final String systemPackageString = _util.getFormattedSystemPackageString(); - - assertEquals("org.abc; version=1.2.3, org.apache.qpid.xyz; version=0.19.0", systemPackageString); - } - - public void testWithQpidPackageWithoutQpidReleaseNumberSet() throws Exception - { - _map.put("org.apache.qpid.xyz", "1.0.0"); - _map.put("org.abc", "1.2.3"); - - _util = new OsgiSystemPackageUtil(null, _map); - - final String systemPackageString = _util.getFormattedSystemPackageString(); - - assertEquals("org.abc; version=1.2.3, org.apache.qpid.xyz; version=1.0.0", systemPackageString); - } -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/plugins/PluginTest.java b/java/broker/src/test/java/org/apache/qpid/server/plugins/PluginTest.java deleted file mode 100644 index b4bda9a032..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/plugins/PluginTest.java +++ /dev/null @@ -1,55 +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.plugins; - -import org.apache.qpid.server.exchange.ExchangeType; -import org.apache.qpid.server.util.InternalBrokerBaseCase; - -import java.util.Map; - -public class PluginTest extends InternalBrokerBaseCase -{ - private static final String TEST_EXCHANGE_CLASS = "org.apache.qpid.extras.exchanges.example.TestExchangeType"; - - private static final String PLUGIN_DIRECTORY = System.getProperty("example.plugin.target"); - private static final String CACHE_DIRECTORY = System.getProperty("example.cache.target"); - - @Override - public void configure() - { - getConfiguration().getConfig().addProperty("plugin-directory", PLUGIN_DIRECTORY); - getConfiguration().getConfig().addProperty("cache-directory", CACHE_DIRECTORY); - } - - public void disabled_testLoadExchanges() throws Exception - { - PluginManager manager = getRegistry().getPluginManager(); - Map<String, ExchangeType<?>> exchanges = manager.getExchanges(); - assertNotNull("No exchanges found in " + PLUGIN_DIRECTORY, exchanges); - assertEquals("Wrong number of exchanges found in " + PLUGIN_DIRECTORY, 2, exchanges.size()); - assertNotNull("Wrong exchange found in " + PLUGIN_DIRECTORY, exchanges.get(TEST_EXCHANGE_CLASS)); - } - - public void testNoExchanges() throws Exception - { - PluginManager manager = new PluginManager("/path/to/nowhere", "/tmp", null); - Map<String, ExchangeType<?>> exchanges = manager.getExchanges(); - assertTrue("Exchanges found", exchanges.isEmpty()); - } -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/protocol/InternalTestProtocolSession.java b/java/broker/src/test/java/org/apache/qpid/server/protocol/InternalTestProtocolSession.java index 96c67941f9..3216f8886a 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/protocol/InternalTestProtocolSession.java +++ b/java/broker/src/test/java/org/apache/qpid/server/protocol/InternalTestProtocolSession.java @@ -28,10 +28,11 @@ import org.apache.qpid.protocol.AMQConstant; import org.apache.qpid.server.AMQChannel; import org.apache.qpid.server.message.AMQMessage; import org.apache.qpid.server.message.MessageContentSource; +import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.output.ProtocolOutputConverter; import org.apache.qpid.server.queue.QueueEntry; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal; +import org.apache.qpid.server.security.auth.AuthenticatedPrincipal; +import org.apache.qpid.server.security.auth.UsernamePrincipal; import org.apache.qpid.server.subscription.ClientDeliveryMethod; import org.apache.qpid.server.subscription.Subscription; import org.apache.qpid.server.subscription.SubscriptionImpl; @@ -39,6 +40,8 @@ import org.apache.qpid.server.virtualhost.VirtualHost; import org.apache.qpid.transport.TestNetworkConnection; import javax.security.auth.Subject; + +import java.security.Principal; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -55,19 +58,28 @@ public class InternalTestProtocolSession extends AMQProtocolEngine implements Pr private AtomicInteger _deliveryCount = new AtomicInteger(0); private static final AtomicLong ID_GENERATOR = new AtomicLong(0); - public InternalTestProtocolSession(VirtualHost virtualHost) throws AMQException + public InternalTestProtocolSession(VirtualHost virtualHost, Broker broker) throws AMQException { - super(ApplicationRegistry.getInstance().getVirtualHostRegistry(), new TestNetworkConnection(), ID_GENERATOR.getAndIncrement()); + super(broker, new TestNetworkConnection(), ID_GENERATOR.getAndIncrement()); _channelDelivers = new HashMap<Integer, Map<AMQShortString, LinkedList<DeliveryPair>>>(); - // Need to authenticate session for it to be representative testing. - setAuthorizedSubject(new Subject(true, Collections.singleton(new UsernamePrincipal("InternalTestProtocolSession")), - Collections.EMPTY_SET, Collections.EMPTY_SET)); - + setTestAuthorizedSubject(); setVirtualHost(virtualHost); } + private void setTestAuthorizedSubject() + { + Principal principal = new AuthenticatedPrincipal(new UsernamePrincipal("InternalTestProtocolSession")); + Subject authorizedSubject = new Subject( + true, + Collections.singleton(principal), + Collections.emptySet(), + Collections.emptySet()); + + setAuthorizedSubject(authorizedSubject); + } + public ProtocolOutputConverter getProtocolOutputConverter() { return this; diff --git a/java/broker/src/test/java/org/apache/qpid/server/protocol/MaxChannelsTest.java b/java/broker/src/test/java/org/apache/qpid/server/protocol/MaxChannelsTest.java index e8ee2c4d0b..99dd42e179 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/protocol/MaxChannelsTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/protocol/MaxChannelsTest.java @@ -23,20 +23,24 @@ package org.apache.qpid.server.protocol; import org.apache.qpid.AMQException; import org.apache.qpid.protocol.AMQConstant; import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.util.InternalBrokerBaseCase; -import org.apache.qpid.server.virtualhost.VirtualHost; +import org.apache.qpid.server.util.BrokerTestHelper; +import org.apache.qpid.test.utils.QpidTestCase; /** Test class to test MBean operations for AMQMinaProtocolSession. */ -public class MaxChannelsTest extends InternalBrokerBaseCase +public class MaxChannelsTest extends QpidTestCase { - private AMQProtocolEngine _session; + private AMQProtocolEngine _session; - public void testChannels() throws Exception + @Override + public void setUp() throws Exception { - VirtualHost vhost = ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost("test"); - _session = new InternalTestProtocolSession(vhost); + super.setUp(); + BrokerTestHelper.setUp(); + _session = BrokerTestHelper.createSession(); + } + public void testChannels() throws Exception + { // check the channel count is correct int channelCount = _session.getChannels().size(); assertEquals("Initial channel count wrong", 0, channelCount); @@ -45,13 +49,15 @@ public class MaxChannelsTest extends InternalBrokerBaseCase _session.setMaximumNumberOfChannels(maxChannels); assertEquals("Number of channels not correctly set.", new Long(maxChannels), _session.getMaximumNumberOfChannels()); + for (long currentChannel = 0L; currentChannel < maxChannels; currentChannel++) + { + _session.addChannel(new AMQChannel(_session, (int) currentChannel, null)); + } try { - for (long currentChannel = 0L; currentChannel < maxChannels; currentChannel++) - { - _session.addChannel(new AMQChannel(_session, (int) currentChannel, null)); - } + _session.addChannel(new AMQChannel(_session, (int) maxChannels, null)); + fail("Cannot create more channels then maximum"); } catch (AMQException e) { @@ -63,14 +69,14 @@ public class MaxChannelsTest extends InternalBrokerBaseCase @Override public void tearDown() throws Exception { - try { - _session.closeSession(); - } catch (AMQException e) { - // Yikes - fail(e.getMessage()); - } + try + { + _session.getVirtualHost().close(); + _session.closeSession(); + } finally { + BrokerTestHelper.tearDown(); super.tearDown(); } } diff --git a/java/broker/src/test/java/org/apache/qpid/server/protocol/MultiVersionProtocolEngineFactoryTest.java b/java/broker/src/test/java/org/apache/qpid/server/protocol/MultiVersionProtocolEngineFactoryTest.java index 6081be8efd..02b8c74feb 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/protocol/MultiVersionProtocolEngineFactoryTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/protocol/MultiVersionProtocolEngineFactoryTest.java @@ -20,36 +20,52 @@ */ package org.apache.qpid.server.protocol; -import org.apache.commons.configuration.XMLConfiguration; - -import org.apache.qpid.protocol.ServerProtocolEngine; -import org.apache.qpid.server.configuration.ServerConfiguration; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.util.TestApplicationRegistry; -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.transport.TestNetworkConnection; +import static org.mockito.Mockito.when; import java.nio.ByteBuffer; import java.util.EnumSet; import java.util.Set; +import org.apache.qpid.protocol.ServerProtocolEngine; +import org.apache.qpid.server.model.Broker; +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; +import org.apache.qpid.transport.TestNetworkConnection; + public class MultiVersionProtocolEngineFactoryTest extends QpidTestCase { + private VirtualHost _virtualHost; + private Broker _broker; + @Override protected void setUp() throws Exception { super.setUp(); + BrokerTestHelper.setUp(); + _broker = BrokerTestHelper.createBrokerMock(); + VirtualHostRegistry virtualHostRegistry = _broker.getVirtualHostRegistry(); + when(_broker.getAttribute(Broker.DEFAULT_VIRTUAL_HOST)).thenReturn("default"); - //the factory needs a registry instance - ApplicationRegistry.initialise(new TestApplicationRegistry(new ServerConfiguration(new XMLConfiguration()))); + // AMQP 1-0 connection needs default vhost to be present + _virtualHost = BrokerTestHelper.createVirtualHost("default", virtualHostRegistry); } - protected void tearDown() + @Override + protected void tearDown() throws Exception { - //the factory opens a registry instance - ApplicationRegistry.remove(); + try + { + _virtualHost.close(); + } + finally + { + BrokerTestHelper.tearDown(); + super.tearDown(); + } } - + private static final byte[] AMQP_0_8_HEADER = new byte[] { (byte) 'A', (byte) 'M', @@ -108,6 +124,7 @@ public class MultiVersionProtocolEngineFactoryTest extends QpidTestCase (byte) 0 }; + private byte[] getAmqpHeader(final AmqpProtocolVersion version) { switch(version) @@ -137,7 +154,7 @@ public class MultiVersionProtocolEngineFactoryTest extends QpidTestCase Set<AmqpProtocolVersion> versions = EnumSet.allOf(AmqpProtocolVersion.class); MultiVersionProtocolEngineFactory factory = - new MultiVersionProtocolEngineFactory(versions, null); + new MultiVersionProtocolEngineFactory(_broker, versions, null); //create a dummy to retrieve the 'current' ID number long previousId = factory.newProtocolEngine().getConnectionId(); @@ -160,6 +177,7 @@ public class MultiVersionProtocolEngineFactoryTest extends QpidTestCase assertEquals("ID was not as expected following receipt of the AMQP version header", expectedID, engine.getConnectionId()); previousId = expectedID; + engine.closed(); } } @@ -174,7 +192,7 @@ public class MultiVersionProtocolEngineFactoryTest extends QpidTestCase try { - new MultiVersionProtocolEngineFactory(versions, AmqpProtocolVersion.v0_9); + new MultiVersionProtocolEngineFactory(_broker, versions, AmqpProtocolVersion.v0_9); fail("should not have been allowed to create the factory"); } catch(IllegalArgumentException iae) diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/AMQPriorityQueueTest.java b/java/broker/src/test/java/org/apache/qpid/server/queue/AMQPriorityQueueTest.java index c3d58f3bdc..81ad57c040 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/queue/AMQPriorityQueueTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/queue/AMQPriorityQueueTest.java @@ -36,8 +36,9 @@ public class AMQPriorityQueueTest extends SimpleAMQQueueTest @Override public void setUp() throws Exception { - _arguments = new FieldTable(); - _arguments.put(new AMQShortString(AMQQueueFactory.X_QPID_PRIORITIES), 3); + FieldTable arguments = new FieldTable(); + arguments.put(new AMQShortString(AMQQueueFactory.X_QPID_PRIORITIES), 3); + setArguments(arguments); super.setUp(); } @@ -45,25 +46,26 @@ public class AMQPriorityQueueTest extends SimpleAMQQueueTest { // Enqueue messages in order - _queue.enqueue(createMessage(1L, (byte) 10)); - _queue.enqueue(createMessage(2L, (byte) 4)); - _queue.enqueue(createMessage(3L, (byte) 0)); + 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)); + 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)); + queue.enqueue(createMessage(7L, (byte) 4)); + queue.enqueue(createMessage(8L, (byte) 10)); + queue.enqueue(createMessage(9L, (byte) 0)); // Register subscriber - _queue.registerSubscription(_subscription, false); + queue.registerSubscription(getSubscription(), false); Thread.sleep(150); - ArrayList<QueueEntry> msgs = _subscription.getMessages(); + ArrayList<QueueEntry> msgs = getSubscription().getMessages(); try { assertEquals(1L, msgs.get(0).getMessage().getMessageNumber()); diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueFactoryTest.java b/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueFactoryTest.java index 186be4dff7..0f82345271 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueFactoryTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueFactoryTest.java @@ -20,23 +20,23 @@ */ package org.apache.qpid.server.queue; +import static org.mockito.Mockito.when; + import org.apache.commons.configuration.XMLConfiguration; import org.apache.qpid.AMQException; import org.apache.qpid.exchange.ExchangeDefaults; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.server.configuration.ServerConfiguration; +import org.apache.qpid.server.configuration.BrokerProperties; +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.exchange.ExchangeRegistry; -import org.apache.qpid.server.logging.SystemOutMessageLogger; -import org.apache.qpid.server.logging.actors.CurrentActor; -import org.apache.qpid.server.logging.actors.TestLogActor; +import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.UUIDGenerator; -import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.store.TestableMemoryMessageStore; -import org.apache.qpid.server.util.TestApplicationRegistry; +import org.apache.qpid.server.util.BrokerTestHelper; import org.apache.qpid.server.virtualhost.VirtualHost; import org.apache.qpid.test.utils.QpidTestCase; @@ -50,19 +50,19 @@ public class AMQQueueFactoryTest extends QpidTestCase { super.setUp(); - CurrentActor.set(new TestLogActor(new SystemOutMessageLogger())); - + BrokerTestHelper.setUp(); XMLConfiguration configXml = new XMLConfiguration(); - configXml.addProperty("virtualhosts.virtualhost(-1).name", getName()); - configXml.addProperty("virtualhosts.virtualhost(-1)."+getName()+".store.class", TestableMemoryMessageStore.class.getName()); + configXml.addProperty("store.class", TestableMemoryMessageStore.class.getName()); - ServerConfiguration configuration = new ServerConfiguration(configXml); - ApplicationRegistry registry = new TestApplicationRegistry(configuration); - ApplicationRegistry.initialise(registry); - registry.getVirtualHostRegistry().setDefaultVirtualHostName(getName()); + Broker broker = BrokerTestHelper.createBrokerMock(); + if (getName().equals("testDeadLetterQueueDoesNotInheritDLQorMDCSettings")) + { + when(broker.getAttribute(Broker.MAXIMUM_DELIVERY_ATTEMPTS)).thenReturn(5); + when(broker.getAttribute(Broker.DEAD_LETTER_QUEUE_ENABLED)).thenReturn(true); + } - _virtualHost = registry.getVirtualHostRegistry().getVirtualHost(getName()); + _virtualHost = BrokerTestHelper.createVirtualHost(new VirtualHostConfiguration(getName(), configXml, broker)); _queueRegistry = _virtualHost.getQueueRegistry(); @@ -73,11 +73,12 @@ public class AMQQueueFactoryTest extends QpidTestCase { try { - super.tearDown(); + _virtualHost.close(); } finally { - ApplicationRegistry.remove(); + BrokerTestHelper.tearDown(); + super.tearDown(); } } @@ -172,11 +173,8 @@ public class AMQQueueFactoryTest extends QpidTestCase * are not applied to the DLQ itself. * @throws AMQException */ - public void testDeadLetterQueueDoesNotInheritDLQorMDCSettings() throws AMQException + public void testDeadLetterQueueDoesNotInheritDLQorMDCSettings() throws Exception { - ApplicationRegistry.getInstance().getConfiguration().getConfig().addProperty("deadLetterQueues","true"); - ApplicationRegistry.getInstance().getConfiguration().getConfig().addProperty("maximumDeliveryCount","5"); - String queueName = "testDeadLetterQueueEnabled"; AMQShortString dlExchangeName = new AMQShortString(queueName + DefaultExchangeFactory.DEFAULT_DLE_NAME_SUFFIX); AMQShortString dlQueueName = new AMQShortString(queueName + AMQQueueFactory.DEFAULT_DLQ_NAME_SUFFIX); @@ -336,11 +334,8 @@ public class AMQQueueFactoryTest extends QpidTestCase try { // change DLQ name to make its length bigger than exchange name - ApplicationRegistry.getInstance().getConfiguration().getConfig() - .addProperty("deadLetterExchangeSuffix", "_DLE"); - ApplicationRegistry.getInstance().getConfiguration().getConfig() - .addProperty("deadLetterQueueSuffix", "_DLQUEUE"); - + setTestSystemProperty(BrokerProperties.PROPERTY_DEAD_LETTER_EXCHANGE_SUFFIX, "_DLE"); + setTestSystemProperty(BrokerProperties.PROPERTY_DEAD_LETTER_QUEUE_SUFFIX, "_DLQUEUE"); FieldTable fieldTable = new FieldTable(); fieldTable.setBoolean(AMQQueueFactory.X_QPID_DLQ_ENABLED, true); AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), queueName, false, "owner", @@ -353,13 +348,6 @@ public class AMQQueueFactoryTest extends QpidTestCase assertTrue("Unexpected exception message!", e.getMessage().contains("DLQ queue name") && e.getMessage().contains("length exceeds limit of 255")); } - finally - { - ApplicationRegistry.getInstance().getConfiguration().getConfig() - .addProperty("deadLetterExchangeSuffix", DefaultExchangeFactory.DEFAULT_DLE_NAME_SUFFIX); - ApplicationRegistry.getInstance().getConfiguration().getConfig() - .addProperty("deadLetterQueueSuffix", AMQQueueFactory.DEFAULT_DLQ_NAME_SUFFIX); - } } /** @@ -372,11 +360,8 @@ public class AMQQueueFactoryTest extends QpidTestCase try { // change DLQ name to make its length bigger than exchange name - ApplicationRegistry.getInstance().getConfiguration().getConfig() - .addProperty("deadLetterExchangeSuffix", "_DLEXCHANGE"); - ApplicationRegistry.getInstance().getConfiguration().getConfig() - .addProperty("deadLetterQueueSuffix", "_DLQ"); - + setTestSystemProperty(BrokerProperties.PROPERTY_DEAD_LETTER_EXCHANGE_SUFFIX, "_DLEXCHANGE"); + setTestSystemProperty(BrokerProperties.PROPERTY_DEAD_LETTER_QUEUE_SUFFIX, "_DLQ"); FieldTable fieldTable = new FieldTable(); fieldTable.setBoolean(AMQQueueFactory.X_QPID_DLQ_ENABLED, true); AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), queueName, false, "owner", @@ -389,13 +374,6 @@ public class AMQQueueFactoryTest extends QpidTestCase assertTrue("Unexpected exception message!", e.getMessage().contains("DL exchange name") && e.getMessage().contains("length exceeds limit of 255")); } - finally - { - ApplicationRegistry.getInstance().getConfiguration().getConfig() - .addProperty("deadLetterExchangeSuffix", DefaultExchangeFactory.DEFAULT_DLE_NAME_SUFFIX); - ApplicationRegistry.getInstance().getConfiguration().getConfig() - .addProperty("deadLetterQueueSuffix", AMQQueueFactory.DEFAULT_DLQ_NAME_SUFFIX); - } } private String generateStringWithLength(char ch, int length) diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/AckTest.java b/java/broker/src/test/java/org/apache/qpid/server/queue/AckTest.java index 190d5c777b..cbbf183232 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/queue/AckTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/queue/AckTest.java @@ -32,18 +32,16 @@ import org.apache.qpid.server.flow.LimitlessCreditManager; import org.apache.qpid.server.flow.Pre0_10CreditManager; import org.apache.qpid.server.message.AMQMessage; import org.apache.qpid.server.message.MessageMetaData; -import org.apache.qpid.server.model.UUIDGenerator; import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.protocol.InternalTestProtocolSession; -import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.store.StoredMessage; import org.apache.qpid.server.store.TestableMemoryMessageStore; import org.apache.qpid.server.subscription.Subscription; import org.apache.qpid.server.subscription.SubscriptionFactoryImpl; import org.apache.qpid.server.txn.AutoCommitTransaction; import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.util.InternalBrokerBaseCase; +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.Set; @@ -51,7 +49,7 @@ import java.util.Set; /** * Tests that acknowledgements are handled correctly. */ -public class AckTest extends InternalBrokerBaseCase +public class AckTest extends QpidTestCase { private Subscription _subscription; @@ -70,15 +68,19 @@ public class AckTest extends InternalBrokerBaseCase public void setUp() throws Exception { super.setUp(); - _virtualHost = ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost("test"); - _messageStore = new TestableMemoryMessageStore(); - _protocolSession = new InternalTestProtocolSession(_virtualHost); - _channel = new AMQChannel(_protocolSession,5, _messageStore /*dont need exchange registry*/); - - _protocolSession.addChannel(_channel); + BrokerTestHelper.setUp(); + _channel = BrokerTestHelper.createChannel(5); + _protocolSession = _channel.getProtocolSession(); + _virtualHost = _protocolSession.getVirtualHost(); + _queue = BrokerTestHelper.createQueue(getTestName(), _virtualHost); + _messageStore = (TestableMemoryMessageStore)_virtualHost.getMessageStore(); + } - _queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), "myQ", false, "guest", true, false, - _virtualHost, null); + @Override + protected void tearDown() throws Exception + { + BrokerTestHelper.tearDown(); + super.tearDown(); } private void publishMessages(int count) throws AMQException diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/InboundMessageAdapterTest.java b/java/broker/src/test/java/org/apache/qpid/server/queue/InboundMessageAdapterTest.java new file mode 100644 index 0000000000..2f160678ba --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/queue/InboundMessageAdapterTest.java @@ -0,0 +1,97 @@ +/* + * + * 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 testGetRoutingKeyShortString() throws Exception + { + String routingKey = getTestName(); + when(_mockMessage.getRoutingKey()).thenReturn(routingKey); + + AMQShortString routingKeyShortString = AMQShortString.valueOf(routingKey); + assertEquals("Unexpected value for routing key short string", routingKeyShortString, _inboundMessageAdapter.getRoutingKeyShortString()); + } + + 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/java/broker/src/test/java/org/apache/qpid/server/queue/MockAMQQueue.java b/java/broker/src/test/java/org/apache/qpid/server/queue/MockAMQQueue.java index bcb8d54636..358246330a 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/queue/MockAMQQueue.java +++ b/java/broker/src/test/java/org/apache/qpid/server/queue/MockAMQQueue.java @@ -23,10 +23,8 @@ 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.ConfigStore; -import org.apache.qpid.server.configuration.ConfiguredObject; -import org.apache.qpid.server.configuration.QueueConfigType; -import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; +import org.apache.qpid.server.configuration.QueueConfiguration; +import org.apache.qpid.server.configuration.plugins.AbstractConfiguration; import org.apache.qpid.server.exchange.Exchange; import org.apache.qpid.server.logging.LogSubject; import org.apache.qpid.server.message.ServerMessage; @@ -106,11 +104,6 @@ public class MockAMQQueue implements AMQQueue return 0; } - public ConfigStore getConfigStore() - { - return getVirtualHost().getConfigStore(); - } - public long getMessageDequeueCount() { return 0; @@ -186,22 +179,6 @@ public class MockAMQQueue implements AMQQueue return null; } - @Override - public UUID getQMFId() - { - return null; - } - - public QueueConfigType getConfigType() - { - return null; - } - - public ConfiguredObject getParent() - { - return null; - } - public boolean isDurable() { return false; @@ -532,16 +509,11 @@ public class MockAMQQueue implements AMQQueue } - public void configure(ConfigurationPlugin config) + public void configure(QueueConfiguration config) { } - public ConfigurationPlugin getConfiguration() - { - return null; - } - public AuthorizationHolder getAuthorizationHolder() { return _authorizationHolder; diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueTest.java b/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueTest.java index 2cd423d4c9..ece42f7de3 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueTest.java @@ -28,8 +28,6 @@ import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Matchers.contains; import static org.mockito.Matchers.eq; -import org.apache.commons.configuration.PropertiesConfiguration; - import org.apache.qpid.AMQException; import org.apache.qpid.AMQInternalException; import org.apache.qpid.AMQSecurityException; @@ -39,7 +37,6 @@ import org.apache.qpid.framing.BasicContentHeaderProperties; import org.apache.qpid.framing.ContentHeaderBody; import org.apache.qpid.framing.FieldTable; import org.apache.qpid.framing.abstraction.MessagePublishInfo; -import org.apache.qpid.server.configuration.VirtualHostConfiguration; import org.apache.qpid.server.exchange.DirectExchange; import org.apache.qpid.server.message.AMQMessage; import org.apache.qpid.server.message.MessageMetaData; @@ -47,16 +44,15 @@ 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.registry.ApplicationRegistry; import org.apache.qpid.server.store.StoredMessage; import org.apache.qpid.server.store.TestableMemoryMessageStore; import org.apache.qpid.server.subscription.MockSubscription; import org.apache.qpid.server.subscription.Subscription; import org.apache.qpid.server.txn.AutoCommitTransaction; import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.util.InternalBrokerBaseCase; +import org.apache.qpid.server.util.BrokerTestHelper; import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; +import org.apache.qpid.test.utils.QpidTestCase; import java.util.ArrayList; import java.util.Collections; @@ -64,17 +60,17 @@ import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -public class SimpleAMQQueueTest extends InternalBrokerBaseCase +public class SimpleAMQQueueTest extends QpidTestCase { - protected SimpleAMQQueue _queue; - protected VirtualHost _virtualHost; - protected AMQShortString _qname = new AMQShortString("qname"); - protected AMQShortString _owner = new AMQShortString("owner"); - protected AMQShortString _routingKey = new AMQShortString("routing key"); - protected DirectExchange _exchange; - protected MockSubscription _subscription = new MockSubscription(); - protected FieldTable _arguments = null; + private SimpleAMQQueue _queue; + private VirtualHost _virtualHost; + private AMQShortString _qname = new AMQShortString("qname"); + private AMQShortString _owner = new AMQShortString("owner"); + private AMQShortString _routingKey = new AMQShortString("routing key"); + private DirectExchange _exchange; + private MockSubscription _subscription = new MockSubscription(); + private FieldTable _arguments = null; private MessagePublishInfo info = new MessagePublishInfo() { @@ -108,25 +104,29 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase public void setUp() throws Exception { super.setUp(); - //Create Application Registry for test - ApplicationRegistry applicationRegistry = (ApplicationRegistry)ApplicationRegistry.getInstance(); + BrokerTestHelper.setUp(); - PropertiesConfiguration env = new PropertiesConfiguration(); - final VirtualHostConfiguration vhostConfig = new VirtualHostConfiguration(getClass().getName(), env); - vhostConfig.setMessageStoreClass(TestableMemoryMessageStore.class.getName()); - _virtualHost = new VirtualHostImpl(ApplicationRegistry.getInstance(), vhostConfig); - applicationRegistry.getVirtualHostRegistry().registerVirtualHost(_virtualHost); + _virtualHost = BrokerTestHelper.createVirtualHost(getClass().getName()); - _queue = (SimpleAMQQueue) AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), _qname.asString(), false, _owner.asString(), false, false, _virtualHost, FieldTable.convertToMap(_arguments)); + _queue = (SimpleAMQQueue) AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), _qname.asString(), false, _owner.asString(), + false, false, _virtualHost, FieldTable.convertToMap(_arguments)); - _exchange = (DirectExchange)_virtualHost.getExchangeRegistry().getExchange(ExchangeDefaults.DIRECT_EXCHANGE_NAME); + _exchange = (DirectExchange) _virtualHost.getExchangeRegistry().getExchange(ExchangeDefaults.DIRECT_EXCHANGE_NAME); } @Override public void tearDown() throws Exception { - _queue.stop(); - super.tearDown(); + try + { + _queue.stop(); + _virtualHost.close(); + } + finally + { + BrokerTestHelper.tearDown(); + super.tearDown(); + } } public void testCreateQueue() throws AMQException @@ -659,7 +659,7 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase public void onRollback() { } - }, 0L); + }); // Check that it is enqueued AMQQueue data = store.getMessages().get(1L); @@ -1269,6 +1269,26 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase } } + public SimpleAMQQueue getQueue() + { + return _queue; + } + + public MockSubscription getSubscription() + { + return _subscription; + } + + public FieldTable getArguments() + { + return _arguments; + } + + public void setArguments(FieldTable arguments) + { + _arguments = arguments; + } + public class TestMessage extends AMQMessage { private final long _tag; diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueThreadPoolTest.java b/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueThreadPoolTest.java index 6b82cd361a..4abb7233dc 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueThreadPoolTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueThreadPoolTest.java @@ -20,20 +20,33 @@ */ package org.apache.qpid.server.queue; -import org.apache.qpid.AMQException; import org.apache.qpid.pool.ReferenceCountingExecutorService; import org.apache.qpid.server.model.UUIDGenerator; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.util.InternalBrokerBaseCase; +import org.apache.qpid.server.util.BrokerTestHelper; import org.apache.qpid.server.virtualhost.VirtualHost; +import org.apache.qpid.test.utils.QpidTestCase; -public class SimpleAMQQueueThreadPoolTest extends InternalBrokerBaseCase +public class SimpleAMQQueueThreadPoolTest extends QpidTestCase { - public void test() throws AMQException + @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 = ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost("test"); + VirtualHost test = BrokerTestHelper.createVirtualHost("test"); try { @@ -50,7 +63,7 @@ public class SimpleAMQQueueThreadPoolTest extends InternalBrokerBaseCase } finally { - ApplicationRegistry.remove(); + test.close(); } } } diff --git a/java/broker/src/test/java/org/apache/qpid/server/registry/ApplicationRegistryShutdownTest.java b/java/broker/src/test/java/org/apache/qpid/server/registry/ApplicationRegistryShutdownTest.java deleted file mode 100644 index 9af950d385..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/registry/ApplicationRegistryShutdownTest.java +++ /dev/null @@ -1,104 +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.registry; - -import org.apache.qpid.server.util.InternalBrokerBaseCase; - -import java.security.Provider; -import java.security.Security; -import java.util.LinkedList; -import java.util.List; - -/** - * QPID-1390 : Test to validate that the AuthenticationManger can successfully unregister any new SASL providers when - * The ApplicationRegistry is closed. - * - * This should be expanded as QPID-1399 is implemented. - */ -public class ApplicationRegistryShutdownTest extends InternalBrokerBaseCase -{ - - private Provider[] _defaultProviders; - @Override - public void setUp() throws Exception - { - // Get default providers - _defaultProviders = Security.getProviders(); - - //Startup the new broker and register the new providers - super.setUp(); - } - - - /** - * QPID-1399 : Ensure that the Authentication manager unregisters any SASL providers created during - * ApplicationRegistry initialisation. - * - */ - public void testAuthenticationMangerCleansUp() throws Exception - { - - // Get the providers after initialisation - Provider[] providersAfterInitialisation = Security.getProviders(); - - // Find the additions - List additions = new LinkedList(); - for (Provider afterInit : providersAfterInitialisation) - { - boolean found = false; - for (Provider defaultProvider : _defaultProviders) - { - if (defaultProvider == afterInit) - { - found=true; - break; - } - } - - // Record added registies - if (!found) - { - additions.add(afterInit); - } - } - - assertFalse("No new SASL mechanisms added by initialisation.", additions.isEmpty()); - - //Close the registry which will perform the close the AuthenticationManager - stopBroker(); - - //Validate that the SASL plugFins have been removed. - Provider[] providersAfterClose = Security.getProviders(); - - assertTrue("No providers unregistered", providersAfterInitialisation.length > providersAfterClose.length); - - //Ensure that the additions are not still present after close(). - for (Provider afterClose : providersAfterClose) - { - assertFalse("Added provider not unregistered", additions.contains(afterClose)); - } - } - - - - - -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/SubjectCreatorTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/SubjectCreatorTest.java new file mode 100644 index 0000000000..b1bc9bea68 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/security/SubjectCreatorTest.java @@ -0,0 +1,138 @@ +/* + * 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.HashSet; + +import javax.security.auth.Subject; +import javax.security.sasl.SaslServer; + +import junit.framework.TestCase; + +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; +import org.apache.qpid.server.security.group.GroupPrincipalAccessor; + +public class SubjectCreatorTest extends TestCase +{ + private static final String USERNAME = "username"; + private static final String PASSWORD = "password"; + + private AuthenticationManager _authenticationManager = mock(AuthenticationManager.class); + private GroupPrincipalAccessor _groupPrincipalAccessor = mock(GroupPrincipalAccessor.class); + private SubjectCreator _subjectCreator = new SubjectCreator(_authenticationManager, _groupPrincipalAccessor); + + private Principal _userPrincipal = mock(Principal.class); + private Principal _group1 = mock(Principal.class); + private Principal _group2 = mock(Principal.class); + + private AuthenticationResult _authenticationResult; + private SaslServer _testSaslServer = mock(SaslServer.class); + private byte[] _saslResponseBytes = PASSWORD.getBytes(); + + @Override + public void setUp() + { + _authenticationResult = new AuthenticationResult(_userPrincipal); + when(_authenticationManager.authenticate(USERNAME, PASSWORD)).thenReturn(_authenticationResult); + + when(_groupPrincipalAccessor.getGroupPrincipals(USERNAME)) + .thenReturn(new HashSet<Principal>(Arrays.asList(_group1, _group2))); + } + + 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()); + } +} diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/auth/AuthenticatedPrincipalTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/AuthenticatedPrincipalTest.java new file mode 100644 index 0000000000..cd5791952f --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/security/auth/AuthenticatedPrincipalTest.java @@ -0,0 +1,147 @@ +/* + * 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/java/broker/src/test/java/org/apache/qpid/server/security/auth/AuthenticatedPrincipalTestHelper.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/AuthenticatedPrincipalTestHelper.java new file mode 100644 index 0000000000..e9d8d16fce --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/security/auth/AuthenticatedPrincipalTestHelper.java @@ -0,0 +1,54 @@ +/* + * 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/java/broker/src/test/java/org/apache/qpid/server/security/auth/AuthenticationResultTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/AuthenticationResultTest.java new file mode 100644 index 0000000000..a023cbdbb2 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/security/auth/AuthenticationResultTest.java @@ -0,0 +1,112 @@ +/* + * 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/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/TestPrincipalUtils.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/TestPrincipalUtils.java index 7ce03eaa79..ea6b40e3de 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/TestPrincipalUtils.java +++ b/java/broker/src/test/java/org/apache/qpid/server/security/auth/TestPrincipalUtils.java @@ -18,9 +18,12 @@ * under the License. * */ -package org.apache.qpid.server.security.auth.sasl; +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; @@ -28,21 +31,19 @@ import java.util.Set; public class TestPrincipalUtils { - /** - * Creates a test subject, with exactly one UsernamePrincipal and zero or more GroupPrincipals. + * 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 UsernamePrincipal(username)); + principals.add(new AuthenticatedPrincipal(username)); for (String group : groups) { principals.add(new GroupPrincipal(group)); } - - final Subject subject = new Subject(true, principals, Collections.EMPTY_SET, Collections.EMPTY_SET); - return subject; + + return new Subject(true, principals, Collections.EMPTY_SET, Collections.EMPTY_SET); } } diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/UsernamePrincipalTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/UsernamePrincipalTest.java index 75bc76c688..5e025d3ca8 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/UsernamePrincipalTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/security/auth/UsernamePrincipalTest.java @@ -18,13 +18,10 @@ * under the License. * */ -package org.apache.qpid.server.security.auth.sasl; +package org.apache.qpid.server.security.auth; import junit.framework.TestCase; -import javax.security.auth.Subject; -import java.security.Principal; - /** * Tests the UsernamePrincipal. * @@ -70,54 +67,4 @@ public class UsernamePrincipalTest extends TestCase UsernamePrincipal principal = new UsernamePrincipal("string"); assertFalse(principal.equals(null)); } - - public void testGetUsernamePrincipalFromSubject() - { - final UsernamePrincipal expected = new UsernamePrincipal("name"); - final Principal other = new Principal() - { - public String getName() - { - return "otherprincipal"; - } - }; - - final Subject subject = new Subject(); - subject.getPrincipals().add(expected); - subject.getPrincipals().add(other); - - final UsernamePrincipal actual = UsernamePrincipal.getUsernamePrincipalFromSubject(subject); - assertSame(expected, actual); - } - - public void testUsernamePrincipalNotInSubject() - { - try - { - UsernamePrincipal.getUsernamePrincipalFromSubject(new Subject()); - fail("Exception not thrown"); - } - catch (IllegalArgumentException iae) - { - // PASS - } - } - - public void testTooManyUsernamePrincipalInSubject() - { - final Subject subject = new Subject(); - subject.getPrincipals().add(new UsernamePrincipal("name1")); - subject.getPrincipals().add(new UsernamePrincipal("name2")); - try - { - - UsernamePrincipal.getUsernamePrincipalFromSubject(subject); - fail("Exception not thrown"); - } - catch (IllegalArgumentException iae) - { - // PASS - } - } - } diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabaseTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabaseTest.java index 33740af1e7..7b244e219e 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabaseTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabaseTest.java @@ -23,7 +23,7 @@ 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.sasl.UsernamePrincipal; +import org.apache.qpid.server.security.auth.UsernamePrincipal; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.login.AccountNotFoundException; diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PlainPasswordFilePrincipalDatabaseTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PlainPasswordFilePrincipalDatabaseTest.java index b8601f0e5c..8e62324f7d 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PlainPasswordFilePrincipalDatabaseTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PlainPasswordFilePrincipalDatabaseTest.java @@ -22,7 +22,7 @@ package org.apache.qpid.server.security.auth.database; import junit.framework.TestCase; -import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal; +import org.apache.qpid.server.security.auth.UsernamePrincipal; import javax.security.auth.login.AccountNotFoundException; import java.io.BufferedReader; diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PropertiesPrincipalDatabase.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PropertiesPrincipalDatabase.java new file mode 100644 index 0000000000..f670d80ae8 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PropertiesPrincipalDatabase.java @@ -0,0 +1,158 @@ +/* + * 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 org.apache.qpid.server.security.auth.sasl.AuthenticationProviderInitialiser; +import org.apache.qpid.server.security.auth.UsernamePrincipal; +import org.apache.qpid.server.security.auth.sasl.crammd5.CRAMMD5Initialiser; +import org.apache.qpid.server.security.auth.sasl.plain.PlainInitialiser; + +import javax.security.auth.callback.PasswordCallback; +import javax.security.auth.login.AccountNotFoundException; +import java.io.IOException; +import java.security.Principal; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +public class PropertiesPrincipalDatabase implements PrincipalDatabase +{ + private Properties _users; + + private Map<String, AuthenticationProviderInitialiser> _saslServers; + + public PropertiesPrincipalDatabase(Properties users) + { + _users = users; + + _saslServers = new HashMap<String, AuthenticationProviderInitialiser>(); + + /** + * Create Authenticators for Properties Principal Database. + */ + + // Accept MD5 incomming and use plain comparison with the file + PlainInitialiser cram = new PlainInitialiser(); + cram.initialise(this); + // Accept Plain incomming and hash it for comparison to the file. + CRAMMD5Initialiser plain = new CRAMMD5Initialiser(); + plain.initialise(this, CRAMMD5Initialiser.HashDirection.INCOMMING); + + _saslServers.put(plain.getMechanismName(), cram); + _saslServers.put(cram.getMechanismName(), plain); + } + + public void setPassword(Principal principal, PasswordCallback callback) throws IOException, AccountNotFoundException + { + if (principal == null) + { + throw new IllegalArgumentException("principal must not be null"); + } + + + + final String pwd = _users.getProperty(principal.getName()); + + if (pwd != null) + { + callback.setPassword(pwd.toCharArray()); + } + else + { + throw new AccountNotFoundException("No account found for principal " + principal); + } + } + + public boolean verifyPassword(String principal, char[] password) throws AccountNotFoundException + { + //fixme this is not correct as toCharArray is not safe based on the type of string. + char[] pwd = _users.getProperty(principal).toCharArray(); + + return compareCharArray(pwd, password); + } + + public boolean updatePassword(Principal principal, char[] password) throws AccountNotFoundException + { + return false; // updates denied + } + + public boolean createPrincipal(Principal principal, char[] password) + { + return false; // updates denied + } + + public boolean deletePrincipal(Principal principal) throws AccountNotFoundException + { + return false; // updates denied + } + + private boolean compareCharArray(char[] a, char[] b) + { + boolean equal = false; + if (a.length == b.length) + { + equal = true; + int index = 0; + while (equal && index < a.length) + { + equal = a[index] == b[index]; + index++; + } + } + return equal; + } + + + public Map<String, AuthenticationProviderInitialiser> getMechanisms() + { + return _saslServers; + } + + public List<Principal> getUsers() + { + return new LinkedList<Principal>(); //todo + } + + public Principal getUser(String username) + { + if (_users.getProperty(username) != null) + { + return new UsernamePrincipal(username); + } + else + { + return null; + } + } + + public void reload() throws IOException + { + //No file to update from, so do nothing. + } + + @Override + public void setPasswordFile(String passwordFile) + { + throw new UnsupportedOperationException(); + } +} diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/AnonymousAuthenticationManagerTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/AnonymousAuthenticationManagerTest.java index 9dcd22c088..cfeb7c525b 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/AnonymousAuthenticationManagerTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/AnonymousAuthenticationManagerTest.java @@ -20,26 +20,17 @@ */ 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.commons.configuration.CompositeConfiguration; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.configuration.XMLConfiguration; -import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; + import org.apache.qpid.server.security.auth.AuthenticationResult; -import org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase; -import org.apache.qpid.server.util.InternalBrokerBaseCase; +import org.apache.qpid.test.utils.QpidTestCase; -public class AnonymousAuthenticationManagerTest extends InternalBrokerBaseCase +public class AnonymousAuthenticationManagerTest extends QpidTestCase { - - private AuthenticationManager _manager = null; - - public void setUp() throws Exception - { - _manager = AnonymousAuthenticationManager.INSTANCE; - } - + private AuthenticationManager _manager = new AnonymousAuthenticationManager(); public void tearDown() throws Exception { @@ -49,29 +40,6 @@ public class AnonymousAuthenticationManagerTest extends InternalBrokerBaseCase } } - private ConfigurationPlugin getPlainDatabaseConfig() throws ConfigurationException - { - final ConfigurationPlugin config = new PrincipalDatabaseAuthenticationManager.PrincipalDatabaseAuthenticationManagerConfiguration(); - - XMLConfiguration xmlconfig = new XMLConfiguration(); - xmlconfig.addProperty("pd-auth-manager.principal-database.class", PlainPasswordFilePrincipalDatabase.class.getName()); - - // Create a CompositeConfiguration as this is what the broker uses - CompositeConfiguration composite = new CompositeConfiguration(); - composite.addConfiguration(xmlconfig); - config.setConfiguration("security", xmlconfig); - return config; - } - - - public void testConfiguration() throws Exception - { - AuthenticationManager authenticationManager = - AnonymousAuthenticationManager.FACTORY.newInstance(getPlainDatabaseConfig()); - - assertNull("AnonymousAuthenticationManager unexpectedly created when not in config", authenticationManager); - } - public void testGetMechanisms() throws Exception { assertEquals("ANONYMOUS", _manager.getMechanisms()); @@ -102,7 +70,8 @@ public class AnonymousAuthenticationManagerTest extends InternalBrokerBaseCase assertEquals("Expected authentication to be successful", AuthenticationResult.AuthenticationStatus.SUCCESS, result.getStatus()); - assertNotNull("Subject should not be null", result.getSubject()); + + assertOnlyContainsWrapped(AnonymousAuthenticationManager.ANONYMOUS_PRINCIPAL, result.getPrincipals()); } diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/AuthenticationManagerRegistryTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/AuthenticationManagerRegistryTest.java deleted file mode 100644 index efb8df3a38..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/AuthenticationManagerRegistryTest.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.security.auth.manager; - -import static org.mockito.Mockito.*; - -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.qpid.server.configuration.ServerConfiguration; -import org.apache.qpid.server.plugins.Plugin; -import org.apache.qpid.server.plugins.PluginManager; -import org.apache.qpid.server.security.SecurityManager.SecurityConfiguration; -import org.mockito.Mockito; - -import junit.framework.TestCase; - -public class AuthenticationManagerRegistryTest extends TestCase -{ - private static final Map<String, AuthenticationManagerPluginFactory<? extends Plugin>> EMPTY_PLUGINMAP = Collections.emptyMap(); - - private PluginManager _pluginManager = Mockito.mock(PluginManager.class); - private ServerConfiguration _serverConfiguration = Mockito.mock(ServerConfiguration.class); - private SecurityConfiguration _securityConfiguration = Mockito.mock(SecurityConfiguration.class); - - private List<AuthenticationManager> _allCreatedAuthManagers = new ArrayList<AuthenticationManager>(); - - @Override - protected void setUp() throws Exception - { - super.setUp(); - - // Setup server configuration to return mock security config. - when(_serverConfiguration.getConfiguration(SecurityConfiguration.class.getName())).thenReturn(_securityConfiguration); - } - - @Override - protected void tearDown() throws Exception - { - try - { - verifyAllCreatedAuthManagersClosed(); - } - finally - { - super.tearDown(); - } - } - - public void testNoAuthenticationManagerFactoryPluginsFound() throws Exception - { - when(_pluginManager.getAuthenticationManagerPlugins()).thenReturn(EMPTY_PLUGINMAP); - try - { - new AuthenticationManagerRegistry(_serverConfiguration, _pluginManager); - fail("Exception not thrown"); - } - catch (ConfigurationException ce) - { - // PASS - assertEquals("No authentication manager factory plugins found. Check the desired authentication manager plugin has been placed in the plugins directory.", - ce.getMessage()); - } - } - - public void testSameAuthenticationManagerSpecifiedTwice() throws Exception - { - AuthenticationManagerPluginFactory<? extends Plugin> myAuthManagerFactory = newMockFactoryProducingMockAuthManagerImplementing(TestAuthenticationManager1.class); - - Map<String, AuthenticationManagerPluginFactory<? extends Plugin>> pluginMap = createPluginMap(myAuthManagerFactory, myAuthManagerFactory); - - when(_pluginManager.getAuthenticationManagerPlugins()).thenReturn(pluginMap); - - try - { - new AuthenticationManagerRegistry(_serverConfiguration, _pluginManager); - fail("Exception not thrown"); - } - catch (ConfigurationException ce) - { - // PASS - assertEquals("Cannot configure more than one authentication manager of type " + myAuthManagerFactory.getPluginClass().getSimpleName() + ". Remove configuration for one of the authentication managers.", - ce.getMessage()); - } - } - - public void testMultipleAuthenticationManagersSpecifiedButNoDefaultSpecified() throws Exception - { - AuthenticationManagerPluginFactory<? extends Plugin> myAuthManagerFactory1 = newMockFactoryProducingMockAuthManagerImplementing(TestAuthenticationManager1.class); - AuthenticationManagerPluginFactory<? extends Plugin> myAuthManagerFactory2 = newMockFactoryProducingMockAuthManagerImplementing(TestAuthenticationManager2.class); - - Map<String, AuthenticationManagerPluginFactory<? extends Plugin>> pluginMap = createPluginMap(myAuthManagerFactory1, myAuthManagerFactory2); - - when(_pluginManager.getAuthenticationManagerPlugins()).thenReturn(pluginMap); - when(_serverConfiguration.getDefaultAuthenticationManager()).thenReturn(null); - - try - { - new AuthenticationManagerRegistry(_serverConfiguration, _pluginManager); - fail("Exception not thrown"); - } - catch (ConfigurationException ce) - { - // PASS - assertEquals("If more than one authentication manager is configured a default MUST be specified.", - ce.getMessage()); - } - } - - public void testDefaultAuthenticationManagerNotKnown() throws Exception - { - String myDefaultAuthManagerSimpleClassName = "UnknownAuthenticationManager"; - - AuthenticationManagerPluginFactory<? extends Plugin> myAuthManagerFactory1 = newMockFactoryProducingMockAuthManagerImplementing(TestAuthenticationManager1.class); - AuthenticationManagerPluginFactory<? extends Plugin> myAuthManagerFactory2 = newMockFactoryProducingMockAuthManagerImplementing(TestAuthenticationManager2.class); - - Map<String, AuthenticationManagerPluginFactory<? extends Plugin>> pluginMap = createPluginMap(myAuthManagerFactory1, myAuthManagerFactory2); - - when(_pluginManager.getAuthenticationManagerPlugins()).thenReturn(pluginMap); - when(_serverConfiguration.getDefaultAuthenticationManager()).thenReturn(myDefaultAuthManagerSimpleClassName); - - try - { - new AuthenticationManagerRegistry(_serverConfiguration, _pluginManager); - fail("Exception not thrown"); - } - catch (ConfigurationException ce) - { - // PASS - assertTrue("Unexpected message " + ce.getMessage(), - ce.getMessage().startsWith("No authentication managers configured of type " + myDefaultAuthManagerSimpleClassName + " which is specified as the default")); - } - } - - public void testPortMappedToUnknownAuthenticationManager() throws Exception - { - String myDefaultAuthManagerSimpleClassName = "UnknownAuthenticationManager"; - int portNumber = 1234; - - AuthenticationManagerPluginFactory<? extends Plugin> myAuthManagerFactory1 = newMockFactoryProducingMockAuthManagerImplementing(TestAuthenticationManager1.class); - - Map<String, AuthenticationManagerPluginFactory<? extends Plugin>> pluginMap = createPluginMap(myAuthManagerFactory1); - - when(_pluginManager.getAuthenticationManagerPlugins()).thenReturn(pluginMap); - when(_serverConfiguration.getPortAuthenticationMappings()).thenReturn(Collections.singletonMap(portNumber, myDefaultAuthManagerSimpleClassName)); - - try - { - new AuthenticationManagerRegistry(_serverConfiguration, _pluginManager); - fail("Exception not thrown"); - } - catch (ConfigurationException ce) - { - // PASS - assertEquals("Unknown authentication manager class " + myDefaultAuthManagerSimpleClassName + " configured for port " + portNumber, ce.getMessage()); - } - } - - public void testGetAuthenticationManagerForInetSocketAddress() throws Exception - { - AuthenticationManagerPluginFactory<? extends Plugin> myAuthManagerFactory1 = newMockFactoryProducingMockAuthManagerImplementing(TestAuthenticationManager1.class); - Map<String, AuthenticationManagerPluginFactory<? extends Plugin>> pluginMap = createPluginMap(myAuthManagerFactory1); - - when(_pluginManager.getAuthenticationManagerPlugins()).thenReturn(pluginMap); - - AuthenticationManagerRegistry registry = new AuthenticationManagerRegistry(_serverConfiguration, _pluginManager); - - AuthenticationManager authenticationManager = registry.getAuthenticationManager(new InetSocketAddress(1234)); - assertEquals("TestAuthenticationManager1", authenticationManager.getMechanisms()); - - registry.close(); - } - - public void testGetAuthenticationManagerForNonInetSocketAddress() throws Exception - { - AuthenticationManagerPluginFactory<? extends Plugin> myAuthManagerFactory1 = newMockFactoryProducingMockAuthManagerImplementing(TestAuthenticationManager1.class); - Map<String, AuthenticationManagerPluginFactory<? extends Plugin>> pluginMap = createPluginMap(myAuthManagerFactory1); - - when(_pluginManager.getAuthenticationManagerPlugins()).thenReturn(pluginMap); - - AuthenticationManagerRegistry registry = new AuthenticationManagerRegistry(_serverConfiguration, _pluginManager); - - AuthenticationManager authenticationManager = registry.getAuthenticationManager(mock(SocketAddress.class)); - assertEquals("TestAuthenticationManager1", authenticationManager.getMechanisms()); - - registry.close(); - } - - public void testGetAuthenticationManagerWithMultipleAuthenticationManager() throws Exception - { - AuthenticationManagerPluginFactory<? extends Plugin> myAuthManagerFactory1 = newMockFactoryProducingMockAuthManagerImplementing(TestAuthenticationManager1.class); - AuthenticationManagerPluginFactory<? extends Plugin> myAuthManagerFactory2 = newMockFactoryProducingMockAuthManagerImplementing(TestAuthenticationManager2.class); - Map<String, AuthenticationManagerPluginFactory<? extends Plugin>> pluginMap = createPluginMap(myAuthManagerFactory1, myAuthManagerFactory2); - - String defaultAuthManger = myAuthManagerFactory1.getPluginName(); - int unmappedPortNumber = 1234; - int mappedPortNumber = 1235; - String mappedAuthManager = myAuthManagerFactory2.getPluginName(); - - when(_pluginManager.getAuthenticationManagerPlugins()).thenReturn(pluginMap); - when(_serverConfiguration.getDefaultAuthenticationManager()).thenReturn(defaultAuthManger); - when(_serverConfiguration.getPortAuthenticationMappings()).thenReturn(Collections.singletonMap(mappedPortNumber, mappedAuthManager)); - - AuthenticationManagerRegistry registry = new AuthenticationManagerRegistry(_serverConfiguration, _pluginManager); - - AuthenticationManager authenticationManager1 = registry.getAuthenticationManager(new InetSocketAddress(unmappedPortNumber)); - assertEquals("TestAuthenticationManager1", authenticationManager1.getMechanisms()); - - AuthenticationManager authenticationManager2 = registry.getAuthenticationManager(new InetSocketAddress(mappedPortNumber)); - assertEquals("TestAuthenticationManager2", authenticationManager2.getMechanisms()); - - registry.close(); - } - - public void testAuthenticationManagersAreClosed() throws Exception - { - AuthenticationManagerPluginFactory<? extends Plugin> myAuthManagerFactory1 = newMockFactoryProducingMockAuthManagerImplementing(TestAuthenticationManager1.class); - AuthenticationManagerPluginFactory<? extends Plugin> myAuthManagerFactory2 = newMockFactoryProducingMockAuthManagerImplementing(TestAuthenticationManager2.class); - Map<String, AuthenticationManagerPluginFactory<? extends Plugin>> pluginMap = createPluginMap(myAuthManagerFactory1, myAuthManagerFactory2); - - String defaultAuthManger = myAuthManagerFactory1.getPluginName(); - when(_pluginManager.getAuthenticationManagerPlugins()).thenReturn(pluginMap); - when(_serverConfiguration.getDefaultAuthenticationManager()).thenReturn(defaultAuthManger); - - AuthenticationManagerRegistry registry = new AuthenticationManagerRegistry(_serverConfiguration, _pluginManager); - - registry.close(); - } - - private AuthenticationManagerPluginFactory<? extends Plugin> newMockFactoryProducingMockAuthManagerImplementing(Class<? extends AuthenticationManager> authManagerClazz) - throws ConfigurationException - { - AuthenticationManager myAuthManager = mock(authManagerClazz); - when(myAuthManager.getMechanisms()).thenReturn(authManagerClazz.getSimpleName()); // used to verify the getAuthenticationManagerFor returns expected impl. - - AuthenticationManagerPluginFactory myAuthManagerFactory = mock(AuthenticationManagerPluginFactory.class); - when(myAuthManagerFactory.getPluginClass()).thenReturn(myAuthManager.getClass()); - when(myAuthManagerFactory.getPluginName()).thenReturn(myAuthManager.getClass().getSimpleName()); - when(myAuthManagerFactory.newInstance(_securityConfiguration)).thenReturn(myAuthManager); - - _allCreatedAuthManagers.add(myAuthManager); - return myAuthManagerFactory; - } - - private Map<String, AuthenticationManagerPluginFactory<? extends Plugin>> createPluginMap( - AuthenticationManagerPluginFactory<? extends Plugin> myAuthManagerFactory) - { - return createPluginMap(myAuthManagerFactory, null); - } - - private Map<String, AuthenticationManagerPluginFactory<? extends Plugin>> createPluginMap( - AuthenticationManagerPluginFactory<? extends Plugin> authManagerFactory1, - AuthenticationManagerPluginFactory<? extends Plugin> authManagerFactory2) - { - Map<String, AuthenticationManagerPluginFactory<? extends Plugin>> pluginMap = new HashMap<String, AuthenticationManagerPluginFactory<? extends Plugin>>(); - pluginMap.put("config.path.unused1", authManagerFactory1); - if (authManagerFactory2 != null) - { - pluginMap.put("config.path.unused2", authManagerFactory2); - } - return pluginMap; - } - - private void verifyAllCreatedAuthManagersClosed() - { - for (Iterator<AuthenticationManager> iterator = _allCreatedAuthManagers.iterator(); iterator.hasNext();) - { - AuthenticationManager authenticationManager = (AuthenticationManager) iterator.next(); - verify(authenticationManager).close(); - } - } - - private interface TestAuthenticationManager1 extends AuthenticationManager - { - } - - private interface TestAuthenticationManager2 extends AuthenticationManager - { - } -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/Base64MD5PasswordFileAuthenticationManagerFactoryTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/Base64MD5PasswordFileAuthenticationManagerFactoryTest.java new file mode 100644 index 0000000000..04e09e073f --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/Base64MD5PasswordFileAuthenticationManagerFactoryTest.java @@ -0,0 +1,111 @@ +/* + * 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/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/ExternalAuthenticationManagerTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/ExternalAuthenticationManagerTest.java index c1a55ef2ad..a66d73c47d 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/ExternalAuthenticationManagerTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/ExternalAuthenticationManagerTest.java @@ -18,58 +18,18 @@ */ 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.commons.configuration.CompositeConfiguration; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.configuration.XMLConfiguration; -import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; + import org.apache.qpid.server.security.auth.AuthenticationResult; -import org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase; -import org.apache.qpid.server.util.InternalBrokerBaseCase; +import org.apache.qpid.test.utils.QpidTestCase; -public class ExternalAuthenticationManagerTest extends InternalBrokerBaseCase +public class ExternalAuthenticationManagerTest extends QpidTestCase { - - private AuthenticationManager _manager = null; - - public void setUp() throws Exception - { - _manager = ExternalAuthenticationManager.INSTANCE; - } - - - public void tearDown() throws Exception - { - if(_manager != null) - { - _manager = null; - } - } - - private ConfigurationPlugin getPlainDatabaseConfig() throws ConfigurationException - { - final ConfigurationPlugin config = new PrincipalDatabaseAuthenticationManager.PrincipalDatabaseAuthenticationManagerConfiguration(); - - XMLConfiguration xmlconfig = new XMLConfiguration(); - xmlconfig.addProperty("pd-auth-manager.principal-database.class", PlainPasswordFilePrincipalDatabase.class.getName()); - - // Create a CompositeConfiguration as this is what the broker uses - CompositeConfiguration composite = new CompositeConfiguration(); - composite.addConfiguration(xmlconfig); - config.setConfiguration("security", xmlconfig); - return config; - } - - - public void testConfiguration() throws Exception - { - AuthenticationManager authenticationManager = - ExternalAuthenticationManager.FACTORY.newInstance(getPlainDatabaseConfig()); - - assertNull("ExternalAuthenticationManager unexpectedly created when not in config", authenticationManager); - } + private AuthenticationManager _manager = new ExternalAuthenticationManager(); public void testGetMechanisms() throws Exception { @@ -103,12 +63,12 @@ public class ExternalAuthenticationManagerTest extends InternalBrokerBaseCase assertEquals("Expected authentication to be successful", AuthenticationResult.AuthenticationStatus.SUCCESS, result.getStatus()); - assertEquals("Expected principal to be unchanged", - principal, - result.getSubject().getPrincipals().iterator().next()); + + assertOnlyContainsWrapped(principal, result.getPrincipals()); 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, diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/PlainPasswordFileAuthenticationManagerFactoryTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/PlainPasswordFileAuthenticationManagerFactoryTest.java new file mode 100644 index 0000000000..d428f8b211 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/PlainPasswordFileAuthenticationManagerFactoryTest.java @@ -0,0 +1,111 @@ +/* + * 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.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()); + + 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, 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/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManagerTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManagerTest.java index 47c189e4fa..1ae667804a 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManagerTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManagerTest.java @@ -20,132 +20,92 @@ */ package org.apache.qpid.server.security.auth.manager; -import org.apache.commons.configuration.CompositeConfiguration; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.configuration.XMLConfiguration; +import static org.apache.qpid.server.security.auth.AuthenticatedPrincipalTestHelper.assertOnlyContainsWrapped; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; -import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; -import org.apache.qpid.server.security.auth.AuthenticationResult; -import org.apache.qpid.server.security.auth.AuthenticationResult.AuthenticationStatus; -import org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase; -import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal; -import org.apache.qpid.server.util.InternalBrokerBaseCase; +import java.security.Provider; +import java.security.Security; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; -import javax.security.auth.Subject; +import javax.security.auth.callback.CallbackHandler; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileWriter; -import java.security.Provider; -import java.security.Security; +import javax.security.sasl.SaslServerFactory; + +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.PrincipalDatabase; +import org.apache.qpid.server.security.auth.sasl.AuthenticationProviderInitialiser; +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 InternalBrokerBaseCase +public class PrincipalDatabaseAuthenticationManagerTest extends QpidTestCase { + 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 String TEST_USERNAME = "guest"; - private String TEST_PASSWORD = "guest"; + private PrincipalDatabase _principalDatabase; - /** - * @see org.apache.qpid.server.util.InternalBrokerBaseCase#tearDown() - */ @Override public void tearDown() throws Exception { - super.tearDown(); if (_manager != null) { _manager.close(); } + super.tearDown(); } - /** - * @see org.apache.qpid.server.util.InternalBrokerBaseCase#setUp() - */ - @Override - public void setUp() throws Exception + private void setupMocks() throws Exception { - super.setUp(); - - final String passwdFilename = createPasswordFile().getCanonicalPath(); - final ConfigurationPlugin config = getConfig(PlainPasswordFilePrincipalDatabase.class.getName(), - "passwordFile", passwdFilename); + _principalDatabase = mock(PrincipalDatabase.class); - _manager = PrincipalDatabaseAuthenticationManager.FACTORY.newInstance(config); - } + AuthenticationProviderInitialiser _mockMechInitialiser = mock(AuthenticationProviderInitialiser.class); + Map<String, AuthenticationProviderInitialiser> _initialisers = Collections.singletonMap(MOCK_MECH_NAME, _mockMechInitialiser); - /** - * Tests where the case where the config specifies a PD implementation - * that is not found. - */ - public void testPrincipalDatabaseImplementationNotFound() throws Exception - { - try - { - _manager = PrincipalDatabaseAuthenticationManager.FACTORY.newInstance(getConfig("not.Found", null, null)); - fail("Exception not thrown"); - } - catch (ConfigurationException ce) - { - // PASS - } - } + when(_principalDatabase.getMechanisms()).thenReturn(_initialisers); - /** - * Tests where the case where the config specifies a PD implementation - * of the wrong type. - */ - public void testPrincipalDatabaseImplementationWrongType() throws Exception - { - try - { - _manager = PrincipalDatabaseAuthenticationManager.FACTORY.newInstance(getConfig(String.class.getName(), null, null)); // Not a PrincipalDatabase implementation - fail("Exception not thrown"); - } - catch (ConfigurationException ce) - { - // PASS - } + _manager = new PrincipalDatabaseAuthenticationManager(_principalDatabase); + _manager.initialise(); } - /** - * Tests the case where a setter with the desired name cannot be found. - */ - public void testPrincipalDatabaseSetterNotFound() throws Exception + private void setupMocksWithInitialiser() throws Exception { - try - { - _manager = PrincipalDatabaseAuthenticationManager.FACTORY.newInstance(getConfig(PlainPasswordFilePrincipalDatabase.class.getName(), "noMethod", "test")); - fail("Exception not thrown"); - } - catch (ConfigurationException ce) - { - // PASS - } - } + _principalDatabase = mock(PrincipalDatabase.class); - /** - * QPID-1347. Make sure the exception message and stack trace is reasonable for an absent password file. - */ - public void testPrincipalDatabaseThrowsSetterFileNotFound() throws Exception - { - try - { - _manager = PrincipalDatabaseAuthenticationManager.FACTORY.newInstance(getConfig(PlainPasswordFilePrincipalDatabase.class.getName(), "passwordFile", "/not/found")); - fail("Exception not thrown"); - } - catch (ConfigurationException ce) + UsernamePasswordInitialiser usernamePasswordInitialiser = new UsernamePasswordInitialiser() { - // PASS - assertNotNull("Expected an underlying cause", ce.getCause()); - assertEquals(FileNotFoundException.class, ce.getCause().getClass()); - } + @Override + public Class<? extends SaslServerFactory> getServerFactoryClassForJCARegistration() + { + return MySaslServerFactory.class; + } + + @Override + public String getMechanismName() + { + return MOCK_MECH_NAME; + } + }; + + Map<String,AuthenticationProviderInitialiser> initialisers = new HashMap<String, AuthenticationProviderInitialiser>(); + initialisers.put(MOCK_MECH_NAME, usernamePasswordInitialiser); + + when(_principalDatabase.getMechanisms()).thenReturn(initialisers); + + usernamePasswordInitialiser.initialise(_principalDatabase); + + _manager = new PrincipalDatabaseAuthenticationManager(_principalDatabase); + _manager.initialise(); } /** @@ -153,11 +113,16 @@ public class PrincipalDatabaseAuthenticationManagerTest extends InternalBrokerBa */ public void testRegisteredMechanisms() throws Exception { + //Ensure we haven't registered anything yet (though this would really indicate a prior test failure!) + Provider qpidProvider = Security.getProvider(AuthenticationManager.PROVIDER_NAME); + assertNull(qpidProvider); + + setupMocksWithInitialiser(); + assertNotNull(_manager.getMechanisms()); - // relies on those mechanisms attached to PropertiesPrincipalDatabaseManager - assertEquals("AMQPLAIN PLAIN CRAM-MD5", _manager.getMechanisms()); + assertEquals(MOCK_MECH_NAME, _manager.getMechanisms()); - Provider qpidProvider = Security.getProvider(PrincipalDatabaseAuthenticationManager.PROVIDER_NAME); + qpidProvider = Security.getProvider(AuthenticationManager.PROVIDER_NAME); assertNotNull(qpidProvider); } @@ -167,96 +132,103 @@ public class PrincipalDatabaseAuthenticationManagerTest extends InternalBrokerBa */ public void testSaslMechanismCreation() throws Exception { - SaslServer server = _manager.createSaslServer("CRAM-MD5", "localhost", null); + setupMocksWithInitialiser(); + + 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()); - final Subject subject = result.getSubject(); - assertTrue(subject.getPrincipals().contains(new UsernamePrincipal("guest"))); + + 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()); - assertNull(result.getSubject()); + 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()); - assertNull(result.getSubject()); + assertEquals("Principals was not expected size", 0, result.getPrincipals().size()); assertEquals(AuthenticationStatus.ERROR, result.getStatus()); } - /** - * Tests that the authenticate method correctly interprets an - * authentication success. - * - */ public void testNonSaslAuthenticationSuccess() throws Exception { + setupMocks(); + + when(_principalDatabase.verifyPassword("guest", "guest".toCharArray())).thenReturn(true); + AuthenticationResult result = _manager.authenticate("guest", "guest"); - final Subject subject = result.getSubject(); - assertFalse("Subject should not be set read-only", subject.isReadOnly()); - assertTrue(subject.getPrincipals().contains(new UsernamePrincipal("guest"))); + assertOnlyContainsWrapped(PRINCIPAL, result.getPrincipals()); assertEquals(AuthenticationStatus.SUCCESS, result.getStatus()); } - /** - * Tests that the authenticate method correctly interprets an - * authentication success. - * - */ public void testNonSaslAuthenticationNotCompleted() throws Exception { + setupMocks(); + + when(_principalDatabase.verifyPassword("guest", "wrongpassword".toCharArray())).thenReturn(false); + AuthenticationResult result = _manager.authenticate("guest", "wrongpassword"); - assertNull(result.getSubject()); + assertEquals("Principals was not expected size", 0, result.getPrincipals().size()); assertEquals(AuthenticationStatus.CONTINUE, result.getStatus()); } - + /** * Tests the ability to de-register the provider. */ public void testClose() throws Exception { - assertEquals("AMQPLAIN PLAIN CRAM-MD5", _manager.getMechanisms()); - assertNotNull(Security.getProvider(PrincipalDatabaseAuthenticationManager.PROVIDER_NAME)); + setupMocksWithInitialiser(); + + assertEquals(MOCK_MECH_NAME, _manager.getMechanisms()); + assertNotNull(Security.getProvider(AuthenticationManager.PROVIDER_NAME)); _manager.close(); // Check provider has been removed. assertNull(_manager.getMechanisms()); - assertNull(Security.getProvider(PrincipalDatabaseAuthenticationManager.PROVIDER_NAME)); + assertNull(Security.getProvider(AuthenticationManager.PROVIDER_NAME)); _manager = null; } @@ -265,94 +237,90 @@ public class PrincipalDatabaseAuthenticationManagerTest extends InternalBrokerBa */ private SaslServer createTestSaslServer(final boolean complete, final boolean throwSaslException) { - return new SaslServer() - { - public String getMechanismName() - { - return null; - } + return new MySaslServer(throwSaslException, complete); + } - public byte[] evaluateResponse(byte[] response) throws SaslException - { - if (throwSaslException) - { - throw new SaslException("Mocked exception"); - } - return null; - } + public static final class MySaslServer implements SaslServer + { + private final boolean _throwSaslException; + private final boolean _complete; - public boolean isComplete() - { - return complete; - } + public MySaslServer() + { + this(false, true); + } - public String getAuthorizationID() - { - return complete ? "guest" : null; - } + private MySaslServer(boolean throwSaslException, boolean complete) + { + _throwSaslException = throwSaslException; + _complete = complete; + } - public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException - { - return null; - } + public String getMechanismName() + { + return null; + } - public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException + public byte[] evaluateResponse(byte[] response) throws SaslException + { + if (_throwSaslException) { - return null; + throw new SaslException("Mocked exception"); } + return null; + } - public Object getNegotiatedProperty(String propName) - { - return null; - } + public boolean isComplete() + { + return _complete; + } - public void dispose() throws SaslException - { - } - }; - } + public String getAuthorizationID() + { + return _complete ? "guest" : null; + } - private ConfigurationPlugin getConfig(final String clazz, final String argName, final String argValue) throws Exception - { - final ConfigurationPlugin config = new PrincipalDatabaseAuthenticationManager.PrincipalDatabaseAuthenticationManagerConfiguration(); + public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException + { + return null; + } - XMLConfiguration xmlconfig = new XMLConfiguration(); - xmlconfig.addProperty("pd-auth-manager.principal-database.class", clazz); + public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException + { + return null; + } - if (argName != null) + public Object getNegotiatedProperty(String propName) { - xmlconfig.addProperty("pd-auth-manager.principal-database.attributes.attribute.name", argName); - xmlconfig.addProperty("pd-auth-manager.principal-database.attributes.attribute.value", argValue); + return null; } - // Create a CompositeConfiguration as this is what the broker uses - CompositeConfiguration composite = new CompositeConfiguration(); - composite.addConfiguration(xmlconfig); - config.setConfiguration("security", xmlconfig); - return config; + public void dispose() throws SaslException + { + } } - private File createPasswordFile() throws Exception + public static class MySaslServerFactory implements SaslServerFactory { - BufferedWriter writer = null; - try - { - File testFile = File.createTempFile(this.getClass().getName(),"tmp"); - testFile.deleteOnExit(); - - writer = new BufferedWriter(new FileWriter(testFile)); - writer.write(TEST_USERNAME + ":" + TEST_PASSWORD); - writer.newLine(); - - return testFile; - - } - finally + @Override + public SaslServer createSaslServer(String mechanism, String protocol, + String serverName, Map<String, ?> props, CallbackHandler cbh) + throws SaslException { - if (writer != null) + if (MOCK_MECH_NAME.equals(mechanism)) { - writer.close(); + return new MySaslServer(); } + else + { + return null; + } + } + + @Override + public String[] getMechanismNames(Map<String, ?> props) + { + return new String[]{MOCK_MECH_NAME}; } } } diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/SimpleLDAPAuthenticationManagerFactoryTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/SimpleLDAPAuthenticationManagerFactoryTest.java new file mode 100644 index 0000000000..1424bee611 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/SimpleLDAPAuthenticationManagerFactoryTest.java @@ -0,0 +1,48 @@ +/* + * 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/java/broker/src/test/java/org/apache/qpid/server/security/auth/rmi/RMIPasswordAuthenticatorTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/rmi/RMIPasswordAuthenticatorTest.java index c0c55de92a..52b525dd80 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/security/auth/rmi/RMIPasswordAuthenticatorTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/security/auth/rmi/RMIPasswordAuthenticatorTest.java @@ -20,20 +20,26 @@ */ package org.apache.qpid.server.security.auth.rmi; +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.configuration.plugins.ConfigurationPlugin; +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.manager.AuthenticationManager; - -import javax.management.remote.JMXPrincipal; -import javax.security.auth.Subject; -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; -import java.net.InetSocketAddress; -import java.util.Collections; +import org.apache.qpid.server.security.auth.SubjectAuthenticationResult; +import org.apache.qpid.server.security.SecurityManager; /** * Tests the RMIPasswordAuthenticator and its collaboration with the AuthenticationManager. @@ -41,36 +47,35 @@ import java.util.Collections; */ public class RMIPasswordAuthenticatorTest extends TestCase { - private final String USERNAME = "guest"; - private final String PASSWORD = "guest"; + 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 RMIPasswordAuthenticator _rmipa; - private String[] _credentials; + + private SubjectCreator _usernamePasswordOkaySuvjectCreator = createMockSubjectCreator(true, null); + private SubjectCreator _badPasswordSubjectCreator = createMockSubjectCreator(false, null); protected void setUp() throws Exception { - _rmipa = new RMIPasswordAuthenticator(new InetSocketAddress(5672)); - - _credentials = new String[] {USERNAME, PASSWORD}; + when(_broker.getSecurityManager()).thenReturn(_securityManager); + _rmipa = new RMIPasswordAuthenticator(_broker, new InetSocketAddress(8999)); } /** - * Tests a successful authentication. Ensures that a populated read-only subject it returned. + * Tests a successful authentication. Ensures that the expected subject is returned. */ public void testAuthenticationSuccess() { - final Subject expectedSubject = new Subject(true, - Collections.singleton(new JMXPrincipal(USERNAME)), - Collections.EMPTY_SET, - Collections.EMPTY_SET); - - _rmipa.setAuthenticationManager(createTestAuthenticationManager(true, null)); - + when(_broker.getSubjectCreator(any(SocketAddress.class))).thenReturn(_usernamePasswordOkaySuvjectCreator); + when(_securityManager.accessManagement()).thenReturn(true); Subject newSubject = _rmipa.authenticate(_credentials); - assertTrue("Subject must be readonly", newSubject.isReadOnly()); - assertTrue("Returned subject does not equal expected value", - newSubject.equals(expectedSubject)); - + assertSame("Subject must be unchanged", _loginSubject, newSubject); } /** @@ -78,7 +83,7 @@ public class RMIPasswordAuthenticatorTest extends TestCase */ public void testUsernameOrPasswordInvalid() { - _rmipa.setAuthenticationManager(createTestAuthenticationManager(false, null)); + when(_broker.getSubjectCreator(any(SocketAddress.class))).thenReturn(_badPasswordSubjectCreator); try { @@ -89,17 +94,31 @@ public class RMIPasswordAuthenticatorTest extends TestCase { assertEquals("Unexpected exception message", RMIPasswordAuthenticator.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", + RMIPasswordAuthenticator.USER_NOT_AUTHORISED_FOR_MANAGEMENT, se.getMessage()); } } - /** - * Tests case where authentication system itself fails. - */ - public void testAuthenticationFailure() + public void testSubjectCreatorInternalFailure() { final Exception mockAuthException = new Exception("Mock Auth system failure"); - _rmipa.setAuthenticationManager(createTestAuthenticationManager(false, mockAuthException)); + SubjectCreator subjectCreator = createMockSubjectCreator(false, mockAuthException); + when(_broker.getSubjectCreator(any(SocketAddress.class))).thenReturn(subjectCreator); try { @@ -112,13 +131,13 @@ public class RMIPasswordAuthenticatorTest extends TestCase } } - /** * Tests case where authentication manager is not set. */ - public void testNullAuthenticationManager() throws Exception + public void testNullSubjectCreator() throws Exception { - _rmipa.setAuthenticationManager(null); + when(_broker.getSubjectCreator(any(SocketAddress.class))).thenReturn(null); + try { _rmipa.authenticate(_credentials); @@ -126,8 +145,7 @@ public class RMIPasswordAuthenticatorTest extends TestCase } catch (SecurityException se) { - assertEquals("Unexpected exception message", - RMIPasswordAuthenticator.UNABLE_TO_LOOKUP, se.getMessage()); + assertTrue("Unexpected exception message", Pattern.matches("Can't get subject creator for .*:8999", se.getMessage())); } } @@ -155,11 +173,13 @@ public class RMIPasswordAuthenticatorTest extends TestCase */ public void testWithIllegalNumberOfArguments() { + String[] credentials; + // Test handling of incorrect number of credentials try { - _credentials = new String[]{USERNAME, PASSWORD, PASSWORD}; - _rmipa.authenticate(_credentials); + credentials = new String[]{USERNAME, PASSWORD, PASSWORD}; + _rmipa.authenticate(credentials); fail("SecurityException expected due to supplying wrong number of credentials"); } catch (SecurityException se) @@ -172,8 +192,8 @@ public class RMIPasswordAuthenticatorTest extends TestCase try { //send a null array - _credentials = null; - _rmipa.authenticate(_credentials); + credentials = null; + _rmipa.authenticate(credentials); fail("SecurityException expected due to not supplying an array of credentials"); } catch (SecurityException se) @@ -185,8 +205,8 @@ public class RMIPasswordAuthenticatorTest extends TestCase try { //send a null password - _credentials = new String[]{USERNAME, null}; - _rmipa.authenticate(_credentials); + credentials = new String[]{USERNAME, null}; + _rmipa.authenticate(credentials); fail("SecurityException expected due to sending a null password"); } catch (SecurityException se) @@ -198,8 +218,8 @@ public class RMIPasswordAuthenticatorTest extends TestCase try { //send a null username - _credentials = new String[]{null, PASSWORD}; - _rmipa.authenticate(_credentials); + credentials = new String[]{null, PASSWORD}; + _rmipa.authenticate(credentials); fail("SecurityException expected due to sending a null username"); } catch (SecurityException se) @@ -209,55 +229,30 @@ public class RMIPasswordAuthenticatorTest extends TestCase } } - private AuthenticationManager createTestAuthenticationManager(final boolean successfulAuth, final Exception exception) + private SubjectCreator createMockSubjectCreator(final boolean successfulAuth, final Exception exception) { - return new AuthenticationManager() + SubjectCreator subjectCreator = mock(SubjectCreator.class); + + SubjectAuthenticationResult subjectAuthenticationResult; + + if (exception != null) { + + subjectAuthenticationResult = new SubjectAuthenticationResult( + new AuthenticationResult(AuthenticationStatus.ERROR, exception)); + } + else if (successfulAuth) { - public void configure(ConfigurationPlugin config) - { - throw new UnsupportedOperationException(); - } - - public void initialise() - { - throw new UnsupportedOperationException(); - } - - public void close() - { - throw new UnsupportedOperationException(); - } - - public String getMechanisms() - { - throw new UnsupportedOperationException(); - } - - public SaslServer createSaslServer(String mechanism, String localFQDN, Principal externalPrincipal) throws SaslException - { - throw new UnsupportedOperationException(); - } - - public AuthenticationResult authenticate(SaslServer server, byte[] response) - { - throw new UnsupportedOperationException(); - } - - public AuthenticationResult authenticate(String username, String password) - { - if (exception != null) { - return new AuthenticationResult(AuthenticationStatus.ERROR, exception); - } - else if (successfulAuth) - { - return new AuthenticationResult(new Subject()); - } - else - { - return new AuthenticationResult(AuthenticationStatus.CONTINUE); - } - } - - }; + + 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/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/TestPrincipalDatabase.java b/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/TestPrincipalDatabase.java index 8c7f3ad6ef..f94d8ddfc3 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/TestPrincipalDatabase.java +++ b/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/TestPrincipalDatabase.java @@ -86,4 +86,10 @@ public class TestPrincipalDatabase implements PrincipalDatabase // TODO Auto-generated method stub } + @Override + public void setPasswordFile(String passwordFile) throws IOException + { + // TODO Auto-generated method stub + } + } diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/group/FileGroupDatabaseTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/group/FileGroupDatabaseTest.java new file mode 100644 index 0000000000..b020c1655a --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/security/group/FileGroupDatabaseTest.java @@ -0,0 +1,456 @@ +/* + * 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/java/broker/src/test/java/org/apache/qpid/server/security/group/FileGroupManagerFactoryTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/group/FileGroupManagerFactoryTest.java new file mode 100644 index 0000000000..934c0082ea --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/security/group/FileGroupManagerFactoryTest.java @@ -0,0 +1,77 @@ +/* + * 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.FILE_GROUP_MANAGER_TYPE); + _configuration.put(FileGroupManagerFactory.FILE, _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.FILE_GROUP_MANAGER_TYPE); + _configuration.put(FileGroupManagerFactory.FILE, null); + + try + { + _factory.createInstance(_configuration); + fail("Exception not thrown"); + } + catch (RuntimeException re) + { + // PASS + } + } + +} diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/group/FileGroupManagerTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/group/FileGroupManagerTest.java new file mode 100644 index 0000000000..b83d25b206 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/security/group/FileGroupManagerTest.java @@ -0,0 +1,197 @@ +/* + * 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.security.Principal; +import java.util.Properties; +import java.util.Set; + +import org.apache.qpid.server.configuration.IllegalConfigurationException; +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 = "/does.not.exist/"; + + try + { + _manager = new FileGroupManager(filePath); + fail("expected exception was not thrown"); + } + catch(IllegalConfigurationException ce) + { + assertNotNull(ce.getCause()); + assertTrue(ce.getCause() instanceof FileNotFoundException); + } + } + + public void testGetGroupPrincipalsForUser() throws Exception + { + final String groupFileName = writeGroupFile(); + _manager = new FileGroupManager(groupFileName); + + 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); + + 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); + + 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); + + 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); + + 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); + + 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); + + 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/java/broker/src/test/java/org/apache/qpid/server/security/group/GroupPrincipalAccessorTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/group/GroupPrincipalAccessorTest.java new file mode 100644 index 0000000000..e58a1a01f8 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/security/group/GroupPrincipalAccessorTest.java @@ -0,0 +1,80 @@ +/* + * 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 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 junit.framework.TestCase; + +import org.apache.qpid.server.model.GroupProvider; + +public class GroupPrincipalAccessorTest extends TestCase +{ + private static final String USERNAME = "username"; + + private GroupProvider _groupManager1 = mock(GroupProvider.class); + private GroupProvider _groupManager2 = mock(GroupProvider.class); + + private Principal _group1 = mock(Principal.class); + private Principal _group2 = mock(Principal.class); + + @Override + public void setUp() + { + when(_groupManager1.getGroupPrincipalsForUser(USERNAME)).thenReturn(Collections.singleton(_group1)); + when(_groupManager2.getGroupPrincipalsForUser(USERNAME)).thenReturn(Collections.singleton(_group2)); + } + + 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) + { + GroupPrincipalAccessor groupPrincipalAccessor = new GroupPrincipalAccessor(Arrays.asList(_groupManager1, _groupManager2)); + + Set<Principal> actualGroupPrincipals = groupPrincipalAccessor.getGroupPrincipals(USERNAME); + + Set<Principal> expectedGroupPrincipals = new HashSet<Principal>(Arrays.asList(expectedGroups)); + + assertEquals(expectedGroupPrincipals, actualGroupPrincipals); + } +} diff --git a/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/GroupPrincipalTest.java b/java/broker/src/test/java/org/apache/qpid/server/security/group/GroupPrincipalTest.java index 076b7c9248..d285a0797a 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/GroupPrincipalTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/security/group/GroupPrincipalTest.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -18,7 +18,9 @@ * under the License. * */ -package org.apache.qpid.server.security.auth.sasl; +package org.apache.qpid.server.security.group; + +import org.apache.qpid.server.security.auth.UsernamePrincipal; import junit.framework.TestCase; @@ -34,7 +36,7 @@ public class GroupPrincipalTest extends TestCase { final GroupPrincipal principal = new GroupPrincipal("group"); final UsernamePrincipal user = new UsernamePrincipal("name"); - + try { principal.addMember(user); @@ -45,7 +47,7 @@ public class GroupPrincipalTest extends TestCase // PASS } } - + public void testEqualitySameName() { final String string = "string"; @@ -80,7 +82,7 @@ public class GroupPrincipalTest extends TestCase assertFalse(principal.equals(null)); } - + } diff --git a/java/broker/src/test/java/org/apache/qpid/server/signal/SignalHandlerTaskTest.java b/java/broker/src/test/java/org/apache/qpid/server/signal/SignalHandlerTaskTest.java deleted file mode 100644 index 23ee82eae6..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/signal/SignalHandlerTaskTest.java +++ /dev/null @@ -1,119 +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.signal; - -import org.apache.log4j.Logger; - -import org.apache.qpid.test.utils.QpidTestCase; - -import java.lang.management.ManagementFactory; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -public class SignalHandlerTaskTest extends QpidTestCase -{ - private static final Logger LOGGER = Logger.getLogger(SignalHandlerTaskTest.class); - private static final String SUN_MISC_SIGNAL_CLASS = "sun.misc.Signal"; - private static final String SUN_MISC_SIGNAL_HANDLER_CLASS = "sun.misc.SignalHandler"; - - protected void setUp() throws Exception - { - super.setUp(); - } - - public void testSignalHandlerTask() throws Exception - { - final boolean expectedResult = classifyExpectedRegistrationResult(); - final int pid = getPID(); - final CountDownLatch latch = new CountDownLatch(1); - - SignalHandlerTask hupReparseTask = new SignalHandlerTask() - { - public void handle() - { - latch.countDown(); - LOGGER.info("Signal handled, latch decremented"); - } - }; - - assertEquals("Unexpected result trying to register Signal handler", - expectedResult, hupReparseTask.register("HUP")); - LOGGER.info("Signal handler was registered"); - - assertEquals("unexpected count for the latch", 1, latch.getCount()); - - if(expectedResult) - { - //registration succeeded as expected, so now - //send SIGHUP and verify the handler was run - String cmd = "/bin/kill -SIGHUP " + pid; - - LOGGER.info("Sending SIGHUP"); - Runtime.getRuntime().exec(cmd); - - assertTrue("HUP Signal was not handled in the allowed timeframe", - latch.await(5, TimeUnit.SECONDS)); - } - } - - public void testGetPlatformDescription() throws Exception - { - assertNotNull(SignalHandlerTask.getPlatformDescription()); - } - - private boolean classifyExpectedRegistrationResult() - { - String os = System.getProperty("os.name"); - if(String.valueOf(os).toLowerCase().contains("windows")) - { - //Windows does not support SIGHUP so registration will fail - LOGGER.info("Running on windows, so we expect SIGHUP handler registration to fail"); - return false; - } - - //otherwise, if the signal handler classes are present we would expect - //registration to succeed - boolean classesPresent = true; - try - { - Class.forName(SUN_MISC_SIGNAL_CLASS); - Class.forName(SUN_MISC_SIGNAL_HANDLER_CLASS); - LOGGER.info("Signal handling classes were present so we expect SIGHUP handler registration to succeed"); - } - catch (ClassNotFoundException cnfe) - { - classesPresent = false; - } - - return classesPresent; - } - - private int getPID() - { - String processName = ManagementFactory.getRuntimeMXBean().getName(); - - int pid = Integer.parseInt(processName.substring(0,processName.indexOf('@'))); - LOGGER.info("PID was determined to be " + pid); - - return pid; - } - -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/store/DurableConfigurationStoreTest.java b/java/broker/src/test/java/org/apache/qpid/server/store/DurableConfigurationStoreTest.java index cd8d91d835..f0ecfb6407 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/store/DurableConfigurationStoreTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/store/DurableConfigurationStoreTest.java @@ -51,10 +51,6 @@ import org.apache.qpid.server.message.EnqueableMessage; import org.apache.qpid.server.model.UUIDGenerator; import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.queue.MockStoredMessage; -import org.apache.qpid.server.store.ConfigurationRecoveryHandler; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.MessageStoreRecoveryHandler; -import org.apache.qpid.server.store.TransactionLogRecoveryHandler; import org.apache.qpid.server.store.ConfigurationRecoveryHandler.BindingRecoveryHandler; import org.apache.qpid.server.store.ConfigurationRecoveryHandler.ExchangeRecoveryHandler; import org.apache.qpid.server.store.ConfigurationRecoveryHandler.QueueRecoveryHandler; @@ -76,7 +72,6 @@ public class DurableConfigurationStoreTest extends QpidTestCase private QueueRecoveryHandler _queueRecoveryHandler; private ExchangeRecoveryHandler _exchangeRecoveryHandler; private BindingRecoveryHandler _bindingRecoveryHandler; - private ConfigurationRecoveryHandler.BrokerLinkRecoveryHandler _linkRecoveryHandler; private MessageStoreRecoveryHandler _messageStoreRecoveryHandler; private StoredMessageRecoveryHandler _storedMessageRecoveryHandler; private TransactionLogRecoveryHandler _logRecoveryHandler; @@ -116,7 +111,6 @@ public class DurableConfigurationStoreTest extends QpidTestCase when(_recoveryHandler.begin(isA(MessageStore.class))).thenReturn(_exchangeRecoveryHandler); when(_exchangeRecoveryHandler.completeExchangeRecovery()).thenReturn(_queueRecoveryHandler); when(_queueRecoveryHandler.completeQueueRecovery()).thenReturn(_bindingRecoveryHandler); - when(_bindingRecoveryHandler.completeBindingRecovery()).thenReturn(_linkRecoveryHandler); when(_logRecoveryHandler.begin(any(MessageStore.class))).thenReturn(_queueEntryRecoveryHandler); when(_queueEntryRecoveryHandler.completeQueueEntryRecovery()).thenReturn(_dtxRecordRecoveryHandler); when(_exchange.getNameShortString()).thenReturn(AMQShortString.valueOf(EXCHANGE_NAME)); @@ -161,7 +155,7 @@ public class DurableConfigurationStoreTest extends QpidTestCase public void testBindQueue() throws Exception { AMQQueue queue = createTestQueue(QUEUE_NAME, "queueOwner", false); - Binding binding = new Binding(UUIDGenerator.generateRandomUUID(), null, ROUTING_KEY, queue, + Binding binding = new Binding(UUIDGenerator.generateRandomUUID(), ROUTING_KEY, queue, _exchange, FieldTable.convertToMap(_bindingArgs)); _store.bindQueue(binding); @@ -175,7 +169,7 @@ public class DurableConfigurationStoreTest extends QpidTestCase public void testUnbindQueue() throws Exception { AMQQueue queue = createTestQueue(QUEUE_NAME, "queueOwner", false); - Binding binding = new Binding(UUIDGenerator.generateRandomUUID(), null, ROUTING_KEY, queue, + Binding binding = new Binding(UUIDGenerator.generateRandomUUID(), ROUTING_KEY, queue, _exchange, FieldTable.convertToMap(_bindingArgs)); _store.bindQueue(binding); diff --git a/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreCreatorTest.java b/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreCreatorTest.java new file mode 100644 index 0000000000..e74937dd1c --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreCreatorTest.java @@ -0,0 +1,39 @@ +/* + * + * 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.server.store.derby.DerbyMessageStore; +import org.apache.qpid.test.utils.QpidTestCase; + +public class MessageStoreCreatorTest extends QpidTestCase +{ + private static final String[] STORE_TYPES = {MemoryMessageStore.TYPE, DerbyMessageStore.TYPE}; + + public void testMessageStoreCreator() + { + MessageStoreCreator messageStoreCreator = new MessageStoreCreator(); + for (String type : STORE_TYPES) + { + MessageStore store = messageStoreCreator.createMessageStore(type); + assertNotNull("Store of type " + type + " is not created", store); + } + } +} diff --git a/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreTest.java b/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreTest.java index a1536565ad..ffd777243b 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreTest.java @@ -20,6 +20,7 @@ */ package org.apache.qpid.server.store; + import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.qpid.AMQException; @@ -35,11 +36,12 @@ import org.apache.qpid.server.configuration.VirtualHostConfiguration; import org.apache.qpid.server.exchange.DirectExchange; import org.apache.qpid.server.exchange.Exchange; import org.apache.qpid.server.exchange.ExchangeRegistry; -import org.apache.qpid.server.exchange.ExchangeType; import org.apache.qpid.server.exchange.TopicExchange; import org.apache.qpid.server.message.AMQMessage; import org.apache.qpid.server.message.MessageMetaData; +import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.UUIDGenerator; +import org.apache.qpid.server.plugin.ExchangeType; import org.apache.qpid.server.queue.AMQPriorityQueue; import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.queue.AMQQueueFactory; @@ -48,11 +50,11 @@ import org.apache.qpid.server.queue.ConflationQueue; import org.apache.qpid.server.queue.IncomingMessage; import org.apache.qpid.server.queue.QueueRegistry; import org.apache.qpid.server.queue.SimpleAMQQueue; -import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.txn.AutoCommitTransaction; import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.util.InternalBrokerBaseCase; +import org.apache.qpid.server.util.BrokerTestHelper; import org.apache.qpid.server.virtualhost.VirtualHost; +import org.apache.qpid.test.utils.QpidTestCase; import org.apache.qpid.util.FileUtils; import java.io.File; @@ -66,7 +68,7 @@ import java.util.Map; * For persistent stores, it validates that Exchanges, Queues, Bindings and * Messages are persisted and recovered correctly. */ -public class MessageStoreTest extends InternalBrokerBaseCase +public class MessageStoreTest extends QpidTestCase { public static final int DEFAULT_PRIORTY_LEVEL = 5; public static final String SELECTOR_VALUE = "Test = 'MST'"; @@ -93,11 +95,15 @@ public class MessageStoreTest extends InternalBrokerBaseCase private AMQShortString queueOwner = new AMQShortString("MST"); - protected PropertiesConfiguration _config; + private PropertiesConfiguration _config; + + private VirtualHost _virtualHost; + private Broker _broker; public void setUp() throws Exception { super.setUp(); + BrokerTestHelper.setUp(); String storePath = System.getProperty("QPID_WORK") + File.separator + getName(); @@ -107,9 +113,38 @@ public class MessageStoreTest extends InternalBrokerBaseCase cleanup(new File(storePath)); + _broker = BrokerTestHelper.createBrokerMock(); + reloadVirtualHost(); } + @Override + public void tearDown() throws Exception + { + try + { + if (_virtualHost != null) + { + _virtualHost.close(); + } + } + finally + { + BrokerTestHelper.tearDown(); + super.tearDown(); + } + } + + public VirtualHost getVirtualHost() + { + return _virtualHost; + } + + public PropertiesConfiguration getConfig() + { + return _config; + } + protected void reloadVirtualHost() { VirtualHost original = getVirtualHost(); @@ -119,8 +154,6 @@ public class MessageStoreTest extends InternalBrokerBaseCase try { getVirtualHost().close(); - getVirtualHost().getApplicationRegistry(). - getVirtualHostRegistry().unregisterVirtualHost(getVirtualHost()); } catch (Exception e) { @@ -131,7 +164,7 @@ public class MessageStoreTest extends InternalBrokerBaseCase try { - setVirtualHost(ApplicationRegistry.getInstance().createVirtualHost(new VirtualHostConfiguration(getClass().getName(), _config))); + _virtualHost = BrokerTestHelper.createVirtualHost(new VirtualHostConfiguration(getClass().getName(), _config, _broker)); } catch (Exception e) { @@ -628,7 +661,7 @@ public class MessageStoreTest extends InternalBrokerBaseCase { //To change body of implemented methods use File | Settings | File Templates. } - }, 0L); + }); } } diff --git a/java/broker/src/test/java/org/apache/qpid/server/store/ReferenceCountingTest.java b/java/broker/src/test/java/org/apache/qpid/server/store/ReferenceCountingTest.java index 4aa023a25c..7c6891da71 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/store/ReferenceCountingTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/store/ReferenceCountingTest.java @@ -27,6 +27,7 @@ import org.apache.qpid.framing.ContentHeaderBody; import org.apache.qpid.framing.abstraction.MessagePublishInfo; import org.apache.qpid.server.message.AMQMessage; import org.apache.qpid.server.message.MessageMetaData; +import org.apache.qpid.server.message.MessageReference; import org.apache.qpid.test.utils.QpidTestCase; /** @@ -86,10 +87,12 @@ public class ReferenceCountingTest extends QpidTestCase AMQMessage message = new AMQMessage(storedMessage); - message.incrementReference(); + MessageReference ref = message.newReference(); assertEquals(1, _store.getMessageCount()); - message.decrementReference(); + + ref.release(); + assertEquals(0, _store.getMessageCount()); } @@ -142,13 +145,13 @@ public class ReferenceCountingTest extends QpidTestCase AMQMessage message = new AMQMessage(storedMessage); - message.incrementReference(); + MessageReference ref = message.newReference(); // we call routing complete to set up the handle // message.routingComplete(_store, _storeContext, new MessageHandleFactory()); assertEquals(1, _store.getMessageCount()); - message.incrementReference(); - message.decrementReference(); + MessageReference ref2 = message.newReference(); + ref.release(); assertEquals(1, _store.getMessageCount()); } diff --git a/java/broker/src/test/java/org/apache/qpid/server/subscription/MockSubscription.java b/java/broker/src/test/java/org/apache/qpid/server/subscription/MockSubscription.java index 8c5d2684ff..a3552639d1 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/subscription/MockSubscription.java +++ b/java/broker/src/test/java/org/apache/qpid/server/subscription/MockSubscription.java @@ -294,17 +294,12 @@ public class MockSubscription implements Subscription private static class MockSessionModel implements AMQSessionModel { + private final UUID _id = UUID.randomUUID(); @Override - public int compareTo(AMQSessionModel o) - { - return 0; - } - - @Override - public UUID getQMFId() + public UUID getId() { - return null; + return _id; } @Override @@ -409,6 +404,12 @@ public class MockSubscription implements Subscription { return 0; } + + @Override + public int compareTo(AMQSessionModel o) + { + return getId().compareTo(o.getId()); + } } private static class MockConnectionModel implements AMQConnectionModel diff --git a/java/broker/src/test/java/org/apache/qpid/server/subscription/QueueBrowserUsesNoAckTest.java b/java/broker/src/test/java/org/apache/qpid/server/subscription/QueueBrowserUsesNoAckTest.java index 3272bd5447..d35a90e3c8 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/subscription/QueueBrowserUsesNoAckTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/subscription/QueueBrowserUsesNoAckTest.java @@ -21,14 +21,75 @@ package org.apache.qpid.server.subscription; import org.apache.qpid.AMQException; +import org.apache.qpid.common.AMQPFilterTypes; +import org.apache.qpid.exchange.ExchangeDefaults; import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.framing.FieldTable; +import org.apache.qpid.server.AMQChannel; +import org.apache.qpid.server.exchange.Exchange; import org.apache.qpid.server.protocol.InternalTestProtocolSession; -import org.apache.qpid.server.util.InternalBrokerBaseCase; +import org.apache.qpid.server.queue.AMQQueue; +import org.apache.qpid.server.queue.SimpleAMQQueue; +import org.apache.qpid.server.store.MessageStore; +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.test.utils.QpidTestCase; import java.util.List; -public class QueueBrowserUsesNoAckTest extends InternalBrokerBaseCase +public class QueueBrowserUsesNoAckTest extends QpidTestCase { + private AMQChannel _channel; + private SimpleAMQQueue _queue; + private MessageStore _messageStore; + private String _queueName; + + @Override + public void setUp() throws Exception + { + super.setUp(); + BrokerTestHelper.setUp(); + _channel = BrokerTestHelper.createChannel(); + VirtualHost virtualHost = _channel.getVirtualHost(); + _queueName = getTestName(); + _queue = BrokerTestHelper.createQueue(_queueName, virtualHost); + _messageStore = virtualHost.getMessageStore(); + Exchange defaultExchange = virtualHost.getExchangeRegistry().getDefaultExchange(); + virtualHost.getBindingFactory().addBinding(_queueName, _queue, defaultExchange, null); + } + + @Override + public void tearDown() throws Exception + { + try + { + if (_channel != null) + { + _channel.getVirtualHost().close(); + } + } + finally + { + BrokerTestHelper.tearDown(); + super.tearDown(); + } + } + + private AMQChannel getChannel() + { + return _channel; + } + + private InternalTestProtocolSession getSession() + { + return (InternalTestProtocolSession)_channel.getProtocolSession(); + } + + private SimpleAMQQueue getQueue() + { + return _queue; + } public void testQueueBrowserUsesNoAck() throws AMQException { @@ -39,7 +100,7 @@ public class QueueBrowserUsesNoAckTest extends InternalBrokerBaseCase checkStoreContents(0); //Send required messsages to the queue - publishMessages(getSession(), getChannel(), sendMessageCount); + BrokerTestHelper.publishMessages(getChannel(), sendMessageCount, _queueName, ExchangeDefaults.DEFAULT_EXCHANGE_NAME.asString()); //Ensure they are stored checkStoreContents(sendMessageCount); @@ -74,4 +135,16 @@ public class QueueBrowserUsesNoAckTest extends InternalBrokerBaseCase .equals(Subscription.State.SUSPENDED)); } + private void checkStoreContents(int messageCount) + { + assertEquals("Message header count incorrect in the MetaDataMap", messageCount, ((TestableMemoryMessageStore) _messageStore).getMessageCount()); + } + + private AMQShortString browse(AMQChannel channel, AMQQueue queue) throws AMQException + { + FieldTable filters = new FieldTable(); + filters.put(AMQPFilterTypes.NO_CONSUME.getValue(), true); + + return channel.subscribeToQueue(null, queue, true, filters, false, true); + } } diff --git a/java/broker/src/test/java/org/apache/qpid/server/subscription/SubscriptionFactoryImplTest.java b/java/broker/src/test/java/org/apache/qpid/server/subscription/SubscriptionFactoryImplTest.java index 29f45bf7f4..89d434e95d 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/subscription/SubscriptionFactoryImplTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/subscription/SubscriptionFactoryImplTest.java @@ -23,20 +23,55 @@ package org.apache.qpid.server.subscription; import org.apache.qpid.common.AMQPFilterTypes; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.FieldTable; +import org.apache.qpid.server.AMQChannel; import org.apache.qpid.server.flow.WindowCreditManager; +import org.apache.qpid.server.logging.UnitTestMessageLogger; +import org.apache.qpid.server.logging.actors.GenericActor; +import org.apache.qpid.server.protocol.AMQProtocolSession; import org.apache.qpid.server.protocol.ProtocolEngine_0_10; import org.apache.qpid.server.transport.ServerConnection; import org.apache.qpid.server.transport.ServerSession; import org.apache.qpid.server.transport.ServerSessionDelegate; -import org.apache.qpid.server.util.InternalBrokerBaseCase; +import org.apache.qpid.server.util.BrokerTestHelper; +import org.apache.qpid.test.utils.QpidTestCase; import org.apache.qpid.transport.Binary; import org.apache.qpid.transport.MessageAcceptMode; import org.apache.qpid.transport.MessageAcquireMode; import org.apache.qpid.transport.MessageFlowMode; import org.apache.qpid.transport.TestNetworkConnection; -public class SubscriptionFactoryImplTest extends InternalBrokerBaseCase +public class SubscriptionFactoryImplTest extends QpidTestCase { + private AMQChannel _channel; + private AMQProtocolSession _session; + + @Override + public void setUp() throws Exception + { + super.setUp(); + BrokerTestHelper.setUp(); + _channel = BrokerTestHelper.createChannel(); + _session = _channel.getProtocolSession(); + GenericActor.setDefaultMessageLogger(new UnitTestMessageLogger(false)); + } + + @Override + public void tearDown() throws Exception + { + try + { + if (_channel != null) + { + _channel.getVirtualHost().close(); + } + } + finally + { + BrokerTestHelper.tearDown(); + super.tearDown(); + } + } + /** * Tests that while creating Subscriptions of various types, the * ID numbers assigned are allocated from a common sequence @@ -46,35 +81,34 @@ public class SubscriptionFactoryImplTest extends InternalBrokerBaseCase { //create a No-Ack subscription, get the first Subscription ID long previousId = 0; - Subscription noAckSub = SubscriptionFactoryImpl.INSTANCE.createSubscription(1, getSession(), new AMQShortString("1"), false, null, false, getChannel().getCreditManager()); + Subscription noAckSub = SubscriptionFactoryImpl.INSTANCE.createSubscription(1, _session, new AMQShortString("1"), false, null, false, _channel.getCreditManager()); previousId = noAckSub.getSubscriptionID(); //create an ack subscription, verify the next Subscription ID is used - Subscription ackSub = SubscriptionFactoryImpl.INSTANCE.createSubscription(1, getSession(), new AMQShortString("1"), true, null, false, getChannel().getCreditManager()); + Subscription ackSub = SubscriptionFactoryImpl.INSTANCE.createSubscription(1, _session, new AMQShortString("1"), true, null, false, _channel.getCreditManager()); assertEquals("Unexpected Subscription ID allocated", previousId + 1, ackSub.getSubscriptionID()); previousId = ackSub.getSubscriptionID(); //create a browser subscription FieldTable filters = new FieldTable(); filters.put(AMQPFilterTypes.NO_CONSUME.getValue(), true); - Subscription browerSub = SubscriptionFactoryImpl.INSTANCE.createSubscription(1, getSession(), new AMQShortString("1"), true, null, false, getChannel().getCreditManager()); + Subscription browerSub = SubscriptionFactoryImpl.INSTANCE.createSubscription(1, _session, new AMQShortString("1"), true, null, false, _channel.getCreditManager()); assertEquals("Unexpected Subscription ID allocated", previousId + 1, browerSub.getSubscriptionID()); previousId = browerSub.getSubscriptionID(); //create an BasicGet NoAck subscription - Subscription getNoAckSub = SubscriptionFactoryImpl.INSTANCE.createBasicGetNoAckSubscription(getChannel(), getSession(), new AMQShortString("1"), null, false, - getChannel().getCreditManager(),getChannel().getClientDeliveryMethod(), getChannel().getRecordDeliveryMethod()); + Subscription getNoAckSub = SubscriptionFactoryImpl.INSTANCE.createBasicGetNoAckSubscription(_channel, _session, new AMQShortString("1"), null, false, + _channel.getCreditManager(),_channel.getClientDeliveryMethod(), _channel.getRecordDeliveryMethod()); assertEquals("Unexpected Subscription ID allocated", previousId + 1, getNoAckSub.getSubscriptionID()); previousId = getNoAckSub.getSubscriptionID(); //create a 0-10 subscription ServerConnection conn = new ServerConnection(1); - ProtocolEngine_0_10 engine = new ProtocolEngine_0_10(conn, new TestNetworkConnection(), getRegistry()); - conn.setVirtualHost(getVirtualHost()); - conn.setConnectionConfig(engine); + ProtocolEngine_0_10 engine = new ProtocolEngine_0_10(conn, new TestNetworkConnection()); + conn.setVirtualHost(_session.getVirtualHost()); ServerSessionDelegate sesDel = new ServerSessionDelegate(); Binary name = new Binary(new byte[]{new Byte("1")}); - ServerSession session = new ServerSession(conn, sesDel, name, 0, engine); + ServerSession session = new ServerSession(conn, sesDel, name, 0); Subscription sub_0_10 = SubscriptionFactoryImpl.INSTANCE.createSubscription(session, "1", MessageAcceptMode.EXPLICIT, MessageAcquireMode.PRE_ACQUIRED, MessageFlowMode.WINDOW, new WindowCreditManager(), null, null); diff --git a/java/broker/src/test/java/org/apache/qpid/server/transport/ServerSessionTest.java b/java/broker/src/test/java/org/apache/qpid/server/transport/ServerSessionTest.java index d775b0f2f8..3389773ff8 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/transport/ServerSessionTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/transport/ServerSessionTest.java @@ -1,5 +1,4 @@ /* - * * 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 @@ -16,19 +15,17 @@ * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. - * */ package org.apache.qpid.server.transport; -import java.util.UUID; - -import org.apache.qpid.server.configuration.MockConnectionConfig; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.util.InternalBrokerBaseCase; +import org.apache.qpid.server.logging.actors.CurrentActor; +import org.apache.qpid.server.logging.actors.GenericActor; +import org.apache.qpid.server.util.BrokerTestHelper; import org.apache.qpid.server.virtualhost.VirtualHost; +import org.apache.qpid.test.utils.QpidTestCase; import org.apache.qpid.transport.Binary; -public class ServerSessionTest extends InternalBrokerBaseCase +public class ServerSessionTest extends QpidTestCase { private VirtualHost _virtualHost; @@ -37,31 +34,44 @@ public class ServerSessionTest extends InternalBrokerBaseCase public void setUp() throws Exception { super.setUp(); - _virtualHost = ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHosts().iterator().next(); + BrokerTestHelper.setUp(); + _virtualHost = BrokerTestHelper.createVirtualHost(getName()); + GenericActor.setDefaultMessageLogger(CurrentActor.get().getRootMessageLogger()); + } + + @Override + public void tearDown() throws Exception + { + try + { + if (_virtualHost != null) + { + _virtualHost.close(); + } + } + finally + { + BrokerTestHelper.tearDown(); + super.tearDown(); + } } public void testCompareTo() throws Exception { ServerConnection connection = new ServerConnection(1); - connection.setConnectionConfig(createConnectionConfig()); + connection.setVirtualHost(_virtualHost); ServerSession session1 = new ServerSession(connection, new ServerSessionDelegate(), - new Binary(getName().getBytes()), 0 , connection.getConfig()); + new Binary(getName().getBytes()), 0); // create a session with the same name but on a different connection ServerConnection connection2 = new ServerConnection(2); - connection2.setConnectionConfig(createConnectionConfig()); + connection2.setVirtualHost(_virtualHost); ServerSession session2 = new ServerSession(connection2, new ServerSessionDelegate(), - new Binary(getName().getBytes()), 0 , connection2.getConfig()); + new Binary(getName().getBytes()), 0); assertFalse("Unexpected compare result", session1.compareTo(session2) == 0); assertEquals("Unexpected compare result", 0, session1.compareTo(session1)); } - private MockConnectionConfig createConnectionConfig() - { - return new MockConnectionConfig(UUID.randomUUID(), null, null, - false, 1, _virtualHost, "address", Boolean.TRUE, Boolean.TRUE, Boolean.TRUE, - "authid", "remoteProcessName", new Integer(1967), new Integer(1970), _virtualHost.getConfigStore(), Boolean.FALSE); - } } diff --git a/java/broker/src/test/java/org/apache/qpid/server/txn/AsyncAutoCommitTransactionTest.java b/java/broker/src/test/java/org/apache/qpid/server/txn/AsyncAutoCommitTransactionTest.java index 1aa91fa98a..5c1012d50b 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/txn/AsyncAutoCommitTransactionTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/txn/AsyncAutoCommitTransactionTest.java @@ -82,7 +82,7 @@ public class AsyncAutoCommitTransactionTest extends QpidTestCase AsyncAutoCommitTransaction asyncAutoCommitTransaction = new AsyncAutoCommitTransaction(_messageStore, _futureRecorder); - asyncAutoCommitTransaction.enqueue(Collections.singletonList(_queue), _message, _postTransactionAction, System.currentTimeMillis()); + asyncAutoCommitTransaction.enqueue(Collections.singletonList(_queue), _message, _postTransactionAction); verify(_storeTransaction).enqueueMessage(_queue, _message); verify(_futureRecorder).recordFuture(_future, _postTransactionAction); diff --git a/java/broker/src/test/java/org/apache/qpid/server/txn/AutoCommitTransactionTest.java b/java/broker/src/test/java/org/apache/qpid/server/txn/AutoCommitTransactionTest.java index cd3fe3c473..06b8539eb1 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/txn/AutoCommitTransactionTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/txn/AutoCommitTransactionTest.java @@ -137,7 +137,7 @@ public class AutoCommitTransactionTest extends QpidTestCase _message = createTestMessage(false); _queues = createTestBaseQueues(new boolean[] {false, false, false}); - _transaction.enqueue(_queues, _message, _action, 0L); + _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()); @@ -157,7 +157,7 @@ public class AutoCommitTransactionTest extends QpidTestCase _message = createTestMessage(true); _queues = createTestBaseQueues(new boolean[] {false, false, false}); - _transaction.enqueue(_queues, _message, _action, 0L); + _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()); @@ -175,7 +175,7 @@ public class AutoCommitTransactionTest extends QpidTestCase _message = createTestMessage(true); _queues = createTestBaseQueues(new boolean[] {false, true, false, true}); - _transaction.enqueue(_queues, _message, _action, 0L); + _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()); @@ -198,7 +198,7 @@ public class AutoCommitTransactionTest extends QpidTestCase try { - _transaction.enqueue(_queues, _message, _action, 0L); + _transaction.enqueue(_queues, _message, _action); fail("Exception not thrown"); } catch (RuntimeException re) diff --git a/java/broker/src/test/java/org/apache/qpid/server/txn/LocalTransactionTest.java b/java/broker/src/test/java/org/apache/qpid/server/txn/LocalTransactionTest.java index 5992829f37..4904cbc6fb 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/txn/LocalTransactionTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/txn/LocalTransactionTest.java @@ -140,7 +140,7 @@ public class LocalTransactionTest extends QpidTestCase _message = createTestMessage(false); _queues = createTestBaseQueues(new boolean[] {false, false, false}); - _transaction.enqueue(_queues, _message, _action1, 0L); + _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()); @@ -156,7 +156,7 @@ public class LocalTransactionTest extends QpidTestCase _message = createTestMessage(true); _queues = createTestBaseQueues(new boolean[] {false, false, false}); - _transaction.enqueue(_queues, _message, _action1, 0L); + _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()); @@ -173,7 +173,7 @@ public class LocalTransactionTest extends QpidTestCase _message = createTestMessage(true); _queues = createTestBaseQueues(new boolean[] {false, true, false, true}); - _transaction.enqueue(_queues, _message, _action1, 0L); + _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()); @@ -196,7 +196,7 @@ public class LocalTransactionTest extends QpidTestCase try { - _transaction.enqueue(_queues, _message, _action1, 0L); + _transaction.enqueue(_queues, _message, _action1); fail("Exception not thrown"); } catch (RuntimeException re) @@ -217,7 +217,7 @@ public class LocalTransactionTest extends QpidTestCase { _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()); @@ -465,7 +465,6 @@ public class LocalTransactionTest extends QpidTestCase */ public void testRollbackWorkWithAdditionalPostAction() throws Exception { - _message = createTestMessage(true); _queue = createTestAMQQueue(true); @@ -482,6 +481,122 @@ public class LocalTransactionTest extends QpidTestCase 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>(); diff --git a/java/broker/src/test/java/org/apache/qpid/server/txn/MockServerMessage.java b/java/broker/src/test/java/org/apache/qpid/server/txn/MockServerMessage.java index f3b6cab626..aa5b555b3b 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/txn/MockServerMessage.java +++ b/java/broker/src/test/java/org/apache/qpid/server/txn/MockServerMessage.java @@ -22,7 +22,6 @@ package org.apache.qpid.server.txn; import org.apache.commons.lang.NotImplementedException; -import org.apache.qpid.server.configuration.SessionConfig; import org.apache.qpid.server.message.AMQMessageHeader; import org.apache.qpid.server.message.MessageReference; import org.apache.qpid.server.message.ServerMessage; @@ -68,11 +67,6 @@ class MockServerMessage implements ServerMessage throw new NotImplementedException(); } - public SessionConfig getSessionConfig() - { - throw new NotImplementedException(); - } - public String getRoutingKey() { throw new NotImplementedException(); diff --git a/java/broker/src/test/java/org/apache/qpid/server/util/BrokerTestHelper.java b/java/broker/src/test/java/org/apache/qpid/server/util/BrokerTestHelper.java new file mode 100644 index 0000000000..3be8927224 --- /dev/null +++ b/java/broker/src/test/java/org/apache/qpid/server/util/BrokerTestHelper.java @@ -0,0 +1,209 @@ +/* + * + * 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.framing.AMQShortString; +import org.apache.qpid.framing.BasicContentHeaderProperties; +import org.apache.qpid.framing.ContentHeaderBody; +import org.apache.qpid.framing.abstraction.MessagePublishInfo; +import org.apache.qpid.server.AMQChannel; +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.protocol.AMQProtocolSession; +import org.apache.qpid.server.protocol.InternalTestProtocolSession; +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.VirtualHost; +import org.apache.qpid.server.virtualhost.VirtualHostImpl; +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.SESSION_COUNT_LIMIT)).thenReturn(1); + when(broker.getAttribute(Broker.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(null)); + 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 + { + StatisticsGatherer statisticsGatherer = mock(StatisticsGatherer.class); + VirtualHost host = new VirtualHostImpl(virtualHostRegistry, statisticsGatherer, new SecurityManager(null), virtualHostConfiguration); + virtualHostRegistry.registerVirtualHost(host); + return host; + } + + public static VirtualHost createVirtualHost(VirtualHostConfiguration virtualHostConfiguration) throws Exception + { + return new VirtualHostImpl(null, mock(StatisticsGatherer.class), new SecurityManager(null), virtualHostConfiguration); + } + + 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 AMQChannel createChannel(int channelId, AMQProtocolSession session) throws AMQException + { + AMQChannel channel = new AMQChannel(session, channelId, session.getVirtualHost().getMessageStore()); + session.addChannel(channel); + return channel; + } + + public static AMQChannel createChannel(int channelId) throws Exception + { + InternalTestProtocolSession session = createSession(); + return createChannel(channelId, session); + } + + public static AMQChannel createChannel() throws Exception + { + return createChannel(1); + } + + public static InternalTestProtocolSession createSession() throws Exception + { + return createSession("test"); + } + + public static InternalTestProtocolSession createSession(String hostName) throws Exception + { + VirtualHost virtualHost = createVirtualHost(hostName); + return new InternalTestProtocolSession(virtualHost, createBrokerMock()); + } + + public static Exchange createExchange(String hostName) throws Exception + { + SecurityManager securityManager = new SecurityManager(null); + 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 void publishMessages(AMQChannel channel, int numberOfMessages, String queueName, String exchangeName) throws AMQException + { + AMQShortString rouningKey = new AMQShortString(queueName); + AMQShortString exchangeNameAsShortString = new AMQShortString(exchangeName); + MessagePublishInfo info = mock(MessagePublishInfo.class); + when(info.getExchange()).thenReturn(exchangeNameAsShortString); + when(info.getRoutingKey()).thenReturn(rouningKey); + + Exchange exchange = channel.getVirtualHost().getExchangeRegistry().getExchange(exchangeName); + for (int count = 0; count < numberOfMessages; count++) + { + channel.setPublishFrame(info, exchange); + + // Set the body size + ContentHeaderBody _headerBody = new ContentHeaderBody(); + _headerBody.setBodySize(0); + + // Set Minimum properties + BasicContentHeaderProperties properties = new BasicContentHeaderProperties(); + + properties.setExpiration(0L); + properties.setTimestamp(System.currentTimeMillis()); + + // Make Message Persistent + properties.setDeliveryMode((byte) 2); + + _headerBody.setProperties(properties); + + channel.publishContentHeader(_headerBody); + } + channel.sync(); + } + + public static SimpleAMQQueue createQueue(String queueName, VirtualHost virtualHost) throws AMQException + { + SimpleAMQQueue queue = (SimpleAMQQueue) AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), queueName, false, null, + false, false, virtualHost, Collections.<String, Object>emptyMap()); + virtualHost.getQueueRegistry().registerQueue(queue); + return queue; + } + + +} diff --git a/java/broker/src/test/java/org/apache/qpid/server/util/InternalBrokerBaseCase.java b/java/broker/src/test/java/org/apache/qpid/server/util/InternalBrokerBaseCase.java deleted file mode 100644 index d7a9078412..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/util/InternalBrokerBaseCase.java +++ /dev/null @@ -1,372 +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.commons.configuration.ConfigurationException; -import org.apache.commons.configuration.XMLConfiguration; - -import org.apache.qpid.AMQException; -import org.apache.qpid.common.AMQPFilterTypes; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.abstraction.MessagePublishInfo; -import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.configuration.ServerConfiguration; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.logging.SystemOutMessageLogger; -import org.apache.qpid.server.logging.actors.CurrentActor; -import org.apache.qpid.server.logging.actors.TestLogActor; -import org.apache.qpid.server.model.UUIDGenerator; -import org.apache.qpid.server.protocol.InternalTestProtocolSession; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.AMQQueueFactory; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.registry.IApplicationRegistry; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.TestableMemoryMessageStore; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.test.utils.QpidTestCase; - - -public class InternalBrokerBaseCase extends QpidTestCase -{ - private IApplicationRegistry _registry; - private MessageStore _messageStore; - private AMQChannel _channel; - private InternalTestProtocolSession _session; - private VirtualHost _virtualHost; - private AMQQueue _queue; - private AMQShortString QUEUE_NAME; - private ServerConfiguration _configuration; - private XMLConfiguration _configXml = new XMLConfiguration(); - private boolean _started = false; - - public void setUp() throws Exception - { - super.setUp(); - - _configXml.addProperty("virtualhosts.virtualhost.name", "test"); - _configXml.addProperty("virtualhosts.virtualhost.test.store.class", TestableMemoryMessageStore.class.getName()); - - _configXml.addProperty("virtualhosts.virtualhost(-1).name", getName()); - _configXml.addProperty("virtualhosts.virtualhost(-1)."+getName()+".store.class", TestableMemoryMessageStore.class.getName()); - - createBroker(); - } - - protected void createBroker() throws Exception - { - _started = true; - CurrentActor.set(new TestLogActor(new SystemOutMessageLogger())); - - _configuration = new ServerConfiguration(_configXml); - - configure(); - - _registry = createApplicationRegistry(); - ApplicationRegistry.initialise(_registry); - _registry.getVirtualHostRegistry().setDefaultVirtualHostName(getName()); - _virtualHost = _registry.getVirtualHostRegistry().getVirtualHost(getName()); - - QUEUE_NAME = new AMQShortString("test"); - // Create a queue on the test Vhost.. this will aid in diagnosing duff tests - // as the ExpiredMessage Task will log with the test Name. - _queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), QUEUE_NAME.asString(), false, "testowner", - false, false, _virtualHost, null); - - Exchange defaultExchange = _virtualHost.getExchangeRegistry().getDefaultExchange(); - _virtualHost.getBindingFactory().addBinding(QUEUE_NAME.toString(), _queue, defaultExchange, null); - - _virtualHost = _registry.getVirtualHostRegistry().getVirtualHost("test"); - _messageStore = _virtualHost.getMessageStore(); - - _queue = AMQQueueFactory.createAMQQueueImpl(UUIDGenerator.generateRandomUUID(), getName(), false, "testowner", - false, false, _virtualHost, null); - - _virtualHost.getQueueRegistry().registerQueue(_queue); - - defaultExchange = _virtualHost.getExchangeRegistry().getDefaultExchange(); - - _virtualHost.getBindingFactory().addBinding(getName(), _queue, defaultExchange, null); - - _session = new InternalTestProtocolSession(_virtualHost); - CurrentActor.set(_session.getLogActor()); - - _channel = new AMQChannel(_session, 1, _messageStore); - - _session.addChannel(_channel); - } - - protected IApplicationRegistry createApplicationRegistry() throws ConfigurationException - { - return new TestApplicationRegistry(_configuration); - } - - protected void configure() - { - // Allow other tests to override configuration - } - - protected void stopBroker() - { - try - { - //Remove the ProtocolSession Actor added during createBroker - CurrentActor.remove(); - } - finally - { - ApplicationRegistry.remove(); - _started = false; - } - } - - - public void tearDown() throws Exception - { - try - { - if (_started) - { - stopBroker(); - } - } - finally - { - super.tearDown(); - // Purge Any erroneously added actors - CurrentActor.removeAll(); - } - } - - protected void checkStoreContents(int messageCount) - { - assertEquals("Message header count incorrect in the MetaDataMap", messageCount, ((TestableMemoryMessageStore) _messageStore).getMessageCount()); - - //The above publish message is sufficiently small not to fit in the header so no Body is required. - //assertEquals("Message body count incorrect in the ContentBodyMap", messageCount, ((TestableMemoryMessageStore) _messageStore).getContentBodyMap().size()); - } - - protected AMQShortString subscribe(InternalTestProtocolSession session, AMQChannel channel, AMQQueue queue) - { - try - { - return channel.subscribeToQueue(null, queue, true, null, false, true); - } - catch (AMQException e) - { - e.printStackTrace(); - fail(e.getMessage()); - } - - //Keep the compiler happy - return null; - } - - protected AMQShortString browse(AMQChannel channel, AMQQueue queue) - { - try - { - FieldTable filters = new FieldTable(); - filters.put(AMQPFilterTypes.NO_CONSUME.getValue(), true); - - return channel.subscribeToQueue(null, queue, true, filters, false, true); - } - catch (AMQException e) - { - e.printStackTrace(); - fail(e.getMessage()); - } - - //Keep the compiler happy - return null; - } - - public void publishMessages(InternalTestProtocolSession session, AMQChannel channel, int messages) throws AMQException - { - MessagePublishInfo info = new MessagePublishInfo() - { - public AMQShortString getExchange() - { - return ExchangeDefaults.DEFAULT_EXCHANGE_NAME; - } - - public void setExchange(AMQShortString exchange) - { - - } - - public boolean isImmediate() - { - return false; - } - - public boolean isMandatory() - { - return false; - } - - public AMQShortString getRoutingKey() - { - return new AMQShortString(getName()); - } - }; - - for (int count = 0; count < messages; count++) - { - channel.setPublishFrame(info, _virtualHost.getExchangeRegistry().getExchange(info.getExchange())); - - //Set the body size - ContentHeaderBody _headerBody = new ContentHeaderBody(); - _headerBody.setBodySize(0); - - //Set Minimum properties - BasicContentHeaderProperties properties = new BasicContentHeaderProperties(); - - properties.setExpiration(0L); - properties.setTimestamp(System.currentTimeMillis()); - - //Make Message Persistent - properties.setDeliveryMode((byte) 2); - - _headerBody.setProperties(properties); - - channel.publishContentHeader(_headerBody); - } - channel.sync(); - } - - public void acknowledge(AMQChannel channel, long deliveryTag) - { - try - { - channel.acknowledgeMessage(deliveryTag, false); - } - catch (AMQException e) - { - e.printStackTrace(); - fail(e.getMessage()); - } - } - - public IApplicationRegistry getRegistry() - { - return _registry; - } - - public void setRegistry(IApplicationRegistry registry) - { - _registry = registry; - } - - public MessageStore getMessageStore() - { - return _messageStore; - } - - public void setMessageStore(MessageStore messageStore) - { - _messageStore = messageStore; - } - - public AMQChannel getChannel() - { - return _channel; - } - - public void setChannel(AMQChannel channel) - { - _channel = channel; - } - - public InternalTestProtocolSession getSession() - { - return _session; - } - - public void setSession(InternalTestProtocolSession session) - { - _session = session; - } - - public VirtualHost getVirtualHost() - { - return _virtualHost; - } - - public void setVirtualHost(VirtualHost virtualHost) - { - _virtualHost = virtualHost; - } - - public AMQQueue getQueue() - { - return _queue; - } - - public void setQueue(AMQQueue queue) - { - _queue = queue; - } - - public AMQShortString getQUEUE_NAME() - { - return QUEUE_NAME; - } - - public void setQUEUE_NAME(AMQShortString QUEUE_NAME) - { - this.QUEUE_NAME = QUEUE_NAME; - } - - public ServerConfiguration getConfiguration() - { - return _configuration; - } - - public void setConfiguration(ServerConfiguration configuration) - { - _configuration = configuration; - } - - public XMLConfiguration getConfigXml() - { - return _configXml; - } - - public void setConfigXml(XMLConfiguration configXml) - { - _configXml = configXml; - } - - public boolean isStarted() - { - return _started; - } - - public void setStarted(boolean started) - { - _started = started; - } -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/util/TestApplicationRegistry.java b/java/broker/src/test/java/org/apache/qpid/server/util/TestApplicationRegistry.java deleted file mode 100644 index a64ab620ab..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/util/TestApplicationRegistry.java +++ /dev/null @@ -1,121 +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.net.SocketAddress; -import java.util.Collections; -import java.util.Map; -import org.apache.commons.configuration.ConfigurationException; - -import org.apache.qpid.server.configuration.ServerConfiguration; -import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; -import org.apache.qpid.server.logging.NullRootMessageLogger; -import org.apache.qpid.server.logging.actors.BrokerActor; -import org.apache.qpid.server.logging.actors.CurrentActor; -import org.apache.qpid.server.logging.actors.GenericActor; -import org.apache.qpid.server.plugins.PluginManager; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.security.auth.database.PropertiesPrincipalDatabase; -import org.apache.qpid.server.security.auth.manager.AuthenticationManager; -import org.apache.qpid.server.security.auth.manager.IAuthenticationManagerRegistry; -import org.apache.qpid.server.security.auth.manager.PrincipalDatabaseAuthenticationManager; - -import java.util.Properties; - -public class TestApplicationRegistry extends ApplicationRegistry -{ - - public TestApplicationRegistry(ServerConfiguration config) throws ConfigurationException - { - super(config); - } - - @Override - public void initialise() throws Exception - { - CurrentActor.setDefault(new BrokerActor(new NullRootMessageLogger())); - GenericActor.setDefaultMessageLogger(new NullRootMessageLogger()); - super.initialise(); - } - - @Override - protected IAuthenticationManagerRegistry createAuthenticationManagerRegistry( - ServerConfiguration _configuration, PluginManager _pluginManager) - throws ConfigurationException - { - final Properties users = new Properties(); - users.put("guest","guest"); - users.put("admin","admin"); - - final PropertiesPrincipalDatabase ppd = new PropertiesPrincipalDatabase(users); - - final AuthenticationManager pdam = new PrincipalDatabaseAuthenticationManager() - { - - /** - * @see org.apache.qpid.server.security.auth.manager.PrincipalDatabaseAuthenticationManager#configure(org.apache.qpid.server.configuration.plugins.ConfigurationPlugin) - */ - @Override - public void configure(ConfigurationPlugin config) throws ConfigurationException - { - // We don't pass configuration to this test instance. - } - - @Override - public void initialise() - { - setPrincipalDatabase(ppd); - - super.initialise(); - } - }; - pdam.initialise(); - - return new IAuthenticationManagerRegistry() - { - @Override - public void close() - { - pdam.close(); - } - - @Override - public AuthenticationManager getAuthenticationManager( - SocketAddress address) - { - return pdam; - } - - @Override - public Map<String, AuthenticationManager> getAvailableAuthenticationManagers() - { - return Collections.singletonMap(pdam.getClass().getName(), pdam); - } - - @Override - public void addRegistryChangeListener(RegistryChangeListener listener) - { - } - }; - } -} - - diff --git a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/MockVirtualHost.java b/java/broker/src/test/java/org/apache/qpid/server/virtualhost/MockVirtualHost.java index 290c465785..1d99d99820 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/MockVirtualHost.java +++ b/java/broker/src/test/java/org/apache/qpid/server/virtualhost/MockVirtualHost.java @@ -22,26 +22,18 @@ package org.apache.qpid.server.virtualhost; import java.util.concurrent.ScheduledFuture; import org.apache.qpid.server.binding.BindingFactory; -import org.apache.qpid.server.configuration.BrokerConfig; -import org.apache.qpid.server.configuration.ConfigStore; -import org.apache.qpid.server.configuration.ConfiguredObject; -import org.apache.qpid.server.configuration.VirtualHostConfig; -import org.apache.qpid.server.configuration.VirtualHostConfigType; import org.apache.qpid.server.configuration.VirtualHostConfiguration; import org.apache.qpid.server.connection.IConnectionRegistry; import org.apache.qpid.server.exchange.ExchangeFactory; import org.apache.qpid.server.exchange.ExchangeRegistry; -import org.apache.qpid.server.federation.BrokerLink; import org.apache.qpid.server.protocol.v1_0.LinkRegistry; import org.apache.qpid.server.queue.QueueRegistry; -import org.apache.qpid.server.registry.IApplicationRegistry; 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.MessageStore; import org.apache.qpid.server.txn.DtxRegistry; -import java.util.Map; import java.util.UUID; public class MockVirtualHost implements VirtualHost @@ -58,19 +50,8 @@ public class MockVirtualHost implements VirtualHost } - public void createBrokerConnection(String transport, String host, int port, - String vhost, boolean durable, String authMechanism, - String username, String password) - { - - } - - public BrokerLink createBrokerConnection(final UUID id, final long createTime, final Map<String, String> arguments) - { - return null; - } - - public IApplicationRegistry getApplicationRegistry() + @Override + public VirtualHostRegistry getVirtualHostRegistry() { return null; } @@ -85,16 +66,6 @@ public class MockVirtualHost implements VirtualHost return null; } - public UUID getBrokerId() - { - return null; - } - - public ConfigStore getConfigStore() - { - return null; - } - public DtxRegistry getDtxRegistry() { return null; @@ -160,12 +131,6 @@ public class MockVirtualHost implements VirtualHost return null; } - - public void removeBrokerConnection(BrokerLink brokerLink) - { - - } - public LinkRegistry getLinkRegistry(String remoteContainerId) { return null; @@ -186,25 +151,6 @@ public class MockVirtualHost implements VirtualHost } - public BrokerConfig getBroker() - { - return null; - } - - public String getFederationTag() - { - return null; - } - - public void setBroker(BrokerConfig brokerConfig) - { - - } - - public VirtualHostConfigType getConfigType() - { - return null; - } public long getCreateTime() { @@ -216,17 +162,6 @@ public class MockVirtualHost implements VirtualHost return null; } - @Override - public UUID getQMFId() - { - return null; - } - - public ConfiguredObject<VirtualHostConfigType, VirtualHostConfig> getParent() - { - return null; - } - public boolean isDurable() { return false; diff --git a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/VirtualHostImplTest.java b/java/broker/src/test/java/org/apache/qpid/server/virtualhost/VirtualHostImplTest.java index b8ba76e43d..559a7f8aaf 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/VirtualHostImplTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/virtualhost/VirtualHostImplTest.java @@ -20,15 +20,21 @@ */ package org.apache.qpid.server.virtualhost; +import static org.mockito.Mockito.mock; + +import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.configuration.XMLConfiguration; +import org.apache.commons.configuration.PropertiesConfiguration; + +import org.apache.qpid.server.configuration.VirtualHostConfiguration; -import org.apache.qpid.server.configuration.ServerConfiguration; 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.registry.ApplicationRegistry; +import org.apache.qpid.server.security.SecurityManager; +import org.apache.qpid.server.stats.StatisticsGatherer; import org.apache.qpid.server.store.MemoryMessageStore; -import org.apache.qpid.server.util.TestApplicationRegistry; +import org.apache.qpid.server.util.BrokerTestHelper; import org.apache.qpid.test.utils.QpidTestCase; import java.io.BufferedWriter; @@ -38,15 +44,31 @@ import java.io.IOException; public class VirtualHostImplTest extends QpidTestCase { - private ServerConfiguration _configuration; - private ApplicationRegistry _registry; + private VirtualHostRegistry _virtualHostRegistry; + + @Override + public void setUp() throws Exception + { + super.setUp(); + BrokerTestHelper.setUp(); + } @Override public void tearDown() throws Exception { - super.tearDown(); + try + { + if (_virtualHostRegistry != null) + { + _virtualHostRegistry.close(); + } + } + finally + { + BrokerTestHelper.tearDown(); + super.tearDown(); + } - ApplicationRegistry.remove(); } /** @@ -74,17 +96,23 @@ public class VirtualHostImplTest extends QpidTestCase */ public void testSpecifyingCustomBindingForDefaultExchangeThrowsException() throws Exception { - File config = writeConfigFile(getName(), getName(), null, false, new String[]{"custom-binding"}); + final String queueName = getName(); + final String customBinding = "custom-binding"; + File config = writeConfigFile(queueName, queueName, null, false, new String[]{customBinding}); try { - createVirtualHost(getName(), config); + createVirtualHost(queueName, config); fail("virtualhost creation should have failed due to illegal configuration"); } catch (RuntimeException e) { + assertNotNull(e.getCause()); + assertEquals(ConfigurationException.class, e.getCause().getClass()); - //expected + + Throwable configException = e.getCause(); + assertEquals("Illegal attempt to bind queue '" + queueName + "' to the default exchange with a key other than the queue name: " + customBinding, configException.getMessage()); } } @@ -96,6 +124,14 @@ public class VirtualHostImplTest extends QpidTestCase 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]); @@ -107,22 +143,39 @@ public class VirtualHostImplTest extends QpidTestCase 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 { - File config = writeConfigFile(getName(), getName(), "made-up-exchange", true, new String[0]); + final String queueName = getName(); + final String exchangeName = "made-up-exchange"; + File config = writeConfigFile(queueName, queueName, exchangeName, true, new String[0]); try { - createVirtualHost(getName(), config); + createVirtualHost(queueName, config); fail("virtualhost creation should have failed due to illegal configuration"); } catch (RuntimeException e) { + assertNotNull(e.getCause()); + assertEquals(ConfigurationException.class, e.getCause().getClass()); - //expected + + Throwable configException = e.getCause(); + assertEquals("Attempt to bind queue '" + queueName + "' to unknown exchange:" + exchangeName, configException.getMessage()); } } @@ -154,12 +207,14 @@ public class VirtualHostImplTest extends QpidTestCase private VirtualHost createVirtualHost(String vhostName, File config) throws Exception { - _configuration = new ServerConfiguration(new XMLConfiguration(config)); + Broker broker = BrokerTestHelper.createBrokerMock(); + _virtualHostRegistry = broker.getVirtualHostRegistry(); - _registry = new TestApplicationRegistry(_configuration); - ApplicationRegistry.initialise(_registry); + VirtualHostConfiguration configuration = new VirtualHostConfiguration(vhostName, config, broker); + VirtualHost host = new VirtualHostImpl(_virtualHostRegistry, mock(StatisticsGatherer.class), new SecurityManager(null), configuration); + _virtualHostRegistry.registerVirtualHost(host); - return _registry.getVirtualHostRegistry().getVirtualHost(vhostName); + return host; } /** @@ -184,7 +239,6 @@ public class VirtualHostImplTest extends QpidTestCase BufferedWriter writer = new BufferedWriter(fstream); //extra outer tag to please Commons Configuration - writer.write("<configuration>"); writer.write("<virtualhosts>"); writer.write(" <default>" + vhostName + "</default>"); @@ -222,8 +276,6 @@ public class VirtualHostImplTest extends QpidTestCase writer.write(" </virtualhost>"); writer.write("</virtualhosts>"); - writer.write("</configuration>"); - writer.flush(); writer.close(); } @@ -234,4 +286,17 @@ public class VirtualHostImplTest extends QpidTestCase return tmpFile; } + + private VirtualHost createVirtualHostUsingStoreType(String virtualHostName) throws ConfigurationException, Exception + { + Broker broker = BrokerTestHelper.createBrokerMock(); + _virtualHostRegistry = broker.getVirtualHostRegistry(); + + Configuration config = new PropertiesConfiguration(); + config.setProperty("store.type", MemoryMessageStore.TYPE); + VirtualHostConfiguration configuration = new VirtualHostConfiguration(virtualHostName, config, broker); + VirtualHost host = new VirtualHostImpl(_virtualHostRegistry, mock(StatisticsGatherer.class), new SecurityManager(null), configuration); + _virtualHostRegistry.registerVirtualHost(host); + return host; + } } diff --git a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionConfigurationTest.java b/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionConfigurationTest.java deleted file mode 100644 index e2375c579b..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionConfigurationTest.java +++ /dev/null @@ -1,347 +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.plugins; - -import org.apache.commons.configuration.CompositeConfiguration; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.configuration.XMLConfiguration; - -import org.apache.qpid.server.configuration.plugins.SlowConsumerDetectionConfiguration; -import org.apache.qpid.server.util.InternalBrokerBaseCase; - -import java.util.concurrent.TimeUnit; - -/** - * Provide Unit Test coverage of the virtualhost SlowConsumer Configuration - * This is what controls how often the plugin will execute - */ -public class SlowConsumerDetectionConfigurationTest extends InternalBrokerBaseCase -{ - - /** - * Default Testing: - * - * Provide a fully complete and valid configuration specifying 'delay' and - * 'timeunit' and ensure that it is correctly processed. - * - * Ensure no exceptions are thrown and that we get the same values back that - * were put into the configuration. - */ - public void testConfigLoadingValidConfig() - { - SlowConsumerDetectionConfiguration config = new SlowConsumerDetectionConfiguration(); - - XMLConfiguration xmlconfig = new XMLConfiguration(); - - long DELAY=10; - String TIMEUNIT=TimeUnit.MICROSECONDS.toString(); - xmlconfig.addProperty("delay", String.valueOf(DELAY)); - xmlconfig.addProperty("timeunit", TIMEUNIT); - - // Create a CompositeConfiguration as this is what the broker uses - CompositeConfiguration composite = new CompositeConfiguration(); - composite.addConfiguration(xmlconfig); - - try - { - config.setConfiguration("", composite); - } - catch (ConfigurationException e) - { - e.printStackTrace(); - fail(e.getMessage()); - } - - assertEquals("Delay not correctly returned.", DELAY, config.getDelay()); - assertEquals("TimeUnit not correctly returned.", - TIMEUNIT, String.valueOf(config.getTimeUnit())); - } - - /** - * Default Testing: - * - * Test Missing TimeUnit value gets default. - * - * The TimeUnit value is optional and default to SECONDS. - * - * Test that if we do not specify a TimeUnit then we correctly get seconds. - * - * Also verify that relying on the default does not impact the setting of - * the 'delay' value. - * - */ - public void testConfigLoadingMissingTimeUnitDefaults() - { - SlowConsumerDetectionConfiguration config = new SlowConsumerDetectionConfiguration(); - - XMLConfiguration xmlconfig = new XMLConfiguration(); - - long DELAY=10; - xmlconfig.addProperty("delay", String.valueOf(DELAY)); - - // Create a CompositeConfiguration as this is what the broker uses - CompositeConfiguration composite = new CompositeConfiguration(); - composite.addConfiguration(xmlconfig); - try - { - config.setConfiguration("", composite); - } - catch (ConfigurationException e) - { - e.printStackTrace(); - fail(e.getMessage()); - } - - assertEquals("Delay not correctly returned.", DELAY, config.getDelay()); - assertEquals("Default TimeUnit incorrect", TimeUnit.SECONDS, config.getTimeUnit()); - } - - /** - * Input Testing: - * - * TimeUnit parsing requires the String value be in UpperCase. - * Ensure we can handle when the user doesn't know this. - * - * Same test as 'testConfigLoadingValidConfig' but checking that - * the timeunit field is not case sensitive. - * i.e. the toUpper is being correctly applied. - */ - public void testConfigLoadingValidConfigStrangeTimeUnit() - { - SlowConsumerDetectionConfiguration config = new SlowConsumerDetectionConfiguration(); - - XMLConfiguration xmlconfig = new XMLConfiguration(); - - long DELAY=10; - - xmlconfig.addProperty("delay", DELAY); - xmlconfig.addProperty("timeunit", "MiCrOsEcOnDs"); - - // Create a CompositeConfiguration as this is what the broker uses - CompositeConfiguration composite = new CompositeConfiguration(); - composite.addConfiguration(xmlconfig); - - try - { - config.setConfiguration("", composite); - } - catch (ConfigurationException e) - { - e.printStackTrace(); - fail(e.getMessage()); - } - - assertEquals("Delay not correctly returned.", DELAY, config.getDelay()); - assertEquals("TimeUnit not correctly returned.", - TimeUnit.MICROSECONDS.toString(), String.valueOf(config.getTimeUnit())); - - } - - /** - * Failure Testing: - * - * Test that delay must be long not a string value. - * Provide a delay as a written value not a long. 'ten'. - * - * This should throw a configuration exception which is being trapped and - * verified to be the right exception, a NumberFormatException. - * - */ - public void testConfigLoadingInValidDelayString() - { - SlowConsumerDetectionConfiguration config = new SlowConsumerDetectionConfiguration(); - - XMLConfiguration xmlconfig = new XMLConfiguration(); - - xmlconfig.addProperty("delay", "ten"); - xmlconfig.addProperty("timeunit", TimeUnit.MICROSECONDS.toString()); - - // Create a CompositeConfiguration as this is what the broker uses - CompositeConfiguration composite = new CompositeConfiguration(); - composite.addConfiguration(xmlconfig); - - try - { - config.setConfiguration("", composite); - fail("Configuration should fail to validate"); - } - catch (ConfigurationException e) - { - Throwable cause = e.getCause(); - - assertEquals("Cause not correct", NumberFormatException.class, cause.getClass()); - } - } - - /** - * Failure Testing: - * - * Test that negative delays are invalid. - * - * Delay must be a positive value as negative delay means doesn't make sense. - * - * Configuration exception with a useful message should be thrown here. - * - */ - public void testConfigLoadingInValidDelayNegative() - { - SlowConsumerDetectionConfiguration config = new SlowConsumerDetectionConfiguration(); - - XMLConfiguration xmlconfig = new XMLConfiguration(); - - xmlconfig.addProperty("delay", "-10"); - xmlconfig.addProperty("timeunit", TimeUnit.MICROSECONDS.toString()); - - // Create a CompositeConfiguration as this is what the broker uses - CompositeConfiguration composite = new CompositeConfiguration(); - composite.addConfiguration(xmlconfig); - - try - { - config.setConfiguration("", composite); - fail("Configuration should fail to validate"); - } - catch (ConfigurationException e) - { - Throwable cause = e.getCause(); - - assertNotNull("Configuration Exception must not be null.", cause); - assertEquals("Cause not correct", - ConfigurationException.class, cause.getClass()); - assertEquals("Incorrect message.", - "SlowConsumerDetectionConfiguration: 'delay' must be a Positive Long value.", - cause.getMessage()); - } - } - - /** - * Failure Testing: - * - * Test that delay cannot be 0. - * - * A zero delay means run constantly. This is not how VirtualHostTasks - * are designed to be run so we dis-allow the use of 0 delay. - * - * Same test as 'testConfigLoadingInValidDelayNegative' but with a 0 value. - * - */ - public void testConfigLoadingInValidDelayZero() - { - SlowConsumerDetectionConfiguration config = new SlowConsumerDetectionConfiguration(); - - XMLConfiguration xmlconfig = new XMLConfiguration(); - - xmlconfig.addProperty("delay", "0"); - xmlconfig.addProperty("timeunit", TimeUnit.MICROSECONDS.toString()); - - // Create a CompositeConfiguration as this is what the broker uses - CompositeConfiguration composite = new CompositeConfiguration(); - composite.addConfiguration(xmlconfig); - - try - { - config.setConfiguration("", composite); - fail("Configuration should fail to validate"); - } - catch (ConfigurationException e) - { - Throwable cause = e.getCause(); - - assertNotNull("Configuration Exception must not be null.", cause); - assertEquals("Cause not correct", - ConfigurationException.class, cause.getClass()); - assertEquals("Incorrect message.", - "SlowConsumerDetectionConfiguration: 'delay' must be a Positive Long value.", - cause.getMessage()); - } - } - - /** - * Failure Testing: - * - * Test that missing delay fails. - * If we have no delay then we do not pick a default. So a Configuration - * Exception is thrown. - * - * */ - public void testConfigLoadingInValidMissingDelay() - { - SlowConsumerDetectionConfiguration config = new SlowConsumerDetectionConfiguration(); - - XMLConfiguration xmlconfig = new XMLConfiguration(); - - xmlconfig.addProperty("timeunit", TimeUnit.SECONDS.toString()); - - // Create a CompositeConfiguration as this is what the broker uses - CompositeConfiguration composite = new CompositeConfiguration(); - composite.addConfiguration(xmlconfig); - try - { - config.setConfiguration("", composite); - fail("Configuration should fail to validate"); - } - catch (ConfigurationException e) - { - assertEquals("Incorrect message.", "SlowConsumerDetectionConfiguration: unable to configure invalid delay:null", e.getMessage()); - } - } - - /** - * Failure Testing: - * - * Test that erroneous TimeUnit fails. - * - * Valid TimeUnit values vary based on the JVM version i.e. 1.6 added HOURS/DAYS etc. - * - * We don't test the values for TimeUnit are accepted other than MILLISECONDS in the - * positive testing at the start. - * - * Here we ensure that an erroneous for TimeUnit correctly throws an exception. - * - * We test with 'foo', which will never be a TimeUnit - * - */ - public void testConfigLoadingInValidTimeUnit() - { - SlowConsumerDetectionConfiguration config = new SlowConsumerDetectionConfiguration(); - - String TIMEUNIT = "foo"; - XMLConfiguration xmlconfig = new XMLConfiguration(); - - xmlconfig.addProperty("delay", "10"); - xmlconfig.addProperty("timeunit", TIMEUNIT); - - // Create a CompositeConfiguration as this is what the broker uses - CompositeConfiguration composite = new CompositeConfiguration(); - composite.addConfiguration(xmlconfig); - try - { - config.setConfiguration("", composite); - fail("Configuration should fail to validate"); - } - catch (ConfigurationException e) - { - assertEquals("Incorrect message.", "Unable to configure Slow Consumer Detection invalid TimeUnit:" + TIMEUNIT, e.getMessage()); - } - } - - -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionPolicyConfigurationTest.java b/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionPolicyConfigurationTest.java deleted file mode 100644 index ea07632873..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionPolicyConfigurationTest.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.virtualhost.plugins; - -import org.apache.commons.configuration.CompositeConfiguration; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.configuration.XMLConfiguration; - -import org.apache.qpid.server.configuration.plugins.SlowConsumerDetectionPolicyConfiguration; -import org.apache.qpid.server.util.InternalBrokerBaseCase; - -/** - * Test class to ensure that the policy configuration can be processed. - */ -public class SlowConsumerDetectionPolicyConfigurationTest extends InternalBrokerBaseCase -{ - - /** - * Input Testing: - * - * Test that a given String can be set and retrieved through the configuration - * - * No validation is being performed to ensure that the policy exists. Only - * that a value can be set for the policy. - * - */ - public void testConfigLoadingValidConfig() - { - SlowConsumerDetectionPolicyConfiguration config = new SlowConsumerDetectionPolicyConfiguration(); - - XMLConfiguration xmlconfig = new XMLConfiguration(); - - String policyName = "TestPolicy"; - xmlconfig.addProperty("name", policyName); - - // Create a CompositeConfiguration as this is what the broker uses - CompositeConfiguration composite = new CompositeConfiguration(); - composite.addConfiguration(xmlconfig); - - try - { - config.setConfiguration("", composite); - } - catch (ConfigurationException e) - { - e.printStackTrace(); - fail(e.getMessage()); - } - - assertEquals("Policy name not retrieved as expected.", - policyName, config.getPolicyName()); - } - - /** - * Failure Testing: - * - * Test that providing a configuration section without the 'name' field - * causes an exception to be thrown. - * - * An empty configuration is provided and the thrown exception message - * is checked to confirm the right reason. - * - */ - public void testConfigLoadingInValidConfig() - { - SlowConsumerDetectionPolicyConfiguration config = new SlowConsumerDetectionPolicyConfiguration(); - - XMLConfiguration xmlconfig = new XMLConfiguration(); - - - // Create a CompositeConfiguration as this is what the broker uses - CompositeConfiguration composite = new CompositeConfiguration(); - composite.addConfiguration(xmlconfig); - - try - { - config.setConfiguration("", composite); - fail("Config is invalid so won't validate."); - } - catch (ConfigurationException e) - { - e.printStackTrace(); - assertEquals("Exception message not as expected.", "No Slow consumer policy defined.", e.getMessage()); - } - } - -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionQueueConfigurationTest.java b/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionQueueConfigurationTest.java deleted file mode 100644 index 96e524acf2..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionQueueConfigurationTest.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.virtualhost.plugins; - -import org.apache.commons.configuration.CompositeConfiguration; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.configuration.XMLConfiguration; - -import org.apache.qpid.server.configuration.plugins.SlowConsumerDetectionQueueConfiguration; -import org.apache.qpid.server.util.InternalBrokerBaseCase; - -/** - * Unit test the QueueConfiguration processing. - * - * This is slightly awkward as the {@link SlowConsumerDetectionQueueConfiguration} - * requries that a policy be available. - * <p> - * So all the Valid test much catch the ensuing {@link ConfigurationException} and - * validate that the error is due to a lack of a valid policy. - */ -public class SlowConsumerDetectionQueueConfigurationTest extends InternalBrokerBaseCase -{ - /** - * Test a fully loaded configuration file. - * - * It is not an error to have all control values specified. - * <p> - * Here we need to catch the {@link ConfigurationException} that ensues due to lack - * of a policy plugin. - */ - public void testConfigLoadingValidConfig() - { - SlowConsumerDetectionQueueConfiguration config = new SlowConsumerDetectionQueueConfiguration(); - - XMLConfiguration xmlconfig = new XMLConfiguration(); - - xmlconfig.addProperty("messageAge", "60000"); - xmlconfig.addProperty("depth", "1024"); - xmlconfig.addProperty("messageCount", "10"); - - // Create a CompositeConfiguration as this is what the broker uses - CompositeConfiguration composite = new CompositeConfiguration(); - composite.addConfiguration(xmlconfig); - - try - { - config.setConfiguration("", composite); - fail("No Policies are avaialbe to load in a unit test"); - } - catch (ConfigurationException e) - { - assertTrue("Exception message incorrect, was: " + e.getMessage(), - e.getMessage().startsWith("No Slow Consumer Policy specified. Known Policies:[")); - } - } - - /** - * When we do not specify any control value then a {@link ConfigurationException} - * must be thrown to remind us. - */ - public void testConfigLoadingMissingConfig() - { - SlowConsumerDetectionQueueConfiguration config = new SlowConsumerDetectionQueueConfiguration(); - - XMLConfiguration xmlconfig = new XMLConfiguration(); - - // Create a CompositeConfiguration as this is what the broker uses - CompositeConfiguration composite = new CompositeConfiguration(); - composite.addConfiguration(xmlconfig); - - try - { - config.setConfiguration("", composite); - fail("No Policies are avaialbe to load in a unit test"); - } - catch (ConfigurationException e) - { - - assertEquals("At least one configuration property('messageAge','depth'" + - " or 'messageCount') must be specified.", e.getMessage()); - } - } - - /** - * Setting messageAge on its own is enough to have a valid configuration - * - * Here we need to catch the {@link ConfigurationException} that ensues due to lack - * of a policy plugin. - */ - public void testConfigLoadingMessageAgeOk() - { - SlowConsumerDetectionQueueConfiguration config = new SlowConsumerDetectionQueueConfiguration(); - - XMLConfiguration xmlconfig = new XMLConfiguration(); - xmlconfig.addProperty("messageAge", "60000"); - - // Create a CompositeConfiguration as this is what the broker uses - CompositeConfiguration composite = new CompositeConfiguration(); - composite.addConfiguration(xmlconfig); - - try - { - config.setConfiguration("", composite); - fail("No Policies are avaialbe to load in a unit test"); - } - catch (ConfigurationException e) - { - assertTrue("Exception message incorrect, was: " + e.getMessage(), - e.getMessage().startsWith("No Slow Consumer Policy specified. Known Policies:[")); - } - } - - /** - * Setting depth on its own is enough to have a valid configuration. - * - * Here we need to catch the {@link ConfigurationException} that ensues due to lack - * of a policy plugin. - */ - public void testConfigLoadingDepthOk() - { - SlowConsumerDetectionQueueConfiguration config = new SlowConsumerDetectionQueueConfiguration(); - - XMLConfiguration xmlconfig = new XMLConfiguration(); - xmlconfig.addProperty("depth", "1024"); - - // Create a CompositeConfiguration as this is what the broker uses - CompositeConfiguration composite = new CompositeConfiguration(); - composite.addConfiguration(xmlconfig); - - try - { - config.setConfiguration("", composite); - fail("No Policies are avaialbe to load in a unit test"); - } - catch (ConfigurationException e) - { - assertTrue("Exception message incorrect, was: " + e.getMessage(), - e.getMessage().startsWith("No Slow Consumer Policy specified. Known Policies:[")); - } - } - - /** - * Setting messageCount on its own is enough to have a valid configuration. - * - * Here we need to catch the {@link ConfigurationException} that ensues due to lack - * of a policy plugin. - */ - public void testConfigLoadingMessageCountOk() - { - SlowConsumerDetectionQueueConfiguration config = new SlowConsumerDetectionQueueConfiguration(); - - XMLConfiguration xmlconfig = new XMLConfiguration(); - xmlconfig.addProperty("messageCount", "10"); - - // Create a CompositeConfiguration as this is what the broker uses - CompositeConfiguration composite = new CompositeConfiguration(); - composite.addConfiguration(xmlconfig); - - try - { - config.setConfiguration("", composite); - fail("No Policies are avaialbe to load in a unit test"); - } - catch (ConfigurationException e) - { - assertTrue("Exception message incorrect, was: " + e.getMessage(), - e.getMessage().startsWith("No Slow Consumer Policy specified. Known Policies:[")); - } - } -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyConfigurationTest.java b/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyConfigurationTest.java deleted file mode 100644 index f034d05c37..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyConfigurationTest.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.virtualhost.plugins.policies; - -import org.apache.commons.configuration.CompositeConfiguration; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.configuration.XMLConfiguration; - -import org.apache.qpid.server.util.InternalBrokerBaseCase; - -/** - * Test to ensure TopicDelete Policy configuration can be loaded. - */ -public class TopicDeletePolicyConfigurationTest extends InternalBrokerBaseCase -{ - /** - * Test without any configuration being provided that the - * deletePersistent option is disabled. - */ - public void testNoConfigNoDeletePersistent() - { - TopicDeletePolicyConfiguration config = new TopicDeletePolicyConfiguration(); - - assertFalse("TopicDelete Configuration with no config should not delete persistent queues.", - config.deletePersistent()); - } - - /** - * Test that with the correct configuration the deletePersistent option can - * be enabled. - * - * Test creates a new Configuration object and passes in the xml snippet - * that the ConfigurationPlugin would receive during normal execution. - * This is the XML that would be matched for this plugin: - * <topicdelete> - * <delete-persistent> - * <topicdelete> - * - * So it would be subset and passed in as just: - * <delete-persistent> - * - * - * The property should therefore be enabled. - * - */ - public void testConfigDeletePersistent() - { - TopicDeletePolicyConfiguration config = new TopicDeletePolicyConfiguration(); - - XMLConfiguration xmlconfig = new XMLConfiguration(); - - xmlconfig.addProperty("delete-persistent",""); - - // Create a CompositeConfiguration as this is what the broker uses - CompositeConfiguration composite = new CompositeConfiguration(); - composite.addConfiguration(xmlconfig); - - try - { - config.setConfiguration("",composite); - } - catch (ConfigurationException e) - { - fail(e.getMessage()); - } - - assertTrue("A configured TopicDelete should delete persistent queues.", - config.deletePersistent()); - } - -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyTest.java b/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyTest.java deleted file mode 100644 index aa8448b99d..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyTest.java +++ /dev/null @@ -1,294 +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.plugins.policies; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.configuration.XMLConfiguration; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.binding.Binding; -import org.apache.qpid.server.exchange.DirectExchange; -import org.apache.qpid.server.exchange.TopicExchange; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.protocol.InternalTestProtocolSession; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.MockAMQQueue; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.util.InternalBrokerBaseCase; -import org.apache.qpid.server.virtualhost.VirtualHost; - -public class TopicDeletePolicyTest extends InternalBrokerBaseCase -{ - - private TopicDeletePolicyConfiguration _config; - - private VirtualHost _defaultVhost; - private InternalTestProtocolSession _connection; - - public void setUp() throws Exception - { - super.setUp(); - - _defaultVhost = ApplicationRegistry.getInstance().getVirtualHostRegistry().getDefaultVirtualHost(); - - _connection = new InternalTestProtocolSession(_defaultVhost); - - _config = new TopicDeletePolicyConfiguration(); - - XMLConfiguration config = new XMLConfiguration(); - - _config.setConfiguration("", config); - } - - private MockAMQQueue createOwnedQueue() - { - MockAMQQueue queue = new MockAMQQueue("testQueue"); - - _defaultVhost.getQueueRegistry().registerQueue(queue); - - try - { - AMQChannel channel = new AMQChannel(_connection, 0, null); - _connection.addChannel(channel); - - queue.setExclusiveOwningSession(channel); - } - catch (AMQException e) - { - fail("Unable to create Channel:" + e.getMessage()); - } - - return queue; - } - - private void setQueueToAutoDelete(final AMQQueue queue) - { - ((MockAMQQueue) queue).setAutoDelete(true); - - queue.setDeleteOnNoConsumers(true); - final AMQProtocolSession.Task deleteQueueTask = - new AMQProtocolSession.Task() - { - public void doTask(AMQProtocolSession session) throws AMQException - { - queue.delete(); - } - }; - - ((AMQChannel) queue.getExclusiveOwningSession()).getProtocolSession().addSessionCloseTask(deleteQueueTask); - } - - /** Check that a null queue passed in does not upset the policy. */ - public void testNullQueueParameter() throws ConfigurationException - { - TopicDeletePolicy policy = new TopicDeletePolicy(); - policy.configure(_config); - - try - { - policy.performPolicy(null); - } - catch (Exception e) - { - fail("Exception should not be thrown:" + e.getMessage()); - } - - } - - /** - * Set a owning Session to null which means this is not an exclusive queue - * so the queue should not be deleted - */ - public void testNonExclusiveQueue() - { - TopicDeletePolicy policy = new TopicDeletePolicy(); - policy.configure(_config); - - MockAMQQueue queue = createOwnedQueue(); - - queue.setExclusiveOwningSession(null); - - policy.performPolicy(queue); - - assertFalse("Queue should not be deleted", queue.isDeleted()); - assertFalse("Connection should not be closed", _connection.isClosed()); - } - - /** - * Test that exclusive JMS Queues are not deleted. - * Bind the queue to the direct exchange (so it is a JMS Queue). - * - * JMS Queues are not to be processed so this should not delete the queue. - */ - public void testQueuesAreNotProcessed() - { - TopicDeletePolicy policy = new TopicDeletePolicy(); - policy.configure(_config); - - MockAMQQueue queue = createOwnedQueue(); - - queue.addBinding(new Binding(null, null, "bindingKey", queue, new DirectExchange(), null)); - - policy.performPolicy(queue); - - assertFalse("Queue should not be deleted", queue.isDeleted()); - assertFalse("Connection should not be closed", _connection.isClosed()); - } - - /** - * Give a non auto-delete queue is bound to the topic exchange the - * TopicDeletePolicy will close the connection and delete the queue, - */ - public void testNonAutoDeleteTopicIsNotClosed() - { - TopicDeletePolicy policy = new TopicDeletePolicy(); - policy.configure(_config); - - MockAMQQueue queue = createOwnedQueue(); - - queue.addBinding(new Binding(null, null, "bindingKey", queue, new TopicExchange(), null)); - - queue.setAutoDelete(false); - - policy.performPolicy(queue); - - assertFalse("Queue should not be deleted", queue.isDeleted()); - assertTrue("Connection should be closed", _connection.isClosed()); - } - - /** - * Give a auto-delete queue bound to the topic exchange the TopicDeletePolicy will - * close the connection and delete the queue - */ - public void testTopicIsClosed() - { - TopicDeletePolicy policy = new TopicDeletePolicy(); - policy.configure(_config); - - final MockAMQQueue queue = createOwnedQueue(); - - queue.addBinding(new Binding(null, null, "bindingKey", queue, new TopicExchange(), null)); - - setQueueToAutoDelete(queue); - - policy.performPolicy(queue); - - assertTrue("Queue should be deleted", queue.isDeleted()); - assertTrue("Connection should be closed", _connection.isClosed()); - } - - /** - * Give a queue bound to the topic exchange the TopicDeletePolicy will - * close the connection and NOT delete the queue - */ - public void testNonAutoDeleteTopicIsClosedNotDeleted() - { - TopicDeletePolicy policy = new TopicDeletePolicy(); - policy.configure(_config); - - MockAMQQueue queue = createOwnedQueue(); - - queue.addBinding(new Binding(null, null, "bindingKey", queue, new TopicExchange(), null)); - - policy.performPolicy(queue); - - assertFalse("Queue should not be deleted", queue.isDeleted()); - assertTrue("Connection should be closed", _connection.isClosed()); - } - - /** - * Give a queue bound to the topic exchange the TopicDeletePolicy suitably - * configured with the delete-persistent tag will close the connection - * and delete the queue - */ - public void testPersistentTopicIsClosedAndDeleted() - { - //Set the config to delete persistent queues - _config.getConfig().addProperty("delete-persistent", ""); - - TopicDeletePolicy policy = new TopicDeletePolicy(); - policy.configure(_config); - - assertTrue("Config was not updated to delete Persistent topics", - _config.deletePersistent()); - - MockAMQQueue queue = createOwnedQueue(); - - queue.addBinding(new Binding(null, null, "bindingKey", queue, new TopicExchange(), null)); - - policy.performPolicy(queue); - - assertTrue("Queue should be deleted", queue.isDeleted()); - assertTrue("Connection should be closed", _connection.isClosed()); - } - - /** - * Give a queue bound to the topic exchange the TopicDeletePolicy not - * configured to close a persistent queue - */ - public void testPersistentTopicIsClosedAndDeletedNullConfig() - { - TopicDeletePolicy policy = new TopicDeletePolicy(); - // Explicity say we are not configuring the policy. - policy.configure(null); - - MockAMQQueue queue = createOwnedQueue(); - - queue.addBinding(new Binding(null, null, "bindingKey", queue, new TopicExchange(), null)); - - policy.performPolicy(queue); - - assertFalse("Queue should not be deleted", queue.isDeleted()); - assertTrue("Connection should be closed", _connection.isClosed()); - } - - public void testNonExclusiveQueueNullConfig() - { - _config = null; - testNonExclusiveQueue(); - } - - public void testQueuesAreNotProcessedNullConfig() - { - _config = null; - testQueuesAreNotProcessed(); - } - - public void testNonAutoDeleteTopicIsNotClosedNullConfig() - { - _config = null; - testNonAutoDeleteTopicIsNotClosed(); - } - - public void testTopicIsClosedNullConfig() - { - _config = null; - testTopicIsClosed(); - } - - public void testNonAutoDeleteTopicIsClosedNotDeletedNullConfig() throws AMQException - { - _config = null; - testNonAutoDeleteTopicIsClosedNotDeleted(); - } - -} |