summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAidan Skinner <aidan@apache.org>2009-09-17 16:21:13 +0000
committerAidan Skinner <aidan@apache.org>2009-09-17 16:21:13 +0000
commit7d6a028be9f6c47418e98a6fa74a359864428150 (patch)
tree78083427e88c48edb3b23605309e57f1301cba19
parent31bbc100ac6b3a31eb25d29f407d60ff23334d1f (diff)
downloadqpid-python-7d6a028be9f6c47418e98a6fa74a359864428150.tar.gz
Merge from trunk
git-svn-id: https://svn.apache.org/repos/asf/qpid/branches/java-network-refactor@816261 13f79535-47bb-0310-9956-ffa450edef68
-rw-r--r--qpid/cpp/bindings/qmf/python/Makefile.am2
-rw-r--r--qpid/cpp/bindings/qmf/python/qmf.py14
-rw-r--r--qpid/cpp/bindings/qmf/ruby/qmf.rb295
-rwxr-xr-xqpid/cpp/bindings/qmf/tests/agent_ruby.rb7
-rw-r--r--qpid/cpp/bindings/qmf/tests/python_agent.py4
-rwxr-xr-xqpid/cpp/bindings/qmf/tests/ruby_console.rb83
-rw-r--r--qpid/cpp/include/qpid/messaging/Receiver.h33
-rw-r--r--qpid/cpp/include/qpid/messaging/Sender.h19
-rw-r--r--qpid/cpp/include/qpid/messaging/Session.h14
-rw-r--r--qpid/cpp/src/CMakeLists.txt4
-rw-r--r--qpid/cpp/src/Makefile.am4
-rw-r--r--qpid/cpp/src/qmf/AgentEngine.cpp19
-rw-r--r--qpid/cpp/src/qmf/ConsoleEngine.cpp379
-rw-r--r--qpid/cpp/src/qmf/ConsoleEngine.h70
-rw-r--r--qpid/cpp/src/qmf/Object.h3
-rw-r--r--qpid/cpp/src/qmf/ObjectId.h1
-rw-r--r--qpid/cpp/src/qmf/ObjectIdImpl.cpp21
-rw-r--r--qpid/cpp/src/qmf/ObjectIdImpl.h3
-rw-r--r--qpid/cpp/src/qmf/ObjectImpl.cpp88
-rw-r--r--qpid/cpp/src/qmf/ObjectImpl.h13
-rw-r--r--qpid/cpp/src/qmf/Query.h70
-rw-r--r--qpid/cpp/src/qmf/QueryImpl.cpp85
-rw-r--r--qpid/cpp/src/qmf/QueryImpl.h78
-rw-r--r--qpid/cpp/src/qmf/SchemaImpl.cpp13
-rw-r--r--qpid/cpp/src/qmf/SchemaImpl.h7
-rw-r--r--qpid/cpp/src/qmf/SequenceManager.cpp52
-rw-r--r--qpid/cpp/src/qmf/SequenceManager.h20
-rw-r--r--qpid/cpp/src/qpid/acl/AclData.cpp91
-rw-r--r--qpid/cpp/src/qpid/acl/AclData.h12
-rw-r--r--qpid/cpp/src/qpid/acl/AclReader.cpp227
-rw-r--r--qpid/cpp/src/qpid/broker/AclModule.h17
-rw-r--r--qpid/cpp/src/qpid/broker/Exchange.cpp26
-rw-r--r--qpid/cpp/src/qpid/broker/Message.cpp2
-rw-r--r--qpid/cpp/src/qpid/broker/Message.h10
-rw-r--r--qpid/cpp/src/qpid/broker/MessageBuilder.cpp28
-rw-r--r--qpid/cpp/src/qpid/broker/PersistableMessage.cpp2
-rw-r--r--qpid/cpp/src/qpid/broker/PersistableMessage.h4
-rw-r--r--qpid/cpp/src/qpid/broker/Queue.cpp4
-rw-r--r--qpid/cpp/src/qpid/broker/QueueRegistry.h2
-rw-r--r--qpid/cpp/src/qpid/broker/RecoveryManagerImpl.cpp2
-rw-r--r--qpid/cpp/src/qpid/broker/SessionAdapter.cpp18
-rw-r--r--qpid/cpp/src/qpid/client/Dispatcher.cpp11
-rw-r--r--qpid/cpp/src/qpid/client/amqp0_10/AcceptTracker.cpp111
-rw-r--r--qpid/cpp/src/qpid/client/amqp0_10/AcceptTracker.h85
-rw-r--r--qpid/cpp/src/qpid/client/amqp0_10/CompletionTracker.cpp48
-rw-r--r--qpid/cpp/src/qpid/client/amqp0_10/CompletionTracker.h50
-rw-r--r--qpid/cpp/src/qpid/client/amqp0_10/IncomingMessages.cpp53
-rw-r--r--qpid/cpp/src/qpid/client/amqp0_10/IncomingMessages.h9
-rw-r--r--qpid/cpp/src/qpid/client/amqp0_10/ReceiverImpl.cpp15
-rw-r--r--qpid/cpp/src/qpid/client/amqp0_10/ReceiverImpl.h3
-rw-r--r--qpid/cpp/src/qpid/client/amqp0_10/SenderImpl.cpp55
-rw-r--r--qpid/cpp/src/qpid/client/amqp0_10/SenderImpl.h34
-rw-r--r--qpid/cpp/src/qpid/client/amqp0_10/SessionImpl.cpp55
-rw-r--r--qpid/cpp/src/qpid/client/amqp0_10/SessionImpl.h17
-rw-r--r--qpid/cpp/src/qpid/cluster/Connection.cpp10
-rw-r--r--qpid/cpp/src/qpid/cluster/Quorum_cman.cpp8
-rw-r--r--qpid/cpp/src/qpid/messaging/Address.cpp3
-rw-r--r--qpid/cpp/src/qpid/messaging/Receiver.cpp3
-rw-r--r--qpid/cpp/src/qpid/messaging/ReceiverImpl.h3
-rw-r--r--qpid/cpp/src/qpid/messaging/Sender.cpp3
-rw-r--r--qpid/cpp/src/qpid/messaging/SenderImpl.h3
-rw-r--r--qpid/cpp/src/qpid/messaging/Session.cpp12
-rw-r--r--qpid/cpp/src/qpid/messaging/SessionImpl.h4
-rw-r--r--qpid/cpp/src/qpid/sys/rdma/RdmaClient.cpp11
-rw-r--r--qpid/cpp/src/qpid/sys/rdma/RdmaServer.cpp11
-rw-r--r--qpid/cpp/src/qpid/xml/XmlExchange.cpp46
-rw-r--r--qpid/cpp/src/tests/AccumulatedAckTest.cpp13
-rw-r--r--qpid/cpp/src/tests/Array.cpp11
-rw-r--r--qpid/cpp/src/tests/AsyncCompletion.cpp11
-rw-r--r--qpid/cpp/src/tests/AtomicValue.cpp5
-rw-r--r--qpid/cpp/src/tests/BrokerFixture.h10
-rw-r--r--qpid/cpp/src/tests/ClientMessageTest.cpp7
-rw-r--r--qpid/cpp/src/tests/ClientSessionTest.cpp67
-rw-r--r--qpid/cpp/src/tests/ClusterFailover.cpp5
-rw-r--r--qpid/cpp/src/tests/ClusterFixture.cpp5
-rw-r--r--qpid/cpp/src/tests/ClusterFixture.h5
-rw-r--r--qpid/cpp/src/tests/ConnectionOptions.h14
-rw-r--r--qpid/cpp/src/tests/ConsoleTest.cpp9
-rw-r--r--qpid/cpp/src/tests/DeliveryRecordTest.cpp8
-rw-r--r--qpid/cpp/src/tests/DispatcherTest.cpp47
-rw-r--r--qpid/cpp/src/tests/DtxWorkRecordTest.cpp18
-rw-r--r--qpid/cpp/src/tests/ExchangeTest.cpp41
-rw-r--r--qpid/cpp/src/tests/FieldTable.cpp19
-rw-r--r--qpid/cpp/src/tests/FieldValue.cpp13
-rw-r--r--qpid/cpp/src/tests/ForkedBroker.cpp20
-rw-r--r--qpid/cpp/src/tests/ForkedBroker.h17
-rw-r--r--qpid/cpp/src/tests/Frame.cpp9
-rw-r--r--qpid/cpp/src/tests/FrameDecoder.cpp11
-rw-r--r--qpid/cpp/src/tests/FramingTest.cpp25
-rw-r--r--qpid/cpp/src/tests/HeaderTest.cpp18
-rw-r--r--qpid/cpp/src/tests/HeadersExchangeTest.cpp31
-rw-r--r--qpid/cpp/src/tests/IncompleteMessageList.cpp17
-rw-r--r--qpid/cpp/src/tests/InlineAllocator.cpp13
-rw-r--r--qpid/cpp/src/tests/InlineVector.cpp11
-rw-r--r--qpid/cpp/src/tests/ManagementTest.cpp9
-rw-r--r--qpid/cpp/src/tests/MessageBuilderTest.cpp46
-rw-r--r--qpid/cpp/src/tests/MessageReplayTracker.cpp21
-rw-r--r--qpid/cpp/src/tests/MessageTest.cpp12
-rw-r--r--qpid/cpp/src/tests/MessageUtils.h13
-rw-r--r--qpid/cpp/src/tests/MessagingSessionTests.cpp119
-rw-r--r--qpid/cpp/src/tests/PartialFailure.cpp5
-rw-r--r--qpid/cpp/src/tests/PollableCondition.cpp18
-rw-r--r--qpid/cpp/src/tests/ProxyTest.cpp11
-rw-r--r--qpid/cpp/src/tests/QueueEvents.cpp17
-rw-r--r--qpid/cpp/src/tests/QueueOptionsTest.cpp27
-rw-r--r--qpid/cpp/src/tests/QueuePolicyTest.cpp45
-rw-r--r--qpid/cpp/src/tests/QueueRegistryTest.cpp17
-rw-r--r--qpid/cpp/src/tests/QueueTest.cpp165
-rw-r--r--qpid/cpp/src/tests/RangeSet.cpp9
-rw-r--r--qpid/cpp/src/tests/RateFlowcontrolTest.cpp19
-rw-r--r--qpid/cpp/src/tests/RefCounted.cpp5
-rw-r--r--qpid/cpp/src/tests/ReplicationTest.cpp13
-rw-r--r--qpid/cpp/src/tests/RetryList.cpp15
-rw-r--r--qpid/cpp/src/tests/SequenceNumberTest.cpp12
-rw-r--r--qpid/cpp/src/tests/SequenceSet.cpp9
-rw-r--r--qpid/cpp/src/tests/SessionState.cpp19
-rw-r--r--qpid/cpp/src/tests/Shlib.cpp9
-rw-r--r--qpid/cpp/src/tests/SocketProxy.h13
-rw-r--r--qpid/cpp/src/tests/TestMessageStore.h13
-rw-r--r--qpid/cpp/src/tests/TestOptions.h6
-rw-r--r--qpid/cpp/src/tests/TimerTest.cpp19
-rw-r--r--qpid/cpp/src/tests/TopicExchangeTest.cpp22
-rw-r--r--qpid/cpp/src/tests/TxBufferTest.cpp9
-rw-r--r--qpid/cpp/src/tests/TxMocks.h49
-rw-r--r--qpid/cpp/src/tests/TxPublishTest.cpp23
-rw-r--r--qpid/cpp/src/tests/Url.cpp5
-rw-r--r--qpid/cpp/src/tests/Uuid.cpp5
-rw-r--r--qpid/cpp/src/tests/Variant.cpp21
-rw-r--r--qpid/cpp/src/tests/XmlClientSessionTest.cpp18
-rwxr-xr-xqpid/cpp/src/tests/acl.py400
-rw-r--r--qpid/cpp/src/tests/client_test.cpp21
-rw-r--r--qpid/cpp/src/tests/cluster_test.cpp9
-rw-r--r--qpid/cpp/src/tests/consume.cpp21
-rw-r--r--qpid/cpp/src/tests/datagen.cpp19
-rw-r--r--qpid/cpp/src/tests/echotest.cpp21
-rw-r--r--qpid/cpp/src/tests/exception_test.cpp17
-rw-r--r--qpid/cpp/src/tests/failover_soak.cpp124
-rw-r--r--qpid/cpp/src/tests/latencytest.cpp55
-rw-r--r--qpid/cpp/src/tests/logging.cpp31
-rw-r--r--qpid/cpp/src/tests/perftest.cpp77
-rw-r--r--qpid/cpp/src/tests/publish.cpp21
-rw-r--r--qpid/cpp/src/tests/qpid_ping.cpp12
-rw-r--r--qpid/cpp/src/tests/qrsh.cpp37
-rw-r--r--qpid/cpp/src/tests/qrsh_server.cpp127
-rw-r--r--qpid/cpp/src/tests/receiver.cpp26
-rw-r--r--qpid/cpp/src/tests/replaying_sender.cpp39
-rw-r--r--qpid/cpp/src/tests/resuming_receiver.cpp45
-rw-r--r--qpid/cpp/src/tests/sender.cpp34
-rw-r--r--qpid/cpp/src/tests/shlibtest.cpp6
-rw-r--r--qpid/cpp/src/tests/test_store.cpp15
-rw-r--r--qpid/cpp/src/tests/test_tools.h6
-rw-r--r--qpid/cpp/src/tests/topic_listener.cpp105
-rw-r--r--qpid/cpp/src/tests/topic_publisher.cpp135
-rw-r--r--qpid/cpp/src/tests/txjob.cpp17
-rw-r--r--qpid/cpp/src/tests/txshift.cpp27
-rw-r--r--qpid/cpp/src/tests/txtest.cpp53
-rwxr-xr-xqpid/java/broker/bin/qpid-passwd70
-rw-r--r--qpid/java/broker/etc/config-systests-derby.xml141
-rw-r--r--qpid/java/broker/etc/config-systests.xml143
-rw-r--r--qpid/java/broker/etc/config.xml132
-rw-r--r--qpid/java/broker/etc/virtualhosts-systests.xml124
-rw-r--r--qpid/java/broker/etc/virtualhosts.xml123
-rw-r--r--qpid/java/broker/src/main/java/org/apache/qpid/server/AMQBrokerManagerMBean.java6
-rw-r--r--qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ServerConfiguration.java35
-rw-r--r--qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHost.java12
-rw-r--r--qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/ServerConfigurationTest.java55
-rw-r--r--qpid/java/systests/etc/config-systests-ServerConfigurationTest-New.xml (renamed from qpid/java/broker/etc/persistent_config-config-test.xml)2
-rw-r--r--qpid/java/systests/etc/config-systests-ServerConfigurationTest-Old.xml (renamed from qpid/java/broker/etc/sample-parsed-config.xml)2
-rw-r--r--qpid/java/systests/etc/config-systests-acl-settings.xml (renamed from qpid/java/broker/etc/acl.config.xml)91
-rw-r--r--qpid/java/systests/etc/config-systests-acl.xml30
-rw-r--r--qpid/java/systests/etc/config-systests-derby-settings.xml64
-rw-r--r--qpid/java/systests/etc/config-systests-derby.xml30
-rw-r--r--qpid/java/systests/etc/config-systests-settings.xml29
-rw-r--r--qpid/java/systests/etc/config-systests.xml29
-rw-r--r--qpid/java/systests/etc/virtualhosts-ServerConfigurationTest-New.xml (renamed from qpid/java/broker/etc/virtualhosts-config-test.xml)0
-rw-r--r--qpid/java/systests/src/main/java/org/apache/qpid/management/jmx/ManagementActorLoggingTest.java527
-rw-r--r--qpid/java/systests/src/main/java/org/apache/qpid/server/configuration/ServerConfigurationFileTest.java2
-rw-r--r--qpid/java/systests/src/main/java/org/apache/qpid/server/logging/AlertingTest.java14
-rw-r--r--qpid/java/systests/src/main/java/org/apache/qpid/server/logging/DerbyMessageStoreLoggingTest.java43
-rw-r--r--qpid/java/systests/src/main/java/org/apache/qpid/server/logging/ManagementLoggingTest.java6
-rw-r--r--qpid/java/systests/src/main/java/org/apache/qpid/server/logging/MemoryMessageStoreLoggingTest.java12
-rw-r--r--qpid/java/systests/src/main/java/org/apache/qpid/server/logging/VirtualHostLoggingTest.java8
-rw-r--r--qpid/java/systests/src/main/java/org/apache/qpid/server/queue/ModelTest.java299
-rw-r--r--qpid/java/systests/src/main/java/org/apache/qpid/server/security/acl/SimpleACLTest.java134
-rw-r--r--qpid/java/systests/src/main/java/org/apache/qpid/test/client/timeouts/SyncWaitDelayTest.java21
-rw-r--r--qpid/java/systests/src/main/java/org/apache/qpid/test/utils/FailoverBaseCase.java4
-rw-r--r--qpid/java/systests/src/main/java/org/apache/qpid/test/utils/JMXTestUtils.java208
-rw-r--r--qpid/java/systests/src/main/java/org/apache/qpid/test/utils/QpidTestCase.java139
-rw-r--r--qpid/java/test-profiles/010Excludes3
-rw-r--r--qpid/java/test-profiles/08Excludes5
-rw-r--r--qpid/java/test-profiles/Excludes6
-rw-r--r--qpid/java/test-profiles/cpp.testprofile1
-rw-r--r--qpid/java/test-profiles/default.testprofile5
-rw-r--r--qpid/python/qpid/datatypes.py18
-rw-r--r--qpid/python/qpid/delegates.py8
-rw-r--r--qpid/python/qpid/ops.py5
-rw-r--r--qpid/python/tests/datatypes.py28
-rw-r--r--qpid/specs/management-schema.xml2
198 files changed, 4998 insertions, 2945 deletions
diff --git a/qpid/cpp/bindings/qmf/python/Makefile.am b/qpid/cpp/bindings/qmf/python/Makefile.am
index f51d26bfad..55d9079fb7 100644
--- a/qpid/cpp/bindings/qmf/python/Makefile.am
+++ b/qpid/cpp/bindings/qmf/python/Makefile.am
@@ -29,7 +29,7 @@ EXTRA_DIST = python.i
BUILT_SOURCES = $(generated_file_list)
$(generated_file_list): $(srcdir)/python.i $(srcdir)/../qmfengine.i
- swig -python -c++ -Wall -I/usr/include $(INCLUDES) $(QPID_CXXFLAGS) -I$(top_srcdir)/src/qmf -o qmfengine.cpp $(srcdir)/python.i
+ swig -c++ -python -Wall -I/usr/include $(INCLUDES) $(QPID_CXXFLAGS) -I$(top_srcdir)/src/qmf -o qmfengine.cpp $(srcdir)/python.i
pylibdir = $(PYTHON_LIB)
diff --git a/qpid/cpp/bindings/qmf/python/qmf.py b/qpid/cpp/bindings/qmf/python/qmf.py
index 265f204852..4800b327f1 100644
--- a/qpid/cpp/bindings/qmf/python/qmf.py
+++ b/qpid/cpp/bindings/qmf/python/qmf.py
@@ -30,6 +30,8 @@ from qmfengine import (TYPE_ABSTIME, TYPE_ARRAY, TYPE_BOOL, TYPE_DELTATIME,
TYPE_INT8, TYPE_LIST, TYPE_LSTR, TYPE_MAP, TYPE_OBJECT,
TYPE_REF, TYPE_SSTR, TYPE_UINT16, TYPE_UINT32, TYPE_UINT64,
TYPE_UINT8, TYPE_UUID)
+from qmfengine import (O_EQ, O_NE, O_LT, O_LE, O_GT, O_GE, O_RE_MATCH, O_RE_NOMATCH,
+ E_NOT, E_AND, E_OR, E_XOR)
##==============================================================================
@@ -404,11 +406,16 @@ class Arguments:
class Query:
- def __init__(self, i=None):
+ def __init__(self, i=None, package="", cls=None, oid=None):
if i:
self.impl = i
else:
- self.impl = qmfengine.Query()
+ if cls:
+ self.impl = qmfengine.Query(cls, package)
+ elif oid:
+ self.impl = qmfengine.Query(oid)
+ else:
+ raise "Argument error"
def package_name(self): return self.impl.getPackage()
@@ -419,9 +426,6 @@ class Query:
return ObjectId(_objid)
else:
return None
- OPER_AND = qmfengine.Query.OPER_AND
- OPER_OR = qmfengine.Query.OPER_OR
-
##==============================================================================
diff --git a/qpid/cpp/bindings/qmf/ruby/qmf.rb b/qpid/cpp/bindings/qmf/ruby/qmf.rb
index 21fbf6c157..16f1058f4a 100644
--- a/qpid/cpp/bindings/qmf/ruby/qmf.rb
+++ b/qpid/cpp/bindings/qmf/ruby/qmf.rb
@@ -67,6 +67,7 @@ module Qmf
class ConnectionHandler
def conn_event_connected(); end
def conn_event_disconnected(error); end
+ def conn_event_visit(); end
def sess_event_session_closed(context, error); end
def sess_event_recv(context, message); end
end
@@ -82,6 +83,7 @@ module Qmf
@sockEngine, @sock = Socket::socketpair(Socket::PF_UNIX, Socket::SOCK_STREAM, 0)
@impl.setNotifyFd(@sockEngine.fileno)
@new_conn_handlers = []
+ @conn_handlers_to_delete = []
@conn_handlers = []
@thread = Thread.new do
@@ -89,17 +91,30 @@ module Qmf
end
end
+ def kick
+ @sockEngine.write(".")
+ @sockEngine.flush
+ end
+
def add_conn_handler(handler)
synchronize do
@new_conn_handlers << handler
end
- @sockEngine.write("x")
+ kick
+ end
+
+ def del_conn_handler(handler)
+ synchronize do
+ @conn_handlers_to_delete << handler
+ end
+ kick
end
def run()
eventImpl = Qmfengine::ResilientConnectionEvent.new
connected = nil
new_handlers = nil
+ del_handlers = nil
bt_count = 0
while :true
@@ -107,7 +122,9 @@ module Qmf
synchronize do
new_handlers = @new_conn_handlers
+ del_handlers = @conn_handlers_to_delete
@new_conn_handlers = []
+ @conn_handlers_to_delete = []
end
new_handlers.each do |nh|
@@ -116,6 +133,11 @@ module Qmf
end
new_handlers = nil
+ del_handlers.each do |dh|
+ d = @conn_handlers.delete(dh)
+ end
+ del_handlers = nil
+
valid = @impl.getEvent(eventImpl)
while valid
begin
@@ -141,6 +163,7 @@ module Qmf
@impl.popEvent
valid = @impl.getEvent(eventImpl)
end
+ @conn_handlers.each { |h| h.conn_event_visit }
end
end
end
@@ -167,23 +190,20 @@ module Qmf
class QmfObject
attr_reader :impl, :object_class
- def initialize(cls)
- @object_class = cls
- @impl = Qmfengine::Object.new(@object_class.impl)
- end
-
- def destroy
- @impl.destroy
+ def initialize(cls, kwargs={})
+ if cls:
+ @object_class = cls
+ @impl = Qmfengine::Object.new(@object_class.impl)
+ elsif kwargs.include?(:impl)
+ @impl = Qmfengine::Object.new(kwargs[:impl])
+ @object_class = SchemaObjectClass.new(nil, nil, :impl => @impl.getClass)
+ end
end
def object_id
return ObjectId.new(@impl.getObjectId)
end
- def set_object_id(oid)
- @impl.setObjectId(oid.impl)
- end
-
def get_attr(name)
val = value(name)
case val.getType
@@ -248,17 +268,31 @@ module Qmf
def value(name)
val = @impl.getValue(name.to_s)
if val.nil?
- raise ArgumentError, "Attribute '#{name}' not defined for class #{@object_class.impl.getName}"
+ raise ArgumentError, "Attribute '#{name}' not defined for class #{@object_class.impl.getClassKey.getPackageName}:#{@object_class.impl.getClassKey.getClassName}"
end
return val
end
end
+ class AgentObject < QmfObject
+ def initialize(cls, kwargs={})
+ super(cls, kwargs)
+ end
+
+ def destroy
+ @impl.destroy
+ end
+
+ def set_object_id(oid)
+ @impl.setObjectId(oid.impl)
+ end
+ end
+
class ConsoleObject < QmfObject
attr_reader :current_time, :create_time, :delete_time
- def initialize(cls)
- super(cls)
+ def initialize(cls, kwargs={})
+ super(cls, kwargs)
end
def update()
@@ -373,10 +407,30 @@ module Qmf
end
end
+ ##==============================================================================
+ ## QUERY
+ ##==============================================================================
+
class Query
attr_reader :impl
- def initialize(i)
- @impl = i
+ def initialize(kwargs = {})
+ if kwargs.include?(:impl)
+ @impl = kwargs[:impl]
+ else
+ package = ''
+ if kwargs.include?(:key)
+ @impl = Qmfengine::Query.new(kwargs[:key])
+ elsif kwargs.include?(:object_id)
+ @impl = Qmfengine::Query.new(kwargs[:object_id])
+ else
+ package = kwargs[:package] if kwargs.include?(:package)
+ if kwargs.include?(:class)
+ @impl = Qmfengine::Query.new(kwargs[:class], package)
+ else
+ raise ArgumentError, "Invalid arguments, use :key or :class[,:package]"
+ end
+ end
+ end
end
def package_name
@@ -403,36 +457,60 @@ module Qmf
class SchemaArgument
attr_reader :impl
def initialize(name, typecode, kwargs={})
- @impl = Qmfengine::SchemaArgument.new(name, typecode)
- @impl.setDirection(kwargs[:dir]) if kwargs.include?(:dir)
- @impl.setUnit(kwargs[:unit]) if kwargs.include?(:unit)
- @impl.setDesc(kwargs[:desc]) if kwargs.include?(:desc)
+ if kwargs.include?(:impl)
+ @impl = kwargs[:impl]
+ else
+ @impl = Qmfengine::SchemaArgument.new(name, typecode)
+ @impl.setDirection(kwargs[:dir]) if kwargs.include?(:dir)
+ @impl.setUnit(kwargs[:unit]) if kwargs.include?(:unit)
+ @impl.setDesc(kwargs[:desc]) if kwargs.include?(:desc)
+ end
+ end
+
+ def name
+ @impl.getName
end
end
class SchemaMethod
- attr_reader :impl
+ attr_reader :impl, :arguments
def initialize(name, kwargs={})
- @impl = Qmfengine::SchemaMethod.new(name)
- @impl.setDesc(kwargs[:desc]) if kwargs.include?(:desc)
@arguments = []
+ if kwargs.include?(:impl)
+ @impl = kwargs[:impl]
+ arg_count = @impl.getArgumentCount
+ for i in 0...arg_count
+ @arguments << SchemaArgument.new(nil, nil, :impl => @impl.getArgument(i))
+ end
+ else
+ @impl = Qmfengine::SchemaMethod.new(name)
+ @impl.setDesc(kwargs[:desc]) if kwargs.include?(:desc)
+ end
end
def add_argument(arg)
@arguments << arg
@impl.addArgument(arg.impl)
end
+
+ def name
+ @impl.getName
+ end
end
class SchemaProperty
attr_reader :impl
def initialize(name, typecode, kwargs={})
- @impl = Qmfengine::SchemaProperty.new(name, typecode)
- @impl.setAccess(kwargs[:access]) if kwargs.include?(:access)
- @impl.setIndex(kwargs[:index]) if kwargs.include?(:index)
- @impl.setOptional(kwargs[:optional]) if kwargs.include?(:optional)
- @impl.setUnit(kwargs[:unit]) if kwargs.include?(:unit)
- @impl.setDesc(kwargs[:desc]) if kwargs.include?(:desc)
+ if kwargs.include?(:impl)
+ @impl = kwargs[:impl]
+ else
+ @impl = Qmfengine::SchemaProperty.new(name, typecode)
+ @impl.setAccess(kwargs[:access]) if kwargs.include?(:access)
+ @impl.setIndex(kwargs[:index]) if kwargs.include?(:index)
+ @impl.setOptional(kwargs[:optional]) if kwargs.include?(:optional)
+ @impl.setUnit(kwargs[:unit]) if kwargs.include?(:unit)
+ @impl.setDesc(kwargs[:desc]) if kwargs.include?(:desc)
+ end
end
def name
@@ -443,9 +521,17 @@ module Qmf
class SchemaStatistic
attr_reader :impl
def initialize(name, typecode, kwargs={})
- @impl = Qmfengine::SchemaStatistic.new(name, typecode)
- @impl.setUnit(kwargs[:unit]) if kwargs.include?(:unit)
- @impl.setDesc(kwargs[:desc]) if kwargs.include?(:desc)
+ if kwargs.include?(:impl)
+ @impl = kwargs[:impl]
+ else
+ @impl = Qmfengine::SchemaStatistic.new(name, typecode)
+ @impl.setUnit(kwargs[:unit]) if kwargs.include?(:unit)
+ @impl.setDesc(kwargs[:desc]) if kwargs.include?(:desc)
+ end
+ end
+
+ def name
+ @impl.getName
end
end
@@ -465,13 +551,25 @@ module Qmf
end
class SchemaObjectClass
- attr_reader :impl
- def initialize(package='', name='', kwargs={})
+ attr_reader :impl, :properties, :statistics, :methods
+ def initialize(package, name, kwargs={})
@properties = []
@statistics = []
@methods = []
if kwargs.include?(:impl)
@impl = kwargs[:impl]
+
+ @impl.getPropertyCount.times do |i|
+ @properties << SchemaProperty.new(nil, nil, :impl => @impl.getProperty(i))
+ end
+
+ @impl.getStatisticCount.times do |i|
+ @statistics << SchemaStatistic.new(nil, nil, :impl => @impl.getStatistic(i))
+ end
+
+ @impl.getMethodCount.times do |i|
+ @methods << SchemaMethod.new(nil, :impl => @impl.getMethod(i))
+ end
else
@impl = Qmfengine::SchemaObjectClass.new(package, name)
end
@@ -495,24 +593,17 @@ module Qmf
def name
@impl.getClassKey.getClassName
end
-
- def properties
- unless @properties
- @properties = []
- @impl.getPropertyCount.times do |i|
- @properties << @impl.getProperty(i)
- end
- end
- return @properties
- end
end
class SchemaEventClass
- attr_reader :impl
- def initialize(package='', name='', kwargs={})
+ attr_reader :impl, :arguments
+ def initialize(package, name, kwargs={})
@arguments = []
if kwargs.include?(:impl)
@impl = kwargs[:impl]
+ @impl.getArgumentCount.times do |i|
+ @arguments << SchemaArgument.new(nil, nil, :impl => @impl.getArgument(i))
+ end
else
@impl = Qmfengine::SchemaEventClass.new(package, name)
@impl.setDesc(kwargs[:desc]) if kwargs.include?(:desc)
@@ -546,13 +637,18 @@ module Qmf
end
class Console
+ include MonitorMixin
attr_reader :impl
def initialize(handler = nil, kwargs={})
+ super()
@handler = handler
@impl = Qmfengine::ConsoleEngine.new
@event = Qmfengine::ConsoleEvent.new
@broker_list = []
+ @cv = new_cond
+ @sync_count = nil
+ @sync_result = nil
end
def add_connection(conn)
@@ -562,6 +658,8 @@ module Qmf
end
def del_connection(broker)
+ broker.shutdown
+ @broker_list.delete(broker)
end
def get_packages()
@@ -581,9 +679,9 @@ module Qmf
class_kind = @impl.getClassKind(key)
if class_kind == kind
if kind == CLASS_OBJECT
- clist << SchemaObjectClass.new('', '', :impl => @impl.getObjectClass(key))
+ clist << SchemaObjectClass.new(nil, nil, :impl => @impl.getObjectClass(key))
elsif kind == CLASS_EVENT
- clist << SchemaEventClass.new('', '', :impl => @impl.getEventClass(key))
+ clist << SchemaEventClass.new(nil, nil, :impl => @impl.getEventClass(key))
end
end
end
@@ -591,19 +689,70 @@ module Qmf
return clist
end
- def get_schema(class_key)
- end
-
def bind_package(package)
+ @impl.bindPackage(package)
end
def bind_class(kwargs = {})
+ if kwargs.include?(:key)
+ @impl.bindClass(kwargs[:key])
+ elsif kwargs.include?(:package)
+ package = kwargs[:package]
+ if kwargs.include?(:class)
+ @impl.bindClass(package, kwargs[:class])
+ else
+ @impl.bindClass(package)
+ end
+ else
+ raise ArgumentError, "Invalid arguments, use :key or :package[,:class]"
+ end
end
def get_agents(broker = nil)
+ blist = []
+ if broker
+ blist << broker
+ else
+ blist = @broker_list
+ end
+
+ agents = []
+ blist.each do |b|
+ count = b.impl.agentCount
+ for idx in 0...count
+ agents << AgentProxy.new(b.impl.getAgent(idx), b)
+ end
+ end
+
+ return agents
end
def get_objects(query, kwargs = {})
+ timeout = 30
+ if kwargs.include?(:timeout)
+ timeout = kwargs[:timeout]
+ end
+ synchronize do
+ @sync_count = 1
+ @sync_result = []
+ broker = @broker_list[0]
+ broker.send_query(query.impl, nil)
+ unless @cv.wait(timeout) { @sync_count == 0 }
+ raise "Timed out waiting for response"
+ end
+
+ return @sync_result
+ end
+ end
+
+ def _get_result(list, context)
+ synchronize do
+ list.each do |item|
+ @sync_result << item
+ end
+ @sync_count -= 1
+ @cv.signal
+ end
end
def start_sync(query)
@@ -638,6 +787,19 @@ module Qmf
end
end
+ class AgentProxy
+ attr_reader :broker
+
+ def initialize(impl, broker)
+ @impl = impl
+ @broker = broker
+ end
+
+ def label
+ @impl.getLabel
+ end
+ end
+
class Broker < ConnectionHandler
include MonitorMixin
attr_reader :impl
@@ -654,6 +816,13 @@ module Qmf
@impl = Qmfengine::BrokerProxy.new(@console.impl)
@console.impl.addConnection(@impl, self)
@conn.add_conn_handler(self)
+ @operational = :true
+ end
+
+ def shutdown()
+ @console.impl.delConnection(@impl)
+ @conn.del_conn_handler(self)
+ @operational = :false
end
def waitForStable(timeout = nil)
@@ -671,6 +840,11 @@ module Qmf
end
end
+ def send_query(query, ctx)
+ @impl.sendQuery(query, ctx)
+ @conn.kick
+ end
+
def do_broker_events()
count = 0
valid = @impl.getEvent(@event)
@@ -694,6 +868,12 @@ module Qmf
@stable = :true
@cv.signal
end
+ when Qmfengine::BrokerEvent::QUERY_COMPLETE
+ result = []
+ for idx in 0...@event.queryResponse.getObjectCount
+ result << ConsoleObject.new(nil, :impl => @event.queryResponse.getObject(idx))
+ end
+ @console._get_result(result, @event.context)
end
@impl.popEvent
valid = @impl.getEvent(@event)
@@ -732,12 +912,17 @@ module Qmf
puts "Console Connection Lost"
end
+ def conn_event_visit
+ do_events
+ end
+
def sess_event_session_closed(context, error)
puts "Console Session Lost"
@impl.sessionClosed()
end
def sess_event_recv(context, message)
+ puts "Unexpected RECV Event" if not @operational
@impl.handleRcvMessage(message)
do_events
end
@@ -798,7 +983,7 @@ module Qmf
count += 1
case @event.kind
when Qmfengine::AgentEvent::GET_QUERY
- @handler.get_query(@event.sequence, Query.new(@event.query), @event.authUserId)
+ @handler.get_query(@event.sequence, Query.new(:impl => @event.query), @event.authUserId)
when Qmfengine::AgentEvent::START_SYNC
when Qmfengine::AgentEvent::END_SYNC
when Qmfengine::AgentEvent::METHOD_CALL
@@ -852,6 +1037,10 @@ module Qmf
puts "Agent Connection Lost"
end
+ def conn_event_visit
+ do_events
+ end
+
def sess_event_session_closed(context, error)
puts "Agent Session Lost"
end
diff --git a/qpid/cpp/bindings/qmf/tests/agent_ruby.rb b/qpid/cpp/bindings/qmf/tests/agent_ruby.rb
index 75de2b5fa1..67591319ee 100755
--- a/qpid/cpp/bindings/qmf/tests/agent_ruby.rb
+++ b/qpid/cpp/bindings/qmf/tests/agent_ruby.rb
@@ -72,8 +72,7 @@ end
class App < Qmf::AgentHandler
def get_query(context, query, userId)
-# puts "Query: user=#{userId} context=#{context} class=#{query.class_name} object_num=#{query.object_id.object_num_low if query.object_id}"
- #@parent.inc_attr("queryCount")
+# puts "Query: user=#{userId} context=#{context} class=#{query.class_name} object_num=#{query.object_id.object_num_low if query.object_id}"
if query.class_name == 'parent'
@agent.query_response(context, @parent)
elsif query.object_id == @parent_oid
@@ -135,7 +134,7 @@ class App < Qmf::AgentHandler
elsif name == "create_child"
oid = @agent.alloc_object_id(2)
args['child_ref'] = oid
- @child = Qmf::QmfObject.new(@model.child_class)
+ @child = Qmf::AgentObject.new(@model.child_class)
@child.set_attr("name", args.by_key("child_name"))
@child.set_object_id(oid)
@agent.method_response(context, 0, "OK", args)
@@ -161,7 +160,7 @@ class App < Qmf::AgentHandler
@agent.set_connection(@connection)
- @parent = Qmf::QmfObject.new(@model.parent_class)
+ @parent = Qmf::AgentObject.new(@model.parent_class)
@parent.set_attr("name", "Parent One")
@parent.set_attr("state", "OPERATIONAL")
diff --git a/qpid/cpp/bindings/qmf/tests/python_agent.py b/qpid/cpp/bindings/qmf/tests/python_agent.py
index f6cb51cbf5..d4373d3bb8 100644
--- a/qpid/cpp/bindings/qmf/tests/python_agent.py
+++ b/qpid/cpp/bindings/qmf/tests/python_agent.py
@@ -72,7 +72,9 @@ class Model:
class App(qmf.AgentHandler):
def get_query(self, context, query, userId):
- # puts "Query: user=#{userId} context=#{context} class=#{query.class_name} object_num=#{query.object_id.object_num_low if query.object_id}"
+ #print "Query: user=%s context=%d class=%s" % (userId, context, query.class_name())
+ #if query.object_id():
+ # print query.object_id().object_num_low()
self._parent.inc_attr("queryCount")
if query.class_name() == 'parent':
self._agent.query_response(context, self._parent)
diff --git a/qpid/cpp/bindings/qmf/tests/ruby_console.rb b/qpid/cpp/bindings/qmf/tests/ruby_console.rb
index fb48c29566..c071829f09 100755
--- a/qpid/cpp/bindings/qmf/tests/ruby_console.rb
+++ b/qpid/cpp/bindings/qmf/tests/ruby_console.rb
@@ -24,33 +24,90 @@ require 'socket'
class App < Qmf::ConsoleHandler
- def main
- @settings = Qmf::ConnectionSettings.new
- @settings.set_attr("host", ARGV[0]) if ARGV.size > 0
- @settings.set_attr("port", ARGV[1].to_i) if ARGV.size > 1
- @connection = Qmf::Connection.new(@settings)
- @qmf = Qmf::Console.new
-
- @broker = @qmf.add_connection(@connection)
- @broker.waitForStable
-
- packages = @qmf.get_packages
+ def dump_schema
+ packages = @qmfc.get_packages
puts "----- Packages -----"
packages.each do |p|
puts p
puts " ----- Object Classes -----"
- classes = @qmf.get_classes(p)
+ classes = @qmfc.get_classes(p)
classes.each do |c|
puts " #{c.name}"
+
+ puts " ---- Properties ----"
+ props = c.properties
+ props.each do |prop|
+ puts " #{prop.name}"
+ end
+
+ puts " ---- Statistics ----"
+ stats = c.statistics
+ stats.each do |stat|
+ puts " #{stat.name}"
+ end
+
+ puts " ---- Methods ----"
+ methods = c.methods
+ methods.each do |method|
+ puts " #{method.name}"
+ puts " ---- Args ----"
+ args = method.arguments
+ args.each do |arg|
+ puts " #{arg.name}"
+ end
+ end
end
+
puts " ----- Event Classes -----"
- classes = @qmf.get_classes(p, Qmf::CLASS_EVENT)
+ classes = @qmfc.get_classes(p, Qmf::CLASS_EVENT)
classes.each do |c|
puts " #{c.name}"
+ puts " ---- Args ----"
+ args = c.arguments
+ args.each do |arg|
+ puts " #{arg.name}"
+ end
end
end
puts "-----"
+ end
+
+ def main
+ @settings = Qmf::ConnectionSettings.new
+ @settings.set_attr("host", ARGV[0]) if ARGV.size > 0
+ @settings.set_attr("port", ARGV[1].to_i) if ARGV.size > 1
+ @connection = Qmf::Connection.new(@settings)
+ @qmfc = Qmf::Console.new
+
+ @broker = @qmfc.add_connection(@connection)
+ @broker.waitForStable
+
+ dump_schema
+
+ agents = @qmfc.get_agents()
+ puts "---- Agents ----"
+ agents.each do |a|
+ puts " => #{a.label}"
+ end
+ puts "----"
+
+ for idx in 0...20
+ blist = @qmfc.get_objects(Qmf::Query.new(:class => "broker"))
+ puts "---- Brokers ----"
+ blist.each do |b|
+ puts " ---- Broker ----"
+ puts " systemRef: #{b.get_attr('systemRef')}"
+ puts " port : #{b.get_attr('port')}"
+ puts " uptime : #{b.get_attr('uptime') / 1000000000}"
+ end
+ puts "----"
+ sleep(5)
+ end
+ sleep(5)
+ puts "Deleting connection..."
+ @qmfc.del_connection(@broker)
+ puts " done"
sleep
end
end
diff --git a/qpid/cpp/include/qpid/messaging/Receiver.h b/qpid/cpp/include/qpid/messaging/Receiver.h
index e51e1093d1..a4fdd7a34b 100644
--- a/qpid/cpp/include/qpid/messaging/Receiver.h
+++ b/qpid/cpp/include/qpid/messaging/Receiver.h
@@ -40,7 +40,7 @@ class MessageListener;
class ReceiverImpl;
/**
- * A pull style interface for message retrieval.
+ * Interface through which messages are received.
*/
class Receiver : public qpid::client::Handle<ReceiverImpl>
{
@@ -75,7 +75,7 @@ class Receiver : public qpid::client::Handle<ReceiverImpl>
QPID_CLIENT_EXTERN bool fetch(Message& message, qpid::sys::Duration timeout=qpid::sys::TIME_INFINITE);
/**
* Retrieves a message for this receivers subscription or waits
- * for upto the specified timeout for one to become
+ * for up to the specified timeout for one to become
* available. Unlike get() this method will check with the server
* that there is no message for the subscription this receiver is
* serving before throwing an exception.
@@ -87,8 +87,8 @@ class Receiver : public qpid::client::Handle<ReceiverImpl>
*/
QPID_CLIENT_EXTERN void start();
/**
- * Stops the message flow for this receiver (without actually
- * cancelling the subscription).
+ * Stops the message flow for this receiver (but does not cancel
+ * the subscription).
*/
QPID_CLIENT_EXTERN void stop();
/**
@@ -97,14 +97,35 @@ class Receiver : public qpid::client::Handle<ReceiverImpl>
* requested by a client via fetch() (or pushed to a listener).
*/
QPID_CLIENT_EXTERN void setCapacity(uint32_t);
+ /**
+ * Returns the capacity of the receiver. The capacity determines
+ * how many incoming messages can be held in the receiver before
+ * being requested by a client via fetch() (or pushed to a
+ * listener).
+ */
+ QPID_CLIENT_EXTERN uint32_t getCapacity();
+ /**
+ * Returns the number of messages received and waiting to be
+ * fetched.
+ */
+ QPID_CLIENT_EXTERN uint32_t available();
+ /**
+ * Returns a count of the number of messages received on this
+ * receiver that have been acknowledged, but for which that
+ * acknowledgement has not yet been confirmed as processed by the
+ * server.
+ */
+ QPID_CLIENT_EXTERN uint32_t pendingAck();
/**
- * Cancels this receiver
+ * Cancels this receiver.
*/
QPID_CLIENT_EXTERN void cancel();
/**
- * Set a message listener for receiving messages asynchronously.
+ * Set a message listener for this receiver.
+ *
+ * @see Session::dispatch()
*/
QPID_CLIENT_EXTERN void setListener(MessageListener* listener);
private:
diff --git a/qpid/cpp/include/qpid/messaging/Sender.h b/qpid/cpp/include/qpid/messaging/Sender.h
index 45ec659ecf..9b83a04d60 100644
--- a/qpid/cpp/include/qpid/messaging/Sender.h
+++ b/qpid/cpp/include/qpid/messaging/Sender.h
@@ -23,6 +23,7 @@
*/
#include "qpid/client/ClientImportExport.h"
#include "qpid/client/Handle.h"
+#include "qpid/sys/IntegerTypes.h"
namespace qpid {
namespace client {
@@ -49,6 +50,24 @@ class Sender : public qpid::client::Handle<SenderImpl>
QPID_CLIENT_EXTERN void send(const Message& message);
QPID_CLIENT_EXTERN void cancel();
+
+ /**
+ * Sets the capacity for the sender. The capacity determines how
+ * many outgoing messages can be held pending confirmation of
+ * receipt by the broker.
+ */
+ QPID_CLIENT_EXTERN void setCapacity(uint32_t);
+ /**
+ * Returns the capacity of the sender.
+ * @see setCapacity
+ */
+ QPID_CLIENT_EXTERN uint32_t getCapacity();
+ /**
+ * Returns the number of sent messages pending confirmation of
+ * receipt by the broker. (These are the 'in-doubt' messages).
+ */
+ QPID_CLIENT_EXTERN uint32_t pending();
+
private:
friend class qpid::client::PrivateImplRef<Sender>;
};
diff --git a/qpid/cpp/include/qpid/messaging/Session.h b/qpid/cpp/include/qpid/messaging/Session.h
index 1d88882db6..979e27adae 100644
--- a/qpid/cpp/include/qpid/messaging/Session.h
+++ b/qpid/cpp/include/qpid/messaging/Session.h
@@ -75,6 +75,17 @@ class Session : public qpid::client::Handle<SessionImpl>
QPID_CLIENT_EXTERN void sync();
QPID_CLIENT_EXTERN void flush();
+ /**
+ * Returns the number of messages received and waiting to be
+ * fetched.
+ */
+ QPID_CLIENT_EXTERN uint32_t available();
+ /**
+ * Returns a count of the number of messages received this session
+ * that have been acknowledged, but for which that acknowledgement
+ * has not yet been confirmed as processed by the server.
+ */
+ QPID_CLIENT_EXTERN uint32_t pendingAck();
QPID_CLIENT_EXTERN bool fetch(Message& message, qpid::sys::Duration timeout=qpid::sys::TIME_INFINITE);
QPID_CLIENT_EXTERN Message fetch(qpid::sys::Duration timeout=qpid::sys::TIME_INFINITE);
QPID_CLIENT_EXTERN bool dispatch(qpid::sys::Duration timeout=qpid::sys::TIME_INFINITE);
@@ -88,9 +99,6 @@ class Session : public qpid::client::Handle<SessionImpl>
QPID_CLIENT_EXTERN Receiver createReceiver(const std::string& address, const Filter& filter, const VariantMap& options = VariantMap());
QPID_CLIENT_EXTERN Address createTempQueue(const std::string& baseName = std::string());
-
- QPID_CLIENT_EXTERN void* getLastConfirmedSent();
- QPID_CLIENT_EXTERN void* getLastConfirmedAcknowledged();
private:
friend class qpid::client::PrivateImplRef<Session>;
};
diff --git a/qpid/cpp/src/CMakeLists.txt b/qpid/cpp/src/CMakeLists.txt
index ff0188890b..786facced9 100644
--- a/qpid/cpp/src/CMakeLists.txt
+++ b/qpid/cpp/src/CMakeLists.txt
@@ -537,12 +537,12 @@ set (libqpidclient_SOURCES
qpid/messaging/Sender.cpp
qpid/messaging/SenderImpl.h
qpid/messaging/Variant.cpp
+ qpid/client/amqp0_10/AcceptTracker.h
+ qpid/client/amqp0_10/AcceptTracker.cpp
qpid/client/amqp0_10/AddressResolution.h
qpid/client/amqp0_10/AddressResolution.cpp
qpid/client/amqp0_10/Codecs.cpp
qpid/client/amqp0_10/CodecsInternal.h
- qpid/client/amqp0_10/CompletionTracker.h
- qpid/client/amqp0_10/CompletionTracker.cpp
qpid/client/amqp0_10/ConnectionImpl.h
qpid/client/amqp0_10/ConnectionImpl.cpp
qpid/client/amqp0_10/IncomingMessages.h
diff --git a/qpid/cpp/src/Makefile.am b/qpid/cpp/src/Makefile.am
index 75cda31dbb..4988f3f031 100644
--- a/qpid/cpp/src/Makefile.am
+++ b/qpid/cpp/src/Makefile.am
@@ -697,14 +697,14 @@ libqpidclient_la_SOURCES = \
qpid/messaging/SenderImpl.h \
qpid/messaging/ReceiverImpl.h \
qpid/messaging/SessionImpl.h \
+ qpid/client/amqp0_10/AcceptTracker.h \
+ qpid/client/amqp0_10/AcceptTracker.cpp \
qpid/client/amqp0_10/AddressResolution.h \
qpid/client/amqp0_10/AddressResolution.cpp \
qpid/client/amqp0_10/Codecs.cpp \
qpid/client/amqp0_10/CodecsInternal.h \
qpid/client/amqp0_10/ConnectionImpl.h \
qpid/client/amqp0_10/ConnectionImpl.cpp \
- qpid/client/amqp0_10/CompletionTracker.h \
- qpid/client/amqp0_10/CompletionTracker.cpp \
qpid/client/amqp0_10/IncomingMessages.h \
qpid/client/amqp0_10/IncomingMessages.cpp \
qpid/client/amqp0_10/MessageSink.h \
diff --git a/qpid/cpp/src/qmf/AgentEngine.cpp b/qpid/cpp/src/qmf/AgentEngine.cpp
index d3204042d5..9ea3be5907 100644
--- a/qpid/cpp/src/qmf/AgentEngine.cpp
+++ b/qpid/cpp/src/qmf/AgentEngine.cpp
@@ -57,7 +57,7 @@ namespace qmf {
string name;
Object* object;
boost::shared_ptr<ObjectId> objectId;
- Query query;
+ boost::shared_ptr<Query> query;
boost::shared_ptr<Value> arguments;
string exchange;
string bindingKey;
@@ -214,7 +214,7 @@ AgentEvent AgentEventImpl::copy()
item.sequence = sequence;
item.object = object;
item.objectId = objectId.get();
- item.query = &query;
+ item.query = query.get();
item.arguments = arguments.get();
item.objectClass = objectClass;
@@ -381,7 +381,7 @@ void AgentEngineImpl::methodResponse(uint32_t sequence, uint32_t status, char* t
}
}
sendBufferLH(buffer, context->exchange, context->key);
- QPID_LOG(trace, "SENT MethodResponse");
+ QPID_LOG(trace, "SENT MethodResponse seq=" << context->sequence << " status=" << status << " text=" << text);
}
void AgentEngineImpl::queryResponse(uint32_t sequence, Object& object, bool prop, bool stat)
@@ -403,7 +403,7 @@ void AgentEngineImpl::queryResponse(uint32_t sequence, Object& object, bool prop
object.impl->encodeStatistics(buffer);
sendBufferLH(buffer, context->exchange, context->key);
- QPID_LOG(trace, "SENT ContentIndication");
+ QPID_LOG(trace, "SENT ContentIndication seq=" << context->sequence);
}
void AgentEngineImpl::queryComplete(uint32_t sequence)
@@ -511,9 +511,10 @@ AgentEventImpl::Ptr AgentEngineImpl::eventQuery(uint32_t num, const string& user
AgentEventImpl::Ptr event(new AgentEventImpl(AgentEvent::GET_QUERY));
event->sequence = num;
event->authUserId = userId;
- event->query.impl->packageName = package;
- event->query.impl->className = cls;
- event->query.impl->oid = oid;
+ if (oid.get())
+ event->query.reset(new Query(oid.get()));
+ else
+ event->query.reset(new Query(cls.c_str(), package.c_str()));
return event;
}
@@ -723,7 +724,7 @@ void AgentEngineImpl::handleGetQuery(Buffer& inBuffer, uint32_t sequence, const
ft.decode(inBuffer);
- QPID_LOG(trace, "RCVD GetQuery: map=" << ft);
+ QPID_LOG(trace, "RCVD GetQuery: seq=" << sequence << " map=" << ft);
value = ft.get("_package");
if (value.get() && value->convertsTo<string>()) {
@@ -773,6 +774,8 @@ void AgentEngineImpl::handleMethodRequest(Buffer& buffer, uint32_t sequence, con
AgentClassKey classKey(buffer);
buffer.getShortString(method);
+ QPID_LOG(trace, "RCVD MethodRequest seq=" << sequence << " method=" << method);
+
map<string, ClassMaps>::const_iterator pIter = packages.find(pname);
if (pIter == packages.end()) {
sendMethodErrorLH(sequence, replyTo, MERR_UNKNOWN_PACKAGE, pname);
diff --git a/qpid/cpp/src/qmf/ConsoleEngine.cpp b/qpid/cpp/src/qmf/ConsoleEngine.cpp
index 3d1b378b68..e7991328ee 100644
--- a/qpid/cpp/src/qmf/ConsoleEngine.cpp
+++ b/qpid/cpp/src/qmf/ConsoleEngine.cpp
@@ -34,6 +34,7 @@
#include <qpid/sys/Mutex.h>
#include <qpid/log/Statement.h>
#include <qpid/sys/Time.h>
+#include <qpid/sys/SystemInfo.h>
#include <string.h>
#include <string>
#include <deque>
@@ -58,12 +59,27 @@ namespace qmf {
auto_ptr<Value> arguments;
MethodResponseImpl(Buffer& buf);
- ~MethodResponseImpl() {}
+ ~MethodResponseImpl() { delete envelope; }
uint32_t getStatus() const { return status; }
const Value* getException() const { return exception.get(); }
const Value* getArgs() const { return arguments.get(); }
};
+ struct QueryResponseImpl {
+ typedef boost::shared_ptr<QueryResponseImpl> Ptr;
+ QueryResponse *envelope;
+ uint32_t status;
+ auto_ptr<Value> exception;
+ vector<ObjectImpl::Ptr> results;
+
+ QueryResponseImpl() : envelope(new QueryResponse(this)), status(0) {}
+ ~QueryResponseImpl() { delete envelope; }
+ uint32_t getStatus() const { return status; }
+ const Value* getException() const { return exception.get(); }
+ uint32_t getObjectCount() const { return results.size(); }
+ const Object* getObject(uint32_t idx) const;
+ };
+
struct ConsoleEventImpl {
typedef boost::shared_ptr<ConsoleEventImpl> Ptr;
ConsoleEvent::EventKind kind;
@@ -89,13 +105,29 @@ namespace qmf {
string name;
string exchange;
string bindingKey;
+ void* context;
+ QueryResponseImpl::Ptr queryResponse;
BrokerEventImpl(BrokerEvent::EventKind k) : kind(k) {}
~BrokerEventImpl() {}
BrokerEvent copy();
};
- class BrokerProxyImpl : public SequenceContext {
+ struct AgentProxyImpl {
+ typedef boost::shared_ptr<AgentProxyImpl> Ptr;
+ AgentProxy* envelope;
+ ConsoleEngineImpl* console;
+ BrokerProxyImpl* broker;
+ uint32_t agentBank;
+ string label;
+
+ AgentProxyImpl(ConsoleEngineImpl* c, BrokerProxyImpl* b, uint32_t ab, const string& l) :
+ envelope(new AgentProxy(this)), console(c), broker(b), agentBank(ab), label(l) {}
+ ~AgentProxyImpl() {}
+ const string& getLabel() const { return label; }
+ };
+
+ class BrokerProxyImpl {
public:
typedef boost::shared_ptr<BrokerProxyImpl> Ptr;
@@ -114,12 +146,17 @@ namespace qmf {
bool getEvent(BrokerEvent& event) const;
void popEvent();
- // From SequenceContext
- void complete();
+ uint32_t agentCount() const;
+ const AgentProxy* getAgent(uint32_t idx) const;
+ void sendQuery(const Query& query, void* context, const AgentProxy* agent);
+ void sendGetRequestLH(SequenceContext::Ptr queryContext, const Query& query, const AgentProxyImpl* agent);
void addBinding(const string& exchange, const string& key);
+ void staticRelease() { decOutstanding(); }
private:
+ friend class StaticContext;
+ friend class QueryContext;
mutable Mutex lock;
BrokerProxy* envelope;
ConsoleEngineImpl* console;
@@ -128,6 +165,7 @@ namespace qmf {
SequenceManager seqMgr;
uint32_t requestsOutstanding;
bool topicBound;
+ vector<AgentProxyImpl::Ptr> agentList;
deque<MessageImpl::Ptr> xmtQueue;
deque<BrokerEventImpl::Ptr> eventQueue;
@@ -138,6 +176,7 @@ namespace qmf {
BrokerEventImpl::Ptr eventBind(const string& exchange, const string& queue, const string& key);
BrokerEventImpl::Ptr eventSetupComplete();
BrokerEventImpl::Ptr eventStable();
+ BrokerEventImpl::Ptr eventQueryComplete(void* context, QueryResponseImpl::Ptr response);
void handleBrokerResponse(Buffer& inBuffer, uint32_t seq);
void handlePackageIndication(Buffer& inBuffer, uint32_t seq);
@@ -147,19 +186,33 @@ namespace qmf {
void handleHeartbeatIndication(Buffer& inBuffer, uint32_t seq);
void handleEventIndication(Buffer& inBuffer, uint32_t seq);
void handleSchemaResponse(Buffer& inBuffer, uint32_t seq);
- void handleObjectIndication(Buffer& inBuffer, uint32_t seq, bool prop, bool stat);
+ ObjectImpl::Ptr handleObjectIndication(Buffer& inBuffer, uint32_t seq, bool prop, bool stat);
void incOutstandingLH();
void decOutstanding();
};
- struct AgentProxyImpl {
- typedef boost::shared_ptr<AgentProxyImpl> Ptr;
- AgentProxy* envelope;
- ConsoleEngineImpl* console;
+ struct StaticContext : public SequenceContext {
+ StaticContext(BrokerProxyImpl& b) : broker(b) {}
+ ~StaticContext() {}
+ void reserve() {}
+ void release() { broker.staticRelease(); }
+ bool handleMessage(uint8_t opcode, uint32_t sequence, Buffer& buffer);
+ BrokerProxyImpl& broker;
+ };
- AgentProxyImpl(AgentProxy* e, ConsoleEngine& _console) :
- envelope(e), console(_console.impl) {}
- ~AgentProxyImpl() {}
+ struct QueryContext : public SequenceContext {
+ QueryContext(BrokerProxyImpl& b, void* u) :
+ broker(b), userContext(u), requestsOutstanding(0), queryResponse(new QueryResponseImpl()) {}
+ ~QueryContext() {}
+ void reserve();
+ void release();
+ bool handleMessage(uint8_t opcode, uint32_t sequence, Buffer& buffer);
+
+ mutable Mutex lock;
+ BrokerProxyImpl& broker;
+ void* userContext;
+ uint32_t requestsOutstanding;
+ QueryResponseImpl::Ptr queryResponse;
};
class ConsoleEngineImpl {
@@ -187,11 +240,6 @@ namespace qmf {
void bindClass(const SchemaClassKey* key);
void bindClass(const char* packageName, const char* className);
- uint32_t agentCount() const;
- const AgentProxy* getAgent(uint32_t idx) const;
-
- void sendQuery(const Query& query, void* context);
-
/*
void startSync(const Query& query, void* context, SyncQuery& sync);
void touchSync(SyncQuery& sync);
@@ -226,13 +274,31 @@ namespace qmf {
void learnClass(SchemaObjectClassImpl::Ptr cls);
void learnClass(SchemaEventClassImpl::Ptr cls);
bool haveClass(const SchemaClassKeyImpl& key) const;
+ SchemaObjectClassImpl::Ptr getSchema(const SchemaClassKeyImpl& key) const;
};
}
namespace {
-const char* QMF_EXCHANGE = "qpid.management";
-const char* DIR_EXCHANGE = "amq.direct";
-const char* BROKER_KEY = "broker";
+ const char* QMF_EXCHANGE = "qpid.management";
+ const char* DIR_EXCHANGE = "amq.direct";
+ const char* BROKER_KEY = "broker";
+ const char* BROKER_PACKAGE = "org.apache.qpid.broker";
+ const char* AGENT_CLASS = "agent";
+ const char* BROKER_AGENT_KEY = "agent.1.0";
+}
+
+const Object* QueryResponseImpl::getObject(uint32_t idx) const
+{
+ vector<ObjectImpl::Ptr>::const_iterator iter = results.begin();
+
+ while (idx > 0) {
+ if (iter == results.end())
+ return 0;
+ iter++;
+ idx--;
+ }
+
+ return (*iter)->envelope;
}
#define STRING_REF(s) {if (!s.empty()) item.s = const_cast<char*>(s.c_str());}
@@ -267,19 +333,29 @@ BrokerEvent BrokerEventImpl::copy()
STRING_REF(name);
STRING_REF(exchange);
STRING_REF(bindingKey);
+ item.context = context;
+ item.queryResponse = queryResponse.get() ? queryResponse->envelope : 0;
return item;
}
BrokerProxyImpl::BrokerProxyImpl(BrokerProxy* e, ConsoleEngine& _console) :
- envelope(e), console(_console.impl), queueName("qmfc-")
+ envelope(e), console(_console.impl)
{
- // TODO: Give the queue name a unique suffix
+ stringstream qn;
+ qpid::TcpAddress addr;
+
+ SystemInfo::getLocalHostname(addr);
+ qn << "qmfc-" << SystemInfo::getProcessName() << "-" << addr << "-" << SystemInfo::getProcessId();
+ queueName = qn.str();
+
+ seqMgr.setUnsolicitedContext(SequenceContext::Ptr(new StaticContext(*this)));
}
void BrokerProxyImpl::sessionOpened(SessionHandle& /*sh*/)
{
Mutex::ScopedLock _lock(lock);
+ agentList.clear();
eventQueue.clear();
xmtQueue.clear();
eventQueue.push_back(eventDeclareQueue(queueName));
@@ -292,6 +368,7 @@ void BrokerProxyImpl::sessionOpened(SessionHandle& /*sh*/)
void BrokerProxyImpl::sessionClosed()
{
Mutex::ScopedLock _lock(lock);
+ agentList.clear();
eventQueue.clear();
xmtQueue.clear();
}
@@ -302,11 +379,14 @@ void BrokerProxyImpl::startProtocol()
char rawbuffer[512];
Buffer buffer(rawbuffer, 512);
+ agentList.push_back(AgentProxyImpl::Ptr(new AgentProxyImpl(console, this, 0, "Agent embedded in broker")));
+
requestsOutstanding = 1;
topicBound = false;
- Protocol::encodeHeader(buffer, Protocol::OP_BROKER_REQUEST);
+ uint32_t sequence(seqMgr.reserve());
+ Protocol::encodeHeader(buffer, Protocol::OP_BROKER_REQUEST, sequence);
sendBufferLH(buffer, QMF_EXCHANGE, BROKER_KEY);
- QPID_LOG(trace, "SENT BrokerRequest");
+ QPID_LOG(trace, "SENT BrokerRequest seq=" << sequence);
}
void BrokerProxyImpl::sendBufferLH(Buffer& buf, const string& destination, const string& routingKey)
@@ -330,23 +410,8 @@ void BrokerProxyImpl::handleRcvMessage(Message& message)
uint8_t opcode;
uint32_t sequence;
- while (Protocol::checkHeader(inBuffer, &opcode, &sequence)) {
- if (opcode == Protocol::OP_BROKER_RESPONSE) handleBrokerResponse(inBuffer, sequence);
- else if (opcode == Protocol::OP_PACKAGE_INDICATION) handlePackageIndication(inBuffer, sequence);
- else if (opcode == Protocol::OP_COMMAND_COMPLETE) handleCommandComplete(inBuffer, sequence);
- else if (opcode == Protocol::OP_CLASS_INDICATION) handleClassIndication(inBuffer, sequence);
- else if (opcode == Protocol::OP_METHOD_RESPONSE) handleMethodResponse(inBuffer, sequence);
- else if (opcode == Protocol::OP_HEARTBEAT_INDICATION) handleHeartbeatIndication(inBuffer, sequence);
- else if (opcode == Protocol::OP_EVENT_INDICATION) handleEventIndication(inBuffer, sequence);
- else if (opcode == Protocol::OP_SCHEMA_RESPONSE) handleSchemaResponse(inBuffer, sequence);
- else if (opcode == Protocol::OP_PROPERTY_INDICATION) handleObjectIndication(inBuffer, sequence, true, false);
- else if (opcode == Protocol::OP_STATISTIC_INDICATION) handleObjectIndication(inBuffer, sequence, false, true);
- else if (opcode == Protocol::OP_OBJECT_INDICATION) handleObjectIndication(inBuffer, sequence, true, true);
- else {
- QPID_LOG(trace, "BrokerProxyImpl::handleRcvMessage invalid opcode: " << opcode);
- break;
- }
- }
+ while (Protocol::checkHeader(inBuffer, &opcode, &sequence))
+ seqMgr.dispatch(opcode, sequence, inBuffer);
}
bool BrokerProxyImpl::getXmtMessage(Message& item) const
@@ -381,9 +446,48 @@ void BrokerProxyImpl::popEvent()
eventQueue.pop_front();
}
-void BrokerProxyImpl::complete()
+uint32_t BrokerProxyImpl::agentCount() const
{
- decOutstanding();
+ Mutex::ScopedLock _lock(lock);
+ return agentList.size();
+}
+
+const AgentProxy* BrokerProxyImpl::getAgent(uint32_t idx) const
+{
+ Mutex::ScopedLock _lock(lock);
+ for (vector<AgentProxyImpl::Ptr>::const_iterator iter = agentList.begin();
+ iter != agentList.end(); iter++)
+ if (idx-- == 0)
+ return (*iter)->envelope;
+ return 0;
+}
+
+void BrokerProxyImpl::sendQuery(const Query& query, void* context, const AgentProxy* agent)
+{
+ SequenceContext::Ptr queryContext(new QueryContext(*this, context));
+ Mutex::ScopedLock _lock(lock);
+ if (agent != 0) {
+ sendGetRequestLH(queryContext, query, agent->impl);
+ } else {
+ // TODO (optimization) only send queries to agents that have the requested class+package
+ for (vector<AgentProxyImpl::Ptr>::const_iterator iter = agentList.begin();
+ iter != agentList.end(); iter++) {
+ sendGetRequestLH(queryContext, query, (*iter).get());
+ }
+ }
+}
+
+void BrokerProxyImpl::sendGetRequestLH(SequenceContext::Ptr queryContext, const Query& query, const AgentProxyImpl* agent)
+{
+ stringstream key;
+ Buffer outBuffer(outputBuffer, MA_BUFFER_SIZE);
+ uint32_t sequence(seqMgr.reserve(queryContext));
+
+ Protocol::encodeHeader(outBuffer, Protocol::OP_GET_QUERY, sequence);
+ query.impl->encode(outBuffer);
+ key << "agent.1." << agent->agentBank;
+ sendBufferLH(outBuffer, QMF_EXCHANGE, key.str());
+ QPID_LOG(trace, "SENT GetQuery seq=" << sequence << " key=" << key.str());
}
void BrokerProxyImpl::addBinding(const string& exchange, const string& key)
@@ -420,17 +524,22 @@ BrokerEventImpl::Ptr BrokerProxyImpl::eventStable()
return event;
}
-void BrokerProxyImpl::handleBrokerResponse(Buffer& inBuffer, uint32_t seq)
+BrokerEventImpl::Ptr BrokerProxyImpl::eventQueryComplete(void* context, QueryResponseImpl::Ptr response)
{
- // Note that this function doesn't touch requestsOutstanding. This is because
- // it accounts for one request completed (the BrokerRequest) and one request
- // started (the PackageRequest) which cancel each other out.
+ BrokerEventImpl::Ptr event(new BrokerEventImpl(BrokerEvent::QUERY_COMPLETE));
+ event->context = context;
+ event->queryResponse = response;
+ return event;
+}
+void BrokerProxyImpl::handleBrokerResponse(Buffer& inBuffer, uint32_t seq)
+{
brokerId.decode(inBuffer);
QPID_LOG(trace, "RCVD BrokerResponse seq=" << seq << " brokerId=" << brokerId);
Mutex::ScopedLock _lock(lock);
Buffer outBuffer(outputBuffer, MA_BUFFER_SIZE);
- uint32_t sequence(seqMgr.reserve(this));
+ uint32_t sequence(seqMgr.reserve());
+ incOutstandingLH();
Protocol::encodeHeader(outBuffer, Protocol::OP_PACKAGE_REQUEST, sequence);
sendBufferLH(outBuffer, QMF_EXCHANGE, BROKER_KEY);
QPID_LOG(trace, "SENT PackageRequest seq=" << sequence);
@@ -446,7 +555,7 @@ void BrokerProxyImpl::handlePackageIndication(Buffer& inBuffer, uint32_t seq)
Mutex::ScopedLock _lock(lock);
Buffer outBuffer(outputBuffer, MA_BUFFER_SIZE);
- uint32_t sequence(seqMgr.reserve(this));
+ uint32_t sequence(seqMgr.reserve());
incOutstandingLH();
Protocol::encodeHeader(outBuffer, Protocol::OP_CLASS_QUERY, sequence);
outBuffer.putShortString(package);
@@ -460,20 +569,12 @@ void BrokerProxyImpl::handleCommandComplete(Buffer& inBuffer, uint32_t seq)
uint32_t code = inBuffer.getLong();
inBuffer.getShortString(text);
QPID_LOG(trace, "RCVD CommandComplete seq=" << seq << " code=" << code << " text=" << text);
- seqMgr.release(seq);
}
void BrokerProxyImpl::handleClassIndication(Buffer& inBuffer, uint32_t seq)
{
- string package;
- string clsName;
- SchemaHash hash;
uint8_t kind = inBuffer.getOctet();
- inBuffer.getShortString(package);
- inBuffer.getShortString(clsName);
- hash.decode(inBuffer);
- Uuid printableHash(hash.get());
- SchemaClassKeyImpl classKey(package, clsName, hash);
+ SchemaClassKeyImpl classKey(inBuffer);
QPID_LOG(trace, "RCVD ClassIndication seq=" << seq << " kind=" << (int) kind << " key=" << classKey.str());
@@ -481,7 +582,7 @@ void BrokerProxyImpl::handleClassIndication(Buffer& inBuffer, uint32_t seq)
Mutex::ScopedLock _lock(lock);
incOutstandingLH();
Buffer outBuffer(outputBuffer, MA_BUFFER_SIZE);
- uint32_t sequence(seqMgr.reserve(this));
+ uint32_t sequence(seqMgr.reserve());
Protocol::encodeHeader(outBuffer, Protocol::OP_SCHEMA_REQUEST, sequence);
classKey.encode(outBuffer);
sendBufferLH(outBuffer, QMF_EXCHANGE, BROKER_KEY);
@@ -515,6 +616,25 @@ void BrokerProxyImpl::handleSchemaResponse(Buffer& inBuffer, uint32_t seq)
console->learnClass(oClassPtr);
key = oClassPtr->getClassKey()->impl;
QPID_LOG(trace, "RCVD SchemaResponse seq=" << seq << " kind=object key=" << key->str());
+
+ //
+ // If we have just learned about the org.apache.qpid.broker:agent class, send a get
+ // request for the current list of agents so we can have it on-hand before we declare
+ // this session "stable".
+ //
+ if (key->getClassName() == AGENT_CLASS && key->getPackageName() == BROKER_PACKAGE) {
+ Mutex::ScopedLock _lock(lock);
+ incOutstandingLH();
+ Buffer outBuffer(outputBuffer, MA_BUFFER_SIZE);
+ uint32_t sequence(seqMgr.reserve());
+ Protocol::encodeHeader(outBuffer, Protocol::OP_GET_QUERY, sequence);
+ FieldTable ft;
+ ft.setString("_class", AGENT_CLASS);
+ ft.setString("_package", BROKER_PACKAGE);
+ ft.encode(outBuffer);
+ sendBufferLH(outBuffer, QMF_EXCHANGE, BROKER_AGENT_KEY);
+ QPID_LOG(trace, "SENT GetQuery seq=" << sequence << " key=" << BROKER_AGENT_KEY);
+ }
} else if (kind == CLASS_EVENT) {
eClassPtr.reset(new SchemaEventClassImpl(inBuffer));
console->learnClass(eClassPtr);
@@ -524,13 +644,20 @@ void BrokerProxyImpl::handleSchemaResponse(Buffer& inBuffer, uint32_t seq)
else {
QPID_LOG(error, "BrokerProxyImpl::handleSchemaResponse received unknown class kind: " << (int) kind);
}
-
- decOutstanding();
}
-void BrokerProxyImpl::handleObjectIndication(Buffer& /*inBuffer*/, uint32_t /*seq*/, bool /*prop*/, bool /*stat*/)
+ObjectImpl::Ptr BrokerProxyImpl::handleObjectIndication(Buffer& inBuffer, uint32_t seq, bool prop, bool stat)
{
- // TODO
+ SchemaClassKeyImpl classKey(inBuffer);
+ QPID_LOG(trace, "RCVD ObjectIndication seq=" << seq << " key=" << classKey.str());
+
+ SchemaObjectClassImpl::Ptr schema = console->getSchema(classKey);
+ if (schema.get() == 0) {
+ QPID_LOG(trace, "No Schema Found for ObjectIndication. seq=" << seq << " key=" << classKey.str());
+ return ObjectImpl::Ptr();
+ }
+
+ return ObjectImpl::Ptr(new ObjectImpl(schema->envelope, inBuffer, prop, stat, true));
}
void BrokerProxyImpl::incOutstandingLH()
@@ -567,6 +694,79 @@ MethodResponseImpl::MethodResponseImpl(Buffer& buf) : envelope(new MethodRespons
arguments.reset(new Value(TYPE_MAP));
}
+bool StaticContext::handleMessage(uint8_t opcode, uint32_t sequence, Buffer& buffer)
+{
+ bool completeContext = false;
+ if (opcode == Protocol::OP_BROKER_RESPONSE) {
+ broker.handleBrokerResponse(buffer, sequence);
+ completeContext = true;
+ }
+ else if (opcode == Protocol::OP_COMMAND_COMPLETE) {
+ broker.handleCommandComplete(buffer, sequence);
+ completeContext = true;
+ }
+ else if (opcode == Protocol::OP_SCHEMA_RESPONSE) {
+ broker.handleSchemaResponse(buffer, sequence);
+ completeContext = true;
+ }
+ else if (opcode == Protocol::OP_PACKAGE_INDICATION)
+ broker.handlePackageIndication(buffer, sequence);
+ else if (opcode == Protocol::OP_CLASS_INDICATION)
+ broker.handleClassIndication(buffer, sequence);
+ else if (opcode == Protocol::OP_HEARTBEAT_INDICATION)
+ broker.handleHeartbeatIndication(buffer, sequence);
+ else if (opcode == Protocol::OP_EVENT_INDICATION)
+ broker.handleEventIndication(buffer, sequence);
+ else if (opcode == Protocol::OP_PROPERTY_INDICATION)
+ broker.handleObjectIndication(buffer, sequence, true, false);
+ else if (opcode == Protocol::OP_STATISTIC_INDICATION)
+ broker.handleObjectIndication(buffer, sequence, false, true);
+ else if (opcode == Protocol::OP_OBJECT_INDICATION)
+ broker.handleObjectIndication(buffer, sequence, true, true);
+ else {
+ QPID_LOG(trace, "StaticContext::handleMessage invalid opcode: " << opcode);
+ completeContext = true;
+ }
+
+ return completeContext;
+}
+
+void QueryContext::reserve()
+{
+ Mutex::ScopedLock _lock(lock);
+ requestsOutstanding++;
+}
+
+void QueryContext::release()
+{
+ Mutex::ScopedLock _lock(lock);
+ if (--requestsOutstanding == 0) {
+ broker.eventQueue.push_back(broker.eventQueryComplete(userContext, queryResponse));
+ }
+}
+
+bool QueryContext::handleMessage(uint8_t opcode, uint32_t sequence, Buffer& buffer)
+{
+ bool completeContext = false;
+ ObjectImpl::Ptr object;
+
+ if (opcode == Protocol::OP_COMMAND_COMPLETE) {
+ broker.handleCommandComplete(buffer, sequence);
+ completeContext = true;
+ }
+ else if (opcode == Protocol::OP_OBJECT_INDICATION) {
+ object = broker.handleObjectIndication(buffer, sequence, true, true);
+ if (object.get() != 0)
+ queryResponse->results.push_back(object);
+ }
+ else {
+ QPID_LOG(trace, "QueryContext::handleMessage invalid opcode: " << opcode);
+ completeContext = true;
+ }
+
+ return completeContext;
+}
+
ConsoleEngineImpl::ConsoleEngineImpl(ConsoleEngine* e, const ConsoleSettings& s) :
envelope(e), settings(s)
{
@@ -757,23 +957,6 @@ void ConsoleEngineImpl::bindClass(const char* packageName, const char* className
(*iter)->addBinding(QMF_EXCHANGE, key.str());
}
-uint32_t ConsoleEngineImpl::agentCount() const
-{
- // TODO
- return 0;
-}
-
-const AgentProxy* ConsoleEngineImpl::getAgent(uint32_t /*idx*/) const
-{
- // TODO
- return 0;
-}
-
-void ConsoleEngineImpl::sendQuery(const Query& /*query*/, void* /*context*/)
-{
- // TODO
-}
-
/*
void ConsoleEngineImpl::startSync(const Query& query, void* context, SyncQuery& sync)
{
@@ -835,11 +1018,29 @@ bool ConsoleEngineImpl::haveClass(const SchemaClassKeyImpl& key) const
return oList.find(&key) != oList.end() || eList.find(&key) != eList.end();
}
+SchemaObjectClassImpl::Ptr ConsoleEngineImpl::getSchema(const SchemaClassKeyImpl& key) const
+{
+ Mutex::ScopedLock _lock(lock);
+ PackageList::const_iterator pIter = packages.find(key.getPackageName());
+ if (pIter == packages.end())
+ return SchemaObjectClassImpl::Ptr();
+
+ const ObjectClassList& oList = pIter->second.first;
+ ObjectClassList::const_iterator iter = oList.find(&key);
+ if (iter == oList.end())
+ return SchemaObjectClassImpl::Ptr();
+
+ return iter->second;
+}
//==================================================================
// Wrappers
//==================================================================
+AgentProxy::AgentProxy(AgentProxyImpl* i) : impl(i) {}
+AgentProxy::~AgentProxy() { delete impl; }
+const char* AgentProxy::getLabel() const { return impl->getLabel().c_str(); }
+
BrokerProxy::BrokerProxy(ConsoleEngine& console) : impl(new BrokerProxyImpl(this, console)) {}
BrokerProxy::~BrokerProxy() { delete impl; }
void BrokerProxy::sessionOpened(SessionHandle& sh) { impl->sessionOpened(sh); }
@@ -850,16 +1051,23 @@ bool BrokerProxy::getXmtMessage(Message& item) const { return impl->getXmtMessag
void BrokerProxy::popXmt() { impl->popXmt(); }
bool BrokerProxy::getEvent(BrokerEvent& event) const { return impl->getEvent(event); }
void BrokerProxy::popEvent() { impl->popEvent(); }
-
-AgentProxy::AgentProxy(ConsoleEngine& console) : impl(new AgentProxyImpl(this, console)) {}
-AgentProxy::~AgentProxy() { delete impl; }
+uint32_t BrokerProxy::agentCount() const { return impl->agentCount(); }
+const AgentProxy* BrokerProxy::getAgent(uint32_t idx) const { return impl->getAgent(idx); }
+void BrokerProxy::sendQuery(const Query& query, void* context, const AgentProxy* agent) { impl->sendQuery(query, context, agent); }
MethodResponse::MethodResponse(MethodResponseImpl* i) : impl(i) {}
-MethodResponse::~MethodResponse() { delete impl; } // TODO: correct to delete here?
+MethodResponse::~MethodResponse() {}
uint32_t MethodResponse::getStatus() const { return impl->getStatus(); }
const Value* MethodResponse::getException() const { return impl->getException(); }
const Value* MethodResponse::getArgs() const { return impl->getArgs(); }
+QueryResponse::QueryResponse(QueryResponseImpl* i) : impl(i) {}
+QueryResponse::~QueryResponse() {}
+uint32_t QueryResponse::getStatus() const { return impl->getStatus(); }
+const Value* QueryResponse::getException() const { return impl->getException(); }
+uint32_t QueryResponse::getObjectCount() const { return impl->getObjectCount(); }
+const Object* QueryResponse::getObject(uint32_t idx) const { return impl->getObject(idx); }
+
ConsoleEngine::ConsoleEngine(const ConsoleSettings& settings) : impl(new ConsoleEngineImpl(this, settings)) {}
ConsoleEngine::~ConsoleEngine() { delete impl; }
bool ConsoleEngine::getEvent(ConsoleEvent& event) const { return impl->getEvent(event); }
@@ -876,9 +1084,6 @@ const SchemaEventClass* ConsoleEngine::getEventClass(const SchemaClassKey* key)
void ConsoleEngine::bindPackage(const char* packageName) { impl->bindPackage(packageName); }
void ConsoleEngine::bindClass(const SchemaClassKey* key) { impl->bindClass(key); }
void ConsoleEngine::bindClass(const char* packageName, const char* className) { impl->bindClass(packageName, className); }
-uint32_t ConsoleEngine::agentCount() const { return impl->agentCount(); }
-const AgentProxy* ConsoleEngine::getAgent(uint32_t idx) const { return impl->getAgent(idx); }
-void ConsoleEngine::sendQuery(const Query& query, void* context) { impl->sendQuery(query, context); }
//void ConsoleEngine::startSync(const Query& query, void* context, SyncQuery& sync) { impl->startSync(query, context, sync); }
//void ConsoleEngine::touchSync(SyncQuery& sync) { impl->touchSync(sync); }
//void ConsoleEngine::endSync(SyncQuery& sync) { impl->endSync(sync); }
diff --git a/qpid/cpp/src/qmf/ConsoleEngine.h b/qpid/cpp/src/qmf/ConsoleEngine.h
index 84ac78cd69..457e83ad58 100644
--- a/qpid/cpp/src/qmf/ConsoleEngine.h
+++ b/qpid/cpp/src/qmf/ConsoleEngine.h
@@ -37,6 +37,8 @@ namespace qmf {
class AgentProxy;
class AgentProxyImpl;
class MethodResponseImpl;
+ class QueryResponseImpl;
+ class QueryContext;
/**
*
@@ -57,6 +59,23 @@ namespace qmf {
/**
*
*/
+ class QueryResponse {
+ public:
+ QueryResponse(QueryResponseImpl* impl);
+ ~QueryResponse();
+ uint32_t getStatus() const;
+ const Value* getException() const;
+ uint32_t getObjectCount() const;
+ const Object* getObject(uint32_t idx) const;
+
+ private:
+ friend class QueryContext;
+ QueryResponseImpl *impl;
+ };
+
+ /**
+ *
+ */
struct ConsoleEvent {
enum EventKind {
AGENT_ADDED = 1,
@@ -64,7 +83,6 @@ namespace qmf {
NEW_PACKAGE = 3,
NEW_CLASS = 4,
OBJECT_UPDATE = 5,
- QUERY_COMPLETE = 6,
EVENT_RECEIVED = 7,
AGENT_HEARTBEAT = 8,
METHOD_RESPONSE = 9
@@ -75,11 +93,12 @@ namespace qmf {
char* name; // (NEW_PACKAGE)
SchemaClassKey* classKey; // (NEW_CLASS)
Object* object; // (OBJECT_UPDATE)
- void* context; // (OBJECT_UPDATE, QUERY_COMPLETE)
+ void* context; // (OBJECT_UPDATE)
Event* event; // (EVENT_RECEIVED)
uint64_t timestamp; // (AGENT_HEARTBEAT)
uint32_t methodHandle; // (METHOD_RESPONSE)
MethodResponse* methodResponse; // (METHOD_RESPONSE)
+ QueryResponse* queryResponse; // (QUERY_COMPLETE)
};
/**
@@ -93,13 +112,30 @@ namespace qmf {
BIND = 13,
UNBIND = 14,
SETUP_COMPLETE = 15,
- STABLE = 16
+ STABLE = 16,
+ QUERY_COMPLETE = 17
};
EventKind kind;
- char* name; // ([DECLARE|DELETE]_QUEUE, [UN]BIND)
- char* exchange; // ([UN]BIND)
- char* bindingKey; // ([UN]BIND)
+ char* name; // ([DECLARE|DELETE]_QUEUE, [UN]BIND)
+ char* exchange; // ([UN]BIND)
+ char* bindingKey; // ([UN]BIND)
+ void* context; // (QUERY_COMPLETE)
+ QueryResponse* queryResponse; // (QUERY_COMPLETE)
+ };
+
+ /**
+ *
+ */
+ class AgentProxy {
+ public:
+ AgentProxy(AgentProxyImpl* impl);
+ ~AgentProxy();
+ const char* getLabel() const;
+
+ private:
+ friend class BrokerProxyImpl;
+ AgentProxyImpl* impl;
};
/**
@@ -121,22 +157,13 @@ namespace qmf {
bool getEvent(BrokerEvent& event) const;
void popEvent();
- private:
- friend class ConsoleEngineImpl;
- BrokerProxyImpl* impl;
- };
-
- /**
- *
- */
- class AgentProxy {
- public:
- AgentProxy(ConsoleEngine& console);
- ~AgentProxy();
+ uint32_t agentCount() const;
+ const AgentProxy* getAgent(uint32_t idx) const;
+ void sendQuery(const Query& query, void* context, const AgentProxy* agent = 0);
private:
friend class ConsoleEngineImpl;
- AgentProxyImpl* impl;
+ BrokerProxyImpl* impl;
};
// TODO - move this to a public header
@@ -178,11 +205,6 @@ namespace qmf {
void bindClass(const SchemaClassKey* key);
void bindClass(const char* packageName, const char* className);
- uint32_t agentCount() const;
- const AgentProxy* getAgent(uint32_t idx) const;
-
- void sendQuery(const Query& query, void* context);
-
/*
void startSync(const Query& query, void* context, SyncQuery& sync);
void touchSync(SyncQuery& sync);
diff --git a/qpid/cpp/src/qmf/Object.h b/qpid/cpp/src/qmf/Object.h
index eb92cbbe45..9cb3224d9b 100644
--- a/qpid/cpp/src/qmf/Object.h
+++ b/qpid/cpp/src/qmf/Object.h
@@ -31,13 +31,14 @@ namespace qmf {
public:
Object(const SchemaObjectClass* type);
Object(ObjectImpl* impl);
+ Object(const Object& from);
virtual ~Object();
void destroy();
const ObjectId* getObjectId() const;
void setObjectId(ObjectId* oid);
const SchemaObjectClass* getClass() const;
- Value* getValue(char* key);
+ Value* getValue(char* key) const;
ObjectImpl* impl;
};
diff --git a/qpid/cpp/src/qmf/ObjectId.h b/qpid/cpp/src/qmf/ObjectId.h
index ffd1b6978b..e894e0b39c 100644
--- a/qpid/cpp/src/qmf/ObjectId.h
+++ b/qpid/cpp/src/qmf/ObjectId.h
@@ -30,6 +30,7 @@ namespace qmf {
class ObjectId {
public:
ObjectId();
+ ObjectId(const ObjectId& from);
ObjectId(ObjectIdImpl* impl);
~ObjectId();
diff --git a/qpid/cpp/src/qmf/ObjectIdImpl.cpp b/qpid/cpp/src/qmf/ObjectIdImpl.cpp
index 75661fdb47..c0618ccc49 100644
--- a/qpid/cpp/src/qmf/ObjectIdImpl.cpp
+++ b/qpid/cpp/src/qmf/ObjectIdImpl.cpp
@@ -100,6 +100,15 @@ void ObjectIdImpl::fromString(const std::string& repr)
agent = 0;
}
+std::string ObjectIdImpl::asString() const
+{
+ stringstream val;
+
+ val << getFlags() << "-" << getSequence() << "-" << getBrokerBank() << "-" <<
+ getAgentBank() << "-" << getObjectNum();
+ return val.str();
+}
+
bool ObjectIdImpl::operator==(const ObjectIdImpl& other) const
{
uint64_t otherFirst = agent == 0 ? other.first : other.first & 0xffff000000000000LL;
@@ -126,15 +135,11 @@ bool ObjectIdImpl::operator>(const ObjectIdImpl& other) const
// Wrappers
//==================================================================
-ObjectId::ObjectId()
-{
- impl = new ObjectIdImpl(this);
-}
+ObjectId::ObjectId() : impl(new ObjectIdImpl(this)) {}
-ObjectId::ObjectId(ObjectIdImpl* i)
-{
- impl = i;
-}
+ObjectId::ObjectId(const ObjectId& from) : impl(new ObjectIdImpl(*(from.impl))) {}
+
+ObjectId::ObjectId(ObjectIdImpl* i) : impl(i) {}
ObjectId::~ObjectId()
{
diff --git a/qpid/cpp/src/qmf/ObjectIdImpl.h b/qpid/cpp/src/qmf/ObjectIdImpl.h
index 5d8ee59aee..38d231237f 100644
--- a/qpid/cpp/src/qmf/ObjectIdImpl.h
+++ b/qpid/cpp/src/qmf/ObjectIdImpl.h
@@ -39,13 +39,14 @@ namespace qmf {
uint64_t first;
uint64_t second;
- ObjectIdImpl(ObjectId* e) : envelope(e), agent(0) {}
+ ObjectIdImpl(ObjectId* e) : envelope(e), agent(0), first(0), second(0) {}
ObjectIdImpl(qpid::framing::Buffer& buffer);
ObjectIdImpl(AgentAttachment* agent, uint8_t flags, uint16_t seq, uint64_t object);
void decode(qpid::framing::Buffer& buffer);
void encode(qpid::framing::Buffer& buffer) const;
void fromString(const std::string& repr);
+ std::string asString() const;
uint8_t getFlags() const { return (first & 0xF000000000000000LL) >> 60; }
uint16_t getSequence() const { return (first & 0x0FFF000000000000LL) >> 48; }
uint32_t getBrokerBank() const { return (first & 0x0000FFFFF0000000LL) >> 28; }
diff --git a/qpid/cpp/src/qmf/ObjectImpl.cpp b/qpid/cpp/src/qmf/ObjectImpl.cpp
index 645ccd5c81..1ea2d54527 100644
--- a/qpid/cpp/src/qmf/ObjectImpl.cpp
+++ b/qpid/cpp/src/qmf/ObjectImpl.cpp
@@ -45,30 +45,40 @@ ObjectImpl::ObjectImpl(Object* e, const SchemaObjectClass* type) :
}
}
-ObjectImpl::ObjectImpl(const SchemaObjectClass* type, Buffer& buffer) :
- envelope(new Object(this)), objectClass(type), createTime(uint64_t(Duration(now()))),
- destroyTime(0), lastUpdatedTime(createTime)
+ObjectImpl::ObjectImpl(const SchemaObjectClass* type, Buffer& buffer, bool prop, bool stat, bool managed) :
+ envelope(new Object(this)), objectClass(type), createTime(0), destroyTime(0), lastUpdatedTime(0)
{
- int propCount = objectClass->getPropertyCount();
- int statCount = objectClass->getStatisticCount();
int idx;
- set<string> excludes;
- parsePresenceMasks(buffer, excludes);
- for (idx = 0; idx < propCount; idx++) {
- const SchemaProperty* prop = objectClass->getProperty(idx);
- if (excludes.count(prop->getName()) != 0) {
- properties[prop->getName()] = ValuePtr(new Value(prop->getType()));
- } else {
- ValueImpl* pval = new ValueImpl(prop->getType(), buffer);
- properties[prop->getName()] = ValuePtr(pval->envelope);
+ if (managed) {
+ lastUpdatedTime = buffer.getLongLong();
+ createTime = buffer.getLongLong();
+ destroyTime = buffer.getLongLong();
+ objectId.reset(new ObjectIdImpl(buffer));
+ }
+
+ if (prop) {
+ int propCount = objectClass->getPropertyCount();
+ set<string> excludes;
+ parsePresenceMasks(buffer, excludes);
+ for (idx = 0; idx < propCount; idx++) {
+ const SchemaProperty* prop = objectClass->getProperty(idx);
+ if (excludes.count(prop->getName()) != 0) {
+ properties[prop->getName()] = ValuePtr(new Value(prop->getType()));
+ } else {
+ ValueImpl* pval = new ValueImpl(prop->getType(), buffer);
+ properties[prop->getName()] = ValuePtr(pval->envelope);
+ }
}
}
- for (idx = 0; idx < statCount; idx++) {
- const SchemaStatistic* stat = objectClass->getStatistic(idx);
- ValueImpl* sval = new ValueImpl(stat->getType(), buffer);
- statistics[stat->getName()] = ValuePtr(sval->envelope);
+ if (stat) {
+ int statCount = objectClass->getStatisticCount();
+ for (idx = 0; idx < statCount; idx++) {
+ const SchemaStatistic* stat = objectClass->getStatistic(idx);
+ ValueImpl* sval = new ValueImpl(stat->getType(), buffer);
+ statistics[stat->getName()] = ValuePtr(sval->envelope);
+ }
}
}
@@ -82,7 +92,7 @@ void ObjectImpl::destroy()
// TODO - flag deletion
}
-Value* ObjectImpl::getValue(const string& key)
+Value* ObjectImpl::getValue(const string& key) const
{
map<string, ValuePtr>::const_iterator iter;
@@ -133,7 +143,7 @@ void ObjectImpl::encodeManagedObjectData(qpid::framing::Buffer& buffer) const
buffer.putLongLong(lastUpdatedTime);
buffer.putLongLong(createTime);
buffer.putLongLong(destroyTime);
- objectId->impl->encode(buffer);
+ objectId->encode(buffer);
}
void ObjectImpl::encodeProperties(qpid::framing::Buffer& buffer) const
@@ -187,36 +197,12 @@ void ObjectImpl::encodeStatistics(qpid::framing::Buffer& buffer) const
//==================================================================
Object::Object(const SchemaObjectClass* type) : impl(new ObjectImpl(this, type)) {}
-
Object::Object(ObjectImpl* i) : impl(i) {}
-
-Object::~Object()
-{
- delete impl;
-}
-
-void Object::destroy()
-{
- impl->destroy();
-}
-
-const ObjectId* Object::getObjectId() const
-{
- return impl->getObjectId();
-}
-
-void Object::setObjectId(ObjectId* oid)
-{
- impl->setObjectId(oid);
-}
-
-const SchemaObjectClass* Object::getClass() const
-{
- return impl->getClass();
-}
-
-Value* Object::getValue(char* key)
-{
- return impl->getValue(key);
-}
+Object::Object(const Object& from) : impl(new ObjectImpl(*(from.impl))) {}
+Object::~Object() { delete impl; }
+void Object::destroy() { impl->destroy(); }
+const ObjectId* Object::getObjectId() const { return impl->getObjectId(); }
+void Object::setObjectId(ObjectId* oid) { impl->setObjectId(oid); }
+const SchemaObjectClass* Object::getClass() const { return impl->getClass(); }
+Value* Object::getValue(char* key) const { return impl->getValue(key); }
diff --git a/qpid/cpp/src/qmf/ObjectImpl.h b/qpid/cpp/src/qmf/ObjectImpl.h
index 4dc2170bfc..d69979e0da 100644
--- a/qpid/cpp/src/qmf/ObjectImpl.h
+++ b/qpid/cpp/src/qmf/ObjectImpl.h
@@ -21,19 +21,22 @@
*/
#include <qmf/Object.h>
+#include <qmf/ObjectIdImpl.h>
#include <map>
#include <set>
#include <string>
#include <qpid/framing/Buffer.h>
#include <boost/shared_ptr.hpp>
+#include <qpid/sys/Mutex.h>
namespace qmf {
struct ObjectImpl {
+ typedef boost::shared_ptr<ObjectImpl> Ptr;
typedef boost::shared_ptr<Value> ValuePtr;
Object* envelope;
const SchemaObjectClass* objectClass;
- boost::shared_ptr<ObjectId> objectId;
+ boost::shared_ptr<ObjectIdImpl> objectId;
uint64_t createTime;
uint64_t destroyTime;
uint64_t lastUpdatedTime;
@@ -41,14 +44,14 @@ namespace qmf {
mutable std::map<std::string, ValuePtr> statistics;
ObjectImpl(Object* e, const SchemaObjectClass* type);
- ObjectImpl(const SchemaObjectClass* type, qpid::framing::Buffer& buffer);
+ ObjectImpl(const SchemaObjectClass* type, qpid::framing::Buffer& buffer, bool prop, bool stat, bool managed);
~ObjectImpl();
void destroy();
- const ObjectId* getObjectId() const { return objectId.get(); }
- void setObjectId(ObjectId* oid) { objectId.reset(oid); }
+ const ObjectId* getObjectId() const { return objectId.get() ? objectId->envelope : 0; }
+ void setObjectId(ObjectId* oid) { objectId.reset(oid->impl); }
const SchemaObjectClass* getClass() const { return objectClass; }
- Value* getValue(const std::string& key);
+ Value* getValue(const std::string& key) const;
void parsePresenceMasks(qpid::framing::Buffer& buffer, std::set<std::string>& excludeList);
void encodeSchemaKey(qpid::framing::Buffer& buffer) const;
diff --git a/qpid/cpp/src/qmf/Query.h b/qpid/cpp/src/qmf/Query.h
index 78bc6f4ae2..875749862e 100644
--- a/qpid/cpp/src/qmf/Query.h
+++ b/qpid/cpp/src/qmf/Query.h
@@ -25,26 +25,76 @@
namespace qmf {
+ struct Object;
+ struct QueryElementImpl;
struct QueryImpl;
+ struct QueryExpressionImpl;
+ struct SchemaClassKey;
+
+ enum ValueOper {
+ O_EQ = 1,
+ O_NE = 2,
+ O_LT = 3,
+ O_LE = 4,
+ O_GT = 5,
+ O_GE = 6,
+ O_RE_MATCH = 7,
+ O_RE_NOMATCH = 8
+ };
+
+ struct QueryOperand {
+ virtual ~QueryOperand() {}
+ virtual bool evaluate(const Object* object) const = 0;
+ };
+
+ struct QueryElement : public QueryOperand {
+ QueryElement(const char* attrName, const Value* value, ValueOper oper);
+ QueryElement(QueryElementImpl* impl);
+ virtual ~QueryElement();
+ bool evaluate(const Object* object) const;
+
+ QueryElementImpl* impl;
+ };
+
+ enum ExprOper {
+ E_NOT = 1,
+ E_AND = 2,
+ E_OR = 3,
+ E_XOR = 4
+ };
+
+ struct QueryExpression : public QueryOperand {
+ QueryExpression(ExprOper oper, const QueryOperand* operand1, const QueryOperand* operand2);
+ QueryExpression(QueryExpressionImpl* impl);
+ virtual ~QueryExpression();
+ bool evaluate(const Object* object) const;
+
+ QueryExpressionImpl* impl;
+ };
+
class Query {
public:
- Query();
+ Query(const char* className, const char* packageName);
+ Query(const SchemaClassKey* key);
+ Query(const ObjectId* oid);
Query(QueryImpl* impl);
~Query();
+ void setSelect(const QueryOperand* criterion);
+ void setLimit(uint32_t maxResults);
+ void setOrderBy(const char* attrName, bool decreasing);
+
const char* getPackage() const;
const char* getClass() const;
const ObjectId* getObjectId() const;
- enum Oper {
- OPER_AND = 1,
- OPER_OR = 2
- };
-
- int whereCount() const;
- Oper whereOper() const;
- const char* whereKey() const;
- const Value* whereValue() const;
+ bool haveSelect() const;
+ bool haveLimit() const;
+ bool haveOrderBy() const;
+ const QueryOperand* getSelect() const;
+ uint32_t getLimit() const;
+ const char* getOrderBy() const;
+ bool getDecreasing() const;
QueryImpl* impl;
};
diff --git a/qpid/cpp/src/qmf/QueryImpl.cpp b/qpid/cpp/src/qmf/QueryImpl.cpp
index 7e827796bb..f75a9aa5d5 100644
--- a/qpid/cpp/src/qmf/QueryImpl.cpp
+++ b/qpid/cpp/src/qmf/QueryImpl.cpp
@@ -18,54 +18,77 @@
*/
#include "qmf/QueryImpl.h"
+#include "qmf/ObjectIdImpl.h"
+#include "qpid/framing/Buffer.h"
+#include "qpid/framing/FieldTable.h"
using namespace std;
using namespace qmf;
+using namespace qpid::framing;
-//==================================================================
-// Wrappers
-//==================================================================
-
-Query::Query() : impl(new QueryImpl(this)) {}
-Query::Query(QueryImpl* i) : impl(i) {}
-
-Query::~Query()
+bool QueryElementImpl::evaluate(const Object* /*object*/) const
{
- delete impl;
+ // TODO: Implement this
+ return false;
}
-const char* Query::getPackage() const
+bool QueryExpressionImpl::evaluate(const Object* /*object*/) const
{
- return impl->getPackage();
+ // TODO: Implement this
+ return false;
}
-const char* Query::getClass() const
+QueryImpl::QueryImpl(Buffer& buffer)
{
- return impl->getClass();
+ FieldTable ft;
+ ft.decode(buffer);
+ // TODO
}
-const ObjectId* Query::getObjectId() const
+void QueryImpl::encode(Buffer& buffer) const
{
- return impl->getObjectId();
-}
+ FieldTable ft;
-int Query::whereCount() const
-{
- return impl->whereCount();
-}
+ if (oid.get() != 0) {
+ ft.setString("_objectid", oid->impl->asString());
+ } else {
+ if (!packageName.empty())
+ ft.setString("_package", packageName);
+ ft.setString("_class", className);
+ }
-Query::Oper Query::whereOper() const
-{
- return impl->whereOper();
+ ft.encode(buffer);
}
-const char* Query::whereKey() const
-{
- return impl->whereKey();
-}
-const Value* Query::whereValue() const
-{
- return impl->whereValue();
-}
+//==================================================================
+// Wrappers
+//==================================================================
+
+QueryElement::QueryElement(const char* attrName, const Value* value, ValueOper oper) : impl(new QueryElementImpl(attrName, value, oper)) {}
+QueryElement::QueryElement(QueryElementImpl* i) : impl(i) {}
+QueryElement::~QueryElement() { delete impl; }
+bool QueryElement::evaluate(const Object* object) const { return impl->evaluate(object); }
+QueryExpression::QueryExpression(ExprOper oper, const QueryOperand* operand1, const QueryOperand* operand2) : impl(new QueryExpressionImpl(oper, operand1, operand2)) {}
+QueryExpression::QueryExpression(QueryExpressionImpl* i) : impl(i) {}
+QueryExpression::~QueryExpression() { delete impl; }
+bool QueryExpression::evaluate(const Object* object) const { return impl->evaluate(object); }
+Query::Query(const char* className, const char* packageName) : impl(new QueryImpl(className, packageName)) {}
+Query::Query(const SchemaClassKey* key) : impl(new QueryImpl(key)) {}
+Query::Query(const ObjectId* oid) : impl(new QueryImpl(oid)) {}
+Query::Query(QueryImpl* i) : impl(i) {}
+Query::~Query() { delete impl; }
+void Query::setSelect(const QueryOperand* criterion) { impl->setSelect(criterion); }
+void Query::setLimit(uint32_t maxResults) { impl->setLimit(maxResults); }
+void Query::setOrderBy(const char* attrName, bool decreasing) { impl->setOrderBy(attrName, decreasing); }
+const char* Query::getPackage() const { return impl->getPackage().c_str(); }
+const char* Query::getClass() const { return impl->getClass().c_str(); }
+const ObjectId* Query::getObjectId() const { return impl->getObjectId(); }
+bool Query::haveSelect() const { return impl->haveSelect(); }
+bool Query::haveLimit() const { return impl->haveLimit(); }
+bool Query::haveOrderBy() const { return impl->haveOrderBy(); }
+const QueryOperand* Query::getSelect() const { return impl->getSelect(); }
+uint32_t Query::getLimit() const { return impl->getLimit(); }
+const char* Query::getOrderBy() const { return impl->getOrderBy().c_str(); }
+bool Query::getDecreasing() const { return impl->getDecreasing(); }
diff --git a/qpid/cpp/src/qmf/QueryImpl.h b/qpid/cpp/src/qmf/QueryImpl.h
index 1cb9bfe554..4a56a457c0 100644
--- a/qpid/cpp/src/qmf/QueryImpl.h
+++ b/qpid/cpp/src/qmf/QueryImpl.h
@@ -20,28 +20,82 @@
* under the License.
*/
-#include <qmf/Query.h>
+#include "qmf/Query.h"
+#include "qmf/Schema.h"
#include <string>
#include <boost/shared_ptr.hpp>
+namespace qpid {
+ namespace framing {
+ class Buffer;
+ }
+}
+
namespace qmf {
+ struct QueryElementImpl {
+ QueryElementImpl(const std::string& a, const Value* v, ValueOper o) :
+ envelope(new QueryElement(this)), attrName(a), value(v), oper(o) {}
+ ~QueryElementImpl() {}
+ bool evaluate(const Object* object) const;
+
+ QueryElement* envelope;
+ std::string attrName;
+ const Value* value;
+ ValueOper oper;
+ };
+
+ struct QueryExpressionImpl {
+ QueryExpressionImpl(ExprOper o, const QueryOperand* operand1, const QueryOperand* operand2) :
+ envelope(new QueryExpression(this)), oper(o), left(operand1), right(operand2) {}
+ ~QueryExpressionImpl() {}
+ bool evaluate(const Object* object) const;
+
+ QueryExpression* envelope;
+ ExprOper oper;
+ const QueryOperand* left;
+ const QueryOperand* right;
+ };
+
struct QueryImpl {
- Query* envelope;
- std::string packageName;
- std::string className;
- boost::shared_ptr<ObjectId> oid;
+ QueryImpl(Query* e) : envelope(e), select(0) {}
+ QueryImpl(const std::string& c, const std::string& p) :
+ envelope(new Query(this)), packageName(p), className(c) {}
+ QueryImpl(const SchemaClassKey* key) :
+ envelope(new Query(this)), packageName(key->getPackageName()), className(key->getClassName()) {}
+ QueryImpl(const ObjectId* oid) :
+ envelope(new Query(this)), oid(new ObjectId(*oid)) {}
+ QueryImpl(qpid::framing::Buffer& buffer);
+ ~QueryImpl() {};
- QueryImpl(Query* e) : envelope(e) {}
+ void setSelect(const QueryOperand* criterion) { select = criterion; }
+ void setLimit(uint32_t maxResults) { resultLimit = maxResults; }
+ void setOrderBy(const std::string& attrName, bool decreasing) {
+ orderBy = attrName; orderDecreasing = decreasing;
+ }
- const char* getPackage() const { return packageName.empty() ? 0 : packageName.c_str(); }
- const char* getClass() const { return className.empty() ? 0 : className.c_str(); }
+ const std::string& getPackage() const { return packageName; }
+ const std::string& getClass() const { return className; }
const ObjectId* getObjectId() const { return oid.get(); }
- int whereCount() const { return 0;}
- Query::Oper whereOper() const { return Query::OPER_AND; }
- const char* whereKey() const { return 0; }
- const Value* whereValue() const { return 0; }
+ bool haveSelect() const { return select != 0; }
+ bool haveLimit() const { return resultLimit > 0; }
+ bool haveOrderBy() const { return !orderBy.empty(); }
+ const QueryOperand* getSelect() const { return select; }
+ uint32_t getLimit() const { return resultLimit; }
+ const std::string& getOrderBy() const { return orderBy; }
+ bool getDecreasing() const { return orderDecreasing; }
+
+ void encode(qpid::framing::Buffer& buffer) const;
+
+ Query* envelope;
+ std::string packageName;
+ std::string className;
+ boost::shared_ptr<ObjectId> oid;
+ const QueryOperand* select;
+ uint32_t resultLimit;
+ std::string orderBy;
+ bool orderDecreasing;
};
}
diff --git a/qpid/cpp/src/qmf/SchemaImpl.cpp b/qpid/cpp/src/qmf/SchemaImpl.cpp
index ae7d6ca689..3eb14c3952 100644
--- a/qpid/cpp/src/qmf/SchemaImpl.cpp
+++ b/qpid/cpp/src/qmf/SchemaImpl.cpp
@@ -261,7 +261,15 @@ void SchemaStatisticImpl::updateHash(SchemaHash& hash) const
SchemaClassKeyImpl::SchemaClassKeyImpl(const string& p, const string& n, const SchemaHash& h) :
envelope(new SchemaClassKey(this)), package(p), name(n), hash(h) {}
-void SchemaClassKeyImpl::encode(qpid::framing::Buffer& buffer) const
+SchemaClassKeyImpl::SchemaClassKeyImpl(Buffer& buffer) :
+ envelope(new SchemaClassKey(this)), package(packageContainer), name(nameContainer), hash(hashContainer)
+{
+ buffer.getShortString(packageContainer);
+ buffer.getShortString(nameContainer);
+ hashContainer.decode(buffer);
+}
+
+void SchemaClassKeyImpl::encode(Buffer& buffer) const
{
buffer.putShortString(package);
buffer.putShortString(name);
@@ -413,8 +421,9 @@ SchemaEventClassImpl::SchemaEventClassImpl(Buffer& buffer) :
buffer.getShortString(package);
buffer.getShortString(name);
hash.decode(buffer);
+ buffer.putOctet(0); // No parent class
- uint16_t argCount = buffer.getShort();
+ uint16_t argCount = buffer.getShort();
for (uint16_t idx = 0; idx < argCount; idx++) {
SchemaArgumentImpl* argument = new SchemaArgumentImpl(buffer);
diff --git a/qpid/cpp/src/qmf/SchemaImpl.h b/qpid/cpp/src/qmf/SchemaImpl.h
index 3e9677d1fa..035d99aecd 100644
--- a/qpid/cpp/src/qmf/SchemaImpl.h
+++ b/qpid/cpp/src/qmf/SchemaImpl.h
@@ -148,7 +148,14 @@ namespace qmf {
const std::string& name;
const SchemaHash& hash;
+ // The *Container elements are only used if there isn't an external place to
+ // store these values.
+ std::string packageContainer;
+ std::string nameContainer;
+ SchemaHash hashContainer;
+
SchemaClassKeyImpl(const std::string& package, const std::string& name, const SchemaHash& hash);
+ SchemaClassKeyImpl(qpid::framing::Buffer& buffer);
const std::string& getPackageName() const { return package; }
const std::string& getClassName() const { return name; }
diff --git a/qpid/cpp/src/qmf/SequenceManager.cpp b/qpid/cpp/src/qmf/SequenceManager.cpp
index f51ce9d8b8..3171e66fac 100644
--- a/qpid/cpp/src/qmf/SequenceManager.cpp
+++ b/qpid/cpp/src/qmf/SequenceManager.cpp
@@ -25,26 +25,72 @@ using namespace qpid::sys;
SequenceManager::SequenceManager() : nextSequence(1) {}
-uint32_t SequenceManager::reserve(SequenceContext* ctx)
+void SequenceManager::setUnsolicitedContext(SequenceContext::Ptr ctx)
+{
+ unsolicitedContext = ctx;
+}
+
+uint32_t SequenceManager::reserve(SequenceContext::Ptr ctx)
{
Mutex::ScopedLock _lock(lock);
+ if (ctx.get() == 0)
+ ctx = unsolicitedContext;
uint32_t seq = nextSequence;
while (contextMap.find(seq) != contextMap.end())
seq = seq < 0xFFFFFFFF ? seq + 1 : 1;
nextSequence = seq < 0xFFFFFFFF ? seq + 1 : 1;
contextMap[seq] = ctx;
+ ctx->reserve();
return seq;
}
void SequenceManager::release(uint32_t sequence)
{
Mutex::ScopedLock _lock(lock);
- map<uint32_t, SequenceContext*>::iterator iter = contextMap.find(sequence);
+
+ if (sequence == 0) {
+ if (unsolicitedContext.get() != 0)
+ unsolicitedContext->release();
+ return;
+ }
+
+ map<uint32_t, SequenceContext::Ptr>::iterator iter = contextMap.find(sequence);
if (iter != contextMap.end()) {
if (iter->second != 0)
- iter->second->complete();
+ iter->second->release();
contextMap.erase(iter);
}
}
+void SequenceManager::releaseAll()
+{
+ Mutex::ScopedLock _lock(lock);
+ contextMap.clear();
+}
+
+void SequenceManager::dispatch(uint8_t opcode, uint32_t sequence, qpid::framing::Buffer& buffer)
+{
+ Mutex::ScopedLock _lock(lock);
+ bool done;
+
+ if (sequence == 0) {
+ if (unsolicitedContext.get() != 0) {
+ done = unsolicitedContext->handleMessage(opcode, sequence, buffer);
+ if (done)
+ unsolicitedContext->release();
+ }
+ return;
+ }
+
+ map<uint32_t, SequenceContext::Ptr>::iterator iter = contextMap.find(sequence);
+ if (iter != contextMap.end()) {
+ if (iter->second != 0) {
+ done = iter->second->handleMessage(opcode, sequence, buffer);
+ if (done) {
+ iter->second->release();
+ contextMap.erase(iter);
+ }
+ }
+ }
+}
diff --git a/qpid/cpp/src/qmf/SequenceManager.h b/qpid/cpp/src/qmf/SequenceManager.h
index c027872313..bbfd0728a7 100644
--- a/qpid/cpp/src/qmf/SequenceManager.h
+++ b/qpid/cpp/src/qmf/SequenceManager.h
@@ -21,29 +21,43 @@
*/
#include "qpid/sys/Mutex.h"
+#include <boost/shared_ptr.hpp>
#include <map>
+namespace qpid {
+ namespace framing {
+ class Buffer;
+ }
+}
+
namespace qmf {
class SequenceContext {
public:
+ typedef boost::shared_ptr<SequenceContext> Ptr;
SequenceContext() {}
virtual ~SequenceContext() {}
- virtual void complete() = 0;
+ virtual void reserve() = 0;
+ virtual bool handleMessage(uint8_t opcode, uint32_t sequence, qpid::framing::Buffer& buffer) = 0;
+ virtual void release() = 0;
};
class SequenceManager {
public:
SequenceManager();
- uint32_t reserve(SequenceContext* ctx);
+ void setUnsolicitedContext(SequenceContext::Ptr ctx);
+ uint32_t reserve(SequenceContext::Ptr ctx = SequenceContext::Ptr());
void release(uint32_t sequence);
+ void releaseAll();
+ void dispatch(uint8_t opcode, uint32_t sequence, qpid::framing::Buffer& buffer);
private:
mutable qpid::sys::Mutex lock;
uint32_t nextSequence;
- std::map<uint32_t, SequenceContext*> contextMap;
+ SequenceContext::Ptr unsolicitedContext;
+ std::map<uint32_t, SequenceContext::Ptr> contextMap;
};
}
diff --git a/qpid/cpp/src/qpid/acl/AclData.cpp b/qpid/cpp/src/qpid/acl/AclData.cpp
index d2a55c0027..81519c3311 100644
--- a/qpid/cpp/src/qpid/acl/AclData.cpp
+++ b/qpid/cpp/src/qpid/acl/AclData.cpp
@@ -53,42 +53,65 @@ bool AclData::matchProp(const std::string & src, const std::string& src1)
}
}
-AclResult AclData::lookup(const std::string& id, const Action& action, const ObjectType& objType, const std::string& name, std::map<Property, std::string>* params)
-{
- AclResult aclresult = decisionMode;
-
- if (actionList[action] && actionList[action][objType]){
- AclData::actObjItr itrRule = actionList[action][objType]->find(id);
- if (itrRule == actionList[action][objType]->end())
- itrRule = actionList[action][objType]->find("*");
- if (itrRule != actionList[action][objType]->end() ) {
-
- //loop the vector
- for (ruleSetItr i=itrRule->second.begin(); i<itrRule->second.end(); i++) {
-
- // loop the names looking for match
- bool match =true;
- for (propertyMapItr pMItr = i->props.begin(); (pMItr != i->props.end()) && match; pMItr++)
- {
- //match name is exists first
- if (pMItr->first == acl::PROP_NAME){
- if (!matchProp(pMItr->second, name)){
- match= false;
- }
- }else if (params){ //match pMItr against params
- propertyMapItr paramItr = params->find (pMItr->first);
- if (paramItr == params->end()){
- match = false;
- }else if (!matchProp(paramItr->second, pMItr->second)){
- match = false;
- }
+AclResult AclData::lookup(const std::string& id, const Action& action, const ObjectType& objType,
+ const std::string& name, std::map<Property, std::string>* params) {
+
+ QPID_LOG(debug, "ACL: Lookup for id:" << id << " action:" << AclHelper::getActionStr((Action) action)
+ << " objectType:" << AclHelper::getObjectTypeStr((ObjectType) objType) << " name:" << name
+ << " with params " << AclHelper::propertyMapToString(params));
+
+ AclResult aclresult = decisionMode;
+ if (actionList[action] && actionList[action][objType]) {
+ AclData::actObjItr itrRule = actionList[action][objType]->find(id);
+ if (itrRule == actionList[action][objType]->end())
+ itrRule = actionList[action][objType]->find("*");
+ if (itrRule != actionList[action][objType]->end()) {
+
+ QPID_LOG(debug, "ACL: checking the following rules for : " << itrRule->first );
+
+ //loop the vector
+ for (ruleSetItr i = itrRule->second.begin(); i < itrRule->second.end(); i++) {
+ QPID_LOG(debug, "ACL: checking rule " << i->toString());
+ // loop the names looking for match
+ bool match = true;
+ for (propertyMapItr pMItr = i->props.begin(); (pMItr != i->props.end()) && match; pMItr++) {
+ //match name is exists first
+ if (pMItr->first == acl::PROP_NAME) {
+ if (matchProp(pMItr->second, name)){
+ QPID_LOG(debug, "ACL: name '" << name << "' matched with name '"
+ << pMItr->second << "' given in the rule");
+ }else{
+ match = false;
+ QPID_LOG(debug, "ACL: name '" << name << "' didn't match with name '"
+ << pMItr->second << "' given in the rule");
+ }
+ } else if (params) { //match pMItr against params
+ propertyMapItr paramItr = params->find(pMItr->first);
+ if (paramItr == params->end()) {
+ match = false;
+ QPID_LOG(debug, "ACL: the given parameter map in lookup doesn't contain the property '"
+ << AclHelper::getPropertyStr(pMItr->first) << "'");
+ } else if (!matchProp(pMItr->second, paramItr->second)) {
+ QPID_LOG(debug, "ACL: the pair("
+ << AclHelper::getPropertyStr(paramItr->first) << "," << paramItr->second
+ << ") given in lookup doesn't match the pair("
+ << AclHelper::getPropertyStr(pMItr->first) << "," << pMItr->second << ") given in the rule");
+ match = false;
}
}
- if (match) return getACLResult(i->logOnly, i->log);
- }
- }
- }
- return aclresult;
+ }
+ if (match)
+ {
+ aclresult = getACLResult(i->logOnly, i->log);
+ QPID_LOG(debug,"Successful match, the decision is:" << AclHelper::getAclResultStr(aclresult));
+ return aclresult;
+ }
+ }
+ }
+ }
+
+ QPID_LOG(debug,"No successful match, defaulting to the decision mode " << AclHelper::getAclResultStr(aclresult));
+ return aclresult;
}
AclResult AclData::lookup(const std::string& id, const Action& action, const ObjectType& objType, const std::string& /*Exchange*/ name, const std::string& RoutingKey)
diff --git a/qpid/cpp/src/qpid/acl/AclData.h b/qpid/cpp/src/qpid/acl/AclData.h
index 249c3523eb..a63afab12b 100644
--- a/qpid/cpp/src/qpid/acl/AclData.h
+++ b/qpid/cpp/src/qpid/acl/AclData.h
@@ -22,7 +22,7 @@
#include "qpid/broker/AclModule.h"
#include <vector>
-
+#include <sstream>
namespace qpid {
namespace acl {
@@ -45,6 +45,16 @@ public:
rule (propertyMap& p):log(false),logOnly(false),props(p) {};
+
+ std::string toString () const {
+ std::ostringstream ruleStr;
+ ruleStr << "[log=" << log << ", logOnly=" << logOnly << " props{";
+ for (propertyMapItr pMItr = props.begin(); pMItr != props.end(); pMItr++) {
+ ruleStr << " " << AclHelper::getPropertyStr((Property) pMItr-> first) << "=" << pMItr->second;
+ }
+ ruleStr << " }]";
+ return ruleStr.str();
+ }
};
typedef std::vector<rule> ruleSet;
typedef ruleSet::const_iterator ruleSetItr;
diff --git a/qpid/cpp/src/qpid/acl/AclReader.cpp b/qpid/cpp/src/qpid/acl/AclReader.cpp
index 8f5e4f5b57..8f419a6f50 100644
--- a/qpid/cpp/src/qpid/acl/AclReader.cpp
+++ b/qpid/cpp/src/qpid/acl/AclReader.cpp
@@ -83,115 +83,142 @@ std::string AclReader::aclRule::toString() {
return oss.str();
}
-void AclReader::loadDecisionData( boost::shared_ptr<AclData> d )
-{
- d->clear();
- QPID_LOG(debug, "ACL Load Rules");
- int cnt = rules.size();
+void AclReader::loadDecisionData(boost::shared_ptr<AclData> d) {
+ d->clear();
+ QPID_LOG(debug, "ACL Load Rules");
+ int cnt = rules.size();
bool foundmode = false;
- for (rlCitr i=rules.end()-1; cnt; i--,cnt--) {
- QPID_LOG(debug, "ACL Processing " << std::setfill(' ') << std::setw(2) << cnt << " " << (*i)->toString());
-
- if (!foundmode && (*i)->actionAll && (*i)->names.size()==1 && (*((*i)->names.begin())).compare("*")==0 ){
- d->decisionMode = (*i)->res;
- QPID_LOG(debug, "ACL FoundMode " << AclHelper::getAclResultStr(d->decisionMode));
- foundmode=true;
- }else{
- AclData::rule rule((*i)->props);
- bool addrule= true;
-
- switch ((*i)->res)
- {
- case qpid::acl::ALLOWLOG:
- rule.log = true;
- if (d->decisionMode == qpid::acl::ALLOW || d->decisionMode == qpid::acl::ALLOWLOG)
- rule.logOnly = true;
+
+ for (rlCitr i = rules.end() - 1; cnt; i--, cnt--) {
+ QPID_LOG(debug, "ACL Processing " << std::setfill(' ') << std::setw(2)
+ << cnt << " " << (*i)->toString());
+
+ if (!foundmode && (*i)->actionAll && (*i)->names.size() == 1
+ && (*((*i)->names.begin())).compare("*") == 0) {
+ d->decisionMode = (*i)->res;
+ QPID_LOG(debug, "ACL FoundMode " << AclHelper::getAclResultStr(
+ d->decisionMode));
+ foundmode = true;
+ } else {
+ AclData::rule rule((*i)->props);
+ bool addrule = true;
+
+ switch ((*i)->res) {
+ case qpid::acl::ALLOWLOG:
+ rule.log = true;
+ if (d->decisionMode == qpid::acl::ALLOW || d->decisionMode
+ == qpid::acl::ALLOWLOG)
+ rule.logOnly = true;
+ break;
+ case qpid::acl::ALLOW:
+ if (d->decisionMode == qpid::acl::ALLOW || d->decisionMode
+ == qpid::acl::ALLOWLOG)
+ addrule = false;
+ break;
+ case qpid::acl::DENYLOG:
+ rule.log = true;
+ if (d->decisionMode == qpid::acl::DENY || d->decisionMode
+ == qpid::acl::DENYLOG)
+ rule.logOnly = true;
+ break;
+ case qpid::acl::DENY:
+ if (d->decisionMode == qpid::acl::DENY || d->decisionMode
+ == qpid::acl::DENYLOG)
+ addrule = false;
break;
- case qpid::acl::ALLOW:
- if (d->decisionMode == qpid::acl::ALLOW || d->decisionMode == qpid::acl::ALLOWLOG)
- addrule = false;
- break;
- case qpid::acl::DENYLOG:
- rule.log = true;
- if (d->decisionMode == qpid::acl::DENY || d->decisionMode == qpid::acl::DENYLOG)
- rule.logOnly = true;
- break;
- case qpid::acl::DENY:
- if (d->decisionMode == qpid::acl::DENY || d->decisionMode == qpid::acl::DENYLOG)
- addrule = false;
- break;
- default:
- throw Exception("Invalid ACL Result loading rules.");
- }
-
-
- // Action -> Object -> map<user -> set<Rule> >
- if (addrule){
- for (int acnt= ((*i)->actionAll?0:(*i)->action);
- acnt< acl::ACTIONSIZE; (*i)->actionAll?acnt++:acnt=acl::ACTIONSIZE ) {
-
- if (acnt == acl::ACT_PUBLISH) d->transferAcl = true; // we have transfer ACL
-
- QPID_LOG(debug, "ACL Adding action:" << AclHelper::getActionStr((Action)acnt) );
-
- //find the Action, create if not exist
- if (d->actionList[acnt]==NULL) {
- d->actionList[acnt] = new AclData::aclAction[qpid::acl::OBJECTSIZE];
- for (int j=0;j<qpid::acl::OBJECTSIZE; j++)
- d->actionList[acnt][j] = NULL;
- }
+ default:
+ throw Exception("Invalid ACL Result loading rules.");
+ }
+
+ // Action -> Object -> map<user -> set<Rule> >
+ if (addrule) {
+ std::ostringstream actionstr;
+ for (int acnt = ((*i)->actionAll ? 0 : (*i)->action); acnt
+ < acl::ACTIONSIZE; (*i)->actionAll ? acnt++ : acnt
+ = acl::ACTIONSIZE) {
+
+ if (acnt == acl::ACT_PUBLISH)
+ d->transferAcl = true; // we have transfer ACL
+
+ actionstr << AclHelper::getActionStr((Action) acnt) << ",";
+
+ //find the Action, create if not exist
+ if (d->actionList[acnt] == NULL) {
+ d->actionList[acnt]
+ = new AclData::aclAction[qpid::acl::OBJECTSIZE];
+ for (int j = 0; j < qpid::acl::OBJECTSIZE; j++)
+ d->actionList[acnt][j] = NULL;
+ }
// optimize this loop to limit to valid options only!!
- for (int ocnt= ((*i)->objStatus!=aclRule::VALUE ?0:(*i)->object);
- ocnt< acl::OBJECTSIZE;
- (*i)->objStatus!=aclRule::VALUE?ocnt++:ocnt=acl::OBJECTSIZE ) {
-
- QPID_LOG(debug, "ACL Adding object:" << AclHelper::getObjectTypeStr((ObjectType)ocnt) );
-
- //find the Object, create if not exist
- if (d->actionList[acnt][ocnt] == NULL)
- d->actionList[acnt][ocnt] = new AclData::actionObject;
-
- // add users and Rule to object set
- bool allNames=false;
- // check to see if names.begin is '*'
- if ( (*(*i)->names.begin()).compare("*")==0 ) allNames = true;
-
- for (nsCitr itr = (allNames?names.begin():(*i)->names.begin());
- itr != (allNames?names.end():(*i)->names.end()); itr++) {
- AclData::actObjItr itrRule = d->actionList[acnt][ocnt]->find(*itr);
- if (itrRule == d->actionList[acnt][ocnt]->end()) {
- QPID_LOG(debug, "ACL Adding rule & user:" << *itr);
- AclData::ruleSet rSet;
- rSet.push_back(rule);
- d->actionList[acnt][ocnt]->insert(make_pair( std::string(*itr) , rSet) );
- }else{
-
- // TODO add code to check for dead rules
- // allow peter create queue name=tmp <-- dead rule!!
- // allow peter create queue
-
- itrRule->second.push_back(rule);
- QPID_LOG(debug, "ACL Adding rule to user:" << *itr);
- }
- }
-
- }
-
- }
- }else{
- QPID_LOG(debug, "ACL Skipping based on Mode:" << AclHelper::getAclResultStr(d->decisionMode) );
- }
- }
-
- }
+ for (int ocnt = ((*i)->objStatus != aclRule::VALUE ? 0
+ : (*i)->object); ocnt < acl::OBJECTSIZE; (*i)->objStatus
+ != aclRule::VALUE ? ocnt++ : ocnt = acl::OBJECTSIZE) {
+
+ //find the Object, create if not exist
+ if (d->actionList[acnt][ocnt] == NULL)
+ d->actionList[acnt][ocnt]
+ = new AclData::actionObject;
+
+ // add users and Rule to object set
+ bool allNames = false;
+ // check to see if names.begin is '*'
+ if ((*(*i)->names.begin()).compare("*") == 0)
+ allNames = true;
+
+ for (nsCitr itr = (allNames ? names.begin()
+ : (*i)->names.begin()); itr
+ != (allNames ? names.end() : (*i)->names.end()); itr++) {
+
+ AclData::actObjItr itrRule =
+ d->actionList[acnt][ocnt]->find(*itr);
+
+ if (itrRule == d->actionList[acnt][ocnt]->end()) {
+ AclData::ruleSet rSet;
+ rSet.push_back(rule);
+ d->actionList[acnt][ocnt]->insert(make_pair(
+ std::string(*itr), rSet));
+ } else {
+
+ // TODO add code to check for dead rules
+ // allow peter create queue name=tmp <-- dead rule!!
+ // allow peter create queue
+
+ itrRule->second.push_back(rule);
+ }
+ }
+
+ }
+ }
+
+ std::ostringstream objstr;
+ for (int ocnt = ((*i)->objStatus != aclRule::VALUE ? 0 : (*i)->object); ocnt < acl::OBJECTSIZE;
+ (*i)->objStatus != aclRule::VALUE ? ocnt++ : ocnt = acl::OBJECTSIZE) {
+ objstr << AclHelper::getObjectTypeStr((ObjectType) ocnt) << ",";
+ }
+
+ bool allNames = ((*(*i)->names.begin()).compare("*") == 0);
+ std::ostringstream userstr;
+ for (nsCitr itr = (allNames ? names.begin() : (*i)->names.begin());
+ itr != (allNames ? names.end() : (*i)->names.end()); itr++) {
+ userstr << *itr << ",";
+ }
+
+ QPID_LOG(debug,"ACL: Adding actions {" << actionstr.str().substr(0,actionstr.str().length()-1)
+ << "} to objects {" << objstr.str().substr(0,objstr.str().length()-1)
+ << "} with props " << AclHelper::propertyMapToString(&rule.props)
+ << " for users {" << userstr.str().substr(0,userstr.str().length()-1) << "}" );
+ } else {
+ QPID_LOG(debug, "ACL Skipping based on Mode:"
+ << AclHelper::getAclResultStr(d->decisionMode));
+ }
+ }
+ }
}
-
-
void AclReader::aclRule::processName(const std::string& name, const groupMap& groups) {
if (name.compare("all") == 0) {
names.insert("*");
diff --git a/qpid/cpp/src/qpid/broker/AclModule.h b/qpid/cpp/src/qpid/broker/AclModule.h
index a78b2d5b4a..536fa21b2b 100644
--- a/qpid/cpp/src/qpid/broker/AclModule.h
+++ b/qpid/cpp/src/qpid/broker/AclModule.h
@@ -26,7 +26,7 @@
#include <map>
#include <set>
#include <string>
-
+#include <sstream>
namespace qpid {
@@ -179,6 +179,8 @@ class AclHelper {
typedef std::map<ObjectType, actionMapPtr> objectMap;
typedef objectMap::const_iterator omCitr;
typedef boost::shared_ptr<objectMap> objectMapPtr;
+ typedef std::map<Property, std::string> propMap;
+ typedef propMap::const_iterator propMapItr;
// This map contains the legal combinations of object/action/properties found in an ACL file
static void loadValidationMap(objectMapPtr& map) {
@@ -248,6 +250,19 @@ class AclHelper {
map->insert(objectPair(OBJ_METHOD, a4));
}
+
+ static std::string propertyMapToString(const std::map<Property, std::string>* params) {
+ std::ostringstream ss;
+ ss << "{";
+ if (params)
+ {
+ for (propMapItr pMItr = params->begin(); pMItr != params->end(); pMItr++) {
+ ss << " " << getPropertyStr((Property) pMItr-> first) << "=" << pMItr->second;
+ }
+ }
+ ss << " }";
+ return ss.str();
+ }
};
diff --git a/qpid/cpp/src/qpid/broker/Exchange.cpp b/qpid/cpp/src/qpid/broker/Exchange.cpp
index b1fc1295f3..90d81b81c6 100644
--- a/qpid/cpp/src/qpid/broker/Exchange.cpp
+++ b/qpid/cpp/src/qpid/broker/Exchange.cpp
@@ -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
@@ -38,7 +38,7 @@ using qpid::management::Manageable;
using qpid::management::Args;
namespace _qmf = qmf::org::apache::qpid::broker;
-namespace
+namespace
{
const std::string qpidMsgSequence("qpid.msg_sequence");
const std::string qpidSequenceCounter("qpid.sequence_counter");
@@ -51,17 +51,19 @@ const std::string fedOpBind("B");
const std::string fedOpUnbind("U");
const std::string fedOpReorigin("R");
const std::string fedOpHello("H");
+
+const std::string QPID_MANAGEMENT("qpid.management");
}
Exchange::PreRoute::PreRoute(Deliverable& msg, Exchange* _p):parent(_p) {
if (parent){
if (parent->sequence || parent->ive) parent->sequenceLock.lock();
-
+
if (parent->sequence){
parent->sequenceNo++;
- msg.getMessage().getProperties<MessageProperties>()->getApplicationHeaders().setInt64(qpidMsgSequence,parent->sequenceNo);
- }
+ msg.getMessage().getProperties<MessageProperties>()->getApplicationHeaders().setInt64(qpidMsgSequence,parent->sequenceNo);
+ }
if (parent->ive) {
parent->lastMsg = &( msg.getMessage());
}
@@ -99,11 +101,9 @@ Exchange::Exchange (const string& _name, Manageable* parent, Broker* b) :
}
}
-static const std::string QPID_MANAGEMENT("qpid.management");
-
Exchange::Exchange(const string& _name, bool _durable, const qpid::framing::FieldTable& _args,
Manageable* parent, Broker* b)
- : name(_name), durable(_durable), alternateUsers(0), persistenceId(0),
+ : name(_name), durable(_durable), alternateUsers(0), persistenceId(0),
args(_args), sequence(false), sequenceNo(0), ive(false), mgmtExchange(0), broker(b)
{
if (parent != 0 && broker != 0)
@@ -169,7 +169,7 @@ Exchange::shared_ptr Exchange::decode(ExchangeRegistry& exchanges, Buffer& buffe
string name;
string type;
FieldTable args;
-
+
buffer.getShortString(name);
bool durable(buffer.getOctet());
buffer.getShortString(type);
@@ -185,7 +185,7 @@ Exchange::shared_ptr Exchange::decode(ExchangeRegistry& exchanges, Buffer& buffe
}
}
-void Exchange::encode(Buffer& buffer) const
+void Exchange::encode(Buffer& buffer) const
{
buffer.putShortString(name);
buffer.putOctet(durable);
@@ -195,8 +195,8 @@ void Exchange::encode(Buffer& buffer) const
buffer.put(args);
}
-uint32_t Exchange::encodedSize() const
-{
+uint32_t Exchange::encodedSize() const
+{
return name.size() + 1/*short string size*/
+ 1 /*durable*/
+ getType().size() + 1/*short string size*/
diff --git a/qpid/cpp/src/qpid/broker/Message.cpp b/qpid/cpp/src/qpid/broker/Message.cpp
index 639f04faa2..7360010192 100644
--- a/qpid/cpp/src/qpid/broker/Message.cpp
+++ b/qpid/cpp/src/qpid/broker/Message.cpp
@@ -362,7 +362,7 @@ boost::intrusive_ptr<Message>& Message::getReplacementMessage(const Queue* qfor)
Replacement::iterator i = replacement.find(qfor);
if (i != replacement.end()){
return i->second;
- }
+ }
return empty;
}
diff --git a/qpid/cpp/src/qpid/broker/Message.h b/qpid/cpp/src/qpid/broker/Message.h
index 0024509bc8..e4d09b1042 100644
--- a/qpid/cpp/src/qpid/broker/Message.h
+++ b/qpid/cpp/src/qpid/broker/Message.h
@@ -34,12 +34,12 @@
#include <vector>
namespace qpid {
-
+
namespace framing {
class FieldTable;
class SequenceNumber;
}
-
+
namespace broker {
class ConnectionToken;
class Exchange;
@@ -145,9 +145,9 @@ public:
bool isExcluded(const std::vector<std::string>& excludes) const;
void addTraceId(const std::string& id);
-
- void forcePersistent();
- bool isForcedPersistent();
+
+ void forcePersistent();
+ bool isForcedPersistent();
boost::intrusive_ptr<Message>& getReplacementMessage(const Queue* qfor) const;
void setReplacementMessage(boost::intrusive_ptr<Message> msg, const Queue* qfor);
diff --git a/qpid/cpp/src/qpid/broker/MessageBuilder.cpp b/qpid/cpp/src/qpid/broker/MessageBuilder.cpp
index e01fd81074..14b233fd6c 100644
--- a/qpid/cpp/src/qpid/broker/MessageBuilder.cpp
+++ b/qpid/cpp/src/qpid/broker/MessageBuilder.cpp
@@ -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
@@ -30,14 +30,14 @@ using boost::intrusive_ptr;
using namespace qpid::broker;
using namespace qpid::framing;
-namespace
+namespace
{
std::string type_str(uint8_t type);
+ const std::string QPID_MANAGEMENT("qpid.management");
}
-MessageBuilder::MessageBuilder(MessageStore* const _store, uint64_t _stagingThreshold) :
- state(DORMANT), store(_store), stagingThreshold(_stagingThreshold), staging(false) {}
-static const std::string QPID_MANAGEMENT("qpid.management");
+MessageBuilder::MessageBuilder(MessageStore* const _store, uint64_t _stagingThreshold) :
+ state(DORMANT), store(_store), stagingThreshold(_stagingThreshold), staging(false) {}
void MessageBuilder::handle(AMQFrame& frame)
{
@@ -54,10 +54,10 @@ void MessageBuilder::handle(AMQFrame& frame)
AMQFrame header((AMQHeaderBody()));
header.setBof(false);
header.setEof(false);
- message->getFrames().append(header);
+ message->getFrames().append(header);
} else if (type != HEADER_BODY) {
throw CommandInvalidException(
- QPID_MSG("Invalid frame sequence for message, expected header or content got "
+ QPID_MSG("Invalid frame sequence for message, expected header or content got "
<< type_str(type) << ")"));
}
state = CONTENT;
@@ -74,13 +74,13 @@ void MessageBuilder::handle(AMQFrame& frame)
} else {
message->getFrames().append(frame);
//have we reached the staging limit? if so stage message and release content
- if (state == CONTENT
- && stagingThreshold
+ if (state == CONTENT
+ && stagingThreshold
&& message->getFrames().getContentSize() >= stagingThreshold
&& !NullMessageStore::isNullStore(store)
- && message->getExchangeName() != QPID_MANAGEMENT /* don't stage mgnt messages */)
+ && message->getExchangeName() != QPID_MANAGEMENT /* don't stage mgnt messages */)
{
- message->releaseContent(store);
+ message->releaseContent(store);
staging = true;
}
}
@@ -108,7 +108,7 @@ const std::string CONTENT_BODY_S = "CONTENT";
const std::string HEARTBEAT_BODY_S = "HEARTBEAT";
const std::string UNKNOWN = "unknown";
-std::string type_str(uint8_t type)
+std::string type_str(uint8_t type)
{
switch(type) {
case METHOD_BODY: return METHOD_BODY_S;
@@ -124,7 +124,7 @@ std::string type_str(uint8_t type)
void MessageBuilder::checkType(uint8_t expected, uint8_t actual)
{
if (expected != actual) {
- throw CommandInvalidException(QPID_MSG("Invalid frame sequence for message (expected "
+ throw CommandInvalidException(QPID_MSG("Invalid frame sequence for message (expected "
<< type_str(expected) << " got " << type_str(actual) << ")"));
}
}
diff --git a/qpid/cpp/src/qpid/broker/PersistableMessage.cpp b/qpid/cpp/src/qpid/broker/PersistableMessage.cpp
index c1f86d4ca4..2ef223aa81 100644
--- a/qpid/cpp/src/qpid/broker/PersistableMessage.cpp
+++ b/qpid/cpp/src/qpid/broker/PersistableMessage.cpp
@@ -62,7 +62,7 @@ void PersistableMessage::flush()
void PersistableMessage::setContentReleased() {contentReleased = true; }
bool PersistableMessage::isContentReleased()const { return contentReleased; }
-
+
bool PersistableMessage::isEnqueueComplete() {
sys::ScopedLock<sys::Mutex> l(asyncEnqueueLock);
return asyncEnqueueCounter == 0;
diff --git a/qpid/cpp/src/qpid/broker/PersistableMessage.h b/qpid/cpp/src/qpid/broker/PersistableMessage.h
index 05de9ff4c3..0274b41375 100644
--- a/qpid/cpp/src/qpid/broker/PersistableMessage.h
+++ b/qpid/cpp/src/qpid/broker/PersistableMessage.h
@@ -46,7 +46,7 @@ class PersistableMessage : public Persistable
sys::Mutex asyncEnqueueLock;
sys::Mutex asyncDequeueLock;
sys::Mutex storeLock;
-
+
/**
* Tracks the number of outstanding asynchronous enqueue
* operations. When the message is enqueued asynchronously the
@@ -97,7 +97,7 @@ class PersistableMessage : public Persistable
void flush();
bool isContentReleased() const;
-
+
QPID_BROKER_EXTERN bool isEnqueueComplete();
QPID_BROKER_EXTERN void enqueueComplete();
diff --git a/qpid/cpp/src/qpid/broker/Queue.cpp b/qpid/cpp/src/qpid/broker/Queue.cpp
index 08ee133981..b2a8e223c5 100644
--- a/qpid/cpp/src/qpid/broker/Queue.cpp
+++ b/qpid/cpp/src/qpid/broker/Queue.cpp
@@ -597,7 +597,7 @@ void Queue::push(boost::intrusive_ptr<Message>& msg, bool isRecovery){
Mutex::ScopedUnlock u(messageLock);
dequeue(0, QueuedMessage(qm.queue, old, qm.position));
}
- }
+ }
}else {
messages.push_back(qm);
listeners.populate(copy);
@@ -702,7 +702,7 @@ bool Queue::enqueue(TransactionContext* ctxt, boost::intrusive_ptr<Message> msg)
if (inLastNodeFailure && persistLastNode){
msg->forcePersistent();
}
-
+
if (traceId.size()) {
msg->addTraceId(traceId);
}
diff --git a/qpid/cpp/src/qpid/broker/QueueRegistry.h b/qpid/cpp/src/qpid/broker/QueueRegistry.h
index c134f399c8..72a91dff24 100644
--- a/qpid/cpp/src/qpid/broker/QueueRegistry.h
+++ b/qpid/cpp/src/qpid/broker/QueueRegistry.h
@@ -111,7 +111,7 @@ class QueueRegistry {
/** Call f for each queue in the registry. */
template <class F> void eachQueue(F f) const {
- qpid::sys::RWlock::ScopedWlock l(lock);
+ qpid::sys::RWlock::ScopedRlock l(lock);
for (QueueMap::const_iterator i = queues.begin(); i != queues.end(); ++i)
f(i->second);
}
diff --git a/qpid/cpp/src/qpid/broker/RecoveryManagerImpl.cpp b/qpid/cpp/src/qpid/broker/RecoveryManagerImpl.cpp
index 2a19115fd1..5bc4cdf960 100644
--- a/qpid/cpp/src/qpid/broker/RecoveryManagerImpl.cpp
+++ b/qpid/cpp/src/qpid/broker/RecoveryManagerImpl.cpp
@@ -195,7 +195,7 @@ void RecoverableQueueImpl::setPersistenceId(uint64_t id)
{
queue->setPersistenceId(id);
}
-
+
uint64_t RecoverableQueueImpl::getPersistenceId() const
{
return queue->getPersistenceId();
diff --git a/qpid/cpp/src/qpid/broker/SessionAdapter.cpp b/qpid/cpp/src/qpid/broker/SessionAdapter.cpp
index af07605552..a1ad5a0a30 100644
--- a/qpid/cpp/src/qpid/broker/SessionAdapter.cpp
+++ b/qpid/cpp/src/qpid/broker/SessionAdapter.cpp
@@ -72,7 +72,7 @@ void SessionAdapter::ExchangeHandlerImpl::declare(const string& exchange, const
params.insert(make_pair(acl::PROP_PASSIVE, std::string(passive ? _TRUE : _FALSE) ));
params.insert(make_pair(acl::PROP_DURABLE, std::string(durable ? _TRUE : _FALSE)));
if (!acl->authorise(getConnection().getUserId(),acl::ACT_CREATE,acl::OBJ_EXCHANGE,exchange,&params) )
- throw NotAllowedException(QPID_MSG("ACL denied exhange declare request from " << getConnection().getUserId()));
+ throw NotAllowedException(QPID_MSG("ACL denied exchange declare request from " << getConnection().getUserId()));
}
//TODO: implement autoDelete
@@ -134,7 +134,7 @@ void SessionAdapter::ExchangeHandlerImpl::delete_(const string& name, bool /*ifU
AclModule* acl = getBroker().getAcl();
if (acl) {
if (!acl->authorise(getConnection().getUserId(),acl::ACT_DELETE,acl::OBJ_EXCHANGE,name,NULL) )
- throw NotAllowedException(QPID_MSG("ACL denied exhange delete request from " << getConnection().getUserId()));
+ throw NotAllowedException(QPID_MSG("ACL denied exchange delete request from " << getConnection().getUserId()));
}
//TODO: implement unused
@@ -154,7 +154,7 @@ ExchangeQueryResult SessionAdapter::ExchangeHandlerImpl::query(const string& nam
AclModule* acl = getBroker().getAcl();
if (acl) {
if (!acl->authorise(getConnection().getUserId(),acl::ACT_ACCESS,acl::OBJ_EXCHANGE,name,NULL) )
- throw NotAllowedException(QPID_MSG("ACL denied exhange query request from " << getConnection().getUserId()));
+ throw NotAllowedException(QPID_MSG("ACL denied exchange query request from " << getConnection().getUserId()));
}
try {
@@ -171,8 +171,12 @@ void SessionAdapter::ExchangeHandlerImpl::bind(const string& queueName,
{
AclModule* acl = getBroker().getAcl();
if (acl) {
- if (!acl->authorise(getConnection().getUserId(),acl::ACT_BIND,acl::OBJ_EXCHANGE,exchangeName,routingKey) )
- throw NotAllowedException(QPID_MSG("ACL denied exhange bind request from " << getConnection().getUserId()));
+ std::map<acl::Property, std::string> params;
+ params.insert(make_pair(acl::PROP_QUEUENAME, queueName));
+ params.insert(make_pair(acl::PROP_ROUTINGKEY, routingKey));
+
+ if (!acl->authorise(getConnection().getUserId(),acl::ACT_BIND,acl::OBJ_EXCHANGE,exchangeName,&params))
+ throw NotAllowedException(QPID_MSG("ACL denied exchange bind request from " << getConnection().getUserId()));
}
Queue::shared_ptr queue = getQueue(queueName);
@@ -234,8 +238,8 @@ ExchangeBoundResult SessionAdapter::ExchangeHandlerImpl::bound(const std::string
std::map<acl::Property, std::string> params;
params.insert(make_pair(acl::PROP_QUEUENAME, queueName));
params.insert(make_pair(acl::PROP_ROUTINGKEY, key));
- if (!acl->authorise(getConnection().getUserId(),acl::ACT_CREATE,acl::OBJ_EXCHANGE,exchangeName,&params) )
- throw NotAllowedException(QPID_MSG("ACL denied exhange bound request from " << getConnection().getUserId()));
+ if (!acl->authorise(getConnection().getUserId(),acl::ACT_ACCESS,acl::OBJ_EXCHANGE,exchangeName,&params) )
+ throw NotAllowedException(QPID_MSG("ACL denied exchange bound request from " << getConnection().getUserId()));
}
Exchange::shared_ptr exchange;
diff --git a/qpid/cpp/src/qpid/client/Dispatcher.cpp b/qpid/cpp/src/qpid/client/Dispatcher.cpp
index 43cbf3aa4d..a715c623bf 100644
--- a/qpid/cpp/src/qpid/client/Dispatcher.cpp
+++ b/qpid/cpp/src/qpid/client/Dispatcher.cpp
@@ -29,7 +29,14 @@
#include "qpid/client/Message.h"
#include "qpid/client/MessageImpl.h"
-#include <boost/state_saver.hpp>
+#include <boost/version.hpp>
+#if (BOOST_VERSION >= 104000)
+# include <boost/serialization/state_saver.hpp>
+ using boost::serialization::state_saver;
+#else
+# include <boost/state_saver.hpp>
+ using boost::state_saver;
+#endif /* BOOST_VERSION */
using qpid::framing::FrameSet;
using qpid::framing::MessageTransferBody;
@@ -65,7 +72,7 @@ void Dispatcher::run()
Mutex::ScopedLock l(lock);
if (running)
throw Exception("Dispatcher is already running.");
- boost::state_saver<bool> reset(running); // Reset to false on exit.
+ state_saver<bool> reset(running); // Reset to false on exit.
running = true;
try {
while (!queue->isClosed()) {
diff --git a/qpid/cpp/src/qpid/client/amqp0_10/AcceptTracker.cpp b/qpid/cpp/src/qpid/client/amqp0_10/AcceptTracker.cpp
new file mode 100644
index 0000000000..80be5c56f3
--- /dev/null
+++ b/qpid/cpp/src/qpid/client/amqp0_10/AcceptTracker.cpp
@@ -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.
+ *
+ */
+#include "AcceptTracker.h"
+
+namespace qpid {
+namespace client {
+namespace amqp0_10 {
+
+void AcceptTracker::State::accept()
+{
+ unconfirmed.add(unaccepted);
+ unaccepted.clear();
+}
+
+void AcceptTracker::State::release()
+{
+ unaccepted.clear();
+}
+
+uint32_t AcceptTracker::State::acceptsPending()
+{
+ return unconfirmed.size();
+}
+
+void AcceptTracker::State::completed(qpid::framing::SequenceSet& set)
+{
+ unconfirmed.remove(set);
+}
+
+void AcceptTracker::delivered(const std::string& destination, const qpid::framing::SequenceNumber& id)
+{
+ aggregateState.unaccepted.add(id);
+ destinationState[destination].unaccepted.add(id);
+}
+
+void AcceptTracker::accept(qpid::client::AsyncSession& session)
+{
+ for (StateMap::iterator i = destinationState.begin(); i != destinationState.end(); ++i) {
+ i->second.accept();
+ }
+ Record record;
+ record.status = session.messageAccept(aggregateState.unaccepted);
+ record.accepted = aggregateState.unaccepted;
+ pending.push_back(record);
+ aggregateState.accept();
+}
+
+void AcceptTracker::release(qpid::client::AsyncSession& session)
+{
+ session.messageRelease(aggregateState.unaccepted);
+ for (StateMap::iterator i = destinationState.begin(); i != destinationState.end(); ++i) {
+ i->second.release();
+ }
+ aggregateState.release();
+}
+
+uint32_t AcceptTracker::acceptsPending()
+{
+ checkPending();
+ return aggregateState.acceptsPending();
+}
+
+uint32_t AcceptTracker::acceptsPending(const std::string& destination)
+{
+ checkPending();
+ return destinationState[destination].acceptsPending();
+}
+
+void AcceptTracker::reset()
+{
+ destinationState.clear();
+ aggregateState.unaccepted.clear();
+ aggregateState.unconfirmed.clear();
+ pending.clear();
+}
+
+void AcceptTracker::checkPending()
+{
+ while (!pending.empty() && pending.front().status.isComplete()) {
+ completed(pending.front().accepted);
+ pending.pop_front();
+ }
+}
+
+void AcceptTracker::completed(qpid::framing::SequenceSet& set)
+{
+ for (StateMap::iterator i = destinationState.begin(); i != destinationState.end(); ++i) {
+ i->second.completed(set);
+ }
+ aggregateState.completed(set);
+}
+
+}}} // namespace qpid::client::amqp0_10
diff --git a/qpid/cpp/src/qpid/client/amqp0_10/AcceptTracker.h b/qpid/cpp/src/qpid/client/amqp0_10/AcceptTracker.h
new file mode 100644
index 0000000000..fb58a3a8c8
--- /dev/null
+++ b/qpid/cpp/src/qpid/client/amqp0_10/AcceptTracker.h
@@ -0,0 +1,85 @@
+#ifndef QPID_CLIENT_AMQP0_10_ACCEPTTRACKER_H
+#define QPID_CLIENT_AMQP0_10_ACCEPTTRACKER_H
+
+/*
+ *
+ * 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.
+ *
+ */
+#include "qpid/client/AsyncSession.h"
+#include "qpid/client/Completion.h"
+#include "qpid/framing/SequenceNumber.h"
+#include "qpid/framing/SequenceSet.h"
+#include <deque>
+#include <map>
+
+namespace qpid {
+namespace client {
+namespace amqp0_10 {
+
+/**
+ * Tracks the set of messages requiring acceptance, and those for
+ * which an accept has been issued but is yet to be confirmed
+ * complete.
+ */
+class AcceptTracker
+{
+ public:
+ void delivered(const std::string& destination, const qpid::framing::SequenceNumber& id);
+ void accept(qpid::client::AsyncSession&);
+ void release(qpid::client::AsyncSession&);
+ uint32_t acceptsPending();
+ uint32_t acceptsPending(const std::string& destination);
+ void reset();
+ private:
+ struct State
+ {
+ /**
+ * ids of messages that have been delivered but not yet
+ * accepted
+ */
+ qpid::framing::SequenceSet unaccepted;
+ /**
+ * ids of messages for which an accpet has been issued but not
+ * yet confirmed as completed
+ */
+ qpid::framing::SequenceSet unconfirmed;
+
+ void accept();
+ void release();
+ uint32_t acceptsPending();
+ void completed(qpid::framing::SequenceSet&);
+ };
+ typedef std::map<std::string, State> StateMap;
+ struct Record
+ {
+ qpid::client::Completion status;
+ qpid::framing::SequenceSet accepted;
+ };
+ typedef std::deque<Record> Records;
+
+ State aggregateState;
+ StateMap destinationState;
+ Records pending;
+
+ void checkPending();
+ void completed(qpid::framing::SequenceSet&);
+};
+}}} // namespace qpid::client::amqp0_10
+
+#endif /*!QPID_CLIENT_AMQP0_10_ACCEPTTRACKER_H*/
diff --git a/qpid/cpp/src/qpid/client/amqp0_10/CompletionTracker.cpp b/qpid/cpp/src/qpid/client/amqp0_10/CompletionTracker.cpp
deleted file mode 100644
index 52b623b65c..0000000000
--- a/qpid/cpp/src/qpid/client/amqp0_10/CompletionTracker.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-#include "CompletionTracker.h"
-
-namespace qpid {
-namespace client {
-namespace amqp0_10 {
-
-using qpid::framing::SequenceNumber;
-
-void CompletionTracker::track(SequenceNumber command, void* token)
-{
- tokens[command] = token;
-}
-
-void CompletionTracker::completedTo(SequenceNumber command)
-{
- Tokens::iterator i = tokens.lower_bound(command);
- if (i != tokens.end()) {
- lastCompleted = i->second;
- tokens.erase(tokens.begin(), ++i);
- }
-}
-
-void* CompletionTracker::getLastCompletedToken()
-{
- return lastCompleted;
-}
-
-}}} // namespace qpid::client::amqp0_10
diff --git a/qpid/cpp/src/qpid/client/amqp0_10/CompletionTracker.h b/qpid/cpp/src/qpid/client/amqp0_10/CompletionTracker.h
deleted file mode 100644
index 6147c5682e..0000000000
--- a/qpid/cpp/src/qpid/client/amqp0_10/CompletionTracker.h
+++ /dev/null
@@ -1,50 +0,0 @@
-#ifndef QPID_CLIENT_AMQP0_10_COMPLETIONTRACKER_H
-#define QPID_CLIENT_AMQP0_10_COMPLETIONTRACKER_H
-
-/*
- *
- * 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.
- *
- */
-
-#include "qpid/framing/SequenceNumber.h"
-#include <map>
-
-namespace qpid {
-namespace client {
-namespace amqp0_10 {
-
-/**
- * Provides a mapping from command ids to application supplied
- * 'tokens', and is used to determine when the sending or
- * acknowledging of a specific message is complete.
- */
-class CompletionTracker
-{
- public:
- void track(qpid::framing::SequenceNumber command, void* token);
- void completedTo(qpid::framing::SequenceNumber command);
- void* getLastCompletedToken();
- private:
- typedef std::map<qpid::framing::SequenceNumber, void*> Tokens;
- Tokens tokens;
- void* lastCompleted;
-};
-}}} // namespace qpid::client::amqp0_10
-
-#endif /*!QPID_CLIENT_AMQP0_10_COMPLETIONTRACKER_H*/
diff --git a/qpid/cpp/src/qpid/client/amqp0_10/IncomingMessages.cpp b/qpid/cpp/src/qpid/client/amqp0_10/IncomingMessages.cpp
index b0a16674e1..d22208368b 100644
--- a/qpid/cpp/src/qpid/client/amqp0_10/IncomingMessages.cpp
+++ b/qpid/cpp/src/qpid/client/amqp0_10/IncomingMessages.cpp
@@ -81,12 +81,31 @@ struct MatchAndTrack
}
}
};
+
+struct Match
+{
+ const std::string destination;
+ uint32_t matched;
+
+ Match(const std::string& d) : destination(d), matched(0) {}
+
+ bool operator()(boost::shared_ptr<qpid::framing::FrameSet> command)
+ {
+ if (command->as<MessageTransferBody>()->getDestination() == destination) {
+ ++matched;
+ return true;
+ } else {
+ return false;
+ }
+ }
+};
}
void IncomingMessages::setSession(qpid::client::AsyncSession s)
{
session = s;
incoming = SessionBase_0_10Access(session).get()->getDemux().getDefault();
+ acceptTracker.reset();
}
bool IncomingMessages::get(Handler& handler, Duration timeout)
@@ -106,8 +125,7 @@ bool IncomingMessages::get(Handler& handler, Duration timeout)
void IncomingMessages::accept()
{
- session.messageAccept(unaccepted);
- unaccepted.clear();
+ acceptTracker.accept(session);
}
void IncomingMessages::releaseAll()
@@ -121,8 +139,7 @@ void IncomingMessages::releaseAll()
GetAny handler;
while (process(&handler, 0)) ;
//now release all messages
- session.messageRelease(unaccepted);
- unaccepted.clear();
+ acceptTracker.release(session);
}
void IncomingMessages::releasePending(const std::string& destination)
@@ -166,6 +183,32 @@ bool IncomingMessages::process(Handler* handler, qpid::sys::Duration duration)
return false;
}
+uint32_t IncomingMessages::pendingAccept()
+{
+ return acceptTracker.acceptsPending();
+}
+uint32_t IncomingMessages::pendingAccept(const std::string& destination)
+{
+ return acceptTracker.acceptsPending(destination);
+}
+
+uint32_t IncomingMessages::available()
+{
+ //first pump all available messages from incoming to received...
+ while (process(0, 0)) {}
+ //return the count of received messages
+ return received.size();
+}
+
+uint32_t IncomingMessages::available(const std::string& destination)
+{
+ //first pump all available messages from incoming to received...
+ while (process(0, 0)) {}
+
+ //count all messages for this destination from received list
+ return std::for_each(received.begin(), received.end(), Match(destination)).matched;
+}
+
void populate(qpid::messaging::Message& message, FrameSet& command);
/**
@@ -180,7 +223,7 @@ void IncomingMessages::retrieve(FrameSetPtr command, qpid::messaging::Message* m
}
const MessageTransferBody* transfer = command->as<MessageTransferBody>();
if (transfer->getAcquireMode() == ACQUIRE_MODE_PRE_ACQUIRED && transfer->getAcceptMode() == ACCEPT_MODE_EXPLICIT) {
- unaccepted.add(command->getId());
+ acceptTracker.delivered(transfer->getDestination(), command->getId());
}
session.markCompleted(command->getId(), false, false);
}
diff --git a/qpid/cpp/src/qpid/client/amqp0_10/IncomingMessages.h b/qpid/cpp/src/qpid/client/amqp0_10/IncomingMessages.h
index 5e28877305..e84cd18892 100644
--- a/qpid/cpp/src/qpid/client/amqp0_10/IncomingMessages.h
+++ b/qpid/cpp/src/qpid/client/amqp0_10/IncomingMessages.h
@@ -27,6 +27,7 @@
#include "qpid/framing/SequenceSet.h"
#include "qpid/sys/BlockingQueue.h"
#include "qpid/sys/Time.h"
+#include "qpid/client/amqp0_10/AcceptTracker.h"
namespace qpid {
@@ -74,13 +75,19 @@ class IncomingMessages
void accept();
void releaseAll();
void releasePending(const std::string& destination);
+
+ uint32_t pendingAccept();
+ uint32_t pendingAccept(const std::string& destination);
+
+ uint32_t available();
+ uint32_t available(const std::string& destination);
private:
typedef std::deque<FrameSetPtr> FrameSetQueue;
qpid::client::AsyncSession session;
- qpid::framing::SequenceSet unaccepted;
boost::shared_ptr< sys::BlockingQueue<FrameSetPtr> > incoming;
FrameSetQueue received;
+ AcceptTracker acceptTracker;
bool process(Handler*, qpid::sys::Duration);
void retrieve(FrameSetPtr, qpid::messaging::Message*);
diff --git a/qpid/cpp/src/qpid/client/amqp0_10/ReceiverImpl.cpp b/qpid/cpp/src/qpid/client/amqp0_10/ReceiverImpl.cpp
index 31efff38a6..da91c4a160 100644
--- a/qpid/cpp/src/qpid/client/amqp0_10/ReceiverImpl.cpp
+++ b/qpid/cpp/src/qpid/client/amqp0_10/ReceiverImpl.cpp
@@ -120,6 +120,21 @@ qpid::messaging::MessageListener* ReceiverImpl::getListener() { return listener;
const std::string& ReceiverImpl::getName() const { return destination; }
+uint32_t ReceiverImpl::getCapacity()
+{
+ return capacity;
+}
+
+uint32_t ReceiverImpl::available()
+{
+ return parent.available(destination);
+}
+
+uint32_t ReceiverImpl::pendingAck()
+{
+ return parent.pendingAck(destination);
+}
+
ReceiverImpl::ReceiverImpl(SessionImpl& p, const std::string& name,
const qpid::messaging::Address& a,
const qpid::messaging::Filter* f,
diff --git a/qpid/cpp/src/qpid/client/amqp0_10/ReceiverImpl.h b/qpid/cpp/src/qpid/client/amqp0_10/ReceiverImpl.h
index 509c784513..b941348fc8 100644
--- a/qpid/cpp/src/qpid/client/amqp0_10/ReceiverImpl.h
+++ b/qpid/cpp/src/qpid/client/amqp0_10/ReceiverImpl.h
@@ -62,6 +62,9 @@ class ReceiverImpl : public qpid::messaging::ReceiverImpl
void stop();
const std::string& getName() const;
void setCapacity(uint32_t);
+ uint32_t getCapacity();
+ uint32_t available();
+ uint32_t pendingAck();
void setListener(qpid::messaging::MessageListener* listener);
qpid::messaging::MessageListener* getListener();
void received(qpid::messaging::Message& message);
diff --git a/qpid/cpp/src/qpid/client/amqp0_10/SenderImpl.cpp b/qpid/cpp/src/qpid/client/amqp0_10/SenderImpl.cpp
index c619d1226a..4cd2dc0521 100644
--- a/qpid/cpp/src/qpid/client/amqp0_10/SenderImpl.cpp
+++ b/qpid/cpp/src/qpid/client/amqp0_10/SenderImpl.cpp
@@ -32,11 +32,12 @@ SenderImpl::SenderImpl(SessionImpl& _parent, const std::string& _name,
const qpid::messaging::Address& _address,
const qpid::messaging::Variant::Map& _options) :
parent(_parent), name(_name), address(_address), options(_options), state(UNRESOLVED),
- capacity(50), window(0) {}
+ capacity(50), window(0), flushed(false) {}
-void SenderImpl::send(const qpid::messaging::Message& m)
+void SenderImpl::send(const qpid::messaging::Message& message)
{
- execute1<Send>(&m);
+ Send f(*this, &message);
+ while (f.repeat) parent.execute(f);
}
void SenderImpl::cancel()
@@ -44,6 +45,20 @@ void SenderImpl::cancel()
execute<Cancel>();
}
+void SenderImpl::setCapacity(uint32_t c)
+{
+ bool flush = c < capacity;
+ capacity = c;
+ execute1<CheckPendingSends>(flush);
+}
+uint32_t SenderImpl::getCapacity() { return capacity; }
+uint32_t SenderImpl::pending()
+{
+ CheckPendingSends f(*this, false);
+ parent.execute(f);
+ return f.pending;
+}
+
void SenderImpl::init(qpid::client::AsyncSession s, AddressResolution& resolver)
{
session = s;
@@ -60,18 +75,31 @@ void SenderImpl::init(qpid::client::AsyncSession s, AddressResolution& resolver)
}
}
+void SenderImpl::waitForCapacity()
+{
+ //TODO: add option to throw exception rather than blocking?
+ if (capacity <= (flushed ? checkPendingSends(false) : outgoing.size())) {
+ //Initial implementation is very basic. As outgoing is
+ //currently only reduced on receiving completions and we are
+ //blocking anyway we may as well sync(). If successful that
+ //should clear all outstanding sends.
+ session.sync();
+ checkPendingSends(false);
+ }
+ //flush periodically and check for conmpleted sends
+ if (++window > (capacity / 4)) {//TODO: make this configurable?
+ checkPendingSends(true);
+ window = 0;
+ }
+}
+
void SenderImpl::sendImpl(const qpid::messaging::Message& m)
{
- //TODO: make recoding for replay optional
+ //TODO: make recording for replay optional (would still want to track completion however)
std::auto_ptr<OutgoingMessage> msg(new OutgoingMessage());
msg->convert(m);
outgoing.push_back(msg.release());
sink->send(session, name, outgoing.back());
- if (++window > (capacity / 2)) {//TODO: make this configurable?
- session.flush();
- checkPendingSends();
- window = 0;
- }
}
void SenderImpl::replay()
@@ -81,11 +109,18 @@ void SenderImpl::replay()
}
}
-void SenderImpl::checkPendingSends()
+uint32_t SenderImpl::checkPendingSends(bool flush)
{
+ if (flush) {
+ session.flush();
+ flushed = true;
+ } else {
+ flushed = false;
+ }
while (!outgoing.empty() && outgoing.front().status.isComplete()) {
outgoing.pop_front();
}
+ return outgoing.size();
}
void SenderImpl::cancelImpl()
diff --git a/qpid/cpp/src/qpid/client/amqp0_10/SenderImpl.h b/qpid/cpp/src/qpid/client/amqp0_10/SenderImpl.h
index 4ba793d71c..028d26bda7 100644
--- a/qpid/cpp/src/qpid/client/amqp0_10/SenderImpl.h
+++ b/qpid/cpp/src/qpid/client/amqp0_10/SenderImpl.h
@@ -51,6 +51,9 @@ class SenderImpl : public qpid::messaging::SenderImpl
const qpid::messaging::Variant::Map& options);
void send(const qpid::messaging::Message&);
void cancel();
+ void setCapacity(uint32_t);
+ uint32_t getCapacity();
+ uint32_t pending();
void init(qpid::client::AsyncSession, AddressResolution&);
private:
@@ -69,14 +72,17 @@ class SenderImpl : public qpid::messaging::SenderImpl
OutgoingMessages outgoing;
uint32_t capacity;
uint32_t window;
+ bool flushed;
- void checkPendingSends();
+ uint32_t checkPendingSends(bool flush);
void replay();
+ void waitForCapacity();
//logic for application visible methods:
void sendImpl(const qpid::messaging::Message&);
void cancelImpl();
+
//functors for application visible methods (allowing locking and
//retry to be centralised):
struct Command
@@ -89,9 +95,17 @@ class SenderImpl : public qpid::messaging::SenderImpl
struct Send : Command
{
const qpid::messaging::Message* message;
-
- Send(SenderImpl& i, const qpid::messaging::Message* m) : Command(i), message(m) {}
- void operator()() { impl.sendImpl(*message); }
+ bool repeat;
+
+ Send(SenderImpl& i, const qpid::messaging::Message* m) : Command(i), message(m), repeat(true) {}
+ void operator()()
+ {
+ impl.waitForCapacity();
+ //from this point message will be recorded if there is any
+ //failure (and replayed) so need not repeat the call
+ repeat = false;
+ impl.sendImpl(*message);
+ }
};
struct Cancel : Command
@@ -100,6 +114,14 @@ class SenderImpl : public qpid::messaging::SenderImpl
void operator()() { impl.cancelImpl(); }
};
+ struct CheckPendingSends : Command
+ {
+ bool flush;
+ uint32_t pending;
+ CheckPendingSends(SenderImpl& i, bool f) : Command(i), flush(f), pending(0) {}
+ void operator()() { pending = impl.checkPendingSends(flush); }
+ };
+
//helper templates for some common patterns
template <class F> void execute()
{
@@ -107,10 +129,10 @@ class SenderImpl : public qpid::messaging::SenderImpl
parent.execute(f);
}
- template <class F, class P> void execute1(P p)
+ template <class F, class P> bool execute1(P p)
{
F f(*this, p);
- parent.execute(f);
+ return parent.execute(f);
}
};
}}} // namespace qpid::client::amqp0_10
diff --git a/qpid/cpp/src/qpid/client/amqp0_10/SessionImpl.cpp b/qpid/cpp/src/qpid/client/amqp0_10/SessionImpl.cpp
index 0e6c430d89..bc6289d84b 100644
--- a/qpid/cpp/src/qpid/client/amqp0_10/SessionImpl.cpp
+++ b/qpid/cpp/src/qpid/client/amqp0_10/SessionImpl.cpp
@@ -298,6 +298,61 @@ bool SessionImpl::fetch(qpid::messaging::Message& message, qpid::sys::Duration t
}
}
+uint32_t SessionImpl::available()
+{
+ return get1<Available, uint32_t>((const std::string*) 0);
+}
+uint32_t SessionImpl::available(const std::string& destination)
+{
+ return get1<Available, uint32_t>(&destination);
+}
+
+struct SessionImpl::Available : Command
+{
+ const std::string* destination;
+ uint32_t result;
+
+ Available(SessionImpl& i, const std::string* d) : Command(i), destination(d), result(0) {}
+ void operator()() { result = impl.availableImpl(destination); }
+};
+
+uint32_t SessionImpl::availableImpl(const std::string* destination)
+{
+ if (destination) {
+ return incoming.available(*destination);
+ } else {
+ return incoming.available();
+ }
+}
+
+uint32_t SessionImpl::pendingAck()
+{
+ return get1<PendingAck, uint32_t>((const std::string*) 0);
+}
+
+uint32_t SessionImpl::pendingAck(const std::string& destination)
+{
+ return get1<PendingAck, uint32_t>(&destination);
+}
+
+struct SessionImpl::PendingAck : Command
+{
+ const std::string* destination;
+ uint32_t result;
+
+ PendingAck(SessionImpl& i, const std::string* d) : Command(i), destination(d), result(0) {}
+ void operator()() { result = impl.pendingAckImpl(destination); }
+};
+
+uint32_t SessionImpl::pendingAckImpl(const std::string* destination)
+{
+ if (destination) {
+ return incoming.pendingAccept(*destination);
+ } else {
+ return incoming.pendingAccept();
+ }
+}
+
void SessionImpl::syncImpl()
{
session.sync();
diff --git a/qpid/cpp/src/qpid/client/amqp0_10/SessionImpl.h b/qpid/cpp/src/qpid/client/amqp0_10/SessionImpl.h
index 1c7db17bbb..b453f3f08f 100644
--- a/qpid/cpp/src/qpid/client/amqp0_10/SessionImpl.h
+++ b/qpid/cpp/src/qpid/client/amqp0_10/SessionImpl.h
@@ -83,6 +83,12 @@ class SessionImpl : public qpid::messaging::SessionImpl
void receiverCancelled(const std::string& name);
void senderCancelled(const std::string& name);
+ uint32_t available();
+ uint32_t available(const std::string& destination);
+
+ uint32_t pendingAck();
+ uint32_t pendingAck(const std::string& destination);
+
void setSession(qpid::client::Session);
template <class T> bool execute(T& f)
@@ -128,6 +134,8 @@ class SessionImpl : public qpid::messaging::SessionImpl
qpid::messaging::Receiver createReceiverImpl(const qpid::messaging::Address& address,
const qpid::messaging::Filter* filter,
const qpid::messaging::VariantMap& options);
+ uint32_t availableImpl(const std::string* destination);
+ uint32_t pendingAckImpl(const std::string* destination);
//functors for public facing methods (allows locking and retry
//logic to be centralised)
@@ -178,6 +186,8 @@ class SessionImpl : public qpid::messaging::SessionImpl
struct CreateSender;
struct CreateReceiver;
+ struct PendingAck;
+ struct Available;
//helper templates for some common patterns
template <class F> bool execute()
@@ -196,6 +206,13 @@ class SessionImpl : public qpid::messaging::SessionImpl
F f(*this, p);
return execute(f);
}
+
+ template <class F, class R, class P> R get1(P p)
+ {
+ F f(*this, p);
+ while (!execute(f)) {}
+ return f.result;
+ }
};
}}} // namespace qpid::client::amqp0_10
diff --git a/qpid/cpp/src/qpid/cluster/Connection.cpp b/qpid/cpp/src/qpid/cluster/Connection.cpp
index 4cc977d14a..6873827b81 100644
--- a/qpid/cpp/src/qpid/cluster/Connection.cpp
+++ b/qpid/cpp/src/qpid/cluster/Connection.cpp
@@ -156,8 +156,17 @@ bool Connection::checkUnsupported(const AMQBody& body) {
return !message.empty();
}
+struct GiveReadCreditOnExit {
+ Connection& connection;
+ int credit;
+ GiveReadCreditOnExit(Connection& connection_, int credit_) :
+ connection(connection_), credit(credit_) {}
+ ~GiveReadCreditOnExit() { connection.giveReadCredit(credit); }
+};
+
// Called in delivery thread, in cluster order.
void Connection::deliveredFrame(const EventFrame& f) {
+ GiveReadCreditOnExit gc(*this, f.readCredit);
assert(!catchUp);
currentChannel = f.frame.getChannel();
if (f.frame.getBody() // frame can be emtpy with just readCredit
@@ -171,7 +180,6 @@ void Connection::deliveredFrame(const EventFrame& f) {
if (ss) ss->out(const_cast<AMQFrame&>(f.frame));
}
}
- giveReadCredit(f.readCredit);
}
// A local connection is closed by the network layer.
diff --git a/qpid/cpp/src/qpid/cluster/Quorum_cman.cpp b/qpid/cpp/src/qpid/cluster/Quorum_cman.cpp
index 277adaf7b1..507d9649b9 100644
--- a/qpid/cpp/src/qpid/cluster/Quorum_cman.cpp
+++ b/qpid/cpp/src/qpid/cluster/Quorum_cman.cpp
@@ -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
@@ -33,8 +33,8 @@ namespace {
boost::function<void()> errorFn;
-void cmanCallbackFn(cman_handle_t handle, void */*privdata*/, int reason, int arg) {
- if (reason == CMAN_REASON_STATECHANGE && arg == 0) {
+void cmanCallbackFn(cman_handle_t handle, void */*privdata*/, int reason, int /*arg*/) {
+ if (reason == CMAN_REASON_STATECHANGE && !cman_is_quorate(handle)) {
QPID_LOG(critical, "Lost contact with cluster quorum.");
if (errorFn) errorFn();
cman_stop_notification(handle);
diff --git a/qpid/cpp/src/qpid/messaging/Address.cpp b/qpid/cpp/src/qpid/messaging/Address.cpp
index ed35054a00..813a8e1377 100644
--- a/qpid/cpp/src/qpid/messaging/Address.cpp
+++ b/qpid/cpp/src/qpid/messaging/Address.cpp
@@ -21,9 +21,6 @@
#include "qpid/messaging/Address.h"
namespace qpid {
-namespace client {
-}
-
namespace messaging {
Address::Address() {}
diff --git a/qpid/cpp/src/qpid/messaging/Receiver.cpp b/qpid/cpp/src/qpid/messaging/Receiver.cpp
index 2e8b89d27f..3290ea98ac 100644
--- a/qpid/cpp/src/qpid/messaging/Receiver.cpp
+++ b/qpid/cpp/src/qpid/messaging/Receiver.cpp
@@ -45,6 +45,9 @@ Message Receiver::fetch(qpid::sys::Duration timeout) { return impl->fetch(timeou
void Receiver::start() { impl->start(); }
void Receiver::stop() { impl->stop(); }
void Receiver::setCapacity(uint32_t c) { impl->setCapacity(c); }
+uint32_t Receiver::getCapacity() { return impl->getCapacity(); }
+uint32_t Receiver::available() { return impl->available(); }
+uint32_t Receiver::pendingAck() { return impl->pendingAck(); }
void Receiver::cancel() { impl->cancel(); }
void Receiver::setListener(MessageListener* listener) { impl->setListener(listener); }
diff --git a/qpid/cpp/src/qpid/messaging/ReceiverImpl.h b/qpid/cpp/src/qpid/messaging/ReceiverImpl.h
index 77697b730c..7db20acc29 100644
--- a/qpid/cpp/src/qpid/messaging/ReceiverImpl.h
+++ b/qpid/cpp/src/qpid/messaging/ReceiverImpl.h
@@ -44,6 +44,9 @@ class ReceiverImpl : public virtual qpid::RefCounted
virtual void start() = 0;
virtual void stop() = 0;
virtual void setCapacity(uint32_t) = 0;
+ virtual uint32_t getCapacity() = 0;
+ virtual uint32_t available() = 0;
+ virtual uint32_t pendingAck() = 0;
virtual void cancel() = 0;
virtual void setListener(MessageListener*) = 0;
};
diff --git a/qpid/cpp/src/qpid/messaging/Sender.cpp b/qpid/cpp/src/qpid/messaging/Sender.cpp
index 8db700b060..62b2944701 100644
--- a/qpid/cpp/src/qpid/messaging/Sender.cpp
+++ b/qpid/cpp/src/qpid/messaging/Sender.cpp
@@ -40,5 +40,8 @@ Sender::~Sender() { PI::dtor(*this); }
Sender& Sender::operator=(const Sender& s) { return PI::assign(*this, s); }
void Sender::send(const Message& message) { impl->send(message); }
void Sender::cancel() { impl->cancel(); }
+void Sender::setCapacity(uint32_t c) { impl->setCapacity(c); }
+uint32_t Sender::getCapacity() { return impl->getCapacity(); }
+uint32_t Sender::pending() { return impl->pending(); }
}} // namespace qpid::messaging
diff --git a/qpid/cpp/src/qpid/messaging/SenderImpl.h b/qpid/cpp/src/qpid/messaging/SenderImpl.h
index 77d2cfaeaf..fa3794ca4e 100644
--- a/qpid/cpp/src/qpid/messaging/SenderImpl.h
+++ b/qpid/cpp/src/qpid/messaging/SenderImpl.h
@@ -37,6 +37,9 @@ class SenderImpl : public virtual qpid::RefCounted
virtual ~SenderImpl() {}
virtual void send(const Message& message) = 0;
virtual void cancel() = 0;
+ virtual void setCapacity(uint32_t) = 0;
+ virtual uint32_t getCapacity() = 0;
+ virtual uint32_t pending() = 0;
private:
};
}} // namespace qpid::messaging
diff --git a/qpid/cpp/src/qpid/messaging/Session.cpp b/qpid/cpp/src/qpid/messaging/Session.cpp
index 284b20dacc..62b1ca0dcf 100644
--- a/qpid/cpp/src/qpid/messaging/Session.cpp
+++ b/qpid/cpp/src/qpid/messaging/Session.cpp
@@ -103,15 +103,7 @@ bool Session::dispatch(qpid::sys::Duration timeout)
{
return impl->dispatch(timeout);
}
-
-void* Session::getLastConfirmedSent()
-{
- return impl->getLastConfirmedSent();
-}
-
-void* Session::getLastConfirmedAcknowledged()
-{
- return impl->getLastConfirmedAcknowledged();
-}
+uint32_t Session::available() { return impl->available(); }
+uint32_t Session::pendingAck() { return impl->pendingAck(); }
}} // namespace qpid::messaging
diff --git a/qpid/cpp/src/qpid/messaging/SessionImpl.h b/qpid/cpp/src/qpid/messaging/SessionImpl.h
index 9b122a24bc..0933cea9c8 100644
--- a/qpid/cpp/src/qpid/messaging/SessionImpl.h
+++ b/qpid/cpp/src/qpid/messaging/SessionImpl.h
@@ -56,8 +56,8 @@ class SessionImpl : public virtual qpid::RefCounted
virtual Sender createSender(const Address& address, const VariantMap& options) = 0;
virtual Receiver createReceiver(const Address& address, const VariantMap& options) = 0;
virtual Receiver createReceiver(const Address& address, const Filter& filter, const VariantMap& options) = 0;
- virtual void* getLastConfirmedSent() = 0;
- virtual void* getLastConfirmedAcknowledged() = 0;
+ virtual uint32_t available() = 0;
+ virtual uint32_t pendingAck() = 0;
private:
};
}} // namespace qpid::messaging
diff --git a/qpid/cpp/src/qpid/sys/rdma/RdmaClient.cpp b/qpid/cpp/src/qpid/sys/rdma/RdmaClient.cpp
index 52208d0519..9da6c835ce 100644
--- a/qpid/cpp/src/qpid/sys/rdma/RdmaClient.cpp
+++ b/qpid/cpp/src/qpid/sys/rdma/RdmaClient.cpp
@@ -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
@@ -45,6 +45,9 @@ using qpid::sys::Duration;
using qpid::sys::TIME_SEC;
using qpid::sys::TIME_INFINITE;
+namespace qpid {
+namespace tests {
+
// count of messages
int64_t smsgs = 0;
int64_t sbytes = 0;
@@ -144,6 +147,10 @@ void rejected(boost::shared_ptr<Poller> p, Rdma::Connection::intrusive_ptr&, con
p->shutdown();
}
+}} // namespace qpid::tests
+
+using namespace qpid::tests;
+
int main(int argc, char* argv[]) {
vector<string> args(&argv[0], &argv[argc]);
diff --git a/qpid/cpp/src/qpid/sys/rdma/RdmaServer.cpp b/qpid/cpp/src/qpid/sys/rdma/RdmaServer.cpp
index 1ab5268596..07d6379362 100644
--- a/qpid/cpp/src/qpid/sys/rdma/RdmaServer.cpp
+++ b/qpid/cpp/src/qpid/sys/rdma/RdmaServer.cpp
@@ -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
@@ -39,6 +39,9 @@ using qpid::sys::Poller;
using qpid::sys::Dispatcher;
// All the accepted connections
+namespace qpid {
+namespace tests {
+
struct ConRec {
Rdma::Connection::intrusive_ptr connection;
Rdma::AsynchIO* data;
@@ -134,6 +137,10 @@ void connected(Poller::shared_ptr poller, Rdma::Connection::intrusive_ptr& ci) {
cr->data->start(poller);
}
+}} // namespace qpid::tests
+
+using namespace qpid::tests;
+
int main(int argc, char* argv[]) {
vector<string> args(&argv[0], &argv[argc]);
diff --git a/qpid/cpp/src/qpid/xml/XmlExchange.cpp b/qpid/cpp/src/qpid/xml/XmlExchange.cpp
index a41c8840ff..8a1ef6149e 100644
--- a/qpid/cpp/src/qpid/xml/XmlExchange.cpp
+++ b/qpid/cpp/src/qpid/xml/XmlExchange.cpp
@@ -156,7 +156,7 @@ bool XmlExchange::matches(Query& query, Deliverable& msg, const qpid::framing::F
// This will parse the document using either Xerces or FastXDM, depending
// on your XQilla configuration. FastXDM can be as much as 10x faster.
-
+
Sequence seq(context->parseDocument(xml));
if(!seq.isEmpty() && seq.first()->isNode()) {
@@ -206,11 +206,11 @@ void XmlExchange::route(Deliverable& msg, const string& routingKey, const FieldT
PreRoute pr(msg, this);
try {
XmlBinding::vector::ConstPtr p;
- {
+ {
RWlock::ScopedRlock l(lock);
- p = bindingsMap[routingKey].snapshot();
- if (!p) return;
- }
+ p = bindingsMap[routingKey].snapshot();
+ if (!p) return;
+ }
int count(0);
for (std::vector<XmlBinding::shared_ptr>::const_iterator i = p->begin(); i != p->end(); i++) {
@@ -222,24 +222,24 @@ void XmlExchange::route(Deliverable& msg, const string& routingKey, const FieldT
if ((*i)->mgmtBinding != 0)
(*i)->mgmtBinding->inc_msgMatched ();
}
- }
- if (!count) {
- QPID_LOG(warning, "XMLExchange " << getName() << ": could not route message with query " << routingKey);
- if (mgmtExchange != 0) {
- mgmtExchange->inc_msgDrops ();
- mgmtExchange->inc_byteDrops (msg.contentSize ());
- }
- } else {
- if (mgmtExchange != 0) {
- mgmtExchange->inc_msgRoutes (count);
- mgmtExchange->inc_byteRoutes (count * msg.contentSize ());
- }
- }
-
- if (mgmtExchange != 0) {
- mgmtExchange->inc_msgReceives ();
- mgmtExchange->inc_byteReceives (msg.contentSize ());
- }
+ }
+ if (!count) {
+ QPID_LOG(warning, "XMLExchange " << getName() << ": could not route message with query " << routingKey);
+ if (mgmtExchange != 0) {
+ mgmtExchange->inc_msgDrops ();
+ mgmtExchange->inc_byteDrops (msg.contentSize ());
+ }
+ } else {
+ if (mgmtExchange != 0) {
+ mgmtExchange->inc_msgRoutes (count);
+ mgmtExchange->inc_byteRoutes (count * msg.contentSize ());
+ }
+ }
+
+ if (mgmtExchange != 0) {
+ mgmtExchange->inc_msgReceives ();
+ mgmtExchange->inc_byteReceives (msg.contentSize ());
+ }
} catch (...) {
QPID_LOG(warning, "XMLExchange " << getName() << ": exception routing message with query " << routingKey);
}
diff --git a/qpid/cpp/src/tests/AccumulatedAckTest.cpp b/qpid/cpp/src/tests/AccumulatedAckTest.cpp
index 028ce71907..c736a519d2 100644
--- a/qpid/cpp/src/tests/AccumulatedAckTest.cpp
+++ b/qpid/cpp/src/tests/AccumulatedAckTest.cpp
@@ -8,9 +8,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
@@ -28,6 +28,9 @@ using std::list;
using namespace qpid::framing;
+namespace qpid {
+namespace tests {
+
bool covers(const AccumulatedAck& ack, int i)
{
return ack.covers(SequenceNumber(i));
@@ -97,7 +100,7 @@ QPID_AUTO_TEST_CASE(testUpdateFromCompletionData)
ack.update(mark, ranges);
- for(int i = 0; i <= 15; i++) {
+ for(int i = 0; i <= 15; i++) {
BOOST_CHECK(covers(ack, i));
}
BOOST_CHECK(!covers(ack, 16));
@@ -221,7 +224,7 @@ QPID_AUTO_TEST_CASE(testConsolidation4)
ack.update(SequenceNumber(9), SequenceNumber(9));
ack.update(SequenceNumber(3), SequenceNumber(4));
- for(int i = 0; i <= 15; i++) {
+ for(int i = 0; i <= 15; i++) {
BOOST_CHECK(covers(ack, i));
}
BOOST_CHECK(!covers(ack, 16));
@@ -230,3 +233,5 @@ QPID_AUTO_TEST_CASE(testConsolidation4)
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/Array.cpp b/qpid/cpp/src/tests/Array.cpp
index c779cbe901..7622b89d15 100644
--- a/qpid/cpp/src/tests/Array.cpp
+++ b/qpid/cpp/src/tests/Array.cpp
@@ -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
@@ -25,6 +25,9 @@
#include "unit_test.h"
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(ArrayTestSuite)
using namespace qpid::framing;
@@ -69,7 +72,7 @@ QPID_AUTO_TEST_CASE(testArrayAssignment)
Array a(data);
b = a;
BOOST_CHECK_EQUAL(a, b);
- }
+ }
std::vector<std::string> data2;
b.collect(data2);
//BOOST_CHECK_EQUAL(data, data2);
@@ -77,3 +80,5 @@ QPID_AUTO_TEST_CASE(testArrayAssignment)
}
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/AsyncCompletion.cpp b/qpid/cpp/src/tests/AsyncCompletion.cpp
index 41423d8245..4492e6b6bc 100644
--- a/qpid/cpp/src/tests/AsyncCompletion.cpp
+++ b/qpid/cpp/src/tests/AsyncCompletion.cpp
@@ -49,10 +49,13 @@ using boost::intrusive_ptr;
* message enqueues at the correct time.
*/
+namespace qpid {
+namespace tests {
+
class AsyncCompletionMessageStore : public NullMessageStore {
public:
sys::BlockingQueue<boost::intrusive_ptr<PersistableMessage> > enqueued;
-
+
AsyncCompletionMessageStore() : NullMessageStore() {}
~AsyncCompletionMessageStore(){}
@@ -82,10 +85,10 @@ QPID_AUTO_TEST_CASE(testWaitTillComplete) {
transfers[i] = s.messageTransfer(arg::content=msg);
}
- // Get hold of the broker-side messages.
+ // Get hold of the broker-side messages.
typedef vector<intrusive_ptr<PersistableMessage> > BrokerMessages;
BrokerMessages enqueued;
- for (int j = 0; j < count; ++j)
+ for (int j = 0; j < count; ++j)
enqueued.push_back(store->enqueued.pop(TIME_SEC));
// Send a sync, make sure it does not complete till all messages are complete.
@@ -111,3 +114,5 @@ QPID_AUTO_TEST_CASE(testGetResult) {
}
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/AtomicValue.cpp b/qpid/cpp/src/tests/AtomicValue.cpp
index 05083ad177..d855d993a7 100644
--- a/qpid/cpp/src/tests/AtomicValue.cpp
+++ b/qpid/cpp/src/tests/AtomicValue.cpp
@@ -21,6 +21,9 @@
#include "test_tools.h"
#include "qpid/sys/AtomicValue.h"
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(AtomicValueTestSuite)
QPID_AUTO_TEST_CASE(test) {
@@ -47,3 +50,5 @@ QPID_AUTO_TEST_CASE(test) {
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/BrokerFixture.h b/qpid/cpp/src/tests/BrokerFixture.h
index 397045d00b..bb985cf7e1 100644
--- a/qpid/cpp/src/tests/BrokerFixture.h
+++ b/qpid/cpp/src/tests/BrokerFixture.h
@@ -10,9 +10,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
@@ -35,6 +35,9 @@
#include "qpid/sys/Thread.h"
#include <boost/noncopyable.hpp>
+namespace qpid {
+namespace tests {
+
/**
* A fixture with an in-process broker.
*/
@@ -55,7 +58,7 @@ struct BrokerFixture : private boost::noncopyable {
}
opts.port=0;
// Management doesn't play well with multiple in-process brokers.
- opts.enableMgmt=false;
+ opts.enableMgmt=false;
opts.workerThreads=1;
opts.dataDir="";
opts.auth=false;
@@ -144,5 +147,6 @@ struct SessionFixtureT : BrokerFixture, ClientT<ConnectionType,SessionType> {
typedef SessionFixtureT<LocalConnection> SessionFixture;
typedef SessionFixtureT<ProxyConnection> ProxySessionFixture;
+}} // namespace qpid::tests
#endif /*!TESTS_BROKERFIXTURE_H*/
diff --git a/qpid/cpp/src/tests/ClientMessageTest.cpp b/qpid/cpp/src/tests/ClientMessageTest.cpp
index bc0945674f..f925f1c234 100644
--- a/qpid/cpp/src/tests/ClientMessageTest.cpp
+++ b/qpid/cpp/src/tests/ClientMessageTest.cpp
@@ -24,6 +24,9 @@
using namespace qpid::client;
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(ClientMessageTestSuite)
QPID_AUTO_TEST_CASE(MessageCopyAssign) {
@@ -33,7 +36,7 @@ QPID_AUTO_TEST_CASE(MessageCopyAssign) {
Message c(m);
BOOST_CHECK_EQUAL("foo", c.getData());
Message a;
- BOOST_CHECK_EQUAL("", a.getData());
+ BOOST_CHECK_EQUAL("", a.getData());
a = m;
BOOST_CHECK_EQUAL("foo", a.getData());
a.setData("a");
@@ -44,3 +47,5 @@ QPID_AUTO_TEST_CASE(MessageCopyAssign) {
}
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/ClientSessionTest.cpp b/qpid/cpp/src/tests/ClientSessionTest.cpp
index 3ed7491f7d..6ca0aa6d44 100644
--- a/qpid/cpp/src/tests/ClientSessionTest.cpp
+++ b/qpid/cpp/src/tests/ClientSessionTest.cpp
@@ -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
@@ -40,6 +40,9 @@
#include <vector>
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(ClientSessionTest)
using namespace qpid::client;
@@ -122,12 +125,12 @@ QPID_AUTO_TEST_CASE(testDispatcher)
ClientSessionFixture fix;
fix.session =fix.connection.newSession();
size_t count = 100;
- for (size_t i = 0; i < count; ++i)
+ for (size_t i = 0; i < count; ++i)
fix.session.messageTransfer(arg::content=Message(boost::lexical_cast<string>(i), "my-queue"));
DummyListener listener(fix.session, "my-queue", count);
listener.run();
- BOOST_CHECK_EQUAL(count, listener.messages.size());
- for (size_t i = 0; i < count; ++i)
+ BOOST_CHECK_EQUAL(count, listener.messages.size());
+ for (size_t i = 0; i < count; ++i)
BOOST_CHECK_EQUAL(boost::lexical_cast<string>(i), listener.messages[i].getData());
}
@@ -142,8 +145,8 @@ QPID_AUTO_TEST_CASE(testDispatcherThread)
fix.session.messageTransfer(arg::content=Message(boost::lexical_cast<string>(i), "my-queue"));
}
t.join();
- BOOST_CHECK_EQUAL(count, listener.messages.size());
- for (size_t i = 0; i < count; ++i)
+ BOOST_CHECK_EQUAL(count, listener.messages.size());
+ for (size_t i = 0; i < count; ++i)
BOOST_CHECK_EQUAL(boost::lexical_cast<string>(i), listener.messages[i].getData());
}
@@ -215,7 +218,7 @@ QPID_AUTO_TEST_CASE(testLocalQueue) {
BOOST_CHECK_EQUAL("foo1", lq.pop().getData());
BOOST_CHECK(lq.empty()); // Credit exhausted.
fix.subs.getSubscription("lq").setFlowControl(FlowControl::unlimited());
- BOOST_CHECK_EQUAL("foo2", lq.pop().getData());
+ BOOST_CHECK_EQUAL("foo2", lq.pop().getData());
}
struct DelayedTransfer : sys::Runnable
@@ -246,7 +249,7 @@ QPID_AUTO_TEST_CASE(testGet) {
Thread t(sender);
//test timed get where message shows up after a short delay
BOOST_CHECK(fix.subs.get(got, "getq", 5*TIME_SEC));
- BOOST_CHECK_EQUAL("foo2", got.getData());
+ BOOST_CHECK_EQUAL("foo2", got.getData());
t.join();
}
@@ -271,8 +274,8 @@ QPID_AUTO_TEST_CASE(testPeriodicExpiration) {
ClientSessionFixture fix(opts);
fix.session.queueDeclare(arg::queue="my-queue", arg::exclusive=true, arg::autoDelete=true);
- for (uint i = 0; i < 10; i++) {
- Message m((boost::format("Message_%1%") % (i+1)).str(), "my-queue");
+ for (uint i = 0; i < 10; i++) {
+ Message m((boost::format("Message_%1%") % (i+1)).str(), "my-queue");
if (i % 2) m.getDeliveryProperties().setTtl(500);
fix.session.messageTransfer(arg::content=m);
}
@@ -286,15 +289,15 @@ QPID_AUTO_TEST_CASE(testExpirationOnPop) {
ClientSessionFixture fix;
fix.session.queueDeclare(arg::queue="my-queue", arg::exclusive=true, arg::autoDelete=true);
- for (uint i = 0; i < 10; i++) {
- Message m((boost::format("Message_%1%") % (i+1)).str(), "my-queue");
+ for (uint i = 0; i < 10; i++) {
+ Message m((boost::format("Message_%1%") % (i+1)).str(), "my-queue");
if (i % 2) m.getDeliveryProperties().setTtl(200);
fix.session.messageTransfer(arg::content=m);
}
qpid::sys::usleep(300* 1000);
- for (uint i = 0; i < 10; i++) {
+ for (uint i = 0; i < 10; i++) {
if (i % 2) continue;
Message m;
BOOST_CHECK(fix.subs.get(m, "my-queue", TIME_SEC));
@@ -306,8 +309,8 @@ QPID_AUTO_TEST_CASE(testRelease) {
ClientSessionFixture fix;
const uint count=10;
- for (uint i = 0; i < count; i++) {
- Message m((boost::format("Message_%1%") % (i+1)).str(), "my-queue");
+ for (uint i = 0; i < count; i++) {
+ Message m((boost::format("Message_%1%") % (i+1)).str(), "my-queue");
fix.session.messageTransfer(arg::content=m);
}
@@ -334,7 +337,7 @@ QPID_AUTO_TEST_CASE(testRelease) {
for (uint i = 0; i < count; i++) {
BOOST_CHECK_EQUAL((boost::format("Message_%1%") % (i+1)).str(), l2.messages[i].getData());
}
-
+
fix.subs.stop();
fix.subs.wait();
fix.session.close();
@@ -344,8 +347,8 @@ QPID_AUTO_TEST_CASE(testCompleteOnAccept) {
ClientSessionFixture fix;
const uint count = 8;
const uint chunk = 4;
- for (uint i = 0; i < count; i++) {
- Message m((boost::format("Message_%1%") % (i+1)).str(), "my-queue");
+ for (uint i = 0; i < count; i++) {
+ Message m((boost::format("Message_%1%") % (i+1)).str(), "my-queue");
fix.session.messageTransfer(arg::content=m);
}
@@ -358,25 +361,25 @@ QPID_AUTO_TEST_CASE(testCompleteOnAccept) {
Subscription s = fix.subs.subscribe(q, "my-queue", settings);
fix.session.messageFlush(arg::destination=s.getName());
SequenceSet accepted;
- for (uint i = 0; i < chunk; i++) {
+ for (uint i = 0; i < chunk; i++) {
Message m;
BOOST_CHECK(q.get(m));
BOOST_CHECK_EQUAL((boost::format("Message_%1%") % (i+1)).str(), m.getData());
accepted.add(m.getId());
- }
+ }
Message m;
BOOST_CHECK(!q.get(m));
-
+
s.accept(accepted);
fix.session.messageFlush(arg::destination=s.getName());
accepted.clear();
-
- for (uint i = chunk; i < count; i++) {
+
+ for (uint i = chunk; i < count; i++) {
Message m;
BOOST_CHECK(q.get(m));
BOOST_CHECK_EQUAL((boost::format("Message_%1%") % (i+1)).str(), m.getData());
accepted.add(m.getId());
- }
+ }
fix.session.messageAccept(accepted);
}
@@ -424,7 +427,7 @@ QPID_AUTO_TEST_CASE(testConcurrentSenders)
connection.open(settings);
AsyncSession session = connection.newSession();
Message message(string(512, 'X'));
-
+
boost::ptr_vector<Publisher> publishers;
for (size_t i = 0; i < 5; i++) {
publishers.push_back(new Publisher(connection, message, 100));
@@ -447,7 +450,7 @@ QPID_AUTO_TEST_CASE(testExclusiveSubscribe)
ScopedSuppressLogging sl;
BOOST_CHECK_THROW(fix.subs.subscribe(q, "myq", "second"), ResourceLockedException);
;
-
+
}
QPID_AUTO_TEST_CASE(testExclusiveBinding) {
@@ -478,7 +481,7 @@ QPID_AUTO_TEST_CASE(testResubscribeWithLocalQueue) {
fix.subs.subscribe(p, "some-queue");
fix.subs.cancel("some-queue");
fix.subs.subscribe(q, "some-queue");
-
+
fix.session.messageTransfer(arg::content=Message("some-data", "some-queue"));
fix.session.messageFlush(arg::destination="some-queue");
@@ -542,10 +545,10 @@ QPID_AUTO_TEST_CASE(testLVQVariedSize) {
std::ostringstream data;
size_t size = 100 - ((i % 10) * 10);
data << std::string(size, 'x');
-
+
Message m(data.str(), queue);
m.getHeaders().setString(key, "abc");
- fix.session.messageTransfer(arg::content=m);
+ fix.session.messageTransfer(arg::content=m);
}
}
@@ -594,7 +597,7 @@ QPID_AUTO_TEST_CASE(testExpirationNotAltered) {
ClientSessionFixture fix;
fix.session.queueDeclare(arg::queue="my-queue", arg::exclusive=true, arg::autoDelete=true);
- Message m("my-message", "my-queue");
+ Message m("my-message", "my-queue");
m.getDeliveryProperties().setTtl(60000);
m.getDeliveryProperties().setExpiration(12345);
fix.session.messageTransfer(arg::content=m);
@@ -606,4 +609,4 @@ QPID_AUTO_TEST_CASE(testExpirationNotAltered) {
QPID_AUTO_TEST_SUITE_END()
-
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/ClusterFailover.cpp b/qpid/cpp/src/tests/ClusterFailover.cpp
index 9ce9c4a36b..c2fb1282b1 100644
--- a/qpid/cpp/src/tests/ClusterFailover.cpp
+++ b/qpid/cpp/src/tests/ClusterFailover.cpp
@@ -32,6 +32,9 @@
#include <boost/algorithm/string.hpp>
#include <boost/bind.hpp>
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(ClusterFailoverTestSuite)
using namespace std;
@@ -60,3 +63,5 @@ QPID_AUTO_TEST_CASE(testReconnectSameSessionName) {
}
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/ClusterFixture.cpp b/qpid/cpp/src/tests/ClusterFixture.cpp
index e12106c464..7c357c3cd1 100644
--- a/qpid/cpp/src/tests/ClusterFixture.cpp
+++ b/qpid/cpp/src/tests/ClusterFixture.cpp
@@ -61,6 +61,9 @@ using boost::assign::list_of;
#include "ClusterFixture.h"
+namespace qpid {
+namespace tests {
+
ClusterFixture::ClusterFixture(size_t n, const Args& args_, int localIndex_)
: name(Uuid(true).str()), localIndex(localIndex_), userArgs(args_)
{
@@ -152,3 +155,5 @@ std::set<int> knownBrokerPorts(qpid::client::Connection& source, int n) {
s.insert((*i)[0].get<qpid::TcpAddress>()->port);
return s;
}
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/ClusterFixture.h b/qpid/cpp/src/tests/ClusterFixture.h
index 08b314499e..5952cc1736 100644
--- a/qpid/cpp/src/tests/ClusterFixture.h
+++ b/qpid/cpp/src/tests/ClusterFixture.h
@@ -60,6 +60,9 @@ using qpid::broker::Broker;
using boost::shared_ptr;
using qpid::cluster::Cluster;
+namespace qpid {
+namespace tests {
+
/** Cluster fixture is a vector of ports for the replicas.
*
* At most one replica (by default replica 0) is in the current
@@ -107,4 +110,6 @@ class ClusterFixture : public vector<uint16_t> {
*/
std::set<int> knownBrokerPorts(qpid::client::Connection& source, int n=-1);
+}} // namespace qpid::tests
+
#endif /*!CLUSTER_FIXTURE_H*/
diff --git a/qpid/cpp/src/tests/ConnectionOptions.h b/qpid/cpp/src/tests/ConnectionOptions.h
index cf86894235..6fd6c2c63f 100644
--- a/qpid/cpp/src/tests/ConnectionOptions.h
+++ b/qpid/cpp/src/tests/ConnectionOptions.h
@@ -10,9 +10,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
@@ -25,6 +25,8 @@
#include "qpid/client/ConnectionSettings.h"
#include "qpid/Options.h"
+namespace qpid {
+
/**
* Options parser for ConnectionOptions.
*/
@@ -35,9 +37,9 @@ struct ConnectionOptions : public qpid::Options,
{
using namespace qpid;
addOptions()
- ("broker,b", optValue(host, "HOST"), "Broker host to connect to")
+ ("broker,b", optValue(host, "HOST"), "Broker host to connect to")
("port,p", optValue(port, "PORT"), "Broker port to connect to")
- ("protocol,P", optValue(protocol, "tcp|rdma"), "Protocol to use for broker connection")
+ ("protocol,P", optValue(protocol, "tcp|rdma"), "Protocol to use for broker connection")
("virtualhost,v", optValue(virtualhost, "VHOST"), "virtual host")
("username", optValue(username, "USER"), "user name for broker log in.")
("password", optValue(password, "PASSWORD"), "password for broker log in.")
@@ -46,7 +48,7 @@ struct ConnectionOptions : public qpid::Options,
("max-channels", optValue(maxChannels, "N"), "the maximum number of channels the client requires.")
("heartbeat", optValue(heartbeat, "N"), "Desired heartbeat interval in seconds.")
("max-frame-size", optValue(maxFrameSize, "N"), "the maximum frame size to request.")
- ("bounds-multiplier", optValue(bounds, "N"),
+ ("bounds-multiplier", optValue(bounds, "N"),
"bound size of write queue (as a multiple of the max frame size).")
("tcp-nodelay", optValue(tcpNoDelay), "Turn on tcp-nodelay")
("service", optValue(service, "SERVICE-NAME"), "SASL service name.")
@@ -55,4 +57,6 @@ struct ConnectionOptions : public qpid::Options,
}
};
+} // namespace qpid
+
#endif /*!QPID_CLIENT_CONNECTIONOPTIONS_H*/
diff --git a/qpid/cpp/src/tests/ConsoleTest.cpp b/qpid/cpp/src/tests/ConsoleTest.cpp
index 1d55b13f3c..107472ed9e 100644
--- a/qpid/cpp/src/tests/ConsoleTest.cpp
+++ b/qpid/cpp/src/tests/ConsoleTest.cpp
@@ -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
@@ -23,6 +23,9 @@
#include "qpid/console/ClassKey.h"
#include "unit_test.h"
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(ConsoleTestSuite)
using namespace qpid::framing;
@@ -40,4 +43,4 @@ QPID_AUTO_TEST_CASE(testClassKey) {
QPID_AUTO_TEST_SUITE_END()
-
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/DeliveryRecordTest.cpp b/qpid/cpp/src/tests/DeliveryRecordTest.cpp
index 8ff7ad3584..17f9a0d148 100644
--- a/qpid/cpp/src/tests/DeliveryRecordTest.cpp
+++ b/qpid/cpp/src/tests/DeliveryRecordTest.cpp
@@ -8,9 +8,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
@@ -31,6 +31,9 @@ using namespace qpid::framing;
using boost::dynamic_pointer_cast;
using std::list;
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(DeliveryRecordTestSuite)
QPID_AUTO_TEST_CASE(testSort)
@@ -60,3 +63,4 @@ QPID_AUTO_TEST_CASE(testSort)
QPID_AUTO_TEST_SUITE_END()
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/DispatcherTest.cpp b/qpid/cpp/src/tests/DispatcherTest.cpp
index c619a36438..17b3b4e3e6 100644
--- a/qpid/cpp/src/tests/DispatcherTest.cpp
+++ b/qpid/cpp/src/tests/DispatcherTest.cpp
@@ -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
@@ -39,6 +39,9 @@
using namespace std;
using namespace qpid::sys;
+namespace qpid {
+namespace tests {
+
int writeALot(int fd, const string& s) {
int bytesWritten = 0;
do {
@@ -46,7 +49,7 @@ int writeALot(int fd, const string& s) {
int lastWrite = ::write(fd, s.c_str(), s.size());
if ( lastWrite >= 0) {
bytesWritten += lastWrite;
- }
+ }
} while (errno != EAGAIN);
return bytesWritten;
}
@@ -54,13 +57,13 @@ int writeALot(int fd, const string& s) {
int readALot(int fd) {
int bytesRead = 0;
char buf[10240];
-
+
do {
errno = 0;
int lastRead = ::read(fd, buf, sizeof(buf));
if ( lastRead >= 0) {
bytesRead += lastRead;
- }
+ }
} while (errno != EAGAIN);
return bytesRead;
}
@@ -83,7 +86,7 @@ void rInterrupt(DispatchHandle&) {
}
void wInterrupt(DispatchHandle&) {
- cerr << "W";
+ cerr << "W";
}
DispatchHandle::Callback rcb = rInterrupt;
@@ -108,15 +111,19 @@ void timer_handler(int /*signo*/, siginfo_t* /*info*/, void* /*context*/) {
wh->call(wcb);
} else {
phase1finished = true;
- assert(::timer_delete(timer) == 0);
+ assert(::timer_delete(timer) == 0);
}
}
+}} // namespace qpid::tests
+
+using namespace qpid::tests;
+
int main(int /*argc*/, char** /*argv*/)
{
// Create poller
Poller::shared_ptr poller(new Poller);
-
+
// Create dispatcher thread
Dispatcher d(poller);
Dispatcher d1(poller);
@@ -131,14 +138,14 @@ int main(int /*argc*/, char** /*argv*/)
int sv[2];
int rc = ::socketpair(AF_UNIX, SOCK_STREAM, 0, sv);
assert(rc >= 0);
-
+
// Set non-blocking
rc = ::fcntl(sv[0], F_SETFL, O_NONBLOCK);
assert(rc >= 0);
rc = ::fcntl(sv[1], F_SETFL, O_NONBLOCK);
assert(rc >= 0);
-
+
// Make up a large string
string testString = "This is only a test ... 1,2,3,4,5,6,7,8,9,10;";
for (int i = 0; i < 8; i++)
@@ -148,19 +155,19 @@ int main(int /*argc*/, char** /*argv*/)
PosixIOHandle f1(sv[1]);
rh = new DispatchHandleRef(f0, boost::bind(reader, _1, sv[0]), 0, 0);
- wh = new DispatchHandleRef(f1, 0, boost::bind(writer, _1, sv[1], testString), 0);
+ wh = new DispatchHandleRef(f1, 0, boost::bind(writer, _1, sv[1], testString), 0);
rh->startWatch(poller);
wh->startWatch(poller);
// Set up a regular itimer interupt
-
+
// Ignore signal in this thread
::sigset_t sm;
::sigemptyset(&sm);
::sigaddset(&sm, SIGRTMIN);
::pthread_sigmask(SIG_BLOCK, &sm, 0);
-
+
// Signal handling
struct ::sigaction sa;
sa.sa_sigaction = timer_handler;
@@ -168,18 +175,18 @@ int main(int /*argc*/, char** /*argv*/)
::sigemptyset(&sa.sa_mask);
rc = ::sigaction(SIGRTMIN, &sa,0);
assert(rc == 0);
-
+
::sigevent se;
::memset(&se, 0, sizeof(se)); // Clear to make valgrind happy (this *is* the neatest way to do this portably - sigh)
se.sigev_notify = SIGEV_SIGNAL;
se.sigev_signo = SIGRTMIN;
rc = ::timer_create(CLOCK_REALTIME, &se, &timer);
assert(rc == 0);
-
+
itimerspec ts = {
/*.it_value = */ {2, 0}, // s, ns
/*.it_interval = */ {2, 0}}; // s, ns
-
+
rc = ::timer_settime(timer, 0, &ts, 0);
assert(rc == 0);
@@ -200,11 +207,11 @@ int main(int /*argc*/, char** /*argv*/)
sa.sa_sigaction = stop_handler;
rc = ::sigaction(SIGRTMIN, &sa,0);
assert(rc == 0);
-
+
itimerspec nts = {
/*.it_value = */ {30, 0}, // s, ns
/*.it_interval = */ {30, 0}}; // s, ns
-
+
rc = ::timer_create(CLOCK_REALTIME, &se, &timer);
assert(rc == 0);
rc = ::timer_settime(timer, 0, &nts, 0);
@@ -228,7 +235,7 @@ int main(int /*argc*/, char** /*argv*/)
rc = ::timer_delete(timer);
assert(rc == 0);
-
+
poller->shutdown();
dt.join();
dt1.join();
@@ -237,6 +244,6 @@ int main(int /*argc*/, char** /*argv*/)
cout << "\nWrote: " << writtenBytes << "\n";
cout << "Read: " << readBytes << "\n";
-
+
return 0;
}
diff --git a/qpid/cpp/src/tests/DtxWorkRecordTest.cpp b/qpid/cpp/src/tests/DtxWorkRecordTest.cpp
index c7c1b460ff..9d7666dca4 100644
--- a/qpid/cpp/src/tests/DtxWorkRecordTest.cpp
+++ b/qpid/cpp/src/tests/DtxWorkRecordTest.cpp
@@ -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
@@ -27,6 +27,9 @@
using namespace qpid::broker;
using boost::static_pointer_cast;
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(DtxWorkRecordTestSuite)
QPID_AUTO_TEST_CASE(testOnePhaseCommit){
@@ -44,7 +47,7 @@ QPID_AUTO_TEST_CASE(testOnePhaseCommit){
DtxBuffer::shared_ptr bufferB(new DtxBuffer());
bufferB->enlist(static_pointer_cast<TxOp>(opB));
bufferB->markEnded();
-
+
DtxWorkRecord work("my-xid", &store);
work.add(bufferA);
work.add(bufferB);
@@ -77,7 +80,7 @@ QPID_AUTO_TEST_CASE(testFailOnOnePhaseCommit){
DtxBuffer::shared_ptr bufferC(new DtxBuffer());
bufferC->enlist(static_pointer_cast<TxOp>(opC));
bufferC->markEnded();
-
+
DtxWorkRecord work("my-xid", &store);
work.add(bufferA);
work.add(bufferB);
@@ -108,7 +111,7 @@ QPID_AUTO_TEST_CASE(testTwoPhaseCommit){
DtxBuffer::shared_ptr bufferB(new DtxBuffer());
bufferB->enlist(static_pointer_cast<TxOp>(opB));
bufferB->markEnded();
-
+
DtxWorkRecord work("my-xid", &store);
work.add(bufferA);
work.add(bufferB);
@@ -142,7 +145,7 @@ QPID_AUTO_TEST_CASE(testFailOnTwoPhaseCommit){
DtxBuffer::shared_ptr bufferC(new DtxBuffer());
bufferC->enlist(static_pointer_cast<TxOp>(opC));
bufferC->markEnded();
-
+
DtxWorkRecord work("my-xid", &store);
work.add(bufferA);
work.add(bufferB);
@@ -171,7 +174,7 @@ QPID_AUTO_TEST_CASE(testRollback){
DtxBuffer::shared_ptr bufferB(new DtxBuffer());
bufferB->enlist(static_pointer_cast<TxOp>(opB));
bufferB->markEnded();
-
+
DtxWorkRecord work("my-xid", &store);
work.add(bufferA);
work.add(bufferB);
@@ -187,3 +190,4 @@ QPID_AUTO_TEST_CASE(testRollback){
QPID_AUTO_TEST_SUITE_END()
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/ExchangeTest.cpp b/qpid/cpp/src/tests/ExchangeTest.cpp
index 2100fb5ed7..44835c6184 100644
--- a/qpid/cpp/src/tests/ExchangeTest.cpp
+++ b/qpid/cpp/src/tests/ExchangeTest.cpp
@@ -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
@@ -39,9 +39,12 @@ using namespace qpid::framing;
using namespace qpid::sys;
using namespace qpid;
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(ExchangeTestSuite)
-QPID_AUTO_TEST_CASE(testMe)
+QPID_AUTO_TEST_CASE(testMe)
{
Queue::shared_ptr queue(new Queue("queue", true));
Queue::shared_ptr queue2(new Queue("queue2", true));
@@ -70,7 +73,7 @@ QPID_AUTO_TEST_CASE(testIsBound)
Queue::shared_ptr b(new Queue("b", true));
Queue::shared_ptr c(new Queue("c", true));
Queue::shared_ptr d(new Queue("d", true));
-
+
string k1("abc");
string k2("def");
string k3("xyz");
@@ -139,7 +142,7 @@ QPID_AUTO_TEST_CASE(testIsBound)
headers.bind(a, "", &args3);
headers.bind(b, "", &args2);
headers.bind(c, "", &args1);
-
+
BOOST_CHECK(headers.isBound(a, 0, 0));
BOOST_CHECK(headers.isBound(a, 0, &args1));
BOOST_CHECK(headers.isBound(a, 0, &args3));
@@ -153,7 +156,7 @@ QPID_AUTO_TEST_CASE(testIsBound)
BOOST_CHECK(!headers.isBound(d, 0, &args3));
}
-QPID_AUTO_TEST_CASE(testDeleteGetAndRedeclare)
+QPID_AUTO_TEST_CASE(testDeleteGetAndRedeclare)
{
ExchangeRegistry exchanges;
exchanges.declare("my-exchange", "direct", false, FieldTable());
@@ -162,7 +165,7 @@ QPID_AUTO_TEST_CASE(testDeleteGetAndRedeclare)
exchanges.get("my-exchange");
} catch (const NotFoundException&) {}
std::pair<Exchange::shared_ptr, bool> response = exchanges.declare("my-exchange", "direct", false, FieldTable());
- BOOST_CHECK_EQUAL(string("direct"), response.first->getType());
+ BOOST_CHECK_EQUAL(string("direct"), response.first->getType());
}
intrusive_ptr<Message> cmessage(std::string exchange, std::string routingKey) {
@@ -175,7 +178,7 @@ intrusive_ptr<Message> cmessage(std::string exchange, std::string routingKey) {
return msg;
}
-QPID_AUTO_TEST_CASE(testSequenceOptions)
+QPID_AUTO_TEST_CASE(testSequenceOptions)
{
FieldTable args;
args.setInt("qpid.msg_sequence",1);
@@ -225,22 +228,22 @@ QPID_AUTO_TEST_CASE(testSequenceOptions)
direct.encode(buffer);
}
{
-
+
ExchangeRegistry exchanges;
buffer.reset();
DirectExchange::shared_ptr exch_dec = Exchange::decode(exchanges, buffer);
-
+
intrusive_ptr<Message> msg1 = cmessage("e", "A");
DeliverableMessage dmsg1(msg1);
exch_dec->route(dmsg1, "abc", 0);
BOOST_CHECK_EQUAL(4, msg1->getApplicationHeaders()->getAsInt64("qpid.msg_sequence"));
-
+
}
delete [] buff;
}
-QPID_AUTO_TEST_CASE(testIVEOption)
+QPID_AUTO_TEST_CASE(testIVEOption)
{
FieldTable args;
args.setInt("qpid.ive",1);
@@ -248,7 +251,7 @@ QPID_AUTO_TEST_CASE(testIVEOption)
FanOutExchange fanout("fanout1", false, args);
HeadersExchange header("headers1", false, args);
TopicExchange topic ("topic1", false, args);
-
+
intrusive_ptr<Message> msg1 = cmessage("direct1", "abc");
msg1->getProperties<MessageProperties>()->getApplicationHeaders().setString("a", "abc");
DeliverableMessage dmsg1(msg1);
@@ -256,7 +259,7 @@ QPID_AUTO_TEST_CASE(testIVEOption)
FieldTable args2;
args2.setString("x-match", "any");
args2.setString("a", "abc");
-
+
direct.route(dmsg1, "abc", 0);
fanout.route(dmsg1, "abc", 0);
header.route(dmsg1, "abc", &args2);
@@ -265,20 +268,22 @@ QPID_AUTO_TEST_CASE(testIVEOption)
Queue::shared_ptr queue1(new Queue("queue1", true));
Queue::shared_ptr queue2(new Queue("queue2", true));
Queue::shared_ptr queue3(new Queue("queue3", true));
-
+
BOOST_CHECK(HeadersExchange::match(args2, msg1->getProperties<MessageProperties>()->getApplicationHeaders()));
-
+
BOOST_CHECK(direct.bind(queue, "abc", 0));
BOOST_CHECK(fanout.bind(queue1, "abc", 0));
BOOST_CHECK(header.bind(queue2, "", &args2));
BOOST_CHECK(topic.bind(queue3, "abc", 0));
-
+
BOOST_CHECK_EQUAL(1u,queue->getMessageCount());
BOOST_CHECK_EQUAL(1u,queue1->getMessageCount());
BOOST_CHECK_EQUAL(1u,queue2->getMessageCount());
BOOST_CHECK_EQUAL(1u,queue3->getMessageCount());
-
+
}
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/FieldTable.cpp b/qpid/cpp/src/tests/FieldTable.cpp
index 5b43871f6d..fe2a14ec03 100644
--- a/qpid/cpp/src/tests/FieldTable.cpp
+++ b/qpid/cpp/src/tests/FieldTable.cpp
@@ -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
@@ -29,6 +29,9 @@
using namespace qpid::framing;
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(FieldTableTestSuite)
QPID_AUTO_TEST_CASE(testMe)
@@ -57,7 +60,7 @@ QPID_AUTO_TEST_CASE(testAssignment)
a.setInt("B", 1234);
b = a;
a.setString("A", "CCCC");
-
+
BOOST_CHECK(string("CCCC") == a.getAsString("A"));
BOOST_CHECK(string("BBBB") == b.getAsString("A"));
BOOST_CHECK_EQUAL(1234, a.getAsInt("B"));
@@ -69,7 +72,7 @@ QPID_AUTO_TEST_CASE(testAssignment)
{
FieldTable c;
c = a;
-
+
char* buff = static_cast<char*>(::alloca(c.encodedSize()));
Buffer wbuffer(buff, c.encodedSize());
wbuffer.put(c);
@@ -102,7 +105,7 @@ QPID_AUTO_TEST_CASE(testNestedValues)
list.push_back(List::ValuePtr(new Unsigned32Value(u)));
list.push_back(List::ValuePtr(new Str8Value("yellow")));
list.push_back(List::ValuePtr(new DoubleValue(d)));
-
+
a.setString("id", "A");
b.setString("id", "B");
a.setTable("B", b);
@@ -192,7 +195,7 @@ QPID_AUTO_TEST_CASE(test64GetAndSetConverts)
FieldTable args;
args.setInt64("a",100);
args.setInt64("b",-(int64_t) ((int64_t) 1<<34));
-
+
args.setUInt64("c",1u);
args.setUInt64("d",(uint64_t) ((uint64_t) 1<<34));
BOOST_CHECK_EQUAL(1u, args.getAsUInt64("c"));
@@ -204,5 +207,7 @@ QPID_AUTO_TEST_CASE(test64GetAndSetConverts)
BOOST_CHECK_EQUAL((int64_t) ((int64_t) 1<<34), args.getAsInt64("d"));
}
-
+
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/FieldValue.cpp b/qpid/cpp/src/tests/FieldValue.cpp
index 448f068107..0ebd0d7d44 100644
--- a/qpid/cpp/src/tests/FieldValue.cpp
+++ b/qpid/cpp/src/tests/FieldValue.cpp
@@ -6,9 +6,9 @@
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@@ -20,6 +20,9 @@
#include "unit_test.h"
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(FieldValueTestSuite)
using namespace qpid::framing;
@@ -32,7 +35,7 @@ IntegerValue i(42);
QPID_AUTO_TEST_CASE(testStr16ValueEquals)
{
-
+
BOOST_CHECK(Str16Value("abc") == s);
BOOST_CHECK(Str16Value("foo") != s);
BOOST_CHECK(s != i);
@@ -73,7 +76,7 @@ QPID_AUTO_TEST_CASE(testFieldTableValueEquals)
BOOST_CHECK_EQUAL(std::string("FOO"),
ft.getValue().getString("foo"));
BOOST_CHECK_EQUAL(7, ft.getValue().getInt("magic"));
-
+
FieldTableValue f2;
BOOST_CHECK(ft != f2);
f2.getValue().setString("foo", "FOO");
@@ -88,3 +91,5 @@ QPID_AUTO_TEST_CASE(testFieldTableValueEquals)
#endif
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/ForkedBroker.cpp b/qpid/cpp/src/tests/ForkedBroker.cpp
index 30c346850c..e1a96c8e90 100644
--- a/qpid/cpp/src/tests/ForkedBroker.cpp
+++ b/qpid/cpp/src/tests/ForkedBroker.cpp
@@ -30,6 +30,16 @@
using namespace std;
using qpid::ErrnoException;
+namespace std {
+static ostream& operator<<(ostream& o, const qpid::tests::ForkedBroker::Args& a) {
+copy(a.begin(), a.end(), ostream_iterator<string>(o, " "));
+return o;
+}
+}
+
+namespace qpid {
+namespace tests {
+
ForkedBroker::ForkedBroker(const Args& constArgs) {
Args args(constArgs);
Args::iterator i = find(args.begin(), args.end(), string("TMP_DATA_DIR"));
@@ -71,12 +81,6 @@ void ForkedBroker::kill(int sig) {
throw qpid::Exception(QPID_MSG("Forked broker exited with: " << WEXITSTATUS(status)));
}
-namespace std {
-static ostream& operator<<(ostream& o, const ForkedBroker::Args& a) {
- copy(a.begin(), a.end(), ostream_iterator<string>(o, " "));
- return o;
-}
-
bool isLogOption(const std::string& s) {
const char * log_enable = "--log-enable",
* trace = "--trace";
@@ -85,8 +89,6 @@ bool isLogOption(const std::string& s) {
);
}
-}
-
void ForkedBroker::init(const Args& userArgs) {
using qpid::ErrnoException;
port = 0;
@@ -125,3 +127,5 @@ void ForkedBroker::init(const Args& userArgs) {
::exit(1);
}
}
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/ForkedBroker.h b/qpid/cpp/src/tests/ForkedBroker.h
index 45b522068c..ddbad185d8 100644
--- a/qpid/cpp/src/tests/ForkedBroker.h
+++ b/qpid/cpp/src/tests/ForkedBroker.h
@@ -11,9 +11,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
@@ -31,9 +31,12 @@
#include <stdio.h>
#include <sys/wait.h>
+namespace qpid {
+namespace tests {
+
/**
* Class to fork a broker child process.
- *
+ *
* For most tests a BrokerFixture may be more convenient as it starts
* a broker in the same process which allows you to easily debug into
* the broker.
@@ -42,17 +45,17 @@
* those brokers can't coexist in the same process (e.g. for cluster
* tests where CPG doesn't allow multiple group members in a single
* process.)
- *
+ *
*/
class ForkedBroker {
public:
typedef std::vector<std::string> Args;
// argv args are passed to broker.
- //
+ //
// Special value "TMP_DATA_DIR" is substituted with a temporary
// data directory for the broker.
- //
+ //
ForkedBroker(const Args& argv);
~ForkedBroker();
@@ -70,4 +73,6 @@ class ForkedBroker {
std::string dataDir;
};
+}} // namespace qpid::tests
+
#endif /*!TESTS_FORKEDBROKER_H*/
diff --git a/qpid/cpp/src/tests/Frame.cpp b/qpid/cpp/src/tests/Frame.cpp
index 11905911fa..1270eabba3 100644
--- a/qpid/cpp/src/tests/Frame.cpp
+++ b/qpid/cpp/src/tests/Frame.cpp
@@ -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
@@ -23,6 +23,9 @@
#include <boost/lexical_cast.hpp>
#include "unit_test.h"
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(FrameTestSuite)
using namespace std;
@@ -78,3 +81,5 @@ QPID_AUTO_TEST_CASE(testLoop) {
}
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/FrameDecoder.cpp b/qpid/cpp/src/tests/FrameDecoder.cpp
index f5db66d5fe..9eeff2a41e 100644
--- a/qpid/cpp/src/tests/FrameDecoder.cpp
+++ b/qpid/cpp/src/tests/FrameDecoder.cpp
@@ -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
@@ -27,6 +27,9 @@
#include <string>
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(FrameDecoderTest)
using namespace std;
@@ -69,5 +72,7 @@ QPID_AUTO_TEST_CASE(testByteFragments) {
}
-
+
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/FramingTest.cpp b/qpid/cpp/src/tests/FramingTest.cpp
index e09ee19bc2..3d0fa0c0de 100644
--- a/qpid/cpp/src/tests/FramingTest.cpp
+++ b/qpid/cpp/src/tests/FramingTest.cpp
@@ -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
@@ -39,8 +39,11 @@ using namespace qpid;
using namespace qpid::framing;
using namespace std;
+namespace qpid {
+namespace tests {
+
template <class T>
-std::string tostring(const T& x)
+std::string tostring(const T& x)
{
std::ostringstream out;
out << x;
@@ -49,7 +52,7 @@ std::string tostring(const T& x)
QPID_AUTO_TEST_SUITE(FramingTestSuite)
-QPID_AUTO_TEST_CASE(testMessageTransferBody)
+QPID_AUTO_TEST_CASE(testMessageTransferBody)
{
char buffer[1024];
ProtocolVersion version(highestProtocolVersion);
@@ -62,8 +65,8 @@ QPID_AUTO_TEST_CASE(testMessageTransferBody)
out.decode(rbuff);
BOOST_CHECK_EQUAL(tostring(in), tostring(out));
}
-
-QPID_AUTO_TEST_CASE(testConnectionSecureBody)
+
+QPID_AUTO_TEST_CASE(testConnectionSecureBody)
{
char buffer[1024];
ProtocolVersion version(highestProtocolVersion);
@@ -88,10 +91,10 @@ QPID_AUTO_TEST_CASE(testConnectionRedirectBody)
Array hosts(0x95);
hosts.add(boost::shared_ptr<FieldValue>(new Str16Value(a)));
hosts.add(boost::shared_ptr<FieldValue>(new Str16Value(b)));
-
+
ConnectionRedirectBody in(version, a, hosts);
in.encode(wbuff);
-
+
Buffer rbuff(buffer, sizeof(buffer));
ConnectionRedirectBody out(version);
out.decode(rbuff);
@@ -111,7 +114,7 @@ QPID_AUTO_TEST_CASE(testQueueDeclareBody)
out.decode(rbuff);
BOOST_CHECK_EQUAL(tostring(in), tostring(out));
}
-
+
QPID_AUTO_TEST_CASE(testConnectionRedirectBodyFrame)
{
char buffer[1024];
@@ -122,7 +125,7 @@ QPID_AUTO_TEST_CASE(testConnectionRedirectBodyFrame)
Array hosts(0x95);
hosts.add(boost::shared_ptr<FieldValue>(new Str16Value(a)));
hosts.add(boost::shared_ptr<FieldValue>(new Str16Value(b)));
-
+
AMQFrame in((ConnectionRedirectBody(version, a, hosts)));
in.setChannel(999);
in.encode(wbuff);
@@ -149,3 +152,5 @@ QPID_AUTO_TEST_CASE(testMessageCancelBodyFrame)
}
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/HeaderTest.cpp b/qpid/cpp/src/tests/HeaderTest.cpp
index 01e7c22ee6..4b16f3c793 100644
--- a/qpid/cpp/src/tests/HeaderTest.cpp
+++ b/qpid/cpp/src/tests/HeaderTest.cpp
@@ -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
@@ -26,9 +26,12 @@
using namespace qpid::framing;
using namespace std;
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(HeaderTestSuite)
-QPID_AUTO_TEST_CASE(testGenericProperties)
+QPID_AUTO_TEST_CASE(testGenericProperties)
{
AMQHeaderBody body;
body.get<MessageProperties>(true)->getApplicationHeaders().setString(
@@ -47,10 +50,10 @@ QPID_AUTO_TEST_CASE(testGenericProperties)
props->getApplicationHeaders().get("A")->get<string>());
}
-QPID_AUTO_TEST_CASE(testMessageProperties)
+QPID_AUTO_TEST_CASE(testMessageProperties)
{
AMQFrame out((AMQHeaderBody()));
- MessageProperties* props1 =
+ MessageProperties* props1 =
out.castBody<AMQHeaderBody>()->get<MessageProperties>(true);
props1->setContentLength(42);
@@ -82,10 +85,10 @@ QPID_AUTO_TEST_CASE(testMessageProperties)
}
-QPID_AUTO_TEST_CASE(testDeliveryProperies)
+QPID_AUTO_TEST_CASE(testDeliveryProperies)
{
AMQFrame out((AMQHeaderBody()));
- DeliveryProperties* props1 =
+ DeliveryProperties* props1 =
out.castBody<AMQHeaderBody>()->get<DeliveryProperties>(true);
props1->setDiscardUnroutable(true);
@@ -108,3 +111,4 @@ QPID_AUTO_TEST_CASE(testDeliveryProperies)
QPID_AUTO_TEST_SUITE_END()
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/HeadersExchangeTest.cpp b/qpid/cpp/src/tests/HeadersExchangeTest.cpp
index 46933f955a..40deb59c86 100644
--- a/qpid/cpp/src/tests/HeadersExchangeTest.cpp
+++ b/qpid/cpp/src/tests/HeadersExchangeTest.cpp
@@ -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
@@ -28,9 +28,12 @@
using namespace qpid::broker;
using namespace qpid::framing;
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(HeadersExchangeTestSuite)
-
-QPID_AUTO_TEST_CASE(testMatchAll)
+
+QPID_AUTO_TEST_CASE(testMatchAll)
{
FieldTable b, m, n;
b.setString("x-match", "all");
@@ -43,7 +46,7 @@ QPID_AUTO_TEST_CASE(testMatchAll)
// Ignore extras.
m.setString("extra", "x");
BOOST_CHECK(HeadersExchange::match(b, m));
-
+
// Fail mismatch, wrong value.
m.setString("foo", "NotFoo");
BOOST_CHECK(!HeadersExchange::match(b, m));
@@ -54,7 +57,7 @@ QPID_AUTO_TEST_CASE(testMatchAll)
BOOST_CHECK(!HeadersExchange::match(b, n));
}
-QPID_AUTO_TEST_CASE(testMatchAny)
+QPID_AUTO_TEST_CASE(testMatchAny)
{
FieldTable b, m, n;
b.setString("x-match", "any");
@@ -67,7 +70,7 @@ QPID_AUTO_TEST_CASE(testMatchAny)
BOOST_CHECK(HeadersExchange::match(b, m));
}
-QPID_AUTO_TEST_CASE(testMatchEmptyValue)
+QPID_AUTO_TEST_CASE(testMatchEmptyValue)
{
FieldTable b, m;
b.setString("x-match", "all");
@@ -82,23 +85,23 @@ QPID_AUTO_TEST_CASE(testMatchEmptyArgs)
{
FieldTable b, m;
m.setString("foo", "FOO");
-
+
b.setString("x-match", "all");
BOOST_CHECK(HeadersExchange::match(b, m));
b.setString("x-match", "any");
BOOST_CHECK(!HeadersExchange::match(b, m));
}
-
-QPID_AUTO_TEST_CASE(testMatchNoXMatch)
+
+QPID_AUTO_TEST_CASE(testMatchNoXMatch)
{
FieldTable b, m;
b.setString("foo", "FOO");
m.setString("foo", "FOO");
BOOST_CHECK(!HeadersExchange::match(b, m));
}
-
-QPID_AUTO_TEST_CASE(testBindNoXMatch)
+
+QPID_AUTO_TEST_CASE(testBindNoXMatch)
{
HeadersExchange exchange("test");
Queue::shared_ptr queue;
@@ -112,4 +115,6 @@ QPID_AUTO_TEST_CASE(testBindNoXMatch)
}
}
-QPID_AUTO_TEST_SUITE_END()
+QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/IncompleteMessageList.cpp b/qpid/cpp/src/tests/IncompleteMessageList.cpp
index e830df0e8b..303d83cd66 100644
--- a/qpid/cpp/src/tests/IncompleteMessageList.cpp
+++ b/qpid/cpp/src/tests/IncompleteMessageList.cpp
@@ -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
@@ -27,6 +27,9 @@
#include "unit_test.h"
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(IncompleteMessageListTestSuite)
using namespace qpid::broker;
@@ -41,7 +44,7 @@ struct Checker
Checker(uint start, uint end) {
for (uint i = start; i <= end; i++) {
ids.push_back(i);
- }
+ }
}
Checker& expect(const SequenceNumber& id) {
@@ -49,11 +52,11 @@ struct Checker
return *this;
}
- void operator()(boost::intrusive_ptr<Message> msg) {
+ void operator()(boost::intrusive_ptr<Message> msg) {
BOOST_CHECK(!ids.empty());
BOOST_CHECK_EQUAL(msg->getCommandId(), ids.front());
ids.pop_front();
- }
+ }
};
QPID_AUTO_TEST_CASE(testProcessSimple)
@@ -91,7 +94,7 @@ QPID_AUTO_TEST_CASE(testProcessWithIncomplete)
list.process(Checker(1, 2), false);
//mark message complete and re-process to get remaining messages sent to listener
middle->enqueueComplete();
- list.process(Checker(3, 5), false);
+ list.process(Checker(3, 5), false);
}
@@ -127,3 +130,5 @@ QPID_AUTO_TEST_CASE(testSyncProcessWithIncomplete)
}
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/InlineAllocator.cpp b/qpid/cpp/src/tests/InlineAllocator.cpp
index fe6eaefaf4..a4c4d64cea 100644
--- a/qpid/cpp/src/tests/InlineAllocator.cpp
+++ b/qpid/cpp/src/tests/InlineAllocator.cpp
@@ -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
@@ -22,6 +22,9 @@
#include "qpid/InlineAllocator.h"
#include "unit_test.h"
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(InlineAllocatorTestSuite)
using namespace qpid;
@@ -48,16 +51,18 @@ QPID_AUTO_TEST_CASE(testAllocateFull) {
char* p = alloc.allocate(1);
BOOST_CHECK(p == (char*)&alloc);
-
+
char* q = alloc.allocate(1);
BOOST_CHECK(q != (char*)&alloc);
alloc.deallocate(p,1);
p = alloc.allocate(1);
BOOST_CHECK(p == (char*)&alloc);
-
+
alloc.deallocate(p,1);
alloc.deallocate(q,1);
}
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/InlineVector.cpp b/qpid/cpp/src/tests/InlineVector.cpp
index 009f10af9d..ba5165886d 100644
--- a/qpid/cpp/src/tests/InlineVector.cpp
+++ b/qpid/cpp/src/tests/InlineVector.cpp
@@ -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
@@ -22,6 +22,9 @@
#include "qpid/InlineVector.h"
#include "unit_test.h"
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(InlineVectorTestSuite)
using namespace qpid;
@@ -117,7 +120,9 @@ QPID_AUTO_TEST_CASE(testAssign) {
QPID_AUTO_TEST_CASE(testResize) {
Vec v;
v.resize(5);
- BOOST_CHECK(!isInline(v));
+ BOOST_CHECK(!isInline(v));
}
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/ManagementTest.cpp b/qpid/cpp/src/tests/ManagementTest.cpp
index e6f2e2e3fd..d05b4676ba 100644
--- a/qpid/cpp/src/tests/ManagementTest.cpp
+++ b/qpid/cpp/src/tests/ManagementTest.cpp
@@ -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
@@ -24,6 +24,9 @@
#include "qpid/console/ObjectId.h"
#include "unit_test.h"
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(ManagementTestSuite)
using namespace qpid::framing;
@@ -109,4 +112,4 @@ QPID_AUTO_TEST_CASE(testConsoleObjectId) {
QPID_AUTO_TEST_SUITE_END()
-
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/MessageBuilderTest.cpp b/qpid/cpp/src/tests/MessageBuilderTest.cpp
index 1f3f830633..c2fb8ad32e 100644
--- a/qpid/cpp/src/tests/MessageBuilderTest.cpp
+++ b/qpid/cpp/src/tests/MessageBuilderTest.cpp
@@ -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
@@ -31,15 +31,18 @@ using namespace qpid::broker;
using namespace qpid::framing;
using namespace qpid::sys;
+namespace qpid {
+namespace tests {
+
class MockMessageStore : public NullMessageStore
{
enum Op {STAGE=1, APPEND=2};
uint64_t id;
- boost::intrusive_ptr<PersistableMessage> expectedMsg;
+ boost::intrusive_ptr<PersistableMessage> expectedMsg;
string expectedData;
std::list<Op> ops;
-
+
void checkExpectation(Op actual)
{
BOOST_CHECK_EQUAL(ops.front(), actual);
@@ -49,17 +52,17 @@ class MockMessageStore : public NullMessageStore
public:
MockMessageStore() : id(0), expectedMsg(0) {}
- void expectStage(PersistableMessage& msg)
- {
+ void expectStage(PersistableMessage& msg)
+ {
expectedMsg = &msg;
- ops.push_back(STAGE);
+ ops.push_back(STAGE);
}
- void expectAppendContent(PersistableMessage& msg, const string& data)
- {
+ void expectAppendContent(PersistableMessage& msg, const string& data)
+ {
expectedMsg = &msg;
expectedData = data;
- ops.push_back(APPEND);
+ ops.push_back(APPEND);
}
void stage(const boost::intrusive_ptr<PersistableMessage>& msg)
@@ -74,7 +77,7 @@ class MockMessageStore : public NullMessageStore
{
checkExpectation(APPEND);
BOOST_CHECK_EQUAL(boost::static_pointer_cast<const PersistableMessage>(expectedMsg), msg);
- BOOST_CHECK_EQUAL(expectedData, data);
+ BOOST_CHECK_EQUAL(expectedData, data);
}
bool expectationsMet()
@@ -89,7 +92,7 @@ class MockMessageStore : public NullMessageStore
}
};
-
+
QPID_AUTO_TEST_SUITE(MessageBuilderTestSuite)
QPID_AUTO_TEST_CASE(testHeaderOnly)
@@ -103,7 +106,7 @@ QPID_AUTO_TEST_CASE(testHeaderOnly)
AMQFrame method((MessageTransferBody(ProtocolVersion(), exchange, 0, 0)));
AMQFrame header((AMQHeaderBody()));
- header.castBody<AMQHeaderBody>()->get<MessageProperties>(true)->setContentLength(0);
+ header.castBody<AMQHeaderBody>()->get<MessageProperties>(true)->setContentLength(0);
header.castBody<AMQHeaderBody>()->get<DeliveryProperties>(true)->setRoutingKey(key);
builder.handle(method);
@@ -132,7 +135,7 @@ QPID_AUTO_TEST_CASE(test1ContentFrame)
header.setEof(false);
content.setBof(false);
- header.castBody<AMQHeaderBody>()->get<MessageProperties>(true)->setContentLength(data.size());
+ header.castBody<AMQHeaderBody>()->get<MessageProperties>(true)->setContentLength(data.size());
header.castBody<AMQHeaderBody>()->get<DeliveryProperties>(true)->setRoutingKey(key);
builder.handle(method);
@@ -143,7 +146,7 @@ QPID_AUTO_TEST_CASE(test1ContentFrame)
BOOST_CHECK(builder.getMessage());
BOOST_CHECK(!builder.getMessage()->getFrames().isComplete());
- builder.handle(content);
+ builder.handle(content);
BOOST_CHECK(builder.getMessage());
BOOST_CHECK(builder.getMessage()->getFrames().isComplete());
}
@@ -169,7 +172,7 @@ QPID_AUTO_TEST_CASE(test2ContentFrames)
content1.setEof(false);
content2.setBof(false);
- header.castBody<AMQHeaderBody>()->get<MessageProperties>(true)->setContentLength(data1.size() + data2.size());
+ header.castBody<AMQHeaderBody>()->get<MessageProperties>(true)->setContentLength(data1.size() + data2.size());
header.castBody<AMQHeaderBody>()->get<DeliveryProperties>(true)->setRoutingKey(key);
builder.handle(method);
@@ -188,7 +191,7 @@ QPID_AUTO_TEST_CASE(testStaging)
MockMessageStore store;
MessageBuilder builder(&store, 5);
builder.start(SequenceNumber());
-
+
std::string data1("abcdefg");
std::string data2("hijklmn");
std::string exchange("builder-exchange");
@@ -199,7 +202,7 @@ QPID_AUTO_TEST_CASE(testStaging)
AMQFrame content1((AMQContentBody(data1)));
AMQFrame content2((AMQContentBody(data2)));
- header.castBody<AMQHeaderBody>()->get<MessageProperties>(true)->setContentLength(data1.size() + data2.size());
+ header.castBody<AMQHeaderBody>()->get<MessageProperties>(true)->setContentLength(data1.size() + data2.size());
header.castBody<AMQHeaderBody>()->get<DeliveryProperties>(true)->setRoutingKey(key);
builder.handle(method);
@@ -223,7 +226,7 @@ QPID_AUTO_TEST_CASE(testNoManagementStaging)
MockMessageStore store;
MessageBuilder builder(&store, 5);
builder.start(SequenceNumber());
-
+
std::string data1("abcdefg");
std::string exchange("qpid.management");
std::string key("builder-exchange");
@@ -232,7 +235,7 @@ QPID_AUTO_TEST_CASE(testNoManagementStaging)
AMQFrame header((AMQHeaderBody()));
AMQFrame content1((AMQContentBody(data1)));
- header.castBody<AMQHeaderBody>()->get<MessageProperties>(true)->setContentLength(data1.size());
+ header.castBody<AMQHeaderBody>()->get<MessageProperties>(true)->setContentLength(data1.size());
header.castBody<AMQHeaderBody>()->get<DeliveryProperties>(true)->setRoutingKey(key);
builder.handle(method);
@@ -242,4 +245,7 @@ QPID_AUTO_TEST_CASE(testNoManagementStaging)
BOOST_CHECK(store.expectationsMet());
BOOST_CHECK_EQUAL((uint64_t) 0, builder.getMessage()->getPersistenceId());
}
+
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/MessageReplayTracker.cpp b/qpid/cpp/src/tests/MessageReplayTracker.cpp
index a5121cdeb7..3d79ee53c2 100644
--- a/qpid/cpp/src/tests/MessageReplayTracker.cpp
+++ b/qpid/cpp/src/tests/MessageReplayTracker.cpp
@@ -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
@@ -23,6 +23,9 @@
#include "qpid/client/MessageReplayTracker.h"
#include "qpid/sys/Time.h"
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(MessageReplayTrackerTests)
using namespace qpid::client;
@@ -53,8 +56,8 @@ QPID_AUTO_TEST_CASE(testReplay)
MessageReplayTracker tracker(10);
tracker.init(fix.session);
- for (uint i = 0; i < 5; i++) {
- Message message((boost::format("Message_%1%") % (i+1)).str(), "my-queue");
+ for (uint i = 0; i < 5; i++) {
+ Message message((boost::format("Message_%1%") % (i+1)).str(), "my-queue");
tracker.send(message);
}
ReplayBufferChecker checker(1, 10);
@@ -62,7 +65,7 @@ QPID_AUTO_TEST_CASE(testReplay)
tracker.replay(fix.session);
for (uint j = 0; j < 2; j++) {//each message should have been sent twice
- for (uint i = 0; i < 5; i++) {
+ for (uint i = 0; i < 5; i++) {
Message m;
BOOST_CHECK(fix.subs.get(m, "my-queue", TIME_SEC));
BOOST_CHECK_EQUAL((boost::format("Message_%1%") % (i+1)).str(), m.getData());
@@ -79,15 +82,15 @@ QPID_AUTO_TEST_CASE(testCheckCompletion)
MessageReplayTracker tracker(10);
tracker.init(fix.session);
- for (uint i = 0; i < 5; i++) {
- Message message((boost::format("Message_%1%") % (i+1)).str(), "my-queue");
+ for (uint i = 0; i < 5; i++) {
+ Message message((boost::format("Message_%1%") % (i+1)).str(), "my-queue");
tracker.send(message);
}
fix.session.sync();//ensures all messages are complete
tracker.checkCompletion();
tracker.replay(fix.session);
Message received;
- for (uint i = 0; i < 5; i++) {
+ for (uint i = 0; i < 5; i++) {
BOOST_CHECK(fix.subs.get(received, "my-queue"));
BOOST_CHECK_EQUAL((boost::format("Message_%1%") % (i+1)).str(), received.getData());
}
@@ -96,4 +99,4 @@ QPID_AUTO_TEST_CASE(testCheckCompletion)
QPID_AUTO_TEST_SUITE_END()
-
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/MessageTest.cpp b/qpid/cpp/src/tests/MessageTest.cpp
index cd63f64a37..7d67c92b37 100644
--- a/qpid/cpp/src/tests/MessageTest.cpp
+++ b/qpid/cpp/src/tests/MessageTest.cpp
@@ -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
@@ -33,6 +33,9 @@
using namespace qpid::broker;
using namespace qpid::framing;
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(MessageTestSuite)
QPID_AUTO_TEST_CASE(testEncodeDecode)
@@ -56,7 +59,7 @@ QPID_AUTO_TEST_CASE(testEncodeDecode)
msg->getFrames().append(content2);
MessageProperties* mProps = msg->getFrames().getHeaders()->get<MessageProperties>(true);
- mProps->setContentLength(data1.size() + data2.size());
+ mProps->setContentLength(data1.size() + data2.size());
mProps->setMessageId(messageId);
FieldTable applicationHeaders;
applicationHeaders.setString("abc", "xyz");
@@ -69,7 +72,7 @@ QPID_AUTO_TEST_CASE(testEncodeDecode)
char* buff = static_cast<char*>(::alloca(msg->encodedSize()));
Buffer wbuffer(buff, msg->encodedSize());
msg->encode(wbuffer);
-
+
Buffer rbuffer(buff, msg->encodedSize());
msg = new Message();
msg->decodeHeader(rbuffer);
@@ -86,3 +89,4 @@ QPID_AUTO_TEST_CASE(testEncodeDecode)
QPID_AUTO_TEST_SUITE_END()
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/MessageUtils.h b/qpid/cpp/src/tests/MessageUtils.h
index 6a12c72007..dae74cce7d 100644
--- a/qpid/cpp/src/tests/MessageUtils.h
+++ b/qpid/cpp/src/tests/MessageUtils.h
@@ -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
@@ -28,9 +28,12 @@ using namespace qpid;
using namespace broker;
using namespace framing;
+namespace qpid {
+namespace tests {
+
struct MessageUtils
{
- static boost::intrusive_ptr<Message> createMessage(const string& exchange="", const string& routingKey="",
+ static boost::intrusive_ptr<Message> createMessage(const string& exchange="", const string& routingKey="",
const Uuid& messageId=Uuid(true), uint64_t contentSize = 0)
{
boost::intrusive_ptr<broker::Message> msg(new broker::Message());
@@ -41,7 +44,7 @@ struct MessageUtils
msg->getFrames().append(method);
msg->getFrames().append(header);
MessageProperties* props = msg->getFrames().getHeaders()->get<MessageProperties>(true);
- props->setContentLength(contentSize);
+ props->setContentLength(contentSize);
props->setMessageId(messageId);
msg->getFrames().getHeaders()->get<DeliveryProperties>(true)->setRoutingKey(routingKey);
return msg;
@@ -53,3 +56,5 @@ struct MessageUtils
msg->getFrames().append(content);
}
};
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/MessagingSessionTests.cpp b/qpid/cpp/src/tests/MessagingSessionTests.cpp
index 4ee27f0764..f5a5420d3a 100644
--- a/qpid/cpp/src/tests/MessagingSessionTests.cpp
+++ b/qpid/cpp/src/tests/MessagingSessionTests.cpp
@@ -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
@@ -36,6 +36,9 @@
#include <string>
#include <vector>
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(MessagingSessionTests)
using namespace qpid::messaging;
@@ -86,7 +89,7 @@ struct MessagingFixture : public BrokerFixture
Session session;
BrokerAdmin admin;
- MessagingFixture(Broker::Options opts = Broker::Options()) :
+ MessagingFixture(Broker::Options opts = Broker::Options()) :
BrokerFixture(opts),
connection(Connection::open((boost::format("amqp:tcp:localhost:%1%") % (broker->getPort(Broker::TCP_TRANSPORT))).str())),
session(connection.newSession()),
@@ -133,7 +136,7 @@ struct TopicFixture : MessagingFixture
struct MultiQueueFixture : MessagingFixture
{
- typedef std::vector<std::string>::const_iterator const_iterator;
+ typedef std::vector<std::string>::const_iterator const_iterator;
std::vector<std::string> queues;
MultiQueueFixture(const std::vector<std::string>& names = boost::assign::list_of<std::string>("q1")("q2")("q3")) : queues(names)
@@ -161,7 +164,7 @@ struct MessageDataCollector : MessageListener
}
};
-std::vector<std::string> fetch(Receiver& receiver, int count, qpid::sys::Duration timeout=qpid::sys::TIME_SEC*5)
+std::vector<std::string> fetch(Receiver& receiver, int count, qpid::sys::Duration timeout=qpid::sys::TIME_SEC*5)
{
std::vector<std::string> data;
Message message;
@@ -189,13 +192,12 @@ QPID_AUTO_TEST_CASE(testSendReceiveHeaders)
Sender sender = fix.session.createSender(fix.queue);
Message out("test-message");
for (uint i = 0; i < 10; ++i) {
- out.getHeaders()["a"] = i;
+ out.getHeaders()["a"] = i;
sender.send(out);
}
Receiver receiver = fix.session.createReceiver(fix.queue);
Message in;
for (uint i = 0; i < 10; ++i) {
- //Message in = receiver.fetch(5 * qpid::sys::TIME_SEC);
BOOST_CHECK(receiver.fetch(in, 5 * qpid::sys::TIME_SEC));
BOOST_CHECK_EQUAL(in.getBytes(), out.getBytes());
BOOST_CHECK_EQUAL(in.getHeaders()["a"].asUint32(), i);
@@ -249,14 +251,14 @@ QPID_AUTO_TEST_CASE(testSimpleTopic)
Message in;
BOOST_CHECK(!sub2.fetch(in, 0));//TODO: or should this raise an error?
-
+
//TODO: check pending messages...
}
QPID_AUTO_TEST_CASE(testSessionFetch)
{
MultiQueueFixture fix;
-
+
for (uint i = 0; i < fix.queues.size(); i++) {
Receiver r = fix.session.createReceiver(fix.queues[i]);
r.setCapacity(10u);
@@ -267,8 +269,8 @@ QPID_AUTO_TEST_CASE(testSessionFetch)
Sender s = fix.session.createSender(fix.queues[i]);
Message msg((boost::format("Message_%1%") % (i+1)).str());
s.send(msg);
- }
-
+ }
+
for (uint i = 0; i < fix.queues.size(); i++) {
Message msg;
BOOST_CHECK(fix.session.fetch(msg, qpid::sys::TIME_SEC));
@@ -279,7 +281,7 @@ QPID_AUTO_TEST_CASE(testSessionFetch)
QPID_AUTO_TEST_CASE(testSessionDispatch)
{
MultiQueueFixture fix;
-
+
MessageDataCollector collector;
for (uint i = 0; i < fix.queues.size(); i++) {
Receiver r = fix.session.createReceiver(fix.queues[i]);
@@ -292,10 +294,10 @@ QPID_AUTO_TEST_CASE(testSessionDispatch)
Sender s = fix.session.createSender(fix.queues[i]);
Message msg((boost::format("Message_%1%") % (i+1)).str());
s.send(msg);
- }
+ }
while (fix.session.dispatch(qpid::sys::TIME_SEC)) ;
-
+
BOOST_CHECK_EQUAL(collector.messageData, boost::assign::list_of<std::string>("Message_1")("Message_2")("Message_3"));
}
@@ -309,7 +311,7 @@ QPID_AUTO_TEST_CASE(testMapMessage)
out.getContent().asMap()["pi"] = 3.14f;
sender.send(out);
Receiver receiver = fix.session.createReceiver(fix.queue);
- Message in = receiver.fetch(5 * qpid::sys::TIME_SEC);
+ Message in = receiver.fetch(5 * qpid::sys::TIME_SEC);
BOOST_CHECK_EQUAL(in.getContent().asMap()["abc"].asString(), "def");
BOOST_CHECK_EQUAL(in.getContent().asMap()["pi"].asFloat(), 3.14f);
fix.session.acknowledge();
@@ -324,11 +326,11 @@ QPID_AUTO_TEST_CASE(testListMessage)
out.getContent() << "abc";
out.getContent() << 1234;
out.getContent() << "def";
- out.getContent() << 56.789;
+ out.getContent() << 56.789;
sender.send(out);
Receiver receiver = fix.session.createReceiver(fix.queue);
- Message in = receiver.fetch(5 * qpid::sys::TIME_SEC);
- Variant::List& list = in.getContent().asList();
+ Message in = receiver.fetch(5 * qpid::sys::TIME_SEC);
+ Variant::List& list = in.getContent().asList();
BOOST_CHECK_EQUAL(list.size(), out.getContent().asList().size());
BOOST_CHECK_EQUAL(list.front().asString(), "abc");
list.pop_front();
@@ -354,7 +356,86 @@ QPID_AUTO_TEST_CASE(testReject)
fix.session.reject(in);
in = receiver.fetch(5 * qpid::sys::TIME_SEC);
BOOST_CHECK_EQUAL(in.getBytes(), m2.getBytes());
- fix.session.acknowledge();
+ fix.session.acknowledge();
+}
+
+QPID_AUTO_TEST_CASE(testAvailable)
+{
+ MultiQueueFixture fix;
+
+ Receiver r1 = fix.session.createReceiver(fix.queues[0]);
+ r1.setCapacity(100);
+ r1.start();
+
+ Receiver r2 = fix.session.createReceiver(fix.queues[1]);
+ r2.setCapacity(100);
+ r2.start();
+
+ Sender s1 = fix.session.createSender(fix.queues[0]);
+ Sender s2 = fix.session.createSender(fix.queues[1]);
+
+ for (uint i = 0; i < 10; ++i) {
+ s1.send(Message((boost::format("A_%1%") % (i+1)).str()));
+ }
+ for (uint i = 0; i < 5; ++i) {
+ s2.send(Message((boost::format("B_%1%") % (i+1)).str()));
+ }
+ qpid::sys::sleep(1);//is there any avoid an arbitrary sleep while waiting for messages to be dispatched?
+ for (uint i = 0; i < 5; ++i) {
+ BOOST_CHECK_EQUAL(fix.session.available(), 15u - 2*i);
+ BOOST_CHECK_EQUAL(r1.available(), 10u - i);
+ BOOST_CHECK_EQUAL(r1.fetch().getBytes(), (boost::format("A_%1%") % (i+1)).str());
+ BOOST_CHECK_EQUAL(r2.available(), 5u - i);
+ BOOST_CHECK_EQUAL(r2.fetch().getBytes(), (boost::format("B_%1%") % (i+1)).str());
+ fix.session.acknowledge();
+ }
+ for (uint i = 5; i < 10; ++i) {
+ BOOST_CHECK_EQUAL(fix.session.available(), 10u - i);
+ BOOST_CHECK_EQUAL(r1.available(), 10u - i);
+ BOOST_CHECK_EQUAL(r1.fetch().getBytes(), (boost::format("A_%1%") % (i+1)).str());
+ }
+}
+
+QPID_AUTO_TEST_CASE(testPendingAck)
+{
+ QueueFixture fix;
+ Sender sender = fix.session.createSender(fix.queue);
+ for (uint i = 0; i < 10; ++i) {
+ sender.send(Message((boost::format("Message_%1%") % (i+1)).str()));
+ }
+ Receiver receiver = fix.session.createReceiver(fix.queue);
+ for (uint i = 0; i < 10; ++i) {
+ BOOST_CHECK_EQUAL(receiver.fetch().getBytes(), (boost::format("Message_%1%") % (i+1)).str());
+ }
+ BOOST_CHECK_EQUAL(fix.session.pendingAck(), 0u);
+ fix.session.acknowledge();
+ BOOST_CHECK_EQUAL(fix.session.pendingAck(), 10u);
+ fix.session.sync();
+ BOOST_CHECK_EQUAL(fix.session.pendingAck(), 0u);
+}
+
+QPID_AUTO_TEST_CASE(testPendingSend)
+{
+ QueueFixture fix;
+ Sender sender = fix.session.createSender(fix.queue);
+ for (uint i = 0; i < 10; ++i) {
+ sender.send(Message((boost::format("Message_%1%") % (i+1)).str()));
+ }
+ //Note: this test relies on 'inside knowledge' of the sender
+ //implementation and the fact that the simple test case makes it
+ //possible to predict when completion information will be sent to
+ //the client. TODO: is there a better way of testing this?
+ BOOST_CHECK_EQUAL(sender.pending(), 10u);
+ fix.session.sync();
+ BOOST_CHECK_EQUAL(sender.pending(), 0u);
+
+ Receiver receiver = fix.session.createReceiver(fix.queue);
+ for (uint i = 0; i < 10; ++i) {
+ BOOST_CHECK_EQUAL(receiver.fetch().getBytes(), (boost::format("Message_%1%") % (i+1)).str());
+ }
+ fix.session.acknowledge();
}
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/PartialFailure.cpp b/qpid/cpp/src/tests/PartialFailure.cpp
index f77a1401f8..8d9970f909 100644
--- a/qpid/cpp/src/tests/PartialFailure.cpp
+++ b/qpid/cpp/src/tests/PartialFailure.cpp
@@ -31,6 +31,9 @@
#include <boost/algorithm/string.hpp>
#include <boost/bind.hpp>
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(PartialFailureTestSuite)
using namespace std;
@@ -257,3 +260,5 @@ QPID_AUTO_TEST_CASE(testPartialFailureMemberLeaves) {
#endif
#endif // FIXME aconway 2009-07-30:
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/PollableCondition.cpp b/qpid/cpp/src/tests/PollableCondition.cpp
index b5cf1b4cd2..f9b3c25c93 100644
--- a/qpid/cpp/src/tests/PollableCondition.cpp
+++ b/qpid/cpp/src/tests/PollableCondition.cpp
@@ -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
@@ -28,6 +28,8 @@
#include "qpid/sys/Thread.h"
#include <boost/bind.hpp>
+namespace qpid {
+namespace tests {
QPID_AUTO_TEST_SUITE(PollableConditionTest)
@@ -37,7 +39,7 @@ const Duration SHORT = TIME_SEC/100;
const Duration LONG = TIME_SEC/10;
class Callback {
- public:
+ public:
enum Action { NONE, CLEAR };
Callback() : count(), action(NONE) {}
@@ -46,7 +48,7 @@ class Callback {
Mutex::ScopedLock l(lock);
++count;
switch(action) {
- case NONE: break;
+ case NONE: break;
case CLEAR: pc.clear(); break;
}
action = NONE;
@@ -62,9 +64,9 @@ class Callback {
action = a;
return wait(LONG);
}
-
+
private:
- bool wait(Duration timeout) {
+ bool wait(Duration timeout) {
int n = count;
AbsTime deadline(now(), timeout);
while (n == count && lock.wait(deadline))
@@ -83,7 +85,7 @@ QPID_AUTO_TEST_CASE(testPollableCondition) {
PollableCondition pc(boost::bind(&Callback::call, &callback, _1), poller);
Thread runner = Thread(*poller);
-
+
BOOST_CHECK(callback.isNotCalling()); // condition is not set.
pc.set();
@@ -104,4 +106,4 @@ QPID_AUTO_TEST_CASE(testPollableCondition) {
QPID_AUTO_TEST_SUITE_END()
-
+}} //namespace qpid::tests
diff --git a/qpid/cpp/src/tests/ProxyTest.cpp b/qpid/cpp/src/tests/ProxyTest.cpp
index 4ea10f7be9..a926b28395 100644
--- a/qpid/cpp/src/tests/ProxyTest.cpp
+++ b/qpid/cpp/src/tests/ProxyTest.cpp
@@ -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
@@ -28,6 +28,9 @@
using namespace qpid::framing;
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(ProxyTestSuite)
@@ -47,5 +50,7 @@ QPID_AUTO_TEST_CASE(testScopedSync)
Proxy::ScopedSync s(p);
p.send(ExecutionSyncBody(p.getVersion()));
}
-
+
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/QueueEvents.cpp b/qpid/cpp/src/tests/QueueEvents.cpp
index cd9439355e..bd18fa45fb 100644
--- a/qpid/cpp/src/tests/QueueEvents.cpp
+++ b/qpid/cpp/src/tests/QueueEvents.cpp
@@ -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
@@ -31,6 +31,9 @@
#include <boost/bind.hpp>
#include <boost/format.hpp>
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(QueueEventsSuite)
using namespace qpid::client;
@@ -156,7 +159,7 @@ QPID_AUTO_TEST_CASE(testSystemLevelEventProcessing)
fixture.session.queueDeclare(arg::queue=q, arg::arguments=options);
//send and consume some messages
LocalQueue incoming;
- Subscription sub = fixture.subs.subscribe(incoming, q);
+ Subscription sub = fixture.subs.subscribe(incoming, q);
for (int i = 0; i < 5; i++) {
fixture.session.messageTransfer(arg::content=client::Message((boost::format("%1%_%2%") % "Message" % (i+1)).str(), q));
}
@@ -177,7 +180,7 @@ QPID_AUTO_TEST_CASE(testSystemLevelEventProcessing)
SequenceNumber dequeueId(1);
for (int i = 0; i < 5; i++) {
listener.checkEnqueue(q, (boost::format("%1%_%2%") % "Message" % (i+1)).str(), enqueueId++);
- }
+ }
for (int i = 0; i < 3; i++) {
listener.checkDequeue(q, (boost::format("%1%_%2%") % "Message" % (i+1)).str(), dequeueId++);
}
@@ -203,7 +206,7 @@ QPID_AUTO_TEST_CASE(testSystemLevelEventProcessing_enqueuesOnly)
fixture.session.queueDeclare(arg::queue=q, arg::arguments=options);
//send and consume some messages
LocalQueue incoming;
- Subscription sub = fixture.subs.subscribe(incoming, q);
+ Subscription sub = fixture.subs.subscribe(incoming, q);
for (int i = 0; i < 5; i++) {
fixture.session.messageTransfer(arg::content=client::Message((boost::format("%1%_%2%") % "Message" % (i+1)).str(), q));
}
@@ -224,7 +227,7 @@ QPID_AUTO_TEST_CASE(testSystemLevelEventProcessing_enqueuesOnly)
SequenceNumber dequeueId(1);
for (int i = 0; i < 5; i++) {
listener.checkEnqueue(q, (boost::format("%1%_%2%") % "Message" % (i+1)).str(), enqueueId++);
- }
+ }
for (int i = 5; i < 10; i++) {
listener.checkEnqueue(q, (boost::format("%1%_%2%") % "Message" % (i+1)).str(), enqueueId++);
}
@@ -232,4 +235,4 @@ QPID_AUTO_TEST_CASE(testSystemLevelEventProcessing_enqueuesOnly)
QPID_AUTO_TEST_SUITE_END()
-
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/QueueOptionsTest.cpp b/qpid/cpp/src/tests/QueueOptionsTest.cpp
index 93d1961caa..f2fbaba2c1 100644
--- a/qpid/cpp/src/tests/QueueOptionsTest.cpp
+++ b/qpid/cpp/src/tests/QueueOptionsTest.cpp
@@ -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
@@ -27,14 +27,17 @@
using namespace qpid::client;
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(QueueOptionsTestSuite)
QPID_AUTO_TEST_CASE(testSizePolicy)
{
QueueOptions ft;
-
+
ft.setSizePolicy(REJECT,1,2);
-
+
BOOST_CHECK(QueueOptions::strREJECT == ft.getAsString(QueueOptions::strTypeKey));
BOOST_CHECK(1 == ft.getAsInt(QueueOptions::strMaxSizeKey));
BOOST_CHECK(2 == ft.getAsInt(QueueOptions::strMaxCountKey));
@@ -49,7 +52,7 @@ QPID_AUTO_TEST_CASE(testSizePolicy)
ft.setSizePolicy(RING_STRICT,1,0);
BOOST_CHECK(QueueOptions::strRING_STRICT == ft.getAsString(QueueOptions::strTypeKey));
-
+
ft.clearSizePolicy();
BOOST_CHECK(!ft.isSet(QueueOptions::strTypeKey));
BOOST_CHECK(!ft.isSet(QueueOptions::strMaxSizeKey));
@@ -59,13 +62,13 @@ QPID_AUTO_TEST_CASE(testSizePolicy)
QPID_AUTO_TEST_CASE(testFlags)
{
QueueOptions ft;
-
+
ft.setPersistLastNode();
ft.setOrdering(LVQ);
-
+
BOOST_CHECK(1 == ft.getAsInt(QueueOptions::strPersistLastNode));
BOOST_CHECK(1 == ft.getAsInt(QueueOptions::strLastValueQueue));
-
+
ft.clearPersistLastNode();
ft.setOrdering(FIFO);
@@ -78,8 +81,8 @@ QPID_AUTO_TEST_CASE(testSetOrdering)
{
//ensure setOrdering(FIFO) works even if not preceded by a call to
//setOrdering(LVQ)
- QueueOptions ft;
- ft.setOrdering(FIFO);
+ QueueOptions ft;
+ ft.setOrdering(FIFO);
BOOST_CHECK(!ft.isSet(QueueOptions::strLastValueQueue));
}
@@ -88,10 +91,12 @@ QPID_AUTO_TEST_CASE(testClearPersistLastNode)
{
//ensure clear works even if not preceded by the setting on the
//option
- QueueOptions ft;
+ QueueOptions ft;
ft.clearPersistLastNode();
BOOST_CHECK(!ft.isSet(QueueOptions::strPersistLastNode));
}
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/QueuePolicyTest.cpp b/qpid/cpp/src/tests/QueuePolicyTest.cpp
index 7c7f8b7a10..f40d30b588 100644
--- a/qpid/cpp/src/tests/QueuePolicyTest.cpp
+++ b/qpid/cpp/src/tests/QueuePolicyTest.cpp
@@ -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
@@ -32,6 +32,9 @@ using namespace qpid::broker;
using namespace qpid::client;
using namespace qpid::framing;
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(QueuePolicyTestSuite)
QueuedMessage createMessage(uint32_t size)
@@ -50,11 +53,11 @@ QPID_AUTO_TEST_CASE(testCount)
BOOST_CHECK_EQUAL((uint32_t) 5, policy->getMaxCount());
QueuedMessage msg = createMessage(10);
- for (size_t i = 0; i < 5; i++) {
+ for (size_t i = 0; i < 5; i++) {
policy->tryEnqueue(msg);
}
try {
- policy->tryEnqueue(msg);
+ policy->tryEnqueue(msg);
BOOST_FAIL("Policy did not fail on enqueuing sixth message");
} catch (const ResourceLimitExceededException&) {}
@@ -62,7 +65,7 @@ QPID_AUTO_TEST_CASE(testCount)
policy->tryEnqueue(msg);
try {
- policy->tryEnqueue(msg);
+ policy->tryEnqueue(msg);
BOOST_FAIL("Policy did not fail on enqueuing sixth message (after dequeue)");
} catch (const ResourceLimitExceededException&) {}
}
@@ -71,12 +74,12 @@ QPID_AUTO_TEST_CASE(testSize)
{
std::auto_ptr<QueuePolicy> policy(QueuePolicy::createQueuePolicy(0, 50));
QueuedMessage msg = createMessage(10);
-
- for (size_t i = 0; i < 5; i++) {
+
+ for (size_t i = 0; i < 5; i++) {
policy->tryEnqueue(msg);
}
try {
- policy->tryEnqueue(msg);
+ policy->tryEnqueue(msg);
BOOST_FAIL("Policy did not fail on aggregate size exceeding 50. " << *policy);
} catch (const ResourceLimitExceededException&) {}
@@ -84,7 +87,7 @@ QPID_AUTO_TEST_CASE(testSize)
policy->tryEnqueue(msg);
try {
- policy->tryEnqueue(msg);
+ policy->tryEnqueue(msg);
BOOST_FAIL("Policy did not fail on aggregate size exceeding 50 (after dequeue). " << *policy);
} catch (const ResourceLimitExceededException&) {}
}
@@ -104,7 +107,7 @@ QPID_AUTO_TEST_CASE(testBoth)
messages.push_back(createMessage(11));
messages.push_back(createMessage(2));
messages.push_back(createMessage(7));
- for (size_t i = 0; i < messages.size(); i++) {
+ for (size_t i = 0; i < messages.size(); i++) {
policy->tryEnqueue(messages[i]);
}
//size = 45 at this point, count = 5
@@ -140,7 +143,7 @@ QPID_AUTO_TEST_CASE(testSettings)
BOOST_CHECK_EQUAL(a->getMaxSize(), b->getMaxSize());
}
-QPID_AUTO_TEST_CASE(testRingPolicy)
+QPID_AUTO_TEST_CASE(testRingPolicy)
{
FieldTable args;
std::auto_ptr<QueuePolicy> policy = QueuePolicy::createQueuePolicy(5, 0, QueuePolicy::RING);
@@ -169,7 +172,7 @@ QPID_AUTO_TEST_CASE(testRingPolicy)
BOOST_CHECK(!f.subs.get(msg, q));
}
-QPID_AUTO_TEST_CASE(testStrictRingPolicy)
+QPID_AUTO_TEST_CASE(testStrictRingPolicy)
{
FieldTable args;
std::auto_ptr<QueuePolicy> policy = QueuePolicy::createQueuePolicy(5, 0, QueuePolicy::RING_STRICT);
@@ -181,7 +184,7 @@ QPID_AUTO_TEST_CASE(testStrictRingPolicy)
LocalQueue incoming;
SubscriptionSettings settings(FlowControl::unlimited());
settings.autoAck = 0; // no auto ack.
- Subscription sub = f.subs.subscribe(incoming, q, settings);
+ Subscription sub = f.subs.subscribe(incoming, q, settings);
for (int i = 0; i < 5; i++) {
f.session.messageTransfer(arg::content=client::Message((boost::format("%1%_%2%") % "Message" % (i+1)).str(), q));
}
@@ -192,10 +195,10 @@ QPID_AUTO_TEST_CASE(testStrictRingPolicy)
ScopedSuppressLogging sl; // Suppress messages for expected errors.
f.session.messageTransfer(arg::content=client::Message("Message_6", q));
BOOST_FAIL("expecting ResourceLimitExceededException.");
- } catch (const ResourceLimitExceededException&) {}
+ } catch (const ResourceLimitExceededException&) {}
}
-QPID_AUTO_TEST_CASE(testPolicyWithDtx)
+QPID_AUTO_TEST_CASE(testPolicyWithDtx)
{
FieldTable args;
std::auto_ptr<QueuePolicy> policy = QueuePolicy::createQueuePolicy(5, 0, QueuePolicy::REJECT);
@@ -207,7 +210,7 @@ QPID_AUTO_TEST_CASE(testPolicyWithDtx)
LocalQueue incoming;
SubscriptionSettings settings(FlowControl::unlimited());
settings.autoAck = 0; // no auto ack.
- Subscription sub = f.subs.subscribe(incoming, q, settings);
+ Subscription sub = f.subs.subscribe(incoming, q, settings);
f.session.dtxSelect();
Xid tx1(1, "test-dtx-mgr", "tx1");
f.session.dtxStart(arg::xid=tx1);
@@ -244,7 +247,7 @@ QPID_AUTO_TEST_CASE(testPolicyWithDtx)
ScopedSuppressLogging sl; // Suppress messages for expected errors.
other.messageTransfer(arg::content=client::Message("Message_6", q));
BOOST_FAIL("expecting ResourceLimitExceededException.");
- } catch (const ResourceLimitExceededException&) {}
+ } catch (const ResourceLimitExceededException&) {}
f.session.dtxCommit(arg::xid=tx3);
//now retry and this time should succeed
@@ -252,7 +255,7 @@ QPID_AUTO_TEST_CASE(testPolicyWithDtx)
other.messageTransfer(arg::content=client::Message("Message_6", q));
}
-QPID_AUTO_TEST_CASE(testFlowToDiskWithNoStore)
+QPID_AUTO_TEST_CASE(testFlowToDiskWithNoStore)
{
//Ensure that with no store loaded, we don't flow to disk but
//fallback to rejecting messages
@@ -265,7 +268,7 @@ QPID_AUTO_TEST_CASE(testFlowToDiskWithNoStore)
LocalQueue incoming;
SubscriptionSettings settings(FlowControl::unlimited());
settings.autoAck = 0; // no auto ack.
- Subscription sub = f.subs.subscribe(incoming, q, settings);
+ Subscription sub = f.subs.subscribe(incoming, q, settings);
for (int i = 0; i < 5; i++) {
f.session.messageTransfer(arg::content=client::Message((boost::format("%1%_%2%") % "Message" % (i+1)).str(), q));
}
@@ -276,8 +279,10 @@ QPID_AUTO_TEST_CASE(testFlowToDiskWithNoStore)
ScopedSuppressLogging sl; // Suppress messages for expected errors.
f.session.messageTransfer(arg::content=client::Message("Message_6", q));
BOOST_FAIL("expecting ResourceLimitExceededException.");
- } catch (const ResourceLimitExceededException&) {}
+ } catch (const ResourceLimitExceededException&) {}
}
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/QueueRegistryTest.cpp b/qpid/cpp/src/tests/QueueRegistryTest.cpp
index 7ad4e0b89d..712cb568c3 100644
--- a/qpid/cpp/src/tests/QueueRegistryTest.cpp
+++ b/qpid/cpp/src/tests/QueueRegistryTest.cpp
@@ -6,9 +6,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
@@ -23,6 +23,9 @@
using namespace qpid::broker;
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(QueueRegistryTest)
QPID_AUTO_TEST_CASE(testDeclare)
@@ -49,7 +52,7 @@ QPID_AUTO_TEST_CASE(testDeclare)
BOOST_CHECK_EQUAL(bar, q->getName());
}
-QPID_AUTO_TEST_CASE(testDeclareTmp)
+QPID_AUTO_TEST_CASE(testDeclareTmp)
{
QueueRegistry reg;
std::pair<Queue::shared_ptr, bool> qc;
@@ -58,8 +61,8 @@ QPID_AUTO_TEST_CASE(testDeclareTmp)
BOOST_CHECK(qc.second);
BOOST_CHECK_EQUAL(std::string("tmp_1"), qc.first->getName());
}
-
-QPID_AUTO_TEST_CASE(testFind)
+
+QPID_AUTO_TEST_CASE(testFind)
{
std::string foo("foo");
std::string bar("bar");
@@ -75,7 +78,7 @@ QPID_AUTO_TEST_CASE(testFind)
BOOST_CHECK_EQUAL(bar, q->getName());
}
-QPID_AUTO_TEST_CASE(testDestroy)
+QPID_AUTO_TEST_CASE(testDestroy)
{
std::string foo("foo");
QueueRegistry reg;
@@ -92,3 +95,5 @@ QPID_AUTO_TEST_CASE(testDestroy)
}
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/QueueTest.cpp b/qpid/cpp/src/tests/QueueTest.cpp
index b70afa52a7..841a19f7c1 100644
--- a/qpid/cpp/src/tests/QueueTest.cpp
+++ b/qpid/cpp/src/tests/QueueTest.cpp
@@ -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
@@ -39,9 +39,12 @@ using namespace qpid::broker;
using namespace qpid::framing;
using namespace qpid::sys;
+namespace qpid {
+namespace tests {
+
class TestConsumer : public virtual Consumer{
public:
- typedef boost::shared_ptr<TestConsumer> shared_ptr;
+ typedef boost::shared_ptr<TestConsumer> shared_ptr;
intrusive_ptr<Message> last;
bool received;
@@ -82,68 +85,68 @@ QPID_AUTO_TEST_SUITE(QueueTestSuite)
QPID_AUTO_TEST_CASE(testAsyncMessage) {
Queue::shared_ptr queue(new Queue("my_test_queue", true));
intrusive_ptr<Message> received;
-
+
TestConsumer::shared_ptr c1(new TestConsumer());
queue->consume(c1);
-
-
+
+
//Test basic delivery:
intrusive_ptr<Message> msg1 = create_message("e", "A");
msg1->enqueueAsync(queue, 0);//this is done on enqueue which is not called from process
queue->process(msg1);
sleep(2);
-
+
BOOST_CHECK(!c1->received);
msg1->enqueueComplete();
-
+
received = queue->get().payload;
- BOOST_CHECK_EQUAL(msg1.get(), received.get());
+ BOOST_CHECK_EQUAL(msg1.get(), received.get());
}
-
-
+
+
QPID_AUTO_TEST_CASE(testAsyncMessageCount){
Queue::shared_ptr queue(new Queue("my_test_queue", true));
intrusive_ptr<Message> msg1 = create_message("e", "A");
msg1->enqueueAsync(queue, 0);//this is done on enqueue which is not called from process
-
+
queue->process(msg1);
sleep(2);
uint32_t compval=0;
BOOST_CHECK_EQUAL(compval, queue->getMessageCount());
msg1->enqueueComplete();
compval=1;
- BOOST_CHECK_EQUAL(compval, queue->getMessageCount());
+ BOOST_CHECK_EQUAL(compval, queue->getMessageCount());
}
QPID_AUTO_TEST_CASE(testConsumers){
Queue::shared_ptr queue(new Queue("my_queue", true));
-
+
//Test adding consumers:
TestConsumer::shared_ptr c1(new TestConsumer());
TestConsumer::shared_ptr c2(new TestConsumer());
queue->consume(c1);
queue->consume(c2);
-
+
BOOST_CHECK_EQUAL(uint32_t(2), queue->getConsumerCount());
-
+
//Test basic delivery:
intrusive_ptr<Message> msg1 = create_message("e", "A");
intrusive_ptr<Message> msg2 = create_message("e", "B");
intrusive_ptr<Message> msg3 = create_message("e", "C");
-
+
queue->deliver(msg1);
BOOST_CHECK(queue->dispatch(c1));
BOOST_CHECK_EQUAL(msg1.get(), c1->last.get());
-
+
queue->deliver(msg2);
BOOST_CHECK(queue->dispatch(c2));
BOOST_CHECK_EQUAL(msg2.get(), c2->last.get());
-
+
c1->received = false;
queue->deliver(msg3);
BOOST_CHECK(queue->dispatch(c1));
- BOOST_CHECK_EQUAL(msg3.get(), c1->last.get());
-
+ BOOST_CHECK_EQUAL(msg3.get(), c1->last.get());
+
//Test cancellation:
queue->cancel(c1);
BOOST_CHECK_EQUAL(uint32_t(1), queue->getConsumerCount());
@@ -157,15 +160,15 @@ QPID_AUTO_TEST_CASE(testRegistry){
registry.declare("queue1", true, true);
registry.declare("queue2", true, true);
registry.declare("queue3", true, true);
-
+
BOOST_CHECK(registry.find("queue1"));
BOOST_CHECK(registry.find("queue2"));
BOOST_CHECK(registry.find("queue3"));
-
+
registry.destroy("queue1");
registry.destroy("queue2");
registry.destroy("queue3");
-
+
BOOST_CHECK(!registry.find("queue1"));
BOOST_CHECK(!registry.find("queue2"));
BOOST_CHECK(!registry.find("queue3"));
@@ -177,13 +180,13 @@ QPID_AUTO_TEST_CASE(testDequeue){
intrusive_ptr<Message> msg2 = create_message("e", "B");
intrusive_ptr<Message> msg3 = create_message("e", "C");
intrusive_ptr<Message> received;
-
+
queue->deliver(msg1);
queue->deliver(msg2);
queue->deliver(msg3);
-
+
BOOST_CHECK_EQUAL(uint32_t(3), queue->getMessageCount());
-
+
received = queue->get().payload;
BOOST_CHECK_EQUAL(msg1.get(), received.get());
BOOST_CHECK_EQUAL(uint32_t(2), queue->getMessageCount());
@@ -204,7 +207,7 @@ QPID_AUTO_TEST_CASE(testDequeue){
received = queue->get().payload;
BOOST_CHECK(!received);
BOOST_CHECK_EQUAL(uint32_t(0), queue->getMessageCount());
-
+
}
QPID_AUTO_TEST_CASE(testBound)
@@ -236,7 +239,7 @@ QPID_AUTO_TEST_CASE(testBound)
queue->unbind(exchanges, queue);
//ensure the remaining exchanges don't still have the queue bound to them:
- FailOnDeliver deliverable;
+ FailOnDeliver deliverable;
exchange1->route(deliverable, key, &args);
exchange3->route(deliverable, key, &args);
}
@@ -245,10 +248,10 @@ QPID_AUTO_TEST_CASE(testPersistLastNodeStanding){
client::QueueOptions args;
args.setPersistLastNode();
-
+
Queue::shared_ptr queue(new Queue("my-queue", true));
queue->configure(args);
-
+
intrusive_ptr<Message> msg1 = create_message("e", "A");
intrusive_ptr<Message> msg2 = create_message("e", "B");
intrusive_ptr<Message> msg3 = create_message("e", "C");
@@ -256,13 +259,13 @@ QPID_AUTO_TEST_CASE(testPersistLastNodeStanding){
//enqueue 2 messages
queue->deliver(msg1);
queue->deliver(msg2);
-
+
//change mode
queue->setLastNodeFailure();
-
+
//enqueue 1 message
queue->deliver(msg3);
-
+
//check all have persistent ids.
BOOST_CHECK(msg1->isPersistent());
BOOST_CHECK(msg2->isPersistent());
@@ -277,7 +280,7 @@ class TestMessageStoreOC : public NullMessageStore
uint enqCnt;
uint deqCnt;
bool error;
-
+
virtual void dequeue(TransactionContext*,
const boost::intrusive_ptr<PersistableMessage>& /*msg*/,
const PersistableQueue& /*queue*/)
@@ -298,7 +301,7 @@ class TestMessageStoreOC : public NullMessageStore
{
error=true;
}
-
+
TestMessageStoreOC() : NullMessageStore(),enqCnt(0),deqCnt(0),error(false) {}
~TestMessageStoreOC(){}
};
@@ -312,7 +315,7 @@ QPID_AUTO_TEST_CASE(testLVQOrdering){
Queue::shared_ptr queue(new Queue("my-queue", true ));
queue->configure(args);
-
+
intrusive_ptr<Message> msg1 = create_message("e", "A");
intrusive_ptr<Message> msg2 = create_message("e", "B");
intrusive_ptr<Message> msg3 = create_message("e", "C");
@@ -324,27 +327,27 @@ QPID_AUTO_TEST_CASE(testLVQOrdering){
string key;
args.getLVQKey(key);
BOOST_CHECK_EQUAL(key, "qpid.LVQ_key");
-
+
msg1->getProperties<MessageProperties>()->getApplicationHeaders().setString(key,"a");
msg2->getProperties<MessageProperties>()->getApplicationHeaders().setString(key,"b");
msg3->getProperties<MessageProperties>()->getApplicationHeaders().setString(key,"c");
msg4->getProperties<MessageProperties>()->getApplicationHeaders().setString(key,"a");
-
+
//enqueue 4 message
queue->deliver(msg1);
queue->deliver(msg2);
queue->deliver(msg3);
queue->deliver(msg4);
-
+
BOOST_CHECK_EQUAL(queue->getMessageCount(), 3u);
-
+
received = queue->get().payload;
BOOST_CHECK_EQUAL(msg4.get(), received.get());
received = queue->get().payload;
BOOST_CHECK_EQUAL(msg2.get(), received.get());
-
+
received = queue->get().payload;
BOOST_CHECK_EQUAL(msg3.get(), received.get());
@@ -357,18 +360,18 @@ QPID_AUTO_TEST_CASE(testLVQOrdering){
queue->deliver(msg5);
queue->deliver(msg6);
queue->deliver(msg7);
-
+
BOOST_CHECK_EQUAL(queue->getMessageCount(), 3u);
-
+
received = queue->get().payload;
BOOST_CHECK_EQUAL(msg5.get(), received.get());
received = queue->get().payload;
BOOST_CHECK_EQUAL(msg6.get(), received.get());
-
+
received = queue->get().payload;
BOOST_CHECK_EQUAL(msg7.get(), received.get());
-
+
}
QPID_AUTO_TEST_CASE(testLVQEmptyKey){
@@ -379,20 +382,20 @@ QPID_AUTO_TEST_CASE(testLVQEmptyKey){
Queue::shared_ptr queue(new Queue("my-queue", true ));
queue->configure(args);
-
+
intrusive_ptr<Message> msg1 = create_message("e", "A");
intrusive_ptr<Message> msg2 = create_message("e", "B");
string key;
args.getLVQKey(key);
BOOST_CHECK_EQUAL(key, "qpid.LVQ_key");
-
+
msg1->getProperties<MessageProperties>()->getApplicationHeaders().setString(key,"a");
queue->deliver(msg1);
queue->deliver(msg2);
BOOST_CHECK_EQUAL(queue->getMessageCount(), 2u);
-
+
}
QPID_AUTO_TEST_CASE(testLVQAcquire){
@@ -403,7 +406,7 @@ QPID_AUTO_TEST_CASE(testLVQAcquire){
Queue::shared_ptr queue(new Queue("my-queue", true ));
queue->configure(args);
-
+
intrusive_ptr<Message> msg1 = create_message("e", "A");
intrusive_ptr<Message> msg2 = create_message("e", "B");
intrusive_ptr<Message> msg3 = create_message("e", "C");
@@ -416,7 +419,7 @@ QPID_AUTO_TEST_CASE(testLVQAcquire){
string key;
args.getLVQKey(key);
BOOST_CHECK_EQUAL(key, "qpid.LVQ_key");
-
+
msg1->getProperties<MessageProperties>()->getApplicationHeaders().setString(key,"a");
msg2->getProperties<MessageProperties>()->getApplicationHeaders().setString(key,"b");
@@ -424,13 +427,13 @@ QPID_AUTO_TEST_CASE(testLVQAcquire){
msg4->getProperties<MessageProperties>()->getApplicationHeaders().setString(key,"a");
msg5->getProperties<MessageProperties>()->getApplicationHeaders().setString(key,"b");
msg6->getProperties<MessageProperties>()->getApplicationHeaders().setString(key,"c");
-
+
//enqueue 4 message
queue->deliver(msg1);
queue->deliver(msg2);
queue->deliver(msg3);
queue->deliver(msg4);
-
+
BOOST_CHECK_EQUAL(queue->getMessageCount(), 3u);
framing::SequenceNumber sequence(1);
@@ -439,9 +442,9 @@ QPID_AUTO_TEST_CASE(testLVQAcquire){
BOOST_CHECK(!queue->acquire(qmsg));
BOOST_CHECK(queue->acquire(qmsg2));
-
+
BOOST_CHECK_EQUAL(queue->getMessageCount(), 2u);
-
+
queue->deliver(msg5);
BOOST_CHECK_EQUAL(queue->getMessageCount(), 3u);
@@ -449,11 +452,11 @@ QPID_AUTO_TEST_CASE(testLVQAcquire){
args.setOrdering(client::LVQ_NO_BROWSE);
queue->configure(args);
TestConsumer::shared_ptr c1(new TestConsumer(false));
-
+
queue->dispatch(c1);
queue->dispatch(c1);
queue->dispatch(c1);
-
+
queue->deliver(msg6);
BOOST_CHECK_EQUAL(queue->getMessageCount(), 3u);
@@ -474,7 +477,7 @@ QPID_AUTO_TEST_CASE(testLVQMultiQueue){
intrusive_ptr<Message> received;
queue1->configure(args);
queue2->configure(args);
-
+
intrusive_ptr<Message> msg1 = create_message("e", "A");
intrusive_ptr<Message> msg2 = create_message("e", "A");
@@ -484,17 +487,17 @@ QPID_AUTO_TEST_CASE(testLVQMultiQueue){
msg1->getProperties<MessageProperties>()->getApplicationHeaders().setString(key,"a");
msg2->getProperties<MessageProperties>()->getApplicationHeaders().setString(key,"a");
-
+
queue1->deliver(msg1);
queue2->deliver(msg1);
queue1->deliver(msg2);
-
+
received = queue1->get().payload;
BOOST_CHECK_EQUAL(msg2.get(), received.get());
received = queue2->get().payload;
BOOST_CHECK_EQUAL(msg1.get(), received.get());
-
+
}
QPID_AUTO_TEST_CASE(testLVQRecover){
@@ -518,7 +521,7 @@ QPID_AUTO_TEST_CASE(testLVQRecover){
Queue::shared_ptr queue1(new Queue("my-queue", true, &testStore));
intrusive_ptr<Message> received;
queue1->configure(args);
-
+
intrusive_ptr<Message> msg1 = create_message("e", "A");
intrusive_ptr<Message> msg2 = create_message("e", "A");
// 2
@@ -544,7 +547,7 @@ QPID_AUTO_TEST_CASE(testLVQRecover){
BOOST_CHECK_EQUAL(testStore.deqCnt, 1u);
}
-void addMessagesToQueue(uint count, Queue& queue, uint oddTtl = 200, uint evenTtl = 0)
+void addMessagesToQueue(uint count, Queue& queue, uint oddTtl = 200, uint evenTtl = 0)
{
for (uint i = 0; i < count; i++) {
intrusive_ptr<Message> m = create_message("exchange", "key");
@@ -592,7 +595,7 @@ QPID_AUTO_TEST_CASE(testMultiQueueLastNode){
queue1->configure(args);
Queue::shared_ptr queue2(new Queue("queue2", true, &testStore ));
queue2->configure(args);
-
+
intrusive_ptr<Message> msg1 = create_message("e", "A");
queue1->deliver(msg1);
@@ -623,7 +626,7 @@ QPID_AUTO_TEST_CASE(testMultiQueueLastNode){
// check no failure messages are stored
queue1->clearLastNodeFailure();
queue2->clearLastNodeFailure();
-
+
intrusive_ptr<Message> msg3 = create_message("e", "B");
queue1->deliver(msg3);
queue2->deliver(msg3);
@@ -631,7 +634,7 @@ QPID_AUTO_TEST_CASE(testMultiQueueLastNode){
queue1->setLastNodeFailure();
queue2->setLastNodeFailure();
BOOST_CHECK_EQUAL(testStore.enqCnt, 6u);
-
+
// check requeue 1
intrusive_ptr<Message> msg4 = create_message("e", "C");
intrusive_ptr<Message> msg5 = create_message("e", "D");
@@ -639,17 +642,17 @@ QPID_AUTO_TEST_CASE(testMultiQueueLastNode){
framing::SequenceNumber sequence(1);
QueuedMessage qmsg1(queue1.get(), msg4, sequence);
QueuedMessage qmsg2(queue2.get(), msg5, ++sequence);
-
+
queue1->requeue(qmsg1);
BOOST_CHECK_EQUAL(testStore.enqCnt, 7u);
-
+
// check requeue 2
queue2->clearLastNodeFailure();
queue2->requeue(qmsg2);
BOOST_CHECK_EQUAL(testStore.enqCnt, 7u);
queue2->setLastNodeFailure();
BOOST_CHECK_EQUAL(testStore.enqCnt, 8u);
-
+
queue2->clearLastNodeFailure();
queue2->setLastNodeFailure();
BOOST_CHECK_EQUAL(testStore.enqCnt, 8u);
@@ -664,8 +667,8 @@ simulate this:
4. stop and recover remaining node
5. add another node
6. kill that new node again
-make sure that an attempt to re-enqueue a message does not happen which will
-result in the last man standing exiting with an error.
+make sure that an attempt to re-enqueue a message does not happen which will
+result in the last man standing exiting with an error.
we need to make sure that recover is safe, i.e. messages are
not requeued to the store.
@@ -678,7 +681,7 @@ not requeued to the store.
Queue::shared_ptr queue1(new Queue("my-queue", true, &testStore));
intrusive_ptr<Message> received;
queue1->configure(args);
-
+
// check requeue 1
intrusive_ptr<Message> msg1 = create_message("e", "C");
intrusive_ptr<Message> msg2 = create_message("e", "D");
@@ -711,17 +714,29 @@ simulate store excption going into last node standing
Queue::shared_ptr queue1(new Queue("my-queue", true, &testStore));
intrusive_ptr<Message> received;
queue1->configure(args);
-
+
// check requeue 1
intrusive_ptr<Message> msg1 = create_message("e", "C");
queue1->deliver(msg1);
testStore.createError();
-
+
ScopedSuppressLogging sl; // Suppress messages for expected errors.
queue1->setLastNodeFailure();
BOOST_CHECK_EQUAL(testStore.enqCnt, 0u);
-}QPID_AUTO_TEST_SUITE_END()
+}
+
+intrusive_ptr<Message> mkMsg(std::string exchange, std::string routingKey) {
+ intrusive_ptr<Message> msg(new Message());
+ AMQFrame method((MessageTransferBody(ProtocolVersion(), exchange, 0, 0)));
+ AMQFrame header((AMQHeaderBody()));
+ msg->getFrames().append(method);
+ msg->getFrames().append(header);
+ msg->getFrames().getHeaders()->get<DeliveryProperties>(true)->setRoutingKey(routingKey);
+ return msg;
+}
+QPID_AUTO_TEST_SUITE_END()
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/RangeSet.cpp b/qpid/cpp/src/tests/RangeSet.cpp
index 9c602de78d..db3a964086 100644
--- a/qpid/cpp/src/tests/RangeSet.cpp
+++ b/qpid/cpp/src/tests/RangeSet.cpp
@@ -24,6 +24,9 @@
using namespace std;
using namespace qpid;
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(RangeSetTestSuite)
typedef qpid::Range<int> TestRange;
@@ -44,8 +47,8 @@ QPID_AUTO_TEST_CASE(testRangeSetAddPoint) {
BOOST_CHECK_MESSAGE(r.contains(TestRange(3,4)), r);
BOOST_CHECK(!r.empty());
r += 5;
- BOOST_CHECK_MESSAGE(r.contains(5), r);
- BOOST_CHECK_MESSAGE(r.contains(TestRange(5,6)), r);
+ BOOST_CHECK_MESSAGE(r.contains(5), r);
+ BOOST_CHECK_MESSAGE(r.contains(TestRange(5,6)), r);
BOOST_CHECK_MESSAGE(!r.contains(TestRange(3,6)), r);
r += 4;
BOOST_CHECK_MESSAGE(r.contains(TestRange(3,6)), r);
@@ -139,3 +142,5 @@ QPID_AUTO_TEST_CASE(testRangeContaining) {
}
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/RateFlowcontrolTest.cpp b/qpid/cpp/src/tests/RateFlowcontrolTest.cpp
index b8fda09f61..80ad06af8c 100644
--- a/qpid/cpp/src/tests/RateFlowcontrolTest.cpp
+++ b/qpid/cpp/src/tests/RateFlowcontrolTest.cpp
@@ -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
@@ -27,25 +27,28 @@
using namespace qpid::broker;
using namespace qpid::sys;
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(RateFlowcontrolTestSuite)
QPID_AUTO_TEST_CASE(RateFlowcontrolTest)
{
// BOOST_CHECK(predicate);
// BOOST_CHECK_EQUAL(a, b);
-
+
RateFlowcontrol fc(100);
AbsTime n=AbsTime::now();
-
+
BOOST_CHECK_EQUAL( fc.receivedMessage(n, 0), 0U );
-
+
fc.sentCredit(n, 0);
-
+
BOOST_CHECK_EQUAL( fc.receivedMessage(n, 0), 0U );
fc.sentCredit(n, 50);
Duration d=250*TIME_MSEC;
-
+
n = AbsTime(n,d);
BOOST_CHECK_EQUAL( fc.receivedMessage(n, 25), 0U );
BOOST_CHECK_EQUAL( fc.availableCredit(n), 25U );
@@ -64,3 +67,5 @@ QPID_AUTO_TEST_CASE(RateFlowcontrolTest)
}
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/RefCounted.cpp b/qpid/cpp/src/tests/RefCounted.cpp
index 8c679a3d2e..e4c1da5696 100644
--- a/qpid/cpp/src/tests/RefCounted.cpp
+++ b/qpid/cpp/src/tests/RefCounted.cpp
@@ -27,6 +27,9 @@ using boost::intrusive_ptr;
using namespace std;
using namespace qpid;
+namespace qpid {
+namespace tests {
+
struct CountMe : public RefCounted {
static int instances;
CountMe() { ++instances; }
@@ -48,3 +51,5 @@ QPID_AUTO_TEST_CASE(testRefCounted) {
}
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/ReplicationTest.cpp b/qpid/cpp/src/tests/ReplicationTest.cpp
index 38dc1a9e52..ed768f1306 100644
--- a/qpid/cpp/src/tests/ReplicationTest.cpp
+++ b/qpid/cpp/src/tests/ReplicationTest.cpp
@@ -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
@@ -42,6 +42,9 @@ using namespace qpid::framing;
using namespace qpid::replication::constants;
using boost::assign::list_of;
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(ReplicationTestSuite)
// The CMake-based build passes in the module suffix; if it's not there, this
@@ -63,7 +66,7 @@ qpid::broker::Broker::Options getBrokerOpts(const std::vector<std::string>& args
return opts;
}
-QPID_AUTO_TEST_CASE(testReplicationExchange)
+QPID_AUTO_TEST_CASE(testReplicationExchange)
{
qpid::broker::Broker::Options brokerOpts(getBrokerOpts(list_of<string>("qpidd")
("--replication-exchange-name=qpid.replication")));
@@ -79,7 +82,7 @@ QPID_AUTO_TEST_CASE(testReplicationExchange)
f.session.queueDeclare(arg::queue=eventQ, arg::exclusive=true, arg::autoDelete=true, arg::arguments=eventQopts);
f.session.exchangeBind(arg::exchange="qpid.replication", arg::queue=eventQ, arg::bindingKey=dataQ);
-
+
f.session.queueDeclare(arg::queue=eventQ2, arg::exclusive=true, arg::autoDelete=true, arg::arguments=eventQopts);
f.session.exchangeBind(arg::exchange="qpid.replication", arg::queue=eventQ2, arg::bindingKey=dataQ2);
@@ -133,3 +136,5 @@ QPID_AUTO_TEST_CASE(testReplicationExchange)
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/RetryList.cpp b/qpid/cpp/src/tests/RetryList.cpp
index 80f59bf15f..d1d22348a3 100644
--- a/qpid/cpp/src/tests/RetryList.cpp
+++ b/qpid/cpp/src/tests/RetryList.cpp
@@ -24,6 +24,9 @@
using namespace qpid;
using namespace qpid::broker;
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(RetryListTestSuite)
struct RetryListFixture
@@ -36,7 +39,7 @@ struct RetryListFixture
{
urls.push_back(Url(s));
}
-
+
void addExpectation(const std::string& host, uint16_t port)
{
expected.push_back(TcpAddress(host, port));
@@ -57,7 +60,7 @@ struct RetryListFixture
}
};
-QPID_AUTO_TEST_CASE(testWithSingleAddress)
+QPID_AUTO_TEST_CASE(testWithSingleAddress)
{
RetryListFixture test;
test.addUrl("amqp:host:5673");
@@ -65,7 +68,7 @@ QPID_AUTO_TEST_CASE(testWithSingleAddress)
test.check();
}
-QPID_AUTO_TEST_CASE(testWithSingleUrlOfMultipleAddresses)
+QPID_AUTO_TEST_CASE(testWithSingleUrlOfMultipleAddresses)
{
RetryListFixture test;
test.addUrl("amqp:host1,host2:2222,tcp:host3:5673,host4:1");
@@ -78,7 +81,7 @@ QPID_AUTO_TEST_CASE(testWithSingleUrlOfMultipleAddresses)
test.check();
}
-QPID_AUTO_TEST_CASE(testWithMultipleUrlsOfMultipleAddresses)
+QPID_AUTO_TEST_CASE(testWithMultipleUrlsOfMultipleAddresses)
{
RetryListFixture test;
test.addUrl("amqp:my-host");
@@ -97,10 +100,12 @@ QPID_AUTO_TEST_CASE(testWithMultipleUrlsOfMultipleAddresses)
test.check();
}
-QPID_AUTO_TEST_CASE(testEmptyList)
+QPID_AUTO_TEST_CASE(testEmptyList)
{
RetryListFixture test;
test.check();
}
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/SequenceNumberTest.cpp b/qpid/cpp/src/tests/SequenceNumberTest.cpp
index e4c6d066ef..f3c934e3ca 100644
--- a/qpid/cpp/src/tests/SequenceNumberTest.cpp
+++ b/qpid/cpp/src/tests/SequenceNumberTest.cpp
@@ -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
@@ -26,6 +26,8 @@
using namespace qpid::framing;
+namespace qpid {
+namespace tests {
void checkDifference(SequenceNumber& a, SequenceNumber& b, int gap)
{
@@ -54,7 +56,7 @@ void checkComparison(SequenceNumber& a, SequenceNumber& b, int gap)
BOOST_CHECK(++a < ++b);//test prefix
}
//keep incrementing until a also wraps around
- for (int i = 0; i < (gap + 2); i++) {
+ for (int i = 0; i < (gap + 2); i++) {
BOOST_CHECK(a++ < b++);//test postfix
}
//let a 'catch up'
@@ -91,7 +93,7 @@ QPID_AUTO_TEST_CASE(testIncrementPostfix)
BOOST_CHECK(b != c);
}
-QPID_AUTO_TEST_CASE(testIncrementPrefix)
+QPID_AUTO_TEST_CASE(testIncrementPrefix)
{
SequenceNumber a;
SequenceNumber b;
@@ -203,3 +205,5 @@ QPID_AUTO_TEST_CASE(testDifferenceWithWrapAround2)
}
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/SequenceSet.cpp b/qpid/cpp/src/tests/SequenceSet.cpp
index ba2f1391a1..aaeb68e3c5 100644
--- a/qpid/cpp/src/tests/SequenceSet.cpp
+++ b/qpid/cpp/src/tests/SequenceSet.cpp
@@ -20,6 +20,9 @@
#include "unit_test.h"
#include <list>
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(SequenceSetTestSuite)
using namespace qpid::framing;
@@ -72,7 +75,7 @@ QPID_AUTO_TEST_CASE(testAdd) {
BOOST_CHECK(!s.contains(i));
RangeExpectations().expect(2, 5).expect(8, 8).check(s);
-
+
SequenceSet t;
t.add(6, 10);
t.add(s);
@@ -90,7 +93,7 @@ QPID_AUTO_TEST_CASE(testAdd2) {
SequenceSet s;
s.add(7,6);
s.add(4,4);
- s.add(3,10);
+ s.add(3,10);
s.add(2);
RangeExpectations().expect(2, 10).check(s);
}
@@ -137,4 +140,4 @@ QPID_AUTO_TEST_CASE(testRemove) {
QPID_AUTO_TEST_SUITE_END()
-
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/SessionState.cpp b/qpid/cpp/src/tests/SessionState.cpp
index 5e21ff2b70..157cabfb63 100644
--- a/qpid/cpp/src/tests/SessionState.cpp
+++ b/qpid/cpp/src/tests/SessionState.cpp
@@ -28,6 +28,9 @@
#include <functional>
#include <numeric>
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(SessionStateTestSuite)
using namespace std;
@@ -94,7 +97,7 @@ size_t transfer1(qpid::SessionState& s, string content) {
size_t transfer1Char(qpid::SessionState& s, char content) {
return transfer1(s, string(1,content));
}
-
+
// Send transfer frame with multiple single-byte content frames.
size_t transferN(qpid::SessionState& s, string content) {
size_t size=send(s, transferFrame(!content.empty()));
@@ -134,7 +137,7 @@ QPID_AUTO_TEST_CASE(testSendGetReplyList) {
BOOST_CHECK_EQUAL(str(s.senderExpected(SessionPoint(0,0))),"CabcCdCeCfCxyz");
// Ignore controls.
s.senderRecord(AMQFrame(new SessionFlushBody()));
- BOOST_CHECK_EQUAL(str(s.senderExpected(SessionPoint(2,0))),"CeCfCxyz");
+ BOOST_CHECK_EQUAL(str(s.senderExpected(SessionPoint(2,0))),"CeCfCxyz");
}
QPID_AUTO_TEST_CASE(testNeedFlush) {
@@ -185,7 +188,7 @@ QPID_AUTO_TEST_CASE(testPeerConfirmed) {
s.senderConfirmed(SessionPoint(5));
BOOST_CHECK_EQUAL(str(s.senderExpected(SessionPoint(5,0))), "CxCy");
BOOST_CHECK(s.senderNeedFlush());
-
+
s.senderConfirmed(SessionPoint(6));
BOOST_CHECK_EQUAL(str(s.senderExpected(SessionPoint(6,0))), "Cy");
BOOST_CHECK(!s.senderNeedFlush());
@@ -195,7 +198,7 @@ QPID_AUTO_TEST_CASE(testPeerCompleted) {
qpid::SessionState s;
s.setTimeout(1);
s.senderGetCommandPoint();
- // Completion implies confirmation
+ // Completion implies confirmation
transfers(s, "abc");
BOOST_CHECK_EQUAL(str(s.senderExpected(SessionPoint(0,0))), "CaCbCc");
SequenceSet set(SequenceSet() + 0 + 1);
@@ -205,7 +208,7 @@ QPID_AUTO_TEST_CASE(testPeerCompleted) {
transfers(s, "def");
// We dont do out-of-order confirmation, so this will only confirm up to 3:
set = SequenceSet(SequenceSet() + 2 + 3 + 5);
- s.senderCompleted(set);
+ s.senderCompleted(set);
BOOST_CHECK_EQUAL(str(s.senderExpected(SessionPoint(4,0))), "CeCf");
}
@@ -215,11 +218,11 @@ QPID_AUTO_TEST_CASE(testReceive) {
s.receiverSetCommandPoint(SessionPoint());
BOOST_CHECK_EQUAL(s.receiverGetExpected(), SessionPoint(0));
BOOST_CHECK_EQUAL(s.receiverGetReceived(), SessionPoint(0));
-
+
BOOST_CHECK(s.receiverRecord(transferFrame(false)));
BOOST_CHECK_EQUAL(s.receiverGetExpected(), SessionPoint(1));
BOOST_CHECK_EQUAL(s.receiverGetReceived(), SessionPoint(1));
-
+
BOOST_CHECK(s.receiverRecord(transferFrame(true)));
SessionPoint point = SessionPoint(1, transferFrameSize());
BOOST_CHECK_EQUAL(s.receiverGetExpected(), point);
@@ -297,3 +300,5 @@ QPID_AUTO_TEST_CASE(testNeedKnownCompleted) {
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/Shlib.cpp b/qpid/cpp/src/tests/Shlib.cpp
index 7d2f2456c7..692cfcdff9 100644
--- a/qpid/cpp/src/tests/Shlib.cpp
+++ b/qpid/cpp/src/tests/Shlib.cpp
@@ -24,6 +24,9 @@
#include "unit_test.h"
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(ShlibTestSuite)
using namespace qpid::sys;
@@ -51,7 +54,7 @@ QPID_AUTO_TEST_CASE(testShlib) {
}
catch (const qpid::Exception&) {}
}
-
+
QPID_AUTO_TEST_CASE(testAutoShlib) {
int unloaded = 0;
{
@@ -66,6 +69,8 @@ QPID_AUTO_TEST_CASE(testAutoShlib) {
}
BOOST_CHECK_EQUAL(42, unloaded);
}
-
+
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/SocketProxy.h b/qpid/cpp/src/tests/SocketProxy.h
index ccce3c8842..9df32a1336 100644
--- a/qpid/cpp/src/tests/SocketProxy.h
+++ b/qpid/cpp/src/tests/SocketProxy.h
@@ -35,8 +35,11 @@
#include "qpid/sys/Mutex.h"
#include "qpid/log/Statement.h"
+namespace qpid {
+namespace tests {
+
/**
- * A simple socket proxy that forwards to another socket.
+ * A simple socket proxy that forwards to another socket.
* Used between client & local broker to simulate network failures.
*/
class SocketProxy : private qpid::sys::Runnable
@@ -59,7 +62,7 @@ class SocketProxy : private qpid::sys::Runnable
joined = false;
thread = qpid::sys::Thread(static_cast<qpid::sys::Runnable*>(this));
}
-
+
~SocketProxy() { close(); if (!joined) thread.join(); }
/** Simulate a network disconnect. */
@@ -88,7 +91,7 @@ class SocketProxy : private qpid::sys::Runnable
}
uint16_t getPort() const { return port; }
-
+
private:
static void throwErrno(const std::string& msg) {
throw qpid::Exception(msg+":"+qpid::sys::strError(errno));
@@ -153,7 +156,7 @@ class SocketProxy : private qpid::sys::Runnable
}
try {
if (server.get()) server->close();
- close();
+ close();
}
catch (const std::exception& e) {
QPID_LOG(debug, "SocketProxy::run exception in client/server close()" << e.what());
@@ -169,4 +172,6 @@ class SocketProxy : private qpid::sys::Runnable
bool dropClient, dropServer;
};
+}} // namespace qpid::tests
+
#endif
diff --git a/qpid/cpp/src/tests/TestMessageStore.h b/qpid/cpp/src/tests/TestMessageStore.h
index be1ed57349..20e0b755b2 100644
--- a/qpid/cpp/src/tests/TestMessageStore.h
+++ b/qpid/cpp/src/tests/TestMessageStore.h
@@ -10,9 +10,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
@@ -28,6 +28,9 @@ using namespace qpid;
using namespace qpid::broker;
using namespace qpid::framing;
+namespace qpid {
+namespace tests {
+
typedef std::pair<string, boost::intrusive_ptr<PersistableMessage> > msg_queue_pair;
class TestMessageStore : public NullMessageStore
@@ -35,7 +38,7 @@ class TestMessageStore : public NullMessageStore
public:
std::vector<boost::intrusive_ptr<PersistableMessage> > dequeued;
std::vector<msg_queue_pair> enqueued;
-
+
void dequeue(TransactionContext*,
const boost::intrusive_ptr<PersistableMessage>& msg,
const PersistableQueue& /*queue*/)
@@ -47,7 +50,7 @@ class TestMessageStore : public NullMessageStore
const boost::intrusive_ptr<PersistableMessage>& msg,
const PersistableQueue& queue)
{
- msg->enqueueComplete();
+ msg->enqueueComplete();
enqueued.push_back(msg_queue_pair(queue.getName(), msg));
}
@@ -55,4 +58,6 @@ class TestMessageStore : public NullMessageStore
~TestMessageStore(){}
};
+}} // namespace qpid::tests
+
#endif
diff --git a/qpid/cpp/src/tests/TestOptions.h b/qpid/cpp/src/tests/TestOptions.h
index a400fe5ecb..f8da0f59cf 100644
--- a/qpid/cpp/src/tests/TestOptions.h
+++ b/qpid/cpp/src/tests/TestOptions.h
@@ -9,9 +9,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
@@ -67,7 +67,7 @@ struct TestOptions : public qpid::Options
connection.open(con);
}
-
+
bool help;
ConnectionOptions con;
qpid::log::Options log;
diff --git a/qpid/cpp/src/tests/TimerTest.cpp b/qpid/cpp/src/tests/TimerTest.cpp
index 2642c980ba..1552421ba0 100644
--- a/qpid/cpp/src/tests/TimerTest.cpp
+++ b/qpid/cpp/src/tests/TimerTest.cpp
@@ -8,9 +8,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
@@ -32,6 +32,9 @@ using namespace qpid::sys;
using boost::intrusive_ptr;
using boost::dynamic_pointer_cast;
+namespace qpid {
+namespace tests {
+
class Counter
{
Mutex lock;
@@ -44,7 +47,7 @@ class Counter
return ++counter;
}
};
-
+
class TestTask : public TimerTask
{
const AbsTime start;
@@ -56,7 +59,7 @@ class TestTask : public TimerTask
Counter& counter;
public:
- TestTask(Duration timeout, Counter& _counter)
+ TestTask(Duration timeout, Counter& _counter)
: TimerTask(timeout), start(now()), expected(timeout), end(start), fired(false), counter(_counter) {}
void fire()
@@ -106,14 +109,14 @@ QPID_AUTO_TEST_CASE(testGeneral)
intrusive_ptr<TestTask> task2(new TestTask(Duration(1 * TIME_SEC), counter));
intrusive_ptr<TestTask> task3(new TestTask(Duration(4 * TIME_SEC), counter));
intrusive_ptr<TestTask> task4(new TestTask(Duration(2 * TIME_SEC), counter));
-
+
timer.add(task1);
timer.add(task2);
timer.add(task3);
timer.add(task4);
-
+
dynamic_pointer_cast<TestTask>(task3)->wait(Duration(6 * TIME_SEC));
-
+
dynamic_pointer_cast<TestTask>(task1)->check(3);
dynamic_pointer_cast<TestTask>(task2)->check(1);
dynamic_pointer_cast<TestTask>(task3)->check(4);
@@ -121,3 +124,5 @@ QPID_AUTO_TEST_CASE(testGeneral)
}
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/TopicExchangeTest.cpp b/qpid/cpp/src/tests/TopicExchangeTest.cpp
index d707066534..c103620dbf 100644
--- a/qpid/cpp/src/tests/TopicExchangeTest.cpp
+++ b/qpid/cpp/src/tests/TopicExchangeTest.cpp
@@ -6,9 +6,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
@@ -22,11 +22,15 @@
using namespace qpid::broker;
using namespace std;
+
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(TopicExchangeTestSuite)
#define CHECK_NORMALIZED(expect, pattern) BOOST_CHECK_EQUAL(expect, TopicExchange::normalize(pattern));
-QPID_AUTO_TEST_CASE(testNormalize)
+QPID_AUTO_TEST_CASE(testNormalize)
{
CHECK_NORMALIZED("", "");
CHECK_NORMALIZED("a.b.c", "a.b.c");
@@ -38,8 +42,8 @@ QPID_AUTO_TEST_CASE(testNormalize)
CHECK_NORMALIZED("a.*.*.*.#", "a.*.#.*.#.*");
CHECK_NORMALIZED("*.*.*.#", "*.#.#.*.*.#");
}
-
-QPID_AUTO_TEST_CASE(testPlain)
+
+QPID_AUTO_TEST_CASE(testPlain)
{
string pattern("ab.cd.e");
BOOST_CHECK(TopicExchange::match(pattern, "ab.cd.e"));
@@ -57,7 +61,7 @@ QPID_AUTO_TEST_CASE(testPlain)
}
-QPID_AUTO_TEST_CASE(testStar)
+QPID_AUTO_TEST_CASE(testStar)
{
string pattern("a.*.b");
BOOST_CHECK(TopicExchange::match(pattern, "a.xx.b"));
@@ -75,7 +79,7 @@ QPID_AUTO_TEST_CASE(testStar)
BOOST_CHECK(!TopicExchange::match(pattern, "q.x.y"));
}
-QPID_AUTO_TEST_CASE(testHash)
+QPID_AUTO_TEST_CASE(testHash)
{
string pattern("a.#.b");
BOOST_CHECK(TopicExchange::match(pattern, "a.b"));
@@ -99,7 +103,7 @@ QPID_AUTO_TEST_CASE(testHash)
BOOST_CHECK(TopicExchange::match(pattern, "a.x.x.b.y.y.c"));
}
-QPID_AUTO_TEST_CASE(testMixed)
+QPID_AUTO_TEST_CASE(testMixed)
{
string pattern("*.x.#.y");
BOOST_CHECK(TopicExchange::match(pattern, "a.x.y"));
@@ -119,3 +123,5 @@ QPID_AUTO_TEST_CASE(testMixed)
}
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/TxBufferTest.cpp b/qpid/cpp/src/tests/TxBufferTest.cpp
index 3d6a12cacc..4807026ab7 100644
--- a/qpid/cpp/src/tests/TxBufferTest.cpp
+++ b/qpid/cpp/src/tests/TxBufferTest.cpp
@@ -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
@@ -27,6 +27,9 @@
using namespace qpid::broker;
using boost::static_pointer_cast;
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(TxBufferTestSuite)
QPID_AUTO_TEST_CASE(testCommitLocal)
@@ -174,3 +177,5 @@ QPID_AUTO_TEST_CASE(testBufferIsClearedAfterCommit)
}
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/TxMocks.h b/qpid/cpp/src/tests/TxMocks.h
index fe103c5fe5..a34d864bae 100644
--- a/qpid/cpp/src/tests/TxMocks.h
+++ b/qpid/cpp/src/tests/TxMocks.h
@@ -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
@@ -32,6 +32,9 @@ using namespace qpid::broker;
using boost::static_pointer_cast;
using std::string;
+namespace qpid {
+namespace tests {
+
template <class T> void assertEqualVector(std::vector<T>& expected, std::vector<T>& actual){
unsigned int i = 0;
while(i < expected.size() && i < actual.size()){
@@ -62,15 +65,15 @@ class MockTxOp : public TxOp, public TxOpConstants{
string debugName;
public:
typedef boost::shared_ptr<MockTxOp> shared_ptr;
-
+
MockTxOp() : failOnPrepare(false) {}
MockTxOp(bool _failOnPrepare) : failOnPrepare(_failOnPrepare) {}
-
+
void setDebugName(string name){
debugName = name;
}
- void printExpected(){
+ void printExpected(){
std::cout << std::endl << "MockTxOp[" << debugName << "] expects: ";
for (std::vector<string>::iterator i = expected.begin(); i < expected.end(); i++) {
if(i != expected.begin()) std::cout << ", ";
@@ -79,7 +82,7 @@ public:
std::cout << std::endl;
}
- void printActual(){
+ void printActual(){
std::cout << std::endl << "MockTxOp[" << debugName << "] actual: ";
for (std::vector<string>::iterator i = actual.begin(); i < actual.end(); i++) {
if(i != actual.begin()) std::cout << ", ";
@@ -87,7 +90,7 @@ public:
}
std::cout << std::endl;
}
-
+
bool prepare(TransactionContext*) throw(){
actual.push_back(PREPARE);
return !failOnPrepare;
@@ -116,8 +119,8 @@ public:
}
void accept(TxOpConstVisitor&) const {}
-
- ~MockTxOp(){}
+
+ ~MockTxOp(){}
};
class MockTransactionalStore : public TransactionalStore{
@@ -128,10 +131,10 @@ class MockTransactionalStore : public TransactionalStore{
const string ABORT;
std::vector<string> expected;
std::vector<string> actual;
-
+
enum states {OPEN = 1, PREPARED = 2, COMMITTED = 3, ABORTED = 4};
int state;
-
+
class TestTransactionContext : public TPCTransactionContext{
MockTransactionalStore* store;
public:
@@ -145,29 +148,29 @@ class MockTransactionalStore : public TransactionalStore{
if(!store->isOpen() && !store->isPrepared()) throw "txn already completed";
store->state = COMMITTED;
}
-
+
void abort(){
if(!store->isOpen() && !store->isPrepared()) throw "txn already completed";
store->state = ABORTED;
}
~TestTransactionContext(){}
};
-
+
public:
MockTransactionalStore() :
BEGIN("BEGIN"), BEGIN2PC("BEGIN2PC"), PREPARE("PREPARE"), COMMIT("COMMIT"), ABORT("ABORT"), state(OPEN){}
void collectPreparedXids(std::set<std::string>&)
{
- throw "Operation not supported";
+ throw "Operation not supported";
}
-
- std::auto_ptr<TPCTransactionContext> begin(const std::string&){
+
+ std::auto_ptr<TPCTransactionContext> begin(const std::string&){
actual.push_back(BEGIN2PC);
std::auto_ptr<TPCTransactionContext> txn(new TestTransactionContext(this));
return txn;
}
- std::auto_ptr<TransactionContext> begin(){
+ std::auto_ptr<TransactionContext> begin(){
actual.push_back(BEGIN);
std::auto_ptr<TransactionContext> txn(new TestTransactionContext(this));
return txn;
@@ -183,7 +186,7 @@ public:
void abort(TransactionContext& ctxt){
actual.push_back(ABORT);
dynamic_cast<TestTransactionContext&>(ctxt).abort();
- }
+ }
MockTransactionalStore& expectBegin(){
expected.push_back(BEGIN);
return *this;
@@ -207,23 +210,25 @@ public:
void check(){
assertEqualVector(expected, actual);
}
-
+
bool isPrepared(){
return state == PREPARED;
}
-
+
bool isCommitted(){
return state == COMMITTED;
}
-
+
bool isAborted(){
return state == ABORTED;
}
-
+
bool isOpen() const{
return state == OPEN;
}
~MockTransactionalStore(){}
};
+}} // namespace qpid::tests
+
#endif
diff --git a/qpid/cpp/src/tests/TxPublishTest.cpp b/qpid/cpp/src/tests/TxPublishTest.cpp
index 63dbf99266..fabb01b864 100644
--- a/qpid/cpp/src/tests/TxPublishTest.cpp
+++ b/qpid/cpp/src/tests/TxPublishTest.cpp
@@ -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
@@ -35,30 +35,33 @@ using boost::intrusive_ptr;
using namespace qpid::broker;
using namespace qpid::framing;
+namespace qpid {
+namespace tests {
+
struct TxPublishTest
{
-
+
TestMessageStore store;
Queue::shared_ptr queue1;
Queue::shared_ptr queue2;
intrusive_ptr<Message> msg;
TxPublish op;
-
+
TxPublishTest() :
- queue1(new Queue("queue1", false, &store, 0)),
- queue2(new Queue("queue2", false, &store, 0)),
+ queue1(new Queue("queue1", false, &store, 0)),
+ queue2(new Queue("queue2", false, &store, 0)),
msg(MessageUtils::createMessage("exchange", "routing_key", "id")),
op(msg)
{
msg->getProperties<DeliveryProperties>()->setDeliveryMode(PERSISTENT);
op.deliverTo(queue1);
op.deliverTo(queue2);
- }
+ }
};
QPID_AUTO_TEST_SUITE(TxPublishTestSuite)
-
+
QPID_AUTO_TEST_CASE(testPrepare)
{
TxPublishTest t;
@@ -88,7 +91,9 @@ QPID_AUTO_TEST_CASE(testCommit)
BOOST_CHECK_EQUAL(t.msg, msg_dequeue);
BOOST_CHECK_EQUAL((uint32_t) 1, t.queue2->getMessageCount());
- BOOST_CHECK_EQUAL(t.msg, t.queue2->get().payload);
+ BOOST_CHECK_EQUAL(t.msg, t.queue2->get().payload);
}
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/Url.cpp b/qpid/cpp/src/tests/Url.cpp
index f3b42a7208..343186eb1f 100644
--- a/qpid/cpp/src/tests/Url.cpp
+++ b/qpid/cpp/src/tests/Url.cpp
@@ -26,6 +26,9 @@ using namespace std;
using namespace qpid;
using namespace boost::assign;
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(UrlTestSuite)
#define URL_CHECK_STR(STR) BOOST_CHECK_EQUAL(Url(STR).str(), STR)
@@ -65,3 +68,5 @@ QPID_AUTO_TEST_CASE(TestInvalidAddress) {
}
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/Uuid.cpp b/qpid/cpp/src/tests/Uuid.cpp
index ea2e80b63b..a6ddb9b5a5 100644
--- a/qpid/cpp/src/tests/Uuid.cpp
+++ b/qpid/cpp/src/tests/Uuid.cpp
@@ -24,6 +24,9 @@
#include <set>
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(UuidTestSuite)
using namespace std;
@@ -77,3 +80,5 @@ QPID_AUTO_TEST_CASE(testUuidEncodeDecode) {
}
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/Variant.cpp b/qpid/cpp/src/tests/Variant.cpp
index b7ce776827..2d68bb842c 100644
--- a/qpid/cpp/src/tests/Variant.cpp
+++ b/qpid/cpp/src/tests/Variant.cpp
@@ -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
@@ -25,6 +25,9 @@
using namespace qpid::messaging;
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(VariantSuite)
QPID_AUTO_TEST_CASE(testConversions)
@@ -94,11 +97,11 @@ QPID_AUTO_TEST_CASE(testAssignment)
const uint32_t i(1000);
value = i;
BOOST_CHECK_EQUAL(VAR_UINT32, value.getType());
- BOOST_CHECK_EQUAL(VAR_STRING, other.getType());
+ BOOST_CHECK_EQUAL(VAR_STRING, other.getType());
}
QPID_AUTO_TEST_CASE(testList)
-{
+{
const std::string s("abc");
const float f(9.876f);
const int16_t x(1000);
@@ -108,7 +111,7 @@ QPID_AUTO_TEST_CASE(testList)
value.asList().push_back(Variant(f));
value.asList().push_back(Variant(x));
BOOST_CHECK_EQUAL(3u, value.asList().size());
- Variant::List::const_iterator i = value.asList().begin();
+ Variant::List::const_iterator i = value.asList().begin();
BOOST_CHECK(i != value.asList().end());
BOOST_CHECK_EQUAL(VAR_STRING, i->getType());
@@ -129,7 +132,7 @@ QPID_AUTO_TEST_CASE(testList)
}
QPID_AUTO_TEST_CASE(testMap)
-{
+{
const std::string red("red");
const float pi(3.14f);
const int16_t x(1000);
@@ -145,7 +148,7 @@ QPID_AUTO_TEST_CASE(testMap)
BOOST_CHECK_EQUAL(VAR_FLOAT, value.asMap()["pi"].getType());
BOOST_CHECK_EQUAL(pi, value.asMap()["pi"].asFloat());
-
+
BOOST_CHECK_EQUAL(VAR_INT16, value.asMap()["my-key"].getType());
BOOST_CHECK_EQUAL(x, value.asMap()["my-key"].asInt16());
@@ -153,5 +156,7 @@ QPID_AUTO_TEST_CASE(testMap)
BOOST_CHECK_EQUAL(VAR_STRING, value.asMap()["my-key"].getType());
BOOST_CHECK_EQUAL(std::string("now it's a string"), value.asMap()["my-key"].asString());
}
-
+
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/XmlClientSessionTest.cpp b/qpid/cpp/src/tests/XmlClientSessionTest.cpp
index b6b8520bd8..46a4c826a3 100644
--- a/qpid/cpp/src/tests/XmlClientSessionTest.cpp
+++ b/qpid/cpp/src/tests/XmlClientSessionTest.cpp
@@ -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
@@ -39,6 +39,9 @@
#include <vector>
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(XmlClientSessionTest)
using namespace qpid::client;
@@ -118,10 +121,10 @@ QPID_AUTO_TEST_CASE(testXmlBinding) {
FieldTable binding;
binding.setString("xquery", "declare variable $color external;"
"(./message/id mod 2 = 1) and ($color = 'blue')");
- f.session.exchangeBind(qpid::client::arg::exchange="xml", qpid::client::arg::queue="odd_blue", qpid::client::arg::bindingKey="query_name", qpid::client::arg::arguments=binding);
+ f.session.exchangeBind(qpid::client::arg::exchange="xml", qpid::client::arg::queue="odd_blue", qpid::client::arg::bindingKey="query_name", qpid::client::arg::arguments=binding);
Message message;
- message.getDeliveryProperties().setRoutingKey("query_name");
+ message.getDeliveryProperties().setRoutingKey("query_name");
message.getHeaders().setString("color", "blue");
string m = "<message><id>1</id></message>";
@@ -130,7 +133,7 @@ QPID_AUTO_TEST_CASE(testXmlBinding) {
f.session.messageTransfer(qpid::client::arg::content=message, qpid::client::arg::destination="xml");
Message m2 = localQueue.get();
- BOOST_CHECK_EQUAL(m, m2.getData());
+ BOOST_CHECK_EQUAL(m, m2.getData());
}
/**
@@ -146,10 +149,10 @@ QPID_AUTO_TEST_CASE(testXMLBindMultipleQueues) {
FieldTable blue;
blue.setString("xquery", "./colour = 'blue'");
- f.session.exchangeBind(arg::exchange="xml", arg::queue="blue", arg::bindingKey="by-colour", arg::arguments=blue);
+ f.session.exchangeBind(arg::exchange="xml", arg::queue="blue", arg::bindingKey="by-colour", arg::arguments=blue);
FieldTable red;
red.setString("xquery", "./colour = 'red'");
- f.session.exchangeBind(arg::exchange="xml", arg::queue="red", arg::bindingKey="by-colour", arg::arguments=red);
+ f.session.exchangeBind(arg::exchange="xml", arg::queue="red", arg::bindingKey="by-colour", arg::arguments=red);
Message sent1("<colour>blue</colour>", "by-colour");
f.session.messageTransfer(arg::content=sent1, arg::destination="xml");
@@ -223,3 +226,4 @@ olour", arg::arguments=blue);
QPID_AUTO_TEST_SUITE_END()
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/acl.py b/qpid/cpp/src/tests/acl.py
index b62288a769..fc53d2ce8b 100755
--- a/qpid/cpp/src/tests/acl.py
+++ b/qpid/cpp/src/tests/acl.py
@@ -61,7 +61,7 @@ class ACLTests(TestBase010):
# ACL general tests
#=====================================
- def test_deny_all(self):
+ def test_deny_mode(self):
"""
Test the deny all mode
"""
@@ -71,7 +71,9 @@ class ACLTests(TestBase010):
aclf.write('acl deny all all')
aclf.close()
- self.reload_acl()
+ result = self.reload_acl()
+ if (result.text.find("format error",0,len(result.text)) != -1):
+ self.fail(result)
session = self.get_session('bob','bob')
try:
@@ -87,7 +89,7 @@ class ACLTests(TestBase010):
except qpid.session.SessionException, e:
self.assertEqual(530,e.args[0].error_code)
- def test_allow_all(self):
+ def test_allow_mode(self):
"""
Test the allow all mode
"""
@@ -96,7 +98,9 @@ class ACLTests(TestBase010):
aclf.write('acl allow all all')
aclf.close()
- self.reload_acl()
+ result = self.reload_acl()
+ if (result.text.find("format error",0,len(result.text)) != -1):
+ self.fail(result)
session = self.get_session('bob','bob')
try:
@@ -124,7 +128,9 @@ class ACLTests(TestBase010):
aclf.write('acl allow all all')
aclf.close()
- self.reload_acl()
+ result = self.reload_acl()
+ if (result.text.find("format error",0,len(result.text)) != -1):
+ self.fail(result)
session = self.get_session('bob','bob')
try:
@@ -208,9 +214,9 @@ class ACLTests(TestBase010):
# ACL queue tests
#=====================================
- def test_queue_acl(self):
+ def test_queue_allow_mode(self):
"""
- Test various modes for queue acl
+ Test cases for queue acl in allow mode
"""
aclf = ACLFile()
aclf.write('acl deny bob@QPID create queue name=q1 durable=true passive=true\n')
@@ -221,27 +227,35 @@ class ACLTests(TestBase010):
aclf.write('acl allow all all')
aclf.close()
- self.reload_acl()
+ result = self.reload_acl()
+ if (result.text.find("format error",0,len(result.text)) != -1):
+ self.fail(result)
session = self.get_session('bob','bob')
try:
- session.queue_declare(queue="q1", durable='true', passive='true')
+ session.queue_declare(queue="q1", durable=True, passive=True)
self.fail("ACL should deny queue create request with name=q1 durable=true passive=true");
except qpid.session.SessionException, e:
self.assertEqual(530,e.args[0].error_code)
session = self.get_session('bob','bob')
try:
- session.queue_declare(queue="q2", exclusive='true')
+ session.queue_declare(queue="q2", exclusive=True)
self.fail("ACL should deny queue create request with name=q2 exclusive=true");
except qpid.session.SessionException, e:
self.assertEqual(530,e.args[0].error_code)
session = self.get_session('bob','bob')
try:
- session.queue_declare(queue="q3", exclusive='true')
- session.queue_declare(queue="q4", durable='true')
+ session.queue_declare(queue="q2", durable=True)
+ except qpid.session.SessionException, e:
+ if (530 == e.args[0].error_code):
+ self.fail("ACL should allow queue create request for q2 with any parameter other than exclusive=true");
+
+ try:
+ session.queue_declare(queue="q3", exclusive=True)
+ session.queue_declare(queue="q4", durable=True)
except qpid.session.SessionException, e:
if (530 == e.args[0].error_code):
self.fail("ACL should allow queue create request for q3 and q4 with any parameter");
@@ -279,57 +293,185 @@ class ACLTests(TestBase010):
if (530 == e.args[0].error_code):
self.fail("ACL should allow queue delete request for q3");
+
+ def test_queue_deny_mode(self):
+ """
+ Test cases for queue acl in deny mode
+ """
+ aclf = ACLFile()
+ aclf.write('acl allow bob@QPID create queue name=q1 durable=true passive=true\n')
+ aclf.write('acl allow bob@QPID create queue name=q2 exclusive=true\n')
+ aclf.write('acl allow bob@QPID access queue name=q3\n')
+ aclf.write('acl allow bob@QPID purge queue name=q3\n')
+ aclf.write('acl allow bob@QPID create queue name=q3\n')
+ aclf.write('acl allow bob@QPID create queue name=q4\n')
+ aclf.write('acl allow bob@QPID delete queue name=q4\n')
+ aclf.write('acl allow guest@QPID all all\n')
+ aclf.write('acl deny all all')
+ aclf.close()
+
+ result = self.reload_acl()
+ if (result.text.find("format error",0,len(result.text)) != -1):
+ self.fail(result)
+
+ session = self.get_session('bob','bob')
+
+ try:
+ session.queue_declare(queue="q1", durable=True, passive=True)
+ except qpid.session.SessionException, e:
+ if (530 == e.args[0].error_code):
+ self.fail("ACL should allow queue create request with name=q1 durable=true passive=true");
+
+ try:
+ session.queue_declare(queue="q1", durable=False, passive=False)
+ self.fail("ACL should deny queue create request with name=q1 durable=true passive=false");
+ except qpid.session.SessionException, e:
+ self.assertEqual(530,e.args[0].error_code)
+ session = self.get_session('bob','bob')
+
+ try:
+ session.queue_declare(queue="q2", exclusive=False)
+ self.fail("ACL should deny queue create request with name=q2 exclusive=false");
+ except qpid.session.SessionException, e:
+ self.assertEqual(530,e.args[0].error_code)
+ session = self.get_session('bob','bob')
+
+ try:
+ session.queue_declare(queue="q2", exclusive=True)
+ except qpid.session.SessionException, e:
+ if (530 == e.args[0].error_code):
+ self.fail("ACL should allow queue create request for q2 with exclusive=true");
+
+ try:
+ session.queue_declare(queue="q3")
+ session.queue_declare(queue="q4")
+ except qpid.session.SessionException, e:
+ if (530 == e.args[0].error_code):
+ self.fail("ACL should allow queue create request for q3 and q4");
+
+ try:
+ session.queue_query(queue="q4")
+ self.fail("ACL should deny queue query request for q4");
+ except qpid.session.SessionException, e:
+ self.assertEqual(530,e.args[0].error_code)
+ session = self.get_session('bob','bob')
+
+ try:
+ session.queue_purge(queue="q4")
+ self.fail("ACL should deny queue purge request for q4");
+ except qpid.session.SessionException, e:
+ self.assertEqual(530,e.args[0].error_code)
+ session = self.get_session('bob','bob')
+
+ try:
+ session.queue_purge(queue="q3")
+ except qpid.session.SessionException, e:
+ if (530 == e.args[0].error_code):
+ self.fail("ACL should allow queue purge request for q3");
+
+ try:
+ session.queue_query(queue="q3")
+ except qpid.session.SessionException, e:
+ if (530 == e.args[0].error_code):
+ self.fail("ACL should allow queue query request for q3");
+
+ try:
+ session.queue_delete(queue="q3")
+ self.fail("ACL should deny queue delete request for q3");
+ except qpid.session.SessionException, e:
+ self.assertEqual(530,e.args[0].error_code)
+ session = self.get_session('bob','bob')
+
+ try:
+ session.queue_delete(queue="q4")
+ except qpid.session.SessionException, e:
+ if (530 == e.args[0].error_code):
+ self.fail("ACL should allow queue delete request for q4");
+
#=====================================
# ACL exchange tests
#=====================================
- def test_exchange_acl(self):
+ def test_exchange_acl_allow_mode(self):
+ session = self.get_session('bob','bob')
+ session.queue_declare(queue="baz")
+
"""
- Test various modes for exchange acl
+ Test cases for exchange acl in allow mode
"""
aclf = ACLFile()
aclf.write('acl deny bob@QPID create exchange name=testEx durable=true passive=true\n')
aclf.write('acl deny bob@QPID create exchange name=ex1 type=direct\n')
- aclf.write('acl deny bob@QPID access exchange name=myEx\n')
+ aclf.write('acl deny bob@QPID access exchange name=myEx queuename=q1 routingkey=rk1.*\n')
aclf.write('acl deny bob@QPID bind exchange name=myEx queuename=q1 routingkey=rk1\n')
aclf.write('acl deny bob@QPID unbind exchange name=myEx queuename=q1 routingkey=rk1\n')
- aclf.write('acl deny bob@QPID delete exchange name=myEx\n')
+ aclf.write('acl deny bob@QPID delete exchange name=myEx\n')
aclf.write('acl allow all all')
aclf.close()
- self.reload_acl()
+ result = self.reload_acl()
+ if (result.text.find("format error",0,len(result.text)) != -1):
+ self.fail(result)
session = self.get_session('bob','bob')
-
+ session.queue_declare(queue='q1')
+ session.queue_declare(queue='q2')
+ session.exchange_declare(exchange='myEx', type='direct')
+
try:
- session.exchange_declare(exchange='testEx', durable='true', passive='true')
+ session.exchange_declare(exchange='testEx', durable=True, passive=True)
self.fail("ACL should deny exchange create request with name=testEx durable=true passive=true");
except qpid.session.SessionException, e:
self.assertEqual(530,e.args[0].error_code)
session = self.get_session('bob','bob')
try:
+ session.exchange_declare(exchange='testEx', type='direct', durable=True, passive=False)
+ except qpid.session.SessionException, e:
+ print e
+ if (530 == e.args[0].error_code):
+ self.fail("ACL should allow exchange create request for testEx with any parameter other than durable=true and passive=true");
+
+ try:
session.exchange_declare(exchange='ex1', type='direct')
self.fail("ACL should deny exchange create request with name=ex1 type=direct");
- except qpid.session.SessionException, e:
+ except qpid.session.SessionException, e:
self.assertEqual(530,e.args[0].error_code)
session = self.get_session('bob','bob')
try:
session.exchange_declare(exchange='myXml', type='direct')
- session.queue_declare(queue='q1')
except qpid.session.SessionException, e:
if (530 == e.args[0].error_code):
self.fail("ACL should allow exchange create request for myXml with any parameter");
try:
session.exchange_query(name='myEx')
- self.fail("ACL should deny queue query request for q3");
+ self.fail("ACL should deny exchange query request for myEx");
except qpid.session.SessionException, e:
self.assertEqual(530,e.args[0].error_code)
session = self.get_session('bob','bob')
+
+ try:
+ session.exchange_bound(exchange='myEx', queue='q1', binding_key='rk1.*')
+ self.fail("ACL should deny exchange bound request for myEx with queuename=q1 and routing_key='rk1.*' ");
+ except qpid.session.SessionException, e:
+ self.assertEqual(530,e.args[0].error_code)
+ session = self.get_session('bob','bob')
+
+ try:
+ session.exchange_query(name='amq.topic')
+ except qpid.session.SessionException, e:
+ if (530 == e.args[0].error_code):
+ self.fail("ACL should allow exchange query request for exchange='amq.topic'");
try:
+ session.exchange_bound(exchange='myEx', queue='q1', binding_key='rk2.*')
+ except qpid.session.SessionException, e:
+ if (530 == e.args[0].error_code):
+ self.fail("ACL should allow exchange bound request for myEx with queuename=q1 and binding_key='rk2.*'");
+
+ try:
session.exchange_bind(exchange='myEx', queue='q1', binding_key='rk1')
self.fail("ACL should deny exchange bind request with exchange='myEx' queuename='q1' bindingkey='rk1'");
except qpid.session.SessionException, e:
@@ -337,10 +479,17 @@ class ACLTests(TestBase010):
session = self.get_session('bob','bob')
try:
- session.exchange_bind(exchange='myXml', queue='q1', binding_key='x')
+ session.exchange_bind(exchange='myEx', queue='q1', binding_key='x')
+ except qpid.session.SessionException, e:
+ if (530 == e.args[0].error_code):
+ self.fail("ACL should allow exchange bind request for exchange='myEx', queue='q1', binding_key='x'");
+
+ try:
+ session.exchange_bind(exchange='myEx', queue='q2', binding_key='rk1')
except qpid.session.SessionException, e:
if (530 == e.args[0].error_code):
- self.fail("ACL should allow exchange bind request for exchange='myXml', queue='q1', binding_key='x'");
+ self.fail("ACL should allow exchange bind request for exchange='myEx', queue='q2', binding_key='rk1'");
+
try:
session.exchange_unbind(exchange='myEx', queue='q1', binding_key='rk1')
self.fail("ACL should deny exchange unbind request with exchange='myEx' queuename='q1' bindingkey='rk1'");
@@ -349,10 +498,16 @@ class ACLTests(TestBase010):
session = self.get_session('bob','bob')
try:
- session.exchange_unbind(exchange='myXml', queue='q1', binding_key='x')
+ session.exchange_unbind(exchange='myEx', queue='q1', binding_key='x')
+ except qpid.session.SessionException, e:
+ if (530 == e.args[0].error_code):
+ self.fail("ACL should allow exchange unbind request for exchange='myEx', queue='q1', binding_key='x'");
+
+ try:
+ session.exchange_unbind(exchange='myEx', queue='q2', binding_key='rk1')
except qpid.session.SessionException, e:
if (530 == e.args[0].error_code):
- self.fail("ACL should allow exchange unbind request for exchange='myXml', queue='q1', binding_key='x'");
+ self.fail("ACL should allow exchange unbind request for exchange='myEx', queue='q2', binding_key='rk1'");
try:
session.exchange_delete(exchange='myEx')
@@ -366,45 +521,161 @@ class ACLTests(TestBase010):
except qpid.session.SessionException, e:
if (530 == e.args[0].error_code):
self.fail("ACL should allow exchange delete request for myXml");
-
+
+
+ def test_exchange_acl_deny_mode(self):
+ session = self.get_session('bob','bob')
+ session.queue_declare(queue='bar')
+
+ """
+ Test cases for exchange acl in deny mode
+ """
+ aclf = ACLFile()
+ aclf.write('acl allow bob@QPID create exchange name=myEx durable=true passive=false\n')
+ aclf.write('acl allow bob@QPID bind exchange name=amq.topic queuename=bar routingkey=foo.*\n')
+ aclf.write('acl allow bob@QPID unbind exchange name=amq.topic queuename=bar routingkey=foo.*\n')
+ aclf.write('acl allow bob@QPID access exchange name=myEx queuename=q1 routingkey=rk1.*\n')
+ aclf.write('acl allow bob@QPID delete exchange name=myEx\n')
+ aclf.write('acl allow guest@QPID all all\n')
+ aclf.write('acl deny all all')
+ aclf.close()
+
+ result = self.reload_acl()
+ if (result.text.find("format error",0,len(result.text)) != -1):
+ self.fail(result)
+
+ session = self.get_session('bob','bob')
+
+ try:
+ session.exchange_declare(exchange='myEx', type='direct', durable=True, passive=False)
+ except qpid.session.SessionException, e:
+ if (530 == e.args[0].error_code):
+ self.fail("ACL should allow exchange create request for myEx with durable=true and passive=false");
+ try:
+ session.exchange_declare(exchange='myEx', type='direct', durable=False)
+ self.fail("ACL should deny exchange create request with name=myEx durable=false");
+ except qpid.session.SessionException, e:
+ self.assertEqual(530,e.args[0].error_code)
+ session = self.get_session('bob','bob')
+
+ try:
+ session.exchange_bind(exchange='amq.topic', queue='bar', binding_key='foo.bar')
+ except qpid.session.SessionException, e:
+ if (530 == e.args[0].error_code):
+ self.fail("ACL should allow exchange bind request for exchange='amq.topic', queue='bar', binding_key='foor.bar'");
+
+ try:
+ session.exchange_bind(exchange='amq.topic', queue='baz', binding_key='foo.bar')
+ self.fail("ACL should deny exchange bind request for exchange='amq.topic', queue='baz', binding_key='foo.bar'");
+ except qpid.session.SessionException, e:
+ self.assertEqual(530,e.args[0].error_code)
+ session = self.get_session('bob','bob')
+
+ try:
+ session.exchange_bind(exchange='amq.topic', queue='bar', binding_key='fooz.bar')
+ self.fail("ACL should deny exchange bind request for exchange='amq.topic', queue='bar', binding_key='fooz.bar'");
+ except qpid.session.SessionException, e:
+ self.assertEqual(530,e.args[0].error_code)
+ session = self.get_session('bob','bob')
+
+ try:
+ session.exchange_unbind(exchange='amq.topic', queue='bar', binding_key='foo.bar')
+ except qpid.session.SessionException, e:
+ if (530 == e.args[0].error_code):
+ self.fail("ACL should allow exchange unbind request for exchange='amq.topic', queue='bar', binding_key='foor.bar'");
+ try:
+ session.exchange_unbind(exchange='amq.topic', queue='baz', binding_key='foo.bar')
+ self.fail("ACL should deny exchange unbind request for exchange='amq.topic', queue='baz', binding_key='foo.bar'");
+ except qpid.session.SessionException, e:
+ self.assertEqual(530,e.args[0].error_code)
+ session = self.get_session('bob','bob')
+
+ try:
+ session.exchange_unbind(exchange='amq.topic', queue='bar', binding_key='fooz.bar')
+ self.fail("ACL should deny exchange unbind request for exchange='amq.topic', queue='bar', binding_key='fooz.bar'");
+ except qpid.session.SessionException, e:
+ self.assertEqual(530,e.args[0].error_code)
+ session = self.get_session('bob','bob')
+
+ try:
+ session.exchange_query(name='amq.topic')
+ self.fail("ACL should deny exchange query request for amq.topic");
+ except qpid.session.SessionException, e:
+ self.assertEqual(530,e.args[0].error_code)
+ session = self.get_session('bob','bob')
+
+ try:
+ session.exchange_bound(exchange='myEx', queue='q1', binding_key='rk2.*')
+ self.fail("ACL should deny exchange bound request for amq.topic with queuename=q1 and routing_key='rk2.*' ");
+ except qpid.session.SessionException, e:
+ self.assertEqual(530,e.args[0].error_code)
+ session = self.get_session('bob','bob')
+
+ try:
+ session.exchange_query(name='myEx')
+ except qpid.session.SessionException, e:
+ if (530 == e.args[0].error_code):
+ self.fail("ACL should allow exchange query request for exchange='myEx'");
+
+ try:
+ session.exchange_bound(exchange='myEx', queue='q1', binding_key='rk1.*')
+ except qpid.session.SessionException, e:
+ if (530 == e.args[0].error_code):
+ self.fail("ACL should allow exchange bound request for myEx with queuename=q1 and binding_key='rk1.*'");
+
+ try:
+ session.exchange_delete(exchange='myXml')
+ self.fail("ACL should deny exchange delete request for myXml");
+ except qpid.session.SessionException, e:
+ self.assertEqual(530,e.args[0].error_code)
+ session = self.get_session('bob','bob')
+
+ try:
+ session.exchange_delete(exchange='myEx')
+ except qpid.session.SessionException, e:
+ if (530 == e.args[0].error_code):
+ self.fail("ACL should allow exchange delete request for myEx");
+
#=====================================
# ACL consume tests
#=====================================
- def test_consume_acl(self):
+ def test_consume_allow_mode(self):
"""
- Test various consume acl
+ Test cases for consume in allow mode
"""
aclf = ACLFile()
- aclf.write('acl deny bob@QPID consume queue name=q1 durable=true\n')
- aclf.write('acl deny bob@QPID consume queue name=q2 exclusive=true\n')
+ aclf.write('acl deny bob@QPID consume queue name=q1\n')
+ aclf.write('acl deny bob@QPID consume queue name=q2\n')
aclf.write('acl allow all all')
aclf.close()
- self.reload_acl()
+ result = self.reload_acl()
+ if (result.text.find("format error",0,len(result.text)) != -1):
+ self.fail(result)
session = self.get_session('bob','bob')
try:
- session.queue_declare(queue='q1', durable='true')
- session.queue_declare(queue='q2', exclusive='true')
- session.queue_declare(queue='q3', durable='true')
+ session.queue_declare(queue='q1')
+ session.queue_declare(queue='q2')
+ session.queue_declare(queue='q3')
except qpid.session.SessionException, e:
if (530 == e.args[0].error_code):
self.fail("ACL should allow create queue request");
try:
session.message_subscribe(queue='q1', destination='myq1')
- self.fail("ACL should deny message subscriber request for queue='q1'");
+ self.fail("ACL should deny subscription for queue='q1'");
except qpid.session.SessionException, e:
self.assertEqual(530,e.args[0].error_code)
session = self.get_session('bob','bob')
try:
session.message_subscribe(queue='q2', destination='myq1')
- self.fail("ACL should deny message subscriber request for queue='q2'");
+ self.fail("ACL should deny subscription for queue='q2'");
except qpid.session.SessionException, e:
self.assertEqual(530,e.args[0].error_code)
session = self.get_session('bob','bob')
@@ -413,9 +684,51 @@ class ACLTests(TestBase010):
session.message_subscribe(queue='q3', destination='myq1')
except qpid.session.SessionException, e:
if (530 == e.args[0].error_code):
- self.fail("ACL should allow create message subscribe");
+ self.fail("ACL should allow subscription for q3");
+ def test_consume_deny_mode(self):
+ """
+ Test cases for consume in allow mode
+ """
+ aclf = ACLFile()
+ aclf.write('acl allow bob@QPID consume queue name=q1\n')
+ aclf.write('acl allow bob@QPID consume queue name=q2\n')
+ aclf.write('acl allow bob@QPID create queue\n')
+ aclf.write('acl allow guest@QPID all\n')
+ aclf.write('acl deny all all')
+ aclf.close()
+
+ result = self.reload_acl()
+ if (result.text.find("format error",0,len(result.text)) != -1):
+ self.fail(result)
+
+ session = self.get_session('bob','bob')
+
+
+ try:
+ session.queue_declare(queue='q1')
+ session.queue_declare(queue='q2')
+ session.queue_declare(queue='q3')
+ except qpid.session.SessionException, e:
+ if (530 == e.args[0].error_code):
+ self.fail("ACL should allow create queue request");
+
+ try:
+ session.message_subscribe(queue='q1', destination='myq1')
+ session.message_subscribe(queue='q2', destination='myq2')
+ except qpid.session.SessionException, e:
+ if (530 == e.args[0].error_code):
+ self.fail("ACL should allow subscription for q1 and q2");
+
+ try:
+ session.message_subscribe(queue='q3', destination='myq3')
+ self.fail("ACL should deny subscription for queue='q3'");
+ except qpid.session.SessionException, e:
+ self.assertEqual(530,e.args[0].error_code)
+ session = self.get_session('bob','bob')
+
+
#=====================================
# ACL publish tests
#=====================================
@@ -431,15 +744,11 @@ class ACLTests(TestBase010):
aclf.write('acl allow all all')
aclf.close()
- self.reload_acl()
+ result = self.reload_acl()
+ if (result.text.find("format error",0,len(result.text)) != -1):
+ self.fail(result)
session = self.get_session('bob','bob')
-
- try:
- session.exchange_declare(exchange='myEx', type='topic')
- except qpid.session.SessionException, e:
- if (530 == e.args[0].error_code):
- self.fail("ACL should allow exchange create request for myEx with any parameter");
props = session.delivery_properties(routing_key="rk1")
@@ -458,6 +767,7 @@ class ACLTests(TestBase010):
session = self.get_session('bob','bob')
try:
+ session.exchange_declare(exchange='myEx', type='direct', durable=False)
session.message_transfer(destination="myEx", message=Message(props,"Test"))
except qpid.session.SessionException, e:
if (530 == e.args[0].error_code):
diff --git a/qpid/cpp/src/tests/client_test.cpp b/qpid/cpp/src/tests/client_test.cpp
index 05b42f620c..2f5e8e5afe 100644
--- a/qpid/cpp/src/tests/client_test.cpp
+++ b/qpid/cpp/src/tests/client_test.cpp
@@ -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
@@ -40,13 +40,16 @@ using namespace qpid::client;
using namespace qpid::framing;
using std::string;
+namespace qpid {
+namespace tests {
+
struct Args : public TestOptions {
uint msgSize;
bool verbose;
Args() : TestOptions("Simple test of Qpid c++ client; sends and receives a single message."), msgSize(26)
{
- addOptions()
+ addOptions()
("size", optValue(msgSize, "N"), "message size")
("verbose", optValue(verbose), "print out some status messages");
}
@@ -58,7 +61,7 @@ std::string generateData(uint size)
{
if (size < chars.length()) {
return chars.substr(0, size);
- }
+ }
std::string data;
for (uint i = 0; i < (size / chars.length()); i++) {
data += chars;
@@ -78,6 +81,10 @@ void print(const std::string& text, const Message& msg)
std::cout << std::endl;
}
+}} // namespace qpid::tests
+
+using namespace qpid::tests;
+
int main(int argc, char** argv)
{
try {
@@ -92,7 +99,7 @@ int main(int argc, char** argv)
//Create and open a session on the connection through which
//most functionality is exposed:
Session session = connection.newSession();
- if (opts.verbose) std::cout << "Opened session." << std::endl;
+ if (opts.verbose) std::cout << "Opened session." << std::endl;
//'declare' the exchange and the queue, which will create them
@@ -116,13 +123,13 @@ int main(int argc, char** argv)
// Using the SubscriptionManager, get the message from the queue.
SubscriptionManager subs(session);
Message msgIn = subs.get("MyQueue");
- if (msgIn.getData() == msgOut.getData())
+ if (msgIn.getData() == msgOut.getData())
if (opts.verbose) std::cout << "Received the exepected message." << std::endl;
//close the session & connection
session.close();
if (opts.verbose) std::cout << "Closed session." << std::endl;
- connection.close();
+ connection.close();
if (opts.verbose) std::cout << "Closed connection." << std::endl;
return 0;
} catch(const std::exception& e) {
diff --git a/qpid/cpp/src/tests/cluster_test.cpp b/qpid/cpp/src/tests/cluster_test.cpp
index 50ca241b5d..28fcdd13ad 100644
--- a/qpid/cpp/src/tests/cluster_test.cpp
+++ b/qpid/cpp/src/tests/cluster_test.cpp
@@ -59,8 +59,6 @@ template <class T>
ostream& operator<<(ostream& o, const std::set<T>& s) { return seqPrint(o, s); }
}
-QPID_AUTO_TEST_SUITE(cluster_test)
-
using namespace std;
using namespace qpid;
using namespace qpid::cluster;
@@ -70,6 +68,11 @@ using namespace boost::assign;
using broker::Broker;
using boost::shared_ptr;
+namespace qpid {
+namespace tests {
+
+QPID_AUTO_TEST_SUITE(cluster_test)
+
bool durableFlag = std::getenv("STORE_LIB") != 0;
void prepareArgs(ClusterFixture::Args& args, const bool durableFlag = false) {
@@ -1098,3 +1101,5 @@ QPID_AUTO_TEST_CASE(testRelease) {
}
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/consume.cpp b/qpid/cpp/src/tests/consume.cpp
index 3aacf8b3da..69110d151f 100644
--- a/qpid/cpp/src/tests/consume.cpp
+++ b/qpid/cpp/src/tests/consume.cpp
@@ -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
@@ -36,6 +36,9 @@ using namespace qpid::client;
using namespace qpid::sys;
using namespace std;
+namespace qpid {
+namespace tests {
+
typedef vector<string> StringSet;
struct Args : public qpid::TestOptions {
@@ -46,7 +49,7 @@ struct Args : public qpid::TestOptions {
bool summary;
bool print;
bool durable;
-
+
Args() : count(1000), ack(0), queue("publish-consume"),
declare(false), summary(false), print(false)
{
@@ -63,12 +66,12 @@ struct Args : public qpid::TestOptions {
Args opts;
-struct Client
+struct Client
{
Connection connection;
Session session;
- Client()
+ Client()
{
opts.open(connection);
session = connection.newSession();
@@ -85,7 +88,7 @@ struct Client
settings.flowControl = FlowControl(opts.count, SubscriptionManager::UNLIMITED,false);
Subscription sub = subs.subscribe(lq, opts.queue, settings);
Message msg;
- AbsTime begin=now();
+ AbsTime begin=now();
for (size_t i = 0; i < opts.count; ++i) {
msg=lq.pop();
QPID_LOG(info, "Received: " << msg.getMessageProperties().getCorrelationId());
@@ -99,7 +102,7 @@ struct Client
else cout << "Time: " << secs << "s Rate: " << opts.count/secs << endl;
}
- ~Client()
+ ~Client()
{
try{
session.close();
@@ -110,6 +113,10 @@ struct Client
}
};
+}} // namespace qpid::tests
+
+using namespace qpid::tests;
+
int main(int argc, char** argv)
{
try {
diff --git a/qpid/cpp/src/tests/datagen.cpp b/qpid/cpp/src/tests/datagen.cpp
index 175f14cc57..acbc07d63c 100644
--- a/qpid/cpp/src/tests/datagen.cpp
+++ b/qpid/cpp/src/tests/datagen.cpp
@@ -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
@@ -25,7 +25,10 @@
#include <time.h>
#include "qpid/Options.h"
-struct Args : public qpid::Options
+namespace qpid {
+namespace tests {
+
+struct Args : public qpid::Options
{
uint count;
uint minSize;
@@ -34,12 +37,12 @@ struct Args : public qpid::Options
uint maxChar;
bool help;
- Args() : qpid::Options("Random data generator"),
- count(1), minSize(8), maxSize(4096),
+ Args() : qpid::Options("Random data generator"),
+ count(1), minSize(8), maxSize(4096),
minChar(32), maxChar(126),//safely printable ascii chars
help(false)
{
- addOptions()
+ addOptions()
("count", qpid::optValue(count, "N"), "number of data strings to generate")
("min-size", qpid::optValue(minSize, "N"), "minimum size of data string")
("max-size", qpid::optValue(maxSize, "N"), "maximum size of data string")
@@ -81,6 +84,10 @@ std::string generateData(uint size, uint min, uint max)
return data;
}
+}} // namespace qpid::tests
+
+using namespace qpid::tests;
+
int main(int argc, char** argv)
{
Args opts;
diff --git a/qpid/cpp/src/tests/echotest.cpp b/qpid/cpp/src/tests/echotest.cpp
index 98590e35ff..ab26dcf3fd 100644
--- a/qpid/cpp/src/tests/echotest.cpp
+++ b/qpid/cpp/src/tests/echotest.cpp
@@ -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
@@ -33,6 +33,9 @@ using namespace qpid::framing;
using namespace qpid::sys;
using namespace std;
+namespace qpid {
+namespace tests {
+
struct Args : public qpid::Options,
public qpid::client::ConnectionSettings
{
@@ -48,7 +51,7 @@ struct Args : public qpid::Options,
("help", optValue(help), "Print this usage statement")
("count", optValue(count, "N"), "Number of messages to send")
("size", optValue(count, "N"), "Size of messages")
- ("broker,b", optValue(host, "HOST"), "Broker host to connect to")
+ ("broker,b", optValue(host, "HOST"), "Broker host to connect to")
("port,p", optValue(port, "PORT"), "Broker port to connect to")
("username", optValue(username, "USER"), "user name for broker log in.")
("password", optValue(password, "PASSWORD"), "password for broker log in.")
@@ -75,7 +78,7 @@ class Listener : public MessageListener
Message request;
double total, min, max;
bool summary;
-
+
public:
Listener(Session& session, uint limit, bool summary);
void start(uint size);
@@ -92,7 +95,7 @@ void Listener::start(uint size)
{
session.queueDeclare(arg::queue=queue, arg::exclusive=true, arg::autoDelete=true);
request.getDeliveryProperties().setRoutingKey(queue);
- subscriptions.subscribe(*this, queue, SubscriptionSettings(FlowControl::unlimited(), ACCEPT_MODE_NONE));
+ subscriptions.subscribe(*this, queue, SubscriptionSettings(FlowControl::unlimited(), ACCEPT_MODE_NONE));
request.getDeliveryProperties().setTimestamp(current_time());
if (size) request.setData(std::string(size, 'X'));
@@ -100,7 +103,7 @@ void Listener::start(uint size)
subscriptions.run();
}
-void Listener::received(Message& response)
+void Listener::received(Message& response)
{
//extract timestamp and compute latency:
uint64_t sentAt = response.getDeliveryProperties().getTimestamp();
@@ -122,7 +125,11 @@ void Listener::received(Message& response)
}
}
-int main(int argc, char** argv)
+}} // namespace qpid::tests
+
+using namespace qpid::tests;
+
+int main(int argc, char** argv)
{
Args opts;
opts.parse(argc, argv);
diff --git a/qpid/cpp/src/tests/exception_test.cpp b/qpid/cpp/src/tests/exception_test.cpp
index 379e957ef1..0e9a948f00 100644
--- a/qpid/cpp/src/tests/exception_test.cpp
+++ b/qpid/cpp/src/tests/exception_test.cpp
@@ -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
@@ -28,6 +28,9 @@
#include "qpid/sys/Thread.h"
#include "qpid/framing/reply_exceptions.h"
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(exception_test)
// FIXME aconway 2008-06-12: need to update our exception handling to
@@ -49,12 +52,12 @@ struct Catcher : public Runnable {
function<void ()> f;
bool caught;
Thread thread;
-
+
Catcher(function<void ()> f_) : f(f_), caught(false), thread(this) {}
~Catcher() { join(); }
-
+
void run() {
- try {
+ try {
ScopedSuppressLogging sl; // Suppress messages for expected errors.
f();
}
@@ -110,7 +113,7 @@ QPID_AUTO_TEST_CASE(DisconnectedListen) {
Catcher<TransportFailure> runner(bind(&SubscriptionManager::run, boost::ref(fix.subs)));
fix.connection.proxy.close();
runner.join();
- BOOST_CHECK_THROW(fix.session.close(), TransportFailure);
+ BOOST_CHECK_THROW(fix.session.close(), TransportFailure);
}
QPID_AUTO_TEST_CASE(NoSuchQueueTest) {
@@ -120,3 +123,5 @@ QPID_AUTO_TEST_CASE(NoSuchQueueTest) {
}
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/failover_soak.cpp b/qpid/cpp/src/tests/failover_soak.cpp
index 08691912aa..39d72e258a 100644
--- a/qpid/cpp/src/tests/failover_soak.cpp
+++ b/qpid/cpp/src/tests/failover_soak.cpp
@@ -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
@@ -51,7 +51,8 @@ using namespace qpid::framing;
using namespace qpid::client;
-
+namespace qpid {
+namespace tests {
typedef vector<ForkedBroker *> brokerVector;
@@ -90,9 +91,9 @@ ostream& operator<< ( ostream& os, const childType& ct ) {
struct child
{
- child ( string & name, pid_t pid, childType type )
+ child ( string & name, pid_t pid, childType type )
: name(name), pid(pid), retval(-999), status(RUNNING), type(type)
- {
+ {
gettimeofday ( & startTime, 0 );
}
@@ -107,7 +108,7 @@ struct child
void
- setType ( childType t )
+ setType ( childType t )
{
type = t;
}
@@ -126,7 +127,7 @@ struct child
struct children : public vector<child *>
-{
+{
void
add ( string & name, pid_t pid, childType type )
@@ -135,7 +136,7 @@ struct children : public vector<child *>
}
- child *
+ child *
get ( pid_t pid )
{
vector<child *>::iterator i;
@@ -155,7 +156,7 @@ struct children : public vector<child *>
{
if ( verbosity > 1 )
{
- cerr << "children::exited warning: Can't find child with pid "
+ cerr << "children::exited warning: Can't find child with pid "
<< pid
<< endl;
}
@@ -192,7 +193,7 @@ struct children : public vector<child *>
<< endl;
return (*i)->retval;
}
-
+
return 0;
}
@@ -226,11 +227,11 @@ struct children : public vector<child *>
children allMyChildren;
-void
-childExit ( int )
+void
+childExit ( int )
{
- int childReturnCode;
- pid_t pid = waitpid ( 0, & childReturnCode, WNOHANG);
+ int childReturnCode;
+ pid_t pid = waitpid ( 0, & childReturnCode, WNOHANG);
if ( pid > 0 )
allMyChildren.exited ( pid, childReturnCode );
@@ -270,10 +271,10 @@ printBrokers ( brokerVector & brokers )
{
cout << "Broker List ------------ size: " << brokers.size() << "\n";
for ( brokerVector::iterator i = brokers.begin(); i != brokers.end(); ++ i) {
- cout << "pid: "
- << (*i)->getPID()
- << " port: "
- << (*i)->getPort()
+ cout << "pid: "
+ << (*i)->getPID()
+ << " port: "
+ << (*i)->getPort()
<< endl;
}
cout << "end Broker List ------------\n";
@@ -293,7 +294,7 @@ wait_for_newbie ( )
if ( ! newbie )
return true;
- try
+ try
{
Connection connection;
connection.open ( "127.0.0.1", newbie_port );
@@ -303,8 +304,8 @@ wait_for_newbie ( )
}
catch ( const std::exception& error )
{
- std::cerr << "wait_for_newbie error: "
- << error.what()
+ std::cerr << "wait_for_newbie error: "
+ << error.what()
<< endl;
return false;
}
@@ -320,7 +321,7 @@ startNewBroker ( brokerVector & brokers,
char const * moduleOrDir,
string const clusterName,
int verbosity,
- int durable )
+ int durable )
{
static int brokerId = 0;
stringstream path, prefix;
@@ -353,8 +354,8 @@ startNewBroker ( brokerVector & brokers,
ForkedBroker * broker = newbie;
if ( verbosity > 0 )
- std::cerr << "new broker created: pid == "
- << broker->getPID()
+ std::cerr << "new broker created: pid == "
+ << broker->getPID()
<< " log-prefix == "
<< "soak-" << brokerId
<< endl;
@@ -381,8 +382,8 @@ killFrontBroker ( brokerVector & brokers, int verbosity )
catch ( const exception& error ) {
if ( verbosity > 0 )
{
- cout << "error killing broker: "
- << error.what()
+ cout << "error killing broker: "
+ << error.what()
<< endl;
}
@@ -398,14 +399,14 @@ killFrontBroker ( brokerVector & brokers, int verbosity )
/*
- * The optional delay is to avoid killing newbie brokers that have just
+ * The optional delay is to avoid killing newbie brokers that have just
* been added and are still in the process of updating. This causes
* spurious, test-generated errors that scare everybody.
*/
void
killAllBrokers ( brokerVector & brokers, int delay )
{
- if ( delay > 0 )
+ if ( delay > 0 )
{
std::cerr << "Killing all brokers after delay of " << delay << endl;
sleep ( delay );
@@ -413,8 +414,8 @@ killAllBrokers ( brokerVector & brokers, int delay )
for ( uint i = 0; i < brokers.size(); ++ i )
try { brokers[i]->kill(9); }
- catch ( const exception& error )
- {
+ catch ( const exception& error )
+ {
std::cerr << "killAllBrokers Warning: exception during kill on broker "
<< i
<< " "
@@ -428,21 +429,21 @@ killAllBrokers ( brokerVector & brokers, int delay )
pid_t
-runDeclareQueuesClient ( brokerVector brokers,
+runDeclareQueuesClient ( brokerVector brokers,
char const * host,
char const * path,
int verbosity,
int durable
- )
+ )
{
string name("declareQueues");
int port = brokers[0]->getPort ( );
if ( verbosity > 1 )
- cout << "startDeclareQueuesClient: host: "
- << host
- << " port: "
- << port
+ cout << "startDeclareQueuesClient: host: "
+ << host
+ << " port: "
+ << port
<< endl;
stringstream portSs;
portSs << port;
@@ -473,12 +474,12 @@ runDeclareQueuesClient ( brokerVector brokers,
pid_t
-startReceivingClient ( brokerVector brokers,
+startReceivingClient ( brokerVector brokers,
char const * host,
char const * receiverPath,
char const * reportFrequency,
int verbosity
- )
+ )
{
string name("receiver");
int port = brokers[0]->getPort ( );
@@ -520,14 +521,14 @@ startReceivingClient ( brokerVector brokers,
pid_t
-startSendingClient ( brokerVector brokers,
+startSendingClient ( brokerVector brokers,
char const * host,
char const * senderPath,
char const * nMessages,
char const * reportFrequency,
int verbosity,
int durability
- )
+ )
{
string name("sender");
int port = brokers[0]->getPort ( );
@@ -580,13 +581,14 @@ startSendingClient ( brokerVector brokers,
#define HANGING 7
#define ERROR_KILLING_BROKER 8
+}} // namespace qpid::tests
-// If you want durability, use the "dir" option of "moduleOrDir" .
-
+using namespace qpid::tests;
+// If you want durability, use the "dir" option of "moduleOrDir" .
int
-main ( int argc, char const ** argv )
-{
+main ( int argc, char const ** argv )
+{
if ( argc != 9 ) {
cerr << "Usage: "
<< argv[0]
@@ -626,10 +628,10 @@ main ( int argc, char const ** argv )
int nBrokers = 3;
for ( int i = 0; i < nBrokers; ++ i ) {
startNewBroker ( brokers,
- moduleOrDir,
+ moduleOrDir,
clusterName,
verbosity,
- durable );
+ durable );
}
@@ -638,7 +640,7 @@ main ( int argc, char const ** argv )
// Run the declareQueues child.
int childStatus;
- pid_t dqClientPid =
+ pid_t dqClientPid =
runDeclareQueuesClient ( brokers, host, declareQueuesPath, verbosity, durable );
if ( -1 == dqClientPid ) {
cerr << "END_OF_TEST ERROR_START_DECLARE_1\n";
@@ -657,8 +659,8 @@ main ( int argc, char const ** argv )
// Start the receiving client.
pid_t receivingClientPid =
- startReceivingClient ( brokers,
- host,
+ startReceivingClient ( brokers,
+ host,
receiverPath,
reportFrequency,
verbosity );
@@ -669,10 +671,10 @@ main ( int argc, char const ** argv )
// Start the sending client.
- pid_t sendingClientPid =
- startSendingClient ( brokers,
- host,
- senderPath,
+ pid_t sendingClientPid =
+ startSendingClient ( brokers,
+ host,
+ senderPath,
nMessages,
reportFrequency,
verbosity,
@@ -687,10 +689,10 @@ main ( int argc, char const ** argv )
maxSleep = 4;
- for ( int totalBrokers = 3;
- totalBrokers < maxBrokers;
- ++ totalBrokers
- )
+ for ( int totalBrokers = 3;
+ totalBrokers < maxBrokers;
+ ++ totalBrokers
+ )
{
if ( verbosity > 0 )
cout << totalBrokers << " brokers have been added to the cluster.\n\n\n";
@@ -721,14 +723,14 @@ main ( int argc, char const ** argv )
cout << "Starting new broker.\n\n";
startNewBroker ( brokers,
- moduleOrDir,
+ moduleOrDir,
clusterName,
verbosity,
- durable );
-
+ durable );
+
if ( verbosity > 1 )
printBrokers ( brokers );
-
+
// If all children have exited, quit.
int unfinished = allMyChildren.unfinished();
if ( ! unfinished ) {
diff --git a/qpid/cpp/src/tests/latencytest.cpp b/qpid/cpp/src/tests/latencytest.cpp
index e1c47eab05..a205ef6c7c 100644
--- a/qpid/cpp/src/tests/latencytest.cpp
+++ b/qpid/cpp/src/tests/latencytest.cpp
@@ -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
@@ -40,6 +40,9 @@ using namespace qpid::client;
using namespace qpid::sys;
using std::string;
+namespace qpid {
+namespace tests {
+
typedef std::vector<std::string> StringSet;
struct Args : public qpid::TestOptions {
@@ -64,7 +67,7 @@ struct Args : public qpid::TestOptions {
durable(false), base("latency-test"), singleConnect(false)
{
- addOptions()
+ addOptions()
("size", optValue(size, "N"), "message size")
("concurrentTests", optValue(concurrentConnections, "N"), "number of concurrent test setups, will create another publisher,\
@@ -73,9 +76,9 @@ struct Args : public qpid::TestOptions {
("count", optValue(count, "N"), "number of messages to send")
("rate", optValue(rate, "N"), "target message rate (causes count to be ignored)")
("sync", optValue(sync), "send messages synchronously")
- ("report-frequency", optValue(reportFrequency, "N"),
+ ("report-frequency", optValue(reportFrequency, "N"),
"number of milliseconds to wait between reports (ignored unless rate specified)")
- ("time-limit", optValue(timeLimit, "N"),
+ ("time-limit", optValue(timeLimit, "N"),
"test duration, in seconds")
("prefetch", optValue(prefetch, "N"), "prefetch count (0 implies no flow control, and no acking)")
("ack", optValue(ack, "N"), "Ack frequency in messages (defaults to half the prefetch value)")
@@ -98,7 +101,7 @@ uint64_t current_time()
return t;
}
-struct Stats
+struct Stats
{
Mutex lock;
uint count;
@@ -132,7 +135,7 @@ public:
};
class Receiver : public Client, public MessageListener
-{
+{
SubscriptionManager mgr;
uint count;
Stats& stats;
@@ -168,7 +171,7 @@ class Test
Receiver receiver;
Sender sender;
AbsTime begin;
-
+
public:
Test(const string& q) : queue(q), receiver(queue, stats), sender(queue, receiver), begin(now()) {}
void start();
@@ -186,7 +189,7 @@ Client::Client(const string& q) : queue(q)
connection = &localConnection;
opts.open(localConnection);
}
- session = connection->newSession();
+ session = connection->newSession();
}
void Client::start()
@@ -235,7 +238,7 @@ Receiver::Receiver(const string& q, Stats& s) : Client(q), mgr(session), count(0
settings.acceptMode = ACCEPT_MODE_NONE;
settings.flowControl = FlowControl::unlimited();
}
- mgr.subscribe(*this, queue, settings);
+ mgr.subscribe(*this, queue, settings);
}
void Receiver::test()
@@ -283,7 +286,7 @@ void Stats::print()
if (!opts.csv) {
if (count) {
std::cout << "Latency(ms): min=" << minLatency << ", max=" <<
- maxLatency << ", avg=" << aux_avg;
+ maxLatency << ", avg=" << aux_avg;
} else {
std::cout << "Stalled: no samples for interval";
}
@@ -368,7 +371,7 @@ void Sender::sendByRate()
Duration delay(sentAt, waitTill);
if (delay < 0)
++missedRate;
- else
+ else
sys::usleep(delay / TIME_USEC);
if (timeLimit != 0 && Duration(start, now()) > timeLimit) {
session.sync();
@@ -382,7 +385,7 @@ string Sender::generateData(uint size)
{
if (size < chars.length()) {
return chars.substr(0, size);
- }
+ }
std::string data;
for (uint i = 0; i < (size / chars.length()); i++) {
data += chars;
@@ -392,35 +395,39 @@ string Sender::generateData(uint size)
}
-void Test::start()
-{
- receiver.start();
+void Test::start()
+{
+ receiver.start();
begin = AbsTime(now());
- sender.start();
+ sender.start();
}
-void Test::join()
-{
- sender.join();
- receiver.join();
+void Test::join()
+{
+ sender.join();
+ receiver.join();
AbsTime end = now();
Duration time(begin, end);
double msecs(time / TIME_MSEC);
if (!opts.csv) {
- std::cout << "Sent " << receiver.getCount() << " msgs through " << queue
+ std::cout << "Sent " << receiver.getCount() << " msgs through " << queue
<< " in " << msecs << "ms (" << (receiver.getCount() * 1000 / msecs) << " msgs/s) ";
}
stats.print();
std::cout << std::endl;
}
-void Test::report()
-{
+void Test::report()
+{
stats.print();
std::cout << std::endl;
stats.reset();
}
+}} // namespace qpid::tests
+
+using namespace qpid::tests;
+
int main(int argc, char** argv)
{
try {
diff --git a/qpid/cpp/src/tests/logging.cpp b/qpid/cpp/src/tests/logging.cpp
index 00e1d7de85..5cb563c7d3 100644
--- a/qpid/cpp/src/tests/logging.cpp
+++ b/qpid/cpp/src/tests/logging.cpp
@@ -37,6 +37,9 @@
#include <time.h>
+namespace qpid {
+namespace tests {
+
QPID_AUTO_TEST_SUITE(loggingTestSuite)
using namespace std;
@@ -106,7 +109,7 @@ struct TestOutput : public Logger::Output {
TestOutput(Logger& l) {
l.output(std::auto_ptr<Logger::Output>(this));
}
-
+
void log(const Statement& s, const string& m) {
msg.push_back(m);
stmt.push_back(s);
@@ -117,7 +120,7 @@ struct TestOutput : public Logger::Output {
using boost::assign::list_of;
QPID_AUTO_TEST_CASE(testLoggerOutput) {
- Logger l;
+ Logger l;
l.clear();
l.select(Selector(debug));
Statement s=QPID_LOG_STATEMENT_INIT(debug);
@@ -174,7 +177,7 @@ QPID_AUTO_TEST_CASE(testLoggerFormat) {
l.format(Logger::FUNCTION);
QPID_LOG(critical, "foo");
BOOST_CHECK_EQUAL(string(BOOST_CURRENT_FUNCTION) + ": foo\n", out->last());
-
+
l.format(Logger::LEVEL);
QPID_LOG(critical, "foo");
BOOST_CHECK_EQUAL("critical foo\n", out->last());
@@ -228,12 +231,12 @@ clock_t timeLoop(int times, int (*fp)()) {
// Overhead test disabled because it consumes a ton of CPU and takes
// forever under valgrind. Not friendly for regular test runs.
-//
+//
#if 0
QPID_AUTO_TEST_CASE(testOverhead) {
// Ensure that the ratio of CPU time for an incrementing loop
// with and without disabled log statements is in acceptable limits.
- //
+ //
int times=100000000;
clock_t noLog=timeLoop(times, count);
clock_t withLog=timeLoop(times, loggedCount);
@@ -242,9 +245,9 @@ QPID_AUTO_TEST_CASE(testOverhead) {
// NB: in initial tests the ratio was consistently below 1.5,
// 2.5 is reasonable and should avoid spurios failures
// due to machine load.
- //
- BOOST_CHECK_SMALL(ratio, 2.5);
-}
+ //
+ BOOST_CHECK_SMALL(ratio, 2.5);
+}
#endif // 0
Statement statement(
@@ -290,7 +293,7 @@ QPID_AUTO_TEST_CASE(testOptionsParse) {
}
QPID_AUTO_TEST_CASE(testOptionsDefault) {
- Options opts("");
+ qpid::log::Options opts("");
#ifdef _WIN32
qpid::log::windows::SinkOptions sinks("test");
#else
@@ -328,10 +331,10 @@ QPID_AUTO_TEST_CASE(testSelectorFromOptions) {
QPID_AUTO_TEST_CASE(testLoggerStateure) {
Logger& l=Logger::instance();
ScopedSuppressLogging ls(l);
- Options opts("test");
+ qpid::log::Options opts("test");
const char* argv[]={
0,
- "--log-time", "no",
+ "--log-time", "no",
"--log-source", "yes",
"--log-to-stderr", "no",
"--log-to-file", "logging.tmp",
@@ -352,7 +355,7 @@ QPID_AUTO_TEST_CASE(testLoggerStateure) {
QPID_AUTO_TEST_CASE(testQuoteNonPrintable) {
Logger& l=Logger::instance();
ScopedSuppressLogging ls(l);
- Options opts("test");
+ qpid::log::Options opts("test");
opts.time=false;
#ifdef _WIN32
qpid::log::windows::SinkOptions *sinks =
@@ -367,7 +370,7 @@ QPID_AUTO_TEST_CASE(testQuoteNonPrintable) {
char s[] = "null\0tab\tspace newline\nret\r\x80\x99\xff";
string str(s, sizeof(s));
- QPID_LOG(critical, str);
+ QPID_LOG(critical, str);
ifstream log("logging.tmp");
string line;
getline(log, line, '\0');
@@ -378,3 +381,5 @@ QPID_AUTO_TEST_CASE(testQuoteNonPrintable) {
}
QPID_AUTO_TEST_SUITE_END()
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/perftest.cpp b/qpid/cpp/src/tests/perftest.cpp
index d383e0eb80..88d9fd15cb 100644
--- a/qpid/cpp/src/tests/perftest.cpp
+++ b/qpid/cpp/src/tests/perftest.cpp
@@ -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
@@ -49,6 +49,9 @@ using namespace sys;
using boost::lexical_cast;
using boost::bind;
+namespace qpid {
+namespace tests {
+
enum Mode { SHARED, FANOUT, TOPIC };
const char* modeNames[] = { "shared", "fanout", "topic" };
@@ -105,9 +108,9 @@ struct Opts : public TestOptions {
bool commitAsync;
static const std::string helpText;
-
+
Opts() :
- TestOptions(helpText),
+ TestOptions(helpText),
setup(false), control(false), publish(false), subscribe(false), baseName("perftest"),
pubs(1), count(500000), size(1024), confirm(true), durable(false), uniqueData(false), syncPub(false),
subs(1), ack(0),
@@ -136,16 +139,16 @@ struct Opts : public TestOptions {
("nsubs", optValue(subs, "N"), "Create N subscribers.")
("sub-ack", optValue(ack, "N"), "N>0: Subscriber acks batches of N.\n"
"N==0: Subscriber uses unconfirmed mode")
-
+
("qt", optValue(qt, "N"), "Create N queues or topics.")
("single-connection", optValue(singleConnect, "yes|no"), "Use one connection for multiple sessions.")
-
+
("iterations", optValue(iterations, "N"), "Desired number of iterations of the test.")
("summary,s", optValue(summary), "Summary output: pubs/sec subs/sec transfers/sec Mbytes/sec")
("queue-max-count", optValue(queueMaxCount, "N"), "queue policy: count to trigger 'flow to disk'")
("queue-max-size", optValue(queueMaxSize, "N"), "queue policy: accumulated size to trigger 'flow to disk'")
- ("base-name", optValue(baseName, "NAME"), "base name used for queues or topics")
+ ("base-name", optValue(baseName, "NAME"), "base name used for queues or topics")
("queue-durable", optValue(queueDurable, "N"), "Make queue durable (implied if durable set)")
("interval_sub", optValue(intervalSub, "ms"), ">=0 delay between msg consume")
@@ -171,7 +174,7 @@ struct Opts : public TestOptions {
count += subs - (count % subs);
cout << "WARNING: Adjusted --count to " << count
<< " the nearest multiple of --nsubs" << endl;
- }
+ }
totalPubs = pubs*qt;
totalSubs = subs*qt;
subQuota = (pubs*count)/subs;
@@ -258,7 +261,7 @@ struct Client : public Runnable {
};
struct Setup : public Client {
-
+
void queueInit(string name, bool durable=false, const framing::FieldTable& settings=framing::FieldTable()) {
session.queueDeclare(arg::queue=name, arg::durable=durable, arg::arguments=settings);
session.queuePurge(arg::queue=name);
@@ -278,7 +281,7 @@ struct Setup : public Client {
for (size_t i = 0; i < opts.qt; ++i) {
ostringstream qname;
qname << opts.baseName << i;
- queueInit(qname.str(), opts.durable || opts.queueDurable, settings);
+ queueInit(qname.str(), opts.durable || opts.queueDurable, settings);
}
}
}
@@ -303,7 +306,7 @@ class Stats {
public:
Stats() : sum(0) {}
-
+
// Functor to collect rates.
void operator()(const string& data) {
try {
@@ -314,7 +317,7 @@ class Stats {
throw Exception("Bad report: "+data);
}
}
-
+
double mean() const {
return sum/values.size();
}
@@ -331,7 +334,7 @@ class Stats {
}
return sqrt(ssq/(values.size()-1));
}
-
+
ostream& print(ostream& out) {
ostream_iterator<double> o(out, "\n");
copy(values.begin(), values.end(), o);
@@ -341,11 +344,11 @@ class Stats {
return out << endl;
}
};
-
+
// Manage control queues, collect and print reports.
struct Controller : public Client {
-
+
SubscriptionManager subs;
Controller() : subs(session) {}
@@ -354,7 +357,7 @@ struct Controller : public Client {
void process(size_t n, string queue,
boost::function<void (const string&)> msgFn)
{
- if (!opts.summary)
+ if (!opts.summary)
cout << "Processing " << n << " messages from "
<< queue << " " << flush;
LocalQueue lq;
@@ -370,8 +373,8 @@ struct Controller : public Client {
void process(size_t n, LocalQueue lq, string queue,
boost::function<void (const string&)> msgFn)
{
- session.messageFlow(queue, 0, n);
- if (!opts.summary)
+ session.messageFlow(queue, 0, n);
+ if (!opts.summary)
cout << "Processing " << n << " messages from "
<< queue << " " << flush;
for (size_t i = 0; i < n; ++i) {
@@ -386,7 +389,7 @@ struct Controller : public Client {
cout << "Sending " << data << " " << n << " times to " << queue
<< endl;
Message msg(data, queue);
- for (size_t i = 0; i < n; ++i)
+ for (size_t i = 0; i < n; ++i)
session.messageTransfer(arg::content=msg, arg::acceptMode=1);
}
@@ -419,7 +422,7 @@ struct Controller : public Client {
process(opts.totalPubs, pubDone, fqn("pub_done"), boost::ref(pubRates));
process(opts.totalSubs, subDone, fqn("sub_done"), boost::ref(subRates));
- AbsTime end=now();
+ AbsTime end=now();
double time=secs(start, end);
double txrate=opts.transfers/time;
@@ -469,12 +472,12 @@ struct PublishThread : public Client {
string routingKey;
PublishThread() {};
-
+
PublishThread(string key, string dest=string()) {
destination=dest;
routingKey=key;
}
-
+
void run() { // Publisher
try {
string data;
@@ -492,7 +495,7 @@ struct PublishThread : public Client {
}
} else {
size_t msgSize=max(opts.size, sizeof(size_t));
- data = string(msgSize, 'X');
+ data = string(msgSize, 'X');
}
Message msg(data, routingKey);
@@ -500,21 +503,21 @@ struct PublishThread : public Client {
msg.getDeliveryProperties().setDeliveryMode(framing::PERSISTENT);
- if (opts.txPub){
+ if (opts.txPub){
session.txSelect();
}
SubscriptionManager subs(session);
LocalQueue lq;
- subs.setFlowControl(1, SubscriptionManager::UNLIMITED, true);
- subs.subscribe(lq, fqn("pub_start"));
-
+ subs.setFlowControl(1, SubscriptionManager::UNLIMITED, true);
+ subs.subscribe(lq, fqn("pub_start"));
+
for (size_t j = 0; j < opts.iterations; ++j) {
expect(lq.pop().getData(), "start");
AbsTime start=now();
for (size_t i=0; i<opts.count; i++) {
// Stamp the iteration into the message data, avoid
// any heap allocation.
- const_cast<std::string&>(msg.getData()).replace(offset, sizeof(size_t),
+ const_cast<std::string&>(msg.getData()).replace(offset, sizeof(size_t),
reinterpret_cast<const char*>(&i), sizeof(size_t));
if (opts.syncPub) {
sync(session).messageTransfer(
@@ -540,7 +543,7 @@ struct PublishThread : public Client {
if (opts.confirm) session.sync();
AbsTime end=now();
double time=secs(start,end);
-
+
// Send result to controller.
Message report(lexical_cast<string>(opts.count/time), fqn("pub_done"));
session.messageTransfer(arg::content=report, arg::acceptMode=1);
@@ -561,7 +564,7 @@ struct SubscribeThread : public Client {
string queue;
SubscribeThread() {}
-
+
SubscribeThread(string q) { queue = q; }
SubscribeThread(string key, string ex) {
@@ -586,7 +589,7 @@ struct SubscribeThread : public Client {
}
void run() { // Subscribe
- try {
+ try {
if (opts.txSub) sync(session).txSelect();
SubscriptionManager subs(session);
SubscriptionSettings settings;
@@ -606,15 +609,15 @@ struct SubscribeThread : public Client {
if (opts.iterations > 1) {
subs.subscribe(iterationControl, fqn("sub_iteration"), SubscriptionSettings(FlowControl::messageCredit(0)));
}
-
+
for (size_t j = 0; j < opts.iterations; ++j) {
if (j > 0) {
//need to wait here until all subs are done
- session.messageFlow(fqn("sub_iteration"), 0, 1);
+ session.messageFlow(fqn("sub_iteration"), 0, 1);
iterationControl.pop();
//need to allocate some more credit for subscription
- session.messageFlow(queue, 0, opts.subQuota);
+ session.messageFlow(queue, 0, opts.subQuota);
}
Message msg;
AbsTime start=now();
@@ -627,7 +630,7 @@ struct SubscribeThread : public Client {
}
if (opts.intervalSub)
qpid::sys::usleep(opts.intervalSub*1000);
- // TODO aconway 2007-11-23: check message order for.
+ // TODO aconway 2007-11-23: check message order for.
// multiple publishers. Need an array of counters,
// one per publisher and a publisher ID in the
// message. Careful not to introduce a lot of overhead
@@ -664,6 +667,10 @@ struct SubscribeThread : public Client {
}
};
+}} // namespace qpid::tests
+
+using namespace qpid::tests;
+
int main(int argc, char** argv) {
int exitCode = 0;
boost::ptr_vector<Client> subs(opts.subs);
diff --git a/qpid/cpp/src/tests/publish.cpp b/qpid/cpp/src/tests/publish.cpp
index 34c2b8fefc..3f456e7588 100644
--- a/qpid/cpp/src/tests/publish.cpp
+++ b/qpid/cpp/src/tests/publish.cpp
@@ -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
@@ -36,6 +36,9 @@ using namespace qpid::client;
using namespace qpid::sys;
using namespace std;
+namespace qpid {
+namespace tests {
+
typedef vector<string> StringSet;
struct Args : public qpid::TestOptions {
@@ -61,12 +64,12 @@ struct Args : public qpid::TestOptions {
Args opts;
-struct Client
+struct Client
{
Connection connection;
AsyncSession session;
- Client()
+ Client()
{
opts.open(connection);
session = connection.newSession();
@@ -75,7 +78,7 @@ struct Client
// Cheap hex calculation, avoid expensive ostrstream and string
// creation to generate correlation ids in message loop.
char hex(char i) { return i<10 ? '0'+i : 'A'+i-10; }
- void hex(char i, string& s) {
+ void hex(char i, string& s) {
s[0]=hex(i>>24); s[1]=hex(i>>16); s[2]=hex(i>>8); s[3]=i;
}
@@ -86,7 +89,7 @@ struct Client
string correlationId = "0000";
if (opts.durable)
msg.getDeliveryProperties().setDeliveryMode(framing::PERSISTENT);
-
+
for (uint i = 0; i < opts.count; i++) {
if (opts.id) {
hex(i+1, correlationId);
@@ -103,7 +106,7 @@ struct Client
else cout << "Time: " << secs << "s Rate: " << opts.count/secs << endl;
}
- ~Client()
+ ~Client()
{
try{
session.close();
@@ -114,6 +117,10 @@ struct Client
}
};
+}} // namespace qpid::tests
+
+using namespace qpid::tests;
+
int main(int argc, char** argv)
{
try {
diff --git a/qpid/cpp/src/tests/qpid_ping.cpp b/qpid/cpp/src/tests/qpid_ping.cpp
index cc07ade7bb..b046fdf54b 100644
--- a/qpid/cpp/src/tests/qpid_ping.cpp
+++ b/qpid/cpp/src/tests/qpid_ping.cpp
@@ -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
@@ -38,6 +38,9 @@ using namespace qpid::framing;
using namespace qpid::client;
using namespace qpid;
+namespace qpid {
+namespace tests {
+
struct PingOptions : public qpid::TestOptions {
int timeout; // Timeout in seconds.
bool quiet; // No output
@@ -58,7 +61,7 @@ class Ping : public Runnable {
public:
Ping() : status(WAITING) {}
-
+
void run() {
try {
opts.open(connection);
@@ -100,6 +103,9 @@ class Ping : public Runnable {
}
};
+}} // namespace qpid::tests
+
+using namespace qpid::tests;
int main(int argc, char** argv) {
try {
diff --git a/qpid/cpp/src/tests/qrsh.cpp b/qpid/cpp/src/tests/qrsh.cpp
index 2d71b600d5..0cb52b6b05 100644
--- a/qpid/cpp/src/tests/qrsh.cpp
+++ b/qpid/cpp/src/tests/qrsh.cpp
@@ -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
@@ -37,11 +37,13 @@ using namespace qpid::framing;
using namespace std;
+namespace qpid {
+namespace tests {
class ResponseListener : public MessageListener
{
public :
-
+
int exitCode;
ResponseListener ( SubscriptionManager & subscriptions )
@@ -50,7 +52,7 @@ class ResponseListener : public MessageListener
{
}
- virtual void
+ virtual void
received ( Message & message )
{
char first_word[1000];
@@ -66,9 +68,9 @@ class ResponseListener : public MessageListener
if ( ! strcmp ( first_word, "get_response" ) )
{
// The remainder of the message is the file we requested.
- fprintf ( stdout,
- "%s",
- message.getData().c_str() + strlen("get_response" )
+ fprintf ( stdout,
+ "%s",
+ message.getData().c_str() + strlen("get_response" )
);
subscriptions.cancel(message.getDestination());
}
@@ -76,12 +78,13 @@ class ResponseListener : public MessageListener
private :
-
+
SubscriptionManager & subscriptions;
};
+}} // namespace qpid::tests
-
+using namespace qpid::tests;
/*
* argv[1] host
@@ -90,8 +93,8 @@ class ResponseListener : public MessageListener
* argv[4] command name
* argv[5..N] args to the command
*/
-int
-main ( int argc, char ** argv )
+int
+main ( int argc, char ** argv )
{
const char* host = argv[1];
int port = atoi(argv[2]);
@@ -99,14 +102,14 @@ main ( int argc, char ** argv )
Connection connection;
- try
+ try
{
connection.open ( host, port );
Session session = connection.newSession ( );
// Make a queue and bind it to fanout.
string myQueue = session.getId().getName();
-
+
session.queueDeclare ( arg::queue=myQueue,
arg::exclusive=true,
arg::autoDelete=true
@@ -136,7 +139,7 @@ main ( int argc, char ** argv )
response_command = true;
// Send the payload message.
- // Skip "qrsh host_name port"
+ // Skip "qrsh host_name port"
Message message;
stringstream ss;
for ( int i = 3; i < argc; ++ i )
@@ -144,7 +147,7 @@ main ( int argc, char ** argv )
message.setData ( ss.str() );
- session.messageTransfer(arg::content=message,
+ session.messageTransfer(arg::content=message,
arg::destination="amq.fanout");
if ( response_command )
@@ -153,8 +156,8 @@ main ( int argc, char ** argv )
session.close();
connection.close();
return responseListener.exitCode;
- }
- catch ( exception const & e)
+ }
+ catch ( exception const & e)
{
cerr << e.what() << endl;
}
diff --git a/qpid/cpp/src/tests/qrsh_server.cpp b/qpid/cpp/src/tests/qrsh_server.cpp
index 4b80212eae..f1163ba479 100644
--- a/qpid/cpp/src/tests/qrsh_server.cpp
+++ b/qpid/cpp/src/tests/qrsh_server.cpp
@@ -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
@@ -43,7 +43,8 @@ using namespace qpid::framing;
using namespace std;
-
+namespace qpid {
+namespace tests {
int
mrand ( int max_desired_val )
@@ -54,7 +55,7 @@ mrand ( int max_desired_val )
-char *
+char *
file2str ( char const * file_name )
{
FILE * fp = fopen ( file_name, "r" );
@@ -71,9 +72,9 @@ file2str ( char const * file_name )
if ( ! content )
{
- fprintf ( stderr,
- "file2str error: can't malloc %d bytes.\n",
- (int)file_len
+ fprintf ( stderr,
+ "file2str error: can't malloc %d bytes.\n",
+ (int)file_len
);
return 0;
}
@@ -123,9 +124,9 @@ class QrshServer : public MessageListener
bool myMessage ( Message const & message );
/* ----------------------------------------------
- * Special Commands
+ * Special Commands
* These are commands that the qrsh_server executes
- * directly, rather than through a child process
+ * directly, rather than through a child process
* instance of qrsh_run.
*/
void runCommand ( Message const & message );
@@ -157,9 +158,9 @@ class QrshServer : public MessageListener
char const * skipWord ( char const * s );
- void string_replaceAll ( string & str,
- string & target,
- string & replacement
+ void string_replaceAll ( string & str,
+ string & target,
+ string & replacement
);
@@ -186,12 +187,12 @@ class QrshServer : public MessageListener
-QrshServer::QrshServer ( SubscriptionManager & subs,
+QrshServer::QrshServer ( SubscriptionManager & subs,
char const * name,
char const * qrsh_run_path,
char const * host,
int port
- )
+ )
: subscriptions ( subs ),
name ( name ),
qrsh_run_path ( qrsh_run_path ),
@@ -202,11 +203,11 @@ QrshServer::QrshServer ( SubscriptionManager & subs,
{
data_dir << "/tmp/qrsh_"
<< getpid();
-
+
if(mkdir ( data_dir.str().c_str(), 0777 ) )
{
- fprintf ( stderr,
- "QrshServer::QrshServer error: can't mkdir |%s|\n",
+ fprintf ( stderr,
+ "QrshServer::QrshServer error: can't mkdir |%s|\n",
data_dir.str().c_str()
);
exit ( 1 );
@@ -239,21 +240,21 @@ QrshServer::start ( )
<< name;
send ( announcement_data.str() );
-
+
saidHello = true;
}
-void
+void
QrshServer::send ( string const & content )
{
try
{
Message message;
message.setData ( content );
-
+
Connection connection;
connection.open ( host, port );
Session session = connection.newSession ( );
@@ -289,7 +290,7 @@ QrshServer::sayHello ( )
-void
+void
QrshServer::sayName ( )
{
fprintf ( stderr, "My name is: |%s|\n", name.c_str() );
@@ -343,7 +344,7 @@ QrshServer::getStraw ( Message const & message )
break;
}
}
-
+
if ( i_win && (ties <= 0) )
{
myStraw = 0;
@@ -364,10 +365,10 @@ QrshServer::getStraw ( Message const & message )
/*
* "APB" command (all-points-bullitens (commands that are not addressed
* specifically to any server)) are handled directly, here.
- * Because if I return simply "true", the normal command processing code
+ * Because if I return simply "true", the normal command processing code
* will misinterpret the command.
*/
-bool
+bool
QrshServer::myMessage ( Message const & message )
{
int const maxlen = 100;
@@ -414,7 +415,7 @@ QrshServer::myMessage ( Message const & message )
{
return true;
}
- else
+ else
if ( ! strcmp ( first_word, "any" ) )
{
straws.clear();
@@ -443,7 +444,7 @@ QrshServer::rememberIntroduction ( Message const & message )
-void
+void
QrshServer::addAlias ( Message const & message )
{
char alias[1000];
@@ -463,8 +464,8 @@ QrshServer::getNames ( )
if ( ! dir )
{
- fprintf ( stderr,
- "QrshServer::getNames error: could not open dir |%s|.\n",
+ fprintf ( stderr,
+ "QrshServer::getNames error: could not open dir |%s|.\n",
data_dir.str().c_str()
);
return;
@@ -491,8 +492,8 @@ QrshServer::getNames ( )
}
else
{
- /*
- * Fail silently. The non-existence of this file
+ /*
+ * Fail silently. The non-existence of this file
* is not necessarily an error.
*/
}
@@ -504,9 +505,9 @@ QrshServer::getNames ( )
void
-QrshServer::string_replaceAll ( string & str,
- string & target,
- string & replacement
+QrshServer::string_replaceAll ( string & str,
+ string & target,
+ string & replacement
)
{
int target_size = target.size();
@@ -519,7 +520,7 @@ QrshServer::string_replaceAll ( string & str,
-bool
+bool
QrshServer::isProcessName ( char const * str )
{
getNames();
@@ -537,12 +538,12 @@ QrshServer::isProcessName ( char const * str )
-int
+int
QrshServer::string_countWords ( char const * s1 )
{
int count = 0;
char const * s2 = s1 + 1;
-
+
if ( ! isspace(* s1) )
{
++ count;
@@ -603,7 +604,7 @@ QrshServer::get ( Message const & request_message )
*/
char file_or_process_name[1000];
sscanf ( request_message.getData().c_str(), "%*s%*s%s", file_or_process_name );
-
+
if ( isProcessName ( file_or_process_name ) )
{
stringstream desired_file_name;
@@ -612,13 +613,13 @@ QrshServer::get ( Message const & request_message )
<< file_or_process_name
<< '/';
char requested_output_stream[1000];
- if(1 != sscanf ( request_message.getData().c_str(),
- "%*s%*s%*s%s",
- requested_output_stream
+ if(1 != sscanf ( request_message.getData().c_str(),
+ "%*s%*s%*s%s",
+ requested_output_stream
)
)
{
- fprintf ( stderr,
+ fprintf ( stderr,
"QrshServer::get error: Can't read requested data file name from this message: |%s|\n",
request_message.getData().c_str()
);
@@ -674,7 +675,7 @@ QrshServer::exited ( Message const & message )
if ( truncated_command )
{
stringstream ss;
- ss << qrsh_run_path
+ ss << qrsh_run_path
<< ' '
<< data_dir.str()
<< ' '
@@ -706,9 +707,9 @@ QrshServer::exited ( Message const & message )
fprintf ( stderr, "qrsh_server error awaiting child!\n" );
exit ( 1 );
}
-
+
exit_code >>= 8;
-
+
stringstream data;
data << "wait_response "
<< exit_code;
@@ -731,7 +732,7 @@ QrshServer::wait ( Message const & message )
// The second word is "exec_wait".
// The third word is the symbolic name of the command to wait for.
// The fact that there are exactly three words means that this
- // must be a command that has already been named and started --
+ // must be a command that has already been named and started --
// we just need to find its pid and wait on it.
pre_existing = true;
}
@@ -762,7 +763,7 @@ QrshServer::wait ( Message const & message )
if ( truncated_command )
{
stringstream ss;
- ss << qrsh_run_path
+ ss << qrsh_run_path
<< ' '
<< data_dir.str()
<< ' '
@@ -795,7 +796,7 @@ QrshServer::wait ( Message const & message )
exit ( 1 );
}
}
-
+
exit_code >>= 8;
stringstream data;
@@ -810,7 +811,7 @@ QrshServer::wait ( Message const & message )
-char const *
+char const *
QrshServer::skipWord ( char const * s )
{
if(! (s && *s) )
@@ -884,7 +885,7 @@ QrshServer::getArgs ( char const * str )
arg_len = 0;
}
- done:
+ done:
if ( arg_len > 0 )
lengths.push_back ( arg_len );
@@ -896,8 +897,8 @@ QrshServer::getArgs ( char const * str )
for ( int i = 0; i < n_args; ++ i )
{
argv[i] = ( char *) malloc ( lengths[i] + 1 );
- strncpy ( argv[i],
- str + start_positions[i],
+ strncpy ( argv[i],
+ str + start_positions[i],
lengths[i]
);
argv[i][lengths[i]] = 0;
@@ -971,12 +972,12 @@ QrshServer::runCommand ( Message const & message )
* qrsh_run, which will save all its data in the qrsh dir.
*/
stringstream ss;
- ss << qrsh_run_path
+ ss << qrsh_run_path
<< ' '
<< data_dir.str()
<< ' '
<< s;
-
+
if ( ! fork() )
{
char ** argv = getArgs ( ss.str().c_str() );
@@ -988,8 +989,8 @@ QrshServer::runCommand ( Message const & message )
-void
-QrshServer::received ( Message & message )
+void
+QrshServer::received ( Message & message )
{
if ( myMessage ( message ) )
runCommand ( message );
@@ -997,7 +998,9 @@ QrshServer::received ( Message & message )
+}} // namespace qpid::tests
+using namespace qpid::tests;
/*
* fixme mick Mon Aug 3 10:29:26 EDT 2009
@@ -1024,23 +1027,23 @@ main ( int /*argc*/, char** argv )
// Declare queues.
string myQueue = session.getId().getName();
- session.queueDeclare ( arg::queue=myQueue,
+ session.queueDeclare ( arg::queue=myQueue,
arg::exclusive=true,
arg::autoDelete=true);
- session.exchangeBind ( arg::exchange="amq.fanout",
- arg::queue=myQueue,
+ session.exchangeBind ( arg::exchange="amq.fanout",
+ arg::queue=myQueue,
arg::bindingKey="my-key");
-
+
// Create a server and subscribe it to my queue.
SubscriptionManager subscriptions ( session );
- QrshServer server ( subscriptions,
+ QrshServer server ( subscriptions,
argv[1], // server name
argv[2], // qrsh exe path
host,
port
);
- subscriptions.subscribe ( server, myQueue );
+ subscriptions.subscribe ( server, myQueue );
// Receive messages until the subscription is cancelled
// by QrshServer::received()
@@ -1048,7 +1051,7 @@ main ( int /*argc*/, char** argv )
connection.close();
}
- catch(const exception& error)
+ catch(const exception& error)
{
cout << error.what() << endl;
return 1;
diff --git a/qpid/cpp/src/tests/receiver.cpp b/qpid/cpp/src/tests/receiver.cpp
index 49f7ff0338..e01954e31a 100644
--- a/qpid/cpp/src/tests/receiver.cpp
+++ b/qpid/cpp/src/tests/receiver.cpp
@@ -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
@@ -36,7 +36,10 @@ using namespace qpid::framing;
using namespace std;
-struct Args : public qpid::TestOptions
+namespace qpid {
+namespace tests {
+
+struct Args : public qpid::TestOptions
{
string queue;
uint messages;
@@ -47,7 +50,7 @@ struct Args : public qpid::TestOptions
Args() : queue("test-queue"), messages(0), ignoreDuplicates(false), creditWindow(0), ackFrequency(1), browse(false)
{
- addOptions()
+ addOptions()
("queue", qpid::optValue(queue, "QUEUE NAME"), "Queue from which to request messages")
("messages", qpid::optValue(messages, "N"), "Number of messages to receive; 0 means receive indefinitely")
("ignore-duplicates", qpid::optValue(ignoreDuplicates), "Detect and ignore duplicates (by checking 'sn' header)")
@@ -77,15 +80,15 @@ class Receiver : public MessageListener, public FailoverManager::Command
bool isDuplicate(Message& message);
};
-Receiver::Receiver(const string& q, uint messages, bool ignoreDuplicates, uint creditWindow, uint ackFrequency, bool browse) :
- queue(q), count(messages), skipDups(ignoreDuplicates), processed(0), lastSn(0)
+Receiver::Receiver(const string& q, uint messages, bool ignoreDuplicates, uint creditWindow, uint ackFrequency, bool browse) :
+ queue(q), count(messages), skipDups(ignoreDuplicates), processed(0), lastSn(0)
{
if (browse) settings.acquireMode = ACQUIRE_MODE_NOT_ACQUIRED;
if (creditWindow) settings.flowControl = FlowControl::messageWindow(creditWindow);
settings.autoAck = ackFrequency;
}
-void Receiver::received(Message& message)
+void Receiver::received(Message& message)
{
if (!(skipDups && isDuplicate(message))) {
bool eos = message.getData() == EOS;
@@ -94,7 +97,7 @@ void Receiver::received(Message& message)
}
}
-bool Receiver::isDuplicate(Message& message)
+bool Receiver::isDuplicate(Message& message)
{
uint sn = message.getHeaders().getAsInt("sn");
if (lastSn < sn) {
@@ -115,6 +118,10 @@ void Receiver::execute(AsyncSession& session, bool /*isRetry*/)
}
}
+}} // namespace qpid::tests
+
+using namespace qpid::tests;
+
int main(int argc, char ** argv)
{
Args opts;
@@ -130,6 +137,3 @@ int main(int argc, char ** argv)
}
return 1;
}
-
-
-
diff --git a/qpid/cpp/src/tests/replaying_sender.cpp b/qpid/cpp/src/tests/replaying_sender.cpp
index 3ee69eec14..bfb4b042b6 100644
--- a/qpid/cpp/src/tests/replaying_sender.cpp
+++ b/qpid/cpp/src/tests/replaying_sender.cpp
@@ -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
@@ -35,12 +35,15 @@ using namespace qpid::framing;
using namespace std;
+namespace qpid {
+namespace tests {
+
class Sender : public FailoverManager::Command
{
public:
Sender(const std::string& queue, uint count, uint reportFreq);
void execute(AsyncSession& session, bool isRetry);
- uint getSent();
+ uint getSent();
void setVerbosity ( int v ) { verbosity = v; }
void setPersistence ( int p ) { persistence = p; }
@@ -51,7 +54,7 @@ class Sender : public FailoverManager::Command
uint sent;
const uint reportFrequency;
Message message;
-
+
int verbosity;
int persistence;
};
@@ -93,7 +96,11 @@ uint Sender::getSent()
return sent;
}
-int main(int argc, char ** argv)
+}} // namespace qpid::tests
+
+using namespace qpid::tests;
+
+int main(int argc, char ** argv)
{
ConnectionSettings settings;
@@ -118,23 +125,23 @@ int main(int argc, char ** argv)
connection.execute ( sender );
if ( verbosity > 0 )
{
- std::cout << "Sender finished. Sent "
- << sender.getSent()
- << " messages."
+ std::cout << "Sender finished. Sent "
+ << sender.getSent()
+ << " messages."
<< endl;
}
connection.close();
- return 0;
- }
- catch(const std::exception& error)
+ return 0;
+ }
+ catch(const std::exception& error)
{
- cerr << "Sender (host: "
- << settings.host
- << " port: "
+ cerr << "Sender (host: "
+ << settings.host
+ << " port: "
<< settings.port
<< " ) "
- << " Failed: "
- << error.what()
+ << " Failed: "
+ << error.what()
<< std::endl;
}
return 1;
diff --git a/qpid/cpp/src/tests/resuming_receiver.cpp b/qpid/cpp/src/tests/resuming_receiver.cpp
index ef559a009d..807bd83bee 100644
--- a/qpid/cpp/src/tests/resuming_receiver.cpp
+++ b/qpid/cpp/src/tests/resuming_receiver.cpp
@@ -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
@@ -35,8 +35,11 @@ using namespace qpid::framing;
using namespace std;
-class Listener : public MessageListener,
- public FailoverManager::Command,
+namespace qpid {
+namespace tests {
+
+class Listener : public MessageListener,
+ public FailoverManager::Command,
public FailoverManager::ReconnectionStrategy
{
public:
@@ -57,32 +60,32 @@ class Listener : public MessageListener,
};
-Listener::Listener(int freq, int verbosity)
- : count(0),
- received_twice(0),
- lastSn(0),
- gaps(false),
+Listener::Listener(int freq, int verbosity)
+ : count(0),
+ received_twice(0),
+ lastSn(0),
+ gaps(false),
reportFrequency(freq),
verbosity(verbosity),
done(false)
{}
-void Listener::received(Message & message)
+void Listener::received(Message & message)
{
- if (message.getData() == "That's all, folks!")
+ if (message.getData() == "That's all, folks!")
{
done = true;
if(verbosity > 0 )
{
- std::cout << "Shutting down listener for "
+ std::cout << "Shutting down listener for "
<< message.getDestination() << std::endl;
- std::cout << "Listener received "
- << count
- << " messages ("
- << received_twice
- << " received_twice)"
+ std::cout << "Listener received "
+ << count
+ << " messages ("
+ << received_twice
+ << " received_twice)"
<< endl;
}
subscription.cancel();
@@ -99,8 +102,8 @@ void Listener::received(Message & message)
++count;
if ( ! ( count % reportFrequency ) ) {
if ( verbosity > 0 )
- std::cout << "Listener has received "
- << count
+ std::cout << "Listener has received "
+ << count
<< " messages.\n";
}
} else {
@@ -133,6 +136,10 @@ void Listener::editUrlList(std::vector<Url>& urls)
if (urls.size() > 1) std::rotate(urls.begin(), urls.begin() + 1, urls.end());
}
+}} // namespace qpid::tests
+
+using namespace qpid::tests;
+
int main(int argc, char ** argv)
{
ConnectionSettings settings;
diff --git a/qpid/cpp/src/tests/sender.cpp b/qpid/cpp/src/tests/sender.cpp
index 311de2e5f8..4e845c42b4 100644
--- a/qpid/cpp/src/tests/sender.cpp
+++ b/qpid/cpp/src/tests/sender.cpp
@@ -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
@@ -37,22 +37,27 @@ using namespace qpid::framing;
using namespace std;
-struct Args : public qpid::TestOptions
+namespace qpid {
+namespace tests {
+
+struct Args : public qpid::TestOptions
{
string destination;
string key;
uint sendEos;
bool durable;
+ uint ttl;
string lvqMatchValue;
string lvqMatchFile;
- Args() : key("test-queue"), sendEos(0), durable(false)
+ Args() : key("test-queue"), sendEos(0), durable(false), ttl(0)
{
addOptions()
("exchange", qpid::optValue(destination, "EXCHANGE"), "Exchange to send messages to")
("routing-key", qpid::optValue(key, "KEY"), "Routing key to add to messages")
("send-eos", qpid::optValue(sendEos, "N"), "Send N EOS messages to mark end of input")
("durable", qpid::optValue(durable, "true|false"), "Mark messages as durable.")
+ ("ttl", qpid::optValue(ttl, "msecs"), "Time-to-live for messages, in milliseconds")
("lvq-match-value", qpid::optValue(lvqMatchValue, "KEY"), "The value to set for the LVQ match key property")
("lvq-match-file", qpid::optValue(lvqMatchFile, "FILE"), "A file containing values to set for the LVQ match key property");
}
@@ -63,26 +68,29 @@ const string EOS("eos");
class Sender : public FailoverManager::Command
{
public:
- Sender(const std::string& destination, const std::string& key, uint sendEos, bool durable,
+ Sender(const std::string& destination, const std::string& key, uint sendEos, bool durable, uint ttl,
const std::string& lvqMatchValue, const std::string& lvqMatchFile);
void execute(AsyncSession& session, bool isRetry);
private:
const std::string destination;
MessageReplayTracker sender;
- Message message;
+ Message message;
const uint sendEos;
uint sent;
std::ifstream lvqMatchValues;
};
-Sender::Sender(const std::string& dest, const std::string& key, uint eos, bool durable,
- const std::string& lvqMatchValue, const std::string& lvqMatchFile) :
+Sender::Sender(const std::string& dest, const std::string& key, uint eos, bool durable, uint ttl, const std::string& lvqMatchValue, const std::string& lvqMatchFile) :
destination(dest), sender(10), message("", key), sendEos(eos), sent(0) , lvqMatchValues(lvqMatchFile.c_str())
{
if (durable){
message.getDeliveryProperties().setDeliveryMode(framing::PERSISTENT);
}
+ if (ttl) {
+ message.getDeliveryProperties().setTtl(ttl);
+ }
+
if (!lvqMatchValue.empty()) {
message.getHeaders().setString(QueueOptions::strLVQMatchProperty, lvqMatchValue);
}
@@ -108,16 +116,20 @@ void Sender::execute(AsyncSession& session, bool isRetry)
}
}
-int main(int argc, char ** argv)
+}} // namespace qpid::tests
+
+using namespace qpid::tests;
+
+int main(int argc, char ** argv)
{
Args opts;
try {
opts.parse(argc, argv);
FailoverManager connection(opts.con);
- Sender sender(opts.destination, opts.key, opts.sendEos, opts.durable, opts.lvqMatchValue, opts.lvqMatchFile);
+ Sender sender(opts.destination, opts.key, opts.sendEos, opts.durable, opts.ttl, opts.lvqMatchValue, opts.lvqMatchFile);
connection.execute(sender);
connection.close();
- return 0;
+ return 0;
} catch(const std::exception& error) {
std::cout << "Failed: " << error.what() << std::endl;
}
diff --git a/qpid/cpp/src/tests/shlibtest.cpp b/qpid/cpp/src/tests/shlibtest.cpp
index e485cc9397..5655eb7e64 100644
--- a/qpid/cpp/src/tests/shlibtest.cpp
+++ b/qpid/cpp/src/tests/shlibtest.cpp
@@ -18,6 +18,9 @@
*
*/
+namespace qpid {
+namespace tests {
+
int* loaderData = 0;
extern "C"
#ifdef WIN32
@@ -28,5 +31,4 @@ void callMe(int *i) { loaderData=i; }
struct OnUnload { ~OnUnload() { *loaderData=42; } };
OnUnload unloader; // For destructor.
-
-
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/test_store.cpp b/qpid/cpp/src/tests/test_store.cpp
index 90503818ed..64a96bf71a 100644
--- a/qpid/cpp/src/tests/test_store.cpp
+++ b/qpid/cpp/src/tests/test_store.cpp
@@ -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
@@ -22,7 +22,7 @@
/**@file
* Plug-in message store for tests.
- *
+ *
* Add functionality as required, build up a comprehensive set of
* features to support persistent behavior tests.
*
@@ -46,6 +46,9 @@ using namespace std;
using namespace boost;
using namespace qpid::sys;
+namespace qpid {
+namespace tests {
+
struct TestStoreOptions : public Options {
string name;
@@ -66,7 +69,7 @@ struct Completer : public Runnable {
delete this;
}
};
-
+
class TestStore : public NullMessageStore {
public:
TestStore(const string& name_, Broker& broker_) : name(name_), broker(broker_) {}
@@ -83,7 +86,7 @@ class TestStore : public NullMessageStore {
// Check the message for special instructions.
size_t i = string::npos;
- size_t j = string::npos;
+ size_t j = string::npos;
if (strncmp(data.c_str(), TEST_STORE_DO.c_str(), strlen(TEST_STORE_DO.c_str())) == 0
&& (i = data.find(name+"[")) != string::npos
&& (j = data.find("]", i)) != string::npos)
@@ -144,3 +147,5 @@ struct TestStorePlugin : public Plugin {
};
static TestStorePlugin pluginInstance;
+
+}} // namespace qpid::tests
diff --git a/qpid/cpp/src/tests/test_tools.h b/qpid/cpp/src/tests/test_tools.h
index 54837d3e5b..832c04af04 100644
--- a/qpid/cpp/src/tests/test_tools.h
+++ b/qpid/cpp/src/tests/test_tools.h
@@ -34,7 +34,7 @@ template <class T> std::ostream& seqPrint(std::ostream& o, const T& seq) {
return o;
}
-// Compare sequences
+// Compare sequences
template <class T, class U>
bool seqEqual(const T& a, const U& b) {
typename T::const_iterator i = a.begin();
@@ -60,6 +60,9 @@ template <class T>
bool operator == (const boost::assign_detail::generic_list<T>& b, const vector<T>& a) { return seqEqual(a, b); }
}
+namespace qpid {
+namespace tests {
+
/** NB: order of parameters is regex first, in line with
* CHECK(expected, actual) convention.
*/
@@ -98,6 +101,7 @@ inline std::string getLibPath(const char* envName, const char* defaultPath = 0)
return defaultPath;
}
+}} // namespace qpid::tests
#endif /*!TEST_TOOLS_H*/
diff --git a/qpid/cpp/src/tests/topic_listener.cpp b/qpid/cpp/src/tests/topic_listener.cpp
index 44070cd4c9..aa8c19df99 100644
--- a/qpid/cpp/src/tests/topic_listener.cpp
+++ b/qpid/cpp/src/tests/topic_listener.cpp
@@ -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
@@ -23,7 +23,7 @@
* This file provides one half of a test and example of a pub-sub
* style of interaction. See topic_publisher.cpp for the other half,
* in which the logic for publishing is defined.
- *
+ *
* This file contains the listener logic. A listener will subscribe to
* a logical 'topic'. It will count the number of messages it receives
* and the time elapsed between the first one and the last one. It
@@ -50,11 +50,14 @@ using namespace qpid::sys;
using namespace qpid::framing;
using namespace std;
+namespace qpid {
+namespace tests {
+
/**
* A message listener implementation in which the runtime logic is
* defined.
*/
-class Listener : public MessageListener{
+class Listener : public MessageListener{
Session session;
SubscriptionManager& mgr;
const string responseQueue;
@@ -62,7 +65,7 @@ class Listener : public MessageListener{
bool init;
int count;
AbsTime start;
-
+
void shutdown();
void report();
public:
@@ -91,6 +94,52 @@ struct Args : public qpid::TestOptions {
}
};
+Listener::Listener(const Session& s, SubscriptionManager& m, const string& _responseq, bool tx) :
+ session(s), mgr(m), responseQueue(_responseq), transactional(tx), init(false), count(0){}
+
+void Listener::received(Message& message){
+ if(!init){
+ start = now();
+ count = 0;
+ init = true;
+ cout << "Batch started." << endl;
+ }
+ string type = message.getHeaders().getAsString("TYPE");
+
+ if(string("TERMINATION_REQUEST") == type){
+ shutdown();
+ }else if(string("REPORT_REQUEST") == type){
+ subscription.accept(subscription.getUnaccepted()); // Accept everything upto this point
+ cout <<"Batch ended, sending report." << endl;
+ //send a report:
+ report();
+ init = false;
+ }else if (++count % 1000 == 0){
+ cout <<"Received " << count << " messages." << endl;
+ }
+}
+
+void Listener::shutdown(){
+ mgr.stop();
+}
+
+void Listener::report(){
+ AbsTime finish = now();
+ Duration time(start, finish);
+ stringstream reportstr;
+ reportstr << "Received " << count << " messages in "
+ << time/TIME_MSEC << " ms.";
+ Message msg(reportstr.str(), responseQueue);
+ msg.getHeaders().setString("TYPE", "REPORT");
+ session.messageTransfer(arg::destination="amq.direct", arg::content=msg, arg::acceptMode=1);
+ if(transactional){
+ sync(session).txCommit();
+ }
+}
+
+}} // namespace qpid::tests
+
+using namespace qpid::tests;
/**
* The main routine creates a Listener instance and sets it up to
@@ -142,7 +191,7 @@ int main(int argc, char** argv){
if (args.transactional) {
session.txSelect();
}
-
+
cout << "topic_listener: listening..." << endl;
mgr.run();
if (args.durable) {
@@ -158,47 +207,3 @@ int main(int argc, char** argv){
}
return 1;
}
-
-Listener::Listener(const Session& s, SubscriptionManager& m, const string& _responseq, bool tx) :
- session(s), mgr(m), responseQueue(_responseq), transactional(tx), init(false), count(0){}
-
-void Listener::received(Message& message){
- if(!init){
- start = now();
- count = 0;
- init = true;
- cout << "Batch started." << endl;
- }
- string type = message.getHeaders().getAsString("TYPE");
-
- if(string("TERMINATION_REQUEST") == type){
- shutdown();
- }else if(string("REPORT_REQUEST") == type){
- subscription.accept(subscription.getUnaccepted()); // Accept everything upto this point
- cout <<"Batch ended, sending report." << endl;
- //send a report:
- report();
- init = false;
- }else if (++count % 1000 == 0){
- cout <<"Received " << count << " messages." << endl;
- }
-}
-
-void Listener::shutdown(){
- mgr.stop();
-}
-
-void Listener::report(){
- AbsTime finish = now();
- Duration time(start, finish);
- stringstream reportstr;
- reportstr << "Received " << count << " messages in "
- << time/TIME_MSEC << " ms.";
- Message msg(reportstr.str(), responseQueue);
- msg.getHeaders().setString("TYPE", "REPORT");
- session.messageTransfer(arg::destination="amq.direct", arg::content=msg, arg::acceptMode=1);
- if(transactional){
- sync(session).txCommit();
- }
-}
-
diff --git a/qpid/cpp/src/tests/topic_publisher.cpp b/qpid/cpp/src/tests/topic_publisher.cpp
index 40055bbfa0..3381132b1a 100644
--- a/qpid/cpp/src/tests/topic_publisher.cpp
+++ b/qpid/cpp/src/tests/topic_publisher.cpp
@@ -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
@@ -23,7 +23,7 @@
* This file provides one half of a test and example of a pub-sub
* style of interaction. See topic_listener.cpp for the other half, in
* which the logic for subscribers is defined.
- *
+ *
* This file contains the publisher logic. The publisher will send a
* number of messages to the exchange with the appropriate routing key
* for the logical 'topic'. Once it has done this it will then send a
@@ -49,19 +49,22 @@ using namespace qpid::client;
using namespace qpid::sys;
using namespace std;
+namespace qpid {
+namespace tests {
+
/**
* The publishing logic is defined in this class. It implements
* message listener and can therfore be used to receive messages sent
* back by the subscribers.
*/
-class Publisher {
+class Publisher {
AsyncSession session;
SubscriptionManager mgr;
LocalQueue queue;
const string controlTopic;
const bool transactional;
const bool durable;
-
+
string generateData(int size);
public:
@@ -99,6 +102,64 @@ struct Args : public TestOptions {
}
};
+Publisher::Publisher(const AsyncSession& _session, const string& _controlTopic, bool tx, bool d) :
+ session(_session), mgr(session), controlTopic(_controlTopic), transactional(tx), durable(d)
+{
+ mgr.subscribe(queue, "response");
+}
+
+int64_t Publisher::publish(int msgs, int listeners, int size){
+ Message msg(generateData(size), controlTopic);
+ if (durable) {
+ msg.getDeliveryProperties().setDeliveryMode(framing::PERSISTENT);
+ }
+ AbsTime start = now();
+
+ for(int i = 0; i < msgs; i++){
+ session.messageTransfer(arg::content=msg, arg::destination="amq.topic", arg::acceptMode=1);
+ }
+ //send report request
+ Message reportRequest("", controlTopic);
+ reportRequest.getHeaders().setString("TYPE", "REPORT_REQUEST");
+ session.messageTransfer(arg::content=reportRequest, arg::destination="amq.topic", arg::acceptMode=1);
+ if(transactional){
+ sync(session).txCommit();
+ }
+ //wait for a response from each listener (TODO, could log these)
+ for (int i = 0; i < listeners; i++) {
+ Message report = queue.pop();
+ }
+
+ if(transactional){
+ sync(session).txCommit();
+ }
+
+ AbsTime finish = now();
+ return Duration(start, finish);
+}
+
+string Publisher::generateData(int size){
+ string data;
+ for(int i = 0; i < size; i++){
+ data += ('A' + (i / 26));
+ }
+ return data;
+}
+
+void Publisher::terminate(){
+ //send termination request
+ Message terminationRequest("", controlTopic);
+ terminationRequest.getHeaders().setString("TYPE", "TERMINATION_REQUEST");
+ session.messageTransfer(arg::content=terminationRequest, arg::destination="amq.topic", arg::acceptMode=1);
+ if(transactional){
+ session.txCommit();
+ }
+}
+
+}} // namespace qpid::tests
+
+using namespace qpid::tests;
+
int main(int argc, char** argv) {
try{
Args args;
@@ -120,11 +181,11 @@ int main(int argc, char** argv) {
Message m = statusQ.get();
if( m.getData().find("topic_listener: ", 0) == 0 ) {
cout << "Listener " << (i+1) << " of " << args.subscribers
- << " is ready (pid " << m.getData().substr(16, m.getData().length() - 16)
- << ")" << endl;
+ << " is ready (pid " << m.getData().substr(16, m.getData().length() - 16)
+ << ")" << endl;
} else {
throw Exception(QPID_MSG("Unexpected message received on status queue: " << m.getData()));
- }
+ }
}
}
@@ -150,12 +211,12 @@ int main(int argc, char** argv) {
if(!min || msecs < min) min = msecs;
sum += msecs;
cout << "Completed " << (i+1) << " of " << batchSize
- << " in " << msecs << "ms" << endl;
+ << " in " << msecs << "ms" << endl;
}
publisher.terminate();
int64_t avg = sum / batchSize;
if(batchSize > 1){
- cout << batchSize << " batches completed. avg=" << avg <<
+ cout << batchSize << " batches completed. avg=" << avg <<
", max=" << max << ", min=" << min << endl;
}
session.close();
@@ -167,57 +228,3 @@ int main(int argc, char** argv) {
}
return 1;
}
-
-Publisher::Publisher(const AsyncSession& _session, const string& _controlTopic, bool tx, bool d) :
- session(_session), mgr(session), controlTopic(_controlTopic), transactional(tx), durable(d)
-{
- mgr.subscribe(queue, "response");
-}
-
-int64_t Publisher::publish(int msgs, int listeners, int size){
- Message msg(generateData(size), controlTopic);
- if (durable) {
- msg.getDeliveryProperties().setDeliveryMode(framing::PERSISTENT);
- }
- AbsTime start = now();
-
- for(int i = 0; i < msgs; i++){
- session.messageTransfer(arg::content=msg, arg::destination="amq.topic", arg::acceptMode=1);
- }
- //send report request
- Message reportRequest("", controlTopic);
- reportRequest.getHeaders().setString("TYPE", "REPORT_REQUEST");
- session.messageTransfer(arg::content=reportRequest, arg::destination="amq.topic", arg::acceptMode=1);
- if(transactional){
- sync(session).txCommit();
- }
- //wait for a response from each listener (TODO, could log these)
- for (int i = 0; i < listeners; i++) {
- Message report = queue.pop();
- }
-
- if(transactional){
- sync(session).txCommit();
- }
-
- AbsTime finish = now();
- return Duration(start, finish);
-}
-
-string Publisher::generateData(int size){
- string data;
- for(int i = 0; i < size; i++){
- data += ('A' + (i / 26));
- }
- return data;
-}
-
-void Publisher::terminate(){
- //send termination request
- Message terminationRequest("", controlTopic);
- terminationRequest.getHeaders().setString("TYPE", "TERMINATION_REQUEST");
- session.messageTransfer(arg::content=terminationRequest, arg::destination="amq.topic", arg::acceptMode=1);
- if(transactional){
- session.txCommit();
- }
-}
diff --git a/qpid/cpp/src/tests/txjob.cpp b/qpid/cpp/src/tests/txjob.cpp
index 94db96a666..a7a905c1b7 100644
--- a/qpid/cpp/src/tests/txjob.cpp
+++ b/qpid/cpp/src/tests/txjob.cpp
@@ -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
@@ -33,7 +33,10 @@
using namespace qpid::client;
using namespace qpid::sys;
-struct Args : public qpid::TestOptions
+namespace qpid {
+namespace tests {
+
+struct Args : public qpid::TestOptions
{
string workQueue;
string source;
@@ -43,10 +46,10 @@ struct Args : public qpid::TestOptions
bool quit;
bool declareQueues;
- Args() : workQueue("txshift-control"), source("txshift-1"), dest("txshift-2"), messages(0), jobs(0),
+ Args() : workQueue("txshift-control"), source("txshift-1"), dest("txshift-2"), messages(0), jobs(0),
quit(false), declareQueues(false)
{
- addOptions()
+ addOptions()
("messages", qpid::optValue(messages, "N"), "Number of messages to shift")
("jobs", qpid::optValue(jobs, "N"), "Number of shift jobs to request")
("source", qpid::optValue(source, "QUEUE NAME"), "source queue from which messages will be shifted")
@@ -57,6 +60,10 @@ struct Args : public qpid::TestOptions
}
};
+}} // namespace qpid::tests
+
+using namespace qpid::tests;
+
//TODO: might be nice to make this capable of failover as well at some
//point; for now its just for the setup phase.
int main(int argc, char** argv)
diff --git a/qpid/cpp/src/tests/txshift.cpp b/qpid/cpp/src/tests/txshift.cpp
index 97135c9829..882d3716d8 100644
--- a/qpid/cpp/src/tests/txshift.cpp
+++ b/qpid/cpp/src/tests/txshift.cpp
@@ -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
@@ -34,14 +34,17 @@
using namespace qpid::client;
using namespace qpid::sys;
-struct Args : public qpid::TestOptions
+namespace qpid {
+namespace tests {
+
+struct Args : public qpid::TestOptions
{
string workQueue;
size_t workers;
Args() : workQueue("txshift-control"), workers(1)
{
- addOptions()
+ addOptions()
("workers", qpid::optValue(workers, "N"), "Number of separate worker sessions to start")
("work-queue", qpid::optValue(workQueue, "NAME"), "work queue from which to take instructions");
}
@@ -61,7 +64,7 @@ struct Transfer : MessageListener
Transfer(const std::string control_) : control(control_), expected(0), transfered(0) {}
- void subscribeToSource(SubscriptionManager manager)
+ void subscribeToSource(SubscriptionManager manager)
{
sourceSettings.autoAck = 0;//will accept once at the end of the batch
sourceSettings.flowControl = FlowControl::messageCredit(expected);
@@ -69,7 +72,7 @@ struct Transfer : MessageListener
QPID_LOG(info, "Subscribed to source: " << source << " expecting: " << expected);
}
- void subscribeToControl(SubscriptionManager manager)
+ void subscribeToControl(SubscriptionManager manager)
{
controlSettings.flowControl = FlowControl::messageCredit(1);
controlSubscription = manager.subscribe(*this, control, controlSettings);
@@ -94,7 +97,7 @@ struct Transfer : MessageListener
message.getDeliveryProperties().setRoutingKey(destination);
async(sourceSubscription.getSession()).messageTransfer(arg::content=message);
if (++transfered == expected) {
- QPID_LOG(info, "completed job: " << transfered << " messages shifted from " <<
+ QPID_LOG(info, "completed job: " << transfered << " messages shifted from " <<
source << " to " << destination);
sourceSubscription.accept(sourceSubscription.getUnaccepted());
sourceSubscription.getSession().txCommit();
@@ -111,7 +114,7 @@ struct Transfer : MessageListener
destination = message.getHeaders().getAsString("dest");
expected = message.getHeaders().getAsInt("count");
transfered = 0;
- QPID_LOG(info, "received transfer request: " << expected << " messages to be shifted from " <<
+ QPID_LOG(info, "received transfer request: " << expected << " messages to be shifted from " <<
source << " to " << destination);
subscribeToSource(controlSubscription.getSubscriptionManager());
} else if (message.getData() == "quit") {
@@ -133,7 +136,7 @@ struct Worker : FailoverManager::Command, Runnable
Worker(FailoverManager& c, const std::string& controlQueue) : connection(c), transfer(controlQueue) {}
- void run()
+ void run()
{
connection.execute(*this);
}
@@ -148,7 +151,7 @@ struct Worker : FailoverManager::Command, Runnable
runner.join();
}
- void execute(AsyncSession& session, bool isRetry)
+ void execute(AsyncSession& session, bool isRetry)
{
if (isRetry) QPID_LOG(info, "Retrying...");
session.txSelect();
@@ -159,6 +162,10 @@ struct Worker : FailoverManager::Command, Runnable
}
};
+}} // namespace qpid::tests
+
+using namespace qpid::tests;
+
int main(int argc, char** argv)
{
Args opts;
diff --git a/qpid/cpp/src/tests/txtest.cpp b/qpid/cpp/src/tests/txtest.cpp
index f604df7e21..d0ba2f1245 100644
--- a/qpid/cpp/src/tests/txtest.cpp
+++ b/qpid/cpp/src/tests/txtest.cpp
@@ -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
@@ -41,6 +41,9 @@ using namespace qpid::client;
using namespace qpid::sys;
using std::string;
+namespace qpid {
+namespace tests {
+
typedef std::vector<std::string> StringSet;
struct Args : public qpid::TestOptions {
@@ -55,12 +58,12 @@ struct Args : public qpid::TestOptions {
bool dtx;
bool quiet;
- Args() : init(true), transfer(true), check(true),
- size(256), durable(true), queues(2),
+ Args() : init(true), transfer(true), check(true),
+ size(256), durable(true), queues(2),
base("tx-test"), msgsPerTx(1), txCount(1), totalMsgCount(10),
dtx(false), quiet(false)
{
- addOptions()
+ addOptions()
("init", optValue(init, "yes|no"), "Declare queues and populate one with the initial set of messages.")
("transfer", optValue(transfer, "yes|no"), "'Move' messages from one queue to another using transactions to ensure no message loss.")
@@ -83,7 +86,7 @@ std::string generateData(uint size)
{
if (size < chars.length()) {
return chars.substr(0, size);
- }
+ }
std::string data;
for (uint i = 0; i < (size / chars.length()); i++) {
data += chars;
@@ -103,18 +106,18 @@ void generateSet(const std::string& base, uint count, StringSet& collection)
Args opts;
-struct Client
+struct Client
{
Connection connection;
AsyncSession session;
- Client()
+ Client()
{
opts.open(connection);
session = connection.newSession();
}
- ~Client()
+ ~Client()
{
try{
session.close();
@@ -134,19 +137,19 @@ struct Transfer : public Client, public Runnable
Transfer(const std::string& to, const std::string& from) : src(to), dest(from), xid(0x4c414e47, "", from) {}
- void run()
+ void run()
{
try {
-
+
if (opts.dtx) session.dtxSelect();
else session.txSelect();
SubscriptionManager subs(session);
-
+
LocalQueue lq;
SubscriptionSettings settings(FlowControl::messageWindow(opts.msgsPerTx));
settings.autoAck = 0; // Disabled
Subscription sub = subs.subscribe(lq, src, settings);
-
+
for (uint t = 0; t < opts.txCount; t++) {
Message in;
Message out("", dest);
@@ -187,7 +190,7 @@ struct Transfer : public Client, public Runnable
}
};
-struct Controller : public Client
+struct Controller : public Client
{
StringSet ids;
StringSet queues;
@@ -198,7 +201,7 @@ struct Controller : public Client
generateSet("msg", opts.totalMsgCount, ids);
}
- void init()
+ void init()
{
//declare queues
for (StringSet::iterator i = queues.begin(); i != queues.end(); i++) {
@@ -236,7 +239,7 @@ struct Controller : public Client
}
}
- int check()
+ int check()
{
SubscriptionManager subs(session);
@@ -291,10 +294,10 @@ struct Controller : public Client
//check that drained == ids
StringSet missing;
- set_difference(ids.begin(), ids.end(), drained.begin(), drained.end(), back_inserter(missing));
+ set_difference(ids.begin(), ids.end(), drained.begin(), drained.end(), back_inserter(missing));
StringSet extra;
- set_difference(drained.begin(), drained.end(), ids.begin(), ids.end(), back_inserter(extra));
+ set_difference(drained.begin(), drained.end(), ids.begin(), ids.end(), back_inserter(extra));
if (missing.empty() && extra.empty()) {
std::cout << "All expected messages were retrieved." << std::endl;
@@ -303,26 +306,30 @@ struct Controller : public Client
if (!missing.empty()) {
std::cout << "The following ids were missing:" << std::endl;
for (StringSet::iterator i = missing.begin(); i != missing.end(); i++) {
- std::cout << " '" << *i << "'" << std::endl;
- }
+ std::cout << " '" << *i << "'" << std::endl;
+ }
}
if (!extra.empty()) {
std::cout << "The following extra ids were encountered:" << std::endl;
for (StringSet::iterator i = extra.begin(); i != extra.end(); i++) {
- std::cout << " '" << *i << "'" << std::endl;
- }
+ std::cout << " '" << *i << "'" << std::endl;
+ }
}
return 1;
}
}
};
+}} // namespace qpid::tests
+
+using namespace qpid::tests;
+
int main(int argc, char** argv)
{
try {
opts.parse(argc, argv);
Controller controller;
- if (opts.init) controller.init();
+ if (opts.init) controller.init();
if (opts.transfer) controller.transfer();
if (opts.check) return controller.check();
return 0;
diff --git a/qpid/java/broker/bin/qpid-passwd b/qpid/java/broker/bin/qpid-passwd
index 63b30b5e71..b84580da60 100755
--- a/qpid/java/broker/bin/qpid-passwd
+++ b/qpid/java/broker/bin/qpid-passwd
@@ -1,35 +1,35 @@
-#!/bin/bash
-#
-# 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.
-#
-
-if [ -z "$QPID_HOME" ]; then
- export QPID_HOME=$(dirname $(dirname $(readlink -f $0)))
- export PATH=${PATH}:${QPID_HOME}/bin
-fi
-
-# Set classpath to include Qpid jar with all required jars in manifest
-QPID_LIBS=$QPID_HOME/lib/qpid-all.jar
-
-# Set other variables used by the qpid-run script before calling
-export JAVA=java \
- JAVA_VM=-server \
- JAVA_MEM=-Xmx1024m \
- QPID_CLASSPATH=$QPID_LIBS
-
-. qpid-run org.apache.qpid.tools.security.Passwd "$@"
+#!/bin/bash
+#
+# 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.
+#
+
+if [ -z "$QPID_HOME" ]; then
+ export QPID_HOME=$(dirname $(dirname $(readlink -f $0)))
+ export PATH=${PATH}:${QPID_HOME}/bin
+fi
+
+# Set classpath to include Qpid jar with all required jars in manifest
+QPID_LIBS=$QPID_HOME/lib/qpid-all.jar
+
+# Set other variables used by the qpid-run script before calling
+export JAVA=java \
+ JAVA_VM=-server \
+ JAVA_MEM=-Xmx1024m \
+ QPID_CLASSPATH=$QPID_LIBS
+
+. qpid-run org.apache.qpid.tools.security.Passwd "$@"
diff --git a/qpid/java/broker/etc/config-systests-derby.xml b/qpid/java/broker/etc/config-systests-derby.xml
deleted file mode 100644
index e9cfa04ab5..0000000000
--- a/qpid/java/broker/etc/config-systests-derby.xml
+++ /dev/null
@@ -1,141 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<!--
- -
- - 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.
- -
- -->
-<broker>
- <prefix>${QPID_HOME}</prefix>
- <work>${QPID_WORK}</work>
- <conf>${prefix}/etc</conf>
- <connector>
- <!-- Uncomment out this block and edit the keystorePath and keystorePassword
- to enable SSL support
- <ssl>
- <enabled>true</enabled>
- <sslOnly>true</sslOnly>
- <keystorePath>/path/to/keystore.ks</keystorePath>
- <keystorePassword>keystorepass</keystorePassword>
- </ssl>-->
- <qpidnio>false</qpidnio>
- <protectio>
- <enabled>false</enabled>
- </protectio>
- <transport>nio</transport>
- <port>5672</port>
- <sslport>8672</sslport>
- <socketReceiveBuffer>32768</socketReceiveBuffer>
- <socketSendBuffer>32768</socketSendBuffer>
- </connector>
- <management>
- <enabled>false</enabled>
- <jmxport>8999</jmxport>
- <ssl>
- <enabled>false</enabled>
- <!-- Update below path to your keystore location, eg ${conf}/qpid.keystore -->
- <keyStorePath>${prefix}/../test-profiles/test_resources/ssl/keystore.jks</keyStorePath>
- <keyStorePassword>password</keyStorePassword>
- </ssl>
- </management>
- <advanced>
- <filterchain enableExecutorPool="true"/>
- <enablePooledAllocator>false</enablePooledAllocator>
- <enableDirectBuffers>false</enableDirectBuffers>
- <framesize>65535</framesize>
- <compressBufferOnQueue>false</compressBufferOnQueue>
- <enableJMSXUserID>false</enableJMSXUserID>
- </advanced>
-
- <security>
- <principal-databases>
- <!-- Example use of Base64 encoded MD5 hashes for authentication via CRAM-MD5-Hashed -->
- <principal-database>
- <name>passwordfile</name>
- <class>org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase</class>
- <attributes>
- <attribute>
- <name>passwordFile</name>
- <value>${conf}/passwd</value>
- </attribute>
- </attributes>
- </principal-database>
- </principal-databases>
-
- <access>
- <class>org.apache.qpid.server.security.access.plugins.AllowAll</class>
- </access>
-
- <msg-auth>false</msg-auth>
-
- <jmx>
- <access>${conf}/jmxremote.access</access>
- <principal-database>passwordfile</principal-database>
- </jmx>
- </security>
-
- <virtualhosts>
- <directory>${conf}/virtualhosts</directory>
-
- <virtualhost>
- <name>localhost</name>
- <localhost>
- <store>
- <class>org.apache.qpid.server.store.DerbyMessageStore</class>
- <environment-path>${work}/derbyDB/localhost-store</environment-path>
- </store>
-
- <housekeeping>
- <expiredMessageCheckPeriod>20000</expiredMessageCheckPeriod>
- </housekeeping>
-
- </localhost>
- </virtualhost>
-
- <virtualhost>
- <name>development</name>
- <development>
- <store>
- <class>org.apache.qpid.server.store.DerbyMessageStore</class>
- <environment-path>${work}/derbyDB/development-store</environment-path>
- </store>
- </development>
- </virtualhost>
-
- <virtualhost>
- <name>test</name>
- <test>
- <store>
- <class>org.apache.qpid.server.store.DerbyMessageStore</class>
- <environment-path>${work}/derbyDB/test-store</environment-path>
- </store>
- </test>
- </virtualhost>
-
- </virtualhosts>
- <heartbeat>
- <delay>0</delay>
- <timeoutFactor>2.0</timeoutFactor>
- </heartbeat>
- <queue>
- <auto_register>true</auto_register>
- </queue>
-
- <virtualhosts>${conf}/virtualhosts-systests.xml</virtualhosts>
-</broker>
-
-
diff --git a/qpid/java/broker/etc/config-systests.xml b/qpid/java/broker/etc/config-systests.xml
deleted file mode 100644
index 42e8c9dbba..0000000000
--- a/qpid/java/broker/etc/config-systests.xml
+++ /dev/null
@@ -1,143 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<!--
- -
- - 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.
- -
- -->
-<broker>
- <prefix>${QPID_HOME}</prefix>
- <work>${QPID_WORK}</work>
- <conf>${prefix}/etc</conf>
- <connector>
- <!-- Uncomment out this block and edit the keystorePath and keystorePassword
- to enable SSL support
- <ssl>
- <enabled>true</enabled>
- <sslOnly>true</sslOnly>
- <keystorePath>/path/to/keystore.ks</keystorePath>
- <keystorePassword>keystorepass</keystorePassword>
- </ssl>-->
- <qpidnio>false</qpidnio>
- <protectio>
- <enabled>false</enabled>
- <readBufferLimitSize>262144</readBufferLimitSize>
- <writeBufferLimitSize>262144</writeBufferLimitSize>
- </protectio>
- <transport>nio</transport>
- <port>5672</port>
- <sslport>8672</sslport>
- <socketReceiveBuffer>32768</socketReceiveBuffer>
- <socketSendBuffer>32768</socketSendBuffer>
- </connector>
- <management>
- <enabled>false</enabled>
- <jmxport>8999</jmxport>
- <ssl>
- <enabled>false</enabled>
- <!-- Update below path to your keystore location, eg ${conf}/qpid.keystore -->
- <keyStorePath>${prefix}/../test-profiles/test_resources/ssl/keystore.jks</keyStorePath>
- <keyStorePassword>password</keyStorePassword>
- </ssl>
- </management>
- <advanced>
- <filterchain enableExecutorPool="true"/>
- <enablePooledAllocator>false</enablePooledAllocator>
- <enableDirectBuffers>false</enableDirectBuffers>
- <framesize>65535</framesize>
- <compressBufferOnQueue>false</compressBufferOnQueue>
- <enableJMSXUserID>false</enableJMSXUserID>
- <locale>en_US</locale>
- </advanced>
-
- <security>
- <principal-databases>
- <!-- Example use of Base64 encoded MD5 hashes for authentication via CRAM-MD5-Hashed -->
- <principal-database>
- <name>passwordfile</name>
- <class>org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase</class>
- <attributes>
- <attribute>
- <name>passwordFile</name>
- <value>${conf}/passwd</value>
- </attribute>
- </attributes>
- </principal-database>
- </principal-databases>
-
- <access>
- <class>org.apache.qpid.server.security.access.plugins.AllowAll</class>
- </access>
-
- <msg-auth>false</msg-auth>
-
- <jmx>
- <access>${conf}/jmxremote.access</access>
- <principal-database>passwordfile</principal-database>
- </jmx>
- </security>
-
- <virtualhosts>
- <directory>${conf}/virtualhosts</directory>
-
- <virtualhost>
- <name>localhost</name>
- <localhost>
- <store>
- <class>org.apache.qpid.server.store.MemoryMessageStore</class>
- </store>
-
- <housekeeping>
- <expiredMessageCheckPeriod>20000</expiredMessageCheckPeriod>
- </housekeeping>
-
- </localhost>
- </virtualhost>
-
- <virtualhost>
- <name>development</name>
- <development>
- <store>
- <class>org.apache.qpid.server.store.MemoryMessageStore</class>
- </store>
- </development>
- </virtualhost>
-
- <virtualhost>
- <name>test</name>
- <test>
- <store>
- <class>org.apache.qpid.server.store.MemoryMessageStore</class>
- </store>
- </test>
- </virtualhost>
-
- </virtualhosts>
- <heartbeat>
- <delay>0</delay>
- <timeoutFactor>2.0</timeoutFactor>
- </heartbeat>
- <queue>
- <auto_register>true</auto_register>
- </queue>
-
- <status-updates>ON</status-updates>
-
- <virtualhosts>${conf}/virtualhosts-systests.xml</virtualhosts>
-</broker>
-
-
diff --git a/qpid/java/broker/etc/config.xml b/qpid/java/broker/etc/config.xml
index 928b773606..8fb3a8cf5a 100644
--- a/qpid/java/broker/etc/config.xml
+++ b/qpid/java/broker/etc/config.xml
@@ -24,17 +24,20 @@
<work>${QPID_WORK}</work>
<conf>${prefix}/etc</conf>
<connector>
- <!-- Uncomment out this block and edit the keystorePath and keystorePassword
- to enable SSL support
+ <!-- To enable SSL edit the keystorePath and keystorePassword
+ and set enabled to true.
+ To disasble Non-SSL port set sslOnly to true -->
<ssl>
- <enabled>true</enabled>
- <sslOnly>true</sslOnly>
+ <enabled>false</enabled>
+ <sslOnly>false</sslOnly>
<keystorePath>/path/to/keystore.ks</keystorePath>
<keystorePassword>keystorepass</keystorePassword>
- </ssl>-->
+ </ssl>
<qpidnio>false</qpidnio>
<protectio>
<enabled>false</enabled>
+ <readBufferLimitSize>262144</readBufferLimitSize>
+ <writeBufferLimitSize>262144</writeBufferLimitSize>
</protectio>
<transport>nio</transport>
<port>5672</port>
@@ -59,6 +62,7 @@
<framesize>65535</framesize>
<compressBufferOnQueue>false</compressBufferOnQueue>
<enableJMSXUserID>false</enableJMSXUserID>
+ <locale>en_US</locale>
</advanced>
<security>
@@ -89,40 +93,143 @@
</security>
<virtualhosts>
- <directory>${conf}/virtualhosts</directory>
+ <default>test</default>
<virtualhost>
<name>localhost</name>
<localhost>
<store>
- <class>org.apache.qpid.server.store.MemoryMessageStore</class>
+ <class>org.apache.qpid.server.store.MemoryMessageStore
+ </class>
</store>
<housekeeping>
<expiredMessageCheckPeriod>20000</expiredMessageCheckPeriod>
</housekeeping>
+ <exchanges>
+ <exchange>
+ <type>direct</type>
+ <name>test.direct</name>
+ <durable>true</durable>
+ </exchange>
+ <exchange>
+ <type>topic</type>
+ <name>test.topic</name>
+ </exchange>
+ </exchanges>
+ <queues>
+ <exchange>amq.direct</exchange>
+ <maximumQueueDepth>4235264</maximumQueueDepth>
+ <!-- 4Mb -->
+ <maximumMessageSize>2117632</maximumMessageSize>
+ <!-- 2Mb -->
+ <maximumMessageAge>600000</maximumMessageAge>
+ <!-- 10 mins -->
+ <maximumMessageCount>50</maximumMessageCount>
+ <!-- 50 messages -->
+
+ <queue>
+ <name>queue</name>
+ </queue>
+ <queue>
+ <name>ping</name>
+ </queue>
+ <queue>
+ <name>test-queue</name>
+ <test-queue>
+ <exchange>test.direct</exchange>
+ <durable>true</durable>
+ </test-queue>
+ </queue>
+ <queue>
+ <name>test-ping</name>
+ <test-ping>
+ <exchange>test.direct</exchange>
+ </test-ping>
+ </queue>
+
+ </queues>
</localhost>
</virtualhost>
+
<virtualhost>
<name>development</name>
<development>
<store>
- <class>org.apache.qpid.server.store.MemoryMessageStore</class>
+ <class>org.apache.qpid.server.store.MemoryMessageStore
+ </class>
</store>
+
+ <queues>
+ <minimumAlertRepeatGap>30000</minimumAlertRepeatGap>
+ <maximumMessageCount>50</maximumMessageCount>
+ <queue>
+ <name>queue</name>
+ <queue>
+ <exchange>amq.direct</exchange>
+ <maximumQueueDepth>4235264</maximumQueueDepth>
+ <!-- 4Mb -->
+ <maximumMessageSize>2117632</maximumMessageSize>
+ <!-- 2Mb -->
+ <maximumMessageAge>600000</maximumMessageAge>
+ <!-- 10 mins -->
+ </queue>
+ </queue>
+ <queue>
+ <name>ping</name>
+ <ping>
+ <exchange>amq.direct</exchange>
+ <maximumQueueDepth>4235264</maximumQueueDepth>
+ <!-- 4Mb -->
+ <maximumMessageSize>2117632</maximumMessageSize>
+ <!-- 2Mb -->
+ <maximumMessageAge>600000</maximumMessageAge>
+ <!-- 10 mins -->
+ </ping>
+ </queue>
+ </queues>
</development>
</virtualhost>
-
<virtualhost>
<name>test</name>
<test>
<store>
- <class>org.apache.qpid.server.store.MemoryMessageStore</class>
+ <class>org.apache.qpid.server.store.MemoryMessageStore
+ </class>
</store>
+
+ <queues>
+ <minimumAlertRepeatGap>30000</minimumAlertRepeatGap>
+ <maximumMessageCount>50</maximumMessageCount>
+ <queue>
+ <name>queue</name>
+ <queue>
+ <exchange>amq.direct</exchange>
+ <maximumQueueDepth>4235264</maximumQueueDepth>
+ <!-- 4Mb -->
+ <maximumMessageSize>2117632</maximumMessageSize>
+ <!-- 2Mb -->
+ <maximumMessageAge>600000</maximumMessageAge>
+ <!-- 10 mins -->
+ </queue>
+ </queue>
+ <queue>
+ <name>ping</name>
+ <ping>
+ <exchange>amq.direct</exchange>
+ <maximumQueueDepth>4235264</maximumQueueDepth>
+ <!-- 4Mb -->
+ <maximumMessageSize>2117632</maximumMessageSize>
+ <!-- 2Mb -->
+ <maximumMessageAge>600000</maximumMessageAge>
+ <!-- 10 mins -->
+ </ping>
+ </queue>
+ </queues>
</test>
</virtualhost>
-
</virtualhosts>
<heartbeat>
<delay>0</delay>
@@ -132,7 +239,8 @@
<auto_register>true</auto_register>
</queue>
- <virtualhosts>${conf}/virtualhosts.xml</virtualhosts>
+ <status-updates>ON</status-updates>
+
</broker>
diff --git a/qpid/java/broker/etc/virtualhosts-systests.xml b/qpid/java/broker/etc/virtualhosts-systests.xml
deleted file mode 100644
index 4f23f55579..0000000000
--- a/qpid/java/broker/etc/virtualhosts-systests.xml
+++ /dev/null
@@ -1,124 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<!--
- -
- - 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.
- -
- -->
-<virtualhosts>
- <default>test</default>
- <virtualhost>
- <name>localhost</name>
- <localhost>
- <exchanges>
- <exchange>
- <type>direct</type>
- <name>test.direct</name>
- <durable>true</durable>
- </exchange>
- <exchange>
- <type>topic</type>
- <name>test.topic</name>
- </exchange>
- </exchanges>
- <queues>
- <exchange>amq.direct</exchange>
- <maximumQueueDepth>4235264</maximumQueueDepth> <!-- 4Mb -->
- <maximumMessageSize>2117632</maximumMessageSize> <!-- 2Mb -->
- <maximumMessageAge>600000</maximumMessageAge> <!-- 10 mins -->
- <maximumMessageCount>50</maximumMessageCount> <!-- 50 messages -->
-
- <queue>
- <name>queue</name>
- </queue>
- <queue>
- <name>ping</name>
- </queue>
- <queue>
- <name>test-queue</name>
- <test-queue>
- <exchange>test.direct</exchange>
- <durable>true</durable>
- </test-queue>
- </queue>
- <queue>
- <name>test-ping</name>
- <test-ping>
- <exchange>test.direct</exchange>
- </test-ping>
- </queue>
-
- </queues>
- </localhost>
- </virtualhost>
-
-
- <virtualhost>
- <name>development</name>
- <development>
- <queues>
- <minimumAlertRepeatGap>30000</minimumAlertRepeatGap>
- <maximumMessageCount>50</maximumMessageCount>
- <queue>
- <name>queue</name>
- <queue>
- <exchange>amq.direct</exchange>
- <maximumQueueDepth>4235264</maximumQueueDepth> <!-- 4Mb -->
- <maximumMessageSize>2117632</maximumMessageSize> <!-- 2Mb -->
- <maximumMessageAge>600000</maximumMessageAge> <!-- 10 mins -->
- </queue>
- </queue>
- <queue>
- <name>ping</name>
- <ping>
- <exchange>amq.direct</exchange>
- <maximumQueueDepth>4235264</maximumQueueDepth> <!-- 4Mb -->
- <maximumMessageSize>2117632</maximumMessageSize> <!-- 2Mb -->
- <maximumMessageAge>600000</maximumMessageAge> <!-- 10 mins -->
- </ping>
- </queue>
- </queues>
- </development>
- </virtualhost>
- <virtualhost>
- <name>test</name>
- <test>
- <queues>
- <minimumAlertRepeatGap>30000</minimumAlertRepeatGap>
- <maximumMessageCount>50</maximumMessageCount>
- <queue>
- <name>queue</name>
- <queue>
- <exchange>amq.direct</exchange>
- <maximumQueueDepth>4235264</maximumQueueDepth> <!-- 4Mb -->
- <maximumMessageSize>2117632</maximumMessageSize> <!-- 2Mb -->
- <maximumMessageAge>600000</maximumMessageAge> <!-- 10 mins -->
- </queue>
- </queue>
- <queue>
- <name>ping</name>
- <ping>
- <exchange>amq.direct</exchange>
- <maximumQueueDepth>4235264</maximumQueueDepth> <!-- 4Mb -->
- <maximumMessageSize>2117632</maximumMessageSize> <!-- 2Mb -->
- <maximumMessageAge>600000</maximumMessageAge> <!-- 10 mins -->
- </ping>
- </queue>
- </queues>
- </test>
- </virtualhost>
-</virtualhosts>
diff --git a/qpid/java/broker/etc/virtualhosts.xml b/qpid/java/broker/etc/virtualhosts.xml
deleted file mode 100644
index f62ec3f5d7..0000000000
--- a/qpid/java/broker/etc/virtualhosts.xml
+++ /dev/null
@@ -1,123 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<!--
- -
- - 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.
- -
- -->
-<virtualhosts>
- <default>test</default>
- <virtualhost>
- <name>localhost</name>
- <localhost>
- <exchanges>
- <exchange>
- <type>direct</type>
- <name>test.direct</name>
- <durable>true</durable>
- </exchange>
- <exchange>
- <type>topic</type>
- <name>test.topic</name>
- </exchange>
- </exchanges>
- <queues>
- <exchange>amq.direct</exchange>
- <maximumQueueDepth>4235264</maximumQueueDepth> <!-- 4Mb -->
- <maximumMessageSize>2117632</maximumMessageSize> <!-- 2Mb -->
- <maximumMessageAge>600000</maximumMessageAge> <!-- 10 mins -->
-
- <queue>
- <name>queue</name>
- </queue>
- <queue>
- <name>ping</name>
- </queue>
- <queue>
- <name>test-queue</name>
- <test-queue>
- <exchange>test.direct</exchange>
- <durable>true</durable>
- </test-queue>
- </queue>
- <queue>
- <name>test-ping</name>
- <test-ping>
- <exchange>test.direct</exchange>
- </test-ping>
- </queue>
-
- </queues>
- </localhost>
- </virtualhost>
-
-
- <virtualhost>
- <name>development</name>
- <development>
- <queues>
- <minimumAlertRepeatGap>30000</minimumAlertRepeatGap>
- <maximumMessageCount>5000</maximumMessageCount>
- <queue>
- <name>queue</name>
- <queue>
- <exchange>amq.direct</exchange>
- <maximumQueueDepth>4235264</maximumQueueDepth> <!-- 4Mb -->
- <maximumMessageSize>2117632</maximumMessageSize> <!-- 2Mb -->
- <maximumMessageAge>600000</maximumMessageAge> <!-- 10 mins -->
- </queue>
- </queue>
- <queue>
- <name>ping</name>
- <ping>
- <exchange>amq.direct</exchange>
- <maximumQueueDepth>4235264</maximumQueueDepth> <!-- 4Mb -->
- <maximumMessageSize>2117632</maximumMessageSize> <!-- 2Mb -->
- <maximumMessageAge>600000</maximumMessageAge> <!-- 10 mins -->
- </ping>
- </queue>
- </queues>
- </development>
- </virtualhost>
- <virtualhost>
- <name>test</name>
- <test>
- <queues>
- <minimumAlertRepeatGap>30000</minimumAlertRepeatGap>
- <maximumMessageCount>5000</maximumMessageCount>
- <queue>
- <name>queue</name>
- <queue>
- <exchange>amq.direct</exchange>
- <maximumQueueDepth>4235264</maximumQueueDepth> <!-- 4Mb -->
- <maximumMessageSize>2117632</maximumMessageSize> <!-- 2Mb -->
- <maximumMessageAge>600000</maximumMessageAge> <!-- 10 mins -->
- </queue>
- </queue>
- <queue>
- <name>ping</name>
- <ping>
- <exchange>amq.direct</exchange>
- <maximumQueueDepth>4235264</maximumQueueDepth> <!-- 4Mb -->
- <maximumMessageSize>2117632</maximumMessageSize> <!-- 2Mb -->
- <maximumMessageAge>600000</maximumMessageAge> <!-- 10 mins -->
- </ping>
- </queue>
- </queues>
- </test>
- </virtualhost>
-</virtualhosts>
diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/AMQBrokerManagerMBean.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/AMQBrokerManagerMBean.java
index 2afd3c1dc3..5cfa8066e5 100644
--- a/qpid/java/broker/src/main/java/org/apache/qpid/server/AMQBrokerManagerMBean.java
+++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/AMQBrokerManagerMBean.java
@@ -317,8 +317,10 @@ public class AMQBrokerManagerMBean extends AMQManagedObject implements ManagedBr
try
{
queue.delete();
- _messageStore.removeQueue(queue);
-
+ if (queue.isDurable())
+ {
+ _messageStore.removeQueue(queue);
+ }
}
catch (AMQException ex)
{
diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ServerConfiguration.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ServerConfiguration.java
index b3c8975c7c..a72c2889d1 100644
--- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ServerConfiguration.java
+++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ServerConfiguration.java
@@ -148,32 +148,27 @@ public class ServerConfiguration implements SignalHandler
Object thing = i.next();
if (thing instanceof String)
{
+ //Open the Virtualhost.xml file and copy values in to main config
XMLConfiguration vhostConfiguration = new XMLConfiguration((String) thing);
- List hosts = vhostConfiguration.getList("virtualhost.name");
- for (int j = 0; j < hosts.size(); j++)
- {
- String name = (String) hosts.get(j);
- // Add the keys of the virtual host to the main config then bail out
-
- Configuration myConf = vhostConfiguration.subset("virtualhost." + name);
- Iterator k = myConf.getKeys();
- while (k.hasNext())
- {
- String key = (String) k.next();
- conf.setProperty("virtualhosts.virtualhost."+name+"."+key, myConf.getProperty(key));
- }
- VirtualHostConfiguration vhostConfig = new VirtualHostConfiguration(name, conf.subset("virtualhosts.virtualhost."+name));
- _virtualHosts.put(vhostConfig.getName(), vhostConfig);
- }
- // Grab things other than the virtualhosts themselves
Iterator keys = vhostConfiguration.getKeys();
while (keys.hasNext())
{
String key = (String) keys.next();
- conf.setProperty("virtualhosts."+key, vhostConfiguration.getProperty(key));
+ conf.setProperty("virtualhosts." + key, vhostConfiguration.getProperty(key));
}
}
}
+
+ List hosts = conf.getList("virtualhosts.virtualhost.name");
+ for (int j = 0; j < hosts.size(); j++)
+ {
+ String name = (String) hosts.get(j);
+ // Add the keys of the virtual host to the main config then bail out
+
+ VirtualHostConfiguration vhostConfig = new VirtualHostConfiguration(name, conf.subset("virtualhosts.virtualhost." + name));
+ _virtualHosts.put(vhostConfig.getName(), vhostConfig);
+ }
+
}
private void substituteEnvironmentVariables()
@@ -203,7 +198,7 @@ public class ServerConfiguration implements SignalHandler
}
/**
- * Check the configuration file to see if status updates are enabled.
+ * Check the configuration file to see if status updates are enabled.
* @return true if status updates are enabled
*/
public boolean getStatusUpdatesEnabled()
@@ -467,7 +462,7 @@ public class ServerConfiguration implements SignalHandler
{
return getConfig().getBoolean("management.enabled", true);
}
-
+
public void setManagementEnabled(boolean enabled)
{
getConfig().setProperty("management.enabled", enabled);
diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHost.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHost.java
index aec437b700..3b776a62b4 100644
--- a/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHost.java
+++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHost.java
@@ -195,10 +195,22 @@ public class VirtualHost implements Accessable
// perform a createExchange twice with the same details in the
// MessageStore(RoutingTable) as some instances may not like that.
// Derby being one.
+ // todo this can be removed with the resolution fo QPID-2096
configFileRT.exchange.clear();
initialiseModel(hostConfig);
+ //todo REMOVE Work Around for QPID-2096
+ // This means that all durable exchanges declared in the configuration
+ // will not be stored in the MessageStore.
+ // They will still be created/registered/available on startup for as
+ // long as they are contained in the configuration. However, when they
+ // are removed from the configuration they will no longer exist.
+ // This differs from durable queues as they will be writen to to the
+ // store. After QPID-2096 has been resolved exchanges will mirror that
+ // functionality.
+ configFileRT.exchange.clear();
+
if (store != null)
{
_messageStore = store;
diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/ServerConfigurationTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/ServerConfigurationTest.java
index 2285f5256e..93e7e756e6 100644
--- a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/ServerConfigurationTest.java
+++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/ServerConfigurationTest.java
@@ -54,7 +54,7 @@ public class ServerConfigurationTest extends TestCase
_config = new XMLConfiguration();
}
-
+
@Override
public void tearDown() throws Exception
{
@@ -727,7 +727,7 @@ public class ServerConfigurationTest extends TestCase
assertEquals(true, config.getQpidNIO()); // From the second file, not
// present in the first
}
-
+
public void testVariableInterpolation() throws Exception
{
File mainFile = File.createTempFile(getClass().getName(), null);
@@ -742,7 +742,7 @@ public class ServerConfigurationTest extends TestCase
out.close();
ServerConfiguration config = new ServerConfiguration(mainFile.getAbsoluteFile());
- assertEquals("Did not get correct interpolated value",
+ assertEquals("Did not get correct interpolated value",
"foo", config.getManagementKeyStorePath());
}
@@ -783,7 +783,7 @@ public class ServerConfigurationTest extends TestCase
out.write("\t</virtualhosts>\n");
out.write("</broker>\n");
out.close();
-
+
// Load config
ApplicationRegistry reg = new ConfigurationFileApplicationRegistry(mainFile);
ApplicationRegistry.initialise(reg, 1);
@@ -791,18 +791,18 @@ public class ServerConfigurationTest extends TestCase
// Test config
VirtualHostRegistry virtualHostRegistry = reg.getVirtualHostRegistry();
VirtualHost virtualHost = virtualHostRegistry.getVirtualHost("test");
-
+
TestNetworkDriver testDriver = new TestNetworkDriver();
testDriver.setRemoteAddress("127.0.0.1");
AMQProtocolEngine session = new AMQProtocolEngine(virtualHostRegistry, testDriver);
assertFalse(reg.getAccessManager().authoriseConnect(session, virtualHost));
-
+
testDriver.setRemoteAddress("127.1.2.3");
session = new AMQProtocolEngine(virtualHostRegistry, testDriver);
assertTrue(reg.getAccessManager().authoriseConnect(session, virtualHost));
}
-
+
public void testCombinedConfigurationFirewall() throws Exception
{
// Write out config
@@ -868,7 +868,7 @@ public class ServerConfigurationTest extends TestCase
TestNetworkDriver testDriver = new TestNetworkDriver();
testDriver.setRemoteAddress("127.0.0.1");
-
+
AMQProtocolEngine session = new AMQProtocolEngine(virtualHostRegistry, testDriver);
session.setNetworkDriver(testDriver);
assertFalse(reg.getAccessManager().authoriseConnect(session, virtualHost));
@@ -945,22 +945,22 @@ public class ServerConfigurationTest extends TestCase
fileBRandom.setLength(0);
fileBRandom.seek(0);
fileBRandom.close();
-
+
out = new FileWriter(fileB);
out.write("<firewall>\n");
out.write("\t<rule access=\"allow\" network=\"127.0.0.1\"/>");
out.write("</firewall>\n");
out.close();
-
+
reg.getConfiguration().reparseConfigFile();
-
+
assertTrue(reg.getAccessManager().authoriseConnect(session, virtualHost));
-
+
fileBRandom = new RandomAccessFile(fileB, "rw");
fileBRandom.setLength(0);
fileBRandom.seek(0);
fileBRandom.close();
-
+
out = new FileWriter(fileB);
out.write("<firewall>\n");
out.write("\t<rule access=\"deny\" network=\"127.0.0.1\"/>");
@@ -968,17 +968,17 @@ public class ServerConfigurationTest extends TestCase
out.close();
reg.getConfiguration().reparseConfigFile();
-
+
assertFalse(reg.getAccessManager().authoriseConnect(session, virtualHost));
}
public void testnewParserOutputVsOldParserOutput() throws ConfigurationException
{
String configDir = System.getProperty("QPID_HOME")+"/etc";
-
- XMLConfiguration oldConfig = new XMLConfiguration(configDir +"/sample-parsed-config.xml");
- Configuration newConfig = new ServerConfiguration(new File(configDir+"/persistent_config-config-test.xml")).getConfig();
-
+
+ XMLConfiguration oldConfig = new XMLConfiguration(configDir +"/config-systests-ServerConfigurationTest-Old.xml");
+ Configuration newConfig = new ServerConfiguration(new File(configDir+"/config-systests-ServerConfigurationTest-New.xml")).getConfig();
+
Iterator xmlKeys = oldConfig.getKeys();
while (xmlKeys.hasNext())
{
@@ -986,6 +986,21 @@ public class ServerConfigurationTest extends TestCase
assertEquals("Incorrect value for "+key, oldConfig.getProperty(key), newConfig.getProperty(key));
}
}
-
-
+
+
+ public void testNoVirtualhostXMLFile() throws Exception
+ {
+ int REGISTRY=1;
+
+ File configFile = new File(System.getProperty("QPID_HOME")+"/etc/config.xml");
+ assertTrue(configFile.exists());
+
+ ApplicationRegistry.initialise(new ConfigurationFileApplicationRegistry(configFile), REGISTRY);
+
+ VirtualHostRegistry virtualHostRegistry = ApplicationRegistry.getInstance(REGISTRY).getVirtualHostRegistry();
+
+ assertEquals("Incorrect virtualhost count", 3 , virtualHostRegistry.getVirtualHosts().size());
+ }
+
+
}
diff --git a/qpid/java/broker/etc/persistent_config-config-test.xml b/qpid/java/systests/etc/config-systests-ServerConfigurationTest-New.xml
index 258f54397d..33cc90b895 100644
--- a/qpid/java/broker/etc/persistent_config-config-test.xml
+++ b/qpid/java/systests/etc/config-systests-ServerConfigurationTest-New.xml
@@ -87,7 +87,7 @@
<auto_register>true</auto_register>
</queue>
- <virtualhosts>${conf}/virtualhosts-config-test.xml</virtualhosts>
+ <virtualhosts>${conf}/virtualhosts-ServerConfigurationTest-New.xml</virtualhosts>
</broker>
diff --git a/qpid/java/broker/etc/sample-parsed-config.xml b/qpid/java/systests/etc/config-systests-ServerConfigurationTest-Old.xml
index 37dfae4d2e..67e0702c41 100644
--- a/qpid/java/broker/etc/sample-parsed-config.xml
+++ b/qpid/java/systests/etc/config-systests-ServerConfigurationTest-Old.xml
@@ -41,7 +41,7 @@
<principal-database>passwordfile</principal-database>
</jmx>
</security>
-<virtualhosts>${conf}/virtualhosts-config-test.xml
+<virtualhosts>${conf}/virtualhosts-ServerConfigurationTest-New.xml
<default>dev-only</default>
<virtualhost>
<name>dev-only</name>
diff --git a/qpid/java/broker/etc/acl.config.xml b/qpid/java/systests/etc/config-systests-acl-settings.xml
index a2b723fc63..c5374a5c5e 100644
--- a/qpid/java/broker/etc/acl.config.xml
+++ b/qpid/java/systests/etc/config-systests-acl-settings.xml
@@ -20,76 +20,12 @@
-
-->
<broker>
- <prefix>${QPID_HOME}</prefix>
- <work>${QPID_WORK}</work>
- <conf>${prefix}/etc</conf>
- <connector>
- <!-- Uncomment out this block and edit the keystorePath and keystorePassword
- to enable SSL support
- <ssl>
- <enabled>true</enabled>
- <sslOnly>true</sslOnly>
- <keystorePath>/path/to/keystore.ks</keystorePath>
- <keystorePassword>keystorepass</keystorePassword>
- </ssl>-->
- <qpidnio>false</qpidnio>
- <!-- I've had the 0.0 and 0.1 Reader threads continually throwing IOException when client closes-->
- <protectio>false</protectio>
- <transport>nio</transport>
- <port>5672</port>
- <sslport>8672</sslport>
- <socketReceiveBuffer>32768</socketReceiveBuffer>
- <socketSendBuffer>32768</socketSendBuffer>
- </connector>
- <management>
- <enabled>false</enabled>
- <jmxport>8999</jmxport>
- <security-enabled>false</security-enabled>
- </management>
- <advanced>
- <filterchain enableExecutorPool="true"/>
- <enablePooledAllocator>false</enablePooledAllocator>
- <enableDirectBuffers>false</enableDirectBuffers>
- <framesize>65535</framesize>
- <compressBufferOnQueue>false</compressBufferOnQueue>
- <enableJMSXUserID>false</enableJMSXUserID>
- </advanced>
-
- <security>
- <principal-databases>
- <!-- Example use of Base64 encoded MD5 hashes for authentication via CRAM-MD5-Hashed -->
- <principal-database>
- <name>passwordfile</name>
- <class>org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase</class>
- <attributes>
- <attribute>
- <name>passwordFile</name>
- <value>${conf}/passwd</value>
- </attribute>
- </attributes>
- </principal-database>
- </principal-databases>
-
- <access>
- <class>org.apache.qpid.server.security.access.plugins.DenyAll</class>
- </access>
-
- <jmx>
- <access>${conf}/jmxremote.access</access>
- <principal-database>passwordfile</principal-database>
- </jmx>
- </security>
<virtualhosts>
- <directory>${conf}/virtualhosts</directory>
<virtualhost>
<name>test</name>
<test>
- <store>
- <class>org.apache.qpid.server.store.MemoryMessageStore</class>
- </store>
-
<queues>
<exchange>amq.direct</exchange>
<!-- 4Mb -->
@@ -197,34 +133,7 @@
</security>
</test>
</virtualhost>
-
-
- <virtualhost>
- <name>development</name>
- <development>
- <store>
- <class>org.apache.qpid.server.store.MemoryMessageStore</class>
- </store>
- </development>
- </virtualhost>
-
- <virtualhost>
- <name>localhost</name>
- <localhost>
- <store>
- <class>org.apache.qpid.server.store.MemoryMessageStore</class>
- </store>
- </localhost>
- </virtualhost>
-
</virtualhosts>
-
- <heartbeat>
- <delay>0</delay>
- <timeoutFactor>2.0</timeoutFactor>
- </heartbeat>
-
- <virtualhosts>${conf}/virtualhosts.xml</virtualhosts>
</broker>
diff --git a/qpid/java/systests/etc/config-systests-acl.xml b/qpid/java/systests/etc/config-systests-acl.xml
new file mode 100644
index 0000000000..34104dbe6b
--- /dev/null
+++ b/qpid/java/systests/etc/config-systests-acl.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!--
+ -
+ - 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.
+ -
+ -->
+<configuration>
+ <system/>
+ <override>
+ <xml fileName="${test.config}" config-optional="true"/>
+ <xml fileName="${QPID_HOME}/etc/config-systests-acl-settings.xml"/>
+ <xml fileName="${QPID_HOME}/etc/config-systests-settings.xml"/>
+ <xml fileName="${QPID_HOME}/etc/config.xml"/>
+ </override>
+</configuration>
diff --git a/qpid/java/systests/etc/config-systests-derby-settings.xml b/qpid/java/systests/etc/config-systests-derby-settings.xml
new file mode 100644
index 0000000000..9c25b5682e
--- /dev/null
+++ b/qpid/java/systests/etc/config-systests-derby-settings.xml
@@ -0,0 +1,64 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!--
+ -
+ - 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.
+ -
+ -->
+<broker>
+ <virtualhosts>
+ <directory>${conf}/virtualhosts</directory>
+
+ <virtualhost>
+ <name>localhost</name>
+ <localhost>
+ <store>
+ <class>org.apache.qpid.server.store.DerbyMessageStore</class>
+ <environment-path>${work}/derbyDB/localhost-store</environment-path>
+ </store>
+
+ <housekeeping>
+ <expiredMessageCheckPeriod>20000</expiredMessageCheckPeriod>
+ </housekeeping>
+
+ </localhost>
+ </virtualhost>
+
+ <virtualhost>
+ <name>development</name>
+ <development>
+ <store>
+ <class>org.apache.qpid.server.store.DerbyMessageStore</class>
+ <environment-path>${work}/derbyDB/development-store</environment-path>
+ </store>
+ </development>
+ </virtualhost>
+
+ <virtualhost>
+ <name>test</name>
+ <test>
+ <store>
+ <class>org.apache.qpid.server.store.DerbyMessageStore</class>
+ <environment-path>${work}/derbyDB/test-store</environment-path>
+ </store>
+ </test>
+ </virtualhost>
+
+ </virtualhosts>
+</broker>
+
+
diff --git a/qpid/java/systests/etc/config-systests-derby.xml b/qpid/java/systests/etc/config-systests-derby.xml
new file mode 100644
index 0000000000..18ba0c4ad9
--- /dev/null
+++ b/qpid/java/systests/etc/config-systests-derby.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!--
+ -
+ - 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.
+ -
+ -->
+<configuration>
+ <system/>
+ <override>
+ <xml fileName="${test.config}" config-optional="true"/>
+ <xml fileName="${QPID_HOME}/etc/config-systests-derby-settings.xml"/>
+ <xml fileName="${QPID_HOME}/etc/config-systests-settings.xml"/>
+ <xml fileName="${QPID_HOME}/etc/config.xml"/>
+ </override>
+</configuration>
diff --git a/qpid/java/systests/etc/config-systests-settings.xml b/qpid/java/systests/etc/config-systests-settings.xml
new file mode 100644
index 0000000000..4e9c863fda
--- /dev/null
+++ b/qpid/java/systests/etc/config-systests-settings.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!--
+ -
+ - 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.
+ -
+ -->
+<broker>
+ <management>
+ <enabled>false</enabled>
+ <ssl>
+ <enabled>false</enabled>
+ </ssl>
+ </management>
+</broker>
diff --git a/qpid/java/systests/etc/config-systests.xml b/qpid/java/systests/etc/config-systests.xml
new file mode 100644
index 0000000000..290c082a4f
--- /dev/null
+++ b/qpid/java/systests/etc/config-systests.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!--
+ -
+ - 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.
+ -
+ -->
+<configuration>
+ <system/>
+ <override>
+ <xml fileName="${test.config}" config-optional="true"/>
+ <xml fileName="${QPID_HOME}/etc/config-systests-settings.xml"/>
+ <xml fileName="${QPID_HOME}/etc/config.xml"/>
+ </override>
+</configuration>
diff --git a/qpid/java/broker/etc/virtualhosts-config-test.xml b/qpid/java/systests/etc/virtualhosts-ServerConfigurationTest-New.xml
index 168aa074da..168aa074da 100644
--- a/qpid/java/broker/etc/virtualhosts-config-test.xml
+++ b/qpid/java/systests/etc/virtualhosts-ServerConfigurationTest-New.xml
diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/management/jmx/ManagementActorLoggingTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/management/jmx/ManagementActorLoggingTest.java
index b4ba6e8156..2e107ada34 100644
--- a/qpid/java/systests/src/main/java/org/apache/qpid/management/jmx/ManagementActorLoggingTest.java
+++ b/qpid/java/systests/src/main/java/org/apache/qpid/management/jmx/ManagementActorLoggingTest.java
@@ -20,26 +20,19 @@
*/
package org.apache.qpid.management.jmx;
-import org.apache.qpid.commands.objects.AllObjects;
-import org.apache.qpid.management.common.JMXConnnectionFactory;
import org.apache.qpid.management.common.mbeans.ManagedBroker;
import org.apache.qpid.management.common.mbeans.ManagedConnection;
import org.apache.qpid.management.common.mbeans.ManagedExchange;
import org.apache.qpid.server.logging.AbstractTestLogging;
import org.apache.qpid.server.logging.subjects.AbstractTestLogSubject;
+import org.apache.qpid.test.utils.JMXTestUtils;
import javax.jms.Connection;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.management.JMException;
-import javax.management.MBeanException;
-import javax.management.MBeanServerConnection;
-import javax.management.MBeanServerInvocationHandler;
-import javax.management.ObjectName;
-import javax.management.remote.JMXConnector;
import java.io.IOException;
import java.util.List;
-import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -50,33 +43,21 @@ import java.util.concurrent.TimeUnit;
*/
public class ManagementActorLoggingTest extends AbstractTestLogging
{
- MBeanServerConnection _mbsc;
- JMXConnector _jmxc;
+ private JMXTestUtils _jmxUtils;
private static final String USER = "admin";
@Override
public void setUp() throws Exception
{
- setConfigurationProperty("management.enabled", "true");
+ _jmxUtils = new JMXTestUtils(this, USER, USER);
+ _jmxUtils.setUp();
super.setUp();
-
- if (isExternalBroker())
- {
- _jmxc = JMXConnnectionFactory.getJMXConnection(
- 5000, "127.0.0.1",
- getManagementPort(getPort()), USER, USER);
-
- _mbsc = _jmxc.getMBeanServerConnection();
- }
}
@Override
public void tearDown() throws Exception
{
- if (isExternalBroker())
- {
- _jmxc.close();
- }
+ _jmxUtils.close();
super.tearDown();
}
@@ -107,34 +88,31 @@ public class ManagementActorLoggingTest extends AbstractTestLogging
*/
public void testJMXManagementConsoleConnection() throws IOException
{
- if (isExternalBroker())
- {
- List<String> results = _monitor.findMatches("MNG-1007");
+ List<String> results = _monitor.findMatches("MNG-1007");
- assertEquals("Unexpected Management Connection count", 1, results.size());
+ assertEquals("Unexpected Management Connection count", 1, results.size());
- String log = getLog(results.get(0));
+ String log = getLog(results.get(0));
- validateMessageID("MNG-1007", log);
+ validateMessageID("MNG-1007", log);
- assertTrue("User not in log message:" + log, log.endsWith(USER));
- // Extract the id from the log string
- // MESSAGE [mng:1(rmi://169.24.29.116)] MNG-1007 : Open : User admin
- int connectionID = Integer.parseInt(fromActor(getLog(results.get(0))).charAt(4) + "");
+ assertTrue("User not in log message:" + log, log.endsWith(USER));
+ // Extract the id from the log string
+ // MESSAGE [mng:1(rmi://169.24.29.116)] MNG-1007 : Open : User admin
+ int connectionID = Integer.parseInt(fromActor(getLog(results.get(0))).charAt(4) + "");
- results = _monitor.findMatches("MNG-1008");
+ results = _monitor.findMatches("MNG-1008");
- assertEquals("Unexpected Management Connection close count", 0, results.size());
+ assertEquals("Unexpected Management Connection close count", 0, results.size());
- _jmxc.close();
+ _jmxUtils.close();
- results = _monitor.findMatches("MNG-1008");
+ results = _monitor.findMatches("MNG-1008");
- assertEquals("Unexpected Management Connection count", 1, results.size());
+ assertEquals("Unexpected Management Connection count", 1, results.size());
- assertEquals("Close does not have same id as open,", connectionID,
- Integer.parseInt(fromActor(getLog(results.get(0))).charAt(4) + ""));
- }
+ assertEquals("Close does not have same id as open,", connectionID,
+ Integer.parseInt(fromActor(getLog(results.get(0))).charAt(4) + ""));
}
/**
@@ -159,56 +137,40 @@ public class ManagementActorLoggingTest extends AbstractTestLogging
*/
public void testConnectionCloseViaManagement() throws IOException, Exception
{
- if (isExternalBroker())
+ //Create a connection to the broker
+ Connection connection = getConnection();
+
+ // Monitor the connection for an exception being thrown
+ // this should be a DisconnectionException but it is not this tests
+ // job to valiate that. Only use the exception as a synchronisation
+ // to check the log file for the Close message
+ final CountDownLatch exceptionReceived = new CountDownLatch(1);
+ connection.setExceptionListener(new ExceptionListener()
{
-
- //Create a connection to the broker
- Connection connection = getConnection();
-
- // Monitor the connection for an exception being thrown
- // this should be a DisconnectionException but it is not this tests
- // job to valiate that. Only use the exception as a synchronisation
- // to check the log file for the Close message
- final CountDownLatch exceptionReceived = new CountDownLatch(1);
- connection.setExceptionListener(new ExceptionListener()
+ public void onException(JMSException e)
{
- public void onException(JMSException e)
- {
- //Failover being attempted.
- exceptionReceived.countDown();
- }
- });
-
- //Remove the connection close from any 0-10 connections
- _monitor.reset();
+ //Failover being attempted.
+ exceptionReceived.countDown();
+ }
+ });
- // Get all active AMQP connections
- AllObjects allObject = new AllObjects(_mbsc);
- allObject.querystring = "org.apache.qpid:type=VirtualHost.Connection,*";
+ //Remove the connection close from any 0-10 connections
+ _monitor.reset();
- Set<ObjectName> objectNames = allObject.returnObjects();
+ // Get a managedConnection
+ ManagedConnection mangedConnection = _jmxUtils.getManagedObject(ManagedConnection.class, "org.apache.qpid:type=VirtualHost.Connection,*");
- assertEquals("More than one test connection returned", 1, objectNames.size());
+ //Close the connection
+ mangedConnection.closeConnection();
- ObjectName connectionName = objectNames.iterator().next();
+ //Wait for the connection to close
+ assertTrue("Timed out waiting for conneciton to report close",
+ exceptionReceived.await(2, TimeUnit.SECONDS));
- ManagedConnection mangedConnection = MBeanServerInvocationHandler.
- newProxyInstance(_mbsc, connectionName,
- ManagedConnection.class, false);
+ //Validate results
+ List<String> results = _monitor.findMatches("CON-1002");
-
- //Close the connection
- mangedConnection.closeConnection();
-
- //Wait for the connection to close
- assertTrue("Timed out waiting for conneciton to report close",
- exceptionReceived.await(2, TimeUnit.SECONDS));
-
- //Validate results
- List<String> results = _monitor.findMatches("CON-1002");
-
- assertEquals("Unexpected Connection Close count", 1, results.size());
- }
+ assertEquals("Unexpected Connection Close count", 1, results.size());
}
/**
@@ -234,114 +196,100 @@ public class ManagementActorLoggingTest extends AbstractTestLogging
*/
public void testCreateExchangeDirectTransientViaManagementConsole() throws IOException, JMException
{
- if (isExternalBroker())
- {
- //Remove any previous exchange declares
- _monitor.reset();
-
- createExchange("direct");
+ _monitor.reset();
- // Validate
+ _jmxUtils.createExchange("test", "direct", null, false);
- //1 - ID is correct
- List<String> results = _monitor.findMatches("EXH-1001");
+ // Validate
- assertEquals("More than one exchange creation found", 1, results.size());
+ //1 - ID is correct
+ List<String> results = _monitor.findMatches("EXH-1001");
- String log = getLog(results.get(0));
+ assertEquals("More than one exchange creation found", 1, results.size());
- // Validate correct exchange name
- assertTrue("Incorrect exchange name created:" + log, log.endsWith(getName()));
+ String log = getLog(results.get(0));
- // Validate it was a management actor.
- String actor = fromActor(log);
- assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
+ // Validate correct exchange name
+ assertTrue("Incorrect exchange name created:" + log, log.endsWith(getName()));
- }
+ // Validate it was a management actor.
+ String actor = fromActor(log);
+ assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
}
public void testCreateExchangeTopicTransientViaManagementConsole() throws IOException, JMException
{
- if (isExternalBroker())
- {
- //Remove any previous exchange declares
- _monitor.reset();
+ //Remove any previous exchange declares
+ _monitor.reset();
- createExchange("topic");
+ _jmxUtils.createExchange("test", "topic", null, false);
- // Validate
+ // Validate
- //1 - ID is correct
- List<String> results = _monitor.findMatches("EXH-1001");
+ //1 - ID is correct
+ List<String> results = _monitor.findMatches("EXH-1001");
- assertEquals("More than one exchange creation found", 1, results.size());
+ assertEquals("More than one exchange creation found", 1, results.size());
- String log = getLog(results.get(0));
+ String log = getLog(results.get(0));
- // Validate correct exchange name
- assertTrue("Incorrect exchange name created:" + log, log.endsWith(getName()));
+ // Validate correct exchange name
+ assertTrue("Incorrect exchange name created:" + log, log.endsWith(getName()));
- // Validate it was a management actor.
- String actor = fromActor(log);
- assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
+ // Validate it was a management actor.
+ String actor = fromActor(log);
+ assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
- }
}
public void testCreateExchangeFanoutTransientViaManagementConsole() throws IOException, JMException
{
- if (isExternalBroker())
- {
- //Remove any previous exchange declares
- _monitor.reset();
+ //Remove any previous exchange declares
+ _monitor.reset();
- createExchange("fanout");
+ _jmxUtils.createExchange("test", "fanout", null, false);
- // Validate
+ // Validate
- //1 - ID is correct
- List<String> results = _monitor.findMatches("EXH-1001");
+ //1 - ID is correct
+ List<String> results = _monitor.findMatches("EXH-1001");
- assertEquals("More than one exchange creation found", 1, results.size());
+ assertEquals("More than one exchange creation found", 1, results.size());
- String log = getLog(results.get(0));
+ String log = getLog(results.get(0));
- // Validate correct exchange name
- assertTrue("Incorrect exchange name created:" + log, log.endsWith(getName()));
+ // Validate correct exchange name
+ assertTrue("Incorrect exchange name created:" + log, log.endsWith(getName()));
- // Validate it was a management actor.
- String actor = fromActor(log);
- assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
+ // Validate it was a management actor.
+ String actor = fromActor(log);
+ assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
- }
}
public void testCreateExchangeHeadersTransientViaManagementConsole() throws IOException, JMException
{
- if (isExternalBroker())
- {
- //Remove any previous exchange declares
- _monitor.reset();
+ //Remove any previous exchange declares
+ _monitor.reset();
- createExchange("headers");
+ _jmxUtils.createExchange("test", "headers", null, false);
- // Validate
+ // Validate
- //1 - ID is correct
- List<String> results = _monitor.findMatches("EXH-1001");
+ //1 - ID is correct
+ List<String> results = _monitor.findMatches("EXH-1001");
- assertEquals("More than one exchange creation found", 1, results.size());
+ assertEquals("More than one exchange creation found", 1, results.size());
- String log = getLog(results.get(0));
+ String log = getLog(results.get(0));
- // Validate correct exchange name
- assertTrue("Incorrect exchange name created:" + log, log.endsWith(getName()));
+ // Validate correct exchange name
+ assertTrue("Incorrect exchange name created:" + log, log.endsWith(getName()));
- // Validate it was a management actor.
- String actor = fromActor(log);
- assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
+ // Validate it was a management actor.
+ String actor = fromActor(log);
+ assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
- }
}
/**
@@ -365,29 +313,26 @@ public class ManagementActorLoggingTest extends AbstractTestLogging
*/
public void testCreateQueueTransientViaManagementConsole() throws IOException, JMException
{
- if (isExternalBroker())
- {
- //Remove any previous queue declares
- _monitor.reset();
+ //Remove any previous queue declares
+ _monitor.reset();
- createQueue();
+ _jmxUtils.createQueue("test", getName(), null, false);
- // Validate
+ // Validate
- List<String> results = _monitor.findMatches("QUE-1001");
+ List<String> results = _monitor.findMatches("QUE-1001");
- assertEquals("More than one queue creation found", 1, results.size());
+ assertEquals("More than one queue creation found", 1, results.size());
- String log = getLog(results.get(0));
+ String log = getLog(results.get(0));
- // Validate correct queue name
- String subject = fromSubject(log);
- assertEquals("Incorrect queue name created", getName(), AbstractTestLogSubject.getSlice("qu", subject));
+ // Validate correct queue name
+ String subject = fromSubject(log);
+ assertEquals("Incorrect queue name created", getName(), AbstractTestLogSubject.getSlice("qu", subject));
- // Validate it was a management actor.
- String actor = fromActor(log);
- assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
- }
+ // Validate it was a management actor.
+ String actor = fromActor(log);
+ assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
}
/**
@@ -411,34 +356,29 @@ public class ManagementActorLoggingTest extends AbstractTestLogging
*/
public void testQueueDeleteViaManagementConsole() throws IOException, JMException
{
- if (isExternalBroker())
- {
- //Remove any previous queue declares
- _monitor.reset();
+ //Remove any previous queue declares
+ _monitor.reset();
- createQueue();
+ _jmxUtils.createQueue("test", getName(), null, false);
- ManagedBroker managedBroker = MBeanServerInvocationHandler.
- newProxyInstance(_mbsc, getVirtualHostManagerObjectName(),
- ManagedBroker.class, false);
+ ManagedBroker managedBroker = _jmxUtils.getManagedBroker("test");
- managedBroker.deleteQueue(getName());
+ managedBroker.deleteQueue(getName());
- List<String> results = _monitor.findMatches("QUE-1002");
+ List<String> results = _monitor.findMatches("QUE-1002");
- assertEquals("More than one queue deletion found", 1, results.size());
+ assertEquals("More than one queue deletion found", 1, results.size());
- String log = getLog(results.get(0));
+ String log = getLog(results.get(0));
- // Validate correct binding
- String subject = fromSubject(log);
- assertEquals("Incorrect queue named in delete", getName(), AbstractTestLogSubject.getSlice("qu", subject));
+ // Validate correct binding
+ String subject = fromSubject(log);
+ assertEquals("Incorrect queue named in delete", getName(), AbstractTestLogSubject.getSlice("qu", subject));
- // Validate it was a management actor.
- String actor = fromActor(log);
- assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
+ // Validate it was a management actor.
+ String actor = fromActor(log);
+ assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
- }
}
/**
@@ -462,98 +402,83 @@ public class ManagementActorLoggingTest extends AbstractTestLogging
*/
public void testBindingCreateOnDirectViaManagementConsole() throws IOException, JMException
{
- if (isExternalBroker())
- {
- //Remove any previous queue declares
- _monitor.reset();
+ //Remove any previous queue declares
+ _monitor.reset();
- createQueue();
+ _jmxUtils.createQueue("test", getName(), null, false);
- ManagedExchange managedExchange = MBeanServerInvocationHandler.
- newProxyInstance(_mbsc, getExchange("amq.direct"),
- ManagedExchange.class, false);
+ ManagedExchange managedExchange = _jmxUtils.getManagedExchange("amq.direct");
- managedExchange.createNewBinding(getName(), getName());
+ managedExchange.createNewBinding(getName(), getName());
- List<String> results = _monitor.findMatches("BND-1001");
+ List<String> results = _monitor.findMatches("BND-1001");
- assertEquals("More than one bind creation found", 1, results.size());
+ assertEquals("More than one bind creation found", 1, results.size());
- String log = getLog(results.get(0));
+ String log = getLog(results.get(0));
- // Validate correct binding
- String subject = fromSubject(log);
- assertEquals("Incorrect queue named in create", getName(), AbstractTestLogSubject.getSlice("qu", subject));
- assertEquals("Incorrect routing key in create", getName(), AbstractTestLogSubject.getSlice("rk", subject));
+ // Validate correct binding
+ String subject = fromSubject(log);
+ assertEquals("Incorrect queue named in create", getName(), AbstractTestLogSubject.getSlice("qu", subject));
+ assertEquals("Incorrect routing key in create", getName(), AbstractTestLogSubject.getSlice("rk", subject));
- // Validate it was a management actor.
- String actor = fromActor(log);
- assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
- }
+ // Validate it was a management actor.
+ String actor = fromActor(log);
+ assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
}
public void testBindingCreateOnTopicViaManagementConsole() throws IOException, JMException
{
- if (isExternalBroker())
- {
- //Remove any previous queue declares
- _monitor.reset();
+ //Remove any previous queue declares
+ _monitor.reset();
- createQueue();
+ _jmxUtils.createQueue("test", getName(), null, false);
- ManagedExchange managedExchange = MBeanServerInvocationHandler.
- newProxyInstance(_mbsc, getExchange("amq.topic"),
- ManagedExchange.class, false);
+ ManagedExchange managedExchange = _jmxUtils.getManagedExchange("amq.topic");
- managedExchange.createNewBinding(getName(), getName());
+ managedExchange.createNewBinding(getName(), getName());
- List<String> results = _monitor.findMatches("BND-1001");
+ List<String> results = _monitor.findMatches("BND-1001");
- assertEquals("More than one bind creation found", 1, results.size());
+ assertEquals("More than one bind creation found", 1, results.size());
- String log = getLog(results.get(0));
+ String log = getLog(results.get(0));
- // Validate correct binding
- String subject = fromSubject(log);
- assertEquals("Incorrect queue named in create", getName(), AbstractTestLogSubject.getSlice("qu", subject));
- assertEquals("Incorrect routing key in create", getName(), AbstractTestLogSubject.getSlice("rk", subject));
+ // Validate correct binding
+ String subject = fromSubject(log);
+ assertEquals("Incorrect queue named in create", getName(), AbstractTestLogSubject.getSlice("qu", subject));
+ assertEquals("Incorrect routing key in create", getName(), AbstractTestLogSubject.getSlice("rk", subject));
- // Validate it was a management actor.
- String actor = fromActor(log);
- assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
- }
+ // Validate it was a management actor.
+ String actor = fromActor(log);
+ assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
}
public void testBindingCreateOnFanoutViaManagementConsole() throws IOException, JMException
{
- if (isExternalBroker())
- {
- //Remove any previous queue declares
- _monitor.reset();
+ //Remove any previous queue declares
+ _monitor.reset();
- createQueue();
+ _jmxUtils.createQueue("test", getName(), null, false);
- ManagedExchange managedExchange = MBeanServerInvocationHandler.
- newProxyInstance(_mbsc, getExchange("amq.fanout"),
- ManagedExchange.class, false);
+ ManagedExchange managedExchange = _jmxUtils.getManagedExchange("amq.fanout");
- managedExchange.createNewBinding(getName(), getName());
+ managedExchange.createNewBinding(getName(), getName());
- List<String> results = _monitor.findMatches("BND-1001");
+ List<String> results = _monitor.findMatches("BND-1001");
- assertEquals("More than one bind creation found", 1, results.size());
+ assertEquals("More than one bind creation found", 1, results.size());
- String log = getLog(results.get(0));
+ String log = getLog(results.get(0));
- // Validate correct binding
- String subject = fromSubject(log);
- assertEquals("Incorrect queue named in create", getName(), AbstractTestLogSubject.getSlice("qu", subject));
- assertEquals("Incorrect routing key in create", "*", AbstractTestLogSubject.getSlice("rk", subject));
+ // Validate correct binding
+ String subject = fromSubject(log);
+ assertEquals("Incorrect queue named in create", getName(), AbstractTestLogSubject.getSlice("qu", subject));
+ assertEquals("Incorrect routing key in create", "*", AbstractTestLogSubject.getSlice("rk", subject));
- // Validate it was a management actor.
- String actor = fromActor(log);
- assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
- }
+ // Validate it was a management actor.
+ String actor = fromActor(log);
+ assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
}
/**
@@ -578,114 +503,28 @@ public class ManagementActorLoggingTest extends AbstractTestLogging
*/
public void testUnRegisterExchangeViaManagementConsole() throws IOException, JMException
{
- if (isExternalBroker())
- {
+ //Remove any previous queue declares
+ _monitor.reset();
- //Remove any previous queue declares
- _monitor.reset();
+ _jmxUtils.createExchange("test", "direct", null, false);
- createExchange("direct");
+ ManagedBroker managedBroker = _jmxUtils.getManagedBroker("test");
- ManagedBroker managedBroker = MBeanServerInvocationHandler.
- newProxyInstance(_mbsc, getVirtualHostManagerObjectName(),
- ManagedBroker.class, false);
+ managedBroker.unregisterExchange(getName());
- managedBroker.unregisterExchange(getName());
+ List<String> results = _monitor.findMatches("EXH-1002");
- List<String> results = _monitor.findMatches("EXH-1002");
-
- assertEquals("More than one exchange deletion found", 1, results.size());
-
- String log = getLog(results.get(0));
-
- // Validate correct binding
- String subject = fromSubject(log);
- assertEquals("Incorrect exchange named in delete", "direct/" + getName(), AbstractTestLogSubject.getSlice("ex", subject));
-
- // Validate it was a management actor.
- String actor = fromActor(log);
- assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
- }
- }
-
- /**
- * Create a non-durable test exchange with the current test name
- *
- * @throws JMException - is thrown if a exchange with this testName already exists
- * @throws IOException - if there is a problem with the JMX Connection
- * @throws javax.management.MBeanException
- * - if there is another problem creating the exchange
- */
- private void createExchange(String type)
- throws JMException, IOException, MBeanException
- {
- ManagedBroker managedBroker = MBeanServerInvocationHandler.
- newProxyInstance(_mbsc, getVirtualHostManagerObjectName(),
- ManagedBroker.class, false);
-
- managedBroker.createNewExchange(getName(), type, false);
- }
-
- /**
- * Create a non-durable queue (with no owner) that is named after the
- * creating test.
- *
- * @throws JMException - is thrown if a queue with this testName already exists
- * @throws IOException - if there is a problem with the JMX Connection
- */
- private void createQueue()
- throws JMException, IOException
- {
- ManagedBroker managedBroker = MBeanServerInvocationHandler.
- newProxyInstance(_mbsc, getVirtualHostManagerObjectName(),
- ManagedBroker.class, false);
-
- managedBroker.createNewQueue(getName(), null, false);
- }
-
- /**
- * Retrive the ObjectName for the test Virtualhost.
- *
- * This is then use to create aproxy to the ManagedBroker MBean.
- *
- * @return the ObjectName for the 'test' VirtualHost.
- */
- private ObjectName getVirtualHostManagerObjectName()
- {
- // Get the name of the test manager
- AllObjects allObject = new AllObjects(_mbsc);
- allObject.querystring = "org.apache.qpid:type=VirtualHost.VirtualHostManager,VirtualHost=test,*";
-
- Set<ObjectName> objectNames = allObject.returnObjects();
-
- assertEquals("Incorrect number test vhosts returned", 1, objectNames.size());
-
- // We have verified we have only one value in objectNames so return it
- return objectNames.iterator().next();
- }
-
- /**
- * Retrive the ObjectName for the given Exchange on the test Virtualhost.
- *
- * This is then use to create aproxy to the ManagedExchange MBean.
- *
- * @param exchange The exchange to retireve e.g. 'direct'
- *
- * @return the ObjectName for the given exchange on the test VirtualHost.
- */
- private ObjectName getExchange(String exchange)
- {
- // Get the name of the test manager
- AllObjects allObject = new AllObjects(_mbsc);
- allObject.querystring = "org.apache.qpid:type=VirtualHost.Exchange,VirtualHost=test,name=" + exchange + ",*";
+ assertEquals("More than one exchange deletion found", 1, results.size());
- Set<ObjectName> objectNames = allObject.returnObjects();
+ String log = getLog(results.get(0));
- assertEquals("Incorrect number of exchange with name '" + exchange +
- "' returned", 1, objectNames.size());
+ // Validate correct binding
+ String subject = fromSubject(log);
+ assertEquals("Incorrect exchange named in delete", "direct/" + getName(), AbstractTestLogSubject.getSlice("ex", subject));
- // We have verified we have only one value in objectNames so return it
- return objectNames.iterator().next();
+ // Validate it was a management actor.
+ String actor = fromActor(log);
+ assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng"));
}
}
diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/server/configuration/ServerConfigurationFileTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/server/configuration/ServerConfigurationFileTest.java
index c4803e121e..0a88ef391c 100644
--- a/qpid/java/systests/src/main/java/org/apache/qpid/server/configuration/ServerConfigurationFileTest.java
+++ b/qpid/java/systests/src/main/java/org/apache/qpid/server/configuration/ServerConfigurationFileTest.java
@@ -40,6 +40,8 @@ public class ServerConfigurationFileTest extends QpidTestCase
{
fail("Unable to test without config file:" + _configFile);
}
+
+ saveTestConfiguration();
_serverConfig = new ServerConfiguration(_configFile);
}
diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/AlertingTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/AlertingTest.java
index 620b2a5161..683abee4da 100644
--- a/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/AlertingTest.java
+++ b/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/AlertingTest.java
@@ -94,7 +94,7 @@ public class AlertingTest extends AbstractTestLogging
{
_connection = getConnection();
_session = _connection.createSession(true, Session.SESSION_TRANSACTED);
- _destination = _session.createQueue("testQueue");
+ _destination = _session.createQueue(getTestQueueName());
// Consumer is only used to actually create the destination
_session.createConsumer(_destination).close();
@@ -116,14 +116,12 @@ public class AlertingTest extends AbstractTestLogging
// Add the current contents of the log file to test output
message.append(_monitor.readFile());
- // Write the server config file to test output
- message.append("Server configuration file in use:\n");
- message.append(FileUtils.readFileAsString(_configFile));
+ // Write the test config file to test output
+ message.append("Server configuration overrides in use:\n");
+ message.append(FileUtils.readFileAsString(getTestConfigFile()));
- // Write the virtualhost config file to test output
- message.append("\nVirtualhost configuration file in use:\n");
- message.append(FileUtils.readFileAsString(ServerConfiguration.
- flatConfig(_configFile).getString("virtualhosts")));
+ message.append("\nVirtualhost maxMessageCount:\n");
+ message.append((new ServerConfiguration(_configFile)).getConfig().getString("virtualhosts.virtualhost." + VIRTUALHOST + ".queues.maximumMessageCount"));
fail(message.toString());
}
diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/DerbyMessageStoreLoggingTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/DerbyMessageStoreLoggingTest.java
index 254ec9693d..cc3993249c 100644
--- a/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/DerbyMessageStoreLoggingTest.java
+++ b/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/DerbyMessageStoreLoggingTest.java
@@ -28,6 +28,7 @@ import javax.jms.Connection;
import javax.jms.Queue;
import javax.jms.Session;
import java.util.List;
+import java.io.File;
/**
* The MessageStore test suite validates that the follow log messages as
@@ -56,9 +57,9 @@ public class DerbyMessageStoreLoggingTest extends MemoryMessageStoreLoggingTest
//We call super.setUp but this will not start the broker as that is
//part of the test case.
- // Load current configuration file to get the list of defined vhosts
- Configuration configuration = ServerConfiguration.flatConfig(_configFile);
- List<String> vhosts = configuration.getList("virtualhosts.virtualhost.name");
+ // Load the default configuration file to get the list of defined vhosts
+ ServerConfiguration configuration = new ServerConfiguration(new File(_configFile.getParent() + "/config.xml"));
+ List<String> vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name");
// Make them all persistent i.e. Use DerbyMessageStore and
// test that it logs correctly.
@@ -97,8 +98,8 @@ public class DerbyMessageStoreLoggingTest extends MemoryMessageStoreLoggingTest
assertTrue("MST messages not logged", results.size() > 0);
// Load VirtualHost list from file.
- Configuration configuration = ServerConfiguration.flatConfig(_configFile);
- List<String> vhosts = configuration.getList("virtualhosts.virtualhost.name");
+ ServerConfiguration configuration = new ServerConfiguration(_configFile);
+ List<String> vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name");
//Validate each vhost logs a creation
results = _monitor.findMatches("MST-1002");
@@ -117,7 +118,7 @@ public class DerbyMessageStoreLoggingTest extends MemoryMessageStoreLoggingTest
// the virtualhost name, found above. AND
// the index that the virtualhost is within the configuration.
// we can retrive that from the vhosts list previously extracted.
- String fullStoreName = configuration.getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class");
+ String fullStoreName = configuration.getConfig().getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class");
// Get the Simple class name from the expected class name of o.a.q.s.s.MMS
String storeName = fullStoreName.substring(fullStoreName.lastIndexOf(".") + 1);
@@ -160,8 +161,8 @@ public class DerbyMessageStoreLoggingTest extends MemoryMessageStoreLoggingTest
assertTrue("MST messages not logged", results.size() > 0);
// Load VirtualHost list from file.
- Configuration configuration = ServerConfiguration.flatConfig(_configFile);
- List<String> vhosts = configuration.getList("virtualhosts.virtualhost.name");
+ ServerConfiguration configuration = new ServerConfiguration(_configFile);
+ List<String> vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name");
//Validate each vhost logs a creation
results = _monitor.findMatches("MST-1004");
@@ -186,7 +187,7 @@ public class DerbyMessageStoreLoggingTest extends MemoryMessageStoreLoggingTest
// the virtualhost name, found above. AND
// the index that the virtualhost is within the configuration.
// we can retrive that from the vhosts list previously extracted.
- String fullStoreName = configuration.getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class");
+ String fullStoreName = configuration.getConfig().getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class");
// Get the Simple class name from the expected class name of o.a.q.s.s.MMS
String storeName = fullStoreName.substring(fullStoreName.lastIndexOf(".") + 1);
@@ -227,8 +228,8 @@ public class DerbyMessageStoreLoggingTest extends MemoryMessageStoreLoggingTest
assertTrue("MST messages not logged", results.size() > 0);
// Load VirtualHost list from file.
- Configuration configuration = ServerConfiguration.flatConfig(_configFile);
- List<String> vhosts = configuration.getList("virtualhosts.virtualhost.name");
+ ServerConfiguration configuration = new ServerConfiguration(_configFile);
+ List<String> vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name");
//Validate each vhost logs a creation
results = _monitor.findMatches("MST-1006");
@@ -253,7 +254,7 @@ public class DerbyMessageStoreLoggingTest extends MemoryMessageStoreLoggingTest
// the virtualhost name, found above. AND
// the index that the virtualhost is within the configuration.
// we can retrive that from the vhosts list previously extracted.
- String fullStoreName = configuration.getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class");
+ String fullStoreName = configuration.getConfig().getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class");
// Get the Simple class name from the expected class name of o.a.q.s.s.MMS
String storeName = fullStoreName.substring(fullStoreName.lastIndexOf(".") + 1);
@@ -293,8 +294,8 @@ public class DerbyMessageStoreLoggingTest extends MemoryMessageStoreLoggingTest
assertTrue("MST messages not logged", results.size() > 0);
// Load VirtualHost list from file.
- Configuration configuration = ServerConfiguration.flatConfig(_configFile);
- List<String> vhosts = configuration.getList("virtualhosts.virtualhost.name");
+ ServerConfiguration configuration = new ServerConfiguration(_configFile);
+ List<String> vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name");
//Validate each vhost logs a creation
results = _monitor.findMatches("MST-1004 : Recovery Start :");
@@ -316,7 +317,7 @@ public class DerbyMessageStoreLoggingTest extends MemoryMessageStoreLoggingTest
// the virtualhost name, found above. AND
// the index that the virtualhost is within the configuration.
// we can retrive that from the vhosts list previously extracted.
- String fullStoreName = configuration.getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class");
+ String fullStoreName = configuration.getConfig().getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class");
// Get the Simple class name from the expected class name of o.a.q.s.s.MMS
String storeName = fullStoreName.substring(fullStoreName.lastIndexOf(".") + 1);
@@ -358,8 +359,8 @@ public class DerbyMessageStoreLoggingTest extends MemoryMessageStoreLoggingTest
assertTrue("MST messages not logged", results.size() > 0);
// Load VirtualHost list from file.
- Configuration configuration = ServerConfiguration.flatConfig(_configFile);
- List<String> vhosts = configuration.getList("virtualhosts.virtualhost.name");
+ ServerConfiguration configuration = new ServerConfiguration(_configFile);
+ List<String> vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name");
//Validate each vhost logs a creation
results = _monitor.findMatches("MST-1006 : Recovery Complete :");
@@ -381,7 +382,7 @@ public class DerbyMessageStoreLoggingTest extends MemoryMessageStoreLoggingTest
// the virtualhost name, found above. AND
// the index that the virtualhost is within the configuration.
// we can retrive that from the vhosts list previously extracted.
- String fullStoreName = configuration.getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class");
+ String fullStoreName = configuration.getConfig().getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class");
// Get the Simple class name from the expected class name of o.a.q.s.s.MMS
String storeName = fullStoreName.substring(fullStoreName.lastIndexOf(".") + 1);
@@ -500,8 +501,8 @@ public class DerbyMessageStoreLoggingTest extends MemoryMessageStoreLoggingTest
assertTrue("MST messages not logged", results.size() > 0);
// Load VirtualHost list from file.
- Configuration configuration = ServerConfiguration.flatConfig(_configFile);
- List<String> vhosts = configuration.getList("virtualhosts.virtualhost.name");
+ ServerConfiguration configuration = new ServerConfiguration(_configFile);
+ List<String> vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name");
//Validate each vhost logs a creation
results = _monitor.findMatches("MST-1004 : Recovery Start : " + queueName);
@@ -542,7 +543,7 @@ public class DerbyMessageStoreLoggingTest extends MemoryMessageStoreLoggingTest
// the virtualhost name, found above. AND
// the index that the virtualhost is within the configuration.
// we can retrive that from the vhosts list previously extracted.
- String fullStoreName = configuration.getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class");
+ String fullStoreName = configuration.getConfig().getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class");
// Get the Simple class name from the expected class name of o.a.q.s.s.MMS
String storeName = fullStoreName.substring(fullStoreName.lastIndexOf(".") + 1);
diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/ManagementLoggingTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/ManagementLoggingTest.java
index 11c003a2a7..8b7c881a32 100644
--- a/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/ManagementLoggingTest.java
+++ b/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/ManagementLoggingTest.java
@@ -24,6 +24,7 @@ import junit.framework.AssertionFailedError;
import org.apache.qpid.util.LogMonitor;
import java.util.List;
+import java.io.File;
/**
* Management Console Test Suite
@@ -308,9 +309,8 @@ public class ManagementLoggingTest extends AbstractTestLogging
// We expect the RMIConnector Server port to be 100 higher than
// the RMI Server Port
- int mPort = getPort() + (DEFAULT_MANAGEMENT_PORT - DEFAULT_PORT) + 100;
- assertTrue("SSL Keystore entry expected(" + mPort + ").:" + getMessageString(log),
- getMessageString(log).endsWith(getConfigurationStringProperty("management.ssl.keyStorePath")));
+ assertTrue("SSL Keystore entry expected.:" + getMessageString(log),
+ getMessageString(log).endsWith(new File(getConfigurationStringProperty("management.ssl.keyStorePath")).getName()));
}
catch (AssertionFailedError afe)
{
diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/MemoryMessageStoreLoggingTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/MemoryMessageStoreLoggingTest.java
index a1cbeca6de..2298ba4da0 100644
--- a/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/MemoryMessageStoreLoggingTest.java
+++ b/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/MemoryMessageStoreLoggingTest.java
@@ -89,8 +89,8 @@ public class MemoryMessageStoreLoggingTest extends AbstractTestLogging
assertEquals("MST-1001 is not the first MST message", "MST-1001", getMessageID(fromMessage(log)));
// Load VirtualHost list from file.
- Configuration configuration = ServerConfiguration.flatConfig(_configFile);
- List<String> vhosts = configuration.getList("virtualhosts.virtualhost.name");
+ ServerConfiguration configuration = new ServerConfiguration(_configFile);
+ List<String> vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name");
//Validate each vhost logs a creation
results = _monitor.findMatches("MST-1001");
@@ -109,7 +109,7 @@ public class MemoryMessageStoreLoggingTest extends AbstractTestLogging
// the virtualhost name, found above. AND
// the index that the virtualhost is within the configuration.
// we can retrive that from the vhosts list previously extracted.
- String fullStoreName = configuration.getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class");
+ String fullStoreName = configuration.getConfig().getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class");
// Get the Simple class name from the expected class name of o.a.q.s.s.MMS
String storeName = fullStoreName.substring(fullStoreName.lastIndexOf(".") + 1);
@@ -156,8 +156,8 @@ public class MemoryMessageStoreLoggingTest extends AbstractTestLogging
assertTrue("MST messages not logged", results.size() > 0);
// Load VirtualHost list from file.
- Configuration configuration = ServerConfiguration.flatConfig(_configFile);
- List<String> vhosts = configuration.getList("virtualhosts.virtualhost.name");
+ ServerConfiguration configuration = new ServerConfiguration(_configFile);
+ List<String> vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name");
//Validate each vhost logs a creation
results = _monitor.findMatches("MST-1003");
@@ -176,7 +176,7 @@ public class MemoryMessageStoreLoggingTest extends AbstractTestLogging
// the virtualhost name, found above. AND
// the index that the virtualhost is within the configuration.
// we can retrive that from the vhosts list previously extracted.
- String fullStoreName = configuration.getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class");
+ String fullStoreName = configuration.getConfig().getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class");
// Get the Simple class name from the expected class name of o.a.q.s.s.MMS
String storeName = fullStoreName.substring(fullStoreName.lastIndexOf(".") + 1);
diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/VirtualHostLoggingTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/VirtualHostLoggingTest.java
index 7bf644508e..f4a0c8b27d 100644
--- a/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/VirtualHostLoggingTest.java
+++ b/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/VirtualHostLoggingTest.java
@@ -64,8 +64,8 @@ public class VirtualHostLoggingTest extends AbstractTestLogging
try
{
// Validation
- Configuration configuration = ServerConfiguration.flatConfig(_configFile);
- List<String> vhosts = configuration.getList("virtualhosts.virtualhost.name");
+ ServerConfiguration configuration = new ServerConfiguration(_configFile);
+ List<String> vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name");
//Validate each vhost logs a creation
results = _monitor.findMatches("VHT-1001");
@@ -117,8 +117,8 @@ public class VirtualHostLoggingTest extends AbstractTestLogging
{
// Validation
- Configuration configuration = ServerConfiguration.flatConfig(_configFile);
- List<String> vhosts = configuration.getList("virtualhosts.virtualhost.name");
+ ServerConfiguration configuration = new ServerConfiguration(_configFile);
+ List<String> vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name");
//Validate each vhost logs a creation
results = _monitor.findMatches("VHT-1002");
diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/server/queue/ModelTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/server/queue/ModelTest.java
new file mode 100644
index 0000000000..078b8f43ce
--- /dev/null
+++ b/qpid/java/systests/src/main/java/org/apache/qpid/server/queue/ModelTest.java
@@ -0,0 +1,299 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package org.apache.qpid.server.queue;
+
+import org.apache.qpid.AMQException;
+import org.apache.qpid.client.AMQConnection;
+import org.apache.qpid.client.AMQSession;
+import org.apache.qpid.framing.AMQShortString;
+import org.apache.qpid.management.common.mbeans.ManagedBroker;
+import org.apache.qpid.management.common.mbeans.ManagedQueue;
+import org.apache.qpid.test.utils.JMXTestUtils;
+import org.apache.qpid.test.utils.QpidTestCase;
+
+import javax.jms.Connection;
+import javax.jms.JMSException;
+import javax.jms.Session;
+import javax.management.JMException;
+import javax.management.MBeanException;
+import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.UndeclaredThrowableException;
+
+/**
+ * This Test validates the Queue Model on the broker.
+ * Currently it has some basic queue creation / deletion tests.
+ * However, it should be expanded to include other tests that relate to the
+ * model. i.e.
+ *
+ * The Create and Delete tests should ensure that the requisite logging is
+ * performed.
+ *
+ * Additions to this suite would be to complete testing of creations, validating
+ * fields such as owner/exclusive, autodelete and priority are correctly set.
+ *
+ * Currently this test uses the JMX interface to validate that the queue has
+ * been declared as expected so these tests cannot run against a CPP broker.
+ *
+ *
+ * Tests should ensure that they clean up after themselves.
+ * e,g. Durable queue creation test should perform a queue delete.
+ */
+public class ModelTest extends QpidTestCase
+{
+
+ private static final String USER = "admin";
+ private JMXTestUtils _jmxUtils;
+ private static final String VIRTUALHOST_NAME = "test";
+
+ @Override
+ public void setUp() throws Exception
+ {
+ // Create a JMX Helper
+ _jmxUtils = new JMXTestUtils(this, USER, USER);
+ _jmxUtils.setUp();
+ super.setUp();
+
+ // Open the JMX Connection
+ _jmxUtils.open();
+ }
+
+ @Override
+ public void tearDown() throws Exception
+ {
+ // Close the JMX Connection
+ _jmxUtils.close();
+ super.tearDown();
+ }
+
+ /**
+ * Test that a transient queue can be created via AMQP.
+ *
+ * @throws Exception On unexpected error
+ */
+ public void testQueueCreationTransientViaAMQP() throws Exception
+ {
+ Connection connection = getConnection();
+
+ String queueName = getTestQueueName();
+ boolean durable = false;
+ boolean autoDelete = false;
+ boolean exclusive = false;
+
+ createViaAMQPandValidateViaJMX(connection, queueName, durable,
+ autoDelete, exclusive);
+ }
+
+ /**
+ * Test that a durable queue can be created via AMQP.
+ *
+ * @throws Exception On unexpected error
+ */
+
+ public void testQueueCreationDurableViaAMQP() throws Exception
+ {
+ Connection connection = getConnection();
+
+ String queueName = getTestQueueName();
+ boolean durable = true;
+ boolean autoDelete = false;
+ boolean exclusive = false;
+
+ createViaAMQPandValidateViaJMX(connection, queueName, durable,
+ autoDelete, exclusive);
+
+ // Clean up
+ ManagedBroker managedBroker =
+ _jmxUtils.getManagedBroker(VIRTUALHOST_NAME);
+ managedBroker.deleteQueue(queueName);
+ }
+
+ /**
+ * Test that a transient queue can be created via JMX.
+ *
+ * @throws IOException if there is a problem via the JMX connection
+ * @throws javax.management.JMException if there is a problem with the JMX command
+ */
+ public void testCreationTransientViaJMX() throws IOException, JMException
+ {
+ String name = getName();
+ String owner = null;
+ boolean durable = false;
+
+ createViaJMXandValidateViaJMX(name, owner, durable, durable);
+ }
+
+ /**
+ * Test that a durable queue can be created via JMX.
+ *
+ * @throws IOException if there is a problem via the JMX connection
+ * @throws javax.management.JMException if there is a problem with the JMX command
+ */
+ public void testCreationDurableViaJMX() throws IOException, JMException
+ {
+ String name = getName();
+ String owner = null;
+ boolean durable = true;
+
+ createViaJMXandValidateViaJMX(name, owner, durable, durable);
+
+ // Clean up
+ ManagedBroker managedBroker =
+ _jmxUtils.getManagedBroker(VIRTUALHOST_NAME);
+ managedBroker.deleteQueue(name);
+ }
+
+ /**
+ * Test that a transient queue can be deleted via JMX.
+ *
+ * @throws IOException if there is a problem via the JMX connection
+ * @throws javax.management.JMException if there is a problem with the JMX command
+ */
+ public void testDeletionTransientViaJMX() throws IOException, JMException
+ {
+ String name = getName();
+
+ _jmxUtils.createQueue(VIRTUALHOST_NAME, name, null, false);
+
+ ManagedBroker managedBroker = _jmxUtils.
+ getManagedBroker(VIRTUALHOST_NAME);
+
+ try
+ {
+ managedBroker.deleteQueue(name);
+ }
+ catch (UndeclaredThrowableException e)
+ {
+ fail(((MBeanException) ((InvocationTargetException)
+ e.getUndeclaredThrowable()).getTargetException()).getTargetException().getMessage());
+ }
+ }
+
+ /**
+ * Test that a durable queue can be created via JMX.
+ *
+ * @throws IOException if there is a problem via the JMX connection
+ * @throws javax.management.JMException if there is a problem with the JMX command
+ */
+ public void testDeletionDurableViaJMX() throws IOException, JMException
+ {
+ String name = getName();
+
+ _jmxUtils.createQueue(VIRTUALHOST_NAME, name, null, true);
+
+ ManagedBroker managedBroker = _jmxUtils.
+ getManagedBroker(VIRTUALHOST_NAME);
+
+ try
+ {
+ managedBroker.deleteQueue(name);
+ }
+ catch (UndeclaredThrowableException e)
+ {
+ fail(((MBeanException) ((InvocationTargetException)
+ e.getUndeclaredThrowable()).getTargetException()).getTargetException().getMessage());
+ }
+ }
+
+ /*
+ * Helper Methods
+ */
+
+ /**
+ * Using the provided JMS Connection create a queue using the AMQP extension
+ * with the given properties and then validate it was created correctly via
+ * the JMX Connection
+ *
+ * @param connection Qpid JMS Connection
+ * @param queueName String the desired QueueName
+ * @param durable boolean if the queue should be durable
+ * @param autoDelete boolean if the queue is an autoDelete queue
+ * @param exclusive boolean if the queue is exclusive
+ *
+ * @throws AMQException if there is a problem with the createQueue call
+ * @throws JMException if there is a problem with the JMX validatation
+ * @throws IOException if there is a problem with the JMX connection
+ * @throws JMSException if there is a problem creating the JMS Session
+ */
+ private void createViaAMQPandValidateViaJMX(Connection connection,
+ String queueName,
+ boolean durable,
+ boolean autoDelete,
+ boolean exclusive)
+ throws AMQException, JMException, IOException, JMSException
+ {
+ AMQSession session = (AMQSession) connection.createSession(false,
+ Session.AUTO_ACKNOWLEDGE);
+
+ session.createQueue(new AMQShortString(queueName),
+ autoDelete, durable, exclusive);
+
+ validateQueueViaJMX(queueName, exclusive ? ((AMQConnection) connection).
+ getUsername() : null, durable, autoDelete);
+ }
+
+ /**
+ * Use the JMX Helper to create a queue with the given properties and then
+ * validate it was created correctly via the JMX Connection
+ *
+ * @param queueName String the desired QueueName
+ * @param owner String the owner value that should be set
+ * @param durable boolean if the queue should be durable
+ * @param autoDelete boolean if the queue is an autoDelete queue
+ *
+ * @throws JMException if there is a problem with the JMX validatation
+ * @throws IOException if there is a problem with the JMX connection
+ */
+ private void createViaJMXandValidateViaJMX(String queueName, String owner,
+ boolean durable, boolean autoDelete)
+ throws JMException, IOException
+ {
+ _jmxUtils.createQueue(VIRTUALHOST_NAME, queueName, owner, durable);
+
+ validateQueueViaJMX(queueName, owner, durable, autoDelete);
+ }
+
+ /**
+ * Validate that a queue with the given properties exists on the broker
+ *
+ * @param queueName String the desired QueueName
+ * @param owner String the owner value that should be set
+ * @param durable boolean if the queue should be durable
+ * @param autoDelete boolean if the queue is an autoDelete queue
+ *
+ * @throws JMException if there is a problem with the JMX validatation
+ * @throws IOException if there is a problem with the JMX connection
+ */
+ private void validateQueueViaJMX(String queueName, String owner, boolean durable, boolean autoDelete)
+ throws JMException, IOException
+ {
+ ManagedQueue managedQueue = _jmxUtils.
+ getManagedObject(ManagedQueue.class,
+ _jmxUtils.getQueueObjectName(VIRTUALHOST_NAME,
+ queueName));
+
+ assertEquals(queueName, managedQueue.getName());
+ assertEquals(String.valueOf(owner), managedQueue.getOwner());
+ assertEquals(durable, managedQueue.isDurable());
+ assertEquals(autoDelete, managedQueue.isAutoDelete());
+ }
+
+}
diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/server/security/acl/SimpleACLTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/server/security/acl/SimpleACLTest.java
index f402522a19..bb7b5efc75 100644
--- a/qpid/java/systests/src/main/java/org/apache/qpid/server/security/acl/SimpleACLTest.java
+++ b/qpid/java/systests/src/main/java/org/apache/qpid/server/security/acl/SimpleACLTest.java
@@ -21,6 +21,7 @@
package org.apache.qpid.server.security.acl;
+
import junit.framework.TestCase;
import org.apache.log4j.BasicConfigurator;
@@ -30,6 +31,7 @@ import org.apache.qpid.client.*;
import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.server.registry.ApplicationRegistry;
import org.apache.qpid.server.registry.ConfigurationFileApplicationRegistry;
+import org.apache.qpid.AMQConnectionFailureException;
import org.apache.qpid.AMQException;
import org.apache.qpid.test.utils.QpidTestCase;
import org.apache.qpid.jms.ConnectionListener;
@@ -37,6 +39,7 @@ import org.apache.qpid.url.URLSyntaxException;
import javax.jms.*;
import javax.jms.IllegalStateException;
+import javax.naming.NamingException;
import java.io.File;
import java.util.ArrayList;
@@ -51,46 +54,30 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E
public void setUp() throws Exception
{
- //Shutdown the QTC broker
- stopBroker();
-
- // Initialise ACLs.
- final String QpidExampleHome = System.getProperty("QPID_EXAMPLE_HOME");
- final File defaultaclConfigFile = new File(QpidExampleHome, "etc/acl.config.xml");
-
- if (!defaultaclConfigFile.exists())
- {
- System.err.println("Configuration file not found:" + defaultaclConfigFile);
- fail("Configuration file not found:" + defaultaclConfigFile);
- }
+ final String QPID_HOME = System.getProperty("QPID_HOME");
- if (System.getProperty("QPID_HOME") == null)
+ if (QPID_HOME == null)
{
fail("QPID_HOME not set");
}
- ConfigurationFileApplicationRegistry config = new ConfigurationFileApplicationRegistry(defaultaclConfigFile);
- ApplicationRegistry.initialise(config, ApplicationRegistry.DEFAULT_INSTANCE);
- TransportConnection.createVMBroker(ApplicationRegistry.DEFAULT_INSTANCE);
- }
+ // Initialise ACLs.
+ _configFile = new File(QPID_HOME, "etc/config-systests-acl.xml");
- public void tearDown()
- {
- TransportConnection.killVMBroker(ApplicationRegistry.DEFAULT_INSTANCE);
- ApplicationRegistry.remove(ApplicationRegistry.DEFAULT_INSTANCE);
+ super.setUp();
}
- public String createConnectionString(String username, String password, String broker)
+ public String createConnectionString(String username, String password)
{
- return "amqp://" + username + ":" + password + "@clientid/test?brokerlist='" + broker + "?retries='0''";
+ return "amqp://" + username + ":" + password + "@clientid/test?brokerlist='" + getBroker() + "?retries='0''";
}
public void testAccessAuthorized() throws AMQException, URLSyntaxException
{
try
{
- Connection conn = createConnection("client", "guest");
+ Connection conn = getConnection("client", "guest");
Session sesh = conn.createSession(true, Session.SESSION_TRANSACTED);
@@ -103,28 +90,32 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E
}
catch (Exception e)
{
- fail("Connection was not created due to:" + e.getMessage());
+ fail("Connection was not created due to:" + e);
}
}
- public void testAccessNoRights() throws URLSyntaxException, JMSException
+ public void testAccessNoRights() throws Exception
{
try
{
- Connection conn = createConnection("guest", "guest");
+ Connection conn = getConnection("guest", "guest");
//Attempt to do do things to test connection.
Session sesh = conn.createSession(true, Session.SESSION_TRANSACTED);
conn.start();
sesh.rollback();
- conn.close();
fail("Connection was created.");
}
- catch (AMQException amqe)
+ catch (JMSException jmse)
{
- Throwable cause = amqe.getCause();
- assertEquals("Exception was wrong type", AMQAuthenticationException.class, cause.getClass());
+ Throwable linkedException = jmse.getLinkedException();
+ assertNotNull("Cause was null", linkedException);
+
+ assertEquals("Linked Exception was wrong type", AMQConnectionFailureException.class, linkedException.getClass());
+
+ Throwable cause = linkedException.getCause();
+ assertEquals("Cause was wrong type", AMQAuthenticationException.class, cause.getClass());
assertEquals("Incorrect error code thrown", 403, ((AMQAuthenticationException) cause).getErrorCode().getCode());
}
}
@@ -133,7 +124,7 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E
{
try
{
- Connection conn = createConnection("client", "guest");
+ Connection conn = getConnection("client", "guest");
Session sesh = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
@@ -149,11 +140,11 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E
}
}
- public void testClientConsumeFromNamedQueueInvalid() throws AMQException, URLSyntaxException
+ public void testClientConsumeFromNamedQueueInvalid() throws NamingException, Exception
{
try
{
- Connection conn = createConnection("client", "guest");
+ Connection conn = getConnection("client", "guest");
//Prevent Failover
((AMQConnection) conn).setConnectionListener(this);
@@ -180,7 +171,7 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E
{
try
{
- Connection conn = createConnection("client", "guest");
+ Connection conn = getConnection("client", "guest");
Session sesh = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
@@ -198,11 +189,11 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E
}
}
- public void testClientCreateNamedQueue() throws JMSException, URLSyntaxException, AMQException
+ public void testClientCreateNamedQueue() throws NamingException, JMSException, AMQException, Exception
{
try
{
- Connection conn = createConnection("client", "guest");
+ Connection conn = getConnection("client", "guest");
Session sesh = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
@@ -216,6 +207,7 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E
}
catch (AMQAuthenticationException amqe)
{
+ amqe.printStackTrace();
assertEquals("Incorrect error code thrown", 403, ((AMQAuthenticationException) amqe).getErrorCode().getCode());
}
}
@@ -224,7 +216,7 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E
{
try
{
- Connection conn = createConnection("client", "guest");
+ Connection conn = getConnection("client", "guest");
((AMQConnection) conn).setConnectionListener(this);
@@ -251,7 +243,7 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E
{
try
{
- Connection conn = createConnection("client", "guest");
+ Connection conn = getConnection("client", "guest");
((AMQConnection) conn).setConnectionListener(this);
@@ -277,11 +269,11 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E
}
}
- public void testClientPublishInvalidQueueSuccess() throws AMQException, URLSyntaxException, JMSException, InterruptedException
+ public void testClientPublishInvalidQueueSuccess() throws AMQException, URLSyntaxException, JMSException, NamingException, Exception
{
try
{
- Connection conn = createConnection("client", "guest");
+ Connection conn = getConnection("client", "guest");
((AMQConnection) conn).setConnectionListener(this);
@@ -323,7 +315,7 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E
{
try
{
- Connection conn = createConnection("server", "guest");
+ Connection conn = getConnection("server", "guest");
Session sesh = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
@@ -339,11 +331,11 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E
}
}
- public void testServerConsumeFromNamedQueueInvalid() throws AMQException, URLSyntaxException
+ public void testServerConsumeFromNamedQueueInvalid() throws AMQException, URLSyntaxException, NamingException, Exception
{
try
- {
- Connection conn = createConnection("client", "guest");
+ {
+ Connection conn = getConnection("client", "guest");
Session sesh = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
@@ -364,11 +356,11 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E
}
}
- public void testServerConsumeFromTemporaryQueue() throws AMQException, URLSyntaxException
+ public void testServerConsumeFromTemporaryQueue() throws AMQException, URLSyntaxException, NamingException, Exception
{
try
{
- Connection conn = createConnection("server","guest");
+ Connection conn = getConnection("server", "guest");
Session sesh = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
@@ -388,30 +380,22 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E
}
}
- private Connection createConnection(String username, String password) throws AMQException
+ @Override
+ public Connection getConnection(String username, String password) throws NamingException, JMSException
{
- AMQConnection connection = null;
- try
- {
- connection = new AMQConnection(createConnectionString(username, password, BROKER));
- }
- catch (URLSyntaxException e)
- {
- // This should never happen as we generate the URLs.
- fail(e.getMessage());
- }
+ AMQConnection connection = (AMQConnection) super.getConnection(username, password);
//Prevent Failover
connection.setConnectionListener(this);
- return (Connection)connection;
+ return (Connection) connection;
}
public void testServerCreateNamedQueueValid() throws JMSException, URLSyntaxException
{
try
{
- Connection conn = createConnection("server", "guest");
+ Connection conn = getConnection("server", "guest");
Session sesh = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
@@ -428,11 +412,11 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E
}
}
- public void testServerCreateNamedQueueInvalid() throws JMSException, URLSyntaxException, AMQException
+ public void testServerCreateNamedQueueInvalid() throws JMSException, URLSyntaxException, AMQException, NamingException, Exception
{
try
{
- Connection conn = createConnection("server", "guest");
+ Connection conn = getConnection("server", "guest");
Session sesh = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
@@ -450,18 +434,18 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E
}
}
- public void testServerCreateTemporaryQueueInvalid() throws JMSException, URLSyntaxException, AMQException
+ public void testServerCreateTemporaryQueueInvalid() throws NamingException, Exception
{
try
{
- Connection conn = createConnection("server", "guest");
+ Connection conn = getConnection("server", "guest");
Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
conn.start();
session.createTemporaryQueue();
-
+
fail("Test failed as creation succeded.");
//conn will be automatically closed
}
@@ -475,19 +459,19 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E
}
}
- public void testServerCreateAutoDeleteQueueInvalid() throws JMSException, URLSyntaxException, AMQException
+ public void testServerCreateAutoDeleteQueueInvalid() throws NamingException, JMSException, AMQException, Exception
{
Connection connection = null;
try
{
- connection = createConnection("server", "guest");
+ connection = getConnection("server", "guest");
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
connection.start();
((AMQSession) session).createQueue(new AMQShortString("again_ensure_auto_delete_queue_for_temporary"),
- true, false, false);
+ true, false, false);
fail("Test failed as creation succeded.");
//connection will be automatically closed
@@ -495,7 +479,7 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E
catch (AMQAuthenticationException amqe)
{
assertEquals("Incorrect error code thrown", 403, amqe.getErrorCode().getCode());
- }
+ }
}
/**
@@ -506,10 +490,10 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E
* @throws URLSyntaxException
* @throws JMSException
*/
- public void testServerPublishUsingTransactionSuccess() throws AMQException, URLSyntaxException, JMSException
+ public void testServerPublishUsingTransactionSuccess() throws AMQException, URLSyntaxException, JMSException, NamingException, Exception
{
//Set up the Server
- Connection serverConnection = createConnection("server", "guest");
+ Connection serverConnection = getConnection("server", "guest");
((AMQConnection) serverConnection).setConnectionListener(this);
@@ -522,7 +506,7 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E
serverConnection.start();
//Set up the consumer
- Connection clientConnection = createConnection("client", "guest");
+ Connection clientConnection = getConnection("client", "guest");
//Send a test mesage
Session clientSession = clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
@@ -563,8 +547,6 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E
//Send the message using a transaction as this will allow us to retrieve any errors that occur on the broker.
serverSession.commit();
-
-
//Ensure Response is received.
Message clientResponseMsg = clientResponse.receive(2000);
assertNotNull("Client did not receive response message,", clientResponseMsg);
@@ -588,11 +570,11 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E
}
}
- public void testServerPublishInvalidQueueSuccess() throws AMQException, URLSyntaxException, JMSException
+ public void testServerPublishInvalidQueueSuccess() throws AMQException, URLSyntaxException, JMSException, NamingException, Exception
{
try
{
- Connection conn = createConnection("server", "guest");
+ Connection conn = getConnection("server", "guest");
((AMQConnection) conn).setConnectionListener(this);
diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/client/timeouts/SyncWaitDelayTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/client/timeouts/SyncWaitDelayTest.java
index b13170efc9..a123fb290c 100644
--- a/qpid/java/systests/src/main/java/org/apache/qpid/test/client/timeouts/SyncWaitDelayTest.java
+++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/client/timeouts/SyncWaitDelayTest.java
@@ -57,26 +57,13 @@ public class SyncWaitDelayTest extends QpidTestCase
public void setUp() throws Exception
{
- super.setUp();
- stopBroker();
- if (!_configFile.exists())
- {
- fail("Unable to test without config file:" + _configFile);
- }
- XMLConfiguration configuration = new XMLConfiguration(_configFile);
- configuration.setProperty("virtualhosts.virtualhost." + VIRTUALHOST+".store.class", "org.apache.qpid.server.store.SlowMessageStore");
- configuration.setProperty("virtualhosts.virtualhost." + VIRTUALHOST+".store.delays.commitTran.post", POST_COMMIT_DELAY);
- configuration.setProperty("management.enabled", "false");
+ setConfigurationProperty("virtualhosts.virtualhost." + VIRTUALHOST+".store.class", "org.apache.qpid.server.store.SlowMessageStore");
+ setConfigurationProperty("virtualhosts.virtualhost." + VIRTUALHOST+".store.delays.commitTran.post", String.valueOf(POST_COMMIT_DELAY));
+ setConfigurationProperty("management.enabled", "false");
- File tmpFile = File.createTempFile("configFile", "test");
- tmpFile.deleteOnExit();
- configuration.save(tmpFile);
-
- _configFile = tmpFile;
-
- startBroker(1);
+ super.setUp();
//Set the syncWrite timeout to be just larger than the delay on the commitTran.
setSystemProperty("amqj.default_syncwrite_timeout", String.valueOf(SYNC_WRITE_TIMEOUT));
diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/FailoverBaseCase.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/FailoverBaseCase.java
index 1bef07fcd5..64bd1503ba 100644
--- a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/FailoverBaseCase.java
+++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/FailoverBaseCase.java
@@ -21,6 +21,8 @@
package org.apache.qpid.test.utils;
import javax.jms.Connection;
+import javax.jms.JMSException;
+import javax.naming.NamingException;
import org.apache.qpid.util.FileUtils;
@@ -64,7 +66,7 @@ public class FailoverBaseCase extends QpidTestCase
* @return a connection
* @throws Exception
*/
- public Connection getConnection() throws Exception
+ public Connection getConnection() throws JMSException, NamingException
{
Connection conn =
(Boolean.getBoolean("profile.use_ssl"))?
diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/JMXTestUtils.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/JMXTestUtils.java
new file mode 100644
index 0000000000..3f8cdb9c25
--- /dev/null
+++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/JMXTestUtils.java
@@ -0,0 +1,208 @@
+/*
+ *
+ * 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.test.utils;
+
+import org.apache.commons.configuration.ConfigurationException;
+import org.apache.qpid.commands.objects.AllObjects;
+import org.apache.qpid.management.common.JMXConnnectionFactory;
+import org.apache.qpid.management.common.mbeans.ManagedBroker;
+import org.apache.qpid.management.common.mbeans.ManagedExchange;
+
+import javax.management.JMException;
+import javax.management.MBeanException;
+import javax.management.MBeanServerConnection;
+import javax.management.MBeanServerInvocationHandler;
+import javax.management.ObjectName;
+import javax.management.remote.JMXConnector;
+import java.io.IOException;
+import java.util.Set;
+
+/**
+ *
+ */
+public class JMXTestUtils
+{
+ QpidTestCase _test;
+ MBeanServerConnection _mbsc;
+ JMXConnector _jmxc;
+
+ private String USER;
+ private String PASSWORD;
+
+ public JMXTestUtils(QpidTestCase test, String user, String password)
+ {
+ _test = test;
+ USER = user;
+ PASSWORD = password;
+ }
+
+ public void setUp() throws IOException, ConfigurationException, Exception
+ {
+ _test.setConfigurationProperty("management.enabled", "true");
+ }
+
+ public void open() throws Exception
+ {
+ _jmxc = JMXConnnectionFactory.getJMXConnection(
+ 5000, "127.0.0.1",
+ _test.getManagementPort(_test.getPort()), USER, PASSWORD);
+
+ _mbsc = _jmxc.getMBeanServerConnection();
+ }
+
+ public void close() throws IOException
+ {
+ _jmxc.close();
+ }
+
+ /**
+ * Create a non-durable test exchange with the current test name
+ *
+ * @throws javax.management.JMException - is thrown if a exchange with this testName already exists
+ * @throws java.io.IOException - if there is a problem with the JMX Connection
+ * @throws javax.management.MBeanException
+ * - if there is another problem creating the exchange
+ */
+ public void createExchange(String virtualHostName, String name, String type, boolean durable)
+ throws JMException, IOException, MBeanException
+ {
+ ManagedBroker managedBroker = getManagedBroker(virtualHostName);
+
+ managedBroker.createNewExchange(name, type, durable);
+ }
+
+ /**
+ * Create a non-durable queue (with no owner) that is named after the
+ * creating test.
+ *
+ * @throws JMException - is thrown if a queue with this testName already exists
+ * @throws IOException - if there is a problem with the JMX Connection
+ */
+ public void createQueue(String virtualHostName, String name, String owner, boolean durable)
+ throws JMException, IOException
+ {
+ ManagedBroker managedBroker = getManagedBroker(virtualHostName);
+
+ managedBroker.createNewQueue(name, owner, durable);
+ }
+
+ /**
+ * Retrive the ObjectName for the test Virtualhost.
+ *
+ * This is then use to create aproxy to the ManagedBroker MBean.
+ *
+ * @return the ObjectName for the 'test' VirtualHost.
+ */
+ public ObjectName getVirtualHostManagerObjectName(String vhostName)
+ {
+ // Get the name of the test manager
+ AllObjects allObject = new AllObjects(_mbsc);
+ allObject.querystring = "org.apache.qpid:type=VirtualHost.VirtualHostManager,VirtualHost=" + vhostName + ",*";
+
+ Set<ObjectName> objectNames = allObject.returnObjects();
+
+ _test.assertEquals("Incorrect number test vhosts returned", 1, objectNames.size());
+
+ // We have verified we have only one value in objectNames so return it
+ return objectNames.iterator().next();
+ }
+
+ /**
+ * Retrive the ObjectName for the given Exchange on the test Virtualhost.
+ *
+ * This is then use to create aproxy to the ManagedExchange MBean.
+ *
+ * @param queue The exchange to retireve e.g. 'direct'
+ *
+ * @return the ObjectName for the given exchange on the test VirtualHost.
+ */
+ public ObjectName getQueueObjectName(String virtualHostName, String queue)
+ {
+ // Get the name of the test manager
+ AllObjects allObject = new AllObjects(_mbsc);
+ allObject.querystring = "org.apache.qpid:type=VirtualHost.Queue,VirtualHost=" + virtualHostName + ",name=" + queue + ",*";
+
+ Set<ObjectName> objectNames = allObject.returnObjects();
+
+ _test.assertEquals("Incorrect number of exchange with name '" + queue +
+ "' returned", 1, objectNames.size());
+
+ // We have verified we have only one value in objectNames so return it
+ return objectNames.iterator().next();
+ }
+
+ /**
+ * Retrive the ObjectName for the given Exchange on the test Virtualhost.
+ *
+ * This is then use to create aproxy to the ManagedExchange MBean.
+ *
+ * @param virtualHostName
+ * @param exchange The exchange to retireve e.g. 'direct'
+ *
+ * @return the ObjectName for the given exchange on the test VirtualHost.
+ */
+ public ObjectName getExchangeObjectName(String virtualHostName, String exchange)
+ {
+ // Get the name of the test manager
+ AllObjects allObject = new AllObjects(_mbsc);
+ allObject.querystring = "org.apache.qpid:type=VirtualHost.Exchange,VirtualHost=" + virtualHostName + ",name=" + exchange + ",*";
+
+ Set<ObjectName> objectNames = allObject.returnObjects();
+
+ _test.assertEquals("Incorrect number of exchange with name '" + exchange +
+ "' returned", 1, objectNames.size());
+
+ // We have verified we have only one value in objectNames so return it
+ return objectNames.iterator().next();
+ }
+
+ public <T> T getManagedObject(Class<T> managedClass, String queryString)
+ {
+ AllObjects allObject = new AllObjects(_mbsc);
+ allObject.querystring = queryString;
+
+ Set<ObjectName> objectNames = allObject.returnObjects();
+
+ _test.assertEquals("More than one " + managedClass + " returned", 1, objectNames.size());
+
+ ObjectName objectName = objectNames.iterator().next();
+
+ return getManagedObject(managedClass, objectName);
+ }
+
+ public <T> T getManagedObject(Class<T> managedClass, ObjectName objectName)
+ {
+ return MBeanServerInvocationHandler.
+ newProxyInstance(_mbsc, objectName, managedClass, false);
+ }
+
+ public ManagedBroker getManagedBroker(String virtualHost)
+ {
+ return getManagedObject(ManagedBroker.class, getVirtualHostManagerObjectName(virtualHost).toString());
+ }
+
+ public ManagedExchange getManagedExchange(String exchangeName)
+ {
+ return MBeanServerInvocationHandler.
+ newProxyInstance(_mbsc, getExchangeObjectName("test", exchangeName),
+ ManagedExchange.class, false);
+ }
+}
diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/QpidTestCase.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/QpidTestCase.java
index db096710dc..76e4118c96 100644
--- a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/QpidTestCase.java
+++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/QpidTestCase.java
@@ -21,6 +21,7 @@ import junit.framework.TestCase;
import junit.framework.TestResult;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
+import org.apache.qpid.AMQException;
import org.apache.qpid.client.AMQConnection;
import org.apache.qpid.client.AMQConnectionFactory;
import org.apache.qpid.client.transport.TransportConnection;
@@ -30,6 +31,7 @@ import org.apache.qpid.server.configuration.ServerConfiguration;
import org.apache.qpid.server.registry.ApplicationRegistry;
import org.apache.qpid.server.registry.ConfigurationFileApplicationRegistry;
import org.apache.qpid.server.store.DerbyMessageStore;
+import org.apache.qpid.url.URLSyntaxException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -73,6 +75,7 @@ public class QpidTestCase extends TestCase
protected long RECEIVE_TIMEOUT = 1000l;
private Map<String, String> _setProperties = new HashMap<String, String>();
+ private XMLConfiguration _testConfiguration = new XMLConfiguration();
/**
* Some tests are excluded when the property test.excludes is set to true.
@@ -183,8 +186,7 @@ public class QpidTestCase extends TestCase
public static final String QUEUE = "queue";
public static final String TOPIC = "topic";
/** Map to hold test defined environment properties */
- private Map<String,String> _env;
-
+ private Map<String, String> _env;
public QpidTestCase(String name)
{
@@ -335,7 +337,7 @@ public class QpidTestCase extends TestCase
latch.countDown();
}
- if (latch != null && line.contains(stopped))
+ if (!seenReady && line.contains(stopped))
{
stopLine = line;
}
@@ -368,7 +370,9 @@ public class QpidTestCase extends TestCase
/**
* Return the management portin use by the broker on this main port
+ *
* @param mainPort the broker's main port.
+ *
* @return the management port that corresponds to the broker on the given port
*/
protected int getManagementPort(int mainPort)
@@ -415,9 +419,14 @@ public class QpidTestCase extends TestCase
{
port = getPort(port);
+ // Save any configuratio changes that have been made
+ saveTestConfiguration();
+
Process process = null;
if (_broker.equals(VM))
{
+ setConfigurationProperty("management.jmxport", String.valueOf(getManagementPort(port)));
+ saveTestConfiguration();
// create an in_VM broker
ApplicationRegistry.initialise(new ConfigurationFileApplicationRegistry(_configFile), port);
TransportConnection.createVMBroker(port);
@@ -438,15 +447,35 @@ public class QpidTestCase extends TestCase
env.put("PATH", env.get("PATH").concat(File.pathSeparator + qpidHome + "/bin"));
//Add the test name to the broker run.
- env.put("QPID_PNAME", "-DPNAME=\"" + _testName + "\"");
+ // DON'T change PNAME, qpid.stop needs this value.
+ env.put("QPID_PNAME", "-DPNAME=QPBRKR -DTNAME=\"" + _testName + "\"");
env.put("QPID_WORK", System.getProperty("QPID_WORK"));
// Add all the environment settings the test requested
if (!_env.isEmpty())
{
- for(Map.Entry<String,String> entry : _env.entrySet())
+ for (Map.Entry<String, String> entry : _env.entrySet())
+ {
+ env.put(entry.getKey(), entry.getValue());
+ }
+ }
+
+ String QPID_OPTS = " ";
+ // Add all the specified system properties to QPID_OPTS
+ if (!_setProperties.isEmpty())
+ {
+ for (String key : _setProperties.keySet())
+ {
+ QPID_OPTS += "-D" + key + "=" + System.getProperty(key) + " ";
+ }
+
+ if (env.containsKey("QPID_OPTS"))
{
- env.put(entry.getKey() ,entry.getValue());
+ env.put("QPID_OPTS", env.get("QPID_OPTS") + QPID_OPTS);
+ }
+ else
+ {
+ env.put("QPID_OPTS", QPID_OPTS);
}
}
@@ -484,6 +513,27 @@ public class QpidTestCase extends TestCase
_brokers.put(port, process);
}
+ public String getTestConfigFile()
+ {
+ String path = _output == null ? System.getProperty("java.io.tmpdir") : _output;
+ return path + "/" + getTestQueueName() + ".xml";
+ }
+
+ protected void saveTestConfiguration() throws ConfigurationException
+ {
+ String testConfig = getTestConfigFile();
+ //Specifiy the test configuration
+ setSystemProperty("test.config", testConfig);
+
+ // This is a work
+ if (_testConfiguration.isEmpty())
+ {
+ _testConfiguration.addProperty("test", getTestQueueName());
+ }
+
+ _testConfiguration.save(getTestConfigFile());
+ }
+
public void cleanBroker()
{
if (_brokerClean != null)
@@ -565,18 +615,12 @@ public class QpidTestCase extends TestCase
storeClass = bdb;
}
- // First we munge the config file and, if we're in a VM, set up an additional logfile
- XMLConfiguration configuration = new XMLConfiguration(_configFile);
- configuration.setProperty("virtualhosts.virtualhost." + virtualhost +
+
+ _testConfiguration.setProperty("virtualhosts.virtualhost." + virtualhost +
".store.class", storeClass.getName());
- configuration.setProperty("virtualhosts.virtualhost." + virtualhost +
+ _testConfiguration.setProperty("virtualhosts.virtualhost." + virtualhost +
".store." + DerbyMessageStore.ENVIRONMENT_PATH_PROPERTY,
- "${work}/" + virtualhost);
-
- File tmpFile = File.createTempFile("configFile", "test");
- tmpFile.deleteOnExit();
- configuration.save(tmpFile);
- _configFile = tmpFile;
+ "${QPID_WORK}/" + virtualhost);
}
/**
@@ -591,6 +635,10 @@ public class QpidTestCase extends TestCase
*/
protected String getConfigurationStringProperty(String property) throws ConfigurationException
{
+ // Call save Configuration to be sure we have saved the test specific
+ // file. As the optional status
+ saveTestConfiguration();
+
ServerConfiguration configuration = new ServerConfiguration(_configFile);
return configuration.getConfig().getString(property);
}
@@ -613,48 +661,9 @@ public class QpidTestCase extends TestCase
protected void setConfigurationProperty(String property, String value)
throws ConfigurationException, IOException
{
- XMLConfiguration configuration = new XMLConfiguration(_configFile);
-
- // If we are modifying a virtualhost value then we need to do so in
- // the virtualhost.xml file as these values overwrite the values in
- // the main config.xml file
- if (property.startsWith("virtualhosts"))
- {
- // So locate the virtualhost.xml file and use the ServerConfiguration
- // flatConfig method to get the interpolated value.
- String vhostConfigFile = ServerConfiguration.
- flatConfig(_configFile).getString("virtualhosts");
-
- // Load the vhostConfigFile
- XMLConfiguration vhostConfiguration = new XMLConfiguration(vhostConfigFile);
-
- // Set the value specified in to the vhostConfig.
- // Remembering that property will be 'virtualhosts.virtulhost....'
- // so we need to take off the 'virtualhosts.' from the start.
- vhostConfiguration.setProperty(property.substring(property.indexOf(".") + 1), value);
-
- // Write out the new virtualhost config file
- File tmpFile = File.createTempFile("virtualhost-configFile", ".xml");
- tmpFile.deleteOnExit();
- vhostConfiguration.save(tmpFile);
-
- // Change the property and value to be the new virtualhosts file
- // so that then update the value in the main config file.
- property = "virtualhosts";
- value = tmpFile.getAbsolutePath();
- }
-
- configuration.setProperty(property, value);
-
- // Write the new server config file
- File tmpFile = File.createTempFile("configFile", ".xml");
- tmpFile.deleteOnExit();
- configuration.save(tmpFile);
-
- _logger.info("Qpid Test Case now using configuration File:"
- + tmpFile.getAbsolutePath());
-
- _configFile = tmpFile;
+ //Write the value in to this configuration file which will override the
+ // defaults.
+ _testConfiguration.setProperty(property, value);
}
/**
@@ -695,14 +704,13 @@ public class QpidTestCase extends TestCase
* Add an environtmen variable for the external broker environment
*
* @param property the property to set
- * @param value the value to set it to
+ * @param value the value to set it to
*/
protected void setBrokerEnvironment(String property, String value)
{
- _env.put(property,value);
+ _env.put(property, value);
}
-
/**
* Check whether the broker is an 0.8
*
@@ -720,7 +728,7 @@ public class QpidTestCase extends TestCase
protected boolean isJavaBroker()
{
- return _brokerLanguage.equals("java");
+ return _brokerLanguage.equals("java") || _broker.equals("vm");
}
protected boolean isCppBroker()
@@ -807,7 +815,7 @@ public class QpidTestCase extends TestCase
return (AMQConnectionFactory) getInitialContext().lookup(factoryName);
}
- public Connection getConnection() throws Exception
+ public Connection getConnection() throws JMSException, NamingException
{
return getConnection("guest", "guest");
}
@@ -831,7 +839,7 @@ public class QpidTestCase extends TestCase
*
* @throws Exception if there is an error getting the connection
*/
- public Connection getConnection(String username, String password) throws Exception
+ public Connection getConnection(String username, String password) throws JMSException, NamingException
{
_logger.info("get Connection");
Connection con = getConnectionFactory().createConnection(username, password);
@@ -840,7 +848,7 @@ public class QpidTestCase extends TestCase
return con;
}
- public Connection getConnection(String username, String password, String id) throws Exception
+ public Connection getConnection(String username, String password, String id) throws JMSException, URLSyntaxException, AMQException, NamingException
{
_logger.info("get Connection");
Connection con;
@@ -860,6 +868,7 @@ public class QpidTestCase extends TestCase
/**
* Return a uniqueName for this test.
* In this case it returns a queue Named by the TestCase and TestName
+ *
* @return String name for a queue
*/
protected String getTestQueueName()
diff --git a/qpid/java/test-profiles/010Excludes b/qpid/java/test-profiles/010Excludes
index 36e7317e31..f03d62667d 100644
--- a/qpid/java/test-profiles/010Excludes
+++ b/qpid/java/test-profiles/010Excludes
@@ -83,6 +83,9 @@ org.apache.qpid.server.logging.*
// CPP Broker does not have a JMX interface to test
org.apache.qpid.management.jmx.*
+// JMX is used in this test for validation
+org.apache.qpid.server.queue.ModelTest#*
+
// 0-10 is not supported by the MethodRegistry
org.apache.qpid.test.unit.close.JavaServerCloseRaceConditionTest#*
diff --git a/qpid/java/test-profiles/08Excludes b/qpid/java/test-profiles/08Excludes
index 0866694854..b277c6d929 100644
--- a/qpid/java/test-profiles/08Excludes
+++ b/qpid/java/test-profiles/08Excludes
@@ -15,3 +15,8 @@ org.apache.qpid.server.persistent.NoLocalAfterRecoveryTest#*
org.apache.qpid.client.SessionCreateTest#*
org.apache.qpid.test.client.RollbackOrderTest#*
+
+// QPID-2097 exclude it from the InVM test runs until InVM JMX Interface is reliable
+org.apache.qpid.management.jmx.ManagementActorLoggingTest#*
+org.apache.qpid.server.queue.ModelTest#*
+
diff --git a/qpid/java/test-profiles/Excludes b/qpid/java/test-profiles/Excludes
index 7ef2a15e51..a72d3bc86c 100644
--- a/qpid/java/test-profiles/Excludes
+++ b/qpid/java/test-profiles/Excludes
@@ -13,5 +13,9 @@ org.apache.qpid.server.logging.BrokerLoggingTest#testBrokerShutdownListeningTCPS
org.apache.qpid.server.logging.BrokerLoggingTest#testBrokerShutdownStopped
org.apache.qpid.server.logging.VirtualHostLoggingTest#testVirtualhostClosure
org.apache.qpid.server.logging.MemoryMessageStoreLoggingTest#testMessageStoreClose
-org.apache.qpid.server.logging.DerbyMessageStoreLoggingTest#testMessageStoreClose
+// QPID-XXX : Test fails to start external broker due to Derby Exception.
+org.apache.qpid.server.logging.DerbyMessageStoreLoggingTest#*
+
+// QPID-2081 :The configuration changes are now highlighting the close race condition
+org.apache.qpid.server.security.acl.SimpleACLTest#*
diff --git a/qpid/java/test-profiles/cpp.testprofile b/qpid/java/test-profiles/cpp.testprofile
index 1d5416fe19..b3b979c786 100644
--- a/qpid/java/test-profiles/cpp.testprofile
+++ b/qpid/java/test-profiles/cpp.testprofile
@@ -8,6 +8,7 @@ broker.executable=${broker.dir}/qpidd
broker.module.ssl=${module.dir}/ssl.so
broker.module.cluster=${module.dir}/cluster.so
broker.module.store=${store.module.dir}/msgstore.so
+broker.stopped=Exception constructed
broker.modules=
broker.args=
diff --git a/qpid/java/test-profiles/default.testprofile b/qpid/java/test-profiles/default.testprofile
index 49d4a25b82..86a5b2efb3 100644
--- a/qpid/java/test-profiles/default.testprofile
+++ b/qpid/java/test-profiles/default.testprofile
@@ -18,9 +18,10 @@ log4j.debug=false
test.port=15672
test.mport=18999
+#Note : Management will start open second port on: mport + 100 : 19099
test.port.ssl=15671
-test.port.alt=15772
-test.port.alt.ssl=15771
+test.port.alt=25672
+test.port.alt.ssl=25671
test.exclude=true
profile.excludes=08TransientExcludes
diff --git a/qpid/python/qpid/datatypes.py b/qpid/python/qpid/datatypes.py
index f832ddae34..61643715e4 100644
--- a/qpid/python/qpid/datatypes.py
+++ b/qpid/python/qpid/datatypes.py
@@ -234,6 +234,24 @@ class RangedSet:
def add(self, lower, upper = None):
self.add_range(Range(lower, upper))
+ def empty(self):
+ for r in self.ranges:
+ if r.lower <= r.upper:
+ return False
+ return True
+
+ def max(self):
+ if self.ranges:
+ return self.ranges[-1].upper
+ else:
+ return None
+
+ def min(self):
+ if self.ranges:
+ return self.ranges[0].lower
+ else:
+ return None
+
def __iter__(self):
return iter(self.ranges)
diff --git a/qpid/python/qpid/delegates.py b/qpid/python/qpid/delegates.py
index c74cc5a945..14111a88df 100644
--- a/qpid/python/qpid/delegates.py
+++ b/qpid/python/qpid/delegates.py
@@ -139,12 +139,18 @@ class Server(Delegate):
class Client(Delegate):
+ ppid = 0
+ try:
+ ppid = os.getppid()
+ except:
+ pass
+
PROPERTIES = {"product": "qpid python client",
"version": "development",
"platform": os.name,
"qpid.client_process": os.path.basename(sys.argv[0]),
"qpid.client_pid": os.getpid(),
- "qpid.client_ppid": os.getppid()}
+ "qpid.client_ppid": ppid}
def __init__(self, connection, username="guest", password="guest",
mechanism="PLAIN", heartbeat=None):
diff --git a/qpid/python/qpid/ops.py b/qpid/python/qpid/ops.py
index 447f9953df..11e7d11fe9 100644
--- a/qpid/python/qpid/ops.py
+++ b/qpid/python/qpid/ops.py
@@ -74,10 +74,7 @@ class Compound(object):
def dispatch(self, target, *args):
handler = "do_%s" % self.NAME
- if hasattr(target, handler):
- getattr(target, handler)(self, *args)
- else:
- print "UNHANDLED:", target, args
+ getattr(target, handler)(self, *args)
def __repr__(self, extras=()):
return "%s(%s)" % (self.__class__.__name__,
diff --git a/qpid/python/tests/datatypes.py b/qpid/python/tests/datatypes.py
index b00e5e78f8..00e649d6cf 100644
--- a/qpid/python/tests/datatypes.py
+++ b/qpid/python/tests/datatypes.py
@@ -148,6 +148,34 @@ class RangedSetTest(TestCase):
assert range.lower == 0
assert range.upper == 8
+ def testEmpty(self):
+ s = RangedSet()
+ assert s.empty()
+ s.add(0, -1)
+ assert s.empty()
+ s.add(0, 0)
+ assert not s.empty()
+
+ def testMinMax(self):
+ s = RangedSet()
+ assert s.max() is None
+ assert s.min() is None
+ s.add(0, 10)
+ assert s.max() == 10
+ assert s.min() == 0
+ s.add(0, 5)
+ assert s.max() == 10
+ assert s.min() == 0
+ s.add(0, 11)
+ assert s.max() == 11
+ assert s.min() == 0
+ s.add(15, 20)
+ assert s.max() == 20
+ assert s.min() == 0
+ s.add(-10, -5)
+ assert s.max() == 20
+ assert s.min() == -10
+
class RangeTest(TestCase):
def testIntersect1(self):
diff --git a/qpid/specs/management-schema.xml b/qpid/specs/management-schema.xml
index e72ba1cdd7..c25aca67ed 100644
--- a/qpid/specs/management-schema.xml
+++ b/qpid/specs/management-schema.xml
@@ -169,7 +169,7 @@
<property name="type" type="sstr" access="RO"/>
<property name="durable" type="bool" access="RO"/>
<property name="autoDelete" type="bool" access="RO"/>
- <property name="altExchange" type="objId" access="RO" optional="y"/>
+ <property name="altExchange" type="objId" references="Exchange" access="RO" optional="y"/>
<property name="arguments" type="map" access="RO" desc="Arguments supplied in exchange.declare"/>
<statistic name="producerCount" type="hilo32" desc="Current producers on exchange"/>