You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@qpid.apache.org by or...@apache.org on 2018/04/11 16:29:07 UTC
[1/6] qpid-broker-j git commit: QPID-8158: [Broker-J] [System Tests]
Remove qpid-systest module including QpidBrokerTestCase and its dependecies
Repository: qpid-broker-j
Updated Branches:
refs/heads/master 7f0219c93 -> 768f4fb09
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/systests/src/main/resources/logback-test.xml
----------------------------------------------------------------------
diff --git a/systests/src/main/resources/logback-test.xml b/systests/src/main/resources/logback-test.xml
deleted file mode 100644
index 0df4cdb..0000000
--- a/systests/src/main/resources/logback-test.xml
+++ /dev/null
@@ -1,59 +0,0 @@
-<?xml version="1.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.
- ~
- -->
-<configuration debug="true">
-
- <contextName>qpid-systests</contextName>
-
- <!-- Logging configuration used for this and other 'systests' modules. This is named
- logback-test.xml in order that it is found in preference to the logback.xml
- found in qpid-test-utils (which is used for other, non-systests, modules). -->
-
- <define name="receiverPort" class="org.apache.qpid.test.utils.LogbackSocketPortNumberDefiner"/>
-
- <appender name="RootSiftAppender" class="ch.qos.logback.classic.sift.SiftingAppender">
- <discriminator class="org.apache.qpid.test.utils.LogbackPropertyValueDiscriminator">
- <Key>classQualifiedTestName</Key>
- <DefaultValue>testrun</DefaultValue>
- </discriminator>
- <sift>
- <appender name="FILE-${classQualifiedTestName}" class="ch.qos.logback.core.FileAppender">
- <File>${test.output.dir}${file.separator}TEST-${classQualifiedTestName}.txt</File>
- <Append>False</Append>
- <encoder>
- <!-- origin identifies the broker, valuable when the test involves multiple brokers -->
- <pattern>%date %-8X{origin} %-5level [%thread] %logger{10} %msg%n</pattern>
- </encoder>
- </appender>
- </sift>
- </appender>
- <!-- Used to receive the log output from spawned brokers so this log is a consolidated one. -->
- <receiver class="ch.qos.logback.classic.net.server.ServerSocketReceiver">
- <port>${receiverPort}</port>
- </receiver>
- <logger name="qpid.message" level="info" />
- <logger name="qpid.statistics" level="info" />
- <logger name="org.apache.qpid" level="debug" />
- <logger name="org.apache.qpid.jms.provider.amqp.FRAMES" level="trace"/>
- <root level="warn">
- <appender-ref ref="RootSiftAppender"/>
- </root>
- <shutdownHook class="ch.qos.logback.core.hook.DelayingShutdownHook"/>
-</configuration>
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org
[3/6] qpid-broker-j git commit: QPID-8158: [Broker-J] [System Tests]
Remove qpid-systest module including QpidBrokerTestCase and its dependecies
Posted by or...@apache.org.
QPID-8158: [Broker-J] [System Tests] Remove qpid-systest module including QpidBrokerTestCase and its dependecies
Project: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/repo
Commit: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/commit/768f4fb0
Tree: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/tree/768f4fb0
Diff: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/diff/768f4fb0
Branch: refs/heads/master
Commit: 768f4fb0961ff82ef49e09062ce19a7176b7d86a
Parents: 1c38d9e
Author: Alex Rudyy <or...@apache.org>
Authored: Wed Apr 11 16:09:15 2018 +0100
Committer: Alex Rudyy <or...@apache.org>
Committed: Wed Apr 11 17:27:23 2018 +0100
----------------------------------------------------------------------
bdbstore/systests/pom.xml | 5 -
pom.xml | 7 -
qpid-perftests-systests/pom.xml | 5 -
.../org/apache/qpid/test/utils/TestUtils.java | 55 ++
systests/etc/bin/fail.py | 88 --
systests/etc/config-systests.json | 66 --
systests/etc/groups-systests | 29 -
systests/etc/log.properties | 21 -
systests/pom.xml | 206 ----
.../org/apache/qpid/systest/rest/Asserts.java | 45 -
.../qpid/systest/rest/QpidRestTestCase.java | 85 --
.../qpid/systest/rest/RestTestHelper.java | 620 ------------
.../qpid/test/utils/AbstractBrokerHolder.java | 261 -----
.../qpid/test/utils/BrokerCommandHelper.java | 87 --
.../apache/qpid/test/utils/BrokerHolder.java | 50 -
.../qpid/test/utils/InternalBrokerHolder.java | 207 ----
.../utils/LogbackSocketPortNumberDefiner.java | 43 -
.../java/org/apache/qpid/test/utils/Piper.java | 121 ---
.../qpid/test/utils/QpidBrokerTestCase.java | 974 -------------------
.../apache/qpid/test/utils/ReflectionUtils.java | 259 -----
.../test/utils/ReflectionUtilsException.java | 44 -
.../qpid/test/utils/SpawnedBrokerHolder.java | 530 ----------
.../test/utils/TestBrokerConfiguration.java | 493 ----------
.../org/apache/qpid/test/utils/TestUtils.java | 55 --
systests/src/main/resources/logback-test.xml | 59 --
25 files changed, 55 insertions(+), 4360 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/bdbstore/systests/pom.xml
----------------------------------------------------------------------
diff --git a/bdbstore/systests/pom.xml b/bdbstore/systests/pom.xml
index b81f3b1..4c52564 100644
--- a/bdbstore/systests/pom.xml
+++ b/bdbstore/systests/pom.xml
@@ -39,11 +39,6 @@
<dependency>
<groupId>org.apache.qpid</groupId>
- <artifactId>qpid-systests</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.apache.qpid</groupId>
<artifactId>qpid-bdbstore</artifactId>
</dependency>
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index 5b56477..a60b7e4 100644
--- a/pom.xml
+++ b/pom.xml
@@ -191,7 +191,6 @@
<module>qpid-systests-parent</module>
<module>qpid-test-utils</module>
- <module>systests</module>
<module>systests/systests-utils</module>
<module>systests/qpid-systests-jms-core</module>
<module>systests/qpid-systests-jms_1.1</module>
@@ -396,12 +395,6 @@
<dependency>
<groupId>org.apache.qpid</groupId>
- <artifactId>qpid-systests</artifactId>
- <version>${project.version}</version>
- </dependency>
-
- <dependency>
- <groupId>org.apache.qpid</groupId>
<artifactId>qpid-test-utils</artifactId>
<version>${project.version}</version>
</dependency>
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/qpid-perftests-systests/pom.xml
----------------------------------------------------------------------
diff --git a/qpid-perftests-systests/pom.xml b/qpid-perftests-systests/pom.xml
index 57b724f..570292d 100644
--- a/qpid-perftests-systests/pom.xml
+++ b/qpid-perftests-systests/pom.xml
@@ -39,11 +39,6 @@
<artifactId>qpid-perftests</artifactId>
</dependency>
- <dependency>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid-systests</artifactId>
- </dependency>
-
<!-- client deps -->
<dependency>
<groupId>org.apache.qpid</groupId>
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/qpid-test-utils/src/main/java/org/apache/qpid/test/utils/TestUtils.java
----------------------------------------------------------------------
diff --git a/qpid-test-utils/src/main/java/org/apache/qpid/test/utils/TestUtils.java b/qpid-test-utils/src/main/java/org/apache/qpid/test/utils/TestUtils.java
new file mode 100644
index 0000000..5069e20
--- /dev/null
+++ b/qpid-test-utils/src/main/java/org/apache/qpid/test/utils/TestUtils.java
@@ -0,0 +1,55 @@
+/*
+ *
+ * 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 java.lang.management.ManagementFactory;
+import java.lang.management.ThreadInfo;
+import java.lang.management.ThreadMXBean;
+
+public class TestUtils
+{
+ public static String dumpThreads()
+ {
+ ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
+ ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(true, true);
+ StringBuilder dump = new StringBuilder();
+ dump.append(String.format("%n"));
+ for (ThreadInfo threadInfo : threadInfos)
+ {
+ dump.append(threadInfo);
+ }
+
+ long[] deadLocks = threadMXBean.findDeadlockedThreads();
+ if (deadLocks != null && deadLocks.length > 0)
+ {
+ ThreadInfo[] deadlockedThreads = threadMXBean.getThreadInfo(deadLocks);
+ dump.append(String.format("%n"));
+ dump.append("Deadlock is detected!");
+ dump.append(String.format("%n"));
+ for (ThreadInfo threadInfo : deadlockedThreads)
+ {
+ dump.append(threadInfo);
+ }
+ }
+ return dump.toString();
+ }
+}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/systests/etc/bin/fail.py
----------------------------------------------------------------------
diff --git a/systests/etc/bin/fail.py b/systests/etc/bin/fail.py
deleted file mode 100644
index 517f31d..0000000
--- a/systests/etc/bin/fail.py
+++ /dev/null
@@ -1,88 +0,0 @@
-#!/usr/bin/env python
-#
-#
-# 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.
-
-import os
-import re
-import datetime
-
-from optparse import OptionParser
-
-BASE_CMD = "mvn -Dskip.python.test=true %s test"
-
-def main():
- parser = OptionParser()
- parser.add_option("-t", "--test", dest="test",
- action="store", type="string",
- help="run specific tests")
- parser.add_option("-c", "--continuous", dest="continuous",
- action="store_true", default=False,
- help="run tests after failures, don't stop")
-
-
- (options, args) = parser.parse_args()
-
- # determine command to run
- if (options.test != None):
- cmd = (BASE_CMD % ("-Dtest="+options.test))
- else:
- cmd = (BASE_CMD % (""))
-
- run_forever = options.continuous
-
-
- failed_runs = []
- iteration = 0
- fail_match = re.compile("BUILD SUCCESSFUL")
- done = False
-
- while (run_forever or not (len(failed_runs) > 0)):
- iteration = iteration + 1
- if (run_forever):
- extra_text = (", %d failures so far: %s:" % (len(failed_runs), failed_runs))
- else:
- extra_text = ""
- print ("%s Test run %d%s" % (datetime.datetime.today().isoformat(), iteration, extra_text))
- (child_stdin, child_stdout_and_stderr) = os.popen4(cmd)
- output = child_stdout_and_stderr.read()
- child_stdin.close()
- child_stdout_and_stderr.close()
- matches = fail_match.search(output)
- if (matches == None):
- failed_runs.append(iteration)
- output_name = ("test-run-%d.out" % (iteration))
- #write testouput
- test_output = file(output_name, "w")
- test_output.write(output)
- test_output.close()
- #tar test-output and surefire reports together
- find_stdout = os.popen("find . -type d -name surefire-reports")
- surefire_dirs = find_stdout.read().replace('\n', ' ')
- find_stdout.close()
- tarcmd = ("tar -zcf test-failures-%d.tar.gz %s %s" % (iteration, output_name, surefire_dirs))
- tar_stdout = os.popen(tarcmd)
- tar_output = tar_stdout.read()
- tar_exitstatus = tar_stdout.close()
- print ("Something failed! Check %s" % (output_name))
- if (tar_exitstatus != None):
- print ("tar exited abornmally, aborting\n %s" % (tar_output))
- run_forever = False
-
-if __name__ == "__main__":
- main()
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/systests/etc/config-systests.json
----------------------------------------------------------------------
diff --git a/systests/etc/config-systests.json b/systests/etc/config-systests.json
deleted file mode 100644
index c342413..0000000
--- a/systests/etc/config-systests.json
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-{
- "name": "Broker",
- "modelVersion": "7.0",
- "authenticationproviders" : [ {
- "name" : "plain",
- "type" : "PlainPasswordFile",
- "path" : "${qpid.home_dir}${file.separator}etc${file.separator}passwd"
- } ],
- "keystores" : [ {
- "name" : "systestsKeyStore",
- "storeUrl" : "${qpid.home_dir}${file.separator}..${file.separator}test-profiles${file.separator}test_resources${file.separator}ssl${file.separator}java_broker_keystore.jks",
- "password" : "password"
- } ],
- "truststores" : [ {
- "name" : "systestsTrustStore",
- "storeUrl" : "${qpid.home_dir}${file.separator}..${file.separator}test-profiles${file.separator}test_resources${file.separator}ssl${file.separator}java_broker_truststore.jks",
- "password" : "password"
- } ],
- "ports" : [ {
- "name" : "amqp",
- "authenticationProvider" : "plain",
- "port" : "${test.port}",
- "protocols" : "${test.amqp_port_protocols}",
- "virtualhostaliases" : [ {
- "name" : "nameAlias",
- "type" : "nameAlias"
- }, {
- "name" : "defaultAlias",
- "type" : "defaultAlias"
- } ]
- }, {
- "name" : "http",
- "authenticationProvider" : "plain",
- "port" : "${test.hport}",
- "protocols" : [ "HTTP" ]
- }],
- "virtualhostnodes" : [ {
- "name" : "test",
- "type" : "${virtualhostnode.type}",
- "defaultVirtualHostNode" : "true",
- "storePath" : "${qpid.work_dir}${file.separator}test${file.separator}config",
- "context" : {
- "virtualhostBlueprint" : "${virtualhostnode.context.blueprint}"
- }
- } ]
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/systests/etc/groups-systests
----------------------------------------------------------------------
diff --git a/systests/etc/groups-systests b/systests/etc/groups-systests
deleted file mode 100644
index e3912ec..0000000
--- a/systests/etc/groups-systests
+++ /dev/null
@@ -1,29 +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.
-#
-
-#
-# To define a group, use the format:
-#
-# <groupname>.users=<user1>,<user2>,...,<usern>
-#
-
-messaging-users.users=guest,client,server
-administrators.users=admin
-webadmins.users=webadmin
-
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/systests/etc/log.properties
----------------------------------------------------------------------
diff --git a/systests/etc/log.properties b/systests/etc/log.properties
deleted file mode 100644
index ff36b7c..0000000
--- a/systests/etc/log.properties
+++ /dev/null
@@ -1,21 +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.
-#
-
-com.sleepycat.je.util.FileHandler.level=ALL
-com.sleepycat.je.util.ConsoleHandler.level=ALL
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/systests/pom.xml
----------------------------------------------------------------------
diff --git a/systests/pom.xml b/systests/pom.xml
deleted file mode 100644
index 6e132d2..0000000
--- a/systests/pom.xml
+++ /dev/null
@@ -1,206 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid-systests-parent</artifactId>
- <version>7.1.0-SNAPSHOT</version>
- <relativePath>../qpid-systests-parent/pom.xml</relativePath>
- </parent>
-
- <artifactId>qpid-systests</artifactId>
- <name>Apache Qpid Broker-J System Tests</name>
- <description>System testing configuration, code and tests</description>
-
- <dependencies>
-
- <dependency>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid-test-utils</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid-systests-jms-core</artifactId>
- </dependency>
-
- <!-- broker deps -->
- <dependency>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid-broker</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid-broker-core</artifactId>
- <classifier>tests</classifier>
- </dependency>
-
- <dependency>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid-broker-plugins-access-control</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid-broker-plugins-amqp-0-8-protocol</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid-broker-plugins-amqp-0-10-protocol</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid-broker-plugins-amqp-1-0-protocol</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid-broker-plugins-amqp-msg-conv-0-8-to-0-10</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid-broker-plugins-amqp-msg-conv-0-8-to-1-0</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid-broker-plugins-amqp-msg-conv-0-10-to-1-0</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid-broker-plugins-derby-store</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid-broker-plugins-jdbc-provider-bone</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid-broker-plugins-jdbc-store</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid-broker-plugins-logging-logback</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid-broker-plugins-management-http</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid-broker-plugins-memory-store</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid-broker-plugins-amqp-1-0-protocol-jdbc-link-store</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid-broker-plugins-amqp-1-0-protocol-bdb-link-store</artifactId>
- <optional>true</optional>
- </dependency>
-
- <dependency>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid-bdbstore</artifactId>
- <scope>test</scope>
- <optional>true</optional>
- </dependency>
-
- </dependencies>
-
- <build>
- <resources>
- <resource>
- <directory>src/main/resources</directory>
- </resource>
- </resources>
-
- <plugins>
- <plugin>
- <groupId>org.apache.rat</groupId>
- <artifactId>apache-rat-plugin</artifactId>
- <configuration>
- <excludes>
- <exclude>src/test/resources/org/apache/qpid/test/unit/message/**</exclude>
- <exclude>qpid-systests-jms-core/**</exclude>
- <exclude>qpid-systests-jms_1.1/**</exclude>
- <exclude>qpid-systests-jms_2.0/**</exclude>
- <exclude>protocol-tests-core/**</exclude>
- <exclude>protocol-tests-amqp-1-0/**</exclude>
- <exclude>protocol-tests-amqp-0-8/**</exclude>
- <exclude>protocol-tests-amqp-0-10/**</exclude>
- <exclude>systests-utils/**</exclude>
- <exclude>end-to-end-conversion-tests/**</exclude>
- </excludes>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
-
- <profiles>
- <profile>
- <id>addQpidJmsClientIfNecessary</id>
- <activation>
- <property>
- <name>!enableAmqp0-x</name>
- </property>
- </activation>
- <dependencies>
- <dependency>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid-jms-client</artifactId>
- </dependency>
- </dependencies>
- </profile>
- <profile>
- <!-- The 0-x client does not have a dependency on the JMS 1.1 spec. Add it now. -->
- <id>addJms11IfNecessary</id>
- <activation>
- <property>
- <name>enableAmqp0-x</name>
- </property>
- </activation>
- <dependencies>
- <dependency>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid-client</artifactId>
- </dependency>
- <dependency>
- <groupId>org.apache.geronimo.specs</groupId>
- <artifactId>geronimo-jms_1.1_spec</artifactId>
- </dependency>
- </dependencies>
- </profile>
- </profiles>
-</project>
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/systests/src/main/java/org/apache/qpid/systest/rest/Asserts.java
----------------------------------------------------------------------
diff --git a/systests/src/main/java/org/apache/qpid/systest/rest/Asserts.java b/systests/src/main/java/org/apache/qpid/systest/rest/Asserts.java
deleted file mode 100644
index be0dd54..0000000
--- a/systests/src/main/java/org/apache/qpid/systest/rest/Asserts.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.systest.rest;
-
-import java.util.Map;
-
-import junit.framework.TestCase;
-
-import org.apache.qpid.server.model.ConfiguredObject;
-
-public class Asserts
-{
- public static final String STATISTICS_ATTRIBUTE = "statistics";
-
-
- public static void assertActualAndDesiredState(final String expectedDesiredState,
- final String expectedActualState,
- final Map<String, Object> data)
- {
- String name = (String) data.get(ConfiguredObject.NAME);
- TestCase.assertEquals("Object with name " + name + " has unexpected desired state",
- expectedDesiredState,
- data.get(ConfiguredObject.DESIRED_STATE));
- TestCase.assertEquals("Object with name " + name + " has unexpected actual state",
- expectedActualState, data.get(ConfiguredObject.STATE));
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/systests/src/main/java/org/apache/qpid/systest/rest/QpidRestTestCase.java
----------------------------------------------------------------------
diff --git a/systests/src/main/java/org/apache/qpid/systest/rest/QpidRestTestCase.java b/systests/src/main/java/org/apache/qpid/systest/rest/QpidRestTestCase.java
deleted file mode 100644
index 06f1b4c..0000000
--- a/systests/src/main/java/org/apache/qpid/systest/rest/QpidRestTestCase.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.systest.rest;
-
-import org.apache.qpid.server.model.VirtualHostNode;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.test.utils.TestBrokerConfiguration;
-
-public class QpidRestTestCase extends QpidBrokerTestCase
-{
- public static final String EXTERNAL_AUTHENTICATION_PROVIDER = "testExternal";
-
- public static final String TEST1_VIRTUALHOST = "test";
- public static final String TEST2_VIRTUALHOST = "test2";
- public static final String TEST3_VIRTUALHOST = "test3";
-
- public static final String[] EXPECTED_VIRTUALHOSTS = { TEST1_VIRTUALHOST, TEST2_VIRTUALHOST, TEST3_VIRTUALHOST};
- public static final String[] EXPECTED_EXCHANGES = { "amq.fanout", "amq.match", "amq.direct","amq.topic" };
-
- protected RestTestHelper _restTestHelper;
-
- @Override
- public void setUp() throws Exception
- {
- // remove the normal 'test' vhost, we will configure the vhosts below
- getDefaultBrokerConfiguration().removeObjectConfiguration(VirtualHostNode.class, TestBrokerConfiguration.ENTRY_NAME_VIRTUAL_HOST);
-
- // Set up virtualhost config with queues and bindings to the amq.direct
- for (String virtualhost : EXPECTED_VIRTUALHOSTS)
- {
- createTestVirtualHostNode(virtualhost);
- }
-
- customizeConfiguration();
- super.setUp();
- }
-
- @Override
- public void startDefaultBroker() throws Exception
- {
- super.startDefaultBroker();
- _restTestHelper = new RestTestHelper(getDefaultBroker().getHttpPort());
- }
-
- @Override
- protected void tearDown() throws Exception
- {
- try
- {
- super.tearDown();
- }
- finally
- {
- getRestTestHelper().tearDown();
- }
- }
-
- protected void customizeConfiguration() throws Exception
- {
- getDefaultBrokerConfiguration().addHttpManagementConfiguration();
- }
-
- public RestTestHelper getRestTestHelper()
- {
- return _restTestHelper;
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/systests/src/main/java/org/apache/qpid/systest/rest/RestTestHelper.java
----------------------------------------------------------------------
diff --git a/systests/src/main/java/org/apache/qpid/systest/rest/RestTestHelper.java b/systests/src/main/java/org/apache/qpid/systest/rest/RestTestHelper.java
deleted file mode 100644
index 368f116..0000000
--- a/systests/src/main/java/org/apache/qpid/systest/rest/RestTestHelper.java
+++ /dev/null
@@ -1,620 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.qpid.systest.rest;
-
-import static java.nio.charset.StandardCharsets.UTF_8;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.UnsupportedEncodingException;
-import java.net.HttpURLConnection;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLEncoder;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.function.Predicate;
-
-import javax.servlet.http.HttpServletResponse;
-import javax.xml.bind.DatatypeConverter;
-
-import com.fasterxml.jackson.core.type.TypeReference;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import org.junit.Assert;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.apache.qpid.server.model.Queue;
-import org.apache.qpid.server.model.SystemConfig;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.test.utils.TestBrokerConfiguration;
-
-public class RestTestHelper
-{
-
- private static final TypeReference<List<LinkedHashMap<String, Object>>> TYPE_LIST_OF_LINKED_HASH_MAPS = new TypeReference<List<LinkedHashMap<String, Object>>>()
- {
- };
- private static final TypeReference<LinkedHashMap<String, Object>> TYPE_LINKED_HASH_MAPS = new TypeReference<LinkedHashMap<String, Object>>()
- {
- };
- public static final String API_BASE = "/api/latest/";
-
- private static final Logger LOGGER = LoggerFactory.getLogger(RestTestHelper.class);
- public static final String DEFAULT_USERNAME = "webadmin";
- public static final String DEFAULT_PASSWORD = "webadmin";
-
- private int _httpPort;
-
- private boolean _useSsl;
-
-
- private String _username;
-
- private String _password;
-
- private boolean _useSslAuth;
- static final String[] EXPECTED_QUEUES = { "queue", "ping" };
- private final int _connectTimeout = Integer.getInteger("qpid.resttest_connection_timeout", 30000);
-
- private String _truststore;
- private String _truststorePassword;
-
- private String _keystore;
- private String _keystorePassword;
-
- private String _clientAuthAlias;
- private String _acceptEncoding;
-
- public RestTestHelper(int httpPort)
- {
- _httpPort = httpPort;
- setUsernameAndPassword(DEFAULT_USERNAME, DEFAULT_PASSWORD);
- }
-
- public int getHttpPort()
- {
- return _httpPort;
- }
-
- private String getHostName()
- {
- return "localhost";
- }
-
- private String getProtocol()
- {
- return _useSsl ? "https" : "http";
- }
-
- public String getManagementURL()
- {
- return getProtocol() + "://" + getHostName() + ":" + getHttpPort();
- }
-
- public URL getManagementURL(String path) throws MalformedURLException
- {
- return new URL(getManagementURL() + path);
- }
-
- public void setKeystore(final String keystore, final String keystorePassword)
- {
- _keystore = keystore;
- _keystorePassword = keystorePassword;
- }
-
- public void setTruststore(final String truststore, final String truststorePassword)
- {
- _truststore = truststore;
- _truststorePassword = truststorePassword;
- }
-
- public void setClientAuthAlias(final String clientAuthAlias)
- {
- _clientAuthAlias = clientAuthAlias;
- }
-
- public HttpURLConnection openManagementConnection(String path, String method) throws IOException
- {
- if (!path.startsWith("/"))
- {
- path = API_BASE + path;
- }
- URL url = getManagementURL(path);
- HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
- httpCon.setConnectTimeout(_connectTimeout);
-
- if(_username != null)
- {
- String encoded = DatatypeConverter.printBase64Binary((_username + ":" + _password).getBytes(UTF_8));
- httpCon.setRequestProperty("Authorization", "Basic " + encoded);
- }
-
- if (_acceptEncoding != null && !"".equals(_acceptEncoding))
- {
- httpCon.setRequestProperty("Accept-Encoding", _acceptEncoding);
- }
-
- httpCon.setDoOutput(true);
- httpCon.setRequestMethod(method);
- return httpCon;
- }
-
- public List<Map<String, Object>> readJsonResponseAsList(HttpURLConnection connection) throws IOException
- {
- byte[] data = readConnectionInputStream(connection);
- ObjectMapper mapper = new ObjectMapper();
- List<Map<String, Object>> providedObject = mapper.readValue(new ByteArrayInputStream(data), TYPE_LIST_OF_LINKED_HASH_MAPS);
- return providedObject;
- }
-
- public Map<String, Object> readJsonResponseAsMap(HttpURLConnection connection) throws IOException
- {
- byte[] data = readConnectionInputStream(connection);
-
- ObjectMapper mapper = new ObjectMapper();
- Map<String, Object> providedObject = mapper.readValue(new ByteArrayInputStream(data), TYPE_LINKED_HASH_MAPS);
- return providedObject;
- }
-
- public <T> T readJsonResponse(HttpURLConnection connection, Class<T> valueType) throws IOException
- {
- byte[] data = readConnectionInputStream(connection);
-
- ObjectMapper mapper = new ObjectMapper();
-
- return mapper.readValue(new ByteArrayInputStream(data), valueType);
- }
-
- private byte[] readConnectionInputStream(HttpURLConnection connection) throws IOException
- {
- InputStream is = connection.getInputStream();
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
- int len = -1;
- while ((len = is.read(buffer)) != -1)
- {
- baos.write(buffer, 0, len);
- }
- if (LOGGER.isTraceEnabled())
- {
- LOGGER.trace("RESPONSE:" + new String(baos.toByteArray(), UTF_8));
- }
- return baos.toByteArray();
- }
-
- private void writeJsonRequest(HttpURLConnection connection, Object data) throws IOException
- {
- ObjectMapper mapper = new ObjectMapper();
- mapper.writeValue(connection.getOutputStream(), data);
- }
-
- public Map<String, Object> find(String name, Object value, List<Map<String, Object>> data)
- {
- if (data == null)
- {
- return null;
- }
-
- for (Map<String, Object> map : data)
- {
- Object mapValue = map.get(name);
- if (value.equals(mapValue))
- {
- return map;
- }
- }
- return null;
- }
-
- public Map<String, Object> find(Map<String, Object> searchAttributes, List<Map<String, Object>> data)
- {
- for (Map<String, Object> map : data)
- {
- boolean equals = true;
- for (Map.Entry<String, Object> entry : searchAttributes.entrySet())
- {
- Object mapValue = map.get(entry.getKey());
- if (!entry.getValue().equals(mapValue))
- {
- equals = false;
- break;
- }
- }
- if (equals)
- {
- return map;
- }
- }
- return null;
- }
-
- public Map<String, Object> getJsonAsSingletonList(String path) throws IOException
- {
- List<Map<String, Object>> response = getJsonAsList(path);
-
- Assert.assertNotNull("Response cannot be null", response);
- Assert.assertEquals("Unexpected response from " + path, 1, response.size());
- return response.get(0);
- }
-
- public Map<String, Object> postDataToPathAndGetObject(String path, Map<String, Object> data) throws IOException
- {
- HttpURLConnection connection = openManagementConnection(path, "POST");
- connection.connect();
- writeJsonRequest(connection, data);
- Map<String, Object> response = readJsonResponseAsMap(connection);
- return response;
- }
-
- public List<Map<String, Object>> getJsonAsList(String path) throws IOException
- {
- HttpURLConnection connection = openManagementConnection(path, "GET");
- connection.connect();
- List<Map<String, Object>> response = readJsonResponseAsList(connection);
- return response;
- }
-
- public List<Object> getJsonAsSimpleList(String path) throws IOException
- {
- HttpURLConnection connection = openManagementConnection(path, "GET");
- connection.connect();
- byte[] data = readConnectionInputStream(connection);
- ObjectMapper mapper = new ObjectMapper();
- List<Object> providedObject = mapper.readValue(new ByteArrayInputStream(data), new TypeReference<List<Object>>()
- {
- });
- return providedObject;
- }
-
- public Map<String, Object> getJsonAsMap(String path) throws IOException
- {
- HttpURLConnection connection = openManagementConnection(path, "GET");
- connection.connect();
- Map<String, Object> response = readJsonResponseAsMap(connection);
- return response;
- }
-
- public <T> T getJson(String path, final Class<T> valueType) throws IOException
- {
- HttpURLConnection connection = openManagementConnection(path, "GET");
- connection.connect();
- return readJsonResponse(connection, valueType);
- }
-
- public <T> T postJson(String path, final Object data , final Class<T> valueType) throws IOException
- {
- HttpURLConnection connection = openManagementConnection(path, "POST");
- connection.connect();
- writeJsonRequest(connection, data);
- return readJsonResponse(connection, valueType);
- }
-
- public void createNewGroupMember(String groupProviderName, String groupName, String memberName, int responseCode) throws IOException
- {
- HttpURLConnection connection = openManagementConnection(
- "groupmember/" + encodeAsUTF(groupProviderName) + "/"+ encodeAsUTF(groupName) + "/" + encodeAsUTF(memberName),
- "PUT");
-
- Map<String, Object> groupMemberData = new HashMap<String, Object>();
- // TODO add type
- writeJsonRequest(connection, groupMemberData);
-
- Assert.assertEquals("Unexpected response code", responseCode, connection.getResponseCode());
-
- connection.disconnect();
- }
-
- public void createNewGroupMember(String groupProviderName, String groupName, String memberName) throws IOException
- {
- createNewGroupMember(groupProviderName, groupName, memberName, HttpServletResponse.SC_CREATED);
- }
-
- public void removeMemberFromGroup(String groupProviderName, String groupName, String memberName, int responseCode) throws IOException
- {
- HttpURLConnection connection = openManagementConnection(
- "groupmember/" + encodeAsUTF(groupProviderName) + "/"+ encodeAsUTF(groupName) + "/" + encodeAsUTF(memberName),
- "DELETE");
-
- Assert.assertEquals("Unexpected response code", responseCode, connection.getResponseCode());
-
- connection.disconnect();
- }
-
- public void removeMemberFromGroup(String groupProviderName, String groupName, String memberName) throws IOException
- {
- removeMemberFromGroup(groupProviderName, groupName, memberName, HttpServletResponse.SC_OK);
- }
-
- public void assertNumberOfGroupMembers(Map<String, Object> data, int expectedNumberOfGroupMembers)
- {
- @SuppressWarnings("unchecked")
- List<Map<String, Object>> groups = (List<Map<String, Object>>) data.get("groupmembers");
- if (groups == null)
- {
- groups = Collections.emptyList();
- }
-
- Assert.assertEquals("Unexpected number of group members", expectedNumberOfGroupMembers, groups.size());
- }
-
- public void createGroup(String groupName, String groupProviderName) throws IOException
- {
- createGroup(groupName, groupProviderName, HttpServletResponse.SC_CREATED);
- }
-
- public void createGroup(String groupName, String groupProviderName, int responseCode) throws IOException
- {
- HttpURLConnection connection = openManagementConnection(
- "group/" + encodeAsUTF(groupProviderName) + "/"+ encodeAsUTF(groupName),
- "PUT");
-
- Map<String, Object> groupData = new HashMap<String, Object>();
- writeJsonRequest(connection, groupData);
-
- Assert.assertEquals("Unexpected response code", responseCode, connection.getResponseCode());
-
- connection.disconnect();
- }
-
- public void createOrUpdateUser(String username, String password) throws IOException
- {
- createOrUpdateUser(username, password, HttpServletResponse.SC_CREATED);
- }
-
- public void createOrUpdateUser(String username, String password, int responseCode) throws IOException
- {
- HttpURLConnection connection = openManagementConnection("user/"
- + TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER + "/" + username, "PUT");
-
- Map<String, Object> data = new HashMap<String, Object>();
- data.put("password", password);
- writeJsonRequest(connection, data);
-
- Assert.assertEquals("Unexpected response code", responseCode, connection.getResponseCode());
-
- connection.disconnect();
- }
-
- public void removeGroup(String groupName, String groupProviderName, int responseCode) throws IOException
- {
- HttpURLConnection connection = openManagementConnection(
- "group/" + encodeAsUTF(groupProviderName) + "/"+ encodeAsUTF(groupName),
- "DELETE");
-
- Assert.assertEquals("Unexpected response code", responseCode, connection.getResponseCode());
- connection.disconnect();
- }
-
- public void removeGroup(String groupName, String groupProviderName) throws IOException
- {
- removeGroup(groupName, groupProviderName, HttpServletResponse.SC_OK);
- }
-
- public void removeUserById(String id) throws IOException
- {
- HttpURLConnection connection = openManagementConnection("user/"
- + TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER + "?id=" + id, "DELETE");
- Assert.assertEquals("Unexpected response code", HttpServletResponse.SC_OK, connection.getResponseCode());
- connection.disconnect();
- }
-
- public void removeUser(String username, int responseCode) throws IOException
- {
- HttpURLConnection connection = openManagementConnection("user/"
- + TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER + "/" + username, "DELETE");
- Assert.assertEquals("Unexpected response code", responseCode, connection.getResponseCode());
- connection.disconnect();
- }
-
- public void removeUser(String username) throws IOException
- {
- removeUser(username, HttpServletResponse.SC_OK);
- }
-
- public void assertNumberOfGroups(Map<String, Object> data, int expectedNumberOfGroups)
- {
- @SuppressWarnings("unchecked")
- List<Map<String, Object>> groups = (List<Map<String, Object>>) data.get("groups");
- if (groups == null)
- {
- groups = Collections.emptyList();
- }
- Assert.assertEquals("Unexpected number of groups", expectedNumberOfGroups, groups.size());
- }
-
- public void setUsernameAndPassword(String username, String password)
- {
- _username = username;
- _password = password;
- }
-
- public void setManagementModeCredentials()
- {
- setUsernameAndPassword(SystemConfig.MANAGEMENT_MODE_USER_NAME, QpidBrokerTestCase.MANAGEMENT_MODE_PASSWORD);
- }
-
- public void tearDown()
- {
-
- }
-
-
- public int submitRequest(String url, String method, Object data) throws IOException
- {
- return submitRequest(url, method, data, null);
- }
-
- public int submitRequest(String url, String method, Object data, Map<String, List<String>> responseHeadersToCapture) throws IOException
- {
- HttpURLConnection connection = openManagementConnection(url, method);
- if (data != null)
- {
- writeJsonRequest(connection, data);
- }
- int responseCode = connection.getResponseCode();
- if (responseHeadersToCapture!= null)
- {
- responseHeadersToCapture.putAll(connection.getHeaderFields());
- }
- connection.disconnect();
- return responseCode;
- }
-
- public int submitRequest(String url, String method) throws IOException
- {
- return submitRequest(url, method, (byte[])null);
- }
-
- public void submitRequest(String url, String method, Object data, int expectedResponseCode) throws IOException
- {
- Map<String, List<String>> headers = new HashMap<>();
- int responseCode = submitRequest(url, method, data, headers);
- Assert.assertEquals("Unexpected response code from " + method + " " + url , expectedResponseCode, responseCode);
- if (expectedResponseCode == 201)
- {
- List<String> location = headers.get("Location");
- Assert.assertTrue("Location is not returned by REST create request", location != null && location.size() == 1);
- }
- }
-
- public void submitRequest(String url, String method, int expectedResponseCode) throws IOException
- {
- submitRequest(url, method, null, expectedResponseCode);
- }
-
- public int submitRequest(String url, String method, byte[] parameters) throws IOException
- {
- HttpURLConnection connection = openManagementConnection(url, method);
- if (parameters != null)
- {
- OutputStream os = connection.getOutputStream();
- os.write(parameters);
- os.flush();
- }
- int responseCode = connection.getResponseCode();
- connection.disconnect();
- return responseCode;
- }
-
- public byte[] getBytes(String path) throws IOException
- {
- HttpURLConnection connection = openManagementConnection(path, "GET");
- connection.connect();
- return readConnectionInputStream(connection);
- }
-
- public void setUseSslAuth(final boolean useSslAuth)
- {
- _useSslAuth = useSslAuth;
- _useSsl = true;
- }
-
- public void createTestQueues() throws IOException
- {
- for (int i = 0; i < EXPECTED_QUEUES.length; i++)
- {
- String queueName = EXPECTED_QUEUES[i];
- Map<String, Object> queueData = new HashMap<>();
- queueData.put(Queue.NAME, queueName);
- queueData.put(Queue.DURABLE, Boolean.FALSE);
- int responseCode = submitRequest("queue/test/test/" + queueName, "PUT", queueData);
- Assert.assertEquals("Unexpected response code creating queue" + queueName, 201, responseCode);
-
- Map<String, Object> bindingData = new HashMap<>();
- bindingData.put("bindingKey", queueName);
- bindingData.put("destination", queueName);
- responseCode = submitRequest("exchange/test/test/amq.direct/bind", "POST", bindingData);
- Assert.assertEquals("Unexpected response code binding queue " + queueName, 200, responseCode);
- }
- }
-
- public String encode(String value, String encoding) throws UnsupportedEncodingException
- {
- return URLEncoder.encode(value, encoding).replace("+", "%20");
- }
-
- public String encodeAsUTF(String value)
- {
- try
- {
- return encode(value, "UTF8");
- }
- catch(UnsupportedEncodingException e)
- {
- throw new RuntimeException("Unsupported encoding UTF8", e);
- }
- }
-
- public Map<String, Object> waitForAttributeChanged(String url,
- String attributeName,
- Object newValue) throws Exception
- {
- return waitForAttributeChanged(url, (attr -> newValue.equals(attr.get(attributeName))));
-
- }
-
- public Map<String, Object> waitForAttributeChanged(String url,
- Predicate<Map<String, Object>> attributePredicate) throws Exception
- {
- Map<String, Object> nodeAttributes = getAttributesIgnoringNotFound(url);
- int timeout = 30000;
- long limit = System.currentTimeMillis() + timeout;
- while(System.currentTimeMillis() < limit && (nodeAttributes == null || !attributePredicate.test(nodeAttributes)))
- {
- Thread.sleep(100L);
- nodeAttributes = getAttributesIgnoringNotFound(url);
- }
- Assert.assertTrue(String.format("Attributes predicate not satisfied after %d ms. Last attribute state state : %s",
- timeout,
- nodeAttributes), attributePredicate.test(nodeAttributes));
- return nodeAttributes;
- }
-
- private Map<String, Object> getAttributesIgnoringNotFound(String url) throws IOException
- {
- Map<String, Object> nodeAttributes;
- try
- {
- nodeAttributes = getJsonAsMap(url);
- }
- catch(FileNotFoundException e)
- {
- nodeAttributes = null;
- }
- return nodeAttributes;
- }
-
- public String getAcceptEncoding()
- {
- return _acceptEncoding;
- }
-
- public void setAcceptEncoding(String acceptEncoding)
- {
- _acceptEncoding = acceptEncoding;
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/systests/src/main/java/org/apache/qpid/test/utils/AbstractBrokerHolder.java
----------------------------------------------------------------------
diff --git a/systests/src/main/java/org/apache/qpid/test/utils/AbstractBrokerHolder.java b/systests/src/main/java/org/apache/qpid/test/utils/AbstractBrokerHolder.java
deleted file mode 100644
index 4c447f7..0000000
--- a/systests/src/main/java/org/apache/qpid/test/utils/AbstractBrokerHolder.java
+++ /dev/null
@@ -1,261 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.qpid.test.utils;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.HashSet;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.apache.qpid.server.util.FileUtils;
-
-public abstract class AbstractBrokerHolder implements BrokerHolder
-{
- private static final String RELATIVE_BROKER_CONFIG_PATH = "config.json";
- private static final AtomicInteger BROKER_INDEX = new AtomicInteger();
- private static final Logger LOGGER = LoggerFactory.getLogger(AbstractBrokerHolder.class);
-
- private final String _classQualifiedTestName;
- private final File _logFile;
- private final String _brokerStoreType;
- private final String _configurationPath;
- private final int _brokerIndex;
- private final String _amqpTcpPortRegExp;
- private final String _initialConfigurationPath;
- private final String _httpTcpPortRegExp;
- private final String _amqpTlsPortRegExp;
- private final String _httpTlsPortRegExp;
- private final Path _qpidWorkDir;
-
- private TestBrokerConfiguration _configuration;
- private int _amqpPort;
- private int _httpPort;
- private int _amqpTlsPort;
- private int _httpsPort;
- private boolean _waitForPorts;
-
- public AbstractBrokerHolder(int port, String classQualifiedTestName, File logFile)
- {
- _amqpPort = port;
- _brokerIndex = BROKER_INDEX.getAndIncrement();
- _classQualifiedTestName = classQualifiedTestName;
- _logFile = logFile;
- _initialConfigurationPath = System.getProperty("broker.config");
- _brokerStoreType = System.getProperty("broker.config-store-type", "JSON");
- _amqpTcpPortRegExp =
- System.getProperty("broker.amqpTcpPortRegEx", "BRK-1002 : Starting : Listening on TCP port (\\d+)");
- _httpTcpPortRegExp = System.getProperty("broker.httpTcpPortRegEx",
- "MNG-1002 : Starting : HTTP : Listening on TCP port (\\d+)");
- _amqpTlsPortRegExp =
- System.getProperty("broker.amqpTlsPortRegEx", "BRK-1002 : Starting : Listening on SSL port (\\d+)");
- _httpTlsPortRegExp = System.getProperty("broker.httpTlsPortRegEx",
- "MNG-1002 : Starting : HTTP : Listening on SSL port (\\d+)");
- _waitForPorts = !Boolean.getBoolean("qpid.test_nowait_for_ports");
-
- try
- {
- _qpidWorkDir = Files.createTempDirectory("qpid-work-" + _classQualifiedTestName + "-" + _brokerIndex + "-");
- _configurationPath = _qpidWorkDir.toAbsolutePath().resolve(RELATIVE_BROKER_CONFIG_PATH).toString();
- }
- catch (IOException e)
- {
- throw new RuntimeException("Cannot create work directory", e);
- }
- }
-
- @Override
- public Path getWorkDir()
- {
- return _qpidWorkDir;
- }
-
- @Override
- public String getConfigurationPath()
- {
- return _configurationPath;
- }
-
- @Override
- public int getBrokerIndex()
- {
- return _brokerIndex;
- }
-
- @Override
- public int getAmqpPort()
- {
- return _amqpPort;
- }
-
- @Override
- public int getHttpPort()
- {
- return _httpPort;
- }
-
- @Override
- public int getHttpsPort()
- {
- return _httpsPort;
- }
-
- @Override
- public int getAmqpTlsPort()
- {
- return _amqpTlsPort;
- }
-
- @Override
- public void cleanUp()
- {
- getConfiguration().cleanUp();
- FileUtils.delete(getWorkDir().toFile(), true);
- }
-
- @Override
- public TestBrokerConfiguration getConfiguration()
- {
- if (_configuration == null)
- {
- _configuration = createBrokerConfiguration();
- }
- return _configuration;
- }
-
- @Override
- public void restart() throws Exception
- {
- shutdown();
- start();
- }
-
- @Override
- public void start() throws Exception
- {
- start(false);
- }
-
- @Override
- public void start(boolean managementMode) throws Exception
- {
- saveConfiguration(getConfiguration());
- start(managementMode, _amqpPort);
- if (_amqpPort <= 0)
- {
- _amqpPort = scrapePortFromLog(_logFile, _amqpTcpPortRegExp);
- }
- if (_amqpTlsPort <= 0)
- {
- _amqpTlsPort = scrapePortFromLog(_logFile, _amqpTlsPortRegExp);
- }
- if (_httpPort <= 0)
- {
- _httpPort = scrapePortFromLog(_logFile, _httpTcpPortRegExp);
- }
- if (_httpsPort <= 0)
- {
- _httpsPort = scrapePortFromLog(_logFile, _httpTlsPortRegExp);
- }
- }
-
- @Override
- public void createVirtualHostNode(final String virtualHostNodeName,
- final String storeType,
- final String storeDir,
- final String blueprint)
- {
- getConfiguration().createVirtualHostNode(virtualHostNodeName, storeType, storeDir, blueprint);
- }
-
- protected TestBrokerConfiguration createBrokerConfiguration()
- {
- return new TestBrokerConfiguration(_brokerStoreType, new File(_initialConfigurationPath).getAbsolutePath());
- }
-
- protected String getClassQualifiedTestName()
- {
- return _classQualifiedTestName;
- }
-
- void waitUntilPortsAreFreeIfRequired()
- {
- if (_waitForPorts)
- {
- Set<Integer> ports = new HashSet<>();
- ports.add(getAmqpPort());
- ports.add(getAmqpTlsPort());
- ports.add(getHttpPort());
- ports.add(getHttpsPort());
- new PortHelper().waitUntilPortsAreFree(ports);
- }
- }
-
- abstract protected String getLogPrefix();
-
-
- protected abstract void start(final boolean managementMode, final int amqpPort) throws Exception;
-
- private void saveConfiguration(TestBrokerConfiguration testConfiguration)
- {
- if (testConfiguration != null && !testConfiguration.isSaved())
- {
- LOGGER.info("Saving test broker configuration at: " + _configurationPath);
- testConfiguration.save(new File(_configurationPath));
- testConfiguration.setSaved(true);
- }
- }
-
- private int scrapePortFromLog(final File logFile, final String portRegEx) throws IOException
- {
- final String logPrefix = getLogPrefix();
- Pattern portPattern = Pattern.compile(portRegEx);
- try (BufferedReader br = new BufferedReader(new FileReader(logFile)))
- {
- String line = null;
- while ((line = br.readLine()) != null)
- {
- if (logPrefix == null || line.contains(logPrefix))
- {
- Matcher matcher = portPattern.matcher(line);
- if (matcher.find() && matcher.groupCount() > 0)
- {
- return Integer.valueOf(matcher.group(1)).intValue();
- }
- }
- }
- }
- return 0;
- }
-
- String getBrokerStoreType()
- {
- return _brokerStoreType;
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/systests/src/main/java/org/apache/qpid/test/utils/BrokerCommandHelper.java
----------------------------------------------------------------------
diff --git a/systests/src/main/java/org/apache/qpid/test/utils/BrokerCommandHelper.java b/systests/src/main/java/org/apache/qpid/test/utils/BrokerCommandHelper.java
deleted file mode 100644
index f381702..0000000
--- a/systests/src/main/java/org/apache/qpid/test/utils/BrokerCommandHelper.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.qpid.test.utils;
-
-import java.util.LinkedList;
-import java.util.List;
-
-/**
- * Generates the command to start a broker by substituting the tokens
- * in the provided broker command.
- *
- * The command is returned as a list so that it can be easily used by a
- * {@link java.lang.ProcessBuilder}.
- */
-public class BrokerCommandHelper
-{
- private final List<String> _brokerCommandTemplateAsList;
-
- public BrokerCommandHelper(String brokerCommandTemplate)
- {
- _brokerCommandTemplateAsList = split(brokerCommandTemplate);
- }
-
- public String[] getBrokerCommand(int port, String qpidWork, String storePath, String storeType)
- {
- String[] command = new String[_brokerCommandTemplateAsList.size()];
- int i=0;
- for (String commandPart : _brokerCommandTemplateAsList)
- {
- command[i] = commandPart
- .replace("@PORT", "" + port)
- .replace("@QPID_WORK", qpidWork)
- .replace("@STORE_PATH", storePath)
- .replace("@STORE_TYPE", storeType);
- i++;
- }
- return command;
- }
-
- private static List<String> split(String str)
- {
- List<String> tokens = new LinkedList<String>();
- boolean inQuote = false;
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < str.length(); i++)
- {
- char c = str.charAt(i);
-
- if (c == '\"' || c == '\'')
- {
- inQuote = !inQuote;
- }
- else if (c == ' ' && !inQuote)
- {
- if (sb.length() > 0)
- {
- tokens.add(sb.toString());
- sb.delete(0, sb.length());
- }
- }
- else
- {
- sb.append(c);
- }
- }
- if (sb.length() > 0)
- {
- tokens.add(sb.toString());
- }
- return tokens;
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/systests/src/main/java/org/apache/qpid/test/utils/BrokerHolder.java
----------------------------------------------------------------------
diff --git a/systests/src/main/java/org/apache/qpid/test/utils/BrokerHolder.java b/systests/src/main/java/org/apache/qpid/test/utils/BrokerHolder.java
deleted file mode 100644
index 9373c4c..0000000
--- a/systests/src/main/java/org/apache/qpid/test/utils/BrokerHolder.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.utils;
-
-import java.nio.file.Path;
-
-public interface BrokerHolder
-{
- void start() throws Exception;
- void start(boolean managementMode) throws Exception;
- void restart() throws Exception;
- void shutdown();
- void kill();
- void cleanUp();
- String dumpThreads();
- void createVirtualHostNode(String virtualHostNodeName, String storeType, String storeDir, String blueprint);
- TestBrokerConfiguration getConfiguration();
- String getConfigurationPath();
- Path getWorkDir();
- int getBrokerIndex();
- int getAmqpPort();
- int getHttpPort();
- int getHttpsPort();
- int getAmqpTlsPort();
-
- enum BrokerType
- {
- EXTERNAL /** Test case relies on a Broker started independently of the test-suite */,
- INTERNAL /** Test case starts an embedded broker within this JVM */,
- SPAWNED /** Test case spawns a new broker as a separate process */
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/systests/src/main/java/org/apache/qpid/test/utils/InternalBrokerHolder.java
----------------------------------------------------------------------
diff --git a/systests/src/main/java/org/apache/qpid/test/utils/InternalBrokerHolder.java b/systests/src/main/java/org/apache/qpid/test/utils/InternalBrokerHolder.java
deleted file mode 100644
index c73ba61..0000000
--- a/systests/src/main/java/org/apache/qpid/test/utils/InternalBrokerHolder.java
+++ /dev/null
@@ -1,207 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.utils;
-
-import java.io.File;
-import java.security.PrivilegedAction;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import javax.security.auth.Subject;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.apache.qpid.server.SystemLauncher;
-import org.apache.qpid.server.SystemLauncherListener;
-import org.apache.qpid.server.logging.logback.LogbackLoggingSystemLauncherListener;
-import org.apache.qpid.server.model.ConfiguredObject;
-import org.apache.qpid.server.model.IllegalStateTransitionException;
-import org.apache.qpid.server.model.SystemConfig;
-import org.apache.qpid.server.security.auth.TaskPrincipal;
-
-public class InternalBrokerHolder extends AbstractBrokerHolder
-{
- private final static Logger LOGGER = LoggerFactory.getLogger(InternalBrokerHolder.class);
- private final static UncaughtExceptionHandler UNCAUGHT_EXCEPTION_HANDLER = new UncaughtExceptionHandler();
-
- private volatile SystemLauncher _systemLauncher;
-
- public InternalBrokerHolder(int port, final String classQualifiedTestName, final File logFile)
- {
- super(port, classQualifiedTestName, logFile);
- }
-
-
- @Override
- protected void start(final boolean managementMode, final int amqpPort) throws Exception
- {
-
- Map<String,String> context = new HashMap<>();
- context.put("test.hport", String.valueOf(getHttpPort()));
- context.put("qpid.home_dir", System.getProperty("QPID_HOME"));
- context.put("qpid.work_dir", getWorkDir().toString());
-
- context.put("test.port", String.valueOf(amqpPort));
-
- Map<String,Object> attributes = new HashMap<>();
-
- attributes.put(ConfiguredObject.CONTEXT, context);
- attributes.put(ConfiguredObject.TYPE, getBrokerStoreType());
- attributes.put("storePath", getConfigurationPath());
-
- attributes.put(SystemConfig.MANAGEMENT_MODE, managementMode);
-
- if(managementMode)
- {
- attributes.put(SystemConfig.MANAGEMENT_MODE_PASSWORD, QpidBrokerTestCase.MANAGEMENT_MODE_PASSWORD);
- }
-
- start(attributes);
-
- }
-
- public void start(final Map<String,Object> systemConfig) throws Exception
- {
- if (Thread.getDefaultUncaughtExceptionHandler() == null)
- {
- Thread.setDefaultUncaughtExceptionHandler(UNCAUGHT_EXCEPTION_HANDLER);
- }
-
- LOGGER.info("Starting internal broker (same JVM)");
-
- _systemLauncher = new SystemLauncher(new LogbackLoggingSystemLauncherListener(),
- new SystemLauncherListener.DefaultSystemLauncherListener()
- {
- @Override
- public void onShutdown(final int exitCode)
- {
- _systemLauncher = null;
- }
-
- @Override
- public void exceptionOnShutdown(final Exception e)
- {
- if (e instanceof IllegalStateException
- || e instanceof IllegalStateTransitionException)
- {
- System.out.println(
- "IllegalStateException occurred on broker shutdown in test "
- + getClassQualifiedTestName());
- }
- }
- });
-
- _systemLauncher.startup(systemConfig);
- }
-
- @Override
- public void shutdown()
- {
- if (_systemLauncher != null)
- {
- LOGGER.info("Shutting down Broker instance");
- Subject shutdownSubject = new Subject(true,
- new HashSet<>(Arrays.asList(_systemLauncher.getSystemPrincipal(), new TaskPrincipal("Shutdown"))),
- Collections.emptySet(),
- Collections.emptySet());
- Subject.doAs(shutdownSubject, new PrivilegedAction<Object>()
- {
- @Override
- public Object run()
- {
- if (_systemLauncher != null)
- {
- _systemLauncher.shutdown();
- }
- return null;
- }
- });
- waitUntilPortsAreFreeIfRequired();
- LOGGER.info("Broker instance shutdown");
- }
- else
- {
- LOGGER.info("Nothing to shutdown. Broker instance either was already shut down or not started at all.");
- }
-
- if (UNCAUGHT_EXCEPTION_HANDLER.getAndResetCount() > 0)
- {
- throw new RuntimeException(
- "One or more uncaught exceptions occurred prior to end of this test. Check test logs.");
- }
- }
-
- @Override
- public void kill()
- {
- // Can't kill a internal broker as we would also kill ourselves as we share the same JVM.
- shutdown();
- }
-
- @Override
- public String dumpThreads()
- {
- return TestUtils.dumpThreads();
- }
-
- @Override
- public String toString()
- {
- return "InternalBrokerHolder [amqpPort=" + getAmqpPort() + "]";
- }
-
- @Override
- protected String getLogPrefix()
- {
- return null;
- }
-
- private static class UncaughtExceptionHandler implements Thread.UncaughtExceptionHandler
- {
- private final AtomicInteger _count = new AtomicInteger(0);
-
- @Override
- public void uncaughtException(final Thread t, final Throwable e)
- {
- System.err.print("Thread terminated due to uncaught exception");
- e.printStackTrace();
-
- LOGGER.error("Uncaught exception from thread {}", t.getName(), e);
- _count.getAndIncrement();
- }
-
- public int getAndResetCount()
- {
- int count;
- do
- {
- count = _count.get();
- }
- while (!_count.compareAndSet(count, 0));
- return count;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/systests/src/main/java/org/apache/qpid/test/utils/LogbackSocketPortNumberDefiner.java
----------------------------------------------------------------------
diff --git a/systests/src/main/java/org/apache/qpid/test/utils/LogbackSocketPortNumberDefiner.java b/systests/src/main/java/org/apache/qpid/test/utils/LogbackSocketPortNumberDefiner.java
deleted file mode 100644
index 4b59d5e..0000000
--- a/systests/src/main/java/org/apache/qpid/test/utils/LogbackSocketPortNumberDefiner.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.test.utils;
-
-import ch.qos.logback.core.PropertyDefinerBase;
-
-public class LogbackSocketPortNumberDefiner extends PropertyDefinerBase
-{
- /**
- * Port number that will be bound by a Logback Socket Receiver. This is assigned once per JVM instance.
- */
- private static final int LOGBACK_SOCKET_PORT_NUMBER = new PortHelper().getNextAvailable(Integer.getInteger("qpid.logback.receiver.port", 15000));
-
- public static int getLogbackSocketPortNumber()
- {
- return LOGBACK_SOCKET_PORT_NUMBER;
- }
-
- @Override
- public String getPropertyValue()
- {
- return String.valueOf(LOGBACK_SOCKET_PORT_NUMBER);
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/systests/src/main/java/org/apache/qpid/test/utils/Piper.java
----------------------------------------------------------------------
diff --git a/systests/src/main/java/org/apache/qpid/test/utils/Piper.java b/systests/src/main/java/org/apache/qpid/test/utils/Piper.java
deleted file mode 100644
index 5eb604d..0000000
--- a/systests/src/main/java/org/apache/qpid/test/utils/Piper.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.utils;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public final class Piper extends Thread
-{
- private static final Logger LOGGER = LoggerFactory.getLogger(Piper.class);
-
- private final BufferedReader _in;
- private final Logger _out;
- private final String _ready;
- private final CountDownLatch _latch;
- private final String _stopped;
- private volatile boolean _seenReady;
- private volatile String _stopLine;
-
- public Piper(InputStream in, String ready, String stopped, String threadName, String loggerName)
- {
- super(threadName);
- _in = new BufferedReader(new InputStreamReader(in));
- _out = LoggerFactory.getLogger(loggerName);
- _ready = ready;
- _stopped = stopped;
- _seenReady = false;
-
- if (this._ready != null && !this._ready.equals(""))
- {
- this._latch = new CountDownLatch(1);
- }
- else
- {
- this._latch = null;
- }
- }
-
- public boolean await(long timeout, TimeUnit unit) throws InterruptedException
- {
- if (_latch == null)
- {
- return true;
- }
- else
- {
- _latch.await(timeout, unit);
- return _seenReady;
- }
- }
-
- @Override
- public void run()
- {
- try
- {
- String line;
- while ((line = _in.readLine()) != null)
- {
- _out.info(line);
-
- if (_latch != null && line.contains(_ready))
- {
- _seenReady = true;
- _latch.countDown();
- }
-
- if (!_seenReady && line.contains(_stopped))
- {
- _stopLine = line;
- }
- }
- }
- catch (IOException e)
- {
- LOGGER.warn(e.getMessage() + " : Broker stream from unexpectedly closed; last log lines written by Broker may be lost.");
- }
- finally
- {
- if (_latch != null)
- {
- _latch.countDown();
- }
- }
- }
-
- public String getStopLine()
- {
- return _stopLine;
- }
-
- String getReady()
- {
- return _ready;
- }
-}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org
[2/6] qpid-broker-j git commit: QPID-8158: [Broker-J] [System Tests]
Remove qpid-systest module including QpidBrokerTestCase and its dependecies
Posted by or...@apache.org.
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/systests/src/main/java/org/apache/qpid/test/utils/QpidBrokerTestCase.java
----------------------------------------------------------------------
diff --git a/systests/src/main/java/org/apache/qpid/test/utils/QpidBrokerTestCase.java b/systests/src/main/java/org/apache/qpid/test/utils/QpidBrokerTestCase.java
deleted file mode 100755
index 0725d69..0000000
--- a/systests/src/main/java/org/apache/qpid/test/utils/QpidBrokerTestCase.java
+++ /dev/null
@@ -1,974 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.qpid.test.utils;
-
-import static org.apache.qpid.systests.Utils.getAmqpManagementFacade;
-import static org.apache.qpid.systests.Utils.getProtocol;
-
-import java.io.File;
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-import java.net.URISyntaxException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.EnumSet;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-
-import javax.jms.BytesMessage;
-import javax.jms.Connection;
-import javax.jms.ConnectionFactory;
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.MapMessage;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.ObjectMessage;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.jms.StreamMessage;
-import javax.jms.TextMessage;
-import javax.jms.Topic;
-import javax.naming.NamingException;
-
-import ch.qos.logback.classic.sift.SiftingAppender;
-import ch.qos.logback.classic.spi.ILoggingEvent;
-import ch.qos.logback.core.Appender;
-import ch.qos.logback.core.FileAppender;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.apache.qpid.server.model.Protocol;
-import org.apache.qpid.server.store.MemoryConfigurationStore;
-import org.apache.qpid.systests.AmqpManagementFacade;
-import org.apache.qpid.systests.ConnectionBuilder;
-import org.apache.qpid.systests.JmsProvider;
-import org.apache.qpid.systests.Utils;
-
-/**
- * Qpid base class for system testing test cases.
- */
-public class QpidBrokerTestCase extends QpidTestCase
-{
- public static final int LOGBACK_REMOTE_PORT = LogbackSocketPortNumberDefiner.getLogbackSocketPortNumber();
- public static final String GUEST_USERNAME = "guest";
- public static final String GUEST_PASSWORD = "guest";
- public static final String PROFILE_USE_SSL = "profile.use_ssl";
- public static final String TEST_AMQP_PORT_PROTOCOLS_PROPERTY = "test.amqp_port_protocols";
- public static final int DEFAULT_PORT = Integer.getInteger("test.port", 0);
- public static final int FAILING_PORT = Integer.getInteger("test.port.alt", 0);
- public static final int DEFAULT_SSL_PORT = Integer.getInteger("test.port.ssl", 0);
- public static final String QUEUE = "queue";
- public static final String TOPIC = "topic";
- public static final String MANAGEMENT_MODE_PASSWORD = "mm_password";
- private static final Logger LOGGER = LoggerFactory.getLogger(QpidBrokerTestCase.class);
- protected static final long RECEIVE_TIMEOUT = Long.getLong("qpid.test_receive_timeout", 1000L);
- protected static final String INDEX = "index";
- protected static final String CONTENT = "content";
- protected static final int DEFAULT_MESSAGE_SIZE = 1024;
- private static final String JAVA = "java";
- private static final String BROKER_LANGUAGE = System.getProperty("broker.language", JAVA);
- private static final BrokerHolder.BrokerType DEFAULT_BROKER_TYPE = BrokerHolder.BrokerType.valueOf(
- System.getProperty("broker.type", BrokerHolder.BrokerType.INTERNAL.name()).toUpperCase());
- private static final Boolean BROKER_CLEAN_BETWEEN_TESTS = Boolean.getBoolean("broker.clean.between.tests");
- private static final Boolean BROKER_PERSISTENT = Boolean.getBoolean("broker.persistent");
- private static final Protocol BROKER_PROTOCOL = getProtocol();
- private static List<BrokerHolder> _brokerList = new ArrayList<>();
-
- private final Map<String, String> _propertiesSetForBroker = new HashMap<>();
- private final List<Connection> _connections = new ArrayList<>();
- private AmqpManagementFacade _managementFacade;
- private BrokerHolder _defaultBroker;
- private MessageType _messageType = MessageType.TEXT;
-
- private JmsProvider _jmsProvider;
-
- @Override
- public void runBare() throws Throwable
- {
- try
- {
- _managementFacade = getAmqpManagementFacade();
- _jmsProvider = Utils.getJmsProvider();
-
- _defaultBroker = new BrokerHolderFactory().create(DEFAULT_BROKER_TYPE, DEFAULT_PORT, this);
- super.runBare();
- }
- catch (Exception e)
- {
- LOGGER.error("exception", e);
- throw e;
- }
- finally
- {
- stopAllBrokers();
-
- // reset properties used in the test
- revertSystemProperties();
-
- LOGGER.info("========== stop " + getTestName() + " ==========");
- }
- }
-
- public Logger getLogger()
- {
- return QpidBrokerTestCase.LOGGER;
- }
-
- public File getOutputFile()
- {
- final ch.qos.logback.classic.Logger logger =
- (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
-
- return getFileFromSiftingAppender(logger);
- }
-
- public BrokerHolder getDefaultBroker()
- {
- return _defaultBroker;
- }
-
- public void startDefaultBroker() throws Exception
- {
- startDefaultBroker(false);
- }
-
- public void startDefaultBroker(boolean managementMode) throws Exception
- {
- getDefaultBroker().start(managementMode);
- setTestSystemProperty("test.port", getDefaultBroker().getAmqpPort() + "");
- }
-
- public void stopDefaultBroker() throws Exception
- {
- getDefaultBroker().shutdown();
- }
-
- public TestBrokerConfiguration getDefaultBrokerConfiguration()
- {
- return getDefaultBroker().getConfiguration();
- }
-
- public BrokerHolder createSpawnedBroker() throws Exception
- {
- return createSpawnedBroker(0);
- }
-
- public BrokerHolder createSpawnedBroker(int amqpPort) throws Exception
- {
- return new BrokerHolderFactory().create(BrokerHolder.BrokerType.SPAWNED, amqpPort, this);
- }
-
- public void killDefaultBroker()
- {
- getDefaultBroker().kill();
- }
-
- /**
- * Check whether the broker is an 0.8
- *
- * @return true if the broker is an 0_8 version, false otherwise.
- */
- public boolean isBroker08()
- {
- return BROKER_PROTOCOL.equals(Protocol.AMQP_0_8);
- }
-
- public boolean isBrokerPre010()
- {
- return EnumSet.of(Protocol.AMQP_0_8, Protocol.AMQP_0_9, Protocol.AMQP_0_9_1).contains(BROKER_PROTOCOL);
- }
-
- public boolean isBroker010()
- {
- return BROKER_PROTOCOL.equals(Protocol.AMQP_0_10);
- }
-
- public boolean isBroker10()
- {
- return BROKER_PROTOCOL.equals(Protocol.AMQP_1_0);
- }
-
- public Protocol getBrokerProtocol()
- {
- return BROKER_PROTOCOL;
- }
-
- public void restartDefaultBroker() throws Exception
- {
- getDefaultBroker().restart();
- }
-
- public JmsProvider getJmsProvider()
- {
- return _jmsProvider;
- }
-
- public ConnectionBuilder getConnectionBuilder()
- {
- final ConnectionBuilder connectionBuilder = _jmsProvider.getConnectionBuilder()
- .setPort(Integer.getInteger("test.port"))
- .setSslPort(Integer.getInteger("test.port.ssl"))
- .setVirtualHost("test")
- .setTls(Boolean.getBoolean(PROFILE_USE_SSL))
- .setPopulateJMSXUserID(true)
- .setUsername(GUEST_USERNAME)
- .setPassword(GUEST_PASSWORD);
-
- return (ConnectionBuilder) Proxy.newProxyInstance(getClass().getClassLoader(),
- new Class<?>[]{ConnectionBuilder.class},
- new ConectionBuilderHandler(connectionBuilder, _connections));
- }
-
- /**
- * Get the default connection factory for the currently used broker
- * Default factory is "local"
- *
- * @return A connection factory
- * @throws NamingException if there is an error getting the factory
- */
- public ConnectionFactory getConnectionFactory() throws NamingException
- {
- return getConnectionFactory(Collections.emptyMap());
- }
-
- public ConnectionFactory getConnectionFactory(final Map<String, String> options) throws NamingException
- {
- return getConnectionBuilder().setOptions(options).buildConnectionFactory();
- }
-
- public Connection getConnection() throws JMSException, NamingException
- {
- return getConnection(GUEST_USERNAME, GUEST_PASSWORD);
- }
-
- public Connection getConnection(String username, String password) throws JMSException, NamingException
- {
- return getConnectionBuilder().setUsername(username).setPassword(password).build();
- }
-
- public Connection getConnectionWithPrefetch(int prefetch) throws Exception
- {
- return getConnectionBuilder().setPrefetch(prefetch).build();
- }
-
- public Connection getConnectionWithOptions(Map<String, String> options) throws Exception
- {
- return getConnectionBuilder().setOptions(options).build();
- }
-
- public Connection getConnectionWithOptions(String vhost, Map<String, String> options) throws Exception
- {
- return getConnectionBuilder().setOptions(options)
- .setVirtualHost(vhost)
- .build();
- }
-
- public Connection getConnectionForVHost(String vhost) throws Exception
- {
- return getConnectionBuilder().setVirtualHost(vhost).build();
- }
-
- public Connection getConnection(String urlString) throws Exception
- {
- Connection connection = _jmsProvider.getConnection(urlString);
- _connections.add(connection);
- return connection;
- }
-
- public Queue getTestQueue() throws NamingException
- {
- return _jmsProvider.getTestQueue(getTestQueueName());
- }
-
- public Queue getQueueFromName(Session session, String name) throws JMSException
- {
- return _jmsProvider.getQueueFromName(session, name);
- }
-
- public Queue createTestQueue(Session session) throws JMSException
- {
- return _jmsProvider.createQueue(session, getTestQueueName());
- }
-
- public Queue createTestQueue(Session session, String queueName) throws JMSException
- {
- return _jmsProvider.createQueue(session, queueName);
- }
-
- /**
- * Return a Topic specific for this test.
- * Uses getTestQueueName() as the name of the topic
- */
- public Topic getTestTopic() throws NamingException
- {
- return _jmsProvider.getTestTopic(getTestQueueName());
- }
-
- protected Topic createTopic(final Connection con, final String topicName) throws JMSException
- {
- return _jmsProvider.createTopic(con, topicName);
- }
-
- protected Topic createTopicOnDirect(final Connection con, String topicName) throws JMSException, URISyntaxException
- {
- return _jmsProvider.createTopicOnDirect(con, topicName);
- }
-
- protected Topic createTopicOnFanout(final Connection con, String topicName) throws JMSException, URISyntaxException
- {
- return _jmsProvider.createTopicOnFanout(con, topicName);
- }
-
- protected void createEntityUsingAmqpManagement(final String name, final Session session, final String type)
- throws JMSException
- {
- _managementFacade.createEntityUsingAmqpManagement(name, session, type);
- }
-
- protected void createEntityUsingAmqpManagement(final String name, final Session session, final String type, Map<String, Object> attributes)
- throws JMSException
- {
-
- _managementFacade.createEntityUsingAmqpManagement(name, session, type, attributes);
- }
-
- protected void updatenEntityUsingAmqpManagement(final String name, final Session session, final String type, Map<String, Object> attributes)
- throws JMSException
- {
- _managementFacade.updateEntityUsingAmqpManagement(name, session, type, attributes);
- }
-
- protected void deleteEntityUsingAmqpManagement(final String name, final Session session, final String type)
- throws JMSException
- {
-
- _managementFacade.deleteEntityUsingAmqpManagement(name, session, type);
- }
-
- protected Object performOperationUsingAmqpManagement(final String name, final String operation, final Session session, final String type, Map<String,Object> arguments)
- throws JMSException
- {
- return _managementFacade.performOperationUsingAmqpManagement(name, operation, session, type, arguments);
- }
-
- protected List<Map<String, Object>> managementQueryObjects(final Session session, final String type) throws JMSException
- {
-
- return _managementFacade.managementQueryObjects(session, type);
- }
-
- protected Map<String, Object> managementReadObject(Session session, String type, String name, boolean actuals) throws JMSException
- {
- return _managementFacade.readEntityUsingAmqpManagement(session, type, name, actuals);
- }
-
- public long getQueueDepth(final Connection con, final Queue destination) throws Exception
- {
- Connection connection = getConnection();
- try
- {
- connection.start();
- Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- try
- {
- return _managementFacade.getQueueDepth(destination, session);
- }
-
- finally
- {
- session.close();
- }
- }
- finally
- {
- connection.close();
- }
- }
-
- public boolean isQueueExist(final Connection con, final Queue destination) throws Exception
- {
- Connection connection = getConnection();
- try
- {
- connection.start();
- Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- try
- {
- return _managementFacade.isQueueExist(destination, session);
- }
-
- finally
- {
- session.close();
- }
- }
- finally
- {
- connection.close();
- }
- }
-
- /**
- * Send messages to the given destination.
- * <p/>
- * If session is transacted then messages will be committed before returning
- *
- * @param session the session to use for sending
- * @param destination where to send them to
- * @param count no. of messages to send
- * @return the sent messages
- * @throws Exception
- */
- public List<Message> sendMessage(Session session, Destination destination,
- int count) throws Exception
- {
- return sendMessage(session, destination, count, 0, 0);
- }
-
- /**
- * Send messages to the given destination.
- * <p/>
- * If session is transacted then messages will be committed before returning
- *
- * @param session the session to use for sending
- * @param destination where to send them to
- * @param count no. of messages to send
- * @param batchSize the batchSize in which to commit, 0 means no batching,
- * but a single commit at the end
- * @return the sent message
- * @throws Exception
- */
- public List<Message> sendMessage(Session session, Destination destination,
- int count, int batchSize) throws Exception
- {
- return sendMessage(session, destination, count, 0, batchSize);
- }
-
- /**
- * Send messages to the given destination.
- * <p/>
- * If session is transacted then messages will be committed before returning
- *
- * @param session the session to use for sending
- * @param destination where to send them to
- * @param count no. of messages to send
- * @param offset offset allows the INDEX value of the message to be adjusted.
- * @param batchSize the batchSize in which to commit, 0 means no batching,
- * but a single commit at the end
- * @return the sent message
- * @throws Exception
- */
- public List<Message> sendMessage(Session session, Destination destination,
- int count, int offset, int batchSize) throws Exception
- {
- List<Message> messages = new ArrayList<>(count);
-
- MessageProducer producer = session.createProducer(destination);
-
- int i = offset;
- for (; i < (count + offset); i++)
- {
- Message next = createNextMessage(session, i);
-
- producer.send(next);
-
- if (session.getTransacted() && batchSize > 0)
- {
- if (i % batchSize == 0)
- {
- session.commit();
- }
- }
-
- messages.add(next);
- }
-
- // Ensure we commit the last messages
- // Commit the session if we are transacted and
- // we have no batchSize or
- // our count is not divible by batchSize.
- if (session.getTransacted() &&
- (batchSize == 0 || (i - 1) % batchSize != 0))
- {
- session.commit();
- }
-
- return messages;
- }
-
- public Message createNextMessage(Session session, int msgCount) throws JMSException
- {
- Message message = createMessage(session, DEFAULT_MESSAGE_SIZE);
- message.setIntProperty(INDEX, msgCount);
-
- return message;
- }
-
- public Message createMessage(Session session, int messageSize) throws JMSException
- {
- String payload = new String(new byte[messageSize]);
-
- Message message;
-
- switch (_messageType)
- {
- case BYTES:
- message = session.createBytesMessage();
- ((BytesMessage) message).writeUTF(payload);
- break;
- case MAP:
- message = session.createMapMessage();
- ((MapMessage) message).setString(CONTENT, payload);
- break;
- default: // To keep the compiler happy
- case TEXT:
- message = session.createTextMessage();
- ((TextMessage) message).setText(payload);
- break;
- case OBJECT:
- message = session.createObjectMessage();
- ((ObjectMessage) message).setObject(payload);
- break;
- case STREAM:
- message = session.createStreamMessage();
- ((StreamMessage) message).writeString(payload);
- break;
- }
-
- return message;
- }
-
- public String getBrokerDetailsFromDefaultConnectionUrl()
- {
- return "tcp://localhost:" + (getDefaultBroker().getAmqpTlsPort() > 0
- ? getDefaultBroker().getAmqpTlsPort()
- : getDefaultBroker().getAmqpPort());
- }
-
- /**
- * Tests that a connection is functional by producing and consuming a single message.
- * Will fail if failover interrupts either transaction.
- */
- public void assertProducingConsuming(final Connection connection) throws Exception
- {
- Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
- Destination destination = session.createQueue(getTestQueueName());
- MessageConsumer consumer = session.createConsumer(destination);
- sendMessage(session, destination, 1);
- session.commit();
- connection.start();
- Message m1 = consumer.receive(getReceiveTimeout());
- assertNotNull("Message 1 is not received", m1);
- assertEquals("Unexpected first message received", 0, m1.getIntProperty(INDEX));
- session.commit();
- session.close();
- }
-
- @Override
- protected void setUp() throws Exception
- {
- super.setUp();
- startDefaultBroker();
- }
-
- @Override
- protected void tearDown() throws java.lang.Exception
- {
- LOGGER.debug("tearDown started");
- try
- {
- for (Connection c : _connections)
- {
- c.close();
- }
- }
- finally
- {
- try
- {
- _defaultBroker.shutdown();
- }
- finally
- {
- super.tearDown();
- }
- }
- }
-
- protected int getDefaultAmqpPort()
- {
- return getDefaultBroker().getAmqpPort();
- }
-
- protected boolean stopBrokerSafely(BrokerHolder broker)
- {
- boolean success = true;
- try
- {
- broker.shutdown();
-
- if (BROKER_CLEAN_BETWEEN_TESTS)
- {
- broker.cleanUp();
- }
- }
- catch (Exception e)
- {
- success = false;
- LOGGER.error("Failed to stop broker " + broker, e);
- if (broker != null)
- {
- // save the thread dump in case of dead locks
- try
- {
- LOGGER.error("Broker " + broker + " thread dump:" + broker.dumpThreads());
- }
- finally
- {
- try
- {
- broker.kill();
- }
- catch (Exception killException)
- {
- // ignore
- }
- }
- }
- }
- return success;
- }
-
- protected void createTestVirtualHostNode(String virtualHostNodeName)
- {
- createTestVirtualHostNode(getDefaultBroker(), virtualHostNodeName, true);
- }
-
- protected void createTestVirtualHostNode(BrokerHolder broker, String virtualHostNodeName, boolean withBlueprint)
- {
- String storeType = getTestProfileVirtualHostNodeType();
- String storeDir = null;
-
- if (System.getProperty("profile", "").startsWith("java-dby-mem"))
- {
- storeDir = ":memory:";
- }
- else if (!MemoryConfigurationStore.TYPE.equals(storeType))
- {
- storeDir = "${qpid.work_dir}" + File.separator + virtualHostNodeName;
- }
-
- String blueprint = null;
- if (withBlueprint)
- {
- blueprint = getTestProfileVirtualHostNodeBlueprint();
- }
-
- broker.createVirtualHostNode(virtualHostNodeName, storeType, storeDir, blueprint);
- }
-
- /**
- * Set a System property for the duration of this test.
- * <p/>
- * When the test run is complete the value will be reverted.
- * <p/>
- * The values set using this method will also be propagated to the external
- * Apache Qpid Broker-J via a -D value defined in QPID_OPTS.
- * <p/>
- * If the value should not be set on the broker then use
- * setTestClientSystemProperty().
- *
- * @param property the property to set
- * @param value the new value to use
- */
- protected void setSystemProperty(String property, String value)
- {
- synchronized (_propertiesSetForBroker)
- {
- // Record the value for the external broker
- if (value == null)
- {
- _propertiesSetForBroker.remove(property);
- }
- else
- {
- _propertiesSetForBroker.put(property, value);
- }
- }
- //Set the value for the test client vm aswell.
- setTestClientSystemProperty(property, value);
- }
-
- /**
- * Set a System property for the client (and broker if using the same vm) of this test.
- *
- * @param property The property to set
- * @param value the value to set it to.
- */
- protected void setTestClientSystemProperty(String property, String value)
- {
- setTestSystemProperty(property, value);
- }
-
- /**
- * Restore the System property values that were set before this test run.
- */
- protected void revertSystemProperties()
- {
- revertTestSystemProperties();
-
- // We don't change the current VMs settings for Broker only properties
- // so we can just clear this map
- _propertiesSetForBroker.clear();
- }
-
- protected boolean isJavaBroker()
- {
- return BROKER_LANGUAGE.equals("java");
- }
-
- protected boolean isCppBroker()
- {
- return BROKER_LANGUAGE.equals("cpp");
- }
-
- protected boolean isExternalBroker()
- {
- return !isInternalBroker();
- }
-
- protected boolean isInternalBroker()
- {
- return DEFAULT_BROKER_TYPE.equals(BrokerHolder.BrokerType.INTERNAL);
- }
-
- protected boolean isBrokerStorePersistent()
- {
- return BROKER_PERSISTENT;
- }
-
- protected Connection getConnectionWithSyncPublishing() throws Exception
- {
- return getConnectionBuilder().setSyncPublish(true).build();
- }
-
- protected Connection getClientConnection(String username, String password, String id)
- throws Exception
- {
- return getConnectionBuilder().setClientId(id).setUsername(username).setPassword(password).build();
- }
-
- /**
- * 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()
- {
- return getClass().getSimpleName() + "-" + getName();
- }
-
- protected int getFailingPort()
- {
- return FAILING_PORT;
- }
-
- @Override
- protected void setTestOverriddenProperties(Properties properties)
- {
- for (String propertyName : properties.stringPropertyNames())
- {
- setSystemProperty(propertyName, properties.getProperty(propertyName));
- }
- }
-
- protected long getReceiveTimeout()
- {
- return Long.getLong("qpid.test_receive_timeout", 1000L);
- }
-
- protected long getLongReceiveTimeout()
- {
- return Long.getLong("qpid.test_receive_long_timeout", 5000L);
- }
-
- protected long getShortReceiveTimeout()
- {
- return Long.getLong("qpid.test_receive_short_timeout", 500L);
- }
-
- private File getFileFromSiftingAppender(final ch.qos.logback.classic.Logger logger)
- {
- String key = logger.getLoggerContext().getProperty(LogbackPropertyValueDiscriminator.CLASS_QUALIFIED_TEST_NAME);
-
- for (Iterator<Appender<ILoggingEvent>> index = logger.iteratorForAppenders(); index.hasNext(); /* do nothing */)
- {
- Appender<ILoggingEvent> appender = index.next();
- if (appender instanceof SiftingAppender)
- {
- SiftingAppender siftingAppender = (SiftingAppender) appender;
- Appender subAppender = siftingAppender.getAppenderTracker().find(key);
- if (subAppender instanceof FileAppender)
- {
- return new File(((FileAppender) subAppender).getFile());
- }
- }
- }
- return null;
- }
-
- private boolean existingInternalBroker()
- {
- for (BrokerHolder holder : _brokerList)
- {
- if (holder instanceof InternalBrokerHolder)
- {
- return true;
- }
- }
-
- return false;
- }
-
- private void stopAllBrokers()
- {
- boolean exceptionOccurred = false;
- for (BrokerHolder brokerHolder : _brokerList)
- {
- if (!stopBrokerSafely(brokerHolder))
- {
- exceptionOccurred = true;
- }
- }
- _brokerList.clear();
- if (exceptionOccurred)
- {
- throw new RuntimeException("Exception occurred on stopping of test broker. Please, examine logs for details");
- }
- }
-
- private Map<String, String> getJvmProperties()
- {
- Map<String, String> jvmOptions = new HashMap<>();
- synchronized (_propertiesSetForBroker)
- {
- jvmOptions.putAll(_propertiesSetForBroker);
-
- copySystemProperty("test.port", jvmOptions);
- copySystemProperty("test.hport", jvmOptions);
- copySystemProperty("test.port.ssl", jvmOptions);
- copySystemProperty("test.port.alt", jvmOptions);
- copySystemProperty("test.port.alt.ssl", jvmOptions);
- copySystemProperty("test.amqp_port_protocols", jvmOptions);
-
- copySystemProperty("qpid.globalAddressDomains", jvmOptions);
-
- copySystemProperty("virtualhostnode.type", jvmOptions);
- copySystemProperty("virtualhostnode.context.blueprint", jvmOptions);
- }
- return jvmOptions;
- }
-
- private void copySystemProperty(String name, Map<String, String> jvmOptions)
- {
- String value = System.getProperty(name);
- if (value != null)
- {
- jvmOptions.put(name, value);
- }
- }
-
- /**
- * Type of message
- */
- protected enum MessageType
- {
- BYTES,
- MAP,
- OBJECT,
- STREAM,
- TEXT
- }
-
- public static class BrokerHolderFactory
- {
- public BrokerHolder create(BrokerHolder.BrokerType brokerType, int port, QpidBrokerTestCase testCase)
- {
- // This will force the creation of the file appender
- LOGGER.debug("Creating BrokerHolder");
-
- final File logFile = testCase.getOutputFile();
- final String classQualifiedTestName = testCase.getClassQualifiedTestName();
- BrokerHolder holder = null;
- if (brokerType.equals(BrokerHolder.BrokerType.INTERNAL) && !testCase.existingInternalBroker())
- {
- holder = new InternalBrokerHolder(port, classQualifiedTestName, logFile);
- }
- else if (!brokerType.equals(BrokerHolder.BrokerType.EXTERNAL))
- {
- Map<String, String> jvmOptions = testCase.getJvmProperties();
- Map<String, String> environmentProperties = new HashMap<>(testCase._propertiesSetForBroker);
-
- holder = new SpawnedBrokerHolder(port, classQualifiedTestName, logFile,
- jvmOptions, environmentProperties);
- }
- _brokerList.add(holder);
- return holder;
- }
- }
-
- private static class ConectionBuilderHandler implements InvocationHandler
- {
- private final ConnectionBuilder _connectionBuilder;
- private final List<Connection> _connections;
-
- public ConectionBuilderHandler(final ConnectionBuilder connectionBuilder,
- final List<Connection> connections)
- {
- _connectionBuilder = connectionBuilder;
- _connections = connections;
- }
-
- @Override
- public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable
- {
- if (method.getName().equals("build"))
- {
- Connection connection = _connectionBuilder.build();
- _connections.add(connection);
- return connection;
- }
- else if (method.getName().equals("buildConnectionFactory"))
- {
- return _connectionBuilder.buildConnectionFactory();
- }
- else
- {
- method.invoke(_connectionBuilder, args);
- return proxy;
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/systests/src/main/java/org/apache/qpid/test/utils/ReflectionUtils.java
----------------------------------------------------------------------
diff --git a/systests/src/main/java/org/apache/qpid/test/utils/ReflectionUtils.java b/systests/src/main/java/org/apache/qpid/test/utils/ReflectionUtils.java
deleted file mode 100644
index 83294c1..0000000
--- a/systests/src/main/java/org/apache/qpid/test/utils/ReflectionUtils.java
+++ /dev/null
@@ -1,259 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.utils;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Field;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-
-/**
- * Provides helper methods for operating on classes and methods using reflection. Reflection methods tend to return
- * a lot of checked exception so writing code to use them can be tedious and harder to read, especially when such errors
- * are not expected to occur. This class always works with {@link ReflectionUtilsException}, which is a runtime exception,
- * to wrap the checked exceptions raised by the standard Java reflection methods. Code using it does not normally
- * expect these errors to occur, usually does not have a recovery mechanism for them when they do, but is cleaner,
- * quicker to write and easier to read in the majority of cases.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Look up Classes by name.
- * <tr><td> Instantiate Classes by no-arg constructor.
- * </table>
- */
-public class ReflectionUtils
-{
- /**
- * Gets the Class object for a named class.
- *
- * @param className The class to get the Class object for.
- *
- * @return The Class object for the named class.
- */
- public static Class<?> forName(String className)
- {
- try
- {
- return Class.forName(className);
- }
- catch (ClassNotFoundException e)
- {
- throw new ReflectionUtilsException("ClassNotFoundException whilst finding class.", e);
- }
- }
-
- /**
- * Creates an instance of a Class, instantiated through its no-args constructor.
- *
- * @param cls The Class to instantiate.
- * @param <T> The Class type.
- *
- * @return An instance of the class.
- */
- public static <T> T newInstance(Class<? extends T> cls)
- {
- try
- {
- return cls.newInstance();
- }
- catch (InstantiationException e)
- {
- throw new ReflectionUtilsException("InstantiationException whilst instantiating class.", e);
- }
- catch (IllegalAccessException e)
- {
- throw new ReflectionUtilsException("IllegalAccessException whilst instantiating class.", e);
- }
- }
-
- /**
- * Calls a named method on an object with a specified set of parameters, any Java access modifier are overridden.
- *
- * @param o The object to call.
- * @param method The method name to call.
- * @param params The parameters to pass.
- * @param paramClasses The argument types.
- *
- * @return The return value from the method call.
- */
- public static Object callMethodOverridingIllegalAccess(Object o, String method, Object[] params, Class[] paramClasses)
- {
- // Get the objects class.
- Class cls = o.getClass();
-
- // Get the classes of the parameters.
- /*Class[] paramClasses = new Class[params.length];
-
- for (int i = 0; i < params.length; i++)
- {
- paramClasses[i] = params[i].getClass();
- }*/
-
- try
- {
- // Try to find the matching method on the class.
- Method m = cls.getDeclaredMethod(method, paramClasses);
-
- // Make it accessible.
- m.setAccessible(true);
-
- // Invoke it with the parameters.
- return m.invoke(o, params);
- }
- catch (NoSuchMethodException e)
- {
- throw new ReflectionUtilsException("NoSuchMethodException.", e);
- }
- catch (IllegalAccessException e)
- {
- throw new ReflectionUtilsException("IllegalAccessException.", e);
- }
- catch (InvocationTargetException e)
- {
- throw new ReflectionUtilsException("InvocationTargetException", e);
- }
- }
-
- /**
- * Calls a named method on an object with a specified set of parameters.
- *
- * @param o The object to call.
- * @param method The method name to call.
- * @param params The parameters to pass.
- *
- * @return The return value from the method call.
- */
- public static Object callMethod(Object o, String method, Object[] params)
- {
- // Get the objects class.
- Class cls = o.getClass();
-
- // Get the classes of the parameters.
- Class[] paramClasses = new Class[params.length];
-
- for (int i = 0; i < params.length; i++)
- {
- paramClasses[i] = params[i].getClass();
- }
-
- try
- {
- // Try to find the matching method on the class.
- Method m = cls.getMethod(method, paramClasses);
-
- // Invoke it with the parameters.
- return m.invoke(o, params);
- }
- catch (NoSuchMethodException e)
- {
- throw new ReflectionUtilsException("NoSuchMethodException.", e);
- }
- catch (IllegalAccessException e)
- {
- throw new ReflectionUtilsException("IllegalAccessException", e);
- }
- catch (InvocationTargetException e)
- {
- throw new ReflectionUtilsException("InvocationTargetException", e);
- }
- }
-
- /**
- * Calls a constuctor witht the specified arguments.
- *
- * @param constructor The constructor.
- * @param args The arguments.
- * @param <T> The Class type.
- *
- * @return An instance of the class that the constructor is for.
- */
- public static <T> T newInstance(Constructor<T> constructor, Object[] args)
- {
- try
- {
- return constructor.newInstance(args);
- }
- catch (InstantiationException e)
- {
- throw new ReflectionUtilsException("InstantiationException", e);
- }
- catch (IllegalAccessException e)
- {
- throw new ReflectionUtilsException("IllegalAccessException", e);
- }
- catch (InvocationTargetException e)
- {
- throw new ReflectionUtilsException("InvocationTargetException", e);
- }
- }
-
- /**
- * Gets the constructor of a class that takes the specified set of arguments if any matches. If no matching
- * constructor is found then a runtime exception is raised.
- *
- * @param cls The class to get a constructor from.
- * @param args The arguments to match.
- * @param <T> The class type.
- *
- * @return The constructor.
- */
- public static <T> Constructor<T> getConstructor(Class<T> cls, Class[] args)
- {
- try
- {
- return cls.getConstructor(args);
- }
- catch (NoSuchMethodException e)
- {
- throw new ReflectionUtilsException("NoSuchMethodException", e);
- }
- }
-
- @SuppressWarnings("unchecked")
- public static <T> T getDeclaredField(final Object obj, final String fieldName)
- {
- try
- {
- final Field field = obj.getClass().getDeclaredField(fieldName);
- if (!field.isAccessible())
- {
- field.setAccessible(true);
- }
- return (T) field.get(obj);
- }
- catch (NoSuchFieldException e)
- {
- throw new ReflectionUtilsException("Unable to read field " + fieldName + "from object " + obj, e);
- }
- catch (SecurityException e)
- {
- throw new ReflectionUtilsException("Unable to read field " + fieldName + "from object " + obj, e);
- }
- catch (IllegalArgumentException e)
- {
- throw new ReflectionUtilsException("Unable to read field " + fieldName + "from object " + obj, e);
- }
- catch (IllegalAccessException e)
- {
- throw new ReflectionUtilsException("Unable to read field " + fieldName + "from object " + obj, e);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/systests/src/main/java/org/apache/qpid/test/utils/ReflectionUtilsException.java
----------------------------------------------------------------------
diff --git a/systests/src/main/java/org/apache/qpid/test/utils/ReflectionUtilsException.java b/systests/src/main/java/org/apache/qpid/test/utils/ReflectionUtilsException.java
deleted file mode 100644
index 8388285..0000000
--- a/systests/src/main/java/org/apache/qpid/test/utils/ReflectionUtilsException.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.utils;
-
-/**
- * Wraps a checked exception that occurs when {@link ReflectionUtils} encounters checked exceptions using standard
- * Java reflection methods.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Wrap a checked reflection exception.
- * </table>
- */
-public class ReflectionUtilsException extends RuntimeException
-{
- /**
- * Creates a runtime reflection exception, from a checked one.
- *
- * @param message The message.
- * @param cause The causing exception.
- */
- public ReflectionUtilsException(String message, Throwable cause)
- {
- super(message, cause);
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/systests/src/main/java/org/apache/qpid/test/utils/SpawnedBrokerHolder.java
----------------------------------------------------------------------
diff --git a/systests/src/main/java/org/apache/qpid/test/utils/SpawnedBrokerHolder.java b/systests/src/main/java/org/apache/qpid/test/utils/SpawnedBrokerHolder.java
deleted file mode 100644
index 6156f36..0000000
--- a/systests/src/main/java/org/apache/qpid/test/utils/SpawnedBrokerHolder.java
+++ /dev/null
@@ -1,530 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.utils;
-
-import java.io.BufferedReader;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.TimeUnit;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.apache.qpid.server.Main;
-import org.apache.qpid.server.logging.logback.BrokerLogbackSocketLogger;
-import org.apache.qpid.server.logging.logback.BrokerNameAndLevelLogInclusionRule;
-import org.apache.qpid.server.logging.messages.BrokerMessages;
-import org.apache.qpid.server.model.BrokerLogInclusionRule;
-import org.apache.qpid.server.model.BrokerLogger;
-import org.apache.qpid.server.util.SystemUtils;
-
-public class SpawnedBrokerHolder extends AbstractBrokerHolder
-{
- private static final Logger LOGGER = LoggerFactory.getLogger(SpawnedBrokerHolder.class);
- protected static final String BROKER_READY = System.getProperty("broker.ready", BrokerMessages.READY().toString());
- private static final String BROKER_STOPPED = System.getProperty("broker.stopped", BrokerMessages.STOPPED().toString());
- private static final String BROKER_COMMAND_PLATFORM = "broker.command." + SystemUtils.getOSConfigSuffix();
- private static final String BROKER_COMMAND_TEMPLATE = System.getProperty(BROKER_COMMAND_PLATFORM, System.getProperty("broker.command"));
- private static final int BROKER_STARTUP_TIME = Integer.parseInt(System.getProperty("SpawnedBrokerHolder.brokerStartupTime", "30000"));
-
- private final Map<String, String> _jvmOptions;
- private final Map<String, String> _environmentSettings;
- protected BrokerCommandHelper _brokerCommandHelper;
-
- private Process _process;
- private Integer _pid;
- private List<String> _windowsPids;
- private String _brokerCommand;
- private String _pseudoThreadName;
-
- public SpawnedBrokerHolder(final int port,
- final String classQualifiedTestName,
- final File logFile,
- Map<String, String> jvmOptions,
- Map<String, String> environmentSettings)
- {
- super(port, classQualifiedTestName, logFile);
- _jvmOptions = jvmOptions;
- _environmentSettings = environmentSettings;
- _brokerCommandHelper = new BrokerCommandHelper(BROKER_COMMAND_TEMPLATE);
- _pseudoThreadName = "BROKER-" + getBrokerIndex();
- }
-
- @Override
- public void start(final boolean managementMode, final int amqpPort) throws Exception
- {
- LOGGER.debug("Spawning broker with jvmOptions: {} environmentSettings: {} permitted start-up time: {}",
- _jvmOptions, _environmentSettings, BROKER_STARTUP_TIME);
-
- String[] cmd = _brokerCommandHelper.getBrokerCommand(amqpPort,
- getWorkDir().toString(),
- getConfigurationPath(),
- getBrokerStoreType());
- if (managementMode)
- {
- String[] newCmd = new String[cmd.length + 3];
- System.arraycopy(cmd, 0, newCmd, 0, cmd.length);
- newCmd[cmd.length] = "-mm";
- newCmd[cmd.length + 1] = "-mmpass";
- newCmd[cmd.length + 2] = QpidBrokerTestCase.MANAGEMENT_MODE_PASSWORD;
- cmd = newCmd;
- }
-
- // bat files will treat = as an argument separator, so if an argument contains = it needs to be quoted
- if(cmd[0].endsWith(".bat"))
- {
- for(int i = 1 ; i < cmd.length; i++)
- {
- String orig = cmd[i];
- if(orig.contains("=") && !orig.contains("\""))
- {
- cmd[i] = "\"" + orig + "\"";
- }
- }
- }
-
- ProcessBuilder pb = new ProcessBuilder(cmd);
- pb.redirectErrorStream(true);
- Map<String, String> processEnv = pb.environment();
- String qpidHome = System.getProperty(Main.PROPERTY_QPID_HOME);
- processEnv.put(Main.PROPERTY_QPID_HOME, qpidHome);
-
- //Augment Path with bin directory in QPID_HOME.
- boolean foundPath = false;
- final String pathEntry = qpidHome + File.separator + "bin";
- for(Map.Entry<String,String> entry : processEnv.entrySet())
- {
- if(entry.getKey().equalsIgnoreCase("path"))
- {
- entry.setValue(entry.getValue().concat(File.pathSeparator + pathEntry));
- foundPath = true;
- }
- }
- if(!foundPath)
- {
- processEnv.put("PATH", pathEntry);
- }
- //Add the test name to the broker run.
- // DON'T change PNAME, qpid.stop needs this value.
- processEnv.put("QPID_PNAME", "-DPNAME=QPBRKR -DTNAME=\"" + getClassQualifiedTestName() + "\"");
-
- // Add all the environment settings the test requested
- if (!_environmentSettings.isEmpty())
- {
- for (Map.Entry<String, String> entry : _environmentSettings.entrySet())
- {
- processEnv.put(entry.getKey(), entry.getValue());
- }
- }
-
- String qpidOpts = "";
-
- // Add all the specified system properties to QPID_OPTS
- if (!_jvmOptions.isEmpty())
- {
- boolean isWindows = SystemUtils.isWindows();
- for (String key : _jvmOptions.keySet())
- {
- qpidOpts += " -D" + key + "=" +(isWindows ? doWindowsCommandEscaping(_jvmOptions.get(key)) : _jvmOptions.get(key));
- }
- }
-
- if (processEnv.containsKey("QPID_OPTS"))
- {
- qpidOpts = processEnv.get("QPID_OPTS") + qpidOpts;
- }
- processEnv.put("QPID_OPTS", qpidOpts);
-
- _process = pb.start();
-
- Piper standardOutputPiper = new Piper(_process.getInputStream(),
- BROKER_READY,
- BROKER_STOPPED,
- _pseudoThreadName, getClass().getName());
-
- standardOutputPiper.start();
-
- StringBuilder cmdLine = new StringBuilder(cmd[0]);
- for(int i = 1; i< cmd.length; i++)
- {
- cmdLine.append(' ');
- cmdLine.append(cmd[i]);
- }
-
- _brokerCommand = cmdLine.toString();
- _pid = retrieveUnixPidIfPossible();
-
- if (!standardOutputPiper.await(BROKER_STARTUP_TIME, TimeUnit.MILLISECONDS))
- {
- LOGGER.info("Spawned broker failed to become ready within {} ms."
- + " Ready line '{}'",
- BROKER_STARTUP_TIME, standardOutputPiper.getReady());
- String threadDump = dumpThreads();
- if (!threadDump.isEmpty())
- {
- LOGGER.info("the result of a try to capture thread dump:" + threadDump);
- }
- //Ensure broker has stopped
- _process.destroy();
- throw new RuntimeException(String.format("Broker failed to become ready within %d ms. Stop line : %s",
- BROKER_STARTUP_TIME,
- standardOutputPiper.getStopLine()));
- }
-
- _windowsPids = retrieveWindowsPidsIfPossible();
-
- try
- {
- //test that the broker is still running and hasn't exited unexpectedly
- int exit = _process.exitValue();
- LOGGER.info("broker aborted: {}", exit);
- throw new RuntimeException("broker aborted: " + exit);
- }
- catch (IllegalThreadStateException e)
- {
- // this is expect if the broker started successfully
- }
-
- }
-
- private String doWindowsCommandEscaping(String value)
- {
- if(value.contains("\"") && !value.startsWith("\""))
- {
- return "\"" + value.replaceAll("\"", "\"\"") + "\"";
-
- }
- else
- {
- return value;
- }
- }
-
- @Override
- public void shutdown()
- {
- if(SystemUtils.isWindows())
- {
- doWindowsKill();
- }
-
- if (_process != null)
- {
- LOGGER.info("Destroying broker process");
- _process.destroy();
-
- reapChildProcess();
- waitUntilPortsAreFreeIfRequired();
- }
- }
-
- @Override
- protected String getLogPrefix()
- {
- return _pseudoThreadName;
- }
-
- private List<String> retrieveWindowsPidsIfPossible()
- {
- if(SystemUtils.isWindows())
- {
- try
- {
- Process p = Runtime.getRuntime().exec(new String[]{"wmic", "process", "list"});
- try (BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())))
- {
- String line;
- String headers = reader.readLine();
- int processIdOffset = headers.indexOf(" ProcessId") + 1;
- int parentProcessIdOffset = headers.indexOf(" ParentProcessId") + 1;
- String parentProcess = null;
- Map<String, List<String>> parentProcessMap = new HashMap<String, List<String>>();
-
- while ((line = reader.readLine()) != null)
- {
- if (line.length() > processIdOffset)
- {
- String processIdStr = line.substring(processIdOffset);
- processIdStr = processIdStr.substring(0, processIdStr.indexOf(' '));
- processIdStr = processIdStr.trim();
-
- String parentProcessIdStr = line.substring(parentProcessIdOffset);
- parentProcessIdStr = parentProcessIdStr.substring(0, parentProcessIdStr.indexOf(' '));
- parentProcessIdStr = parentProcessIdStr.trim();
- if (parentProcessIdStr.length() > 0 && (parentProcess == null || parentProcess.equals(
- parentProcessIdStr)))
- {
- List<String> children = parentProcessMap.get(parentProcessIdStr);
- if (children == null)
- {
- children = new ArrayList<String>();
- parentProcessMap.put(parentProcessIdStr, children);
- }
- children.add(processIdStr);
- }
- if (line.toLowerCase()
- .contains(_brokerCommand.toLowerCase()))
- {
- parentProcess = processIdStr;
- }
-
- }
-
- }
- LOGGER.debug("Parent process: " + parentProcess);
- if (parentProcess != null)
- {
- List<String> returnVal = new ArrayList<>();
- returnVal.add(parentProcess);
- List<String> children = parentProcessMap.get(parentProcess);
- if (children != null)
- {
- for (String child : children)
- {
- returnVal.add(child);
- }
- }
- return returnVal;
- }
-
-
- }
- }
- catch (IOException e)
- {
- LOGGER.error("Error whilst killing process " + _brokerCommand, e);
- }
- }
- return null;
- }
-
- private void doWindowsKill()
- {
- if(_windowsPids != null && !_windowsPids.isEmpty())
- {
- String parentProcess = _windowsPids.remove(0);
- try
- {
-
- Process p;
- for (String child : _windowsPids)
- {
- p = Runtime.getRuntime().exec(new String[]{"taskkill", "/PID", child, "/T", "/F"});
- consumeAllOutput(p);
- }
- p = Runtime.getRuntime().exec(new String[]{"taskkill", "/PID", parentProcess, "/T", "/F"});
- consumeAllOutput(p);
-
- }
- catch (IOException e)
- {
- LOGGER.error("Error whilst killing process " + _brokerCommand, e);
- }
- }
- }
-
- private static void consumeAllOutput(Process p) throws IOException
- {
- try(InputStreamReader inputStreamReader = new InputStreamReader(p.getInputStream()))
- {
- try (BufferedReader reader = new BufferedReader(inputStreamReader))
- {
- while (reader.readLine() != null)
- {
- }
- }
- }
- }
-
- @Override
- public void kill()
- {
- if (_pid == null)
- {
- if(SystemUtils.isWindows())
- {
- doWindowsKill();
- }
- LOGGER.info("Destroying broker process (no PID)");
- _process.destroy();
- }
- else
- {
- LOGGER.info("Killing broker process with PID " + _pid);
- sendSigkillForImmediateShutdown(_pid);
- }
-
- reapChildProcess();
-
- waitUntilPortsAreFreeIfRequired();
- }
-
- private void sendSigkillForImmediateShutdown(Integer pid)
- {
- boolean killSuccessful = false;
- try
- {
- final Process killProcess = Runtime.getRuntime().exec("kill -KILL " + pid);
- killProcess.waitFor();
- killSuccessful = killProcess.exitValue() == 0;
- }
- catch (IOException e)
- {
- LOGGER.error("Error whilst killing process " + _pid, e);
- }
- catch (InterruptedException e)
- {
- Thread.currentThread().interrupt();
- }
- finally
- {
- if (!killSuccessful)
- {
- _process.destroy();
- }
- }
- }
-
- private Integer retrieveUnixPidIfPossible()
- {
- if(!SystemUtils.isWindows())
- {
- try
- {
- Integer pid = ReflectionUtils.getDeclaredField(_process, "pid");
- LOGGER.info("PID " + pid);
- return pid;
- }
- catch (ReflectionUtilsException e)
- {
- LOGGER.warn("Could not get pid for process, Broker process shutdown will be graceful");
- }
- }
- return null;
- }
-
- private void reapChildProcess()
- {
- try
- {
- _process.waitFor();
- LOGGER.info("broker exited: " + _process.exitValue());
- }
- catch (InterruptedException e)
- {
- LOGGER.error("Interrupted whilst waiting for process shutdown");
- Thread.currentThread().interrupt();
- }
- finally
- {
- try
- {
- _process.getInputStream().close();
- _process.getErrorStream().close();
- _process.getOutputStream().close();
- }
- catch (IOException e)
- {
- }
- }
- }
-
- @Override
- public String dumpThreads()
- {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- try
- {
- Process process = Runtime.getRuntime().exec("jstack " + _pid);
- InputStream is = process.getInputStream();
- byte[] buffer = new byte[1024];
- int length = -1;
- while ((length = is.read(buffer)) != -1)
- {
- baos.write(buffer, 0, length);
- }
- }
- catch (Exception e)
- {
- LOGGER.error("Error whilst collecting thread dump for " + _pid, e);
- }
- return new String(baos.toByteArray());
- }
-
- @Override
- public String toString()
- {
- return "SpawnedBrokerHolder [_pid=" + _pid + ", _amqpPort="
- + getAmqpPort() + "]";
- }
-
- @Override
- protected TestBrokerConfiguration createBrokerConfiguration()
- {
- TestBrokerConfiguration configuration = super.createBrokerConfiguration();
-
- String remotelogback = "remotelogback";
-
- Map<String, String> mdc = new HashMap<>();
- mdc.put("origin", getLogPrefix());
-
- Map<String, String> contextProperties = new HashMap<>();
- contextProperties.put(LogbackPropertyValueDiscriminator.CLASS_QUALIFIED_TEST_NAME, getClassQualifiedTestName());
-
- Map<String, Object> loggerAttrs = new HashMap<>();
- loggerAttrs.put(BrokerLogger.TYPE, BrokerLogbackSocketLogger.TYPE);
- loggerAttrs.put(BrokerLogbackSocketLogger.NAME, remotelogback);
- loggerAttrs.put(BrokerLogbackSocketLogger.PORT, QpidBrokerTestCase.LOGBACK_REMOTE_PORT);
- loggerAttrs.put(BrokerLogbackSocketLogger.MAPPED_DIAGNOSTIC_CONTEXT, mdc);
- loggerAttrs.put(BrokerLogbackSocketLogger.CONTEXT_PROPERTIES, contextProperties);
-
- configuration.addObjectConfiguration(BrokerLogger.class, loggerAttrs);
-
- Map<String, Object> qpidRuleAttrs = new HashMap<>();
- qpidRuleAttrs.put(BrokerLogInclusionRule.NAME, "Qpid");
- qpidRuleAttrs.put(BrokerLogInclusionRule.TYPE, BrokerNameAndLevelLogInclusionRule.TYPE);
- qpidRuleAttrs.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "DEBUG");
- qpidRuleAttrs.put(BrokerNameAndLevelLogInclusionRule.LOGGER_NAME, "org.apache.qpid.*");
-
- configuration.addObjectConfiguration(BrokerLogger.class, remotelogback,
- BrokerLogInclusionRule.class, qpidRuleAttrs);
-
- Map<String, Object> operationalLoggingRuleAttrs = new HashMap<>();
- operationalLoggingRuleAttrs.put(BrokerLogInclusionRule.NAME, "Operational");
- operationalLoggingRuleAttrs.put(BrokerLogInclusionRule.TYPE, BrokerNameAndLevelLogInclusionRule.TYPE);
- operationalLoggingRuleAttrs.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "INFO");
- operationalLoggingRuleAttrs.put(BrokerNameAndLevelLogInclusionRule.LOGGER_NAME, "qpid.message.*");
-
- configuration.addObjectConfiguration(BrokerLogger.class, remotelogback,
- BrokerLogInclusionRule.class, operationalLoggingRuleAttrs);
-
- return configuration;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/systests/src/main/java/org/apache/qpid/test/utils/TestBrokerConfiguration.java
----------------------------------------------------------------------
diff --git a/systests/src/main/java/org/apache/qpid/test/utils/TestBrokerConfiguration.java b/systests/src/main/java/org/apache/qpid/test/utils/TestBrokerConfiguration.java
deleted file mode 100644
index 526efaa..0000000
--- a/systests/src/main/java/org/apache/qpid/test/utils/TestBrokerConfiguration.java
+++ /dev/null
@@ -1,493 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.utils;
-
-import static org.mockito.Mockito.mock;
-
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.Reader;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.apache.qpid.server.configuration.updater.CurrentThreadTaskExecutor;
-import org.apache.qpid.server.configuration.updater.TaskExecutor;
-import org.apache.qpid.server.logging.EventLogger;
-import org.apache.qpid.server.management.plugin.HttpManagement;
-import org.apache.qpid.server.model.AbstractSystemConfig;
-import org.apache.qpid.server.model.AccessControlProvider;
-import org.apache.qpid.server.model.AuthenticationProvider;
-import org.apache.qpid.server.model.Broker;
-import org.apache.qpid.server.model.BrokerModel;
-import org.apache.qpid.server.model.ConfiguredObject;
-import org.apache.qpid.server.model.GroupProvider;
-import org.apache.qpid.server.model.JsonSystemConfigImpl;
-import org.apache.qpid.server.model.Plugin;
-import org.apache.qpid.server.model.Port;
-import org.apache.qpid.server.model.State;
-import org.apache.qpid.server.model.SystemConfig;
-import org.apache.qpid.server.model.UUIDGenerator;
-import org.apache.qpid.server.model.VirtualHostAlias;
-import org.apache.qpid.server.model.VirtualHostNode;
-import org.apache.qpid.server.model.adapter.FileBasedGroupProvider;
-import org.apache.qpid.server.model.adapter.FileBasedGroupProviderImpl;
-import org.apache.qpid.server.plugin.PluggableFactoryLoader;
-import org.apache.qpid.server.plugin.SystemConfigFactory;
-import org.apache.qpid.server.security.access.plugins.AclFileAccessControlProvider;
-import org.apache.qpid.server.security.access.plugins.AclRule;
-import org.apache.qpid.server.security.access.plugins.RuleBasedAccessControlProvider;
-import org.apache.qpid.server.store.AbstractMemoryStore;
-import org.apache.qpid.server.store.ConfiguredObjectRecord;
-import org.apache.qpid.server.store.ConfiguredObjectRecordConverter;
-import org.apache.qpid.server.store.ConfiguredObjectRecordImpl;
-import org.apache.qpid.server.store.DurableConfigurationStore;
-import org.apache.qpid.server.store.handler.ConfiguredObjectRecordHandler;
-import org.apache.qpid.server.virtualhostnode.JsonVirtualHostNode;
-import org.apache.qpid.server.util.Strings;
-
-public class TestBrokerConfiguration
-{
-
- public static final String ENTRY_NAME_HTTP_PORT = "http";
- public static final String ENTRY_NAME_AMQP_PORT = "amqp";
- public static final String ENTRY_NAME_VIRTUAL_HOST = "test";
- public static final String ENTRY_NAME_AUTHENTICATION_PROVIDER = "plain";
- public static final String ENTRY_NAME_EXTERNAL_PROVIDER = "external";
- public static final String ENTRY_NAME_SSL_PORT = "sslPort";
- public static final String ENTRY_NAME_HTTP_MANAGEMENT = "MANAGEMENT-HTTP";
- public static final String MANAGEMENT_HTTP_PLUGIN_TYPE = "MANAGEMENT-HTTP";
- public static final String ENTRY_NAME_ANONYMOUS_PROVIDER = "anonymous";
- public static final String ENTRY_NAME_SSL_KEYSTORE = "systestsKeyStore";
- public static final String ENTRY_NAME_SSL_TRUSTSTORE = "systestsTrustStore";
- public static final String ENTRY_NAME_GROUP_FILE = "groupFile";
- public static final String ENTRY_NAME_ACL_FILE = "aclFile";
- public static final String ENTRY_NAME_ACL_RULES = "aclRules";
- private final TaskExecutor _taskExecutor;
- private final String _storeType;
-
- private AbstractMemoryStore _store;
- private boolean _saved;
- private File _passwdFile;
-
- private static final Logger LOGGER = LoggerFactory.getLogger(TestBrokerConfiguration.class);
-
- public TestBrokerConfiguration(String storeType, String initialStoreLocation)
- {
- _taskExecutor = new CurrentThreadTaskExecutor();
- _taskExecutor.start();
- _storeType = storeType;
- Map<String,Object> config = new HashMap<>();
- config.put("storePath", initialStoreLocation);
- final AbstractSystemConfig parentObject = new JsonSystemConfigImpl(_taskExecutor,
- mock(EventLogger.class),
- null,
- config)
- {
-
- {
- updateModel(BrokerModel.getInstance());
- }
- };
-
- ConfiguredObjectRecordConverter converter = new ConfiguredObjectRecordConverter(BrokerModel.getInstance());
-
- Reader reader;
- try
- {
- try
- {
- URL url = new URL(initialStoreLocation);
- try(InputStream urlStream = url.openStream())
- {
- reader = new InputStreamReader(urlStream);
- }
- }
- catch (MalformedURLException e)
- {
- reader = new FileReader(initialStoreLocation);
- }
-
- Collection<ConfiguredObjectRecord> records = converter.readFromJson(org.apache.qpid.server.model.Broker.class, parentObject, reader);
- reader.close();
-
- _store = new AbstractMemoryStore(Broker.class){};
-
- ConfiguredObjectRecord[] initialRecords = records.toArray(new ConfiguredObjectRecord[records.size()]);
- _store.init(parentObject);
-
- _store.openConfigurationStore(new ConfiguredObjectRecordHandler()
- {
- @Override
- public void handle(ConfiguredObjectRecord record)
- {
- Map<String, Object> attributes = record.getAttributes();
- String rawType = (String)attributes.get("type");
- if (rawType != null)
- {
- String interpolatedType = Strings.expand(rawType, false, Strings.ENV_VARS_RESOLVER, Strings.JAVA_SYS_PROPS_RESOLVER);
- if (!interpolatedType.equals(rawType))
- {
- setObjectAttribute(record, "type", interpolatedType);
- }
- }
- }
-
- }, initialRecords);
- }
- catch (IOException e)
- {
- throw new RuntimeException("Unable to load initial store", e);
- }
-
-
- }
-
- public boolean setBrokerAttribute(String name, Object value)
- {
- ConfiguredObjectRecord entry = findObject(Broker.class, null);
- if (entry == null)
- {
- return false;
- }
-
- return setObjectAttribute(entry, name, value);
- }
-
- public boolean setObjectAttribute(final Class<? extends ConfiguredObject> category,
- String objectName,
- String attributeName,
- Object value)
- {
- ConfiguredObjectRecord entry = findObject(category, objectName);
- if (entry == null)
- {
- return false;
- }
- return setObjectAttribute(entry, attributeName, value);
- }
-
- public boolean setObjectAttributes(final Class<? extends ConfiguredObject> category,
- String objectName,
- Map<String, Object> attributes)
- {
- ConfiguredObjectRecord entry = findObject(category, objectName);
- if (entry == null)
- {
- return false;
- }
- return setObjectAttributes(entry, attributes);
- }
-
- public boolean save(File configFile)
- {
-
- Map<String, Object> attributes = new HashMap<>();
- attributes.put("storePath", configFile.getAbsolutePath());
-
- SystemConfigFactory configFactory =
- (new PluggableFactoryLoader<>(SystemConfigFactory.class)).get(_storeType);
-
- attributes.put(SystemConfig.STARTUP_LOGGED_TO_SYSTEM_OUT, false);
- attributes.put(ConfiguredObject.DESIRED_STATE, State.QUIESCED);
- final SystemConfig parentObject = configFactory.newInstance(_taskExecutor,
- mock(EventLogger.class),
- null, attributes);
-
- parentObject.open();
- DurableConfigurationStore configurationStore = parentObject.getConfigurationStore();
- configurationStore.closeConfigurationStore();
-
- final List<ConfiguredObjectRecord> records = getConfiguredObjectRecords();
-
-
- configurationStore.init(parentObject);
-
- clearStore(configurationStore);
-
- configurationStore.update(true, records.toArray(new ConfiguredObjectRecord[records.size()]));
-
-
- configurationStore.closeConfigurationStore();
- parentObject.close();
- return true;
- }
-
- public void clearStore(final DurableConfigurationStore configurationStore)
- {
- final List<ConfiguredObjectRecord> recordsToDelete = new ArrayList<>();
- configurationStore.openConfigurationStore(new ConfiguredObjectRecordHandler()
- {
-
- @Override
- public void handle(final ConfiguredObjectRecord record)
- {
- recordsToDelete.add(record);
- }
-
- });
- if(!recordsToDelete.isEmpty())
- {
- configurationStore.remove(recordsToDelete.toArray(new ConfiguredObjectRecord[recordsToDelete.size()]));
- }
- }
-
- public List<ConfiguredObjectRecord> getConfiguredObjectRecords()
- {
- return _store.getConfiguredObjectRecords();
-
- }
-
- public UUID[] removeObjectConfiguration(final Class<? extends ConfiguredObject> category,
- final String name)
- {
- final ConfiguredObjectRecord entry = findObject(category, name);
-
- if (entry != null)
- {
-
- if(category == VirtualHostNode.class)
- {
- final List<ConfiguredObjectRecord> aliasRecords = new ArrayList<>();
- // remove vhost aliases associated with the vhost
-
- for(ConfiguredObjectRecord record : getConfiguredObjectRecords())
- {
- if (record.getType().equals(VirtualHostAlias.class.getSimpleName())
- && name.equals(record.getAttributes().get(ConfiguredObject.NAME)))
- {
- aliasRecords.add(record);
- }
- }
-
- _store.remove(aliasRecords.toArray(new ConfiguredObjectRecord[aliasRecords.size()]));
- }
- return _store.remove(entry);
-
- }
- return null;
- }
-
- public UUID addObjectConfiguration(Class<? extends ConfiguredObject> type, Map<String, Object> attributes)
- {
- UUID id = UUIDGenerator.generateRandomUUID();
- addObjectConfiguration(id, type.getSimpleName(), attributes);
- return id;
- }
-
- public UUID addObjectConfiguration(final Class<? extends ConfiguredObject> parentCategory, final String parentName,
- Class<? extends ConfiguredObject> type, Map<String, Object> attributes)
- {
- UUID id = UUIDGenerator.generateRandomUUID();
- ConfiguredObjectRecord entry =
- new ConfiguredObjectRecordImpl(id, type.getSimpleName(), attributes,
- Collections.singletonMap(parentCategory.getSimpleName(), findObject(parentCategory,parentName).getId()));
-
- _store.update(true, entry);
- return id;
- }
-
- public UUID addHttpManagementConfiguration()
- {
- setObjectAttribute(AuthenticationProvider.class, TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER,
- "secureOnlyMechanisms", "{}");
- setObjectAttribute(Port.class, TestBrokerConfiguration.ENTRY_NAME_HTTP_PORT, Port.AUTHENTICATION_PROVIDER,
- TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER);
-
- Map<String, Object> attributes = new HashMap<>();
- attributes.put(Plugin.TYPE, MANAGEMENT_HTTP_PLUGIN_TYPE);
- attributes.put(Plugin.NAME, ENTRY_NAME_HTTP_MANAGEMENT);
- attributes.put(HttpManagement.HTTP_BASIC_AUTHENTICATION_ENABLED, true);
- return addObjectConfiguration(Plugin.class, attributes);
- }
-
- public UUID addGroupFileConfiguration(String groupFilePath)
- {
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(GroupProvider.NAME, ENTRY_NAME_GROUP_FILE);
- attributes.put(GroupProvider.TYPE, FileBasedGroupProviderImpl.GROUP_FILE_PROVIDER_TYPE);
- attributes.put(FileBasedGroupProvider.PATH, groupFilePath);
-
- return addObjectConfiguration(GroupProvider.class, attributes);
- }
-
- public UUID addAclFileConfiguration(String aclFilePath)
- {
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(AccessControlProvider.NAME, ENTRY_NAME_ACL_FILE);
- attributes.put(AccessControlProvider.TYPE, AclFileAccessControlProvider.ACL_FILE_PROVIDER_TYPE);
- attributes.put(AclFileAccessControlProvider.PATH, aclFilePath);
-
- return addObjectConfiguration(AccessControlProvider.class, attributes);
- }
-
- public UUID addAclRuleConfiguration(AclRule[] aclRules)
- {
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(AccessControlProvider.NAME, ENTRY_NAME_ACL_RULES);
- attributes.put(AccessControlProvider.TYPE, RuleBasedAccessControlProvider.RULE_BASED_TYPE);
- attributes.put(RuleBasedAccessControlProvider.RULES, aclRules);
-
- return addObjectConfiguration(AccessControlProvider.class, attributes);
- }
-
-
- private boolean setObjectAttributes(ConfiguredObjectRecord entry, Map<String, Object> attributes)
- {
- Map<String, Object> newAttributes = new HashMap<String, Object>(entry.getAttributes());
- newAttributes.putAll(attributes);
- ConfiguredObjectRecord newEntry = new ConfiguredObjectRecordImpl(entry.getId(), entry.getType(), newAttributes,
- entry.getParents());
- _store.update(false, newEntry);
- return true;
- }
-
- private ConfiguredObjectRecord findObject(final Class<? extends ConfiguredObject> category, final String objectName)
- {
- Collection<ConfiguredObjectRecord> records = getConfiguredObjectRecords();
- for(ConfiguredObjectRecord record : records)
- {
- if (record.getType().equals(category.getSimpleName())
- && (objectName == null
- || objectName.equals(record.getAttributes().get(ConfiguredObject.NAME))))
- {
- return record;
- }
- }
- return null;
-
- }
-
- private void addObjectConfiguration(UUID id, String type, Map<String, Object> attributes)
- {
- ConfiguredObjectRecord entry = new ConfiguredObjectRecordImpl(id, type, attributes, Collections.singletonMap(Broker.class.getSimpleName(), findObject(Broker.class,null).getId()));
-
- _store.update(true, entry);
- }
-
- private boolean setObjectAttribute(ConfiguredObjectRecord entry, String attributeName, Object value)
- {
- Map<String, Object> attributes = new HashMap<String, Object>(entry.getAttributes());
- attributes.put(attributeName, value);
- ConfiguredObjectRecord newEntry = new ConfiguredObjectRecordImpl(entry.getId(), entry.getType(), attributes, entry.getParents());
- _store.update(false, newEntry);
- return true;
- }
-
- public boolean isSaved()
- {
- return _saved;
- }
-
- public void setSaved(boolean saved)
- {
- _saved = saved;
- }
-
- public Map<String,Object> getObjectAttributes(final Class<? extends ConfiguredObject> category, final String name)
- {
- return findObject(category, name).getAttributes();
- }
-
- public void createVirtualHostNode(final String virtualHostNodeName,
- final String storeType,
- final String storeDir,
- final String blueprint)
- {
- Map<String, Object> attributes = new HashMap<>();
- attributes.put(VirtualHostNode.NAME, virtualHostNodeName);
- attributes.put(VirtualHostNode.TYPE, storeType);
- if (storeDir != null)
- {
- attributes.put(JsonVirtualHostNode.STORE_PATH, storeDir);
- }
-
- if (blueprint != null)
- {
- attributes.put(VirtualHostNode.CONTEXT,
- Collections.singletonMap(VirtualHostNode.VIRTUALHOST_BLUEPRINT_CONTEXT_VAR, blueprint));
- }
-
- addObjectConfiguration(VirtualHostNode.class, attributes);
- }
-
- public void configureTemporaryPasswordFile(String... users) throws IOException
- {
- _passwdFile = createTemporaryPasswordFile(users);
-
- setObjectAttribute(AuthenticationProvider.class, TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER,
- "path", _passwdFile.getAbsolutePath());
- }
-
- public void cleanUp()
- {
- if (_passwdFile != null)
- {
- if (_passwdFile.exists())
- {
- _passwdFile.delete();
- }
- }
- }
-
- public File createTemporaryPasswordFile(String[] users) throws IOException
- {
- BufferedWriter writer = null;
- try
- {
- File testFile = File.createTempFile(this.getClass().getName(),"tmp");
- testFile.deleteOnExit();
-
- writer = new BufferedWriter(new FileWriter(testFile));
- for (int i = 0; i < users.length; i++)
- {
- String username = users[i];
- writer.write(username + ":" + username);
- writer.newLine();
- }
-
- return testFile;
-
- }
- finally
- {
- if (writer != null)
- {
- writer.close();
- }
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/systests/src/main/java/org/apache/qpid/test/utils/TestUtils.java
----------------------------------------------------------------------
diff --git a/systests/src/main/java/org/apache/qpid/test/utils/TestUtils.java b/systests/src/main/java/org/apache/qpid/test/utils/TestUtils.java
deleted file mode 100644
index 5069e20..0000000
--- a/systests/src/main/java/org/apache/qpid/test/utils/TestUtils.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.test.utils;
-
-
-import java.lang.management.ManagementFactory;
-import java.lang.management.ThreadInfo;
-import java.lang.management.ThreadMXBean;
-
-public class TestUtils
-{
- public static String dumpThreads()
- {
- ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
- ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(true, true);
- StringBuilder dump = new StringBuilder();
- dump.append(String.format("%n"));
- for (ThreadInfo threadInfo : threadInfos)
- {
- dump.append(threadInfo);
- }
-
- long[] deadLocks = threadMXBean.findDeadlockedThreads();
- if (deadLocks != null && deadLocks.length > 0)
- {
- ThreadInfo[] deadlockedThreads = threadMXBean.getThreadInfo(deadLocks);
- dump.append(String.format("%n"));
- dump.append("Deadlock is detected!");
- dump.append(String.format("%n"));
- for (ThreadInfo threadInfo : deadlockedThreads)
- {
- dump.append(threadInfo);
- }
- }
- return dump.toString();
- }
-}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org
[5/6] qpid-broker-j git commit: QPID-8158: [Broker-J] [System Tests]
Refactor remaining system tests extending QpidBrokerTestCase
Posted by or...@apache.org.
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/3a6893e4/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/GroupCreator.java
----------------------------------------------------------------------
diff --git a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/GroupCreator.java b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/GroupCreator.java
deleted file mode 100644
index d7e6b7f..0000000
--- a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/GroupCreator.java
+++ /dev/null
@@ -1,514 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.store.berkeleydb.replication;
-
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.StringWriter;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-import java.util.concurrent.Callable;
-import java.util.concurrent.CopyOnWriteArrayList;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-
-import javax.jms.Connection;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.SerializationFeature;
-import com.sleepycat.je.rep.ReplicationConfig;
-import org.junit.Assert;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.apache.qpid.server.model.Port;
-import org.apache.qpid.server.model.Protocol;
-import org.apache.qpid.server.model.VirtualHost;
-import org.apache.qpid.server.model.VirtualHostNode;
-import org.apache.qpid.server.virtualhost.berkeleydb.BDBHAVirtualHostImpl;
-import org.apache.qpid.server.virtualhostnode.AbstractVirtualHostNode;
-import org.apache.qpid.server.virtualhostnode.berkeleydb.BDBHARemoteReplicationNode;
-import org.apache.qpid.server.virtualhostnode.berkeleydb.BDBHAVirtualHostNode;
-import org.apache.qpid.server.virtualhostnode.berkeleydb.BDBHAVirtualHostNodeImpl;
-import org.apache.qpid.systest.rest.RestTestHelper;
-import org.apache.qpid.systests.ConnectionBuilder;
-import org.apache.qpid.test.utils.BrokerHolder;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.test.utils.TestBrokerConfiguration;
-
-public class GroupCreator
-{
- private static final Logger LOGGER = LoggerFactory.getLogger(GroupCreator.class);
-
- private static final int FAILOVER_CYCLECOUNT = 40;
- private static final int FAILOVER_CONNECTDELAY = 1000;
-
- private final QpidBrokerTestCase _testcase;
- private final String _virtualHostName;
-
- private final String _ipAddressOfBroker;
- private final String _groupName ;
- private final int _numberOfNodes;
- private int _bdbHelperPort;
- private int _primaryBrokerPort;
- private Map<Integer, GroupMember> _members;
-
- public GroupCreator(QpidBrokerTestCase testcase, String virtualHostName, int numberOfNodes)
- {
- _members = new TreeMap<>();
- _testcase = testcase;
- _virtualHostName = virtualHostName;
- _groupName = virtualHostName;
- _ipAddressOfBroker = getIpAddressOfBrokerHost();
- _numberOfNodes = numberOfNodes;
- _bdbHelperPort = 0;
- }
-
- public void configureClusterNodes() throws Exception
- {
- int[] bdbPorts = new int[_numberOfNodes];
- int httpPort = 0;
- for (int i = 0; i < _numberOfNodes; i++)
- {
- int brokerPort = i==0 ? _testcase.findFreePort() : _testcase.getNextAvailable(httpPort + 1);
- int bdbPort = _testcase.getNextAvailable(brokerPort + 1);
- httpPort = _testcase.getNextAvailable(bdbPort + 1);
- GroupMember member = new GroupMember();
- member._amqpPort = brokerPort;
- member._bdbPort = bdbPort;
- member._httpPort = httpPort;
- bdbPorts[i] = bdbPort;
- _members.put(member._amqpPort, member);
- }
-
- String bluePrintJson = getBlueprint();
- List<String> permittedNodes = getPermittedNodes(_ipAddressOfBroker, bdbPorts);
-
- String helperName = null;
- for (GroupMember member: _members.values())
- {
- int brokerPort = member._amqpPort;
- int bdbPort = member._bdbPort;
- LOGGER.debug("Cluster broker port " + brokerPort + ", bdb replication port " + bdbPort);
- if (_bdbHelperPort == 0)
- {
- _bdbHelperPort = bdbPort;
- _primaryBrokerPort = brokerPort;
- }
-
- String nodeName = getNodeNameForNodeAt(bdbPort);
- if (helperName == null)
- {
- helperName = nodeName;
- }
-
- Map<String, Object> virtualHostNodeAttributes = new HashMap<>();
- virtualHostNodeAttributes.put(BDBHAVirtualHostNode.GROUP_NAME, _groupName);
- virtualHostNodeAttributes.put(BDBHAVirtualHostNode.NAME, nodeName);
- virtualHostNodeAttributes.put(BDBHAVirtualHostNode.ADDRESS, getNodeHostPortForNodeAt(bdbPort));
- virtualHostNodeAttributes.put(BDBHAVirtualHostNode.HELPER_ADDRESS, getHelperHostPort());
- virtualHostNodeAttributes.put(BDBHAVirtualHostNode.TYPE, BDBHAVirtualHostNodeImpl.VIRTUAL_HOST_NODE_TYPE);
- virtualHostNodeAttributes.put(BDBHAVirtualHostNode.HELPER_NODE_NAME, helperName);
- virtualHostNodeAttributes.put(BDBHAVirtualHostNode.PERMITTED_NODES, permittedNodes);
-
- Map<String, String> context = new HashMap<>();
- context.put(ReplicationConfig.INSUFFICIENT_REPLICAS_TIMEOUT, "2 s");
- context.put(ReplicationConfig.ELECTIONS_PRIMARY_RETRIES, "0");
- context.put(AbstractVirtualHostNode.VIRTUALHOST_BLUEPRINT_CONTEXT_VAR, bluePrintJson);
- virtualHostNodeAttributes.put(BDBHAVirtualHostNode.CONTEXT, context);
-
- BrokerHolder broker = _testcase.createSpawnedBroker(brokerPort);
- member._brokerHolder = broker;
- TestBrokerConfiguration brokerConfiguration = broker.getConfiguration();
- brokerConfiguration.addHttpManagementConfiguration();
- brokerConfiguration.setObjectAttribute(Port.class, TestBrokerConfiguration.ENTRY_NAME_HTTP_PORT, Port.PORT, member._httpPort);
- brokerConfiguration.setObjectAttributes(VirtualHostNode.class, _virtualHostName, virtualHostNodeAttributes);
- }
- }
-
- public void setDesignatedPrimaryOnFirstBroker(boolean designatedPrimary) throws Exception
- {
- if (_numberOfNodes != 2)
- {
- throw new IllegalArgumentException("Only two nodes groups have the concept of primary");
- }
- final GroupMember groupMember = _members.get(_primaryBrokerPort);
- TestBrokerConfiguration config = groupMember._brokerHolder.getConfiguration();
- String nodeName = getNodeNameForNodeAt(groupMember._bdbPort);
- config.setObjectAttribute(VirtualHostNode.class, nodeName, BDBHAVirtualHostNode.DESIGNATED_PRIMARY, designatedPrimary);
- config.setSaved(false);
- }
-
- public void startNode(final int brokerPortNumber) throws Exception
- {
- _members.get(brokerPortNumber)._brokerHolder.start();
- }
-
- public void startCluster() throws Exception
- {
- for (final GroupMember member : _members.values())
- {
- member._brokerHolder.start();
- }
- }
-
- public void startClusterParallel() throws Exception
- {
- final ExecutorService executor = Executors.newFixedThreadPool(_members.size());
- try
- {
- List<Future<Object>> brokerStartFutures = new CopyOnWriteArrayList<>();
- for (final GroupMember member : _members.values())
- {
- Future<Object> future = executor.submit(new Callable<Object>()
- {
- @Override
- public Object call()
- {
- try
- {
- member._brokerHolder.start();
- return "OK";
- }
- catch (Exception e)
- {
- return e;
- }
- }
- });
- brokerStartFutures.add(future);
- }
- for (Future<Object> future : brokerStartFutures)
- {
- Object result = future.get(30, TimeUnit.SECONDS);
- LOGGER.debug("Node startup result:" + result);
- if (result instanceof Exception)
- {
- throw (Exception) result;
- }
- else if (!"OK".equals(result))
- {
- throw new Exception("One of the cluster nodes is not started");
- }
- }
- }
- catch (Exception e)
- {
- stopCluster();
- throw e;
- }
- finally
- {
- executor.shutdown();
- }
-
- }
-
- public void stopNode(final int brokerPortNumber)
- {
- _members.get(brokerPortNumber)._brokerHolder.kill();
- }
-
- public void stopCluster() throws Exception
- {
- for (final GroupMember member : _members.values())
- {
- try
- {
- member._brokerHolder.kill();
- }
- catch(Exception e)
- {
- LOGGER.warn("Failed to stop node on port: " + member._amqpPort);
- }
- }
- }
-
- public int getBrokerPortNumberFromConnection(Connection connection)
- {
- return _testcase.getJmsProvider().getConnectedURI(connection).getPort();
- }
-
- public int getPortNumberOfAnInactiveBroker(final Connection activeConnection)
- {
- final Set<Integer> allBrokerPorts = new HashSet<>(_members.keySet());
- LOGGER.debug("Broker ports:" + allBrokerPorts);
- final int activeBrokerPort = getBrokerPortNumberFromConnection(activeConnection);
- allBrokerPorts.remove(activeBrokerPort);
- LOGGER.debug("Broker ports:" + allBrokerPorts);
- return allBrokerPorts.iterator().next();
- }
-
- public Set<Integer> getBdbPortNumbers()
- {
- HashSet<Integer> ports = new HashSet<>();
- for (final GroupMember member : _members.values())
- {
- ports.add(member._bdbPort);
- }
- return ports;
- }
-
- public ConnectionBuilder getConnectionBuilderForAllClusterNodes() throws Exception
- {
- return getConnectionBuilderForAllClusterNodes(FAILOVER_CONNECTDELAY, FAILOVER_CYCLECOUNT);
- }
-
- public ConnectionBuilder getConnectionBuilderForAllClusterNodes(int connectDelay, final int cyclecount) throws Exception
- {
- final ConnectionBuilder connectionBuilder = _testcase.getConnectionBuilder();
- connectionBuilder.setFailoverReconnectDelay(connectDelay);
- connectionBuilder.setVirtualHost(_virtualHostName);
- connectionBuilder.setFailover(true);
-
- final int reconnectAttempts = cyclecount == 0 ? 1 : cyclecount;
- connectionBuilder.setFailoverReconnectAttempts(reconnectAttempts);
-
- final Iterator<Integer> iterator = _members.keySet().iterator();
- if (iterator.hasNext())
- {
- final int firstBroker = iterator.next();
- connectionBuilder.setPort(firstBroker);
- }
-
- while (iterator.hasNext())
- {
- int brokerPortNumber = iterator.next();
- connectionBuilder.addFailoverPort(brokerPortNumber);
- }
-
- return connectionBuilder;
- }
-
- public String getGroupName()
- {
- return _groupName;
- }
-
- public String getNodeNameForNodeAt(final int bdbPort)
- {
- return "node" + _testcase.getName() + bdbPort;
- }
-
- public String getNodeHostPortForNodeAt(final int bdbPort)
- {
- return _ipAddressOfBroker + ":" + bdbPort;
- }
-
- public String getHelperHostPort()
- {
- if (_bdbHelperPort == 0)
- {
- throw new IllegalStateException("Helper port not yet assigned.");
- }
-
- return _ipAddressOfBroker + ":" + _bdbHelperPort;
- }
-
- public int getBrokerPortNumberOfPrimary()
- {
- if (_numberOfNodes != 2)
- {
- throw new IllegalArgumentException("Only two nodes groups have the concept of primary");
- }
-
- return _primaryBrokerPort;
- }
-
- public int getBrokerPortNumberOfSecondaryNode()
- {
- final Set<Integer> portNumbers = getBrokerPortNumbersForNodes();
- portNumbers.remove(getBrokerPortNumberOfPrimary());
- return portNumbers.iterator().next();
- }
-
- public Set<Integer> getBrokerPortNumbersForNodes()
- {
- return new HashSet<>(_members.keySet());
- }
-
-
- public String getIpAddressOfBrokerHost()
- {
- String brokerHost = "localhost";
- try
- {
- return InetAddress.getByName(brokerHost).getHostAddress();
- }
- catch (UnknownHostException e)
- {
- throw new RuntimeException("Could not determine IP address of host : " + brokerHost, e);
- }
- }
-
- public String getNodeNameForBrokerPort(final int brokerPort)
- {
- return getNodeNameForNodeAt(_members.get(brokerPort)._bdbPort);
- }
-
- public void setNodeAttributes(int brokerPort, Map<String, Object> attributeMap)
- throws Exception
- {
- setNodeAttributes(brokerPort, brokerPort, attributeMap);
- }
-
- public void setNodeAttributes(int localNodePort, int remoteNodePort, Map<String, Object> attributeMap)
- throws Exception
- {
- RestTestHelper restHelper = createRestTestHelper(localNodePort);
- String url = getNodeRestUrl(localNodePort, remoteNodePort);
- int status = restHelper.submitRequest(url, "PUT", attributeMap);
- if (status != 200)
- {
- throw new Exception("Unexpected http status when updating " + getNodeNameForBrokerPort(remoteNodePort) + " attribute(s) : " + status);
- }
- }
-
- private String getNodeRestUrl(int localNodePort, int remoteNodePort)
- {
- String remoteNodeName = getNodeNameForBrokerPort(remoteNodePort);
- String localNodeName = getNodeNameForBrokerPort(localNodePort);
- String url;
- if (localNodePort == remoteNodePort)
- {
- url = "/api/latest/virtualhostnode/" + localNodeName;
- }
- else
- {
- url = "/api/latest/remotereplicationnode/" + localNodeName + "/" + remoteNodeName;
- }
- return url;
- }
-
- public Map<String, Object> getNodeAttributes(int brokerPort) throws IOException
- {
- return getNodeAttributes(brokerPort, brokerPort);
- }
-
- public Map<String, Object> getNodeAttributes(int localNodePort, int remoteNodePort) throws IOException
- {
- RestTestHelper restHelper = createRestTestHelper(localNodePort);
- try
- {
- return restHelper.getJsonAsMap(getNodeRestUrl(localNodePort, remoteNodePort));
- }
- catch (FileNotFoundException e)
- {
- return Collections.emptyMap();
- }
- }
-
- public void awaitNodeToAttainRole(int brokerPort, String... desiredRole) throws Exception
- {
- awaitNodeToAttainRole(brokerPort, brokerPort, desiredRole);
- }
-
- public void awaitNodeToAttainRole(int localNodePort, int remoteNodePort, String... desiredRole) throws Exception
- {
- awaitNodeToAttainAttributeValue(localNodePort, remoteNodePort, BDBHARemoteReplicationNode.ROLE, desiredRole);
- }
-
- public void awaitNodeToAttainAttributeValue(int localNodePort, int remoteNodePort, String attributeName, String... desiredValue) throws Exception
- {
- final long startTime = System.currentTimeMillis();
- List<String> desiredValues = Arrays.asList( desiredValue );
- String attributeValue = null;
- while((System.currentTimeMillis() - startTime) < 30000)
- {
- LOGGER.debug("Awaiting node '" + getNodeNameForBrokerPort(remoteNodePort) + "' attribute " +
- attributeName + " to have value set to any of " + desiredValues);
- Map<String, Object> data = getNodeAttributes(localNodePort, remoteNodePort);
- attributeValue = String.valueOf(data.get(attributeName));
- if (desiredValues.contains(attributeValue))
- {
- break;
- }
- else
- {
- Thread.sleep(1000);
- }
- }
- LOGGER.debug("Node '{}' attribute '{}' value '{}'", getNodeNameForBrokerPort(remoteNodePort), attributeName, attributeValue);
- Assert.assertTrue(String.format("Node port %d: Attribute '%s' has unexpected value '%s', desired values [%s]",
- localNodePort,
- attributeName,
- attributeValue,
- desiredValues),
- desiredValues.contains(attributeValue));
- }
-
- public RestTestHelper createRestTestHelper(int brokerPort)
- {
- int httpPort = _members.get(brokerPort)._httpPort;
- return new RestTestHelper(httpPort);
- }
-
- public static String getBlueprint() throws Exception
- {
- Map<String,Object> bluePrint = new HashMap<>();
- bluePrint.put(VirtualHost.TYPE, BDBHAVirtualHostImpl.VIRTUAL_HOST_TYPE);
-
- StringWriter writer = new StringWriter();
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
- mapper.writeValue(writer, bluePrint);
- return writer.toString();
- }
-
- public static List<String> getPermittedNodes(String hostName, int... ports)
- {
- List<String> permittedNodes = new ArrayList<>();
- for (int port: ports)
- {
- permittedNodes.add(hostName + ":" + port);
- }
- return permittedNodes;
- }
-
- public Map<Integer, String> groupThreadumps()
- {
- Map<Integer,String> threadDumps = new HashMap<>();
- for(GroupMember m: _members.values())
- {
- threadDumps.put(m._amqpPort, m._brokerHolder.dumpThreads());
- }
- return threadDumps;
- }
-
- private class GroupMember
- {
- int _amqpPort;
- int _bdbPort;
- int _httpPort;
- BrokerHolder _brokerHolder;
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/3a6893e4/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/GroupJmsTestBase.java
----------------------------------------------------------------------
diff --git a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/GroupJmsTestBase.java b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/GroupJmsTestBase.java
index 1c2e6fc..e209dd2 100644
--- a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/GroupJmsTestBase.java
+++ b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/GroupJmsTestBase.java
@@ -23,12 +23,15 @@ package org.apache.qpid.server.store.berkeleydb.replication;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
+import static org.junit.Assume.assumeThat;
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.Session;
+import org.junit.BeforeClass;
+
import org.apache.qpid.systests.ConnectionBuilder;
import org.apache.qpid.systests.JmsProvider;
import org.apache.qpid.systests.JmsTestBase;
@@ -43,6 +46,12 @@ public class GroupJmsTestBase extends JmsTestBase
static final int SHORT_FAILOVER_CYCLECOUNT = 2;
static final int SHORT_FAILOVER_CONNECTDELAY = 200;
+ @BeforeClass
+ public static void verify()
+ {
+ assumeThat(System.getProperty("virtualhostnode.type", "BDB"), is(equalTo("BDB")));
+ }
+
@Override
public GroupBrokerAdmin getBrokerAdmin()
{
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/3a6893e4/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index 93ee991..5b56477 100644
--- a/pom.xml
+++ b/pom.xml
@@ -460,6 +460,12 @@
<version>${project.version}</version>
</dependency>
+ <dependency>
+ <groupId>org.apache.qpid</groupId>
+ <artifactId>qpid-systests-http</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
<!-- External dependencies -->
<dependency>
<groupId>org.apache.qpid</groupId>
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/3a6893e4/qpid-perftests-systests/pom.xml
----------------------------------------------------------------------
diff --git a/qpid-perftests-systests/pom.xml b/qpid-perftests-systests/pom.xml
index eec0c5d..57b724f 100644
--- a/qpid-perftests-systests/pom.xml
+++ b/qpid-perftests-systests/pom.xml
@@ -65,17 +65,15 @@
<optional>true</optional>
</dependency>
+ <dependency>
+ <groupId>org.apache.qpid</groupId>
+ <artifactId>qpid-systests-http</artifactId>
+ <scope>test</scope>
+ </dependency>
+
</dependencies>
<build>
- <resources>
- <resource>
- <directory>src/main/resources</directory>
- </resource>
- <resource>
- <directory>${test.resource.directory}/test-profiles/test_resources</directory>
- </resource>
- </resources>
<testResources>
<testResource>
<directory>src/test/java</directory>
@@ -86,6 +84,12 @@
<testResource>
<directory>src/test/resources</directory>
</testResource>
+ <testResource>
+ <directory>${basedir}/../test-profiles/test_resources/ssl</directory>
+ <includes>
+ <include>*.jks</include>
+ </includes>
+ </testResource>
</testResources>
</build>
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/3a6893e4/qpid-perftests-systests/src/test/java/org/apache/qpid/systest/disttest/endtoend/EndToEndTest.java
----------------------------------------------------------------------
diff --git a/qpid-perftests-systests/src/test/java/org/apache/qpid/systest/disttest/endtoend/EndToEndTest.java b/qpid-perftests-systests/src/test/java/org/apache/qpid/systest/disttest/endtoend/EndToEndTest.java
index 74e5ddd..ceeb585 100644
--- a/qpid-perftests-systests/src/test/java/org/apache/qpid/systest/disttest/endtoend/EndToEndTest.java
+++ b/qpid-perftests-systests/src/test/java/org/apache/qpid/systest/disttest/endtoend/EndToEndTest.java
@@ -21,27 +21,35 @@ package org.apache.qpid.systest.disttest.endtoend;
import static org.apache.qpid.disttest.AbstractRunner.JNDI_CONFIG_PROP;
import static org.apache.qpid.disttest.ControllerRunner.HILL_CLIMB;
import static org.apache.qpid.disttest.ControllerRunner.HILL_CLIMBER_CONSUMPTION_TO_PRODUCTION_RATIO_SUCCESS_THRESHOLD;
-import static org.apache.qpid.disttest.ControllerRunner.HILL_CLIMBER_MINIMUM_DELTA;
import static org.apache.qpid.disttest.ControllerRunner.HILL_CLIMBER_MAX_NUMBER_OF_RUNS;
+import static org.apache.qpid.disttest.ControllerRunner.HILL_CLIMBER_MINIMUM_DELTA;
import static org.apache.qpid.disttest.ControllerRunner.HILL_CLIMBER_PRODUCTION_TO_TARGET_RATIO_SUCCESS_THRESHOLD;
import static org.apache.qpid.disttest.ControllerRunner.HILL_CLIMBER_START_TARGET_RATE;
import static org.apache.qpid.disttest.ControllerRunner.OUTPUT_DIR_PROP;
import static org.apache.qpid.disttest.ControllerRunner.TEST_CONFIG_PROP;
+import static org.apache.qpid.tests.http.HttpTestBase.DEFAULT_BROKER_CONFIG;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeThat;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
-import java.io.UnsupportedEncodingException;
-import java.net.URLEncoder;
+import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
-import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
import org.apache.qpid.disttest.ControllerRunner;
import org.apache.qpid.disttest.DistributedTestException;
import org.apache.qpid.disttest.controller.config.QueueConfig;
@@ -49,60 +57,66 @@ import org.apache.qpid.disttest.jms.QpidQueueCreatorFactory;
import org.apache.qpid.disttest.jms.QpidRestAPIQueueCreator;
import org.apache.qpid.disttest.message.ParticipantAttribute;
import org.apache.qpid.disttest.results.aggregation.TestResultAggregator;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.test.utils.TestFileUtils;
+import org.apache.qpid.server.model.Protocol;
+import org.apache.qpid.tests.http.HttpTestBase;
+import org.apache.qpid.tests.utils.BrokerAdmin;
+import org.apache.qpid.tests.utils.ConfigItem;
import org.apache.qpid.util.FileUtils;
-public class EndToEndTest extends QpidBrokerTestCase
+@ConfigItem(name = "qpid.initialConfigurationLocation", value = DEFAULT_BROKER_CONFIG )
+public class EndToEndTest extends HttpTestBase
{
private static final String TEST_CONFIG_ITERATIONS = "qpid-perftests-systests/src/test/resources/org/apache/qpid/systest/disttest/endtoend/iterations.json";
private static final String TEST_CONFIG_MANYPARTICIPANTS = "qpid-perftests-systests/src/test/resources/org/apache/qpid/systest/disttest/endtoend/manyparticipants.json";
private static final String TEST_CONFIG_HILLCLIMBING = "qpid-perftests-systests/src/test/resources/org/apache/qpid/systest/disttest/endtoend/hillclimbing.js";
private static final String TEST_CONFIG_ERROR = "qpid-perftests-systests/src/test/resources/org/apache/qpid/systest/disttest/endtoend/error.json";
- private static final String JNDI_CONFIG_FILE = "qpid-perftests-systests/src/test/resources/org/apache/qpid/systest/disttest/perftests.systests.properties";
+
private static final int NUMBER_OF_HEADERS = 1;
private static final int NUMBER_OF_SUMMARIES = 3;
private File _outputDir;
private File _jndiConfigFile;
- @Override
+ @Before
public void setUp() throws Exception
{
- getDefaultBrokerConfiguration().addHttpManagementConfiguration();
- super.setUp();
- setSystemProperty("perftests.manangement-url", String.format("http://localhost:%d", getDefaultBroker().getHttpPort()));
- setSystemProperty("perftests.broker-virtualhostnode", "test");
- setSystemProperty("perftests.broker-virtualhost", "test");
- setSystemProperty(QpidQueueCreatorFactory.QUEUE_CREATOR_CLASS_NAME_SYSTEM_PROPERTY, QpidRestAPIQueueCreator.class.getName());
+ System.setProperty("perftests.manangement-url", String.format("http://localhost:%d", getBrokerAdmin().getBrokerAddress(
+ BrokerAdmin.PortType.HTTP).getPort()));
+ System.setProperty("perftests.broker-virtualhostnode", getVirtualHost());
+ System.setProperty("perftests.broker-virtualhost", getVirtualHost());
+ System.setProperty(QpidQueueCreatorFactory.QUEUE_CREATOR_CLASS_NAME_SYSTEM_PROPERTY, QpidRestAPIQueueCreator.class.getName());
_outputDir = createTemporaryOutputDirectory();
- assertTrue("Output dir must not exist", _outputDir.isDirectory());
+ assumeThat("Output dir must not exist", _outputDir.isDirectory(), is(equalTo(true)));
_jndiConfigFile = getJNDIPropertiesFile();
QpidRestAPIQueueCreator queueCreator = new QpidRestAPIQueueCreator();
QueueConfig queueConfig = new QueueConfig("controllerqueue", true, Collections.<String, Object>emptyMap());
queueCreator.createQueues(null, null, Collections.<QueueConfig>singletonList(queueConfig));
}
- @Override
- public void tearDown() throws Exception
+ @After
+ public void tearDown()
{
try
{
if (_outputDir != null && _outputDir.exists())
{
- FileUtils.delete(_outputDir, true);
+ FileUtils.delete(_outputDir, true);
}
- if (_jndiConfigFile != null && !new File(JNDI_CONFIG_FILE).equals(_jndiConfigFile))
+ if (_jndiConfigFile != null)
{
FileUtils.delete(_jndiConfigFile, true);
}
}
finally
{
- super.tearDown();
+ System.clearProperty("perftests.manangement-url");
+ System.clearProperty("perftests.broker-virtualhostnode");
+ System.clearProperty("perftests.broker-virtualhost");
+ System.clearProperty(QpidQueueCreatorFactory.QUEUE_CREATOR_CLASS_NAME_SYSTEM_PROPERTY);
}
}
+ @Test
public void testIterations() throws Exception
{
Map<String, String> arguments = new HashMap<>();
@@ -120,7 +134,7 @@ public class EndToEndTest extends QpidBrokerTestCase
int dataRowsPerIteration = numberOfParticipants + NUMBER_OF_SUMMARIES;
int numberOfExpectedRows = NUMBER_OF_HEADERS + dataRowsPerIteration * numberOfIterations;
- assertEquals("Unexpected number of lines in CSV", numberOfExpectedRows, csvLines.length);
+ assertThat("Unexpected number of lines in CSV", csvLines.length, is(equalTo(numberOfExpectedRows)));
final String testName = "Iterations";
assertDataRowsForIterationArePresent(csvLines, testName, 0, dataRowsPerIteration);
@@ -129,6 +143,7 @@ public class EndToEndTest extends QpidBrokerTestCase
assertDataRowHasCorrectTestAndClientName(testName, "", TestResultAggregator.ALL_PARTICIPANTS_NAME, csvLines[4 + dataRowsPerIteration]);
}
+ @Test
public void testManyParticipants() throws Exception
{
Map<String, String> arguments = new HashMap<>();
@@ -145,7 +160,7 @@ public class EndToEndTest extends QpidBrokerTestCase
int dataRowsPerIteration = numberOfParticipants + NUMBER_OF_SUMMARIES;
int numberOfExpectedRows = NUMBER_OF_HEADERS + dataRowsPerIteration;
- assertEquals("Unexpected number of lines in CSV", numberOfExpectedRows, csvLines.length);
+ assertThat("Unexpected number of lines in CSV", csvLines.length, is(equalTo(numberOfExpectedRows)));
int actualMessagesSent = 0;
int reportedTotalMessagesSent = 0;
@@ -180,15 +195,14 @@ public class EndToEndTest extends QpidBrokerTestCase
}
}
- assertEquals("Reported total messages sent does not match total sent by producers",
- reportedTotalMessagesSent,
- actualMessagesSent);
- assertEquals("Reported total messages received does not match total received by consumers",
- reportedTotalMessagesReceived,
- actualMessagesReceived);
+ assertThat("Reported total messages sent does not match total sent by producers",
+ actualMessagesSent, is(equalTo(reportedTotalMessagesSent)));
+ assertThat("Reported total messages received does not match total received by consumers",
+ actualMessagesReceived, is(equalTo(reportedTotalMessagesReceived)));
}
+ @Test
public void testHillClimbing() throws Exception
{
Map<String, String> arguments = new HashMap<>();
@@ -212,7 +226,7 @@ public class EndToEndTest extends QpidBrokerTestCase
int numberOfParticipants = 2;
int numberOfExpectedRows = NUMBER_OF_HEADERS + numberOfParticipants + NUMBER_OF_SUMMARIES;
- assertEquals("Unexpected number of lines in CSV", numberOfExpectedRows, csvLines.length);
+ assertThat("Unexpected number of lines in CSV", csvLines.length, is(equalTo(numberOfExpectedRows)));
final String testName = "HillClimbing";
assertDataRowHasCorrectTestAndClientName(testName, "producingClient", "Producer1", csvLines[1]);
@@ -229,6 +243,7 @@ public class EndToEndTest extends QpidBrokerTestCase
}
+ @Test
public void testTestScriptCausesError() throws Exception
{
Map<String, String> arguments = new HashMap<>();
@@ -267,7 +282,7 @@ public class EndToEndTest extends QpidBrokerTestCase
String expectedCsvFilename = buildOutputFilename(testConfig, ".csv");
File expectedCsvOutputFile = new File(_outputDir, expectedCsvFilename);
- assertTrue("CSV output file must exist", expectedCsvOutputFile.exists());
+ assertThat("CSV output file must exist", expectedCsvOutputFile.exists(), is(equalTo(true)));
final String csvContents = FileUtils.readFileAsString(expectedCsvOutputFile);
return csvContents.split("\n");
}
@@ -278,7 +293,7 @@ public class EndToEndTest extends QpidBrokerTestCase
String expectedXmlFilename = buildOutputFilename(testConfig, ".xml");
File expectedXmlOutputFile = new File(_outputDir, expectedXmlFilename);
- assertTrue("XML output file must exist", expectedXmlOutputFile.exists());
+ assertThat("XML output file must exist", expectedXmlOutputFile.exists(), is(equalTo(true)));
}
private String buildOutputFilename(final String testConfig, final String extension)
@@ -303,7 +318,9 @@ public class EndToEndTest extends QpidBrokerTestCase
}
}
- assertEquals("Unexpected number of data rows for test name " + testName + " iteration nunber " + iterationNumber, expectedCount, actualCount);
+ assertThat(String.format("Unexpected number of data rows for test name %s iteration number %d",
+ testName,
+ iterationNumber), actualCount, is(equalTo(expectedCount)));
}
private void assertDataRowHasThroughputValues(String csvLine)
@@ -312,21 +329,34 @@ public class EndToEndTest extends QpidBrokerTestCase
double throughput = Double.valueOf(cells[ParticipantAttribute.THROUGHPUT.ordinal()]);
int messageThroughput = Integer.valueOf(cells[ParticipantAttribute.MESSAGE_THROUGHPUT.ordinal()]);
- assertTrue("Throughput in line " + csvLine + " is not greater than zero : " + throughput, throughput > 0);
- assertTrue("Message throughput in line " + csvLine + " is not greater than zero : " + messageThroughput, messageThroughput > 0);
-
+ assertThat("Throughput in line " + csvLine + " is not greater than zero : " + throughput,
+ throughput > 0,
+ is(equalTo(true)));
+ assertThat("Message throughput in line " + csvLine + " is not greater than zero : " + messageThroughput,
+ messageThroughput > 0,
+ is(equalTo(true)));
}
- private void assertDataRowHasCorrectTestAndClientName(String testName, String clientName, String participantName, String csvLine)
+ private void assertDataRowHasCorrectTestAndClientName(String testName,
+ String clientName,
+ String participantName,
+ String csvLine)
{
String[] cells = splitCsvCells(csvLine);
// All attributes become cells in the CSV, so this will be true
- assertEquals("Unexpected number of cells in CSV line " + csvLine, ParticipantAttribute.values().length, cells.length);
- assertEquals("Unexpected test name in CSV line " + csvLine, testName, cells[ParticipantAttribute.TEST_NAME.ordinal()]);
- assertEquals("Unexpected client name in CSV line " + csvLine, clientName, cells[ParticipantAttribute.CONFIGURED_CLIENT_NAME.ordinal()]);
- assertEquals("Unexpected participant name in CSV line " + csvLine, participantName, cells[ParticipantAttribute.PARTICIPANT_NAME.ordinal()]);
-
+ assertThat("Unexpected number of cells in CSV line " + csvLine,
+ cells.length,
+ is(equalTo(ParticipantAttribute.values().length)));
+ assertThat("Unexpected test name in CSV line " + csvLine,
+ cells[ParticipantAttribute.TEST_NAME.ordinal()],
+ is(equalTo(testName)));
+ assertThat("Unexpected client name in CSV line " + csvLine,
+ cells[ParticipantAttribute.CONFIGURED_CLIENT_NAME.ordinal()],
+ is(equalTo(clientName)));
+ assertThat("Unexpected participant name in CSV line " + csvLine,
+ cells[ParticipantAttribute.PARTICIPANT_NAME.ordinal()],
+ is(equalTo(participantName)));
}
private String[] splitCsvCells(String csvLine)
@@ -346,56 +376,22 @@ public class EndToEndTest extends QpidBrokerTestCase
private File getJNDIPropertiesFile() throws Exception
{
- if (isBroker10())
- {
- Map<String,String> options = new LinkedHashMap<>();
- options.put("amqp.vhost", "test");
- options.put("jms.username", GUEST_USERNAME);
- options.put("jms.password", GUEST_PASSWORD);
-
- StringBuilder stem = new StringBuilder("amqp://localhost:").append(System.getProperty("test.port"));
- appendOptions(options, stem);
-
- Properties properties = new Properties();
- properties.put("connectionfactory.connectionfactory", stem.toString());
- properties.put("java.naming.factory.initial", "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
- properties.put("queue.controllerqueue", "controllerqueue");
-
- File propertiesFile = TestFileUtils.createTempFile(this, ".jndi.properties");
- try(OutputStream os = new FileOutputStream(propertiesFile))
- {
- properties.store(os, null);
- }
- return propertiesFile;
- }
- else
+ String connectionUrl = getConnectionBuilder().setClientId(null).buildConnectionURL();
+ String factoryClass = getProtocol() == Protocol.AMQP_1_0
+ ? "org.apache.qpid.jms.jndi.JmsInitialContextFactory"
+ : "org.apache.qpid.jndi.PropertiesFileInitialContextFactory";
+
+ Properties properties = new Properties();
+ properties.put("connectionfactory.connectionfactory", connectionUrl);
+ properties.put("java.naming.factory.initial", factoryClass);
+ properties.put("queue.controllerqueue", "controllerqueue");
+
+ File propertiesFile = Files.createTempFile("perftests", ".jndi.properties").toFile();
+ try (OutputStream os = new FileOutputStream(propertiesFile))
{
- return new File(JNDI_CONFIG_FILE);
+ properties.store(os, null);
}
+ return propertiesFile;
}
- private void appendOptions(final Map<String, String> actualOptions, final StringBuilder stem)
- {
- boolean first = true;
- for(Map.Entry<String, String> option : actualOptions.entrySet())
- {
- if(first)
- {
- stem.append('?');
- first = false;
- }
- else
- {
- stem.append('&');
- }
- try
- {
- stem.append(option.getKey()).append('=').append(URLEncoder.encode(option.getValue(), "UTF-8"));
- }
- catch (UnsupportedEncodingException e)
- {
- throw new RuntimeException(e);
- }
- }
- }
}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/3a6893e4/qpid-perftests-systests/src/test/resources/org/apache/qpid/systest/disttest/perftests.systests.properties
----------------------------------------------------------------------
diff --git a/qpid-perftests-systests/src/test/resources/org/apache/qpid/systest/disttest/perftests.systests.properties b/qpid-perftests-systests/src/test/resources/org/apache/qpid/systest/disttest/perftests.systests.properties
deleted file mode 100644
index 23f101f..0000000
--- a/qpid-perftests-systests/src/test/resources/org/apache/qpid/systest/disttest/perftests.systests.properties
+++ /dev/null
@@ -1,29 +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.
-
-# this file is used for running system tests of the performance test framework,
-# (i.e. not for running the performance tests themselves!)
-
-java.naming.factory.initial = org.apache.qpid.jndi.PropertiesFileInitialContextFactory
-
-# use QpidBrokerTestCase's default port
-connectionfactory.connectionfactory = amqp://guest:guest@clientid/test?brokerlist='tcp://localhost:${test.port}'
-
-destination.controllerqueue = direct://amq.direct//controllerqueue
-
-jdbcDriverClass=org.apache.derby.jdbc.EmbeddedDriver
-jdbcUrl=jdbc:derby:/tmp/tempDbDirectory/perftestResultsDb;create=true
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/3a6893e4/systests/qpid-systests-http-management/src/main/java/org/apache/qpid/tests/http/HttpTestBase.java
----------------------------------------------------------------------
diff --git a/systests/qpid-systests-http-management/src/main/java/org/apache/qpid/tests/http/HttpTestBase.java b/systests/qpid-systests-http-management/src/main/java/org/apache/qpid/tests/http/HttpTestBase.java
index 91255ef..04f37ea 100644
--- a/systests/qpid-systests-http-management/src/main/java/org/apache/qpid/tests/http/HttpTestBase.java
+++ b/systests/qpid-systests-http-management/src/main/java/org/apache/qpid/tests/http/HttpTestBase.java
@@ -42,6 +42,8 @@ import org.apache.qpid.tests.utils.BrokerAdminUsingTestBase;
public abstract class HttpTestBase extends BrokerAdminUsingTestBase
{
+ public static final String DEFAULT_BROKER_CONFIG = "classpath:config-http-management-tests.json";
+
@Rule
public final TestName _testName = new TestName();
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/3a6893e4/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/AmqpManagementFacade.java
----------------------------------------------------------------------
diff --git a/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/AmqpManagementFacade.java b/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/AmqpManagementFacade.java
index 5ac57cf..1d54210 100644
--- a/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/AmqpManagementFacade.java
+++ b/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/AmqpManagementFacade.java
@@ -132,13 +132,20 @@ public class AmqpManagementFacade
}
producer.close();
+ return receiveManagementResponse(consumer, replyToDestination, 201);
+ }
+
+ private Map<String, Object> receiveManagementResponse(final MessageConsumer consumer,
+ final Destination replyToDestination,
+ final int responseStatus) throws JMSException
+ {
Message response = consumer.receive(5000);
try
{
if (response != null)
{
int statusCode = response.getIntProperty("statusCode");
- if (statusCode == 201)
+ if (statusCode == responseStatus)
{
if (response instanceof MapMessage)
{
@@ -163,6 +170,10 @@ public class AmqpManagementFacade
return new HashMap<>(bodyMap);
}
}
+ else
+ {
+ return Collections.emptyMap();
+ }
}
else
{
@@ -170,7 +181,7 @@ public class AmqpManagementFacade
}
}
- throw new IllegalArgumentException("Cannot parse the results from a management query");
+ throw new IllegalArgumentException("Cannot parse the results from a management response");
}
finally
{
@@ -182,12 +193,50 @@ public class AmqpManagementFacade
}
}
+ public Map<String,Object> updateEntityUsingAmqpManagementAndReceiveResponse(final String name,
+ final String type,
+ Map<String, Object> attributes,
+ final Session session)
+ throws JMSException
+ {
+
+ Destination replyToDestination;
+ Destination replyConsumerDestination;
+ if (_protocol == Protocol.AMQP_1_0)
+ {
+ replyToDestination = session.createTemporaryQueue();
+ replyConsumerDestination = replyToDestination;
+ }
+ else
+ {
+ replyToDestination = session.createQueue(AMQP_0_X_REPLY_TO_DESTINATION);
+ replyConsumerDestination = session.createQueue(AMQP_0_X_CONSUMER_REPLY_DESTINATION);
+ }
+
+ MessageConsumer consumer = session.createConsumer(replyConsumerDestination);
+
+ updateEntityUsingAmqpManagement(name, type, attributes, replyToDestination, session);
+
+ return receiveManagementResponse(consumer, replyToDestination, 200);
+ }
+
+
public void updateEntityUsingAmqpManagement(final String name,
final Session session,
final String type,
Map<String, Object> attributes)
throws JMSException
{
+ updateEntityUsingAmqpManagement(name, type, attributes, null, session);
+ }
+
+ private void updateEntityUsingAmqpManagement(final String name,
+ final String type,
+ Map<String, Object> attributes,
+ Destination replyToDestination,
+ final Session session)
+ throws JMSException
+ {
MessageProducer producer = session.createProducer(session.createQueue(_managementAddress));
MapMessage createMessage = session.createMapMessage();
@@ -195,6 +244,7 @@ public class AmqpManagementFacade
createMessage.setStringProperty("operation", "UPDATE");
createMessage.setStringProperty("index", "object-path");
createMessage.setStringProperty("key", name);
+ createMessage.setJMSReplyTo(replyToDestination);
for (Map.Entry<String, Object> entry : attributes.entrySet())
{
createMessage.setObject(entry.getKey(), entry.getValue());
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/3a6893e4/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/ConnectionBuilder.java
----------------------------------------------------------------------
diff --git a/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/ConnectionBuilder.java b/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/ConnectionBuilder.java
index 2fa7b16..4f113b4 100644
--- a/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/ConnectionBuilder.java
+++ b/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/ConnectionBuilder.java
@@ -67,4 +67,5 @@ public interface ConnectionBuilder
Connection build() throws NamingException, JMSException;
ConnectionFactory buildConnectionFactory() throws NamingException;
+ String buildConnectionURL();
}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/3a6893e4/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/JmsTestBase.java
----------------------------------------------------------------------
diff --git a/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/JmsTestBase.java b/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/JmsTestBase.java
index e654672..c264b6b 100644
--- a/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/JmsTestBase.java
+++ b/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/JmsTestBase.java
@@ -52,6 +52,8 @@ import org.apache.qpid.tests.utils.BrokerAdminUsingTestBase;
public abstract class JmsTestBase extends BrokerAdminUsingTestBase
{
+ public static final String DEFAULT_BROKER_CONFIG = "classpath:config-jms-tests.json";
+
private static final Logger LOGGER = LoggerFactory.getLogger(JmsTestBase.class);
private static JmsProvider _jmsProvider;
private static AmqpManagementFacade _managementFacade;
@@ -232,7 +234,7 @@ public abstract class JmsTestBase extends BrokerAdminUsingTestBase
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
try
{
- _managementFacade.updateEntityUsingAmqpManagement(entityName, session, entityType, attributes);
+ _managementFacade.updateEntityUsingAmqpManagementAndReceiveResponse(entityName, entityType, attributes, session);
}
finally
{
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/3a6893e4/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClient0xConnectionBuilder.java
----------------------------------------------------------------------
diff --git a/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClient0xConnectionBuilder.java b/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClient0xConnectionBuilder.java
index 262d20b..b9590f6 100644
--- a/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClient0xConnectionBuilder.java
+++ b/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClient0xConnectionBuilder.java
@@ -273,6 +273,27 @@ public class QpidJmsClient0xConnectionBuilder implements ConnectionBuilder
@Override
public ConnectionFactory buildConnectionFactory() throws NamingException
{
+ String connectionUrl = buildConnectionURL();
+
+ final Hashtable<Object, Object> initialContextEnvironment = new Hashtable<>();
+ initialContextEnvironment.put(Context.INITIAL_CONTEXT_FACTORY,
+ "org.apache.qpid.jndi.PropertiesFileInitialContextFactory");
+ final String factoryName = "connectionFactory";
+ initialContextEnvironment.put("connectionfactory." + factoryName, connectionUrl);
+ InitialContext initialContext = new InitialContext(initialContextEnvironment);
+ try
+ {
+ return (ConnectionFactory) initialContext.lookup(factoryName);
+ }
+ finally
+ {
+ initialContext.close();
+ }
+ }
+
+ @Override
+ public String buildConnectionURL()
+ {
StringBuilder cUrlBuilder = new StringBuilder("amqp://");
if (_username != null)
{
@@ -352,21 +373,7 @@ public class QpidJmsClient0xConnectionBuilder implements ConnectionBuilder
{
cUrlBuilder.append("&").append(entry.getKey()).append("='").append(entry.getValue()).append("'");
}
-
- final Hashtable<Object, Object> initialContextEnvironment = new Hashtable<>();
- initialContextEnvironment.put(Context.INITIAL_CONTEXT_FACTORY,
- "org.apache.qpid.jndi.PropertiesFileInitialContextFactory");
- final String factoryName = "connectionFactory";
- initialContextEnvironment.put("connectionfactory." + factoryName, cUrlBuilder.toString());
- InitialContext initialContext = new InitialContext(initialContextEnvironment);
- try
- {
- return (ConnectionFactory) initialContext.lookup(factoryName);
- }
- finally
- {
- initialContext.close();
- }
+ return cUrlBuilder.toString();
}
private String buildTransportQuery()
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/3a6893e4/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClientConnectionBuilder.java
----------------------------------------------------------------------
diff --git a/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClientConnectionBuilder.java b/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClientConnectionBuilder.java
index b5be7d2..b5cb304 100644
--- a/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClientConnectionBuilder.java
+++ b/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClientConnectionBuilder.java
@@ -280,6 +280,25 @@ public class QpidJmsClientConnectionBuilder implements ConnectionBuilder
initialContextEnvironment.put(Context.INITIAL_CONTEXT_FACTORY,
"org.apache.qpid.jms.jndi.JmsInitialContextFactory");
+ final String connectionUrl = buildConnectionURL();
+
+ final String factoryName = "connection";
+ initialContextEnvironment.put("connectionfactory." + factoryName, connectionUrl);
+
+ InitialContext initialContext = new InitialContext(initialContextEnvironment);
+ try
+ {
+ return (ConnectionFactory) initialContext.lookup(factoryName);
+ }
+ finally
+ {
+ initialContext.close();
+ }
+ }
+
+ @Override
+ public String buildConnectionURL()
+ {
final StringBuilder connectionUrlBuilder = new StringBuilder();
final Map<String, Object> options = new TreeMap<>();
@@ -344,19 +363,7 @@ public class QpidJmsClientConnectionBuilder implements ConnectionBuilder
connectionUrlBuilder.append("amqps://").append(_host).append(":").append(_sslPort);
appendOptions(options, connectionUrlBuilder);
}
-
- final String factoryName = "connection";
- initialContextEnvironment.put("connectionfactory." + factoryName, connectionUrlBuilder.toString());
-
- InitialContext initialContext = new InitialContext(initialContextEnvironment);
- try
- {
- return (ConnectionFactory) initialContext.lookup(factoryName);
- }
- finally
- {
- initialContext.close();
- }
+ return connectionUrlBuilder.toString();
}
private void appendOptions(final Map<String, Object> actualOptions, final StringBuilder stem)
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/3a6893e4/systests/qpid-systests-spawn-admin/src/main/java/org/apache/qpid/systests/admin/SpawnBrokerAdmin.java
----------------------------------------------------------------------
diff --git a/systests/qpid-systests-spawn-admin/src/main/java/org/apache/qpid/systests/admin/SpawnBrokerAdmin.java b/systests/qpid-systests-spawn-admin/src/main/java/org/apache/qpid/systests/admin/SpawnBrokerAdmin.java
index 16e26e2..350a431 100644
--- a/systests/qpid-systests-spawn-admin/src/main/java/org/apache/qpid/systests/admin/SpawnBrokerAdmin.java
+++ b/systests/qpid-systests-spawn-admin/src/main/java/org/apache/qpid/systests/admin/SpawnBrokerAdmin.java
@@ -339,10 +339,11 @@ public class SpawnBrokerAdmin implements BrokerAdmin, Closeable
throw new BrokerAdminException("Virtual host is not created");
}
invokeManagementOperation(true, (amqpManagementFacade, session) -> {
- amqpManagementFacade.updateEntityUsingAmqpManagement(_virtualHostNodeName,
- session,
- AMQP_NODE_TYPE,
- Collections.singletonMap("desiredState", "ACTIVE"));
+ amqpManagementFacade.updateEntityUsingAmqpManagementAndReceiveResponse(_virtualHostNodeName,
+ AMQP_NODE_TYPE,
+ Collections.singletonMap(
+ "desiredState",
+ "ACTIVE"), session);
return null;
});
}
@@ -354,10 +355,12 @@ public class SpawnBrokerAdmin implements BrokerAdmin, Closeable
throw new BrokerAdminException("Virtual host is not created");
}
invokeManagementOperation(true, (amqpManagementFacade, session) -> {
- amqpManagementFacade.updateEntityUsingAmqpManagement(_virtualHostNodeName,
- session,
- AMQP_NODE_TYPE,
- Collections.singletonMap("desiredState", "STOPPED"));
+ amqpManagementFacade.updateEntityUsingAmqpManagementAndReceiveResponse(_virtualHostNodeName,
+ AMQP_NODE_TYPE,
+ Collections.singletonMap(
+ "desiredState",
+ "STOPPED"),
+ session);
return null;
});
}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/3a6893e4/systests/qpid-systests-spawn-admin/src/main/resources/spawn-broker.json
----------------------------------------------------------------------
diff --git a/systests/qpid-systests-spawn-admin/src/main/resources/spawn-broker.json b/systests/qpid-systests-spawn-admin/src/main/resources/spawn-broker.json
index 029457f..3d4df12 100644
--- a/systests/qpid-systests-spawn-admin/src/main/resources/spawn-broker.json
+++ b/systests/qpid-systests-spawn-admin/src/main/resources/spawn-broker.json
@@ -70,6 +70,9 @@
"name" : "defaultAlias",
"type" : "defaultAlias"
}, {
+ "name" : "hostnameAlias",
+ "type" : "hostnameAlias"
+ }, {
"name" : "nameAlias",
"type" : "nameAlias"
} ]
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org
[6/6] qpid-broker-j git commit: QPID-8158: [Broker-J] [System Tests]
Refactor remaining system tests extending QpidBrokerTestCase
Posted by or...@apache.org.
QPID-8158: [Broker-J] [System Tests] Refactor remaining system tests extending QpidBrokerTestCase
Project: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/repo
Commit: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/commit/3a6893e4
Tree: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/tree/3a6893e4
Diff: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/diff/3a6893e4
Branch: refs/heads/master
Commit: 3a6893e464ec320a7bf4d8ab988c914be8b8f8d8
Parents: 7f0219c
Author: Alex Rudyy <or...@apache.org>
Authored: Wed Apr 11 15:47:34 2018 +0100
Committer: Alex Rudyy <or...@apache.org>
Committed: Wed Apr 11 17:27:23 2018 +0100
----------------------------------------------------------------------
bdbstore/systests/pom.xml | 7 +-
.../berkeleydb/BDBAMQP10V0UpgradeTest.java | 117 ++--
.../server/store/berkeleydb/BDBBackupTest.java | 147 -----
.../server/store/berkeleydb/BDBUpgradeTest.java | 558 +++++++++----------
.../store/berkeleydb/UpgradeTestBase.java | 88 +++
.../BDBHAVirtualHostNodeRestTest.java | 471 ----------------
.../replication/BDBHAVirtualHostRestTest.java | 168 ------
.../berkeleydb/replication/GroupCreator.java | 514 -----------------
.../replication/GroupJmsTestBase.java | 9 +
pom.xml | 6 +
qpid-perftests-systests/pom.xml | 20 +-
.../systest/disttest/endtoend/EndToEndTest.java | 176 +++---
.../disttest/perftests.systests.properties | 29 -
.../apache/qpid/tests/http/HttpTestBase.java | 2 +
.../qpid/systests/AmqpManagementFacade.java | 54 +-
.../apache/qpid/systests/ConnectionBuilder.java | 1 +
.../org/apache/qpid/systests/JmsTestBase.java | 4 +-
.../QpidJmsClient0xConnectionBuilder.java | 37 +-
.../QpidJmsClientConnectionBuilder.java | 33 +-
.../qpid/systests/admin/SpawnBrokerAdmin.java | 19 +-
.../src/main/resources/spawn-broker.json | 3 +
21 files changed, 639 insertions(+), 1824 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/3a6893e4/bdbstore/systests/pom.xml
----------------------------------------------------------------------
diff --git a/bdbstore/systests/pom.xml b/bdbstore/systests/pom.xml
index eefb5bc..b81f3b1 100644
--- a/bdbstore/systests/pom.xml
+++ b/bdbstore/systests/pom.xml
@@ -57,7 +57,12 @@
<dependency>
<groupId>org.apache.qpid</groupId>
<artifactId>qpid-systests-spawn-admin</artifactId>
- <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.qpid</groupId>
+ <artifactId>qpid-systests-jms-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/3a6893e4/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBAMQP10V0UpgradeTest.java
----------------------------------------------------------------------
diff --git a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBAMQP10V0UpgradeTest.java b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBAMQP10V0UpgradeTest.java
index 4d3d9bd..2d8fd16 100644
--- a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBAMQP10V0UpgradeTest.java
+++ b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBAMQP10V0UpgradeTest.java
@@ -19,10 +19,22 @@
*/
package org.apache.qpid.server.store.berkeleydb;
+import static org.apache.qpid.systests.JmsTestBase.DEFAULT_BROKER_CONFIG;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.instanceOf;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeThat;
+
import java.io.File;
+import java.io.IOException;
import java.io.InputStream;
-import java.nio.file.Files;
import java.security.MessageDigest;
+import java.util.Collections;
+import java.util.Map;
import javax.jms.BytesMessage;
import javax.jms.Connection;
@@ -32,11 +44,16 @@ import javax.jms.Queue;
import javax.jms.Session;
import javax.xml.bind.DatatypeConverter;
-import org.apache.qpid.server.model.VirtualHostNode;
-import org.apache.qpid.server.virtualhostnode.berkeleydb.BDBVirtualHostNode;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.test.utils.TestBrokerConfiguration;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import org.apache.qpid.server.model.Protocol;
import org.apache.qpid.server.util.FileUtils;
+import org.apache.qpid.server.virtualhostnode.berkeleydb.BDBVirtualHostNode;
+import org.apache.qpid.systests.JmsTestBase;
+import org.apache.qpid.tests.utils.ConfigItem;
+import org.apache.qpid.tests.utils.RunBrokerAdmin;
/**
*
@@ -51,77 +68,61 @@ import org.apache.qpid.server.util.FileUtils;
* messageProducer.send(message);
*
*/
-public class BDBAMQP10V0UpgradeTest extends QpidBrokerTestCase
+@ConfigItem(name = "qpid.initialConfigurationLocation", value = DEFAULT_BROKER_CONFIG )
+public class BDBAMQP10V0UpgradeTest extends UpgradeTestBase
{
- private static final int EXPECTED_MESSAGE_LENGTH = 256 * 1024;
+ private static final long EXPECTED_MESSAGE_LENGTH = 256 * 1024;
- private String _storeLocation;
-
- @Override
- public void setUp() throws Exception
+ @BeforeClass
+ public static void verifyClient()
{
- _storeLocation = Files.createTempDirectory("qpid-work-" + getClassQualifiedTestName() + "-bdb-store").toString();
- TestBrokerConfiguration brokerConfiguration = getDefaultBrokerConfiguration();
- brokerConfiguration.setObjectAttribute(VirtualHostNode.class, TestBrokerConfiguration.ENTRY_NAME_VIRTUAL_HOST, BDBVirtualHostNode.STORE_PATH, _storeLocation );
-
- //Clear the two target directories if they exist.
- File directory = new File(_storeLocation);
- if (directory.exists() && directory.isDirectory())
- {
- FileUtils.delete(directory, true);
- }
- directory.mkdirs();
-
- // copy store files
- InputStream src = getClass().getClassLoader().getResourceAsStream("upgrade/bdbstore-v9-amqp10v0/test-store/00000000.jdb");
- FileUtils.copy(src, new File(_storeLocation, "00000000.jdb"));
-
- super.setUp();
+ assumeThat(System.getProperty("virtualhostnode.type", "BDB"), is(equalTo("BDB")));
+ assumeThat(getProtocol(), is(equalTo(Protocol.AMQP_1_0)));
}
- @Override
- public void tearDown() throws Exception
+ @Test
+ public void testRecoverAmqpV0Message() throws Exception
{
+ Connection connection = getConnectionBuilder().setVirtualHost("test").build();
try
{
- super.tearDown();
+ connection.start();
+ Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
+ Queue queue = session.createQueue("queue");
+ MessageConsumer consumer = session.createConsumer(queue);
+
+ Message message = consumer.receive(getReceiveTimeout());
+ assertThat("Recovered message not received", message, is(instanceOf(BytesMessage.class)));
+ BytesMessage bytesMessage = ((BytesMessage) message);
+
+ long length = bytesMessage.getBodyLength();
+ String expectedContentHash = message.getStringProperty("sha256hash");
+ byte[] content = new byte[(int) length];
+ bytesMessage.readBytes(content);
+
+ assertThat("Unexpected content length", length, is(equalTo(EXPECTED_MESSAGE_LENGTH)));
+ assertThat("Message should carry expectedShaHash property", expectedContentHash, is(notNullValue()));
+
+ String contentHash = computeContentHash(content);
+ assertThat("Unexpected content hash", expectedContentHash, is(equalTo(contentHash)));
+ session.commit();
}
finally
{
- FileUtils.delete(new File(_storeLocation), true);
+ connection.close();
}
}
- public void testRecoverAmqpV0Message() throws Exception
- {
- Connection connection = getConnection();
- connection.start();
- Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
- Queue queue = createTestQueue(session, "queue");
- MessageConsumer consumer = session.createConsumer(queue);
-
- Message message = consumer.receive(getReceiveTimeout());
- assertNotNull("Recovered message not received", message);
- assertTrue(message instanceof BytesMessage);
- BytesMessage bytesMessage = ((BytesMessage) message);
-
- long length = bytesMessage.getBodyLength();
- String expectedContentHash = message.getStringProperty("sha256hash");
- byte[] content = new byte[(int) length];
- bytesMessage.readBytes(content);
-
- assertEquals("Unexpected content length", EXPECTED_MESSAGE_LENGTH, length);
- assertNotNull("Message should carry expectedShaHash property", expectedContentHash);
-
- String contentHash = computeContentHash(content);
- assertEquals("Unexpected content hash", expectedContentHash, contentHash);
- session.commit();
- }
-
private String computeContentHash(final byte[] content) throws Exception
{
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(content);
return DatatypeConverter.printHexBinary(hash);
}
+
+ @Override
+ String getOldStoreResourcePath()
+ {
+ return "upgrade/bdbstore-v9-amqp10v0/test-store/00000000.jdb";
+ }
}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/3a6893e4/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBBackupTest.java
----------------------------------------------------------------------
diff --git a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBBackupTest.java b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBBackupTest.java
deleted file mode 100644
index aac33c4..0000000
--- a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBBackupTest.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.qpid.server.store.berkeleydb;
-
-import java.io.File;
-import java.util.Map;
-
-import javax.jms.Connection;
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.Session;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.apache.qpid.server.model.VirtualHostNode;
-import org.apache.qpid.server.virtualhostnode.berkeleydb.BDBVirtualHostNode;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.server.util.FileUtils;
-import org.apache.qpid.server.util.Strings;
-
-/**
- * Tests the BDB backup can successfully perform a backup and that
- * backup can be restored and used by the Broker.
- */
-public class BDBBackupTest extends QpidBrokerTestCase
-{
- protected static final Logger LOGGER = LoggerFactory.getLogger(BDBBackupTest.class);
-
- private static final String TEST_VHOST = "test";
- private static final String SYSTEM_TMP_DIR = System.getProperty("java.io.tmpdir");
-
- private File _backupToDir;
- private File _backupFromDir;
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
- _backupToDir = new File(SYSTEM_TMP_DIR + File.separator + getTestName());
- _backupToDir.mkdirs();
-
- Map<String, Object> virtualHostNodeAttributes = getDefaultBrokerConfiguration().getObjectAttributes(VirtualHostNode.class, TEST_VHOST);
- setSystemProperty("qpid.work_dir", getDefaultBroker().getWorkDir().toString());
- _backupFromDir = new File(Strings.expand((String) virtualHostNodeAttributes.get(BDBVirtualHostNode.STORE_PATH)));
- boolean fromDirExistsAndIsDir = _backupFromDir.isDirectory();
- assertTrue("backupFromDir " + _backupFromDir + " should already exist", fromDirExistsAndIsDir);
- }
-
- @Override
- public void tearDown() throws Exception
- {
- try
- {
- super.tearDown();
- }
- finally
- {
- FileUtils.delete(_backupToDir, true);
- }
- }
-
- public void testBackupAndRestoreMaintainsMessages() throws Exception
- {
- sendNumberedMessages(0, 10);
- invokeBdbBackup(_backupFromDir, _backupToDir);
- sendNumberedMessages(10, 20);
- confirmBrokerHasMessages(0, 20);
- stopDefaultBroker();
-
- deleteStore(_backupFromDir);
- replaceStoreWithBackup(_backupToDir, _backupFromDir);
-
- startDefaultBroker();
- confirmBrokerHasMessages(0, 10);
- }
-
- private void sendNumberedMessages(final int startIndex, final int endIndex) throws JMSException, Exception
- {
- Connection con = getConnection();
- Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
- Destination destination = createTestQueue(session);
-
- final int numOfMessages = endIndex - startIndex;
- final int batchSize = 0;
- sendMessage(session, destination, numOfMessages, startIndex, batchSize);
- con.close();
- }
-
- private void confirmBrokerHasMessages(final int startIndex, final int endIndex) throws Exception
- {
- Connection con = getConnection();
- Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
- con.start();
- Destination destination = session.createQueue(getTestQueueName());
- MessageConsumer consumer = session.createConsumer(destination);
- for (int i = startIndex; i < endIndex; i++)
- {
- Message msg = consumer.receive(RECEIVE_TIMEOUT);
- assertNotNull("Message " + i + " not received", msg);
- assertEquals("Did not receive the expected message", i, msg.getIntProperty(INDEX));
- }
-
- Message msg = consumer.receive(100);
- if(msg != null)
- {
- fail("No more messages should be received, but received additional message with index: " + msg.getIntProperty(INDEX));
- }
- con.close();
- }
-
- private void invokeBdbBackup(final File backupFromDir, final File backupToDir) throws Exception
- {
- BDBBackup.main(new String[]{"-todir", backupToDir.getAbsolutePath(), "-fromdir", backupFromDir.getAbsolutePath()});
- }
-
- private void replaceStoreWithBackup(File source, File dst) throws Exception
- {
- LOGGER.debug("Copying store " + source + " to " + dst);
- FileUtils.copyRecursive(source, dst);
- }
-
- private void deleteStore(File storeDir)
- {
- LOGGER.debug("Deleting store " + storeDir);
- FileUtils.delete(storeDir, true);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/3a6893e4/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBUpgradeTest.java
----------------------------------------------------------------------
diff --git a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBUpgradeTest.java b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBUpgradeTest.java
index bf33786..5de003e 100644
--- a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBUpgradeTest.java
+++ b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBUpgradeTest.java
@@ -20,20 +20,29 @@
*/
package org.apache.qpid.server.store.berkeleydb;
+import static org.apache.qpid.systests.JmsTestBase.DEFAULT_BROKER_CONFIG;
+import static org.apache.qpid.systests.Utils.INDEX;
+import static org.apache.qpid.systests.Utils.sendMessages;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.instanceOf;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeThat;
+
import java.io.File;
-import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
-import java.nio.file.Files;
import java.util.Collection;
import java.util.Collections;
-import java.util.HashMap;
import java.util.Map;
+import java.util.concurrent.ThreadLocalRandom;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
-import javax.jms.Destination;
-import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
@@ -46,83 +55,49 @@ import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
import org.apache.qpid.server.model.AlternateBinding;
import org.apache.qpid.server.model.Exchange;
import org.apache.qpid.server.model.ExclusivityPolicy;
-import org.apache.qpid.server.model.VirtualHostNode;
+import org.apache.qpid.server.model.Protocol;
import org.apache.qpid.server.util.FileUtils;
import org.apache.qpid.server.virtualhostnode.berkeleydb.BDBVirtualHostNode;
-import org.apache.qpid.systest.rest.RestTestHelper;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.test.utils.TestBrokerConfiguration;
+import org.apache.qpid.systests.AmqpManagementFacade;
+import org.apache.qpid.systests.JmsTestBase;
+import org.apache.qpid.tests.utils.ConfigItem;
+import org.apache.qpid.tests.utils.EmbeddedBrokerPerClassAdminImpl;
+import org.apache.qpid.tests.utils.RunBrokerAdmin;
/**
* Tests upgrading a BDB store on broker startup.
* The store will then be used to verify that the upgrade is completed
* properly and that once upgraded it functions as expected.
- *
+ * <p>
* Store prepared using old client/broker with BDBStoreUpgradeTestPreparer.
*/
-public class BDBUpgradeTest extends QpidBrokerTestCase
+@ConfigItem(name = "qpid.initialConfigurationLocation", value = DEFAULT_BROKER_CONFIG )
+public class BDBUpgradeTest extends UpgradeTestBase
{
private static final String STRING_1024 = generateString(1024);
- private static final String STRING_1024_256 = generateString(1024*256);
-
- private static final String TOPIC_NAME="myUpgradeTopic";
- private static final String SUB_NAME="myDurSubName";
- private static final String SELECTOR_SUB_NAME="mySelectorDurSubName";
- private static final String SELECTOR_TOPIC_NAME="mySelectorUpgradeTopic";
- private static final String QUEUE_NAME="myUpgradeQueue";
- private static final String NON_DURABLE_QUEUE_NAME="queue-non-durable";
- private static final String PRIORITY_QUEUE_NAME="myPriorityQueue";
- private static final String QUEUE_WITH_DLQ_NAME="myQueueWithDLQ";
-
- private String _storeLocation;
- private RestTestHelper _restTestHelper;
-
- @Override
- public void setUp() throws Exception
- {
- _storeLocation = Files.createTempDirectory("qpid-work-" + getClassQualifiedTestName() + "-bdb-store").toString();
- TestBrokerConfiguration brokerConfiguration = getDefaultBrokerConfiguration();
- brokerConfiguration.addHttpManagementConfiguration();
- brokerConfiguration.setObjectAttribute(VirtualHostNode.class, TestBrokerConfiguration.ENTRY_NAME_VIRTUAL_HOST, BDBVirtualHostNode.STORE_PATH, _storeLocation );
-
- //Clear the two target directories if they exist.
- File directory = new File(_storeLocation);
- if (directory.exists() && directory.isDirectory())
- {
- FileUtils.delete(directory, true);
- }
- directory.mkdirs();
-
- // copy store files
- InputStream src = getClass().getClassLoader().getResourceAsStream("upgrade/bdbstore-v4/test-store/00000000.jdb");
- FileUtils.copy(src, new File(_storeLocation, "00000000.jdb"));
-
- super.setUp();
- _restTestHelper = new RestTestHelper(getDefaultBroker().getHttpPort());
- }
-
- @Override
- public void tearDown() throws Exception
+ private static final String STRING_1024_256 = generateString(1024 * 256);
+
+ private static final String TOPIC_NAME = "myUpgradeTopic";
+ private static final String SUB_NAME = "myDurSubName";
+ private static final String SELECTOR_SUB_NAME = "mySelectorDurSubName";
+ private static final String SELECTOR_TOPIC_NAME = "mySelectorUpgradeTopic";
+ private static final String QUEUE_NAME = "myUpgradeQueue";
+ private static final String PRIORITY_QUEUE_NAME = "myPriorityQueue";
+ private static final String QUEUE_WITH_DLQ_NAME = "myQueueWithDLQ";
+
+ @BeforeClass
+ public static void verifyClient()
{
- try
- {
- _restTestHelper.tearDown();
- }
- finally
- {
- try
- {
- super.tearDown();
- }
- finally
- {
- FileUtils.delete(new File(_storeLocation), true);
- }
- }
+ assumeThat(System.getProperty("virtualhostnode.type", "BDB"), is(equalTo("BDB")));
+ assumeThat(getProtocol(), is(not(equalTo(Protocol.AMQP_1_0))));
}
/**
@@ -131,93 +106,106 @@ public class BDBUpgradeTest extends QpidBrokerTestCase
* by monitoring message count while sending new messages to the topic and then
* consuming them.
*/
+ @Test
public void testSelectorDurability() throws Exception
{
- Connection con = getConnection();
- Queue queue;
+ TopicConnection connection = getTopicConnection();
try
{
- Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
- queue = session.createQueue("BURL:direct:////clientid" + ":" + SELECTOR_SUB_NAME);
+ connection.start();
+
+ TopicSession session = connection.createTopicSession(true, Session.SESSION_TRANSACTED);
+ Topic topic = session.createTopic(SELECTOR_TOPIC_NAME);
+ TopicPublisher publisher = session.createPublisher(topic);
+
+ int index = ThreadLocalRandom.current().nextInt();
+ Message messageA = session.createTextMessage("A");
+ messageA.setIntProperty("ID", index);
+ messageA.setStringProperty("testprop", "false");
+ publisher.publish(messageA);
+
+ Message messageB = session.createTextMessage("B");
+ messageB.setIntProperty("ID", index);
+ messageB.setStringProperty("testprop", "true");
+ publisher.publish(messageB);
+
+ session.commit();
+
+ TopicSubscriber subscriber =
+ session.createDurableSubscriber(topic, SELECTOR_SUB_NAME, "testprop='true'", false);
+ Message migrated = subscriber.receive(getReceiveTimeout());
+ assertThat("Failed to receive migrated message", migrated, is(notNullValue()));
+
+ Message received = subscriber.receive(getReceiveTimeout());
+ session.commit();
+ assertThat("Failed to receive published message", received, is(notNullValue()));
+ assertThat("Message is not Text message", received, is(instanceOf(TextMessage.class)));
+ assertThat("Unexpected text", ((TextMessage) received).getText(), is(equalTo("B")));
+ assertThat("Unexpected index", received.getIntProperty("ID"), is(equalTo(index)));
+
+ session.close();
}
finally
{
- con.close();
+ connection.close();
}
-
- // Create a connection and start it
- TopicConnection connection = (TopicConnection) getConnection();
- connection.start();
-
- // Send messages which don't match and do match the selector, checking message count
- TopicSession pubSession = connection.createTopicSession(true, Session.SESSION_TRANSACTED);
- assertEquals("DurableSubscription backing queue should have 1 message on it initially",
- 1, getQueueDepth(queue.getQueueName()));
-
- Topic topic = pubSession.createTopic(SELECTOR_TOPIC_NAME);
- TopicPublisher publisher = pubSession.createPublisher(topic);
-
- publishMessages(pubSession, publisher, topic, DeliveryMode.PERSISTENT, 1*1024, 1, "false");
- pubSession.commit();
- assertEquals("DurableSubscription backing queue should still have 1 message on it",
- 1, getQueueDepth(queue.getQueueName()));
-
- publishMessages(pubSession, publisher, topic, DeliveryMode.PERSISTENT, 1*1024, 1, "true");
- pubSession.commit();
- assertEquals("DurableSubscription backing queue should now have 2 messages on it",
- 2, getQueueDepth(queue.getQueueName()));
-
- TopicSubscriber durSub = pubSession.createDurableSubscriber(topic, SELECTOR_SUB_NAME,"testprop='true'", false);
- Message m = durSub.receive(getReceiveTimeout());
- assertNotNull("Failed to receive an expected message", m);
- m = durSub.receive(getReceiveTimeout());
- assertNotNull("Failed to receive an expected message", m);
- pubSession.commit();
-
- pubSession.close();
}
/**
* Test that the DurableSubscription without selector was successfully
* transfered to the new store, and functions as expected with continued use.
*/
+ @Test
public void testDurableSubscriptionWithoutSelector() throws Exception
{
- Connection con = getConnection();
- Queue queue;
+ TopicConnection connection = getTopicConnection();
try
{
- Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
- queue = session.createQueue("BURL:direct:////clientid" + ":" + SUB_NAME);
+ connection.start();
+
+ TopicSession session = connection.createTopicSession(true, Session.SESSION_TRANSACTED);
+
+ Topic topic = session.createTopic(TOPIC_NAME);
+ TopicPublisher publisher = session.createPublisher(topic);
+
+ int index = ThreadLocalRandom.current().nextInt();
+ Message messageA = session.createTextMessage("A");
+ messageA.setIntProperty("ID", index);
+ messageA.setStringProperty("testprop", "false");
+ publisher.publish(messageA);
+
+ Message messageB = session.createTextMessage("B");
+ messageB.setIntProperty("ID", index);
+ messageB.setStringProperty("testprop", "true");
+ publisher.publish(messageB);
+
+ session.commit();
+
+ TopicSubscriber subscriber = session.createDurableSubscriber(topic, SUB_NAME);
+ Message migrated = subscriber.receive(getReceiveTimeout());
+ assertThat("Failed to receive migrated message", migrated, is(notNullValue()));
+
+ Message receivedA = subscriber.receive(getReceiveTimeout());
+ session.commit();
+ assertThat("Failed to receive published message A", receivedA, is(notNullValue()));
+ assertThat("Message A is not Text message", receivedA, is(instanceOf(TextMessage.class)));
+ assertThat("Unexpected text for A", ((TextMessage) receivedA).getText(), is(equalTo("A")));
+ assertThat("Unexpected index", receivedA.getIntProperty("ID"), is(equalTo(index)));
+
+ Message receivedB = subscriber.receive(getReceiveTimeout());
+ session.commit();
+ assertThat("Failed to receive published message B", receivedB, is(notNullValue()));
+ assertThat("Message B is not Text message", receivedB, is(instanceOf(TextMessage.class)));
+ assertThat("Unexpected text for B", ((TextMessage) receivedB).getText(), is(equalTo("B")));
+ assertThat("Unexpected index for B", receivedB.getIntProperty("ID"), is(equalTo(index)));
+
+ session.commit();
+ session.close();
}
finally
{
- con.close();
+ connection.close();
}
- // Create a connection and start it
- TopicConnection connection = (TopicConnection) getConnection();
- connection.start();
-
- // Send new message matching the topic, checking message count
- TopicSession session = connection.createTopicSession(true, Session.SESSION_TRANSACTED);
- assertEquals("DurableSubscription backing queue should have 1 message on it initially",
- 1, getQueueDepth(queue.getQueueName()));
- Topic topic = session.createTopic(TOPIC_NAME);
- TopicPublisher publisher = session.createPublisher(topic);
-
- publishMessages(session, publisher, topic, DeliveryMode.PERSISTENT, 1*1024, 1, "indifferent");
- session.commit();
- assertEquals("DurableSubscription backing queue should now have 2 messages on it",
- 2, getQueueDepth(queue.getQueueName()));
-
- TopicSubscriber durSub = session.createDurableSubscriber(topic, SUB_NAME);
- Message m = durSub.receive(getReceiveTimeout());
- assertNotNull("Failed to receive an expected message", m);
- m = durSub.receive(getReceiveTimeout());
- assertNotNull("Failed to receive an expected message", m);
-
- session.commit();
- session.close();
}
/**
@@ -225,51 +213,61 @@ public class BDBUpgradeTest extends QpidBrokerTestCase
* detected and set as being exclusive during the upgrade process, and that the
* regular queue was not.
*/
+ @Test
public void testQueueExclusivity() throws Exception
{
Map<String, Object> result = getQueueAttributes(QUEUE_NAME);
- ExclusivityPolicy exclusivityPolicy =
- ExclusivityPolicy.valueOf((String) result.get(org.apache.qpid.server.model.Queue.EXCLUSIVE));
- assertEquals("Queue should not have been marked as Exclusive during upgrade",
- ExclusivityPolicy.NONE, exclusivityPolicy);
+ assertThat("Exclusive policy attribute is not found",
+ result.get(org.apache.qpid.server.model.Queue.EXCLUSIVE),
+ is(notNullValue()));
+ assertThat("Queue should not have been marked as Exclusive during upgrade",
+ ExclusivityPolicy.valueOf(String.valueOf(result.get(org.apache.qpid.server.model.Queue.EXCLUSIVE))),
+ is(equalTo(ExclusivityPolicy.NONE)));
result = getQueueAttributes("clientid" + ":" + SUB_NAME);
- exclusivityPolicy =
- ExclusivityPolicy.valueOf((String) result.get(org.apache.qpid.server.model.Queue.EXCLUSIVE));
- assertTrue("DurableSubscription backing queue should have been marked as Exclusive during upgrade",
- exclusivityPolicy != ExclusivityPolicy.NONE);
+ assertThat("Exclusive policy attribute is not found",
+ result.get(org.apache.qpid.server.model.Queue.EXCLUSIVE),
+ is(notNullValue()));
+ assertThat("DurableSubscription backing queue should have been marked as Exclusive during upgrade",
+ ExclusivityPolicy.valueOf(String.valueOf(result.get(org.apache.qpid.server.model.Queue.EXCLUSIVE))),
+ is(not(equalTo(ExclusivityPolicy.NONE))));
}
/**
* Test that the upgraded queue continues to function properly when used
* for persistent messaging and restarting the broker.
- *
+ * <p>
* Sends the new messages to the queue BEFORE consuming those which were
* sent before the upgrade. In doing so, this also serves to test that
* the queue bindings were successfully transitioned during the upgrade.
*/
- public void testBindingAndMessageDurabability() throws Exception
+ @Test
+ public void testBindingAndMessageDurability() throws Exception
{
- // Create a connection and start it
- TopicConnection connection = (TopicConnection) getConnection();
- connection.start();
+ Connection connection = getConnection();
+ try
+ {
+ connection.start();
- Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- Queue queue = session.createQueue(QUEUE_NAME);
- MessageProducer messageProducer = session.createProducer(queue);
+ Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ Queue queue = session.createQueue(QUEUE_NAME);
- // Send a new message
- sendMessages(session, messageProducer, queue, DeliveryMode.PERSISTENT, 256*1024, 1);
+ sendMessages(connection, queue, 1);
- session.close();
+ session.close();
- // Restart the broker
- restartDefaultBroker();
+ // Restart
+ getBrokerAdmin().restart();
- // Drain the queue of all messages
- connection = (TopicConnection) getConnection();
- connection.start();
- consumeQueueMessages(connection, true);
+ // Drain the queue of all messages
+ connection = getConnection();
+ connection.start();
+ consumeQueueMessages(connection, true);
+ }
+ finally
+ {
+ connection.close();
+ }
}
/**
@@ -277,39 +275,22 @@ public class BDBUpgradeTest extends QpidBrokerTestCase
* the broker are properly received following update of the MetaData and
* Content entries during the store upgrade process.
*/
+ @Test
public void testConsumptionOfUpgradedMessages() throws Exception
{
// Create a connection and start it
Connection connection = getConnection();
- connection.start();
-
- consumeDurableSubscriptionMessages(connection, true);
- consumeDurableSubscriptionMessages(connection, false);
- consumeQueueMessages(connection, false);
- }
-
- /**
- * Tests store migration containing messages for non-existing queue.
- *
- * @throws Exception
- */
- public void testMigrationOfMessagesForNonDurableQueues() throws Exception
- {
- // Create a connection and start it
- Connection connection = getConnection();
- connection.start();
-
- // consume a message for non-existing store
- Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- Queue queue = session.createQueue(NON_DURABLE_QUEUE_NAME);
- MessageConsumer messageConsumer = session.createConsumer(queue);
+ try
+ {
+ connection.start();
- for (int i = 1; i <= 3; i++)
+ consumeDurableSubscriptionMessages(connection, true);
+ consumeDurableSubscriptionMessages(connection, false);
+ consumeQueueMessages(connection, false);
+ }
+ finally
{
- Message message = messageConsumer.receive(getReceiveTimeout());
- assertNotNull("Message was not migrated!", message);
- assertTrue("Unexpected message received!", message instanceof TextMessage);
- assertEquals("ID property did not match", i, message.getIntProperty("ID"));
+ connection.close();
}
}
@@ -318,78 +299,90 @@ public class BDBUpgradeTest extends QpidBrokerTestCase
* such that sending messages with priorities out-of-order and then consuming
* them gets the messages back in priority order.
*/
+ @Test
public void testPriorityQueue() throws Exception
{
- // Create a connection and start it
Connection connection = getConnection();
- connection.start();
-
- // send some messages to the priority queue
- Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- Queue queue = session.createQueue(PRIORITY_QUEUE_NAME);
- MessageProducer producer = session.createProducer(queue);
-
- producer.setPriority(4);
- producer.send(createMessage(1, false, session, producer));
- producer.setPriority(1);
- producer.send(createMessage(2, false, session, producer));
- producer.setPriority(9);
- producer.send(createMessage(3, false, session, producer));
- session.close();
-
- //consume the messages, expected order: msg 3, msg 1, msg 2.
- session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- MessageConsumer consumer = session.createConsumer(queue);
-
- Message msg = consumer.receive(getReceiveTimeout());
- assertNotNull("expected message was not received", msg);
- assertEquals(3, msg.getIntProperty("msg"));
- msg = consumer.receive(getReceiveTimeout());
- assertNotNull("expected message was not received", msg);
- assertEquals(1, msg.getIntProperty("msg"));
- msg = consumer.receive(getReceiveTimeout());
- assertNotNull("expected message was not received", msg);
- assertEquals(2, msg.getIntProperty("msg"));
+ try
+ {
+ connection.start();
+
+ // send some messages to the priority queue
+ Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ Queue queue = session.createQueue(PRIORITY_QUEUE_NAME);
+ MessageProducer producer = session.createProducer(queue);
+
+ producer.send(session.createTextMessage("A"), DeliveryMode.PERSISTENT, 4, -1);
+ producer.send(session.createTextMessage("B"), DeliveryMode.PERSISTENT, 1, -1);
+ producer.send(session.createTextMessage("C"), DeliveryMode.PERSISTENT, 9, -1);
+ session.close();
+
+ //consume the messages, expected order: C, A, B.
+ session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ MessageConsumer consumer = session.createConsumer(queue);
+
+ Message message1 = consumer.receive(getReceiveTimeout());
+ assertThat("expected message was not received", message1, is(instanceOf(TextMessage.class)));
+ assertThat(((TextMessage) message1).getText(), is(equalTo("C")));
+ Message message2 = consumer.receive(getReceiveTimeout());
+ assertThat("expected message was not received", message2, is(instanceOf(TextMessage.class)));
+ assertThat(((TextMessage) message2).getText(), is(equalTo("A")));
+ Message message3 = consumer.receive(getReceiveTimeout());
+ assertThat("expected message was not received", message3, is(instanceOf(TextMessage.class)));
+ assertThat(((TextMessage) message3).getText(), is(equalTo("B")));
+ }
+ finally
+ {
+ connection.close();
+ }
}
/**
* Test that the queue configured to have a DLQ was recovered and has the alternate exchange
* and max delivery count, the DLE exists, the DLQ exists with no max delivery count, the
* DLQ is bound to the DLE, and that the DLQ does not itself have a DLQ.
- *
+ * <p>
* DLQs are NOT enabled at the virtualhost level, we are testing recovery of the arguments
* that turned it on for this specific queue.
*/
+ @Test
public void testRecoveryOfQueueWithDLQ() throws Exception
{
//verify the DLE exchange exists, has the expected type, and a single binding for the DLQ
Map<String, Object> exchangeAttributes = getExchangeAttributes(QUEUE_WITH_DLQ_NAME + "_DLE");
- assertEquals("Wrong exchange type", "fanout", (String) exchangeAttributes.get(Exchange.TYPE));
+ assertThat("Wrong exchange type",
+ exchangeAttributes.get(Exchange.TYPE),
+ is(equalTo("org.apache.qpid.FanoutExchange")));
+
+ @SuppressWarnings("unchecked")
Collection<Map<String, Object>> bindings = (Collection<Map<String, Object>>) exchangeAttributes.get("bindings");
- assertEquals(1, bindings.size());
- for(Map<String, Object> binding : bindings)
+ assertThat(bindings.size(), is(equalTo(1)));
+ for (Map<String, Object> binding : bindings)
{
String bindingKey = (String) binding.get("bindingKey");
String queueName = (String) binding.get("destination");
//Because its a fanout exchange, we just return a single '*' key with all bound queues
- assertEquals("unexpected binding key", "dlq", bindingKey);
- assertEquals("unexpected queue name", QUEUE_WITH_DLQ_NAME + "_DLQ", queueName);
+ assertThat("unexpected binding key", bindingKey, is(equalTo("dlq")));
+ assertThat("unexpected queue name", queueName, is(equalTo(QUEUE_WITH_DLQ_NAME + "_DLQ")));
}
//verify the queue exists, has the expected alternate exchange and max delivery count
Map<String, Object> queueAttributes = getQueueAttributes(QUEUE_WITH_DLQ_NAME);
- assertEquals("Queue does not have the expected AlternateExchange",
- new HashMap<>(Collections.singletonMap(AlternateBinding.DESTINATION, QUEUE_WITH_DLQ_NAME + "_DLE")),
- new HashMap<>(((Map<String, Object>) queueAttributes.get(Exchange.ALTERNATE_BINDING))));
- assertEquals("Unexpected maximum delivery count", 2,
- ((Number) queueAttributes.get(org.apache.qpid.server.model.Queue.MAXIMUM_DELIVERY_ATTEMPTS)).intValue());
+ assertThat("Queue does not have the expected AlternateExchange",
+ queueAttributes.get(Exchange.ALTERNATE_BINDING),
+ is(equalTo(Collections.singletonMap(AlternateBinding.DESTINATION, QUEUE_WITH_DLQ_NAME + "_DLE"))));
+
+ assertThat("Unexpected maximum delivery count",
+ ((Number) queueAttributes.get(org.apache.qpid.server.model.Queue.MAXIMUM_DELIVERY_ATTEMPTS)).intValue(),
+ is(equalTo(2)));
Map<String, Object> dlQueueAttributes = getQueueAttributes(QUEUE_WITH_DLQ_NAME + "_DLQ");
- assertNull("Queue should not have an AlternateExchange",
- dlQueueAttributes.get(org.apache.qpid.server.model.Queue.ALTERNATE_BINDING));
- assertEquals("Unexpected maximum delivery count", 0,
- ((Number) dlQueueAttributes.get(org.apache.qpid.server.model.Queue.MAXIMUM_DELIVERY_ATTEMPTS)).intValue());
+ assertThat("Queue should not have an AlternateExchange",
+ dlQueueAttributes.get(org.apache.qpid.server.model.Queue.ALTERNATE_BINDING), is(nullValue()));
+ assertThat("Unexpected maximum delivery count",
+ ((Number) dlQueueAttributes.get(org.apache.qpid.server.model.Queue.MAXIMUM_DELIVERY_ATTEMPTS)).intValue(),
+ is(equalTo(0)));
try
{
@@ -397,33 +390,26 @@ public class BDBUpgradeTest extends QpidBrokerTestCase
getQueueAttributes(queueName);
fail("A DLQ should not exist for the DLQ itself");
}
- catch (FileNotFoundException e)
+ catch (AmqpManagementFacade.OperationUnsuccessfulException e)
{
- // pass
+ assertThat(e.getStatusCode(), is(equalTo(404)));
}
}
- private Map<String, Object> getExchangeAttributes(final String exchangeName) throws IOException
+ @Override
+ String getOldStoreResourcePath()
{
- String exchangeUrl = String.format("exchange/%1$s/%1$s/%2$s",
- TestBrokerConfiguration.ENTRY_NAME_VIRTUAL_HOST,
- exchangeName);
- return _restTestHelper.getJsonAsMap(exchangeUrl);
+ return "upgrade/bdbstore-v4/test-store/00000000.jdb";
}
- private Map<String, Object> getQueueAttributes(final String queueName) throws IOException
+ private Map<String, Object> getExchangeAttributes(final String exchangeName) throws Exception
{
- String queueUrl = String.format("queue/%1$s/%1$s/%2$s",
- TestBrokerConfiguration.ENTRY_NAME_VIRTUAL_HOST,
- queueName);
- return _restTestHelper.getJsonAsMap(queueUrl);
+ return readEntityUsingAmqpManagement(exchangeName, "org.apache.qpid.Exchange", false);
}
- private long getQueueDepth(final String queueName) throws IOException
+ private Map<String, Object> getQueueAttributes(final String queueName) throws Exception
{
- Map<String, Object> queueAttributes = getQueueAttributes(queueName);
- Map<String, Object> statistics = (Map<String, Object>) queueAttributes.get("statistics");
- return ((Number) statistics.get("queueDepthMessages")).longValue();
+ return readEntityUsingAmqpManagement(queueName, "org.apache.qpid.Queue", false);
}
private void consumeDurableSubscriptionMessages(Connection connection, boolean selector) throws Exception
@@ -432,10 +418,10 @@ public class BDBUpgradeTest extends QpidBrokerTestCase
Topic topic = null;
TopicSubscriber durSub = null;
- if(selector)
+ if (selector)
{
topic = session.createTopic(SELECTOR_TOPIC_NAME);
- durSub = session.createDurableSubscriber(topic, SELECTOR_SUB_NAME,"testprop='true'", false);
+ durSub = session.createDurableSubscriber(topic, SELECTOR_SUB_NAME, "testprop='true'", false);
}
else
{
@@ -443,20 +429,21 @@ public class BDBUpgradeTest extends QpidBrokerTestCase
durSub = session.createDurableSubscriber(topic, SUB_NAME);
}
-
// Retrieve the matching message
Message m = durSub.receive(getReceiveTimeout());
- assertNotNull("Failed to receive an expected message", m);
- if(selector)
+ assertThat("Failed to receive an expected message", m, is(notNullValue()));
+ if (selector)
{
- assertEquals("Selector property did not match", "true", m.getStringProperty("testprop"));
+ assertThat("Selector property did not match", m.getStringProperty("testprop"), is(equalTo("true")));
}
- assertEquals("ID property did not match", 1, m.getIntProperty("ID"));
- assertEquals("Message content was not as expected", generateString(1024) , ((TextMessage)m).getText());
+ assertThat("ID property did not match", m.getIntProperty("ID"), is(equalTo(1)));
+ assertThat("Message content was not as expected",
+ ((TextMessage) m).getText(),
+ is(equalTo(generateString(1024))));
// Verify that no more messages are received
- m = durSub.receive(1000);
- assertNull("No more messages should have been recieved", m);
+ m = durSub.receive(getReceiveTimeout());
+ assertThat("No more messages should have been recieved", m, is(nullValue()));
durSub.close();
session.close();
@@ -471,46 +458,41 @@ public class BDBUpgradeTest extends QpidBrokerTestCase
Message m;
// Retrieve the initial pre-upgrade messages
- for (int i=1; i <= 5 ; i++)
+ for (int i = 1; i <= 5; i++)
{
m = consumer.receive(getReceiveTimeout());
- assertNotNull("Failed to receive an expected message", m);
- assertEquals("ID property did not match", i, m.getIntProperty("ID"));
- assertEquals("Message content was not as expected", STRING_1024_256, ((TextMessage)m).getText());
+ assertThat("Failed to receive an expected message", m, is(notNullValue()));
+ assertThat("ID property did not match", m.getIntProperty("ID"), is(equalTo(i)));
+ assertThat("Message content was not as expected",
+ ((TextMessage) m).getText(),
+ is(equalTo(STRING_1024_256)));
}
- for (int i=1; i <= 5 ; i++)
+ for (int i = 1; i <= 5; i++)
{
m = consumer.receive(getReceiveTimeout());
- assertNotNull("Failed to receive an expected message", m);
- assertEquals("ID property did not match", i, m.getIntProperty("ID"));
- assertEquals("Message content was not as expected", STRING_1024, ((TextMessage)m).getText());
+ assertThat("Failed to receive an expected message", m, is(notNullValue()));
+ assertThat("ID property did not match", m.getIntProperty("ID"), is(equalTo(i)));
+ assertThat("Message content was not as expected", ((TextMessage) m).getText(), is((equalTo(STRING_1024))));
}
- if(extraMessage)
+ if (extraMessage)
{
//verify that the extra message is received
m = consumer.receive(getReceiveTimeout());
- assertNotNull("Failed to receive an expected message", m);
- assertEquals("ID property did not match", 1, m.getIntProperty("ID"));
- assertEquals("Message content was not as expected", STRING_1024_256, ((TextMessage)m).getText());
+ assertThat("Failed to receive an expected message", m, is(notNullValue()));
+ assertThat("ID property did not match", m.getIntProperty(INDEX), is(equalTo(0)));
+ }
+ else
+ {
+ // Verify that no more messages are received
+ m = consumer.receive(getReceiveTimeout());
+ assertThat("No more messages should have been recieved", m, is(nullValue()));
}
-
- // Verify that no more messages are received
- m = consumer.receive(getReceiveTimeout());
- assertNull("No more messages should have been recieved", m);
consumer.close();
session.close();
}
- private Message createMessage(int msgId, boolean first, Session producerSession, MessageProducer producer) throws JMSException
- {
- Message send = producerSession.createTextMessage("Message: " + msgId);
- send.setIntProperty("msg", msgId);
-
- return send;
- }
-
/**
* Generates a string of a given length consisting of the sequence 0,1,2,..,9,0,1,2.
*
@@ -528,26 +510,4 @@ public class BDBUpgradeTest extends QpidBrokerTestCase
return new String(chars);
}
- private static void sendMessages(Session session, MessageProducer messageProducer,
- Destination dest, int deliveryMode, int length, int numMesages) throws JMSException
- {
- for (int i = 1; i <= numMesages; i++)
- {
- Message message = session.createTextMessage(generateString(length));
- message.setIntProperty("ID", i);
- messageProducer.send(message, deliveryMode, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
- }
- }
-
- private static void publishMessages(Session session, TopicPublisher publisher,
- Destination dest, int deliveryMode, int length, int numMesages, String selectorProperty) throws JMSException
- {
- for (int i = 1; i <= numMesages; i++)
- {
- Message message = session.createTextMessage(generateString(length));
- message.setIntProperty("ID", i);
- message.setStringProperty("testprop", selectorProperty);
- publisher.publish(message, deliveryMode, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
- }
- }
}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/3a6893e4/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/UpgradeTestBase.java
----------------------------------------------------------------------
diff --git a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/UpgradeTestBase.java b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/UpgradeTestBase.java
new file mode 100644
index 0000000..ae2d373
--- /dev/null
+++ b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/UpgradeTestBase.java
@@ -0,0 +1,88 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package org.apache.qpid.server.store.berkeleydb;
+
+import static org.junit.Assert.fail;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Collections;
+import java.util.Map;
+
+import javax.jms.Connection;
+
+import org.junit.Before;
+
+import org.apache.qpid.server.util.FileUtils;
+import org.apache.qpid.server.virtualhostnode.berkeleydb.BDBVirtualHostNode;
+import org.apache.qpid.systests.JmsTestBase;
+
+public abstract class UpgradeTestBase extends JmsTestBase
+{
+ @Before
+ public void restartWithOldStore() throws Exception
+ {
+ Connection connection = getConnectionBuilder().setVirtualHost("$management").build();
+ try
+ {
+ connection.start();
+ Map<String, Object> attributes =
+ readEntityUsingAmqpManagement(getVirtualHostName(), "org.apache.qpid.VirtualHostNode", false, connection);
+ String storePath = (String) attributes.get(BDBVirtualHostNode.STORE_PATH);
+
+ updateEntityUsingAmqpManagement(getVirtualHostName(),
+ "org.apache.qpid.VirtualHostNode",
+ Collections.singletonMap("desiredState", "STOPPED"), connection);
+ copyStore(new File(storePath));
+ updateEntityUsingAmqpManagement(getVirtualHostName(),
+ "org.apache.qpid.VirtualHostNode",
+ Collections.singletonMap("desiredState", "ACTIVE"), connection);
+ }
+ finally
+ {
+ connection.close();
+ }
+ }
+
+ private void copyStore(final File directory) throws IOException
+ {
+ if (directory.exists() && directory.isDirectory())
+ {
+ FileUtils.delete(directory, true);
+ }
+ if (directory.mkdirs())
+ {
+ try (InputStream src = getClass().getClassLoader()
+ .getResourceAsStream(getOldStoreResourcePath()))
+ {
+ FileUtils.copy(src, new File(directory, "00000000.jdb"));
+ }
+ }
+ else
+ {
+ fail(String.format("Cannot copy store file into '%s'", directory.getAbsolutePath()));
+ }
+ }
+
+
+ abstract String getOldStoreResourcePath();
+}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/3a6893e4/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/BDBHAVirtualHostNodeRestTest.java
----------------------------------------------------------------------
diff --git a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/BDBHAVirtualHostNodeRestTest.java b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/BDBHAVirtualHostNodeRestTest.java
deleted file mode 100644
index 0fde56f..0000000
--- a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/BDBHAVirtualHostNodeRestTest.java
+++ /dev/null
@@ -1,471 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.store.berkeleydb.replication;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletResponse;
-
-import com.sleepycat.je.Durability;
-import com.sleepycat.je.EnvironmentConfig;
-import com.sleepycat.je.rep.NoConsistencyRequiredPolicy;
-import com.sleepycat.je.rep.ReplicatedEnvironment;
-import com.sleepycat.je.rep.ReplicationConfig;
-
-import org.apache.qpid.server.management.plugin.servlet.rest.AbstractServlet;
-import org.apache.qpid.server.model.RemoteReplicationNode;
-import org.apache.qpid.server.model.State;
-import org.apache.qpid.server.model.VirtualHost;
-import org.apache.qpid.server.model.VirtualHostNode;
-import org.apache.qpid.server.virtualhost.berkeleydb.BDBHAVirtualHost;
-import org.apache.qpid.server.virtualhostnode.AbstractVirtualHostNode;
-import org.apache.qpid.server.virtualhostnode.berkeleydb.BDBHARemoteReplicationNode;
-import org.apache.qpid.server.virtualhostnode.berkeleydb.BDBHAVirtualHostNode;
-import org.apache.qpid.server.virtualhostnode.berkeleydb.BDBHAVirtualHostNodeImpl;
-import org.apache.qpid.systest.rest.Asserts;
-import org.apache.qpid.systest.rest.QpidRestTestCase;
-import org.apache.qpid.test.utils.TestBrokerConfiguration;
-
-public class BDBHAVirtualHostNodeRestTest extends QpidRestTestCase
-{
- private static final String NODE1 = "node1";
- private static final String NODE2 = "node2";
- private static final String NODE3 = "node3";
-
- private int _node1HaPort;
- private int _node2HaPort;
- private int _node3HaPort;
-
- private String _hostName;
- private String _baseNodeRestUrl;
-
- @Override
- public void setUp() throws Exception
- {
- setTestSystemProperty(ReplicatedEnvironmentFacade.REMOTE_NODE_MONITOR_INTERVAL_PROPERTY_NAME, "1000");
- setTestSystemProperty(ReplicatedEnvironmentFacade.REMOTE_NODE_MONITOR_TIMEOUT_PROPERTY_NAME, "1000");
-
- super.setUp();
- _hostName = getTestName();
- _baseNodeRestUrl = "virtualhostnode/";
-
- _node1HaPort = findFreePort();
- _node2HaPort = getNextAvailable(_node1HaPort + 1);
- _node3HaPort = getNextAvailable(_node2HaPort + 1);
-
-
- }
-
- @Override
- protected void customizeConfiguration() throws Exception
- {
- super.customizeConfiguration();
- TestBrokerConfiguration config = getDefaultBrokerConfiguration();
- config.removeObjectConfiguration(VirtualHostNode.class, TEST2_VIRTUALHOST);
- config.removeObjectConfiguration(VirtualHostNode.class, TEST3_VIRTUALHOST);
- }
-
- public void testCreate3NodeGroup() throws Exception
- {
- createHANode(NODE1, _node1HaPort, _node1HaPort);
- assertNode(NODE1, _node1HaPort, _node1HaPort, NODE1);
- createHANode(NODE2, _node2HaPort, _node1HaPort);
- assertNode(NODE2, _node2HaPort, _node1HaPort, NODE1);
- createHANode(NODE3, _node3HaPort, _node1HaPort);
- assertNode(NODE3, _node3HaPort, _node1HaPort, NODE1);
- assertRemoteNodes(NODE1, NODE2, NODE3);
- }
-
- public void testMutateStateOfOneNode() throws Exception
- {
- createHANode(NODE1, _node1HaPort, _node1HaPort);
- createHANode(NODE2, _node2HaPort, _node1HaPort);
- createHANode(NODE3, _node3HaPort, _node1HaPort);
-
- String node1Url = _baseNodeRestUrl + NODE1;
- String node2Url = _baseNodeRestUrl + NODE2;
- String node3Url = _baseNodeRestUrl + NODE3;
-
- assertActualAndDesiredStates(node1Url, "ACTIVE", "ACTIVE");
- assertActualAndDesiredStates(node2Url, "ACTIVE", "ACTIVE");
- assertActualAndDesiredStates(node3Url, "ACTIVE", "ACTIVE");
-
- // verify that remote nodes for node1 are created and their state is set to ACTIVE
- _restTestHelper.waitForAttributeChanged("remotereplicationnode/" + NODE2 + "/" + NODE1,
- BDBHARemoteReplicationNode.STATE, "ACTIVE");
- _restTestHelper.waitForAttributeChanged("remotereplicationnode/" + NODE3 + "/" + NODE1,
- BDBHARemoteReplicationNode.STATE, "ACTIVE");
-
- mutateDesiredState(node1Url, "STOPPED");
-
- assertActualAndDesiredStates(node1Url, "STOPPED", "STOPPED");
- assertActualAndDesiredStates(node2Url, "ACTIVE", "ACTIVE");
- assertActualAndDesiredStates(node3Url, "ACTIVE", "ACTIVE");
-
- // verify that remote node state fro node1 is changed to UNAVAILABLE
- _restTestHelper.waitForAttributeChanged("remotereplicationnode/" + NODE2 + "/" + NODE1,
- BDBHARemoteReplicationNode.STATE, "UNAVAILABLE");
- _restTestHelper.waitForAttributeChanged("remotereplicationnode/" + NODE3 + "/" + NODE1,
- BDBHARemoteReplicationNode.STATE, "UNAVAILABLE");
-
- List<Map<String, Object>> remoteNodes = getRestTestHelper().getJsonAsList("remotereplicationnode/" + NODE2);
- assertEquals("Unexpected number of remote nodes on " + NODE2, 2, remoteNodes.size());
-
- Map<String, Object> remoteNode1 = findRemoteNodeByName(remoteNodes, NODE1);
-
- assertEquals("Node 1 observed from node 2 is in the wrong state",
- "UNAVAILABLE", remoteNode1.get(BDBHARemoteReplicationNode.STATE));
- assertEquals("Node 1 observed from node 2 has the wrong role",
- "UNREACHABLE", remoteNode1.get(BDBHARemoteReplicationNode.ROLE));
-
- }
-
- public void testNewMasterElectedWhenVirtualHostIsStopped() throws Exception
- {
- createHANode(NODE1, _node1HaPort, _node1HaPort);
- createHANode(NODE2, _node2HaPort, _node1HaPort);
- createHANode(NODE3, _node3HaPort, _node1HaPort);
-
- String node1Url = _baseNodeRestUrl + NODE1;
- String node2Url = _baseNodeRestUrl + NODE2;
- String node3Url = _baseNodeRestUrl + NODE3;
-
- assertActualAndDesiredStates(node1Url, "ACTIVE", "ACTIVE");
- assertActualAndDesiredStates(node2Url, "ACTIVE", "ACTIVE");
- assertActualAndDesiredStates(node3Url, "ACTIVE", "ACTIVE");
-
- // Put virtualhost in STOPPED state
- String virtualHostRestUrl = "virtualhost/" + NODE1 + "/" + _hostName;
- assertActualAndDesiredStates(virtualHostRestUrl, "ACTIVE", "ACTIVE");
- mutateDesiredState(virtualHostRestUrl, "STOPPED");
- assertActualAndDesiredStates(virtualHostRestUrl, "STOPPED", "STOPPED");
-
- // Now stop node 1 to cause an election between nodes 2 & 3
- mutateDesiredState(node1Url, "STOPPED");
- assertActualAndDesiredStates(node1Url, "STOPPED", "STOPPED");
-
- Map<String, Object> newMasterData = awaitNewMaster(node2Url, node3Url);
-
- //Check the virtual host of the new master is in the stopped state
- String newMasterVirtualHostRestUrl = "virtualhost/" + newMasterData.get(BDBHAVirtualHostNode.NAME) + "/" + _hostName;
- assertActualAndDesiredStates(newMasterVirtualHostRestUrl, "STOPPED", "STOPPED");
- }
-
- public void testDeleteReplicaNode() throws Exception
- {
- createHANode(NODE1, _node1HaPort, _node1HaPort);
- createHANode(NODE2, _node2HaPort, _node1HaPort);
- createHANode(NODE3, _node3HaPort, _node1HaPort);
-
- assertRemoteNodes(NODE1, NODE2, NODE3);
-
- List<Map<String,Object>> data = getRestTestHelper().getJsonAsList("remotereplicationnode/" + NODE1);
- assertEquals("Unexpected number of remote nodes on " + NODE1, 2, data.size());
-
- getRestTestHelper().submitRequest(_baseNodeRestUrl + NODE2, "DELETE", HttpServletResponse.SC_OK);
-
- int counter = 0;
- while (data.size() != 1 && counter<50)
- {
- data = getRestTestHelper().getJsonAsList("remotereplicationnode/" + NODE1);
- if (data.size() != 1)
- {
- Thread.sleep(100l);
- }
- counter++;
- }
- assertEquals("Unexpected number of remote nodes on " + NODE1, 1, data.size());
- }
-
- public void testDeleteMasterNode() throws Exception
- {
- createHANode(NODE1, _node1HaPort, _node1HaPort);
- createHANode(NODE2, _node2HaPort, _node1HaPort);
- createHANode(NODE3, _node3HaPort, _node1HaPort);
-
- assertNode(NODE1, _node1HaPort, _node1HaPort, NODE1);
- assertRemoteNodes(NODE1, NODE2, NODE3);
-
- // change priority to ensure that Node2 becomes a master
- getRestTestHelper().submitRequest(_baseNodeRestUrl + NODE2,
- "PUT",
- Collections.<String, Object>singletonMap(BDBHAVirtualHostNode.PRIORITY, 100),
- HttpServletResponse.SC_OK);
-
- List<Map<String,Object>> data = getRestTestHelper().getJsonAsList("remotereplicationnode/" + NODE2);
- assertEquals("Unexpected number of remote nodes on " + NODE2, 2, data.size());
-
- // delete master
- getRestTestHelper().submitRequest(_baseNodeRestUrl + NODE1, "DELETE", HttpServletResponse.SC_OK);
-
- // wait for new master
- _restTestHelper.waitForAttributeChanged(_baseNodeRestUrl + NODE2 + "?depth=0", BDBHAVirtualHostNode.ROLE, "MASTER");
-
- // delete remote node
- getRestTestHelper().submitRequest("remotereplicationnode/" + NODE2 + "/" + NODE1, "DELETE", HttpServletResponse.SC_OK);
-
- int counter = 0;
- while (data.size() != 1 && counter<50)
- {
- data = getRestTestHelper().getJsonAsList("remotereplicationnode/" + NODE2);
- if (data.size() != 1)
- {
- Thread.sleep(100l);
- }
- counter++;
- }
- assertEquals("Unexpected number of remote nodes on " + NODE2, 1, data.size());
- }
-
- public void testIntruderBDBHAVHNNotAllowedToConnect() throws Exception
- {
- createHANode(NODE1, _node1HaPort, _node1HaPort);
- assertNode(NODE1, _node1HaPort, _node1HaPort, NODE1);
-
- // add permitted node
- Map<String, Object> node3Data = createNodeAttributeMap(NODE3, _node3HaPort, _node1HaPort);
- getRestTestHelper().submitRequest(_baseNodeRestUrl + NODE3, "PUT", node3Data, HttpServletResponse.SC_CREATED);
- assertNode(NODE3, _node3HaPort, _node1HaPort, NODE1);
- assertRemoteNodes(NODE1, NODE3);
-
- int intruderPort = getNextAvailable(_node3HaPort + 1);
-
- // try to add not permitted node
- Map<String, Object> nodeData = createNodeAttributeMap(NODE2, intruderPort, _node1HaPort);
- getRestTestHelper().submitRequest(_baseNodeRestUrl + NODE2, "PUT", nodeData, AbstractServlet.SC_UNPROCESSABLE_ENTITY);
-
- assertRemoteNodes(NODE1, NODE3);
- }
-
- public void testIntruderProtection() throws Exception
- {
- createHANode(NODE1, _node1HaPort, _node1HaPort);
- assertNode(NODE1, _node1HaPort, _node1HaPort, NODE1);
-
- Map<String,Object> nodeData = getRestTestHelper().getJsonAsMap(_baseNodeRestUrl + NODE1);
- String node1StorePath = (String)nodeData.get(BDBHAVirtualHostNode.STORE_PATH);
- long transactionId = ((Number)nodeData.get(BDBHAVirtualHostNode.LAST_KNOWN_REPLICATION_TRANSACTION_ID)).longValue();
-
- // add permitted node
- Map<String, Object> node3Data = createNodeAttributeMap(NODE3, _node3HaPort, _node1HaPort);
- getRestTestHelper().submitRequest(_baseNodeRestUrl + NODE3, "PUT", node3Data, HttpServletResponse.SC_CREATED);
- assertNode(NODE3, _node3HaPort, _node1HaPort, NODE1);
- assertRemoteNodes(NODE1, NODE3);
-
- // Ensure PINGDB is created
- // in order to exclude hanging of environment
- // when environment.close is called whilst PINGDB is created.
- // On node joining, a record is updated in PINGDB
- // if lastTransactionId is incremented then node ping task was executed
- int counter = 0;
- long newTransactionId = transactionId;
- while(newTransactionId == transactionId && counter<50)
- {
- nodeData = getRestTestHelper().getJsonAsMap(_baseNodeRestUrl + NODE1);
- newTransactionId = ((Number)nodeData.get(BDBHAVirtualHostNode.LAST_KNOWN_REPLICATION_TRANSACTION_ID)).longValue();
- if (newTransactionId != transactionId)
- {
- break;
- }
- counter++;
- Thread.sleep(100L);
- }
-
- //connect intruder node
- String nodeName = NODE2;
- String nodeHostPort = "localhost:" + getNextAvailable(_node3HaPort + 1);
- File environmentPathFile = new File(node1StorePath, nodeName);
- environmentPathFile.mkdirs();
- ReplicationConfig replicationConfig = new ReplicationConfig((String)nodeData.get(BDBHAVirtualHostNode.GROUP_NAME), nodeName, nodeHostPort);
- replicationConfig.setHelperHosts((String)nodeData.get(BDBHAVirtualHostNode.ADDRESS));
- replicationConfig.setConsistencyPolicy(NoConsistencyRequiredPolicy.NO_CONSISTENCY);
- EnvironmentConfig envConfig = new EnvironmentConfig();
- envConfig.setAllowCreate(true);
- envConfig.setTransactional(true);
- envConfig.setDurability(Durability.parse((String)nodeData.get(BDBHAVirtualHostNode.DURABILITY)));
-
- ReplicatedEnvironment intruder = null;
- try
- {
- intruder = new ReplicatedEnvironment(environmentPathFile, replicationConfig, envConfig);
- }
- finally
- {
- if (intruder != null)
- {
- intruder.close();
- }
- }
-
- _restTestHelper.waitForAttributeChanged(_baseNodeRestUrl + NODE1, VirtualHostNode.STATE, State.ERRORED.name());
- _restTestHelper.waitForAttributeChanged(_baseNodeRestUrl + NODE3, VirtualHostNode.STATE, State.ERRORED.name());
- }
-
- private void createHANode(String nodeName, int nodePort, int helperPort) throws Exception
- {
- Map<String, Object> nodeData = createNodeAttributeMap(nodeName, nodePort, helperPort);
-
- getRestTestHelper().submitRequest(_baseNodeRestUrl + nodeName, "PUT", nodeData, HttpServletResponse.SC_CREATED);
- String hostExpectedState = nodePort == helperPort ? State.ACTIVE.name(): State.UNAVAILABLE.name();
- _restTestHelper.waitForAttributeChanged("virtualhost/" + nodeName + "/" + _hostName, BDBHAVirtualHost.STATE, hostExpectedState);
- }
-
- private Map<String, Object> createNodeAttributeMap(String nodeName, int nodePort, int helperPort) throws Exception
- {
- Map<String, Object> nodeData = new HashMap<>();
- nodeData.put(BDBHAVirtualHostNode.NAME, nodeName);
- nodeData.put(BDBHAVirtualHostNode.TYPE, BDBHAVirtualHostNodeImpl.VIRTUAL_HOST_NODE_TYPE);
- nodeData.put(BDBHAVirtualHostNode.GROUP_NAME, _hostName);
- nodeData.put(BDBHAVirtualHostNode.ADDRESS, "localhost:" + nodePort);
- nodeData.put(BDBHAVirtualHostNode.HELPER_ADDRESS, "localhost:" + helperPort);
- if (nodePort != helperPort)
- {
- nodeData.put(BDBHAVirtualHostNode.HELPER_NODE_NAME, NODE1);
- }
-
- Map<String,String> context = new HashMap<>();
- nodeData.put(BDBHAVirtualHostNode.CONTEXT, context);
- if (nodePort == helperPort)
- {
- nodeData.put(BDBHAVirtualHostNode.PERMITTED_NODES, GroupCreator.getPermittedNodes("localhost", _node1HaPort, _node2HaPort, _node3HaPort));
- }
- String bluePrint = GroupCreator.getBlueprint();
- context.put(AbstractVirtualHostNode.VIRTUALHOST_BLUEPRINT_CONTEXT_VAR, bluePrint);
- return nodeData;
- }
-
- private void assertNode(String nodeName, int nodePort, int nodeHelperPort, String masterNode) throws Exception
- {
- boolean isMaster = nodeName.equals(masterNode);
- String expectedRole = isMaster? "MASTER" : "REPLICA";
- _restTestHelper.waitForAttributeChanged(_baseNodeRestUrl + nodeName + "?depth=0", BDBHAVirtualHostNode.ROLE, expectedRole);
-
- Map<String, Object> nodeData = getRestTestHelper().getJsonAsMap(_baseNodeRestUrl + nodeName + "?depth=0");
- assertEquals("Unexpected name", nodeName, nodeData.get(BDBHAVirtualHostNode.NAME));
- assertEquals("Unexpected type", BDBHAVirtualHostNodeImpl.VIRTUAL_HOST_NODE_TYPE, nodeData.get(BDBHAVirtualHostNode.TYPE));
- assertEquals("Unexpected address", "localhost:" + nodePort, nodeData.get(BDBHAVirtualHostNode.ADDRESS));
- assertEquals("Unexpected helper address", "localhost:" + nodeHelperPort, nodeData.get(BDBHAVirtualHostNode.HELPER_ADDRESS));
- assertEquals("Unexpected group name", _hostName, nodeData.get(BDBHAVirtualHostNode.GROUP_NAME));
- assertEquals("Unexpected role", expectedRole, nodeData.get(BDBHAVirtualHostNode.ROLE));
-
- Integer lastKnownTransactionId = (Integer) nodeData.get(BDBHAVirtualHostNode.LAST_KNOWN_REPLICATION_TRANSACTION_ID);
- assertNotNull("Unexpected lastKnownReplicationId", lastKnownTransactionId);
- assertTrue("Unexpected lastKnownReplicationId " + lastKnownTransactionId, lastKnownTransactionId > 0);
-
- Long joinTime = (Long) nodeData.get(BDBHAVirtualHostNode.JOIN_TIME);
- assertNotNull("Unexpected joinTime", joinTime);
- assertTrue("Unexpected joinTime " + joinTime, joinTime > 0);
-
- if (isMaster)
- {
- _restTestHelper.waitForAttributeChanged("virtualhost/" + masterNode + "/" + _hostName + "?depth=0", VirtualHost.STATE, State.ACTIVE.name());
- }
-
- }
-
- private void assertRemoteNodes(String masterNode, String... replicaNodes) throws Exception
- {
- List<String> clusterNodes = new ArrayList<>(Arrays.asList(replicaNodes));
- clusterNodes.add(masterNode);
-
- for (String clusterNodeName : clusterNodes)
- {
- List<String> remotes = new ArrayList<>(clusterNodes);
- remotes.remove(clusterNodeName);
- for (String remote : remotes)
- {
- String remoteUrl = "remotereplicationnode/" + clusterNodeName + "/" + remote;
- String desiredNodeState = remote.equals(masterNode) ? "MASTER" : "REPLICA";
- _restTestHelper.waitForAttributeChanged(remoteUrl,
- node -> desiredNodeState.equals(node.get(
- BDBHARemoteReplicationNode.ROLE))
- && (Integer) node.get(BDBHAVirtualHostNode.LAST_KNOWN_REPLICATION_TRANSACTION_ID) > 0
- && ((Number) node.get(BDBHAVirtualHostNode.JOIN_TIME)).longValue() > 0L);
- }
- }
- }
-
- private void assertActualAndDesiredStates(final String restUrl,
- final String expectedDesiredState,
- final String expectedActualState) throws IOException
- {
- Map<String, Object> objectData = getRestTestHelper().getJsonAsMap(restUrl);
- Asserts.assertActualAndDesiredState(expectedDesiredState, expectedActualState, objectData);
- }
-
- private void mutateDesiredState(final String restUrl, final String newState) throws IOException
- {
- Map<String, Object> newAttributes = new HashMap<>();
- newAttributes.put(VirtualHostNode.DESIRED_STATE, newState);
-
- getRestTestHelper().submitRequest(restUrl, "PUT", newAttributes, HttpServletResponse.SC_OK);
- }
-
- private Map<String, Object> findRemoteNodeByName(final List<Map<String, Object>> remoteNodes, final String nodeName)
- {
- Map<String, Object> foundNode = null;
- for (Map<String, Object> remoteNode : remoteNodes)
- {
- if (nodeName.equals(remoteNode.get(RemoteReplicationNode.NAME)))
- {
- foundNode = remoteNode;
- break;
- }
- }
- assertNotNull("Could not find node with name " + nodeName + " amongst remote nodes.");
- return foundNode;
- }
-
- private Map<String, Object> awaitNewMaster(final String... nodeUrls)
- throws IOException, InterruptedException
- {
- Map<String, Object> newMasterData = null;
- int counter = 0;
- while (newMasterData == null && counter < 50)
- {
- for(String nodeUrl: nodeUrls)
- {
- Map<String, Object> nodeData = getRestTestHelper().getJsonAsMap(nodeUrl);
- if ("MASTER".equals(nodeData.get(BDBHAVirtualHostNode.ROLE)))
- {
- newMasterData = nodeData;
- break;
- }
- }
- if (newMasterData == null)
- {
- Thread.sleep(100L);
- counter++;
- }
- }
- assertNotNull("Could not find new master", newMasterData);
- return newMasterData;
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/3a6893e4/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/BDBHAVirtualHostRestTest.java
----------------------------------------------------------------------
diff --git a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/BDBHAVirtualHostRestTest.java b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/BDBHAVirtualHostRestTest.java
deleted file mode 100644
index 9cb5da6..0000000
--- a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/BDBHAVirtualHostRestTest.java
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.store.berkeleydb.replication;
-
-import static org.apache.qpid.server.virtualhost.berkeleydb.BDBHAVirtualHost.LOCAL_TRANSACTION_SYNCHRONIZATION_POLICY;
-import static org.apache.qpid.server.virtualhost.berkeleydb.BDBHAVirtualHost.REMOTE_TRANSACTION_SYNCHRONIZATION_POLICY;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.qpid.server.model.Port;
-import org.apache.qpid.server.model.State;
-import org.apache.qpid.server.model.VirtualHost;
-import org.apache.qpid.server.model.VirtualHostNode;
-import org.apache.qpid.server.virtualhostnode.AbstractVirtualHostNode;
-import org.apache.qpid.server.virtualhostnode.berkeleydb.BDBHAVirtualHostNode;
-import org.apache.qpid.systest.rest.Asserts;
-import org.apache.qpid.systest.rest.QpidRestTestCase;
-import org.apache.qpid.test.utils.TestBrokerConfiguration;
-import org.apache.qpid.server.util.FileUtils;
-
-public class BDBHAVirtualHostRestTest extends QpidRestTestCase
-{
- private String _hostName;
- private File _storeBaseDir;
- private int _nodeHaPort;
- private Object _nodeName;
- private String _virtualhostUrl;
- private String _bluePrint;
- private List<String> _permittedNodes;
- private String _address;
- private int _httpPort;
-
- @Override
- public void setUp() throws Exception
- {
- setTestSystemProperty(ReplicatedEnvironmentFacade.REMOTE_NODE_MONITOR_INTERVAL_PROPERTY_NAME, "1000");
- setTestSystemProperty(ReplicatedEnvironmentFacade.REMOTE_NODE_MONITOR_TIMEOUT_PROPERTY_NAME, "1000");
-
- _hostName = "ha";
- _nodeName = "node1";
- _storeBaseDir = new File(TMP_FOLDER, "store-" + _hostName + "-" + System.currentTimeMillis());
- _httpPort = findFreePort();
- _nodeHaPort = getNextAvailable(_httpPort + 1);
- _virtualhostUrl = "virtualhost/" + _nodeName + "/" + _hostName;
- _bluePrint = GroupCreator.getBlueprint();
- _permittedNodes = GroupCreator.getPermittedNodes("localhost", _nodeHaPort);
- _address = "localhost:" + _nodeHaPort;
- super.setUp();
- }
-
- @Override
- public void tearDown() throws Exception
- {
- try
- {
- super.tearDown();
- }
- finally
- {
- if (_storeBaseDir != null)
- {
- FileUtils.delete(_storeBaseDir, true);
- }
- }
- }
-
- @Override
- protected void customizeConfiguration() throws Exception
- {
- super.customizeConfiguration();
- TestBrokerConfiguration config = getDefaultBrokerConfiguration();
- config.removeObjectConfiguration(VirtualHostNode.class, TEST2_VIRTUALHOST);
- config.removeObjectConfiguration(VirtualHostNode.class, TEST3_VIRTUALHOST);
-
- Map<String, Object> nodeAttributes = new HashMap<String, Object>();
- nodeAttributes.put(BDBHAVirtualHostNode.NAME, _nodeName);
- nodeAttributes.put(BDBHAVirtualHostNode.TYPE, "BDB_HA");
- nodeAttributes.put(BDBHAVirtualHostNode.STORE_PATH, _storeBaseDir.getPath() + File.separator + _nodeName);
- nodeAttributes.put(BDBHAVirtualHostNode.GROUP_NAME, _hostName);
- nodeAttributes.put(BDBHAVirtualHostNode.ADDRESS, _address);
- nodeAttributes.put(BDBHAVirtualHostNode.HELPER_ADDRESS, "localhost:" + _nodeHaPort);
- nodeAttributes.put(BDBHAVirtualHostNode.HELPER_NODE_NAME, _nodeName);
-
- nodeAttributes.put(BDBHAVirtualHostNode.PERMITTED_NODES, _permittedNodes);
- Map<String, String> context = new HashMap<String,String>();
- context.put(AbstractVirtualHostNode.VIRTUALHOST_BLUEPRINT_CONTEXT_VAR, _bluePrint);
-
- nodeAttributes.put(BDBHAVirtualHostNode.CONTEXT, context);
- config.addObjectConfiguration(VirtualHostNode.class, nodeAttributes);
- config.setObjectAttribute(Port.class, TestBrokerConfiguration.ENTRY_NAME_HTTP_PORT, Port.PORT, _httpPort);
- }
-
- public void testSetLocalTransactionSynchronizationPolicy() throws Exception
- {
- Map<String, Object> hostAttributes = _restTestHelper.waitForAttributeChanged(_virtualhostUrl, VirtualHost.STATE, State.ACTIVE.name());
- assertEquals("Unexpected synchronization policy before change", "SYNC", hostAttributes.get(LOCAL_TRANSACTION_SYNCHRONIZATION_POLICY));
-
- Map<String, Object> newPolicy = Collections.<String, Object>singletonMap(LOCAL_TRANSACTION_SYNCHRONIZATION_POLICY, "NO_SYNC");
- getRestTestHelper().submitRequest(_virtualhostUrl, "PUT", newPolicy, HttpServletResponse.SC_OK);
-
- hostAttributes = getRestTestHelper().getJsonAsMap(_virtualhostUrl);
- assertEquals("Unexpected synchronization policy after change", "NO_SYNC", hostAttributes.get(LOCAL_TRANSACTION_SYNCHRONIZATION_POLICY));
- }
-
- public void testSetRemoteTransactionSynchronizationPolicy() throws Exception
- {
- Map<String, Object> hostAttributes = _restTestHelper.waitForAttributeChanged(_virtualhostUrl, VirtualHost.STATE, State.ACTIVE.name());
- assertEquals("Unexpected synchronization policy before change", "NO_SYNC", hostAttributes.get(REMOTE_TRANSACTION_SYNCHRONIZATION_POLICY));
-
- Map<String, Object> newPolicy = Collections.<String, Object>singletonMap(REMOTE_TRANSACTION_SYNCHRONIZATION_POLICY, "SYNC");
- getRestTestHelper().submitRequest(_virtualhostUrl, "PUT", newPolicy, HttpServletResponse.SC_OK);
-
- hostAttributes = getRestTestHelper().getJsonAsMap(_virtualhostUrl);
- assertEquals("Unexpected synchronization policy after change", "SYNC", hostAttributes.get(REMOTE_TRANSACTION_SYNCHRONIZATION_POLICY));
- }
-
- public void testMutateState() throws Exception
- {
- _restTestHelper.waitForAttributeChanged(_virtualhostUrl, VirtualHost.STATE, "ACTIVE");
- assertActualAndDesireStates(_virtualhostUrl, "ACTIVE", "ACTIVE");
-
- Map<String, Object> newAttributes = Collections.<String, Object>singletonMap(VirtualHost.DESIRED_STATE, "STOPPED");
- getRestTestHelper().submitRequest(_virtualhostUrl, "PUT", newAttributes, HttpServletResponse.SC_OK);
-
- _restTestHelper.waitForAttributeChanged(_virtualhostUrl, VirtualHost.STATE, "STOPPED");
- assertActualAndDesireStates(_virtualhostUrl, "STOPPED", "STOPPED");
-
- newAttributes = Collections.<String, Object>singletonMap(VirtualHost.DESIRED_STATE, "ACTIVE");
- getRestTestHelper().submitRequest(_virtualhostUrl, "PUT", newAttributes, HttpServletResponse.SC_OK);
-
- _restTestHelper.waitForAttributeChanged(_virtualhostUrl, VirtualHost.STATE, "ACTIVE");
- assertActualAndDesireStates(_virtualhostUrl, "ACTIVE", "ACTIVE");
- }
-
- private void assertActualAndDesireStates(final String restUrl,
- final String expectedDesiredState,
- final String expectedActualState) throws IOException
- {
- Map<String, Object> virtualhost = getRestTestHelper().getJsonAsMap(restUrl);
- Asserts.assertActualAndDesiredState(expectedDesiredState, expectedActualState, virtualhost);
- }
-
-}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org
[4/6] qpid-broker-j git commit: QPID-8158: [Broker-J] [System Tests]
Stop expanding broker bundle for system tests
Posted by or...@apache.org.
QPID-8158: [Broker-J] [System Tests] Stop expanding broker bundle for system tests
Project: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/repo
Commit: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/commit/1c38d9e0
Tree: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/tree/1c38d9e0
Diff: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/diff/1c38d9e0
Branch: refs/heads/master
Commit: 1c38d9e09f0a4e6a0642ad0348989d0581159e85
Parents: 3a6893e
Author: Alex Rudyy <or...@apache.org>
Authored: Wed Apr 11 17:19:37 2018 +0100
Committer: Alex Rudyy <or...@apache.org>
Committed: Wed Apr 11 17:27:23 2018 +0100
----------------------------------------------------------------------
qpid-systests-parent/pom.xml | 76 ---------------------------------------
1 file changed, 76 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/1c38d9e0/qpid-systests-parent/pom.xml
----------------------------------------------------------------------
diff --git a/qpid-systests-parent/pom.xml b/qpid-systests-parent/pom.xml
index 194421f..2bc41b0 100644
--- a/qpid-systests-parent/pom.xml
+++ b/qpid-systests-parent/pom.xml
@@ -100,82 +100,6 @@
</plugin>
<plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-resources-plugin</artifactId>
- <!--version specified in parent pluginManagement -->
- <executions>
- <!-- copy the systests config files into the ${qpid.home}/etc
- directory where the tests expect them -->
- <execution>
- <id>copy-systests-etc-resources</id>
- <phase>generate-resources</phase>
- <goals>
- <goal>copy-resources</goal>
- </goals>
- <configuration>
- <outputDirectory>${qpid.home}</outputDirectory>
- <resources>
- <resource>
- <directory>${test.systest.resource.directory}</directory>
- <includes>
- <include>etc/</include>
- </includes>
- </resource>
- </resources>
- </configuration>
- </execution>
- <!-- copy the ../test-profiles directory into ${qpid.home}/..
- directory where the tests expect it -->
- <execution>
- <id>copy-test-profile-resources</id>
- <phase>generate-resources</phase>
- <goals>
- <goal>copy-resources</goal>
- </goals>
- <configuration>
- <outputDirectory>${qpid.home}/..</outputDirectory>
- <resources>
- <resource>
- <directory>${test.resource.directory}</directory>
- <includes>
- <include>test-profiles/</include>
- </includes>
- </resource>
- </resources>
- </configuration>
- </execution>
- </executions>
- </plugin>
-
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-dependency-plugin</artifactId>
- <!--version specified in parent pluginManagement -->
- <executions>
- <execution>
- <id>extract-broker-distribution</id>
- <phase>pre-integration-test</phase>
- <goals>
- <goal>unpack</goal>
- </goals>
- <configuration>
- <outputAbsoluteArtifactFilename>false</outputAbsoluteArtifactFilename>
- <outputDirectory>${project.build.directory}</outputDirectory>
- <artifactItems>
- <artifactItem>
- <groupId>org.apache.qpid</groupId>
- <artifactId>apache-qpid-broker-j</artifactId>
- <version>${project.version}</version>
- <classifier>bin</classifier>
- <type>tar.gz</type>
- </artifactItem>
- </artifactItems>
- </configuration>
- </execution>
- </executions>
- </plugin>
-
- <plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<configuration>
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org