diff options
Diffstat (limited to 'java')
453 files changed, 0 insertions, 68373 deletions
diff --git a/java/broker/bin/msTool.sh b/java/broker/bin/msTool.sh deleted file mode 100755 index b291ed9fe3..0000000000 --- a/java/broker/bin/msTool.sh +++ /dev/null @@ -1,60 +0,0 @@ -#!/bin/bash -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - -die() { - if [[ $1 = -usage ]]; then - shift - usage=true - else - usage=false - fi - echo "$@" - $usage && echo - $usage && usage - exit 1 -} - -cygwin=false -if [[ "$(uname -a | fgrep Cygwin)" != "" ]]; then - cygwin=true -fi - -if [ -z "$QPID_TOOLS" ]; then - if [ -z "$QPID_HOME" ]; then - die "QPID_TOOLS must be set" - else - QPID_TOOLS=$QPID_HOME - fi -fi - -if $cygwin; then - QPID_TOOLS=$(cygpath -w $QPID_TOOLS) -fi - -# Set classpath to include Qpid jar with all required jars in manifest -QPID_LIBS=$QPID_TOOLS/lib/qpid-incubating.jar - -# Set other variables used by the qpid-run script before calling -export JAVA=java \ - JAVA_VM=-server \ - JAVA_OPTS=-Dlog4j.configuration=file:$QPID_TOOLS/etc/mstool-log4j.xml \ - QPID_CLASSPATH=$QPID_LIBS - -. qpid-run org.apache.qpid.tools.messagestore.MessageStoreTool "$@" diff --git a/java/broker/bin/qpid-passwd b/java/broker/bin/qpid-passwd deleted file mode 100755 index 9e3ee4ff4a..0000000000 --- a/java/broker/bin/qpid-passwd +++ /dev/null @@ -1,30 +0,0 @@ -#!/bin/bash -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - -# Set classpath to include Qpid jar with all required jars in manifest -QPID_LIBS=$QPID_HOME/lib/qpid-incubating.jar - -# Set other variables used by the qpid-run script before calling -export JAVA=java \ - JAVA_VM=-server \ - JAVA_MEM=-Xmx1024m \ - QPID_CLASSPATH=$QPID_LIBS - -. qpid-run org.apache.qpid.tools.security.Passwd "$@" diff --git a/java/broker/bin/qpid-server b/java/broker/bin/qpid-server deleted file mode 100755 index f1f4d72e64..0000000000 --- a/java/broker/bin/qpid-server +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/bash -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - -# Set classpath to include Qpid jar with all required jars in manifest -QPID_LIBS=$QPID_HOME/lib/qpid-incubating.jar:$QPID_HOME/lib/bdbstore-launch.jar - -# Set other variables used by the qpid-run script before calling -export JAVA=java \ - JAVA_VM=-server \ - JAVA_MEM=-Xmx1024m \ - JAVA_GC="-XX:-UseConcMarkSweepGC -XX:+HeapDumpOnOutOfMemoryError" \ - QPID_CLASSPATH=$QPID_LIBS - -. qpid-run org.apache.qpid.server.Main "$@" diff --git a/java/broker/bin/qpid-server-bdb.bat b/java/broker/bin/qpid-server-bdb.bat deleted file mode 100644 index 8964e577df..0000000000 --- a/java/broker/bin/qpid-server-bdb.bat +++ /dev/null @@ -1,22 +0,0 @@ -@REM
-@REM Licensed to the Apache Software Foundation (ASF) under one
-@REM or more contributor license agreements. See the NOTICE file
-@REM distributed with this work for additional information
-@REM regarding copyright ownership. The ASF licenses this file
-@REM to you under the Apache License, Version 2.0 (the
-@REM "License"); you may not use this file except in compliance
-@REM with the License. You may obtain a copy of the License at
-@REM
-@REM http://www.apache.org/licenses/LICENSE-2.0
-@REM
-@REM Unless required by applicable law or agreed to in writing,
-@REM software distributed under the License is distributed on an
-@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-@REM KIND, either express or implied. See the License for the
-@REM specific language governing permissions and limitations
-@REM under the License.
-@REM
-
-set BDBSTORE_HOME=c:\qpid\trunk\java\bdbstore
-set QPID_MODULE_JARS=%BDBSTORE_HOME%\target\qpid-bdbstore-1.0-incubating-M2-SNAPSHOT.jar;%BDBSTORE_HOME%\lib\bdb\je-3.1.0.jar
-.\qpid-server.bat
\ No newline at end of file diff --git a/java/broker/bin/qpid-server.bat b/java/broker/bin/qpid-server.bat deleted file mode 100644 index a99022cd2d..0000000000 --- a/java/broker/bin/qpid-server.bat +++ /dev/null @@ -1,70 +0,0 @@ -@REM
-@REM Licensed to the Apache Software Foundation (ASF) under one
-@REM or more contributor license agreements. See the NOTICE file
-@REM distributed with this work for additional information
-@REM regarding copyright ownership. The ASF licenses this file
-@REM to you under the Apache License, Version 2.0 (the
-@REM "License"); you may not use this file except in compliance
-@REM with the License. You may obtain a copy of the License at
-@REM
-@REM http://www.apache.org/licenses/LICENSE-2.0
-@REM
-@REM Unless required by applicable law or agreed to in writing,
-@REM software distributed under the License is distributed on an
-@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-@REM KIND, either express or implied. See the License for the
-@REM specific language governing permissions and limitations
-@REM under the License.
-@REM
-
-echo off
-REM Script to run the Qpid Java Broker
-
-rem Guess QPID_HOME if not defined
-set CURRENT_DIR=%cd%
-if not "%QPID_HOME%" == "" goto gotHome
-set QPID_HOME=%CURRENT_DIR%
-echo %QPID_HOME%
-if exist "%QPID_HOME%\bin\qpid-server.bat" goto okHome
-cd ..
-set QPID_HOME=%cd%
-cd %CURRENT_DIR%
-:gotHome
-if exist "%QPID_HOME%\bin\qpid-server.bat" goto okHome
-echo The QPID_HOME environment variable is not defined correctly
-echo This environment variable is needed to run this program
-goto end
-:okHome
-
-if not "%JAVA_HOME%" == "" goto gotJavaHome
-echo The JAVA_HOME environment variable is not defined
-echo This environment variable is needed to run this program
-goto exit
-:gotJavaHome
-if not exist "%JAVA_HOME%\bin\java.exe" goto noJavaHome
-goto okJavaHome
-:noJavaHome
-echo The JAVA_HOME environment variable is not defined correctly
-echo This environment variable is needed to run this program.
-goto exit
-:okJavaHome
-
-rem Slurp the command line arguments. This loop allows for an unlimited number
-rem of agruments (up to the command line limit, anyway).
-set QPID_ARGS=%1
-if ""%1""=="""" goto runCommand
-shift
-:loop
-if ""%1""=="""" goto runCommand
-set QPID_ARGS=%QPID_ARGS% %1
-shift
-goto loop
-
-rem QPID_OPTS intended to hold any -D props for use
-rem user must enclose any value for QPID_OPTS in double quotes
-:runCommand
-set LAUNCH_JAR=%QPID_HOME%\lib\qpid-incubating.jar
-set MODULE_JARS=%QPID_MODULE_JARS%
-"%JAVA_HOME%\bin\java" -server -Xmx1024m %QPID_OPTS% -DQPID_HOME="%QPID_HOME%" -cp "%LAUNCH_JAR%;%MODULE_JARS%" org.apache.qpid.server.Main %QPID_ARGS%
-
-:end
diff --git a/java/broker/bin/qpid.start b/java/broker/bin/qpid.start deleted file mode 100755 index 0793aed84c..0000000000 --- a/java/broker/bin/qpid.start +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/bash -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - -qpid-server -run:debug "$@"
\ No newline at end of file diff --git a/java/broker/bin/qpid.stop b/java/broker/bin/qpid.stop deleted file mode 100755 index 6482fc3293..0000000000 --- a/java/broker/bin/qpid.stop +++ /dev/null @@ -1,137 +0,0 @@ -#!/bin/bash -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - -# qpid.stop Script -# -# Script checks for a given pid running PROGRAM and attempts to quit it -# - -MAX_ATTEMPTS=1 -SLEEP_DELAY=1 -PROGRAM="DQPID" - - -# -# Print what is going to be done -# -printActions() -{ -#ps=`ps o command p $1|grep $PROGRAM` -ps=`ps -o args -p $1|grep $PROGRAM` -echo "Attempting to kill: $ps" -} - -# -# Forcably Quit the specified PID($1) -# -forceQuit() -{ -kill -9 $1 -} - - -# -# Gracefully ask the PID($1) to quit -# -quit() -{ -kill $1 -} - -# -# Grep the ps log for the PID ($1) to ensure that it has quit -# -lookup() -{ -result=`ps -o args -p $1 |grep -v grep |grep $PROGRAM |wc -l` -} - -# -# Sleep and then check then lookup the PID($1) to ensure it has quit -# -check() -{ -echo "Waiting $SLEEP_DELAY second for $1 to exit" -sleep $SLEEP_DELAY -lookup $1 -} - - - -# -# Verify the PID($1) is available -# -verifyPid() -{ -lookup $1 -if [[ $[$result] == 1 ]] ; then - brokerspid=$1 -else - echo "Unable to locate Qpid Process with PID $1" - exit -1 -fi -} - -# -# Main Run -# - -# Check if we are killing all qpid pids or just one. -if [[ $# == 0 ]] ; then - echo "Killing All Qpid Brokers for user: '$USER'" - qpid.stopall - exit $? -else - verifyPid $1 -fi - -printActions $brokerspid - -# Attempt to quit the process MAX_ATTEMPTS Times -attempt=0 -while [[ $[$result] > 0 && $[$attempt] < $[$MAX_ATTEMPTS] ]] ; do - quit $brokerspid - check $brokerspid - attempt=$[$attempt + 1] -done - -# Check that it has quit -if [[ $[$result] == 0 ]] ; then - echo "Process quit" - exit 0 -else - - # Now attempt to force quit the process - attempt=0 - while [[ $[$result] > 0 && $[$attempt] < $[$MAX_ATTEMPTS] ]] ; do - forceQuit $brokerspid - check $brokerspid - attempt=$[$attempt + 1] - done - - - # Output final status - if [[ $[$result] > 0 && $[$attempt] == $[$MAX_ATTEMPTS] ]] ; then - echo "Stopped trying to kill process: $brokerspid" - echo "Attempted to stop $attempt times" - else - echo "Done " - fi -fi diff --git a/java/broker/bin/qpid.stopall b/java/broker/bin/qpid.stopall deleted file mode 100755 index d71f591de8..0000000000 --- a/java/broker/bin/qpid.stopall +++ /dev/null @@ -1,74 +0,0 @@ -#!/bin/bash -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - -# qpid.stopall script -# -# Script attempts to stop all PROGRAMs running under the current user -# Utilises qpid.stop to perform the actual stopping -# - -PROGRAM="DQPID" - -# -# grep ps for instances of $PROGRAM and collect PIDs -# -lookup() -{ -#pids=`ps o pid,command | grep $PROGRAM | grep -v grep | cut -d ' ' -f 1` -pids=`ps -ef |grep $USER | grep $PROGRAM | grep -v grep | awk '{print $2}'` -result=`echo -n $pids | wc -w` -} - - -# -# Show the PS output for given set of pids -# -showPids() -{ -ps -o user,pid,args -p $pids -} - - -# -# Main Run -# - -lookup - -if [[ $[$result] == 0 ]] ; then - echo "No Qpid Brokers found running under user '$USER'" - exit 0 -fi - -for pid in $pids ; do - -qpid.stop $pid - -done - -# Check we have quit all -lookup - -if [[ $[$result] == 0 ]] ; then - echo "All Qpid brokers successfully quit" -else - echo "Some brokers were not quit" - showPids $pids -fi diff --git a/java/broker/bin/run.bat b/java/broker/bin/run.bat deleted file mode 100755 index 5b0aa0f23b..0000000000 --- a/java/broker/bin/run.bat +++ /dev/null @@ -1,31 +0,0 @@ -@REM
-@REM Licensed to the Apache Software Foundation (ASF) under one
-@REM or more contributor license agreements. See the NOTICE file
-@REM distributed with this work for additional information
-@REM regarding copyright ownership. The ASF licenses this file
-@REM to you under the Apache License, Version 2.0 (the
-@REM "License"); you may not use this file except in compliance
-@REM with the License. You may obtain a copy of the License at
-@REM
-@REM http://www.apache.org/licenses/LICENSE-2.0
-@REM
-@REM Unless required by applicable law or agreed to in writing,
-@REM software distributed under the License is distributed on an
-@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-@REM KIND, either express or implied. See the License for the
-@REM specific language governing permissions and limitations
-@REM under the License.
-@REM
-
-@echo off
-set CORE_CLASSES=..\classes;..\testclasses
-
-set COMMONDIR=..\..\common
-
-set COMMONLIB=%COMMONDIR%\lib\slf4j\slf4j-simple.jar;%COMMONDIR%\lib\logging-log4j\log4j-1.2.9.jar;%COMMONDIR%\lib\mina\mina-core-0.9.2.jar
-
-set DIST=..\lib\bdb\je-3.0.12.jar;..\dist\amqpd.jar;..\..\client\dist\amqp-common.jar
-
-set CP=%CORE_CLASSES%;%DIST%;%COMMONLIB%
-
-"%JAVA_HOME%\bin\java" -Xmx512m -Damqj.logging.level=INFO -cp %CP% %*
diff --git a/java/broker/bin/run.sh b/java/broker/bin/run.sh deleted file mode 100755 index 6b62049e94..0000000000 --- a/java/broker/bin/run.sh +++ /dev/null @@ -1,44 +0,0 @@ -#!/bin/bash -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - - -COMMONDIR=../../common - -COMMONLIB=$COMMONLIB:$COMMONDIR/lib/slf4j/slf4j-simple.jar -COMMONLIB=$COMMONLIB:$COMMONDIR/lib/logging-log4j/log4j-1.2.13.jar -COMMONLIB=$COMMONLIB:$COMMONDIR/lib/mina/mina-core-0.9.5-SNAPSHOT.jar -COMMONLIB=$COMMONLIB:$COMMONDIR/lib/mina/mina-filter-ssl-0.9.5-SNAPSHOT.jar -COMMONLIB=$COMMONLIB:$COMMONDIR/lib/commons-collections/commons-collections-3.1.jar -COMMONLIB=$COMMONLIB:$COMMONDIR/lib/commons-cli/commons-cli-1.0.jar -COMMONLIB=$COMMONLIB:$COMMONDIR/lib/commons-configuration/commons-configuration-1.2.jar -COMMONLIB=$COMMONLIB:$COMMONDIR/lib/commons-logging/commons-logging-api.jar -COMMONLIB=$COMMONLIB:$COMMONDIR/lib/commons-logging/commons-logging.jar -COMMONLIB=$COMMONLIB:$COMMONDIR/lib/commons-lang/commons-lang-2.1.jar -COMMONLIB=$COMMONLIB:$COMMONDIR/lib/junit/junit-4.0.jar - -DIST=../lib/bdb/je-3.0.12.jar:../dist/amqpd-tests.jar:../dist/amqpd.jar:../../client/dist/amqp-common.jar - -CP=../intellijclasses:$DIST:$COMMONLIB - -if [ "$(uname -a | fgrep Cygwin)" != "" ]; then - CP=$(cygpath --mixed --path $CP) -fi - -"$JAVA_HOME/bin/java" -Xmx512m -Dprepopulate=10 -Damqj.logging.level=INFO -cp $CP $* diff --git a/java/broker/bin/runAll b/java/broker/bin/runAll deleted file mode 100755 index 4ced1d263b..0000000000 --- a/java/broker/bin/runAll +++ /dev/null @@ -1,37 +0,0 @@ -#!/bin/sh - -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - -doRun() -{ - class=$1 - shift - echo - echo ================================================================================ - echo Running $class - ./run.sh $class "$@" -} - -# parameters are: clients messages iterations -doRun org.apache.qpid.server.queue.SendPerfTest 10 1000 100 - -doRun org.apache.qpid.server.queue.QueuePerfTest - -doRun org.apache.qpid.server.queue.QueueConcurrentPerfTest diff --git a/java/broker/build.xml b/java/broker/build.xml deleted file mode 100644 index f2a6a687d5..0000000000 --- a/java/broker/build.xml +++ /dev/null @@ -1,38 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<project name="AMQ Broker" default="build"> - - <property name="module.depends" value="common"/> - <property name="module.main" value="org.apache.qpid.server.Main"/> - <property name="module.vm.version" value="1.5"/> - - <import file="../module.xml"/> - - <property name="output.dir" value="${module.precompiled}/org/apache/qpid/server/filter/jms/selector"/> - - <target name="precompile"> - <mkdir dir="${output.dir}"/> - <exec executable="javacc"> - <arg line="-OUTPUT_DIRECTORY=${output.dir} src/main/grammar/SelectorParser.jj"/> - </exec> - </target> - -</project> diff --git a/java/broker/distribution/pom.xml b/java/broker/distribution/pom.xml deleted file mode 100644 index 3617296003..0000000000 --- a/java/broker/distribution/pom.xml +++ /dev/null @@ -1,153 +0,0 @@ -<!-- - Licensed to the Apache Software Foundation (ASF) under one - or more contributor license agreements. See the NOTICE file - distributed with this work for additional information - regarding copyright ownership. The ASF licenses this file - to you under the Apache License, Version 2.0 (the - "License"); you may not use this file except in compliance - with the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the - specific language governing permissions and limitations - under the License. - --> -<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> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-distribution</artifactId> - <packaging>jar</packaging> - <version>1.0-incubating-M3-SNAPSHOT</version> - <name>Qpid Broker Distributions</name> - <url>http://cwiki.apache.org/confluence/display/qpid</url> - - <parent> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid</artifactId> - <version>1.0-incubating-M3-SNAPSHOT</version> - </parent> - - <properties> - <topDirectoryLocation>..</topDirectoryLocation> - <java.source.version>1.5</java.source.version> - <qpid.version>${pom.version}</qpid.version> - <qpid.targetDir>${project.build.directory}</qpid.targetDir> - </properties> - - <dependencies> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker</artifactId> - <type>jar</type> - </dependency> - </dependencies> - - <build> - <pluginManagement> - <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-compiler-plugin</artifactId> - <configuration> - <source>${java.source.version}</source> - <target>${java.source.version}</target> - </configuration> - </plugin> - - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-assembly-plugin</artifactId> - <version>${assembly.version}</version> - <configuration> - <descriptors> - <descriptor>src/main/assembly/broker-bin.xml</descriptor> - </descriptors> - <finalName>qpid-${pom.version}</finalName> - <outputDirectory>${qpid.targetDir}</outputDirectory> - <tarLongFileMode>gnu</tarLongFileMode> - </configuration> - </plugin> - - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-jar-plugin</artifactId> - <configuration> - <finalName>qpid-incubating</finalName> - <archive> - <manifest> - <addClasspath>true</addClasspath> - </manifest> - </archive> - </configuration> - </plugin> - - </plugins> - </pluginManagement> - - <plugins> - <plugin> - <artifactId>maven-assembly-plugin</artifactId> - <executions> - <execution> - <id>distribution-package</id> - <phase>package</phase> - <goals> - <goal>single</goal> - </goals> - <configuration> - <descriptors> - <descriptor>src/main/assembly/broker-bin.xml</descriptor> - <descriptor>src/main/assembly/broker-src.xml</descriptor> - </descriptors> - </configuration> - </execution> - </executions> - </plugin> - </plugins> - - </build> - - <profiles> - <profile> - <id>tests</id> - - <dependencies> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker</artifactId> - <type>test-jar</type> - <version>${project.version}</version> - </dependency> - </dependencies> - - <build> - <plugins> - <plugin> - <artifactId>maven-assembly-plugin</artifactId> - <executions> - <execution> - <id>distribution-package</id> - <phase>package</phase> - <goals> - <goal>single</goal> - </goals> - <configuration> - <descriptors> - <descriptor>src/main/assembly/broker-bin-tests.xml</descriptor> - </descriptors> - </configuration> - </execution> - </executions> - </plugin> - </plugins> - - </build> - </profile> - </profiles> -</project> diff --git a/java/broker/distribution/src/main/assembly/broker-bin-tests.xml b/java/broker/distribution/src/main/assembly/broker-bin-tests.xml deleted file mode 100644 index fa017d6232..0000000000 --- a/java/broker/distribution/src/main/assembly/broker-bin-tests.xml +++ /dev/null @@ -1,116 +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. ---> -<assembly> - <id>java-broker-bin-with-tests</id> - <includeBaseDirectory>false</includeBaseDirectory> - <formats> - <format>tar.gz</format> - <format>zip</format> - </formats> - - <fileSets> - <fileSet> - <!-- Apache license files --> - <directory>../../resources</directory> - <outputDirectory>qpid-${qpid.version}</outputDirectory> - <includes> - <include>DISCLAIMER</include> - <include>LICENSE.txt</include> - <include>NOTICE.txt</include> - <include>README.txt</include> - </includes> - </fileSet> - - <fileSet> - <directory>../../release-docs</directory> - <outputDirectory>qpid-${qpid.version}/docs</outputDirectory> - <includes> - <include>RELEASE_NOTES.txt</include> - </includes> - </fileSet> - - <!-- Include easy access to test source--> - <fileSet> - <directory>../src/test</directory> - <outputDirectory>qpid-${qpid.version}/src</outputDirectory> - <includes> - <include>**/*.java</include> - </includes> - </fileSet> - - <!-- Execution Scripts --> - <fileSet> - <directory>../bin/</directory> - <outputDirectory>qpid-${qpid.version}/bin</outputDirectory> - <includes> - <include>**/*</include> - </includes> - <fileMode>777</fileMode> <!-- RWX --> - </fileSet> - - <!-- Configuration --> - <fileSet> - <directory>../etc/</directory> - <outputDirectory>qpid-${qpid.version}/etc</outputDirectory> - <includes> - <include>**/*</include> - </includes> - <fileMode>420</fileMode> - </fileSet> - - <!-- Metadata Jar --> - <fileSet> - <directory>target</directory> - <outputDirectory>qpid-${qpid.version}/lib</outputDirectory> - <includes> - <include>qpid-incubating.jar</include> - </includes> - </fileSet> - </fileSets> - - - <files> - <!-- Common Run scripts --> - <file> - <source>../../common/bin/qpid-run</source> - <outputDirectory>qpid-${qpid.version}/bin</outputDirectory> - <destName>qpid-run</destName> - <fileMode>493</fileMode> - </file> - - <!-- Common Configuration --> - <file> - <source>../../common/etc/qpid-run.conf</source> - <outputDirectory>qpid-${qpid.version}/etc</outputDirectory> - <destName>qpid-run.conf</destName> - <fileMode>420</fileMode> - </file> - </files> - - <dependencySets> - <dependencySet> - <outputDirectory>qpid-${qpid.version}/lib</outputDirectory> - <unpack>false</unpack> - <excludes> - <exclude>org.apache.qpid:qpid-broker-distribution</exclude> - </excludes> - </dependencySet> - </dependencySets> -</assembly> diff --git a/java/broker/distribution/src/main/assembly/broker-bin.xml b/java/broker/distribution/src/main/assembly/broker-bin.xml deleted file mode 100644 index e66190a3f4..0000000000 --- a/java/broker/distribution/src/main/assembly/broker-bin.xml +++ /dev/null @@ -1,183 +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. ---> -<assembly> - <!-- id typically identifies the "type" (src vs bin etc) of the assembly --> - <id>java-broker-bin</id> - <includeBaseDirectory>false</includeBaseDirectory> - <formats> - <format>tar.gz</format> - <format>zip</format> - </formats> - - <fileSets> - <!-- Apache Licensing --> - <fileSet> - <directory>../../resources</directory> - <outputDirectory>qpid-${qpid.version}</outputDirectory> - <includes> - <include>DISCLAIMER</include> - <include>LICENSE.txt</include> - <include>NOTICE.txt</include> - <include>README.txt</include> - </includes> - </fileSet> - <fileSet> - <directory>../..</directory> - <outputDirectory>qpid-${qpid.version}</outputDirectory> - <includes> - <include>*.txt</include> - </includes> - </fileSet> - <fileSet> - <directory>../../src/main/release-docs</directory> - <outputDirectory>qpid-${qpid.version}/docs</outputDirectory> - <includes> - <include>RELEASE_NOTES.txt</include> - </includes> - </fileSet> - - <!-- Metadata Jar --> - <fileSet> - <directory>target</directory> - <outputDirectory>qpid-${qpid.version}/lib</outputDirectory> - <includes> - <include>qpid-incubating.jar</include> - </includes> - </fileSet> - </fileSets> - <files> - <!-- due to a bug in the assembly plugin (MASSEMBLY-153) you have - to use decimal numbers to specify fileMode --> - <file> - <source>../../common/etc/qpid-run.conf</source> - <outputDirectory>qpid-${qpid.version}/etc</outputDirectory> - <destName>qpid-run.conf</destName> - <fileMode>420</fileMode> - </file> - <file> - <source>../etc/config.xml</source> - <outputDirectory>qpid-${qpid.version}/etc</outputDirectory> - <destName>config.xml</destName> - <fileMode>420</fileMode> - </file> - <file> - <source>../etc/jmxremote.access</source> - <outputDirectory>qpid-${qpid.version}/etc</outputDirectory> - <destName>jmxremote.access</destName> - <fileMode>420</fileMode> - </file> - <file> - <source>../etc/log4j.xml</source> - <outputDirectory>qpid-${qpid.version}/etc</outputDirectory> - <destName>log4j.xml</destName> - <fileMode>420</fileMode> - </file> - <file> - <source>../etc/passwd</source> - <outputDirectory>qpid-${qpid.version}/etc</outputDirectory> - <destName>passwd</destName> - <fileMode>420</fileMode> - </file> - <file> - <source>../etc/qpid-server.conf</source> - <outputDirectory>qpid-${qpid.version}/etc</outputDirectory> - <destName>qpid-server.conf</destName> - <fileMode>420</fileMode> - </file> - <file> - <source>../etc/virtualhosts.xml</source> - <outputDirectory>qpid-${qpid.version}/etc</outputDirectory> - <destName>virtualhosts.xml</destName> - <fileMode>420</fileMode> - </file> - <file> - <source>../../common/bin/qpid-run</source> - <outputDirectory>qpid-${qpid.version}/bin</outputDirectory> - <destName>qpid-run</destName> - <fileMode>473</fileMode> - </file> - <file> - <source>../bin/qpid-passwd</source> - <outputDirectory>qpid-${qpid.version}/bin</outputDirectory> - <destName>qpid-passwd</destName> - <fileMode>473</fileMode> - </file> - <file> - <source>../bin/qpid-server</source> - <outputDirectory>qpid-${qpid.version}/bin</outputDirectory> - <destName>qpid-server</destName> - <fileMode>473</fileMode> - </file> - <file> - <source>../bin/qpid-server.bat</source> - <outputDirectory>qpid-${qpid.version}/bin</outputDirectory> - <destName>qpid-server.bat</destName> - <fileMode>473</fileMode> - </file> - <file> - <source>../bin/run.bat</source> - <outputDirectory>qpid-${qpid.version}/bin</outputDirectory> - <destName>run.bat</destName> - <fileMode>473</fileMode> - </file> - <file> - <source>../bin/run.sh</source> - <outputDirectory>qpid-${qpid.version}/bin</outputDirectory> - <destName>run.sh</destName> - <fileMode>473</fileMode> - </file> - <file> - <source>../bin/runAll</source> - <outputDirectory>qpid-${qpid.version}/bin</outputDirectory> - <destName>runAll</destName> - <fileMode>473</fileMode> - </file> - </files> - - <dependencySets> - <dependencySet> - <outputDirectory>qpid-${qpid.version}/lib</outputDirectory> - <unpack>false</unpack> - <!-- This needs to be tidied up QPID-280 --> - <excludes> - <exclude>org.apache.qpid:qpid-broker-distribution</exclude> - <exclude>org.apache.qpid.management:org.apache.qpid.management.ui</exclude> - <exclude>org.eclipse.core:org.eclipse.core.commands</exclude> - <exclude>org.eclipse.core:org.eclipse.core.contenttype</exclude> - <exclude>org.eclipse.core:org.eclipse.core.expressions</exclude> - <exclude>org.eclipse.core:org.eclipse.core.jobs</exclude> - <exclude>org.eclipse.core:org.eclipse.core.runtime</exclude> - <exclude>org.eclipse.core:org.eclipse.core.runtime.compatibility.auth</exclude> - <exclude>org.eclipse.core:org.eclipse.core.runtime.compatibility.registry</exclude> - <exclude>org.eclipse.equinox:org.eclipse.equinox.common</exclude> - <exclude>org.eclipse.equinox:org.eclipse.equinox.preferences</exclude> - <exclude>org.eclipse.equinox:org.eclipse.equinox.registry</exclude> - <exclude>org.eclipse.help:org.eclipse.help</exclude> - <exclude>org.eclipse.jface:org.eclipse.jface</exclude> - <exclude>org.eclipse.osgi:org.eclipse.osgi</exclude> - <exclude>org.eclipse.swt:org.eclipse.swt</exclude> - <exclude>org.eclipse.swt:org.eclipse.swt.win32.win32.x86</exclude> - <exclude>org.eclipse.ui:org.eclipse.ui</exclude> - <exclude>org.eclipse.ui:org.eclipse.ui.forms</exclude> - <exclude>org.eclipse.ui:org.eclipse.ui.workbench</exclude> - </excludes> - </dependencySet> - </dependencySets> -</assembly> diff --git a/java/broker/distribution/src/main/assembly/broker-src.xml b/java/broker/distribution/src/main/assembly/broker-src.xml deleted file mode 100644 index 28a22c3851..0000000000 --- a/java/broker/distribution/src/main/assembly/broker-src.xml +++ /dev/null @@ -1,78 +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. ---> -<assembly> - <!-- id typically identifies the "type" (src vs bin etc) of the assembly --> - <id>java-broker-src</id> - <includeBaseDirectory>false</includeBaseDirectory> - <formats> - <format>tar.gz</format> - <format>zip</format> - </formats> - - <fileSets> - <!-- Apache Licensing --> - <fileSet> - <directory>../../resources</directory> - <outputDirectory>qpid-${qpid.version}-src</outputDirectory> - <includes> - <include>DISCLAIMER</include> - <include>LICENSE.txt</include> - <include>licenses/*.*</include> - <include>NOTICE.txt</include> - <include>README.txt</include> - <include>BUILDING.txt</include> - </includes> - </fileSet> - <!-- Broker source --> - <fileSet> - <directory>..</directory> - <outputDirectory>qpid-${qpid.version}-src</outputDirectory> - <includes> - <include>**/*</include> - </includes> - <!-- Tidy up wrt to QPID-280 --> - <excludes> - <exclude>build.xml</exclude> - <exclude>distribution/build.xml</exclude> - <exclude>benchmark</exclude> - <exclude>benchmark/**/*</exclude> - <exclude>**/target</exclude> - <exclude>**/target/**/*</exclude> - <exclude>**/build</exclude> - <exclude>**/build/**/*</exclude> - <exclude>**/.settings</exclude> - <exclude>**/.classpath</exclude> - <exclude>**/.project</exclude> - <exclude>**/.wtpmodules</exclude> - <exclude>**/surefire*</exclude> - <exclude>**/cobertura.ser</exclude> - <exclude>bin</exclude> - <exclude>bin/*</exclude> - <exclude>lib</exclude> - <exclude>lib/**/*</exclude> - <exclude>**/var/journal</exclude> - <exclude>**/build.out*</exclude> - <exclude>**/eclipse-plugin/bin/**</exclude> - <exclude>**/eclipse-plugin/plugins/**</exclude> - <exclude>**/eclipse-plugin/src/main/resources/**</exclude> - </excludes> - </fileSet> - </fileSets> -</assembly> diff --git a/java/broker/etc/access b/java/broker/etc/access deleted file mode 100644 index 58b7443fa9..0000000000 --- a/java/broker/etc/access +++ /dev/null @@ -1,19 +0,0 @@ -#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-guest:localhost(rw),test(rw)
\ No newline at end of file diff --git a/java/broker/etc/config.xml b/java/broker/etc/config.xml deleted file mode 100644 index 1bb2eb5157..0000000000 --- a/java/broker/etc/config.xml +++ /dev/null @@ -1,186 +0,0 @@ -<?xml version="1.0" encoding="ISO-8859-1"?> -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<broker> - <prefix>${QPID_HOME}</prefix> - <work>${QPID_WORK}</work> - <conf>${prefix}/etc</conf> - <connector> - <!-- Uncomment out this block and edit the keystorePath and keystorePassword - to enable SSL support - <ssl> - <enabled>true</enabled> - <sslOnly>true</sslOnly> - <keystorePath>/path/to/keystore.ks</keystorePath> - <keystorePassword>keystorepass</keystorePassword> - </ssl>--> - <qpidnio>true</qpidnio> - <transport>nio</transport> - <port>5672</port> - <sslport>8672</sslport> - <socketReceiveBuffer>32768</socketReceiveBuffer> - <socketSendBuffer>32768</socketSendBuffer> - </connector> - <management> - <enabled>true</enabled> - <jmxport>8999</jmxport> - <security-enabled>false</security-enabled> - </management> - <advanced> - <filterchain enableExecutorPool="true"/> - <enablePooledAllocator>false</enablePooledAllocator> - <enableDirectBuffers>false</enableDirectBuffers> - <framesize>65535</framesize> - <compressBufferOnQueue>false</compressBufferOnQueue> - </advanced> - - <security> - <principal-databases> - <principal-database> - <name>passwordfile</name> - <class>org.apache.qpid.server.security.auth.database.PlainPasswordVhostFilePrincipalDatabase</class> - <attributes> - <attribute> - <name>passwordFile</name> - <value>${conf}/passwdVhost</value> - </attribute> - </attributes> - </principal-database> - - <!-- Example use of Base64 encoded MD5 hashes for authentication via CRAM-MD5-Hashed - <principal-database> - <name>passwordfile</name> - <class>org.apache.qpid.server.security.auth.database.Base64MD5PasswordFilePrincipalDatabase</class> - <attributes> - <attribute> - <name>passwordFile</name> - <value>${conf}/qpid.passwd</value> - </attribute> - </attributes> - </principal-database--> - </principal-databases> - - <access> - <class>org.apache.qpid.server.security.access.AllowAll</class> - </access> - <jmx> - <access>${conf}/jmxremote.access</access> - <principal-database>passwordfile</principal-database> - </jmx> - </security> - - <virtualhosts> - <virtualhost> - <name>localhost</name> - <localhost> - <store> - <!-- <class>org.apache.qpid.server.store.berkeleydb.BDBMessageStore</class> - <environment-path>${work}/localhost-store</environment-path> --> - - <class>org.apache.qpid.server.store.MemoryMessageStore</class> - </store> - <txn> - <environment-tx-timeout>60</environment-tx-timeout> - <!-- <class>org.apache.qpid.server.store.berkeleydb.txn.TransactionManagerImpl</class> --> - <class>org.apache.qpid.server.txn.MemoryTransactionManager</class> - </txn> - - <security> - <!-- Need protocol changes to allow this--> - <authentication> - <name>passwordfile</name> - <!-- Currently this can't be used as Vhost isn't specified at connection start only connection open --> - <mechanism>PLAIN</mechanism> - </authentication> - <access> - <class>org.apache.qpid.server.security.access.PrincipalDatabaseAccessManager</class> - <attributes> - <attribute> - <name>principalDatabase</name> - <value>passwordfile</value> - </attribute> - <attribute> - <name>defaultAccessManager</name> - <value>DenyAll</value> - </attribute> - </attributes> - </access> - </security> - </localhost> - </virtualhost> - - <virtualhost> - <name>development</name> - <development> - <store> - <class>org.apache.qpid.server.store.MemoryMessageStore</class> - </store> - <txn> - <class>org.apache.qpid.server.txn.MemoryTransactionManager</class> - </txn> - <security> - <name>passwordfile-notusedyet</name> - <mechanism>PLAIN</mechanism> - <mechanism>CRAM-MD5</mechanism> - </security> - </development> - </virtualhost> - - <virtualhost> - <name>test</name> - <test> - <store> - <class>org.apache.qpid.server.store.MemoryMessageStore</class> - </store> - <txn> - <class>org.apache.qpid.server.txn.MemoryTransactionManager</class> - </txn> - <security> - <name>passwordfile-notusedyet</name> - <mechanism>PLAIN</mechanism> - <mechanism>CRAM-MD5</mechanism> - </security> - <access> - <class>org.apache.qpid.server.security.access.PrincipalDatabaseAccessManager</class> - <attributes> - <attribute> - <name>principalDatabase</name> - <value>rubbish-to-cause-default</value> - </attribute> - </attributes> - </access> - - </test> - </virtualhost> - - </virtualhosts> - <heartbeat> - <delay>0</delay> - <timeoutFactor>2.0</timeoutFactor> - </heartbeat> - <queue> - <auto_register>true</auto_register> - </queue> - - <virtualhosts>${conf}/virtualhosts.xml</virtualhosts> -</broker> - - diff --git a/java/broker/etc/debug.log4j.xml b/java/broker/etc/debug.log4j.xml deleted file mode 100644 index e8fd7e119d..0000000000 --- a/java/broker/etc/debug.log4j.xml +++ /dev/null @@ -1,114 +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. - - - --> -<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> -<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> - <appender name="ArchivingFileAppender" class="org.apache.log4j.QpidCompositeRollingAppender"> - <!-- Ensure that logs allways have the dateFormat set--> - <param name="StaticLogFileName" value="false"/> - <param name="File" value="${QPID_WORK}/log/${logprefix}qpid${logsuffix}.log"/> - <param name="Append" value="false"/> - <!-- Change the direction so newer files have bigger numbers --> - <!-- So log.1 is written then log.2 etc This prevents a lot of file renames at log rollover --> - <param name="CountDirection" value="1"/> - <!-- Use default 10MB --> - <!--param name="MaxFileSize" value="100000"/--> - <param name="DatePattern" value="'.'yyyy-MM-dd-HH-mm"/> - <!-- Unlimited number of backups --> - <param name="MaxSizeRollBackups" value="-1"/> - <!-- Compress(gzip) the backup files--> - <param name="CompressBackupFiles" value="true"/> - <!-- Compress the backup files using a second thread --> - <param name="CompressAsync" value="true"/> - <!-- Start at zero numbered files--> - <param name="ZeroBased" value="true"/> - <!-- Backup Location --> - <param name="backupFilesToPath" value="${QPID_WORK}/backup/log"/> - - <layout class="org.apache.log4j.PatternLayout"> - <param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/> - </layout> - </appender> - - <appender name="FileAppender" class="org.apache.log4j.FileAppender"> - <param name="File" value="${QPID_WORK}/log/${logprefix}qpid${logsuffix}.log"/> - <param name="Append" value="false"/> - - <layout class="org.apache.log4j.PatternLayout"> - <param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/> - </layout> - </appender> - - <appender name="AlertFile" class="org.apache.log4j.FileAppender"> - <param name="File" value="${QPID_WORK}/log/alert.log"/> - <param name="Append" value="false"/> - - <layout class="org.apache.log4j.PatternLayout"> - <param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/> - </layout> - </appender> - - <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender"> - - <layout class="org.apache.log4j.PatternLayout"> - <param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/> - </layout> - </appender> - - <category name="Qpid.Broker"> - <priority value="debug"/> - <appender-ref ref="AlertFile"/> - <!--appender-ref ref="STDOUT"/--> - </category> - - - <category name="org.apache.qpid.server.queue.AMQQueueMBean"> - <priority value="info"/> - <appender-ref ref="AlertFile"/> - </category> - - - <!-- Provide warnings to standard output --> - <!--category name="org.apache.qpid"> - <priority value="warn"/> - <appender-ref ref="STDOUT"/> - </category--> - - - <!-- Additional level settings for debugging --> - <!-- Each class in the Broker is a category that can have its logging level adjusted. --> - <!-- This will provide more details if available about that classes processing. --> - <!--category name="org.apache.qpid.server.txn"> - <priority value="debug"/> - </category>--> - - <!--<category name="org.apache.qpid.server.store"> - <priority value="debug"/> - </category--> - - <!-- Log all info events to file --> - <root> - <priority value="info"/> - <appender-ref ref="STDOUT"/> - <appender-ref ref="FileAppender"/> - </root> - -</log4j:configuration> diff --git a/java/broker/etc/jmxremote.access b/java/broker/etc/jmxremote.access deleted file mode 100644 index 1a51a6991b..0000000000 --- a/java/broker/etc/jmxremote.access +++ /dev/null @@ -1,23 +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.
-
-#Generated by JMX Console : Last edited by user:admin
-#Tue Jun 12 16:46:39 BST 2007
-admin=admin
-guest=readonly
-user=readwrite
diff --git a/java/broker/etc/log4j.xml b/java/broker/etc/log4j.xml deleted file mode 100644 index f40da7751e..0000000000 --- a/java/broker/etc/log4j.xml +++ /dev/null @@ -1,121 +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. - - - --> -<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> -<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> - <appender name="ArchivingFileAppender" class="org.apache.log4j.QpidCompositeRollingAppender"> - <!-- Ensure that logs allways have the dateFormat set--> - <param name="StaticLogFileName" value="false"/> - <param name="File" value="${QPID_WORK}/log/${logprefix}qpid${logsuffix}.log"/> - <param name="Append" value="false"/> - <!-- Change the direction so newer files have bigger numbers --> - <!-- So log.1 is written then log.2 etc This prevents a lot of file renames at log rollover --> - <param name="CountDirection" value="1"/> - <!-- Use default 10MB --> - <!--param name="MaxFileSize" value="100000"/--> - <param name="DatePattern" value="'.'yyyy-MM-dd-HH-mm"/> - <!-- Unlimited number of backups --> - <param name="MaxSizeRollBackups" value="-1"/> - <!-- Compress(gzip) the backup files--> - <param name="CompressBackupFiles" value="true"/> - <!-- Compress the backup files using a second thread --> - <param name="CompressAsync" value="true"/> - <!-- Start at zero numbered files--> - <param name="ZeroBased" value="true"/> - <!-- Backup Location --> - <param name="backupFilesToPath" value="${QPID_WORK}/backup/log"/> - - <layout class="org.apache.log4j.PatternLayout"> - <param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/> - </layout> - </appender> - - <appender name="FileAppender" class="org.apache.log4j.FileAppender"> - <param name="File" value="${QPID_WORK}/log/${logprefix}qpid${logsuffix}.log"/> - <param name="Append" value="false"/> - - <layout class="org.apache.log4j.PatternLayout"> - <param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/> - </layout> - </appender> - - <appender name="AlertFile" class="org.apache.log4j.FileAppender"> - <param name="File" value="${QPID_WORK}/log/alert.log"/> - <param name="Append" value="false"/> - - <layout class="org.apache.log4j.PatternLayout"> - <param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/> - </layout> - </appender> - - <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender"> - <layout class="org.apache.log4j.PatternLayout"> - <param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/> - </layout> - </appender> - - <category name="Qpid.Broker"> - <priority value="debug"/> - <appender-ref ref="AlertFile"/> - - </category> - - <category name="org.apache.qpid.server.queue.AMQQueueMBean"> - <priority value="info"/> - <appender-ref ref="AlertFile"/> - </category> - - <!-- Provide warnings to standard output --> - <!--category name="org.apache.qpid"> - <priority value="warn"/> - <appender-ref ref="STDOUT"/> - </category--> - - <category name="org.apache.qpid"> - <priority value="info"/> - <appender-ref ref="STDOUT"/> - <appender-ref ref="FileAppender"/> - </category> - - <!-- Examples of additional logging settings --> - <!-- Used to generate extra debug. See debug.log4j.xml --> - - <!--<category name="org.apache.qpid.server.store"> - <priority value="debug"/> - </category--> - - <!--category name="org.apache.qpid.server.queue"> - <priority value="debug"/> - </category--> - - <!--category name="org.apache.qpid.server.txn"> - <priority value="debug"/> - </category>--> - - <!-- Log all info events to file --> - <root> - <priority value="info"/> - <appender-ref ref="STDOUT"/> - <appender-ref ref="FileAppender"/> - <!--appender-ref ref="ArchivingFileAppender"/--> - </root> - -</log4j:configuration> diff --git a/java/broker/etc/md5passwd b/java/broker/etc/md5passwd deleted file mode 100644 index 6a149919de..0000000000 --- a/java/broker/etc/md5passwd +++ /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.
-#
-guest:CE4DQ6BIb/BVMN9scFyLtA==
-admin:ISMvKXpXpadDiUoOSoAfww==
-user:aBzonUodYLhwSa8s9A10sA==
diff --git a/java/broker/etc/mstool-log4j.xml b/java/broker/etc/mstool-log4j.xml deleted file mode 100644 index 8c46010e2d..0000000000 --- a/java/broker/etc/mstool-log4j.xml +++ /dev/null @@ -1,54 +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. - - - --> -<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> -<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> - - <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender"> - - <layout class="org.apache.log4j.PatternLayout"> - <!--param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/--> - <param name="ConversionPattern" value="%d %-5p [%t] (%F:%L) - %m%n"/> - </layout> - </appender> - - <category name="org.apache.qpid.tools"> - <priority value="info"/> - </category> - - <category name="org.apache.qpid"> - <priority value="error"/> - </category> - - <category name="org.apache.qpid.server.security"> - <priority value="error"/> - </category> - - <category name="org.apache.qpid.server.management"> - <priority value="error"/> - </category> - - - <root> - <priority value="info"/> - <appender-ref ref="STDOUT"/> - </root> -</log4j:configuration> diff --git a/java/broker/etc/passwd b/java/broker/etc/passwd deleted file mode 100644 index 966a16153d..0000000000 --- a/java/broker/etc/passwd +++ /dev/null @@ -1,19 +0,0 @@ -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# -guest:guest diff --git a/java/broker/etc/passwdVhost b/java/broker/etc/passwdVhost deleted file mode 100644 index 48ce8299b6..0000000000 --- a/java/broker/etc/passwdVhost +++ /dev/null @@ -1,19 +0,0 @@ -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# -guest:guest:localhost,test diff --git a/java/broker/etc/persistent_config.xml b/java/broker/etc/persistent_config.xml deleted file mode 100644 index ed0591256b..0000000000 --- a/java/broker/etc/persistent_config.xml +++ /dev/null @@ -1,143 +0,0 @@ -<?xml version="1.0" encoding="ISO-8859-1"?> -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - - This is an example config using the BDBMessageStore available from - the Red Hat Messaging project at etp.108.redhat.com and distributed under GPL. - --> - -<broker> - <prefix>${QPID_HOME}</prefix> - <work>${QPID_WORK}</work> - <conf>${prefix}/etc</conf> - <connector> - <qpidnio>true</qpidnio> - <transport>nio</transport> - <port>5672</port> - <sslport>8672</sslport> - <socketReceiveBuffer>32768</socketReceiveBuffer> - <socketSendBuffer>32768</socketSendBuffer> - </connector> - <management> - <enabled>true</enabled> - <jmxport>8999</jmxport> - </management> - <advanced> - <filterchain enableExecutorPool="true"/> - <enablePooledAllocator>false</enablePooledAllocator> - <enableDirectBuffers>false</enableDirectBuffers> - <framesize>65535</framesize> - <compressBufferOnQueue>false</compressBufferOnQueue> - </advanced> - - <security> - <principal-databases> - <principal-database> - <name>passwordfile</name> - <class>org.apache.qpid.server.security.auth.database.PlainPasswordVhostFilePrincipalDatabase</class> - <attributes> - <attribute> - <name>passwordFile</name> - <value>${conf}/passwdVhost</value> - </attribute> - </attributes> - </principal-database> - </principal-databases> - - <access> - <class>org.apache.qpid.server.security.access.AllowAll</class> - </access> - <jmx> - <access>${conf}/jmxremote.access</access> - <principal-database>passwordfile</principal-database> - </jmx> - </security> - - <virtualhosts> - <virtualhost> - <name>localhost</name> - <localhost> - <store> - <environment-path>${work}/bdbstore/localhost-store</environment-path> - <class>org.apache.qpid.server.store.berkeleydb.messageStore.MessageStoreImpl</class> - </store> - <txn> - <environment-tx-timeout>60</environment-tx-timeout> - <class>org.apache.qpid.server.store.berkeleydb.txn.TransactionManagerImpl</class> - </txn> - <security> - <access> - <class>org.apache.qpid.server.security.access.PrincipalDatabaseAccessManager</class> - <attributes> - <attribute> - <name>principalDatabase</name> - <value>passwordfile</value> - </attribute> - <attribute> - <name>defaultAccessManager</name> - <value>DenyAll</value> - </attribute> - </attributes> - </access> - </security> - </localhost> - </virtualhost> - - <virtualhost> - <name>development</name> - <development> - <store> - <environment-path>${work}/bdbstore/development-store</environment-path> - <class>org.apache.qpid.server.store.berkeleydb.messageStore.MessageStoreImpl</class> - </store> - <txn> - <environment-tx-timeout>60</environment-tx-timeout> - <class>org.apache.qpid.server.store.berkeleydb.txn.TransactionManagerImpl</class> - </txn> - </development> - </virtualhost> - - <virtualhost> - <name>test</name> - <test> - <store> - <environment-path>${work}/bdbstore/test-store</environment-path> - <class>org.apache.qpid.server.store.berkeleydb.messageStore.MessageStoreImpl</class> - </store> - <txn> - <environment-tx-timeout>60</environment-tx-timeout> - <class>org.apache.qpid.server.store.berkeleydb.txn.TransactionManagerImpl</class> - </txn> - </test> - </virtualhost> - - </virtualhosts> - <heartbeat> - <delay>0</delay> - <timeoutFactor>2.0</timeoutFactor> - </heartbeat> - <queue> - <auto_register>true</auto_register> - </queue> - - <virtualhosts>${conf}/virtualhosts.xml</virtualhosts> -</broker> - - diff --git a/java/broker/etc/qpid-server.conf b/java/broker/etc/qpid-server.conf deleted file mode 100644 index c310094817..0000000000 --- a/java/broker/etc/qpid-server.conf +++ /dev/null @@ -1,25 +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. -# - -QPID_LIBS=$QPID_HOME/lib/qpid-incubating.jar:$QPID_HOME/lib/bdbstore-launch.jar - -export JAVA=java \ - JAVA_VM=-server \ - JAVA_MEM=-Xmx1024m \ - CLASSPATH=$QPID_LIBS diff --git a/java/broker/etc/qpid-server.conf.jpp b/java/broker/etc/qpid-server.conf.jpp deleted file mode 100644 index 3ed2431ef3..0000000000 --- a/java/broker/etc/qpid-server.conf.jpp +++ /dev/null @@ -1,49 +0,0 @@ -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - -QPID_LIBS=$(build-classpath backport-util-concurrent \ - commons-beanutils \ - commons-beanutils-core \ - commons-cli \ - commons-codec \ - commons-collections \ - commons-configuration \ - commons-digester \ - commons-lang \ - commons-logging \ - commons-logging-api \ - dom4j \ - geronimo-jms-1.1-api \ - isorelax \ - jaxen \ - log4j \ - mina/core \ - mina/filter-ssl \ - mina/java5 \ - msv-msv \ - qpid-broker \ - qpid-client \ - qpid-common \ - relaxngDatatype \ - slf4j) - -export JAVA=java \ - JAVA_VM=-server \ - JAVA_MEM=-Xmx1024m \ - CLASSPATH=$QPID_LIBS diff --git a/java/broker/etc/qpid.passwd b/java/broker/etc/qpid.passwd deleted file mode 100644 index 79b5e11777..0000000000 --- a/java/broker/etc/qpid.passwd +++ /dev/null @@ -1,22 +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.
-#
-guest:CE4DQ6BIb/BVMN9scFyLtA==
-admin:ISMvKXpXpadDiUoOSoAfww==
-user:CE4DQ6BIb/BVMN9scFyLtA==
-
diff --git a/java/broker/etc/transient_config.xml b/java/broker/etc/transient_config.xml deleted file mode 100644 index ddd5203ccb..0000000000 --- a/java/broker/etc/transient_config.xml +++ /dev/null @@ -1,141 +0,0 @@ -<?xml version="1.0" encoding="ISO-8859-1"?> -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - - This is an example config file that uses the MemoryMessageStore. - As a result it is aimed at brokers sending transient messages. - - --> -<broker> - <prefix>${QPID_HOME}</prefix> - <work>${QPID_WORK}</work> - <conf>${prefix}/etc</conf> - <connector> - <qpidnio>true</qpidnio> - <transport>nio</transport> - <port>5672</port> - <sslport>8672</sslport> - <socketReceiveBuffer>32768</socketReceiveBuffer> - <socketSendBuffer>32768</socketSendBuffer> - </connector> - <management> - <enabled>true</enabled> - <jmxport>8999</jmxport> - </management> - <advanced> - <filterchain enableExecutorPool="true"/> - <enablePooledAllocator>false</enablePooledAllocator> - <enableDirectBuffers>false</enableDirectBuffers> - <framesize>65535</framesize> - <compressBufferOnQueue>false</compressBufferOnQueue> - </advanced> - - <security> - <principal-databases> - <principal-database> - <name>passwordfile</name> - <class>org.apache.qpid.server.security.auth.database.PlainPasswordVhostFilePrincipalDatabase</class> - <attributes> - <attribute> - <name>passwordFile</name> - <value>${conf}/passwdVhost</value> - </attribute> - </attributes> - </principal-database> - </principal-databases> - <access> - <class>org.apache.qpid.server.security.access.AllowAll</class> - </access> - <jmx> - <access>${conf}/jmxremote.access</access> - <principal-database>passwordfile</principal-database> - </jmx> - </security> - - <virtualhosts> - <virtualhost> - <name>localhost</name> - <localhost> - <store> - <class>org.apache.qpid.server.store.berkeleydb.messageStore.MessageStoreImpl</class> - </store> - <txn> - <environment-tx-timeout>60</environment-tx-timeout> - <class>org.apache.qpid.server.store.berkeleydb.txn.TransactionManagerImpl</class> - </txn> - - - <security> - <access> - <class>org.apache.qpid.server.security.access.PrincipalDatabaseAccessManager</class> - <attributes> - <attribute> - <name>principalDatabase</name> - <value>passwordfile</value> - </attribute> - <attribute> - <name>defaultAccessManager</name> - <value>DenyAll</value> - </attribute> - </attributes> - </access> - </security> - </localhost> - </virtualhost> - - <virtualhost> - <name>development</name> - <development> - <store> - <class>org.apache.qpid.server.store.berkeleydb.messageStore.MessageStoreImpl</class> - </store> - <txn> - <environment-tx-timeout>60</environment-tx-timeout> - <class>org.apache.qpid.server.store.berkeleydb.txn.TransactionManagerImpl</class> - </txn> - </development> - </virtualhost> - - <virtualhost> - <name>test</name> - <test> - <store> - <class>org.apache.qpid.server.store.berkeleydb.messageStore.MessageStoreImpl</class> - </store> - <txn> - <environment-tx-timeout>60</environment-tx-timeout> - <class>org.apache.qpid.server.store.berkeleydb.txn.TransactionManagerImpl</class> - </txn> - </test> - </virtualhost> - - </virtualhosts> - <heartbeat> - <delay>0</delay> - <timeoutFactor>2.0</timeoutFactor> - </heartbeat> - <queue> - <auto_register>true</auto_register> - </queue> - - <virtualhosts>${conf}/virtualhosts.xml</virtualhosts> -</broker> - - diff --git a/java/broker/etc/virtualhosts.xml b/java/broker/etc/virtualhosts.xml deleted file mode 100644 index f62ec3f5d7..0000000000 --- a/java/broker/etc/virtualhosts.xml +++ /dev/null @@ -1,123 +0,0 @@ -<?xml version="1.0" encoding="ISO-8859-1"?> -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<virtualhosts> - <default>test</default> - <virtualhost> - <name>localhost</name> - <localhost> - <exchanges> - <exchange> - <type>direct</type> - <name>test.direct</name> - <durable>true</durable> - </exchange> - <exchange> - <type>topic</type> - <name>test.topic</name> - </exchange> - </exchanges> - <queues> - <exchange>amq.direct</exchange> - <maximumQueueDepth>4235264</maximumQueueDepth> <!-- 4Mb --> - <maximumMessageSize>2117632</maximumMessageSize> <!-- 2Mb --> - <maximumMessageAge>600000</maximumMessageAge> <!-- 10 mins --> - - <queue> - <name>queue</name> - </queue> - <queue> - <name>ping</name> - </queue> - <queue> - <name>test-queue</name> - <test-queue> - <exchange>test.direct</exchange> - <durable>true</durable> - </test-queue> - </queue> - <queue> - <name>test-ping</name> - <test-ping> - <exchange>test.direct</exchange> - </test-ping> - </queue> - - </queues> - </localhost> - </virtualhost> - - - <virtualhost> - <name>development</name> - <development> - <queues> - <minimumAlertRepeatGap>30000</minimumAlertRepeatGap> - <maximumMessageCount>5000</maximumMessageCount> - <queue> - <name>queue</name> - <queue> - <exchange>amq.direct</exchange> - <maximumQueueDepth>4235264</maximumQueueDepth> <!-- 4Mb --> - <maximumMessageSize>2117632</maximumMessageSize> <!-- 2Mb --> - <maximumMessageAge>600000</maximumMessageAge> <!-- 10 mins --> - </queue> - </queue> - <queue> - <name>ping</name> - <ping> - <exchange>amq.direct</exchange> - <maximumQueueDepth>4235264</maximumQueueDepth> <!-- 4Mb --> - <maximumMessageSize>2117632</maximumMessageSize> <!-- 2Mb --> - <maximumMessageAge>600000</maximumMessageAge> <!-- 10 mins --> - </ping> - </queue> - </queues> - </development> - </virtualhost> - <virtualhost> - <name>test</name> - <test> - <queues> - <minimumAlertRepeatGap>30000</minimumAlertRepeatGap> - <maximumMessageCount>5000</maximumMessageCount> - <queue> - <name>queue</name> - <queue> - <exchange>amq.direct</exchange> - <maximumQueueDepth>4235264</maximumQueueDepth> <!-- 4Mb --> - <maximumMessageSize>2117632</maximumMessageSize> <!-- 2Mb --> - <maximumMessageAge>600000</maximumMessageAge> <!-- 10 mins --> - </queue> - </queue> - <queue> - <name>ping</name> - <ping> - <exchange>amq.direct</exchange> - <maximumQueueDepth>4235264</maximumQueueDepth> <!-- 4Mb --> - <maximumMessageSize>2117632</maximumMessageSize> <!-- 2Mb --> - <maximumMessageAge>600000</maximumMessageAge> <!-- 10 mins --> - </ping> - </queue> - </queues> - </test> - </virtualhost> -</virtualhosts> diff --git a/java/broker/pom.xml b/java/broker/pom.xml deleted file mode 100644 index ac1d442fdc..0000000000 --- a/java/broker/pom.xml +++ /dev/null @@ -1,241 +0,0 @@ -<!-- - Licensed to the Apache Software Foundation (ASF) under one - or more contributor license agreements. See the NOTICE file - distributed with this work for additional information - regarding copyright ownership. The ASF licenses this file - to you under the Apache License, Version 2.0 (the - "License"); you may not use this file except in compliance - with the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the - specific language governing permissions and limitations - under the License. ---> -<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> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker</artifactId> - <packaging>jar</packaging> - <version>1.0-incubating-M3-SNAPSHOT</version> - <name>Qpid Broker</name> - <url>http://cwiki.apache.org/confluence/display/qpid</url> - - <parent> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid</artifactId> - <version>1.0-incubating-M3-SNAPSHOT</version> - <relativePath>../pom.xml</relativePath> - </parent> - - <properties> - <topDirectoryLocation>..</topDirectoryLocation> - </properties> - - <dependencies> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-common</artifactId> - </dependency> - - <dependency> - <groupId>log4j</groupId> - <artifactId>log4j</artifactId> - </dependency> - - <dependency> - <groupId>org.slf4j</groupId> - <artifactId>slf4j-api</artifactId> - <version>1.4.0</version> - </dependency> - - <dependency> - <groupId>org.slf4j</groupId> - <artifactId>slf4j-log4j12</artifactId> - <version>1.4.0</version> - </dependency> - - <dependency> - <groupId>commons-cli</groupId> - <artifactId>commons-cli</artifactId> - </dependency> - - <dependency> - <groupId>commons-configuration</groupId> - <artifactId>commons-configuration</artifactId> - </dependency> - - <dependency> - <groupId>commons-lang</groupId> - <artifactId>commons-lang</artifactId> - </dependency> - - <!-- Test Dependencies --> - <dependency> - <groupId>junit</groupId> - <artifactId>junit</artifactId> - <scope>test</scope> - </dependency> - - <dependency> - <groupId>org.easymock</groupId> - <artifactId>easymockclassextension</artifactId> - <scope>test</scope> - </dependency> - - </dependencies> - - <build> - - <plugins> - - - <!--plugin> - <artifactId>minijar-maven-plugin</artifactId> - <groupId>org.codehaus.mojo</groupId> - <executions> - <execution> - <phase>package</phase> - <goals> - <goal>minijars</goal> - </goals> - <configuration> - <stripUnusedClasses>true</stripUnusedClasses> - </configuration> - </execution> - </executions> - </plugin--> - - - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-antrun-plugin</artifactId> - </plugin> - - <plugin> - <groupId>org.codehaus.mojo</groupId> - <artifactId>javacc-maven-plugin</artifactId> - <version>2.0</version> - <executions> - <execution> - <phase>generate-sources</phase> - <configuration> - <sourceDirectory>${basedir}/src/main/grammar</sourceDirectory> - <outputDirectory>${basedir}/target/generated-sources</outputDirectory> - <packageName>org.apache.qpid.server.filter.jms.selector</packageName> - </configuration> - <goals> - <goal>javacc</goal> - </goals> - </execution> - </executions> - </plugin> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-surefire-plugin</artifactId> - <configuration> - <systemProperties> - <property> - <name>amqj.noAutoCreateVMBroker</name> - <value>true</value> - </property> - <property> - <name>amqj.logging.level</name> - <value>${amqj.logging.level}</value> - </property> - <property> - <name>log4j.configuration</name> - <value>file:///${basedir}/src/main/java/log4j.properties</value> - </property> - </systemProperties> - </configuration> - </plugin> - - - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-jar-plugin</artifactId> - <executions> - <execution> - <phase>package</phase> - <goals> - <goal>test-jar</goal> - </goals> - </execution> - </executions> - </plugin> - </plugins> - - <testResources> - <testResource> - <targetPath>src/</targetPath> - <filtering>false</filtering> - <directory>src/test/java</directory> - <includes> - <include>**/*.java</include> - </includes> - </testResource> - </testResources> - - <!-- DISABLED - TOBE fixed by ritchiem - should use Jython. --> - <!--pluginManagement> - <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-antrun-plugin</artifactId> - <version>${antrun.version}</version> - <dependencies> - <dependency> - <groupId>ant</groupId> - <artifactId>ant-nodeps</artifactId> - <version>1.6.5</version> - </dependency> - </dependencies> - - <executions> - <execution> - <id>python_test</id> - <phase>test</phase> - <configuration> - <tasks> - - <condition property="broker.dir" - else="${user.dir}${file.separator}broker" - value="${user.dir}"> - <contains string="${user.dir}" substring="broker" /> - </condition> - - <condition property="skip-python-tests" value="true"> - <isset property="skip.python.tests"/> - </condition> - - <property name="command" - value="python run-tests -v -I java_failing_0-8.txt"/> - - <-value="bash -c 'python run-tests -v -I java_failing.txt'"/>-> - - <ant antfile="python-test.xml" inheritRefs="true"> - <target name="run-tests" /> - </ant> - - </tasks> - </configuration> - <goals> - <goal>run</goal> - </goals> - </execution> - </executions> - </plugin> - </plugins> - </pluginManagement--> - - - </build> - -</project> diff --git a/java/broker/python-test.xml b/java/broker/python-test.xml deleted file mode 100755 index a31dae0060..0000000000 --- a/java/broker/python-test.xml +++ /dev/null @@ -1,50 +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. ---> - -<!-- ====================================================================== --> -<!-- Ant build file (http://ant.apache.org/) for Ant 1.6.2 or above. --> -<!-- ====================================================================== --> - -<project basedir="." default="default"> - - <target name="default" > - <echo message="Used via maven to run python tests."/> - </target> - - <property name="pythondir" value="../../python"/> - - <target name="run-tests" unless="skip-python-tests"> - - <echo message="Starting Broker with command"/> - - <java classname="org.apache.qpid.server.RunBrokerWithCommand" - fork="true" - dir="${pythondir}" - failonerror="true" - > - <arg value="${command}"/> - - <classpath refid="maven.test.classpath"/> - <sysproperty key="QPID_HOME" value="${broker.dir}"/> - <sysproperty key="QPID_WORK" value="${broker.dir}${file.separator}target"/> - </java> - - </target> -</project> diff --git a/java/broker/src/main/grammar/SelectorParser.jj b/java/broker/src/main/grammar/SelectorParser.jj deleted file mode 100644 index 61638e5e26..0000000000 --- a/java/broker/src/main/grammar/SelectorParser.jj +++ /dev/null @@ -1,604 +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.
- *
- */
-
- //
- // Original File from r450141 of the Apache ActiveMQ project <http://www.activemq.org/site/home.html>
- //
-
-// ----------------------------------------------------------------------------
-// OPTIONS
-// ----------------------------------------------------------------------------
-options {
- STATIC = false;
- UNICODE_INPUT = true;
-
- // some performance optimizations
- OPTIMIZE_TOKEN_MANAGER = true;
- ERROR_REPORTING = false;
-}
-
-// ----------------------------------------------------------------------------
-// PARSER
-// ----------------------------------------------------------------------------
-
-PARSER_BEGIN(SelectorParser)
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.server.filter.jms.selector;
-
-import java.io.StringReader;
-import java.util.ArrayList;
-
-import org.apache.qpid.AMQInvalidArgumentException;
-import org.apache.qpid.server.filter.ArithmeticExpression;
-import org.apache.qpid.server.filter.BooleanExpression;
-import org.apache.qpid.server.filter.ComparisonExpression;
-import org.apache.qpid.server.filter.ConstantExpression;
-import org.apache.qpid.server.filter.Expression;
-import org.apache.qpid.server.filter.LogicExpression;
-import org.apache.qpid.server.filter.PropertyExpression;
-import org.apache.qpid.server.filter.UnaryExpression;
-
-/**
- * JMS Selector Parser generated by JavaCC
- *
- * Do not edit this .java file directly - it is autogenerated from SelectorParser.jj
- */
-public class SelectorParser {
-
- public SelectorParser() {
- this(new StringReader(""));
- }
-
- public BooleanExpression parse(String sql) throws AMQInvalidArgumentException {
- this.ReInit(new StringReader(sql));
-
- try {
- return this.JmsSelector();
- }
- catch (Throwable e) {
- throw new AMQInvalidArgumentException(sql, e);
- }
-
- }
-
- private BooleanExpression asBooleanExpression(Expression value) throws ParseException {
- if (value instanceof BooleanExpression) {
- return (BooleanExpression) value;
- }
- if (value instanceof PropertyExpression) {
- return UnaryExpression.createBooleanCast( value );
- }
- throw new ParseException("Expression will not result in a boolean value: " + value);
- }
-
-
-}
-
-PARSER_END(SelectorParser)
-
-// ----------------------------------------------------------------------------
-// Tokens
-// ----------------------------------------------------------------------------
-
-/* White Space */
-SPECIAL_TOKEN :
-{
- " " | "\t" | "\n" | "\r" | "\f"
-}
-
-/* Comments */
-SKIP:
-{
- <LINE_COMMENT: "--" (~["\n","\r"])* ("\n"|"\r"|"\r\n") >
-}
-
-SKIP:
-{
- <BLOCK_COMMENT: "/*" (~["*"])* "*" ("*" | (~["*","/"] (~["*"])* "*"))* "/">
-}
-
-/* Reserved Words */
-TOKEN [IGNORE_CASE] :
-{
- < NOT : "NOT">
- | < AND : "AND">
- | < OR : "OR">
- | < BETWEEN : "BETWEEN">
- | < LIKE : "LIKE">
- | < ESCAPE : "ESCAPE">
- | < IN : "IN">
- | < IS : "IS">
- | < TRUE : "TRUE" >
- | < FALSE : "FALSE" >
- | < NULL : "NULL" >
- | < XPATH : "XPATH" >
- | < XQUERY : "XQUERY" >
-}
-
-/* Literals */
-TOKEN [IGNORE_CASE] :
-{
-
- < DECIMAL_LITERAL: ["1"-"9"] (["0"-"9"])* (["l","L"])? >
- | < HEX_LITERAL: "0" ["x","X"] (["0"-"9","a"-"f","A"-"F"])+ >
- | < OCTAL_LITERAL: "0" (["0"-"7"])* >
- | < FLOATING_POINT_LITERAL:
- (["0"-"9"])+ "." (["0"-"9"])* (<EXPONENT>)? // matches: 5.5 or 5. or 5.5E10 or 5.E10
- | "." (["0"-"9"])+ (<EXPONENT>)? // matches: .5 or .5E10
- | (["0"-"9"])+ <EXPONENT> // matches: 5E10
- >
- | < #EXPONENT: "E" (["+","-"])? (["0"-"9"])+ >
- | < STRING_LITERAL: "'" ( ("''") | ~["'"] )* "'" >
-}
-
-TOKEN [IGNORE_CASE] :
-{
- < ID : ["a"-"z", "_", "$"] (["a"-"z","0"-"9","_", "$"])* >
-}
-
-// ----------------------------------------------------------------------------
-// Grammer
-// ----------------------------------------------------------------------------
-BooleanExpression JmsSelector() :
-{
- Expression left=null;
-}
-{
- (
- left = orExpression()
- )
- {
- return asBooleanExpression(left);
- }
-
-}
-
-Expression orExpression() :
-{
- Expression left;
- Expression right;
-}
-{
- (
- left = andExpression()
- (
- <OR> right = andExpression()
- {
- left = LogicExpression.createOR(asBooleanExpression(left), asBooleanExpression(right));
- }
- )*
- )
- {
- return left;
- }
-
-}
-
-
-Expression andExpression() :
-{
- Expression left;
- Expression right;
-}
-{
- (
- left = equalityExpression()
- (
- <AND> right = equalityExpression()
- {
- left = LogicExpression.createAND(asBooleanExpression(left), asBooleanExpression(right));
- }
- )*
- )
- {
- return left;
- }
-}
-
-Expression equalityExpression() :
-{
- Expression left;
- Expression right;
-}
-{
- (
- left = comparisonExpression()
- (
-
- "=" right = comparisonExpression()
- {
- left = ComparisonExpression.createEqual(left, right);
- }
- |
- "<>" right = comparisonExpression()
- {
- left = ComparisonExpression.createNotEqual(left, right);
- }
- |
- LOOKAHEAD(2)
- <IS> <NULL>
- {
- left = ComparisonExpression.createIsNull(left);
- }
- |
- <IS> <NOT> <NULL>
- {
- left = ComparisonExpression.createIsNotNull(left);
- }
- )*
- )
- {
- return left;
- }
-}
-
-Expression comparisonExpression() :
-{
- Expression left;
- Expression right;
- Expression low;
- Expression high;
- String t, u;
- boolean not;
- ArrayList list;
-}
-{
- (
- left = addExpression()
- (
-
- ">" right = addExpression()
- {
- left = ComparisonExpression.createGreaterThan(left, right);
- }
- |
- ">=" right = addExpression()
- {
- left = ComparisonExpression.createGreaterThanEqual(left, right);
- }
- |
- "<" right = addExpression()
- {
- left = ComparisonExpression.createLessThan(left, right);
- }
- |
- "<=" right = addExpression()
- {
- left = ComparisonExpression.createLessThanEqual(left, right);
- }
- |
- {
- u=null;
- }
- <LIKE> t = stringLitteral()
- [ <ESCAPE> u = stringLitteral() ]
- {
- left = ComparisonExpression.createLike(left, t, u);
- }
- |
- LOOKAHEAD(2)
- {
- u=null;
- }
- <NOT> <LIKE> t = stringLitteral() [ <ESCAPE> u = stringLitteral() ]
- {
- left = ComparisonExpression.createNotLike(left, t, u);
- }
- |
- <BETWEEN> low = addExpression() <AND> high = addExpression()
- {
- left = ComparisonExpression.createBetween(left, low, high);
- }
- |
- LOOKAHEAD(2)
- <NOT> <BETWEEN> low = addExpression() <AND> high = addExpression()
- {
- left = ComparisonExpression.createNotBetween(left, low, high);
- }
- |
- <IN>
- "("
- t = stringLitteral()
- {
- list = new ArrayList();
- list.add( t );
- }
- (
- ","
- t = stringLitteral()
- {
- list.add( t );
- }
-
- )*
- ")"
- {
- left = ComparisonExpression.createInFilter(left, list);
- }
- |
- LOOKAHEAD(2)
- <NOT> <IN>
- "("
- t = stringLitteral()
- {
- list = new ArrayList();
- list.add( t );
- }
- (
- ","
- t = stringLitteral()
- {
- list.add( t );
- }
-
- )*
- ")"
- {
- left = ComparisonExpression.createNotInFilter(left, list);
- }
-
- )*
- )
- {
- return left;
- }
-}
-
-Expression addExpression() :
-{
- Expression left;
- Expression right;
-}
-{
- left = multExpr()
- (
- LOOKAHEAD( ("+"|"-") multExpr())
- (
- "+" right = multExpr()
- {
- left = ArithmeticExpression.createPlus(left, right);
- }
- |
- "-" right = multExpr()
- {
- left = ArithmeticExpression.createMinus(left, right);
- }
- )
-
- )*
- {
- return left;
- }
-}
-
-Expression multExpr() :
-{
- Expression left;
- Expression right;
-}
-{
- left = unaryExpr()
- (
- "*" right = unaryExpr()
- {
- left = ArithmeticExpression.createMultiply(left, right);
- }
- |
- "/" right = unaryExpr()
- {
- left = ArithmeticExpression.createDivide(left, right);
- }
- |
- "%" right = unaryExpr()
- {
- left = ArithmeticExpression.createMod(left, right);
- }
-
- )*
- {
- return left;
- }
-}
-
-
-Expression unaryExpr() :
-{
- String s=null;
- Expression left=null;
-}
-{
- (
- LOOKAHEAD( "+" unaryExpr() )
- "+" left=unaryExpr()
- |
- "-" left=unaryExpr()
- {
- left = UnaryExpression.createNegate(left);
- }
- |
- <NOT> left=unaryExpr()
- {
- left = UnaryExpression.createNOT( asBooleanExpression(left) );
- }
- |
- <XPATH> s=stringLitteral()
- {
- left = UnaryExpression.createXPath( s );
- }
- |
- <XQUERY> s=stringLitteral()
- {
- left = UnaryExpression.createXQuery( s );
- }
- |
- left = primaryExpr()
- )
- {
- return left;
- }
-
-}
-
-Expression primaryExpr() :
-{
- Expression left=null;
-}
-{
- (
- left = literal()
- |
- left = variable()
- |
- "(" left = orExpression() ")"
- )
- {
- return left;
- }
-}
-
-
-
-ConstantExpression literal() :
-{
- Token t;
- String s;
- ConstantExpression left=null;
-}
-{
- (
- (
- s = stringLitteral()
- {
- left = new ConstantExpression(s);
- }
- )
- |
- (
- t = <DECIMAL_LITERAL>
- {
- left = ConstantExpression.createFromDecimal(t.image);
- }
- )
- |
- (
- t = <HEX_LITERAL>
- {
- left = ConstantExpression.createFromHex(t.image);
- }
- )
- |
- (
- t = <OCTAL_LITERAL>
- {
- left = ConstantExpression.createFromOctal(t.image);
- }
- )
- |
- (
- t = <FLOATING_POINT_LITERAL>
- {
- left = ConstantExpression.createFloat(t.image);
- }
- )
- |
- (
- <TRUE>
- {
- left = ConstantExpression.TRUE;
- }
- )
- |
- (
- <FALSE>
- {
- left = ConstantExpression.FALSE;
- }
- )
- |
- (
- <NULL>
- {
- left = ConstantExpression.NULL;
- }
- )
- )
- {
- return left;
- }
-}
-
-String stringLitteral() :
-{
- Token t;
- StringBuffer rc = new StringBuffer();
- boolean first=true;
-}
-{
- t = <STRING_LITERAL>
- {
- // Decode the sting value.
- String image = t.image;
- for( int i=1; i < image.length()-1; i++ ) {
- char c = image.charAt(i);
- if( c == '\'' )
- i++;
- rc.append(c);
- }
- return rc.toString();
- }
-}
-
-PropertyExpression variable() :
-{
- Token t;
- PropertyExpression left=null;
-}
-{
- (
- t = <ID>
- {
- left = new PropertyExpression(t.image);
- }
- )
- {
- return left;
- }
-}
diff --git a/java/broker/src/main/java/log4j.properties b/java/broker/src/main/java/log4j.properties deleted file mode 100644 index 87f04f4991..0000000000 --- a/java/broker/src/main/java/log4j.properties +++ /dev/null @@ -1,24 +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. -# -log4j.rootCategory=${amqj.logging.level}, console - -log4j.appender.console=org.apache.log4j.ConsoleAppender -log4j.appender.console.Threshold=info -log4j.appender.console.layout=org.apache.log4j.PatternLayout -log4j.appender.console.layout.ConversionPattern=%t %d %p [%c{4}] %m%n diff --git a/java/broker/src/main/java/org/apache/log4j/QpidCompositeRollingAppender.java b/java/broker/src/main/java/org/apache/log4j/QpidCompositeRollingAppender.java deleted file mode 100644 index 7e0c4defe1..0000000000 --- a/java/broker/src/main/java/org/apache/log4j/QpidCompositeRollingAppender.java +++ /dev/null @@ -1,1007 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.log4j; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.Writer; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.Executor; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.zip.GZIPOutputStream; - -import org.apache.log4j.helpers.CountingQuietWriter; -import org.apache.log4j.helpers.LogLog; -import org.apache.log4j.helpers.OptionConverter; -import org.apache.log4j.spi.LoggingEvent; - -/** - * <p>CompositeRollingAppender combines RollingFileAppender and DailyRollingFileAppender<br> It can function as either - * or do both at the same time (making size based rolling files like RollingFileAppender until a data/time boundary is - * crossed at which time it rolls all of those files as per the DailyRollingFileAppender) based on the setting for - * <code>rollingStyle</code>.<br> <br> To use CompositeRollingAppender to roll log files as they reach a certain size - * (like RollingFileAppender), set rollingStyle=1 (@see config.size)<br> To use CompositeRollingAppender to roll log - * files at certain time intervals (daily for example), set rollingStyle=2 and a datePattern (@see config.time)<br> To - * have CompositeRollingAppender roll log files at a certain size AND rename those according to time intervals, set - * rollingStyle=3 (@see config.composite)<br> - * - * <p>A of few additional optional features have been added:<br> -- Attach date pattern for current log file (@see - * staticLogFileName)<br> -- Backup number increments for newer files (@see countDirection)<br> -- Infinite number of - * backups by file size (@see maxSizeRollBackups)<br> <br> <p>A few notes and warnings: For large or infinite number of - * backups countDirection > 0 is highly recommended, with staticLogFileName = false if time based rolling is also used - * -- this will reduce the number of file renamings to few or none. Changing staticLogFileName or countDirection - * without clearing the directory could have nasty side effects. If Date/Time based rolling is enabled, - * CompositeRollingAppender will attempt to roll existing files in the directory without a date/time tag based on the - * last modified date of the base log files last modification.<br> <br> <p>A maximum number of backups based on - * date/time boundries would be nice but is not yet implemented.<br> - * - * @author Kevin Steppe - * @author Heinz Richter - * @author Eirik Lygre - * @author Ceki Gülcü - * @author Martin Ritchie - */ -public class QpidCompositeRollingAppender extends FileAppender -{ - // The code assumes that the following 'time' constants are in a increasing - // sequence. - static final int TOP_OF_TROUBLE = -1; - static final int TOP_OF_MINUTE = 0; - static final int TOP_OF_HOUR = 1; - static final int HALF_DAY = 2; - static final int TOP_OF_DAY = 3; - static final int TOP_OF_WEEK = 4; - static final int TOP_OF_MONTH = 5; - - /** Style of rolling to use */ - static final int BY_SIZE = 1; - static final int BY_DATE = 2; - static final int BY_COMPOSITE = 3; - - // Not currently used - static final String S_BY_SIZE = "Size"; - static final String S_BY_DATE = "Date"; - static final String S_BY_COMPOSITE = "Composite"; - - /** The date pattern. By default, the pattern is set to "'.'yyyy-MM-dd" meaning daily rollover. */ - private String datePattern = "'.'yyyy-MM-dd"; - - /** - * The actual formatted filename that is currently being written to or will be the file transferred to on roll over - * (based on staticLogFileName). - */ - private String scheduledFilename = null; - - /** The timestamp when we shall next recompute the filename. */ - private long nextCheck = System.currentTimeMillis() - 1; - - /** Holds date of last roll over */ - Date now = new Date(); - - SimpleDateFormat sdf; - - /** Helper class to determine next rollover time */ - RollingCalendar rc = new RollingCalendar(); - - /** Current period for roll overs */ - int checkPeriod = TOP_OF_TROUBLE; - - /** The default maximum file size is 10MB. */ - protected long maxFileSize = 10 * 1024 * 1024; - - /** There is zero backup files by default. */ - protected int maxSizeRollBackups = 0; - /** How many sized based backups have been made so far */ - protected int curSizeRollBackups = 0; - - /** not yet implemented */ - protected int maxTimeRollBackups = -1; - protected int curTimeRollBackups = 0; - - /** - * By default newer files have lower numbers. (countDirection < 0) ie. log.1 is most recent, log.5 is the 5th - * backup, etc... countDirection > 0 does the opposite ie. log.1 is the first backup made, log.5 is the 5th backup - * made, etc. For infinite backups use countDirection > 0 to reduce rollOver costs. - */ - protected int countDirection = -1; - - /** Style of rolling to Use. BY_SIZE (1), BY_DATE(2), BY COMPOSITE(3) */ - protected int rollingStyle = BY_COMPOSITE; - protected boolean rollDate = true; - protected boolean rollSize = true; - - /** - * By default file.log is always the current file. Optionally file.log.yyyy-mm-dd for current formated datePattern - * can by the currently logging file (or file.log.curSizeRollBackup or even file.log.yyyy-mm-dd.curSizeRollBackup) - * This will make time based roll overs with a large number of backups much faster -- it won't have to rename all - * the backups! - */ - protected boolean staticLogFileName = true; - - /** FileName provided in configuration. Used for rolling properly */ - protected String baseFileName; - - /** Do we want to .gz our backup files. */ - protected boolean compress = false; - - /** Do we want to use a second thread when compressing our backup files. */ - protected boolean compressAsync = false; - - /** Do we want to start numbering files at zero. */ - protected boolean zeroBased = false; - - /** Path provided in configuration. Used for moving backup files to */ - protected String backupFilesToPath = null; - private final ConcurrentLinkedQueue<CompressJob> _compress = new ConcurrentLinkedQueue<CompressJob>(); - private AtomicBoolean _compressing = new AtomicBoolean(false); - - /** The default constructor does nothing. */ - public QpidCompositeRollingAppender() - { } - - /** - * Instantiate a <code>CompositeRollingAppender</code> and open the file designated by <code>filename</code>. The - * opened filename will become the ouput destination for this appender. - */ - public QpidCompositeRollingAppender(Layout layout, String filename, String datePattern) throws IOException - { - this(layout, filename, datePattern, true); - } - - /** - * Instantiate a CompositeRollingAppender and open the file designated by <code>filename</code>. The opened filename - * will become the ouput destination for this appender. - * - * <p>If the <code>append</code> parameter is true, the file will be appended to. Otherwise, the file desginated by - * <code>filename</code> will be truncated before being opened. - */ - public QpidCompositeRollingAppender(Layout layout, String filename, boolean append) throws IOException - { - super(layout, filename, append); - } - - /** - * Instantiate a CompositeRollingAppender and open the file designated by <code>filename</code>. The opened filename - * will become the ouput destination for this appender. - */ - public QpidCompositeRollingAppender(Layout layout, String filename, String datePattern, boolean append) - throws IOException - { - super(layout, filename, append); - this.datePattern = datePattern; - activateOptions(); - } - - /** - * Instantiate a CompositeRollingAppender and open the file designated by <code>filename</code>. The opened filename - * will become the output destination for this appender. - * - * <p>The file will be appended to. DatePattern is default. - */ - public QpidCompositeRollingAppender(Layout layout, String filename) throws IOException - { - super(layout, filename); - } - - /** - * The <b>DatePattern</b> takes a string in the same format as expected by {@link java.text.SimpleDateFormat}. This - * options determines the rollover schedule. - */ - public void setDatePattern(String pattern) - { - datePattern = pattern; - } - - /** Returns the value of the <b>DatePattern</b> option. */ - public String getDatePattern() - { - return datePattern; - } - - /** Returns the value of the <b>maxSizeRollBackups</b> option. */ - public int getMaxSizeRollBackups() - { - return maxSizeRollBackups; - } - - /** - * Get the maximum size that the output file is allowed to reach before being rolled over to backup files. - * - * @since 1.1 - */ - public long getMaximumFileSize() - { - return maxFileSize; - } - - /** - * <p>Set the maximum number of backup files to keep around based on file size. - * - * <p>The <b>MaxSizeRollBackups</b> option determines how many backup files are kept before the oldest is erased. - * This option takes an integer value. If set to zero, then there will be no backup files and the log file will be - * truncated when it reaches <code>MaxFileSize</code>. If a negative number is supplied then no deletions will be - * made. Note that this could result in very slow performance as a large number of files are rolled over unless - * {@link #setCountDirection} up is used. - * - * <p>The maximum applys to -each- time based group of files and -not- the total. Using a daily roll the maximum - * total files would be (#days run) * (maxSizeRollBackups) - */ - public void setMaxSizeRollBackups(int maxBackups) - { - maxSizeRollBackups = maxBackups; - } - - /** - * Set the maximum size that the output file is allowed to reach before being rolled over to backup files. - * - * <p>This method is equivalent to {@link #setMaxFileSize} except that it is required for differentiating the setter - * taking a <code>long</code> argument from the setter taking a <code>String</code> argument by the JavaBeans {@link - * java.beans.Introspector Introspector}. - * - * @see #setMaxFileSize(String) - */ - public void setMaxFileSize(long maxFileSize) - { - this.maxFileSize = maxFileSize; - } - - /** - * Set the maximum size that the output file is allowed to reach before being rolled over to backup files. - * - * <p>This method is equivalent to {@link #setMaxFileSize} except that it is required for differentiating the setter - * taking a <code>long</code> argument from the setter taking a <code>String</code> argument by the JavaBeans {@link - * java.beans.Introspector Introspector}. - * - * @see #setMaxFileSize(String) - */ - public void setMaximumFileSize(long maxFileSize) - { - this.maxFileSize = maxFileSize; - } - - /** - * Set the maximum size that the output file is allowed to reach before being rolled over to backup files. - * - * <p>In configuration files, the <b>MaxFileSize</b> option takes an long integer in the range 0 - 2^63. You can - * specify the value with the suffixes "KB", "MB" or "GB" so that the integer is interpreted being expressed - * respectively in kilobytes, megabytes or gigabytes. For example, the value "10KB" will be interpreted as 10240. - */ - public void setMaxFileSize(String value) - { - maxFileSize = OptionConverter.toFileSize(value, maxFileSize + 1); - } - - protected void setQWForFiles(Writer writer) - { - qw = new CountingQuietWriter(writer, errorHandler); - } - - // Taken verbatum from DailyRollingFileAppender - int computeCheckPeriod() - { - RollingCalendar c = new RollingCalendar(); - // set sate to 1970-01-01 00:00:00 GMT - Date epoch = new Date(0); - if (datePattern != null) - { - for (int i = TOP_OF_MINUTE; i <= TOP_OF_MONTH; i++) - { - String r0 = sdf.format(epoch); - c.setType(i); - Date next = new Date(c.getNextCheckMillis(epoch)); - String r1 = sdf.format(next); - // LogLog.debug("Type = "+i+", r0 = "+r0+", r1 = "+r1); - if ((r0 != null) && (r1 != null) && !r0.equals(r1)) - { - return i; - } - } - } - - return TOP_OF_TROUBLE; // Deliberately head for trouble... - } - - // Now for the new stuff - /** - * Handles append time behavior for CompositeRollingAppender. This checks if a roll over either by date (checked - * first) or time (checked second) is need and then appends to the file last. - */ - protected void subAppend(LoggingEvent event) - { - - if (rollDate) - { - long n = System.currentTimeMillis(); - if (n >= nextCheck) - { - now.setTime(n); - nextCheck = rc.getNextCheckMillis(now); - - rollOverTime(); - } - } - - if (rollSize) - { - if ((fileName != null) && (((CountingQuietWriter) qw).getCount() >= maxFileSize)) - { - rollOverSize(); - } - } - - super.subAppend(event); - } - - public void setFile(String file) - { - baseFileName = file.trim(); - fileName = file.trim(); - } - - /** - * Creates and opens the file for logging. If <code>staticLogFileName</code> is false then the fully qualified name - * is determined and used. - */ - public synchronized void setFile(String fileName, boolean append) throws IOException - { - if (!staticLogFileName) - { - scheduledFilename = fileName = fileName.trim() + sdf.format(now); - if (countDirection > 0) - { - scheduledFilename = fileName = fileName + '.' + (++curSizeRollBackups); - } - } - - super.setFile(fileName, append, bufferedIO, bufferSize); - - if (append) - { - File f = new File(fileName); - ((CountingQuietWriter) qw).setCount(f.length()); - } - } - - public int getCountDirection() - { - return countDirection; - } - - public void setCountDirection(int direction) - { - countDirection = direction; - } - - public int getRollingStyle() - { - return rollingStyle; - } - - public void setRollingStyle(int style) - { - rollingStyle = style; - switch (rollingStyle) - { - - case BY_SIZE: - rollDate = false; - rollSize = true; - break; - - case BY_DATE: - rollDate = true; - rollSize = false; - break; - - case BY_COMPOSITE: - rollDate = true; - rollSize = true; - break; - - default: - errorHandler.error("Invalid rolling Style, use 1 (by size only), 2 (by date only) or 3 (both)"); - } - } - - /* - public void setRollingStyle(String style) { - if (style == S_BY_SIZE) { - rollingStyle = BY_SIZE; - } - else if (style == S_BY_DATE) { - rollingStyle = BY_DATE; - } - else if (style == S_BY_COMPOSITE) { - rollingStyle = BY_COMPOSITE; - } - } - */ - public boolean getStaticLogFileName() - { - return staticLogFileName; - } - - public void setStaticLogFileName(boolean s) - { - staticLogFileName = s; - } - - public void setStaticLogFileName(String value) - { - setStaticLogFileName(OptionConverter.toBoolean(value, true)); - } - - public boolean getCompressBackupFiles() - { - return compress; - } - - public void setCompressBackupFiles(boolean c) - { - compress = c; - } - - public boolean getCompressAsync() - { - return compressAsync; - } - - public void setCompressAsync(boolean c) - { - compressAsync = c; - if (compressAsync) - { - executor = Executors.newFixedThreadPool(1); - - compressor = new Compressor(); - } - } - - public boolean getZeroBased() - { - return zeroBased; - } - - public void setZeroBased(boolean z) - { - zeroBased = z; - } - - public String getBackupFilesToPath() - { - return backupFilesToPath; - } - - public void setbackupFilesToPath(String path) - { - File td = new File(path); - if (!td.exists()) - { - td.mkdirs(); - } - - backupFilesToPath = path; - } - - /** - * Initializes based on exisiting conditions at time of <code> activateOptions</code>. The following is done:<br> - * <br> A) determine curSizeRollBackups<br> B) determine curTimeRollBackups (not implemented)<br> C) initiates a - * roll over if needed for crossing a date boundary since the last run. - */ - protected void existingInit() - { - - if (zeroBased) - { - curSizeRollBackups = -1; - } - - curTimeRollBackups = 0; - - // part A starts here - String filter; - if (staticLogFileName || !rollDate) - { - filter = baseFileName + ".*"; - } - else - { - filter = scheduledFilename + ".*"; - } - - File f = new File(baseFileName); - f = f.getParentFile(); - if (f == null) - { - f = new File("."); - } - - LogLog.debug("Searching for existing files in: " + f); - String[] files = f.list(); - - if (files != null) - { - for (int i = 0; i < files.length; i++) - { - if (!files[i].startsWith(baseFileName)) - { - continue; - } - - int index = files[i].lastIndexOf("."); - - if (staticLogFileName) - { - int endLength = files[i].length() - index; - if ((baseFileName.length() + endLength) != files[i].length()) - { - // file is probably scheduledFilename + .x so I don't care - continue; - } - } - - try - { - int backup = Integer.parseInt(files[i].substring(index + 1, files[i].length())); - LogLog.debug("From file: " + files[i] + " -> " + backup); - if (backup > curSizeRollBackups) - { - curSizeRollBackups = backup; - } - } - catch (Exception e) - { - // this happens when file.log -> file.log.yyyy-mm-dd which is normal - // when staticLogFileName == false - LogLog.debug("Encountered a backup file not ending in .x " + files[i]); - } - } - } - - LogLog.debug("curSizeRollBackups starts at: " + curSizeRollBackups); - // part A ends here - - // part B not yet implemented - - // part C - if (staticLogFileName && rollDate) - { - File old = new File(baseFileName); - if (old.exists()) - { - Date last = new Date(old.lastModified()); - if (!(sdf.format(last).equals(sdf.format(now)))) - { - scheduledFilename = baseFileName + sdf.format(last); - LogLog.debug("Initial roll over to: " + scheduledFilename); - rollOverTime(); - } - } - } - - LogLog.debug("curSizeRollBackups after rollOver at: " + curSizeRollBackups); - // part C ends here - - } - - /** - * Sets initial conditions including date/time roll over information, first check, scheduledFilename, and calls - * <code>existingInit</code> to initialize the current # of backups. - */ - public void activateOptions() - { - - // REMOVE removed rollDate from boolean to enable Alex's change - if (datePattern != null) - { - now.setTime(System.currentTimeMillis()); - sdf = new SimpleDateFormat(datePattern); - int type = computeCheckPeriod(); - // printPeriodicity(type); - rc.setType(type); - // next line added as this removes the name check in rollOver - nextCheck = rc.getNextCheckMillis(now); - } - else - { - if (rollDate) - { - LogLog.error("Either DatePattern or rollingStyle options are not set for [" + name + "]."); - } - } - - existingInit(); - - if (rollDate && (fileName != null) && (scheduledFilename == null)) - { - scheduledFilename = fileName + sdf.format(now); - } - - try - { - this.setFile(fileName, true); - } - catch (IOException e) - { - errorHandler.error("Cannot set file name:" + fileName); - } - - super.activateOptions(); - } - - /** - * Rollover the file(s) to date/time tagged file(s). Opens the new file (through setFile) and resets - * curSizeRollBackups. - */ - protected void rollOverTime() - { - - curTimeRollBackups++; - - this.closeFile(); // keep windows happy. - - // delete the old stuff here - - if (staticLogFileName) - { - /* Compute filename, but only if datePattern is specified */ - if (datePattern == null) - { - errorHandler.error("Missing DatePattern option in rollOver()."); - - return; - } - - // is the new file name equivalent to the 'current' one - // something has gone wrong if we hit this -- we should only - // roll over if the new file will be different from the old - String dateFormat = sdf.format(now); - if (scheduledFilename.equals(fileName + dateFormat)) - { - errorHandler.error("Compare " + scheduledFilename + " : " + fileName + dateFormat); - - return; - } - - // close current file, and rename it to datedFilename - this.closeFile(); - - // we may have to roll over a large number of backups here - String from, to; - for (int i = 1; i <= curSizeRollBackups; i++) - { - from = fileName + '.' + i; - to = scheduledFilename + '.' + i; - rollFile(from, to, false); - } - - rollFile(fileName, scheduledFilename, compress); - } - else - { - if (compress) - { - compress(fileName); - } - } - - try - { - // This will also close the file. This is OK since multiple - // close operations are safe. - curSizeRollBackups = 0; // We're cleared out the old date and are ready for the new - - // new scheduled name - scheduledFilename = fileName + sdf.format(now); - this.setFile(baseFileName, false); - } - catch (IOException e) - { - errorHandler.error("setFile(" + fileName + ", false) call failed."); - } - - } - - /** - * Renames file <code>from</code> to file <code>to</code>. It also checks for existence of target file and deletes - * if it does. - */ - protected void rollFile(String from, String to, boolean compress) - { - if (from.equals(to)) - { - if (compress) - { - LogLog.debug("Attempting to compress file with same output name."); - } - - return; - } - - File target = new File(to); - if (target.exists()) - { - LogLog.debug("deleting existing target file: " + target); - target.delete(); - } - - File file = new File(from); - if (compress) - { - compress(file, target); - } - else - { - if (!file.getPath().equals(target.getPath())) - { - file.renameTo(target); - } - } - - LogLog.debug(from + " -> " + to); - } - - protected void compress(String file) - { - File f = new File(file); - compress(f, f); - } - - private void compress(File from, File target) - { - if (compressAsync) - { - synchronized (_compress) - { - _compress.offer(new CompressJob(from, target)); - } - - startCompression(); - } - else - { - doCompress(from, target); - } - } - - private void startCompression() - { - if (_compressing.compareAndSet(false, true)) - { - executor.execute(compressor); - } - } - - /** Delete's the specified file if it exists */ - protected static void deleteFile(String fileName) - { - File file = new File(fileName); - if (file.exists()) - { - file.delete(); - } - } - - /** - * Implements roll overs base on file size. - * - * <p>If the maximum number of size based backups is reached (<code>curSizeRollBackups == maxSizeRollBackups</code) - * then the oldest file is deleted -- it's index determined by the sign of countDirection.<br> If - * <code>countDirection</code> < 0, then files {<code>File.1</code>, ..., <code>File.curSizeRollBackups -1</code>} - * are renamed to {<code>File.2</code>, ..., <code>File.curSizeRollBackups</code>}. Moreover, <code>File</code> is - * renamed <code>File.1</code> and closed.<br> - * - * A new file is created to receive further log output. - * - * <p>If <code>maxSizeRollBackups</code> is equal to zero, then the <code>File</code> is truncated with no backup - * files created. - * - * <p>If <code>maxSizeRollBackups</code> < 0, then <code>File</code> is renamed if needed and no files are deleted. - */ - - // synchronization not necessary since doAppend is alreasy synched - protected void rollOverSize() - { - File file; - - this.closeFile(); // keep windows happy. - - LogLog.debug("rolling over count=" + ((CountingQuietWriter) qw).getCount()); - LogLog.debug("maxSizeRollBackups = " + maxSizeRollBackups); - LogLog.debug("curSizeRollBackups = " + curSizeRollBackups); - LogLog.debug("countDirection = " + countDirection); - - // If maxBackups <= 0, then there is no file renaming to be done. - if (maxSizeRollBackups != 0) - { - - if (countDirection < 0) - { - // Delete the oldest file, to keep Windows happy. - if (curSizeRollBackups == maxSizeRollBackups) - { - deleteFile(fileName + '.' + maxSizeRollBackups); - curSizeRollBackups--; - } - - // Map {(maxBackupIndex - 1), ..., 2, 1} to {maxBackupIndex, ..., 3, 2} - for (int i = curSizeRollBackups; i >= 1; i--) - { - rollFile((fileName + "." + i), (fileName + '.' + (i + 1)), false); - } - - curSizeRollBackups++; - // Rename fileName to fileName.1 - rollFile(fileName, fileName + ".1", compress); - - } // REMOVE This code branching for Alexander Cerna's request - else if (countDirection == 0) - { - // rollFile based on date pattern - curSizeRollBackups++; - now.setTime(System.currentTimeMillis()); - scheduledFilename = fileName + sdf.format(now); - rollFile(fileName, scheduledFilename, compress); - } - else - { // countDirection > 0 - if ((curSizeRollBackups >= maxSizeRollBackups) && (maxSizeRollBackups > 0)) - { - // delete the first and keep counting up. - int oldestFileIndex = curSizeRollBackups - maxSizeRollBackups + 1; - deleteFile(fileName + '.' + oldestFileIndex); - } - - if (staticLogFileName) - { - curSizeRollBackups++; - rollFile(fileName, fileName + '.' + curSizeRollBackups, compress); - } - else - { - if (compress) - { - compress(fileName); - } - } - } - } - - try - { - // This will also close the file. This is OK since multiple - // close operations are safe. - this.setFile(baseFileName, false); - } - catch (IOException e) - { - LogLog.error("setFile(" + fileName + ", false) call failed.", e); - } - } - - protected synchronized void doCompress(File from, File to) - { - String toFile; - if (backupFilesToPath == null) - { - toFile = to.getPath() + ".gz"; - } - else - { - toFile = backupFilesToPath + System.getProperty("file.separator") + to.getName() + ".gz"; - } - - File target = new File(toFile); - if (target.exists()) - { - LogLog.debug("deleting existing target file: " + target); - target.delete(); - } - - try - { - // Create the GZIP output stream - GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(target)); - - // Open the input file - FileInputStream in = new FileInputStream(from); - - // Transfer bytes from the input file to the GZIP output stream - byte[] buf = new byte[1024]; - int len; - while ((len = in.read(buf)) > 0) - { - out.write(buf, 0, len); - } - - in.close(); - - // Complete the GZIP file - out.finish(); - out.close(); - // Remove old file. - from.delete(); - } - catch (IOException e) - { - if (target.exists()) - { - target.delete(); - } - - rollFile(from.getPath(), to.getPath(), false); - } - } - - private class CompressJob - { - File _from, _to; - - CompressJob(File from, File to) - { - _from = from; - _to = to; - } - - File getFrom() - { - return _from; - } - - File getTo() - { - return _to; - } - } - - Compressor compressor = null; - - Executor executor; - - private class Compressor implements Runnable - { - public void run() - { - boolean running = true; - while (running) - { - CompressJob job = _compress.poll(); - - doCompress(job.getFrom(), job.getTo()); - - synchronized (_compress) - { - if (_compress.isEmpty()) - { - running = false; - _compressing.set(false); - } - } - } - - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/configuration/Configuration.java b/java/broker/src/main/java/org/apache/qpid/configuration/Configuration.java deleted file mode 100644 index 40ff590a0a..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/configuration/Configuration.java +++ /dev/null @@ -1,188 +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.configuration; - -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.Option; -import org.apache.commons.cli.Options; -import org.apache.commons.cli.ParseException; -import org.apache.commons.cli.PosixParser; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; - -public class Configuration -{ - public static final String QPID_HOME = "QPID_HOME"; - - final String QPIDHOME = System.getProperty(QPID_HOME); - - private static Logger _devlog = LoggerFactory.getLogger(Configuration.class); - - public static final String DEFAULT_LOG_CONFIG_FILENAME = "log4j.xml"; - public static final String DEFAULT_CONFIG_FILE = "etc/config.xml"; - - protected final Options _options = new Options(); - protected CommandLine _commandLine; - protected File _configFile; - - - public Configuration() - { - - } - - public void processCommandline(String[] args) throws InitException - { - try - { - _commandLine = new PosixParser().parse(_options, args); - } - catch (ParseException e) - { - throw new InitException("Unable to parse commmandline", e); - } - - final File defaultConfigFile = new File(QPIDHOME, DEFAULT_CONFIG_FILE); - setConfig(new File(_commandLine.getOptionValue("c", defaultConfigFile.getPath()))); - } - - public void setConfig(File file) - { - _configFile = file; - } - - /** - * @param option The option to set. - */ - public void setOption(Option option) - { - _options.addOption(option); - } - - /** - * getOptionValue from the configuration - * @param option variable argument, first string is option to get, second if present is the default value. - * @return the String for the given option or null if not present (if default value not specified) - */ - public String getOptionValue(String... option) - { - if (option.length == 1) - { - return _commandLine.getOptionValue(option[0]); - } - else if (option.length == 2) - { - return _commandLine.getOptionValue(option[0], option[1]); - } - return null; - } - - public void loadConfig(File file) throws InitException - { - setConfig(file); - loadConfig(); - } - - private void loadConfig() throws InitException - { - if (!_configFile.exists()) - { - String error = "File " + _configFile + " could not be found. Check the file exists and is readable."; - - if (QPIDHOME == null) - { - error = error + "\nNote: " + QPID_HOME + " is not set."; - } - - throw new InitException(error, null); - } - else - { - _devlog.debug("Using configuration file " + _configFile.getAbsolutePath()); - } - -// String logConfig = _commandLine.getOptionValue("l"); -// String logWatchConfig = _commandLine.getOptionValue("w", "0"); -// if (logConfig != null) -// { -// File logConfigFile = new File(logConfig); -// configureLogging(logConfigFile, logWatchConfig); -// } -// else -// { -// File configFileDirectory = _configFile.getParentFile(); -// File logConfigFile = new File(configFileDirectory, DEFAULT_LOG_CONFIG_FILENAME); -// configureLogging(logConfigFile, logWatchConfig); -// } - } - - -// private void configureLogging(File logConfigFile, String logWatchConfig) -// { -// int logWatchTime = 0; -// try -// { -// logWatchTime = Integer.parseInt(logWatchConfig); -// } -// catch (NumberFormatException e) -// { -// _devlog.error("Log watch configuration value of " + logWatchConfig + " is invalid. Must be " -// + "a non-negative integer. Using default of zero (no watching configured"); -// } -// -// if (logConfigFile.exists() && logConfigFile.canRead()) -// { -// _devlog.info("Configuring logger using configuration file " + logConfigFile.getAbsolutePath()); -// if (logWatchTime > 0) -// { -// _devlog.info("log file " + logConfigFile.getAbsolutePath() + " will be checked for changes every " -// + logWatchTime + " seconds"); -// // log4j expects the watch interval in milliseconds -// DOMConfigurator.configureAndWatch(logConfigFile.getAbsolutePath(), logWatchTime * 1000); -// } -// else -// { -// DOMConfigurator.configure(logConfigFile.getAbsolutePath()); -// } -// } -// else -// { -// System.err.println("Logging configuration error: unable to read file " + logConfigFile.getAbsolutePath()); -// System.err.println("Using basic log4j configuration"); -// BasicConfigurator.configure(); -// } -// } - - public File getConfigFile() - { - return _configFile; - } - - - public class InitException extends Exception - { - InitException(String msg, Throwable cause) - { - super(msg, cause); - } - } -}
\ No newline at end of file diff --git a/java/broker/src/main/java/org/apache/qpid/server/AMQBrokerManagerMBean.java b/java/broker/src/main/java/org/apache/qpid/server/AMQBrokerManagerMBean.java deleted file mode 100644 index 6d67686d1c..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/AMQBrokerManagerMBean.java +++ /dev/null @@ -1,256 +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. - * - */ -/* - * - * Copyright (c) 2006 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.apache.qpid.server; - -import org.apache.commons.configuration.Configuration; -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.configuration.Configurator; -import org.apache.qpid.server.configuration.VirtualHostConfiguration; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.exchange.ExchangeFactory; -import org.apache.qpid.server.exchange.ExchangeRegistry; -import org.apache.qpid.server.management.AMQManagedObject; -import org.apache.qpid.server.management.MBeanConstructor; -import org.apache.qpid.server.management.MBeanDescription; -import org.apache.qpid.server.management.ManagedBroker; -import org.apache.qpid.server.management.ManagedObject; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.QueueRegistry; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.virtualhost.VirtualHost; - -import javax.management.JMException; -import javax.management.MBeanException; -import javax.management.MalformedObjectNameException; -import javax.management.ObjectName; - -/** - * This MBean implements the broker management interface and exposes the - * Broker level management features like creating and deleting exchanges and queue. - */ -@MBeanDescription("This MBean exposes the broker level management features") -public class AMQBrokerManagerMBean extends AMQManagedObject implements ManagedBroker -{ - private final QueueRegistry _queueRegistry; - private final ExchangeRegistry _exchangeRegistry; - private final ExchangeFactory _exchangeFactory; - private final MessageStore _messageStore; - - private final VirtualHost.VirtualHostMBean _virtualHostMBean; - - @MBeanConstructor("Creates the Broker Manager MBean") - public AMQBrokerManagerMBean(VirtualHost.VirtualHostMBean virtualHostMBean) throws JMException - { - super(ManagedBroker.class, ManagedBroker.TYPE); - - _virtualHostMBean = virtualHostMBean; - VirtualHost virtualHost = virtualHostMBean.getVirtualHost(); - - _queueRegistry = virtualHost.getQueueRegistry(); - _exchangeRegistry = virtualHost.getExchangeRegistry(); - _messageStore = virtualHost.getMessageStore(); - _exchangeFactory = virtualHost.getExchangeFactory(); - } - - public String getObjectInstanceName() - { - return _virtualHostMBean.getVirtualHost().getName(); - } - - /** - * Creates new exchange and registers it with the registry. - * - * @param exchangeName - * @param type - * @param durable - * @throws JMException - */ - public void createNewExchange(String exchangeName, String type, boolean durable) throws JMException - { - try - { - synchronized (_exchangeRegistry) - { - Exchange exchange = _exchangeRegistry.getExchange(new AMQShortString(exchangeName)); - if (exchange == null) - { - exchange = _exchangeFactory.createExchange(new AMQShortString(exchangeName), - new AMQShortString(type), durable, false, 0); - _exchangeRegistry.registerExchange(exchange); - } - else - { - throw new JMException("The exchange \"" + exchangeName + "\" already exists."); - } - } - } - catch (AMQException ex) - { - throw new MBeanException(ex, "Error in creating exchange " + exchangeName); - } - } - - /** - * Unregisters the exchange from registry. - * - * @param exchangeName - * @throws JMException - */ - public void unregisterExchange(String exchangeName) throws JMException - { - // TODO - // Check if the exchange is in use. - // boolean inUse = false; - // Check if there are queue-bindings with the exchange and unregister - // when there are no bindings. - try - { - _exchangeRegistry.unregisterExchange(new AMQShortString(exchangeName), false); - } - catch (AMQException ex) - { - throw new MBeanException(ex, "Error in unregistering exchange " + exchangeName); - } - } - - /** - * Creates a new queue and registers it with the registry and puts it - * in persistance storage if durable queue. - * - * @param queueName - * @param durable - * @param owner - * @throws JMException - */ - public void createNewQueue(String queueName, String owner, boolean durable) throws JMException - { - AMQQueue queue = _queueRegistry.getQueue(new AMQShortString(queueName)); - if (queue != null) - { - throw new JMException("The queue \"" + queueName + "\" already exists."); - } - - try - { - AMQShortString ownerShortString = null; - if (owner != null) - { - ownerShortString = new AMQShortString(owner); - } - - queue = new AMQQueue(new AMQShortString(queueName), durable, ownerShortString, false, getVirtualHost()); - if (queue.isDurable() && !queue.isAutoDelete()) - { - //DTX MessageStore -// try -// { - _messageStore.createQueue(queue); -// } -// catch (Exception e) -// { -// JMException jme = new JMException("problem creating queue " + queue.getName()); -// jme.initCause(e); -// throw jme; -// } - } - - Configuration virtualHostDefaultQueueConfiguration = - VirtualHostConfiguration.getDefaultQueueConfiguration(queue); - if (virtualHostDefaultQueueConfiguration != null) - { - Configurator.configure(queue, virtualHostDefaultQueueConfiguration); - } - - _queueRegistry.registerQueue(queue); - } - catch (AMQException ex) - { - throw new MBeanException(ex, "Error in creating queue " + queueName); - } - } - - private VirtualHost getVirtualHost() - { - return _virtualHostMBean.getVirtualHost(); - } - - /** - * Deletes the queue from queue registry and persistant storage. - * - * @param queueName - * @throws JMException - */ - public void deleteQueue(String queueName) throws JMException - { - AMQQueue queue = _queueRegistry.getQueue(new AMQShortString(queueName)); - if (queue == null) - { - throw new JMException("The Queue " + queueName + " is not a registerd queue."); - } - - try - { - queue.delete(); - - //DTX MessageStore -// if (queue.isDurable()) -// { -// _messageStore.destroyQueue(queue); - _messageStore.removeQueue(queue.getName()); -// } - } - catch (Exception ex) - { - /*ex.printStackTrace(); - JMException jme = new JMException(ex.getMessage());*/ - throw new MBeanException(ex, "Error in deleting queue " + queueName); - } - } - - public ManagedObject getParentObject() - { - return _virtualHostMBean; - } - - // This will have a single instance for a virtual host, so not having the name property in the ObjectName - public ObjectName getObjectName() throws MalformedObjectNameException - { - return getObjectNameForSingleInstanceMBean(); - } -} // End of MBean class diff --git a/java/broker/src/main/java/org/apache/qpid/server/AMQChannel.java b/java/broker/src/main/java/org/apache/qpid/server/AMQChannel.java deleted file mode 100644 index bd93ae2f85..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/AMQChannel.java +++ /dev/null @@ -1,980 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.ContentBody; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.abstraction.MessagePublishInfo; -import org.apache.qpid.server.ack.UnacknowledgedMessage; -import org.apache.qpid.server.ack.UnacknowledgedMessageMap; -import org.apache.qpid.server.ack.UnacknowledgedMessageMapImpl; -import org.apache.qpid.server.exchange.MessageRouter; -import org.apache.qpid.server.exchange.NoRouteException; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.queue.AMQMessage; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.MessageHandleFactory; -import org.apache.qpid.server.queue.Subscription; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.StoreContext; -import org.apache.qpid.server.txn.LocalTransactionalContext; -import org.apache.qpid.server.txn.NonTransactionalContext; -import org.apache.qpid.server.txn.TransactionManager; -import org.apache.qpid.server.txn.TransactionalContext; - -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; - -public class AMQChannel -{ - public static final int DEFAULT_PREFETCH = 5000; - - private static final Logger _log = Logger.getLogger(AMQChannel.class); - - private final int _channelId; - - // private boolean _transactional; - - private long _prefetch_HighWaterMark; - - private long _prefetch_LowWaterMark; - - private long _prefetchSize; - - /** - * The delivery tag is unique per channel. This is pre-incremented before putting into the deliver frame so that - * value of this represents the <b>last</b> tag sent out - */ - private AtomicLong _deliveryTag = new AtomicLong(0); - - /** A channel has a default queue (the last declared) that is used when no queue name is explictily set */ - private AMQQueue _defaultQueue; - - /** This tag is unique per subscription to a queue. The server returns this in response to a basic.consume request. */ - private int _consumerTag; - - /** - * The current message - which may be partial in the sense that not all frames have been received yet - which has - * been received by this channel. As the frames are received the message gets updated and once all frames have been - * received the message can then be routed. - */ - private AMQMessage _currentMessage; - - /** Maps from consumer tag to queue instance. Allows us to unsubscribe from a queue. */ - private final Map<AMQShortString, AMQQueue> _consumerTag2QueueMap = new HashMap<AMQShortString, AMQQueue>(); - - private final MessageStore _messageStore; - - private final TransactionManager _transactionManager; - - private UnacknowledgedMessageMap _unacknowledgedMessageMap = new UnacknowledgedMessageMapImpl(DEFAULT_PREFETCH); - - private final AtomicBoolean _suspended = new AtomicBoolean(false); - - private final MessageRouter _exchanges; - - private TransactionalContext _txnContext, _nonTransactedContext; - - /** - * A context used by the message store enabling it to track context for a given channel even across thread - * boundaries - */ - private final StoreContext _storeContext; - - private final List<RequiredDeliveryException> _returnMessages = new LinkedList<RequiredDeliveryException>(); - - private MessageHandleFactory _messageHandleFactory = new MessageHandleFactory(); - - private Set<Long> _browsedAcks = new HashSet<Long>(); - - // Why do we need this reference ? - ritchiem - private final AMQProtocolSession _session; - private boolean _closing; - - public AMQChannel(AMQProtocolSession session, int channelId, TransactionManager transactionManager, - MessageStore messageStore, MessageRouter exchanges) throws AMQException - { - _session = session; - _channelId = channelId; - _storeContext = new StoreContext("Session: " + session.getClientIdentifier() + "; channel: " + channelId); - _prefetch_HighWaterMark = DEFAULT_PREFETCH; - _prefetch_LowWaterMark = _prefetch_HighWaterMark / 2; - _messageStore = messageStore; - _transactionManager = transactionManager; - _exchanges = exchanges; - // by default the session is non-transactional - _txnContext = new NonTransactionalContext(_messageStore, _storeContext, this, _returnMessages, _browsedAcks); - } - - /** Sets this channel to be part of a local transaction */ - public void setLocalTransactional() - { - - _txnContext = new LocalTransactionalContext(_messageStore, _storeContext, _returnMessages); - - // Why is the LocalTransactionalContext always a DTX one? -// _txnContext = -// new DistributedTransactionalContext(_transactionManager, _messageStore, _storeContext, _returnMessages); - } - - public boolean isTransactional() - { - // this does not look great but there should only be one "non-transactional" - // transactional context, while there could be several transactional ones in - // theory - return !(_txnContext instanceof NonTransactionalContext); - } - - public int getChannelId() - { - return _channelId; - } - - public long getPrefetchCount() - { - return _prefetch_HighWaterMark; - } - - public void setPrefetchCount(long prefetchCount) - { - _prefetch_HighWaterMark = prefetchCount; - } - - public long getPrefetchSize() - { - return _prefetchSize; - } - - public void setPrefetchSize(long prefetchSize) - { - _prefetchSize = prefetchSize; - } - - public long getPrefetchLowMarkCount() - { - return _prefetch_LowWaterMark; - } - - public void setPrefetchLowMarkCount(long prefetchCount) - { - _prefetch_LowWaterMark = prefetchCount; - } - - public long getPrefetchHighMarkCount() - { - return _prefetch_HighWaterMark; - } - - public void setPrefetchHighMarkCount(long prefetchCount) - { - _prefetch_HighWaterMark = prefetchCount; - } - - public void setPublishFrame(MessagePublishInfo info, AMQProtocolSession publisher) throws AMQException - { - - _currentMessage = new AMQMessage(_messageStore.getNewMessageId(), info, _txnContext); - _currentMessage.setPublisher(publisher); - } - - public void publishContentHeader(ContentHeaderBody contentHeaderBody, AMQProtocolSession protocolSession) - throws AMQException - { - if (_currentMessage == null) - { - throw new AMQException(null, "Received content header without previously receiving a BasicPublish frame", null); - } - else - { - if (_log.isTraceEnabled()) - { - _log.trace(debugIdentity() + "Content header received on channel " + _channelId); - } - - _currentMessage.setContentHeaderBody(contentHeaderBody); - _currentMessage.setExpiration(); - - routeCurrentMessage(); - _currentMessage.routingComplete(_messageStore, _storeContext, _messageHandleFactory); - - // check and deliver if header says body length is zero - if (contentHeaderBody.bodySize == 0) - { - _txnContext.messageProcessed(protocolSession); - _currentMessage = null; - } - } - } - - public void publishContentBody(ContentBody contentBody, AMQProtocolSession protocolSession) throws AMQException - { - if (_currentMessage == null) - { - throw new AMQException(null, "Received content body without previously receiving a JmsPublishBody", null); - } - - if (_log.isTraceEnabled()) - { - _log.trace(debugIdentity() + "Content body received on channel " + _channelId); - } - - try - { - - // returns true iff the message was delivered (i.e. if all data was - // received - if (_currentMessage.addContentBodyFrame(_storeContext, - protocolSession.getRegistry().getProtocolVersionMethodConverter().convertToContentChunk( - contentBody))) - { - // callback to allow the context to do any post message processing - // primary use is to allow message return processing in the non-tx case - _txnContext.messageProcessed(protocolSession); - _currentMessage = null; - } - } - catch (AMQException e) - { - // we want to make sure we don't keep a reference to the message in the - // event of an error - _currentMessage = null; - throw e; - } - } - - protected void routeCurrentMessage() throws AMQException - { - try - { - _exchanges.routeContent(_currentMessage); - } - catch (NoRouteException e) - { - _returnMessages.add(e); - } - } - - public long getNextDeliveryTag() - { - return _deliveryTag.incrementAndGet(); - } - - public int getNextConsumerTag() - { - return ++_consumerTag; - } - - /** - * Subscribe to a queue. We register all subscriptions in the channel so that if the channel is closed we can clean - * up all subscriptions, even if the client does not explicitly unsubscribe from all queues. - * - * @param tag the tag chosen by the client (if null, server will generate one) - * @param queue the queue to subscribe to - * @param session the protocol session of the subscriber - * @param noLocal Flag stopping own messages being receivied. - * @param exclusive Flag requesting exclusive access to the queue - * @param acks Are acks enabled for this subscriber - * @param filters Filters to apply to this subscriber - * - * @return the consumer tag. This is returned to the subscriber and used in subsequent unsubscribe requests - * - * @throws ConsumerTagNotUniqueException if the tag is not unique - * @throws AMQException if something goes wrong - */ - public AMQShortString subscribeToQueue(AMQShortString tag, AMQQueue queue, AMQProtocolSession session, boolean acks, - FieldTable filters, boolean noLocal, boolean exclusive) throws AMQException, ConsumerTagNotUniqueException - { - if (tag == null) - { - tag = new AMQShortString("sgen_" + getNextConsumerTag()); - } - - if (_consumerTag2QueueMap.containsKey(tag)) - { - throw new ConsumerTagNotUniqueException(); - } - - queue.registerProtocolSession(session, _channelId, tag, acks, filters, noLocal, exclusive); - _consumerTag2QueueMap.put(tag, queue); - - return tag; - } - - public void unsubscribeConsumer(AMQProtocolSession session, final AMQShortString consumerTag) throws AMQException - { - final AMQQueue q = _consumerTag2QueueMap.remove(consumerTag); - if (q != null) - { - q.unregisterProtocolSession(session, _channelId, consumerTag); - } - } - - /** - * Called from the protocol session to close this channel and clean up. T - * - * @param session The session to close - * - * @throws AMQException if there is an error during closure - */ - public void close(AMQProtocolSession session) throws AMQException - { - _txnContext.rollback(); - unsubscribeAllConsumers(session); - requeue(); - - setClosing(true); - } - - private void setClosing(boolean closing) - { - _closing = closing; - } - - private void unsubscribeAllConsumers(AMQProtocolSession session) throws AMQException - { - if (_log.isInfoEnabled()) - { - if (!_consumerTag2QueueMap.isEmpty()) - { - _log.info("Unsubscribing all consumers on channel " + toString()); - } - else - { - _log.info("No consumers to unsubscribe on channel " + toString()); - } - } - - for (Map.Entry<AMQShortString, AMQQueue> me : _consumerTag2QueueMap.entrySet()) - { - if (_log.isInfoEnabled()) - { - _log.info("Unsubscribing consumer '" + me.getKey() + "' on channel " + toString()); - } - - me.getValue().unregisterProtocolSession(session, _channelId, me.getKey()); - } - - _consumerTag2QueueMap.clear(); - } - - /** - * Add a message to the channel-based list of unacknowledged messages - * - * @param message the message that was delivered - * @param deliveryTag the delivery tag used when delivering the message (see protocol spec for description of the - * delivery tag) - * @param consumerTag The tag for the consumer that is to acknowledge this message. - * @param queue the queue from which the message was delivered - */ - public void addUnacknowledgedMessage(AMQMessage message, long deliveryTag, AMQShortString consumerTag, AMQQueue queue) - { - if (_log.isDebugEnabled()) - { - if (queue == null) - { - _log.debug("Adding unacked message with a null queue:" + message.debugIdentity()); - } - else - { - if (_log.isDebugEnabled()) - { - _log.debug(debugIdentity() + " Adding unacked message(" + message.toString() + " DT:" + deliveryTag - + ") with a queue(" + queue + ") for " + consumerTag); - } - } - } - - synchronized (_unacknowledgedMessageMap.getLock()) - { - _unacknowledgedMessageMap.add(deliveryTag, new UnacknowledgedMessage(queue, message, consumerTag, deliveryTag)); - checkSuspension(); - } - } - - private final String id = "(" + System.identityHashCode(this) + ")"; - - public String debugIdentity() - { - return _channelId + id; - } - - /** - * Called to attempt re-delivery all outstanding unacknowledged messages on the channel. May result in delivery to - * this same channel or to other subscribers. - * - * @throws org.apache.qpid.AMQException if the requeue fails - */ - public void requeue() throws AMQException - { - // we must create a new map since all the messages will get a new delivery tag when they are redelivered - Collection<UnacknowledgedMessage> messagesToBeDelivered = _unacknowledgedMessageMap.cancelAllMessages(); - - // Deliver these messages out of the transaction as their delivery was never - // part of the transaction only the receive. - TransactionalContext deliveryContext = null; - - if (!messagesToBeDelivered.isEmpty()) - { - if (_log.isInfoEnabled()) - { - _log.info("Requeuing " + messagesToBeDelivered.size() + " unacked messages. for " + toString()); - } - - if (!(_txnContext instanceof NonTransactionalContext)) - { - // if (_nonTransactedContext == null) - { - _nonTransactedContext = - new NonTransactionalContext(_messageStore, _storeContext, this, _returnMessages, _browsedAcks); - } - - deliveryContext = _nonTransactedContext; - } - else - { - deliveryContext = _txnContext; - } - } - - for (UnacknowledgedMessage unacked : messagesToBeDelivered) - { - if (unacked.queue != null) - { - // Ensure message is released for redelivery - unacked.message.release(unacked.queue); - - // Mark message redelivered - unacked.message.setRedelivered(true); - - // Deliver Message - deliveryContext.deliver(unacked.message, unacked.queue, true); - - // Should we allow access To the DM to directy deliver the message? - // As we don't need to check for Consumers or worry about incrementing the message count? - // unacked.queue.getDeliveryManager().deliver(_storeContext, unacked.queue.getName(), unacked.message, false); - } - } - - } - - /** - * Requeue a single message - * - * @param deliveryTag The message to requeue - * - * @throws AMQException If something goes wrong. - */ - public void requeue(long deliveryTag) throws AMQException - { - UnacknowledgedMessage unacked = _unacknowledgedMessageMap.remove(deliveryTag); - - if (unacked != null) - { - - // Ensure message is released for redelivery - if (unacked.queue != null) - { - unacked.message.release(unacked.queue); - } - - // Mark message redelivered - unacked.message.setRedelivered(true); - - // Deliver these messages out of the transaction as their delivery was never - // part of the transaction only the receive. - TransactionalContext deliveryContext; - if (!(_txnContext instanceof NonTransactionalContext)) - { - // if (_nonTransactedContext == null) - { - _nonTransactedContext = - new NonTransactionalContext(_messageStore, _storeContext, this, _returnMessages, _browsedAcks); - } - - deliveryContext = _nonTransactedContext; - } - else - { - deliveryContext = _txnContext; - } - - if (unacked.queue != null) - { - // Redeliver the messages to the front of the queue - deliveryContext.deliver(unacked.message, unacked.queue, true); - // Deliver increments the message count but we have already deliverted this once so don't increment it again - // this was because deliver did an increment changed this. - } - else - { - _log.warn(System.identityHashCode(this) + " Requested requeue of message(" + unacked.message.debugIdentity() - + "):" + deliveryTag + " but no queue defined and no DeadLetter queue so DROPPING message."); - // _log.error("Requested requeue of message:" + deliveryTag + - // " but no queue defined using DeadLetter queue:" + getDeadLetterQueue()); - // - // deliveryContext.deliver(unacked.message, getDeadLetterQueue(), false); - // - } - } - else - { - _log.warn("Requested requeue of message:" + deliveryTag + " but no such delivery tag exists." - + _unacknowledgedMessageMap.size()); - - if (_log.isDebugEnabled()) - { - _unacknowledgedMessageMap.visit(new UnacknowledgedMessageMap.Visitor() - { - int count = 0; - - public boolean callback(UnacknowledgedMessage message) throws AMQException - { - _log.debug( - (count++) + ": (" + message.message.debugIdentity() + ")" + "[" + message.deliveryTag + "]"); - - return false; // Continue - } - - public void visitComplete() - { - } - }); - } - } - - } - - /** - * Called to resend all outstanding unacknowledged messages to this same channel. - * - * @param requeue Are the messages to be requeued or dropped. - * - * @throws AMQException When something goes wrong. - */ - public void resend(final boolean requeue) throws AMQException - { - final List<UnacknowledgedMessage> msgToRequeue = new LinkedList<UnacknowledgedMessage>(); - final List<UnacknowledgedMessage> msgToResend = new LinkedList<UnacknowledgedMessage>(); - - if (_log.isDebugEnabled()) - { - _log.debug("unacked map Size:" + _unacknowledgedMessageMap.size()); - } - - // Process the Unacked-Map. - // Marking messages who still have a consumer for to be resent - // and those that don't to be requeued. - _unacknowledgedMessageMap.visit(new UnacknowledgedMessageMap.Visitor() - { - public boolean callback(UnacknowledgedMessage message) throws AMQException - { - AMQShortString consumerTag = message.consumerTag; - AMQMessage msg = message.message; - msg.setRedelivered(true); - if (consumerTag != null) - { - // Consumer exists - if (_consumerTag2QueueMap.containsKey(consumerTag)) - { - msgToResend.add(message); - } - else // consumer has gone - { - msgToRequeue.add(message); - } - } - else - { - // Message has no consumer tag, so was "delivered" to a GET - // or consumer no longer registered - // cannot resend, so re-queue. - if (message.queue != null) - { - if (requeue) - { - msgToRequeue.add(message); - } - else - { - _log.info("No DeadLetter Queue and requeue not requested so dropping message:" + message); - } - } - else - { - _log.info("Message.queue is null and no DeadLetter Queue so dropping message:" + message); - } - } - - // false means continue processing - return false; - } - - public void visitComplete() - { - } - }); - - // Process Messages to Resend - if (_log.isDebugEnabled()) - { - if (!msgToResend.isEmpty()) - { - _log.debug("Preparing (" + msgToResend.size() + ") message to resend."); - } - else - { - _log.debug("No message to resend."); - } - } - - for (UnacknowledgedMessage message : msgToResend) - { - AMQMessage msg = message.message; - - // Our Java Client will always suspend the channel when resending! - // If the client has requested the messages be resent then it is - // their responsibility to ensure that thay are capable of receiving them - // i.e. The channel hasn't been server side suspended. - // if (isSuspended()) - // { - // _log.info("Channel is suspended so requeuing"); - // //move this message to requeue - // msgToRequeue.add(message); - // } - // else - // { - // release to allow it to be delivered - msg.release(message.queue); - - // Without any details from the client about what has been processed we have to mark - // all messages in the unacked map as redelivered. - msg.setRedelivered(true); - - Subscription sub = msg.getDeliveredSubscription(message.queue); - - if (sub != null) - { - // Get the lock so we can tell if the sub scription has closed. - // will stop delivery to this subscription until the lock is released. - // note: this approach would allow the use of a single queue if the - // PreDeliveryQueue would allow head additions. - // In the Java Qpid client we are suspended whilst doing this so it is all rather Mute.. - // needs guidance from AMQP WG Model SIG - synchronized (sub.getSendLock()) - { - if (sub.isClosed()) - { - if (_log.isDebugEnabled()) - { - _log.debug("Subscription(" + System.identityHashCode(sub) - + ") closed during resend so requeuing message"); - } - // move this message to requeue - msgToRequeue.add(message); - } - else - { - if (_log.isDebugEnabled()) - { - _log.debug("Requeuing " + msg.debugIdentity() + " for resend via sub:" - + System.identityHashCode(sub)); - } - - sub.addToResendQueue(msg); - _unacknowledgedMessageMap.remove(message.deliveryTag); - } - } // sync(sub.getSendLock) - } - else - { - - if (_log.isInfoEnabled()) - { - _log.info("DeliveredSubscription not recorded so just requeueing(" + message.toString() - + ")to prevent loss"); - } - // move this message to requeue - msgToRequeue.add(message); - } - } // for all messages - // } else !isSuspend - - if (_log.isInfoEnabled()) - { - if (!msgToRequeue.isEmpty()) - { - _log.info("Preparing (" + msgToRequeue.size() + ") message to requeue to."); - } - } - - // Deliver these messages out of the transaction as their delivery was never - // part of the transaction only the receive. - TransactionalContext deliveryContext; - if (!(_txnContext instanceof NonTransactionalContext)) - { - if (_nonTransactedContext == null) - { - _nonTransactedContext = - new NonTransactionalContext(_messageStore, _storeContext, this, _returnMessages, _browsedAcks); - } - - deliveryContext = _nonTransactedContext; - } - else - { - deliveryContext = _txnContext; - } - - // Process Messages to Requeue at the front of the queue - for (UnacknowledgedMessage message : msgToRequeue) - { - message.message.release(message.queue); - message.message.setRedelivered(true); - - deliveryContext.deliver(message.message, message.queue, true); - - _unacknowledgedMessageMap.remove(message.deliveryTag); - } - } - - /** - * Callback indicating that a queue has been deleted. We must update the structure of unacknowledged messages to - * remove the queue reference and also decrement any message reference counts, without actually removing the item - * since we may get an ack for a delivery tag that was generated from the deleted queue. - * - * @param queue the queue that has been deleted - * - * @throws org.apache.qpid.AMQException if there is an error processing the unacked messages - */ - public void queueDeleted(final AMQQueue queue) throws AMQException - { - _unacknowledgedMessageMap.visit(new UnacknowledgedMessageMap.Visitor() - { - public boolean callback(UnacknowledgedMessage message) throws AMQException - { - if (message.queue == queue) - { - try - { - message.discard(_storeContext); - message.queue = null; - } - catch (AMQException e) - { - _log.error( - "Error decrementing ref count on message " + message.message.getMessageId() + ": " + e, e); - } - } - - return false; - } - - public void visitComplete() - { - } - }); - } - - /** - * Acknowledge one or more messages. - * - * @param deliveryTag the last delivery tag - * @param multiple if true will acknowledge all messages up to an including the delivery tag. if false only - * acknowledges the single message specified by the delivery tag - * - * @throws AMQException if the delivery tag is unknown (e.g. not outstanding) on this channel - */ - public void acknowledgeMessage(long deliveryTag, boolean multiple) throws AMQException - { - synchronized (_unacknowledgedMessageMap.getLock()) - { - if (_log.isDebugEnabled()) - { - _log.debug("Unacked (PreAck) Size:" + _unacknowledgedMessageMap.size()); - } - - _unacknowledgedMessageMap.acknowledgeMessage(deliveryTag, multiple, _txnContext); - - if (_log.isDebugEnabled()) - { - _log.debug("Unacked (PostAck) Size:" + _unacknowledgedMessageMap.size()); - } - - } - - checkSuspension(); - } - - /** - * Used only for testing purposes. - * - * @return the map of unacknowledged messages - */ - public UnacknowledgedMessageMap getUnacknowledgedMessageMap() - { - return _unacknowledgedMessageMap; - } - - private void checkSuspension() - { - boolean suspend; - - suspend = - ((_prefetch_HighWaterMark != 0) && (_unacknowledgedMessageMap.size() >= _prefetch_HighWaterMark)) - || ((_prefetchSize != 0) && (_prefetchSize < _unacknowledgedMessageMap.getUnacknowledgeBytes())); - - setSuspended(suspend); - } - - public void setSuspended(boolean suspended) - { - boolean isSuspended = _suspended.get(); - - if (isSuspended && !suspended) - { - // Continue being suspended if we are above the _prefetch_LowWaterMark - suspended = _unacknowledgedMessageMap.size() > _prefetch_LowWaterMark; - } - - boolean wasSuspended = _suspended.getAndSet(suspended); - if (wasSuspended != suspended) - { - if (wasSuspended) - { - _log.debug("Unsuspending channel " + this); - // may need to deliver queued messages - for (AMQQueue q : _consumerTag2QueueMap.values()) - { - q.deliverAsync(); - } - } - else - { - _log.debug("Suspending channel " + this); - } - } - } - - public boolean isSuspended() - { - return _suspended.get(); - } - - public void commit() throws AMQException - { - if (!isTransactional()) - { - throw new AMQException(null, "Fatal error: commit called on non-transactional channel", null); - } - - _txnContext.commit(); - } - - public void rollback() throws AMQException - { - _txnContext.rollback(); - } - - public String toString() - { - StringBuilder sb = new StringBuilder(30); - sb.append("Channel: id ").append(_channelId).append(", transaction mode: ").append(isTransactional()); - sb.append(", prefetch marks: ").append(_prefetch_LowWaterMark); - sb.append("/").append(_prefetch_HighWaterMark); - - return sb.toString(); - } - - public void setDefaultQueue(AMQQueue queue) - { - _defaultQueue = queue; - } - - public AMQQueue getDefaultQueue() - { - return _defaultQueue; - } - - public StoreContext getStoreContext() - { - return _storeContext; - } - - public void processReturns(AMQProtocolSession session) throws AMQException - { - for (RequiredDeliveryException bouncedMessage : _returnMessages) - { - AMQMessage message = bouncedMessage.getAMQMessage(); - session.getProtocolOutputConverter().writeReturn(message, _channelId, bouncedMessage.getReplyCode().getCode(), - new AMQShortString(bouncedMessage.getMessage())); - } - - _returnMessages.clear(); - } - - public boolean wouldSuspend(AMQMessage msg) - { - if (isSuspended()) - { - return true; - } - else - { - boolean willSuspend = - ((_prefetch_HighWaterMark != 0) && ((_unacknowledgedMessageMap.size() + 1) > _prefetch_HighWaterMark)); - if (!willSuspend) - { - final long unackedSize = _unacknowledgedMessageMap.getUnacknowledgeBytes(); - - willSuspend = (_prefetchSize != 0) && (unackedSize != 0) && (_prefetchSize < (msg.getSize() + unackedSize)); - } - - if (willSuspend) - { - setSuspended(true); - } - - return willSuspend; - } - - } - - public TransactionalContext getTransactionalContext() - { - return _txnContext; - } - - public boolean isClosing() - { - return _closing; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/ConsumerTagNotUniqueException.java b/java/broker/src/main/java/org/apache/qpid/server/ConsumerTagNotUniqueException.java deleted file mode 100644 index 3dc2654bd5..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/ConsumerTagNotUniqueException.java +++ /dev/null @@ -1,36 +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; - -/** - * ConsumerTagNotUniqueException indicates that a client has attempted to connect with a consumer tag that is already - * used. - * - * <p/><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Represents error when clients connects with a non-unique tag. - * </table> - * - * @todo Consider replacing with an AMQNotAllowedException, as this is the status code returned when this happens. - */ -public class ConsumerTagNotUniqueException extends Exception -{ -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/Main.java b/java/broker/src/main/java/org/apache/qpid/server/Main.java deleted file mode 100644 index 8932dd25f0..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/Main.java +++ /dev/null @@ -1,573 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server; - -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.HelpFormatter; -import org.apache.commons.cli.Option; -import org.apache.commons.cli.OptionBuilder; -import org.apache.commons.cli.Options; -import org.apache.commons.cli.ParseException; -import org.apache.commons.cli.PosixParser; -import org.apache.commons.configuration.Configuration; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.log4j.BasicConfigurator; -import org.apache.log4j.Logger; -import org.apache.log4j.xml.DOMConfigurator; -import org.apache.mina.common.ByteBuffer; -import org.apache.mina.common.IoAcceptor; -import org.apache.mina.common.SimpleByteBufferAllocator; -import org.apache.mina.transport.socket.nio.SocketAcceptorConfig; -import org.apache.mina.transport.socket.nio.SocketSessionConfig; -import org.apache.qpid.AMQException; -import org.apache.qpid.common.QpidProperties; -import org.apache.qpid.framing.ProtocolVersion; -import org.apache.qpid.pool.ReadWriteThreadModel; -import org.apache.qpid.server.configuration.VirtualHostConfiguration; -import org.apache.qpid.server.management.JMXManagedObjectRegistry; -import org.apache.qpid.server.protocol.AMQPFastProtocolHandler; -import org.apache.qpid.server.protocol.AMQPProtocolProvider; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.registry.ConfigurationFileApplicationRegistry; -import org.apache.qpid.server.transport.ConnectorConfiguration; -import org.apache.qpid.url.URLSyntaxException; - -import java.io.File; -import java.io.IOException; -import java.net.BindException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.util.Collection; -import java.util.List; - -/** - * Main entry point for AMQPD. - * - */ -@SuppressWarnings({"AccessStaticViaInstance"}) -public class Main -{ - /** Used for debugging. */ - private static final Logger _logger = Logger.getLogger(Main.class); - - /** Used for logging operator messages. */ - public static final Logger _brokerLogger = Logger.getLogger("Qpid.Broker"); - - private static final String DEFAULT_CONFIG_FILE = "etc/config.xml"; - - private static final String DEFAULT_LOG_CONFIG_FILENAME = "log4j.xml"; - public static final String QPID_HOME = "QPID_HOME"; - private static final int IPV4_ADDRESS_LENGTH = 4; - - private static final char IPV4_LITERAL_SEPARATOR = '.'; - - protected static class InitException extends Exception - { - InitException(String msg, Throwable cause) - { - super(msg, cause); - } - } - - protected final Options options = new Options(); - protected CommandLine commandLine; - - /** - * @todo Side-effecting constructor; eliminate. Put the processing sequence in the main method. - */ - protected Main(String[] args) - { - setOptions(options); - if (parseCommandline(args)) - { - execute(); - } - } - - protected boolean parseCommandline(String[] args) - { - try - { - commandLine = new PosixParser().parse(options, args); - - return true; - } - catch (ParseException e) - { - System.err.println("Error: " + e.getMessage()); - HelpFormatter formatter = new HelpFormatter(); - formatter.printHelp("Qpid", options, true); - - return false; - } - } - - /** - * Sets up the command line options, with usage help, ready for parsing the command line against. - * - * @param options The object to store the configured command line options in. - */ - protected void setOptions(Options options) - { - Option help = new Option("h", "help", false, "print this message"); - Option version = new Option("v", "version", false, "print the version information and exit"); - Option configFile = - OptionBuilder.withArgName("file").hasArg().withDescription("use given configuration file").withLongOpt("config") - .create("c"); - Option port = - OptionBuilder.withArgName("port").hasArg() - .withDescription("listen on the specified port. Overrides any value in the config file") - .withLongOpt("port").create("p"); - Option mport = - OptionBuilder.withArgName("mport").hasArg() - .withDescription("listen on the specified management port. Overrides any value in the config file") - .withLongOpt("mport").create("m"); - - - Option bind = - OptionBuilder.withArgName("bind").hasArg() - .withDescription("bind to the specified address. Overrides any value in the config file") - .withLongOpt("bind").create("b"); - Option logconfig = - OptionBuilder.withArgName("logconfig").hasArg() - .withDescription("use the specified log4j xml configuration file. By " - + "default looks for a file named " + DEFAULT_LOG_CONFIG_FILENAME - + " in the same directory as the configuration file").withLongOpt("logconfig").create("l"); - Option logwatchconfig = - OptionBuilder.withArgName("logwatch").hasArg() - .withDescription("monitor the log file configuration file for changes. Units are seconds. " - + "Zero means do not check for changes.").withLongOpt("logwatch").create("w"); - - options.addOption(help); - options.addOption(version); - options.addOption(configFile); - options.addOption(logconfig); - options.addOption(logwatchconfig); - options.addOption(port); - options.addOption(mport); - options.addOption(bind); - } - - /** - * @todo Handles command line, but there is already a parse command line method. Put all command line handling - * in a single flow of control. Also part implements the top-level handler, which would more neatly be kept - * together in one place. - */ - protected void execute() - { - // note this understands either --help or -h. If an option only has a long name you can use that but if - // an option has a short name and a long name you must use the short name here. - if (commandLine.hasOption("h")) - { - HelpFormatter formatter = new HelpFormatter(); - formatter.printHelp("Qpid", options, true); - } - else if (commandLine.hasOption("v")) - { - String ver = QpidProperties.getVersionString(); - - StringBuilder protocol = new StringBuilder("AMQP version(s) [major.minor]: "); - - boolean first = true; - for (ProtocolVersion pv : ProtocolVersion.getSupportedProtocolVersions()) - { - if (first) - { - first = false; - } - else - { - protocol.append(", "); - } - - protocol.append(pv.getMajorVersion()).append('-').append(pv.getMinorVersion()); - - } - - System.out.println(ver + " (" + protocol + ")"); - } - else - { - try - { - startup(); - } - catch (InitException e) - { - System.out.println(e.getMessage()); - _brokerLogger.error("Initialisation Error : " + e.getMessage()); - - } - catch (ConfigurationException e) - { - System.out.println("Error configuring message broker: " + e); - _brokerLogger.error("Error configuring message broker: " + e); - e.printStackTrace(); - } - catch (Exception e) - { - System.out.println("Error intialising message broker: " + e); - _brokerLogger.error("Error intialising message broker: " + e); - e.printStackTrace(); - } - } - } - - /** - * Reads the configuration file and performs configuration specified in it. Then hands over to bind to do the - * actual broker start-up. - * - * @todo A bit confusing, seperate out configuration from start-up. Call config method to handle the configuration - * from the config file, in the main flow of control (possibly #main method). Then call #startup or #bind - * to start the broker. - */ - protected void startup() throws InitException, ConfigurationException, Exception - { - final String QpidHome = System.getProperty(QPID_HOME); - final File defaultConfigFile = new File(QpidHome, DEFAULT_CONFIG_FILE); - final File configFile = new File(commandLine.getOptionValue("c", defaultConfigFile.getPath())); - if (!configFile.exists()) - { - String error = "File " + configFile + " could not be found. Check the file exists and is readable."; - - if (QpidHome == null) - { - error = error + "\nNote: " + QPID_HOME + " is not set."; - } - - throw new InitException(error, null); - } - else - { - System.out.println("Using configuration file " + configFile.getAbsolutePath()); - } - - String logConfig = commandLine.getOptionValue("l"); - String logWatchConfig = commandLine.getOptionValue("w", "0"); - if (logConfig != null) - { - File logConfigFile = new File(logConfig); - configureLogging(logConfigFile, logWatchConfig); - } - else - { - File configFileDirectory = configFile.getParentFile(); - File logConfigFile = new File(configFileDirectory, DEFAULT_LOG_CONFIG_FILENAME); - configureLogging(logConfigFile, logWatchConfig); - } - - ConfigurationFileApplicationRegistry config = new ConfigurationFileApplicationRegistry(configFile); - - - updateManagementPort(config.getConfiguration(), commandLine.getOptionValue("m")); - - - - ApplicationRegistry.initialise(config); - - - //fixme .. use QpidProperties.getVersionString when we have fixed the classpath issues - // that are causing the broker build to pick up the wrong properties file and hence say - // Starting Qpid Client - _brokerLogger.info("Starting Qpid Broker " + QpidProperties.getReleaseVersion() - + " build: " + QpidProperties.getBuildVersion()); - - ConnectorConfiguration connectorConfig = - ApplicationRegistry.getInstance().getConfiguredObject(ConnectorConfiguration.class); - - ByteBuffer.setUseDirectBuffers(connectorConfig.enableDirectBuffers); - - // the MINA default is currently to use the pooled allocator although this may change in future - // once more testing of the performance of the simple allocator has been done - if (!connectorConfig.enablePooledAllocator) - { - ByteBuffer.setAllocator(new SimpleByteBufferAllocator()); - } - - int port = connectorConfig.port; - - String portStr = commandLine.getOptionValue("p"); - if (portStr != null) - { - try - { - port = Integer.parseInt(portStr); - } - catch (NumberFormatException e) - { - throw new InitException("Invalid port: " + portStr, e); - } - } - - String VIRTUAL_HOSTS = "virtualhosts"; - - Object virtualHosts = ApplicationRegistry.getInstance().getConfiguration().getProperty(VIRTUAL_HOSTS); - - if (virtualHosts != null) - { - if (virtualHosts instanceof Collection) - { - int totalVHosts = ((Collection) virtualHosts).size(); - for (int vhost = 0; vhost < totalVHosts; vhost++) - { - setupVirtualHosts(configFile.getParent(), (String) ((List) virtualHosts).get(vhost)); - } - } - else - { - setupVirtualHosts(configFile.getParent(), (String) virtualHosts); - } - } - - bind(port, connectorConfig); - - } - - /** - * Update the configuration data with the management port. - * @param configuration - * @param managementPort The string from the command line - */ - private void updateManagementPort(Configuration configuration, String managementPort) - { - if (managementPort != null) - { - int mport; - int defaultMPort = configuration.getInt(JMXManagedObjectRegistry.MANAGEMENT_PORT_CONFIG_PATH); - try - { - mport = Integer.parseInt(managementPort); - configuration.setProperty(JMXManagedObjectRegistry.MANAGEMENT_PORT_CONFIG_PATH, mport); - } - catch (NumberFormatException e) - { - _logger.warn("Invalid management port: " + managementPort + " will use default:" + defaultMPort, e); - } - } - } - - protected void setupVirtualHosts(String configFileParent, String configFilePath) - throws ConfigurationException, AMQException, URLSyntaxException - { - String configVar = "${conf}"; - - if (configFilePath.startsWith(configVar)) - { - configFilePath = configFileParent + configFilePath.substring(configVar.length()); - } - - if (configFilePath.indexOf(".xml") != -1) - { - VirtualHostConfiguration vHostConfig = new VirtualHostConfiguration(configFilePath); - vHostConfig.performBindings(); - } - else - { - // the virtualhosts value is a path. Search it for XML files. - - File virtualHostDir = new File(configFilePath); - - String[] fileNames = virtualHostDir.list(); - - for (int each = 0; each < fileNames.length; each++) - { - if (fileNames[each].endsWith(".xml")) - { - VirtualHostConfiguration vHostConfig = - new VirtualHostConfiguration(configFilePath + "/" + fileNames[each]); - vHostConfig.performBindings(); - } - } - } - } - - /** - * Assembles/configures the components that Mina needs, then start Mina running to accept connections. - * - * @todo Partially implements top-level error handler. Better to let these errors fall through to a single - * top-level handler. - */ - protected void bind(int port, ConnectorConfiguration connectorConfig) throws BindException - { - String bindAddr = commandLine.getOptionValue("b"); - if (bindAddr == null) - { - bindAddr = connectorConfig.bindAddress; - } - - try - { - // IoAcceptor acceptor = new SocketAcceptor(connectorConfig.processors); - IoAcceptor acceptor = connectorConfig.createAcceptor(); - SocketAcceptorConfig sconfig = (SocketAcceptorConfig) acceptor.getDefaultConfig(); - SocketSessionConfig sc = (SocketSessionConfig) sconfig.getSessionConfig(); - - sc.setReceiveBufferSize(connectorConfig.socketReceiveBufferSize); - sc.setSendBufferSize(connectorConfig.socketWriteBuferSize); - sc.setTcpNoDelay(connectorConfig.tcpNoDelay); - - // if we do not use the executor pool threading model we get the default leader follower - // implementation provided by MINA - if (connectorConfig.enableExecutorPool) - { - sconfig.setThreadModel(ReadWriteThreadModel.getInstance()); - } - - if (!connectorConfig.enableSSL || !connectorConfig.sslOnly) - { - AMQPFastProtocolHandler handler = new AMQPProtocolProvider().getHandler(); - InetSocketAddress bindAddress; - if (bindAddr.equals("wildcard")) - { - bindAddress = new InetSocketAddress(port); - } - else - { - bindAddress = new InetSocketAddress(InetAddress.getByAddress(parseIP(bindAddr)), port); - } - - acceptor.bind(bindAddress, handler, sconfig); - // fixme qpid.AMQP should be using qpidproperties to get value - _brokerLogger.info("Qpid.AMQP listening on non-SSL address " + bindAddress); - } - - if (connectorConfig.enableSSL) - { - AMQPFastProtocolHandler handler = new AMQPProtocolProvider().getHandler(); - try - { - - acceptor.bind(new InetSocketAddress(connectorConfig.sslPort), handler, sconfig); - // fixme qpid.AMQP should be using qpidproperties to get value - _brokerLogger.info("Qpid.AMQP listening on SSL port " + connectorConfig.sslPort); - - } - catch (IOException e) - { - _brokerLogger.error("Unable to listen on SSL port: " + e, e); - } - } - - // fixme qpid.AMQP should be using qpidproperties to get value - _brokerLogger.info("Qpid Broker Ready :" + QpidProperties.getReleaseVersion() - + " build: " + QpidProperties.getBuildVersion()); - } - catch (Exception e) - { - _logger.error("Unable to bind service to registry: " + e, e); - //fixme this need tidying up - throw new BindException(e.getMessage()); - } - } - - /** - * Processes the command line and starts the broker running. This method acts as a top-level error handler for - * any exceptions that fall out of the code below this point. These exceptions are logged before System.exit is - * called with an error code. - * - * @param args The command line arguments. - */ - public static void main(String[] args) - { - // Use a try block so that any exceptions that fall through to the top-level are logged before the application - // exits with an error code. - // try - { - // Parse the command line. - - // Create an instance of the Main broker entry point class and start it running. - } - // catch () - { - // Log the exception as an error. - - // Exit with an error code. - } - - new Main(args); - } - - private byte[] parseIP(String address) throws Exception - { - char[] literalBuffer = address.toCharArray(); - int byteCount = 0; - int currByte = 0; - byte[] ip = new byte[IPV4_ADDRESS_LENGTH]; - for (int i = 0; i < literalBuffer.length; i++) - { - char currChar = literalBuffer[i]; - if ((currChar >= '0') && (currChar <= '9')) - { - currByte = (currByte * 10) + (Character.digit(currChar, 10) & 0xFF); - } - - if ((currChar == IPV4_LITERAL_SEPARATOR) || ((i + 1) == literalBuffer.length)) - { - ip[byteCount++] = (byte) currByte; - currByte = 0; - } - } - - if (byteCount != 4) - { - throw new Exception("Invalid IP address: " + address); - } - - return ip; - } - - private void configureLogging(File logConfigFile, String logWatchConfig) - { - int logWatchTime = 0; - try - { - logWatchTime = Integer.parseInt(logWatchConfig); - } - catch (NumberFormatException e) - { - System.err.println("Log watch configuration value of " + logWatchConfig + " is invalid. Must be " - + "a non-negative integer. Using default of zero (no watching configured"); - } - - if (logConfigFile.exists() && logConfigFile.canRead()) - { - System.out.println("Configuring logger using configuration file " + logConfigFile.getAbsolutePath()); - if (logWatchTime > 0) - { - System.out.println("log file " + logConfigFile.getAbsolutePath() + " will be checked for changes every " - + logWatchTime + " seconds"); - // log4j expects the watch interval in milliseconds - DOMConfigurator.configureAndWatch(logConfigFile.getAbsolutePath(), logWatchTime * 1000); - } - else - { - DOMConfigurator.configure(logConfigFile.getAbsolutePath()); - } - } - else - { - System.err.println("Logging configuration error: unable to read file " + logConfigFile.getAbsolutePath()); - System.err.println("Using basic log4j configuration"); - BasicConfigurator.configure(); - } - } - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/ManagedChannel.java b/java/broker/src/main/java/org/apache/qpid/server/ManagedChannel.java deleted file mode 100644 index e76f9c3f6c..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/ManagedChannel.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.server; - -import java.io.IOException; - -import javax.management.JMException; - -/** - * The managed interface exposed to allow management of channels. - * @author Bhupendra Bhardwaj - * @version 0.1 - */ -public interface ManagedChannel -{ - static final String TYPE = "Channel"; - - /** - * Tells whether the channel is transactional. - * @return true if the channel is transactional. - * @throws IOException - */ - boolean isTransactional() throws IOException; - - /** - * Tells the number of unacknowledged messages in this channel. - * @return number of unacknowledged messages. - * @throws IOException - */ - int getUnacknowledgedMessageCount() throws IOException; - - - //********** Operations *****************// - - /** - * Commits the transactions if the channel is transactional. - * @throws IOException - * @throws JMException - */ - void commitTransactions() throws IOException, JMException; - - /** - * Rollsback the transactions if the channel is transactional. - * @throws IOException - * @throws JMException - */ - void rollbackTransactions() throws IOException, JMException; - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/RequiredDeliveryException.java b/java/broker/src/main/java/org/apache/qpid/server/RequiredDeliveryException.java deleted file mode 100644 index 37c5f38ea3..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/RequiredDeliveryException.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server; - -import org.apache.qpid.AMQException; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.queue.AMQMessage; - -/** - * Signals that a required delivery could not be made. This could be bacuse of the immediate flag being set and the - * queue having no consumers, or the mandatory flag being set and the exchange having no valid bindings. - * - * <p/>The failed message is associated with this error condition, by taking a reference to it. This enables the - * correct compensating action to be taken against the message, for example, bouncing it back to the sender. - * - * <p/><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Represent failure to deliver a message that must be delivered. - * <tr><td> Associate the failed message with the error condition. <td> {@link AMQMessage} - * </table> - */ -public abstract class RequiredDeliveryException extends AMQException -{ - private final AMQMessage _amqMessage; - - public RequiredDeliveryException(String message, AMQMessage payload, Throwable cause) - { - super(null, message, cause); - - // Increment the reference as this message is in the routing phase - // and so will have the ref decremented as routing fails. - // we need to keep this message around so we can return it in the - // handler. So increment here. - _amqMessage = payload.takeReference(); - - // payload.incrementReference(); - } - - public AMQMessage getAMQMessage() - { - return _amqMessage; - } - - public AMQConstant getErrorCode() - { - return getReplyCode(); - } - - public abstract AMQConstant getReplyCode(); -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/ack/TxAck.java b/java/broker/src/main/java/org/apache/qpid/server/ack/TxAck.java deleted file mode 100644 index 5ca8d57f7c..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/ack/TxAck.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.ack; - -import java.util.LinkedList; -import java.util.List; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.store.StoreContext; -import org.apache.qpid.server.txn.TxnOp; - -/** - * A TxnOp implementation for handling accumulated acks - */ -public class TxAck implements TxnOp -{ - private final UnacknowledgedMessageMap _map; - private final List <UnacknowledgedMessage> _unacked = new LinkedList<UnacknowledgedMessage>(); - private final List<Long> _individual = new LinkedList<Long>(); - private long _deliveryTag; - private boolean _multiple; - - public TxAck(UnacknowledgedMessageMap map) - { - _map = map; - } - - public void update(long deliveryTag, boolean multiple) - { - if (!multiple) - { - //have acked a single message that is not part of - //the previously acked region so record - //individually - _individual.add(deliveryTag);//_multiple && !multiple - } - else if (deliveryTag > _deliveryTag) - { - //have simply moved the last acked message on a - //bit - _deliveryTag = deliveryTag; - _multiple = true; - } - } - - public void consolidate() - { - //lookup all the unacked messages that have been acked in this transaction - if (_multiple) - { - //get all the unacked messages for the accumulated - //multiple acks - _map.collect(_deliveryTag, true, _unacked); - } - //get any unacked messages for individual acks outside the - //range covered by multiple acks - for (long tag : _individual) - { - if(_deliveryTag < tag) - { - _map.collect(tag, false, _unacked); - } - } - } - - public boolean checkPersistent() throws AMQException - { - //if any of the messages in unacked are persistent the txn - //buffer must be marked as persistent: - for (UnacknowledgedMessage msg : _unacked) - { - if (msg.message.isPersistent()) - { - return true; - } - } - return false; - } - - public void prepare(StoreContext storeContext) throws AMQException - { - //make persistent changes, i.e. dequeue and decrementReference - for (UnacknowledgedMessage msg : _unacked) - { - msg.restoreTransientMessageData(); - - //Message has been ack so discard it. This will dequeue and decrement the reference. - msg.discard(storeContext); - } - } - - public void undoPrepare() - { - //decrementReference is annoyingly untransactional (due to - //in memory counter) so if we failed in prepare for full - //txn, this op will have to compensate by fixing the count - //in memory (persistent changes will be rolled back by store) - for (UnacknowledgedMessage msg : _unacked) - { - msg.clearTransientMessageData(); - msg.message.takeReference(); - } - } - - public void commit(StoreContext storeContext) - { - //remove the unacked messages from the channels map - _map.remove(_unacked); - for (UnacknowledgedMessage msg : _unacked) - { - msg.clearTransientMessageData(); - } - - } - - public void rollback(StoreContext storeContext) - { - } -} - - diff --git a/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessage.java b/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessage.java deleted file mode 100644 index b8c5e821f7..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessage.java +++ /dev/null @@ -1,79 +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.ack; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.queue.AMQMessage; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.store.StoreContext; - -public class UnacknowledgedMessage -{ - public final AMQMessage message; - public final AMQShortString consumerTag; - public final long deliveryTag; - public AMQQueue queue; - - public UnacknowledgedMessage(AMQQueue queue, AMQMessage message, AMQShortString consumerTag, long deliveryTag) - { - this.queue = queue; - this.message = message; - this.consumerTag = consumerTag; - this.deliveryTag = deliveryTag; - } - - public String toString() - { - StringBuilder sb = new StringBuilder(); - sb.append("Q:"); - sb.append(queue); - sb.append(" M:"); - sb.append(message); - sb.append(" CT:"); - sb.append(consumerTag); - sb.append(" DT:"); - sb.append(deliveryTag); - - return sb.toString(); - } - - public void discard(StoreContext storeContext) throws AMQException - { - if (queue != null) - { - message.dequeue(storeContext, queue); - } - //if the queue is null then the message is waiting to be acked, but has been removed. - message.decrementReference(storeContext); - } - - public void restoreTransientMessageData() throws AMQException - { - message.restoreTransientMessageData(); - } - - public void clearTransientMessageData() - { - message.clearTransientMessageData(); - } -} - diff --git a/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMap.java b/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMap.java deleted file mode 100644 index b69a917081..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMap.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.ack; - -import java.util.Collection; -import java.util.List; -import java.util.Set; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.txn.TransactionalContext; - -public interface UnacknowledgedMessageMap -{ - public interface Visitor - { - /** - * @param message the message being iterated over - * @return true to stop iteration, false to continue - * @throws AMQException - */ - boolean callback(UnacknowledgedMessage message) throws AMQException; - - void visitComplete(); - } - - void visit(Visitor visitor) throws AMQException; - - Object getLock(); - - void add(long deliveryTag, UnacknowledgedMessage message); - - void collect(long deliveryTag, boolean multiple, List<UnacknowledgedMessage> msgs); - - boolean contains(long deliveryTag) throws AMQException; - - void remove(List<UnacknowledgedMessage> msgs); - - UnacknowledgedMessage remove(long deliveryTag); - - void drainTo(Collection<UnacknowledgedMessage> destination, long deliveryTag) throws AMQException; - - Collection<UnacknowledgedMessage> cancelAllMessages(); - - void acknowledgeMessage(long deliveryTag, boolean multiple, TransactionalContext txnContext) throws AMQException; - - int size(); - - void clear(); - - UnacknowledgedMessage get(long deliveryTag); - - /** - * Get the set of delivery tags that are outstanding. - * - * @return a set of delivery tags - */ - Set<Long> getDeliveryTags(); - - public long getUnacknowledgeBytes(); -} - - diff --git a/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMapImpl.java b/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMapImpl.java deleted file mode 100644 index 1604d94539..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMapImpl.java +++ /dev/null @@ -1,235 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.ack; - -import java.util.Collection; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.queue.AMQMessage; -import org.apache.qpid.server.txn.TransactionalContext; - -public class UnacknowledgedMessageMapImpl implements UnacknowledgedMessageMap -{ - private final Object _lock = new Object(); - - private long _unackedSize; - - private Map<Long, UnacknowledgedMessage> _map; - - private long _lastDeliveryTag; - - private final int _prefetchLimit; - - public UnacknowledgedMessageMapImpl(int prefetchLimit) - { - _prefetchLimit = prefetchLimit; - _map = new LinkedHashMap<Long, UnacknowledgedMessage>(prefetchLimit); - } - - /*public UnacknowledgedMessageMapImpl(Object lock, Map<Long, UnacknowledgedMessage> map) - { - _lock = lock; - _map = map; - } */ - - public void collect(long deliveryTag, boolean multiple, List<UnacknowledgedMessage> msgs) - { - if (multiple) - { - collect(deliveryTag, msgs); - } - else - { - msgs.add(get(deliveryTag)); - } - - } - - public boolean contains(long deliveryTag) throws AMQException - { - synchronized (_lock) - { - return _map.containsKey(deliveryTag); - } - } - - public void remove(List<UnacknowledgedMessage> msgs) - { - synchronized (_lock) - { - for (UnacknowledgedMessage msg : msgs) - { - remove(msg.deliveryTag); - } - } - } - - public UnacknowledgedMessage remove(long deliveryTag) - { - synchronized (_lock) - { - - UnacknowledgedMessage message = _map.remove(deliveryTag); - if(message != null) - { - _unackedSize -= message.message.getSize(); - } - - return message; - } - } - - public void visit(Visitor visitor) throws AMQException - { - synchronized (_lock) - { - Collection<UnacknowledgedMessage> currentEntries = _map.values(); - for (UnacknowledgedMessage msg : currentEntries) - { - visitor.callback(msg); - } - visitor.visitComplete(); - } - } - - public Object getLock() - { - return _lock; - } - - public void add(long deliveryTag, UnacknowledgedMessage message) - { - synchronized (_lock) - { - _map.put(deliveryTag, message); - _unackedSize += message.message.getSize(); - _lastDeliveryTag = deliveryTag; - } - } - - public Collection<UnacknowledgedMessage> cancelAllMessages() - { - synchronized (_lock) - { - Collection<UnacknowledgedMessage> currentEntries = _map.values(); - _map = new LinkedHashMap<Long, UnacknowledgedMessage>(_prefetchLimit); - _unackedSize = 0l; - return currentEntries; - } - } - - public void acknowledgeMessage(long deliveryTag, boolean multiple, TransactionalContext txnContext) - throws AMQException - { - synchronized (_lock) - { - txnContext.acknowledgeMessage(deliveryTag, _lastDeliveryTag, multiple, this); - } - } - - public int size() - { - synchronized (_lock) - { - return _map.size(); - } - } - - public void clear() - { - synchronized (_lock) - { - _map.clear(); - _unackedSize = 0l; - } - } - - public void drainTo(Collection<UnacknowledgedMessage> destination, long deliveryTag) throws AMQException - { - synchronized (_lock) - { - Iterator<Map.Entry<Long, UnacknowledgedMessage>> it = _map.entrySet().iterator(); - while (it.hasNext()) - { - Map.Entry<Long, UnacknowledgedMessage> unacked = it.next(); - - if (unacked.getKey() > deliveryTag) - { - //This should not occur now. - throw new AMQException(null, "UnacknowledgedMessageMap is out of order:" + unacked.getKey() + - " When deliveryTag is:" + deliveryTag + "ES:" + _map.entrySet().toString(), null); - } - - it.remove(); - _unackedSize -= unacked.getValue().message.getSize(); - - destination.add(unacked.getValue()); - if (unacked.getKey() == deliveryTag) - { - break; - } - } - } - } - - public UnacknowledgedMessage get(long key) - { - synchronized (_lock) - { - return _map.get(key); - } - } - - public Set<Long> getDeliveryTags() - { - synchronized (_lock) - { - return _map.keySet(); - } - } - - private void collect(long key, List<UnacknowledgedMessage> msgs) - { - synchronized (_lock) - { - for (Map.Entry<Long, UnacknowledgedMessage> entry : _map.entrySet()) - { - msgs.add(entry.getValue()); - if (entry.getKey() == key) - { - break; - } - } - } - } - - public long getUnacknowledgeBytes() - { - return _unackedSize; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/Configurator.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/Configurator.java deleted file mode 100644 index 31c1b61a21..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/configuration/Configurator.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.configuration; - -import java.lang.reflect.Field; - -import org.apache.commons.configuration.Configuration; -import org.apache.log4j.Logger; -import org.apache.qpid.configuration.Configured; -import org.apache.qpid.configuration.PropertyException; -import org.apache.qpid.configuration.PropertyUtils; -import org.apache.qpid.server.registry.ApplicationRegistry; - -/** - * This class contains utilities for populating classes automatically from values pulled from configuration - * files. - */ -public class Configurator -{ - private static final Logger _logger = Logger.getLogger(Configurator.class); - - - /** - * Configure a given instance using the supplied configuration. Note that superclasses are <b>not</b> - * currently configured but this could easily be added if required. - * @param instance the instance to configure - * @param config the configuration to use to configure the object - */ - public static void configure(Object instance, Configuration config) - { - - for (Field f : instance.getClass().getDeclaredFields()) - { - Configured annotation = f.getAnnotation(Configured.class); - if (annotation != null) - { - setValueInField(f, instance, config, annotation); - } - } - } - - - - /** - * Configure a given instance using the application configuration. Note that superclasses are <b>not</b> - * currently configured but this could easily be added if required. - * @param instance the instance to configure - */ - public static void configure(Object instance) - { - configure(instance, ApplicationRegistry.getInstance().getConfiguration()); - } - - private static void setValueInField(Field f, Object instance, Configuration config, Configured annotation) - { - Class fieldClass = f.getType(); - String configPath = annotation.path(); - try - { - if (fieldClass == String.class) - { - String val = config.getString(configPath, annotation.defaultValue()); - val = PropertyUtils.replaceProperties(val); - f.set(instance, val); - } - else if (fieldClass == int.class) - { - int val = config.getInt(configPath, Integer.parseInt(annotation.defaultValue())); - f.setInt(instance, val); - } - else if (fieldClass == long.class) - { - long val = config.getLong(configPath, Long.parseLong(annotation.defaultValue())); - f.setLong(instance, val); - } - else if (fieldClass == double.class) - { - double val = config.getDouble(configPath, Double.parseDouble(annotation.defaultValue())); - f.setDouble(instance, val); - } - else if (fieldClass == boolean.class) - { - boolean val = config.getBoolean(configPath, Boolean.parseBoolean(annotation.defaultValue())); - f.setBoolean(instance, val); - } - else - { - _logger.error("Unsupported field type " + fieldClass + " for " + f + " IGNORING configured value"); - } - } - catch (PropertyException e) - { - _logger.error("Unable to expand property: " + e + " INGORING field " + f, e); - } - catch (IllegalAccessException e) - { - _logger.error("Unable to access field " + f + " IGNORING configured value"); - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfiguration.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfiguration.java deleted file mode 100644 index d1589092e9..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfiguration.java +++ /dev/null @@ -1,290 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.configuration; - -import java.util.Collections; -import java.util.List; - -import org.apache.commons.configuration.CompositeConfiguration; -import org.apache.commons.configuration.Configuration; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.configuration.XMLConfiguration; -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.exchange.ExchangeRegistry; -import org.apache.qpid.server.exchange.ExchangeFactory; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.QueueRegistry; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.exception.InternalErrorException; -import org.apache.qpid.server.exception.QueueAlreadyExistsException; - -public class VirtualHostConfiguration -{ - private static final Logger _logger = Logger.getLogger(VirtualHostConfiguration.class); - - private static XMLConfiguration _config; - - private static final String VIRTUALHOST_PROPERTY_BASE = "virtualhost."; - - - public VirtualHostConfiguration(String configFile) - throws - ConfigurationException - { - _logger.info("Loading Config file:" + configFile); - - _config = new XMLConfiguration(configFile); - - } - - - private void configureVirtualHost(String virtualHostName, Configuration configuration) - throws - ConfigurationException, - AMQException - { - _logger.debug("Loding configuration for virtaulhost: " + virtualHostName); - - - VirtualHost virtualHost = ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost(virtualHostName); - - - if (virtualHost == null) - { - throw new ConfigurationException("Unknown virtual host: " + virtualHostName); - } - - List exchangeNames = configuration.getList("exchanges.exchange.name"); - - for (Object exchangeNameObj : exchangeNames) - { - String exchangeName = String.valueOf(exchangeNameObj); - configureExchange(virtualHost, exchangeName, configuration); - } - - - List queueNames = configuration.getList("queues.queue.name"); - - for (Object queueNameObj : queueNames) - { - String queueName = String.valueOf(queueNameObj); - configureQueue(virtualHost, queueName, configuration); - } - - } - - private void configureExchange(VirtualHost virtualHost, String exchangeNameString, Configuration configuration) - throws - AMQException - { - - CompositeConfiguration exchangeConfiguration = new CompositeConfiguration(); - - exchangeConfiguration.addConfiguration(configuration.subset("exchanges.exchange." + exchangeNameString)); - exchangeConfiguration.addConfiguration(configuration.subset("exchanges")); - - QueueRegistry queueRegistry = virtualHost.getQueueRegistry(); - MessageStore messageStore = virtualHost.getMessageStore(); - ExchangeRegistry exchangeRegistry = virtualHost.getExchangeRegistry(); - ExchangeFactory exchangeFactory = virtualHost.getExchangeFactory(); - - AMQShortString exchangeName = new AMQShortString(exchangeNameString); - - - Exchange exchange; - - - synchronized (exchangeRegistry) - { - exchange = exchangeRegistry.getExchange(exchangeName); - if (exchange == null) - { - - AMQShortString type = new AMQShortString(exchangeConfiguration.getString("type", "direct")); - boolean durable = exchangeConfiguration.getBoolean("durable", false); - boolean autodelete = exchangeConfiguration.getBoolean("autodelete", false); - - Exchange newExchange = exchangeFactory.createExchange(exchangeName, type, durable, autodelete, 0); - exchangeRegistry.registerExchange(newExchange); - } - - } - } - - public static CompositeConfiguration getDefaultQueueConfiguration(AMQQueue queue) - { - CompositeConfiguration queueConfiguration = null; - if (_config == null) - return null; - - Configuration vHostConfiguration = _config.subset(VIRTUALHOST_PROPERTY_BASE + queue.getVirtualHost().getName()); - - if (vHostConfiguration == null) - return null; - - Configuration defaultQueueConfiguration = vHostConfiguration.subset("queues"); - if (defaultQueueConfiguration != null) - { - queueConfiguration = new CompositeConfiguration(); - queueConfiguration.addConfiguration(defaultQueueConfiguration); - } - - return queueConfiguration; - } - - private void configureQueue(VirtualHost virtualHost, String queueNameString, Configuration configuration) - throws - AMQException, - ConfigurationException - { - CompositeConfiguration queueConfiguration = new CompositeConfiguration(); - - queueConfiguration.addConfiguration(configuration.subset("queues.queue." + queueNameString)); - queueConfiguration.addConfiguration(configuration.subset("queues")); - - QueueRegistry queueRegistry = virtualHost.getQueueRegistry(); - MessageStore messageStore = virtualHost.getMessageStore(); - ExchangeRegistry exchangeRegistry = virtualHost.getExchangeRegistry(); - - - AMQShortString queueName = new AMQShortString(queueNameString); - - AMQQueue queue; - - synchronized (queueRegistry) - { - queue = queueRegistry.getQueue(queueName); - - if (queue == null) - { - _logger.info("Creating queue '" + queueName + "' on virtual host " + virtualHost.getName()); - - boolean durable = queueConfiguration.getBoolean("durable", false); - boolean autodelete = queueConfiguration.getBoolean("autodelete", false); - String owner = queueConfiguration.getString("owner", null); - - queue = new AMQQueue(queueName, - durable, - owner == null ? null : new AMQShortString(owner) /* These queues will have no owner */, - autodelete /* Therefore autodelete makes no sence */, virtualHost); - - if (queue.isDurable()) - { - - messageStore.createQueue(queue); - //DTX MessageStore -// try -// { -// messageStore.createQueue(queue); -// } catch (InternalErrorException e) -// { -// _logger.error("Problem when creating Queue '" + queueNameString -// + "' on virtual host " + virtualHost.getName() + ", not creating."); -// -// } catch (QueueAlreadyExistsException e) -// { -// _logger.error("Queue '" + queueNameString -// + "' already exists on virtual host " + virtualHost.getName() + ", not creating."); -// } - } - - queueRegistry.registerQueue(queue); - } else - { - _logger.info("Queue '" + queueNameString + "' already exists on virtual host " + virtualHost.getName() + ", not creating."); - } - - String exchangeName = queueConfiguration.getString("exchange", null); - - Exchange exchange = exchangeRegistry.getExchange(exchangeName == null ? null : new AMQShortString(exchangeName)); - - if (exchange == null) - { - exchange = virtualHost.getExchangeRegistry().getDefaultExchange(); - } - - if (exchange == null) - { - throw new ConfigurationException("Attempt to bind queue to unknown exchange:" + exchangeName); - } - - synchronized (exchange) - { - List routingKeys = queueConfiguration.getList("routingKey"); - if (routingKeys == null || routingKeys.isEmpty()) - { - routingKeys = Collections.singletonList(queue.getName()); - } - - for (Object routingKeyNameObj : routingKeys) - { - AMQShortString routingKey = new AMQShortString(String.valueOf(routingKeyNameObj)); - - - queue.bind(routingKey, null, exchange); - - - _logger.info("Queue '" + queue.getName() + "' bound to exchange:" + exchangeName + " RK:'" + routingKey + "'"); - } - - if (exchange != virtualHost.getExchangeRegistry().getDefaultExchange()) - { - queue.bind(queue.getName(), null, virtualHost.getExchangeRegistry().getDefaultExchange()); - } - } - - } - - - Configurator.configure(queue, queueConfiguration); - } - - - public void performBindings() throws AMQException, ConfigurationException - { - List virtualHostNames = _config.getList(VIRTUALHOST_PROPERTY_BASE + "name"); - String defaultVirtualHostName = _config.getString("default"); - if (defaultVirtualHostName != null) - { - ApplicationRegistry.getInstance().getVirtualHostRegistry().setDefaultVirtualHostName(defaultVirtualHostName); - } - _logger.info("Configuring " + virtualHostNames == null ? 0 : virtualHostNames.size() + " virtual hosts: " + virtualHostNames); - - for (Object nameObject : virtualHostNames) - { - String name = String.valueOf(nameObject); - configureVirtualHost(name, _config.subset(VIRTUALHOST_PROPERTY_BASE + name)); - } - - if (virtualHostNames == null || virtualHostNames.isEmpty()) - { - throw new ConfigurationException( - "Virtualhost Configuration document does not contain a valid virtualhost."); - } - } - - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/exception/CommandInvalidException.java b/java/broker/src/main/java/org/apache/qpid/server/exception/CommandInvalidException.java deleted file mode 100644 index 2b5fbf9795..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/exception/CommandInvalidException.java +++ /dev/null @@ -1,66 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.qpid.server.exception;
-
-/**
- * CommandInvalidException indicates that an innapropriate request has been made to a transaction manager. For example,
- * calling prepare on an already prepared transaction.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represents an error due to an innapropriate request to a transction manager.
- * </table>
- */
-public class CommandInvalidException extends Exception
-{
- /**
- * Constructs a new CommandInvalidException with the specified detail message and
- * cause.
- *
- * @param message the detail message .
- * @param cause the cause.
- */
- public CommandInvalidException(String message, Throwable cause)
- {
- super(message, cause);
- }
-
- /**
- * Constructs a new CommandInvalidException with the specified detail message.
- *
- * @param message the detail message.
- *
- * @deprected
- */
- public CommandInvalidException(String message)
- {
- super(message);
- }
-
- /**
- * Constructs a new CommandInvalidException with the specified cause.
- *
- * @param cause the cause
- *
- * @deprected
- */
- public CommandInvalidException(Throwable cause)
- {
- super(cause);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exception/InternalErrorException.java b/java/broker/src/main/java/org/apache/qpid/server/exception/InternalErrorException.java deleted file mode 100644 index 60e1514d2b..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/exception/InternalErrorException.java +++ /dev/null @@ -1,68 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.qpid.server.exception;
-
-/**
- * General purpose exception for non-specifc error cases. Do not use.
- *
- * @deprected Far too broad to be a checked exception. Will be abused as a "don't know what to do with it" exception
- * when Runtimes should be used. If this has a specific meaning within transaction managers, it should
- * be renamed to something like TxManagerException, for example. At the moment, transaction managers are not
- * catching this exception and taking some action, so it is clear that it is being used for errors that are
- * not recoverable/handleable from; use runtimes. So far, it is only caught to be rethrown as AMQException,
- * which is the other catch-all exception case to be eliminated. There are sequences in the code where
- * AMQException is caught and rethrown as InternalErrorException, which is cause and rethrown as AMQException.
- */
-public class InternalErrorException extends Exception
-{
- /**
- * Constructs a new InternalErrorException with the specified detail message.
- *
- * @param message the detail message.
- *
- * @deprected
- */
- public InternalErrorException(String message)
- {
- super(message);
- }
-
- /**
- * Constructs a new InternalErrorException with the specified detail message and
- * cause.
- *
- * @param message the detail message .
- * @param cause the cause.
- */
- public InternalErrorException(String message, Throwable cause)
- {
- super(message, cause);
- }
-
- /**
- * Constructs a new InternalErrorException with the specified cause.
- *
- * @param cause the cause
- *
- * @deprected
- */
- public InternalErrorException(Throwable cause)
- {
- super(cause);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exception/InvalidXidException.java b/java/broker/src/main/java/org/apache/qpid/server/exception/InvalidXidException.java deleted file mode 100644 index 277614afff..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/exception/InvalidXidException.java +++ /dev/null @@ -1,82 +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.exception;
-
-import javax.transaction.xa.Xid;
-
-/**
- * InvalidXidException indicates that an Xid under which to conduct a transaction is invalid. This may be because it
- * has an incorrect format, is null, or a transcaction with the same Xid is already running.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represents an invalid Xid for a transaction.
- * <tr><td>
- */
-public class InvalidXidException extends Exception
-{
- /**
- * Constructs a newr InvalidXidException with a standard message
- *
- * @param xid The invalid xid.
- *
- * @deprected
- */
- public InvalidXidException(Xid xid)
- {
- super("The Xid: " + xid + " is invalid");
- }
-
- /**
- * Constructs a newr InvalidXidException with a cause
- *
- * @param xid The invalid xid.
- * @param cause The casue for the xid to be invalid
- *
- * @deprected
- */
- public InvalidXidException(Xid xid, Throwable cause)
- {
- super("The Xid: " + xid + " is invalid", cause);
- }
-
- /**
- * Constructs a newr InvalidXidException with a reason message
- *
- * @param reason The reason why the xid is invalid
- * @param xid The invalid xid.
- */
- public InvalidXidException(Xid xid, String reason)
- {
- super("The Xid: " + xid + " is invalid, The reason is: " + reason);
- }
-
- /**
- * Constructs a newr InvalidXidException with a reason message and cause
- *
- * @param reason The reason why the xid is invalid
- * @param xid The invalid xid.
- * @param cause The casue for the xid to be invalid
- *
- * @deprected
- */
- public InvalidXidException(Xid xid, String reason, Throwable cause)
- {
- super("The Xid: " + xid + " is invalid, The reason is: " + reason, cause);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exception/MessageAlreadyStagedException.java b/java/broker/src/main/java/org/apache/qpid/server/exception/MessageAlreadyStagedException.java deleted file mode 100644 index 336f5fdf64..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/exception/MessageAlreadyStagedException.java +++ /dev/null @@ -1,60 +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.exception;
-
-/**
- * @todo Need to understand what message staging is to document properly.
- */
-public class MessageAlreadyStagedException extends Exception
-{
- /**
- * Constructs a new MessageAlreadyStagedException with the specified detail message.
- *
- * @param message the detail message.
- */
- public MessageAlreadyStagedException(String message)
- {
- super(message);
- }
-
- /**
- * Constructs a new MessageAlreadyStagedException with the specified detail message and
- * cause.
- *
- * @param message the detail message .
- * @param cause the cause.
- *
- * @deprected
- */
- public MessageAlreadyStagedException(String message, Throwable cause)
- {
- super(message, cause);
- }
-
- /**
- * Constructs a new MessageAlreadyStagedException with the specified cause.
- *
- * @param cause the cause
- *
- * @deprected
- */
- public MessageAlreadyStagedException(Throwable cause)
- {
- super(cause);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exception/MessageDoesntExistException.java b/java/broker/src/main/java/org/apache/qpid/server/exception/MessageDoesntExistException.java deleted file mode 100644 index 544d669d4b..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/exception/MessageDoesntExistException.java +++ /dev/null @@ -1,66 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.qpid.server.exception;
-
-/**
- * MessageDoesntExistException indicates that a message store cannot find a message looked up by its id. This may
- * indicate message loss.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represents failure of message store to find a message.
- * </table>
- */
-public class MessageDoesntExistException extends Exception
-{
- /**
- * Constructs a new MessageDoesntExistException with the specified detail message.
- *
- * @param message the detail message.
- */
- public MessageDoesntExistException(String message)
- {
- super(message);
- }
-
- /**
- * Constructs a new MessageDoesntExistException with the specified detail message and
- * cause.
- *
- * @param message the detail message .
- * @param cause the cause.
- *
- * @deprected
- */
- public MessageDoesntExistException(String message, Throwable cause)
- {
- super(message, cause);
- }
-
- /**
- * Constructs a new MessageDoesntExistException with the specified cause.
- *
- * @param cause the cause
- *
- * @deprected
- */
- public MessageDoesntExistException(Throwable cause)
- {
- super(cause);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exception/NotPreparedException.java b/java/broker/src/main/java/org/apache/qpid/server/exception/NotPreparedException.java deleted file mode 100644 index ab288748f5..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/exception/NotPreparedException.java +++ /dev/null @@ -1,67 +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.exception;
-
-/**
- * NotPreparedException indicates a failure to commit a transaction that has not been prepared.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represents failure to commit an unprepared transaction.
- * </table>
- *
- * @todo There is already a CommandInvalidException which would seem to cover this too. Use it instead?
- */
-public class NotPreparedException extends Exception
-{
- /**
- * Constructs a new NotPreparedException with the specified detail message.
- *
- * @param message the detail message.
- */
- public NotPreparedException(String message)
- {
- super(message);
- }
-
- /**
- * Constructs a new NotPreparedException with the specified detail message and
- * cause.
- *
- * @param message the detail message .
- * @param cause the cause.
- *
- * @deprecated
- */
- public NotPreparedException(String message, Throwable cause)
- {
- super(message, cause);
- }
-
- /**
- * Constructs a new NotPreparedException with the specified cause.
- *
- * @param cause the cause
- *
- * @deprected
- */
- public NotPreparedException(Throwable cause)
- {
- super(cause);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exception/QueueAlreadyExistsException.java b/java/broker/src/main/java/org/apache/qpid/server/exception/QueueAlreadyExistsException.java deleted file mode 100644 index 3635d2c19d..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/exception/QueueAlreadyExistsException.java +++ /dev/null @@ -1,65 +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.exception;
-
-/**
- * QueueAlreadyExistsException inidicates failure of a message store to create a queue that already exists.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represents failure to create a queue that already exists.
- * </table>
- */
-public class QueueAlreadyExistsException extends Exception
-{
- /**
- * Constructs a new QueueAlreadyExistsException with the specified detail message.
- *
- * @param message the detail message.
- */
- public QueueAlreadyExistsException(String message)
- {
- super(message);
- }
-
- /**
- * Constructs a new QueueAlreadyExistsException with the specified detail message and
- * cause.
- *
- * @param message the detail message .
- * @param cause the cause.
- *
- * @deprecated
- */
- public QueueAlreadyExistsException(String message, Throwable cause)
- {
- super(message, cause);
- }
-
- /**
- * Constructs a new QueueDoesntExistException with the specified cause.
- *
- * @param cause the cause
- *
- * @deprecated
- */
- public QueueAlreadyExistsException(Throwable cause)
- {
- super(cause);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exception/QueueDoesntExistException.java b/java/broker/src/main/java/org/apache/qpid/server/exception/QueueDoesntExistException.java deleted file mode 100644 index d05c152228..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/exception/QueueDoesntExistException.java +++ /dev/null @@ -1,65 +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.exception;
-
-/**
- * MessageDoesntExistException indicates that a message store cannot find a queue.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represents failure to find a queue on a message store.
- * </table>
- */
-public class QueueDoesntExistException extends Exception
-{
- /**
- * Constructs a new QueueDoesntExistException with the specified detail message.
- *
- * @param message the detail message.
- */
- public QueueDoesntExistException(String message)
- {
- super(message);
- }
-
- /**
- * Constructs a new QueueDoesntExistException with the specified detail message and
- * cause.
- *
- * @param message the detail message .
- * @param cause the cause.
- *
- * @deprecated
- */
- public QueueDoesntExistException(String message, Throwable cause)
- {
- super(message, cause);
- }
-
- /**
- * Constructs a new QueueDoesntExistException with the specified cause.
- *
- * @param cause the cause
- *
- * @deprecated
- */
- public QueueDoesntExistException(Throwable cause)
- {
- super(cause);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exception/UnknownXidException.java b/java/broker/src/main/java/org/apache/qpid/server/exception/UnknownXidException.java deleted file mode 100644 index e4a5de8ecb..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/exception/UnknownXidException.java +++ /dev/null @@ -1,85 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.qpid.server.exception;
-
-import javax.transaction.xa.Xid;
-
-/**
- * UnknownXidException indicates that an Xid under which a transactional operation is to be run is not known.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represents failure of a transaction manager to recognize an Xid.
- * </table>
- *
- * @todo Already have an InvalidXidException, this might be splitting things too far? There are cases where invalid is
- * caught and rethrown as unknown. What is unknown specifically used for that invalid is not? For example, when
- * recovering, is it important to distinguish between invalid and unknown?
- */
-public class UnknownXidException extends Exception
-{
- /**
- * Constructs a newr UnknownXidException with a standard message
- *
- * @param xid The unknown xid.
- *
- * @deprecated
- */
- public UnknownXidException(Xid xid)
- {
- super("The Xid: " + xid + " is unknown");
- }
-
- /**
- * Constructs a newr UnknownXidException with a cause
- *
- * @param xid The unknown xid.
- * @param cause The casue for the xid to be unknown
- */
- public UnknownXidException(Xid xid, Throwable cause)
- {
- super("The Xid: " + xid + " is unknown", cause);
- }
-
- /**
- * Constructs a newr UnknownXidException with a reason message
- *
- * @param reason The reason why the xid is unknown
- * @param xid The unknown xid.
- *
- * @deprecated
- */
- /*public UnknownXidException(Xid xid, String reason)
- {
- super("The Xid: " + xid + " is unknown, The reason is: " + reason);
- }*/
-
- /**
- * Constructs a newr UnknownXidException with a reason message and cause
- *
- * @param reason The reason why the xid is unknown
- * @param xid The unknown xid.
- * @param cause The casue for the xid to be unknown
- *
- * @deprected
- */
- public UnknownXidException(Xid xid, String reason, Throwable cause)
- {
- super("The Xid: " + xid + " is unknown, The reason is: " + reason, cause);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/AbstractExchange.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/AbstractExchange.java deleted file mode 100644 index 0558906fb6..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/exchange/AbstractExchange.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.exchange; - -import javax.management.MalformedObjectNameException; -import javax.management.NotCompliantMBeanException; -import javax.management.ObjectName; -import javax.management.openmbean.OpenType; -import javax.management.openmbean.CompositeType; -import javax.management.openmbean.TabularType; -import javax.management.openmbean.TabularDataSupport; -import javax.management.openmbean.OpenDataException; -import javax.management.openmbean.SimpleType; -import javax.management.openmbean.ArrayType; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.management.AMQManagedObject; -import org.apache.qpid.server.management.Managable; -import org.apache.qpid.server.management.ManagedObject; -import org.apache.qpid.server.management.ManagedObjectRegistry; -import org.apache.qpid.server.queue.QueueRegistry; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.virtualhost.VirtualHost; - -import java.util.List; -import java.util.Map; - -public abstract class AbstractExchange implements Exchange, Managable -{ - private AMQShortString _name; - - protected boolean _durable; - protected String _exchangeType; - - private VirtualHost _virtualHost; - - protected ExchangeMBean _exchangeMbean; - - /** - * Whether the exchange is automatically deleted once all queues have detached from it - */ - protected boolean _autoDelete; - - /** - * Abstract MBean class. This has some of the methods implemented from - * management intrerface for exchanges. Any implementaion of an - * Exchange MBean should extend this class. - */ - protected abstract class ExchangeMBean extends AMQManagedObject implements ManagedExchange - { - // open mbean data types for representing exchange bindings - protected String[] _bindingItemNames; - protected String[] _bindingItemIndexNames; - protected OpenType[] _bindingItemTypes; - protected CompositeType _bindingDataType; - protected TabularType _bindinglistDataType; - protected TabularDataSupport _bindingList; - - public ExchangeMBean() throws NotCompliantMBeanException - { - super(ManagedExchange.class, ManagedExchange.TYPE); - } - - protected void init() throws OpenDataException - { - _bindingItemNames = new String[]{"Binding Key", "Queue Names"}; - _bindingItemIndexNames = new String[]{_bindingItemNames[0]}; - - _bindingItemTypes = new OpenType[2]; - _bindingItemTypes[0] = SimpleType.STRING; - _bindingItemTypes[1] = new ArrayType(1, SimpleType.STRING); - _bindingDataType = new CompositeType("Exchange Binding", "Binding key and Queue names", - _bindingItemNames, _bindingItemNames, _bindingItemTypes); - _bindinglistDataType = new TabularType("Exchange Bindings", "Exchange Bindings for " + getName(), - _bindingDataType, _bindingItemIndexNames); - } - - public ManagedObject getParentObject() - { - return _virtualHost.getManagedObject(); - } - - public String getObjectInstanceName() - { - return _name.toString(); - } - - public String getName() - { - return _name.toString(); - } - - public String getExchangeType() - { - return _exchangeType; - } - - public boolean isDurable() - { - return _durable; - } - - public boolean isAutoDelete() - { - return _autoDelete; - } - - // Added exchangetype in the object name lets maangement apps to do any customization required - public ObjectName getObjectName() throws MalformedObjectNameException - { - String objNameString = super.getObjectName().toString(); - objNameString = objNameString + ",ExchangeType=" + _exchangeType; - return new ObjectName(objNameString); - } - - protected ManagedObjectRegistry getManagedObjectRegistry() - { - return ApplicationRegistry.getInstance().getManagedObjectRegistry(); - } - } // End of MBean class - - public AMQShortString getName() - { - return _name; - } - - /** - * Concrete exchanges must implement this method in order to create the managed representation. This is - * called during initialisation (template method pattern). - * @return the MBean - */ - protected abstract ExchangeMBean createMBean() throws AMQException; - - public void initialise(VirtualHost host, AMQShortString name, boolean durable, boolean autoDelete) throws AMQException - { - _virtualHost = host; - _name = name; - _durable = durable; - _autoDelete = autoDelete; - _exchangeMbean = createMBean(); - _exchangeMbean.register(); - } - - public boolean isDurable() - { - return _durable; - } - - public boolean isAutoDelete() - { - return _autoDelete; - } - - public void close() throws AMQException - { - if (_exchangeMbean != null) - { - _exchangeMbean.unregister(); - } - } - - abstract public Map<AMQShortString, List<AMQQueue>> getBindings(); - - public String toString() - { - return getClass().getName() + "[" + getName() +"]"; - } - - public ManagedObject getManagedObject() - { - return _exchangeMbean; - } - - public VirtualHost getVirtualHost() - { - return _virtualHost; - } - - public QueueRegistry getQueueRegistry() - { - return getVirtualHost().getQueueRegistry(); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeFactory.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeFactory.java deleted file mode 100644 index e3b715d45f..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeFactory.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.exchange; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.log4j.Logger; -import org.apache.commons.configuration.Configuration; - -import org.apache.qpid.AMQException; -import org.apache.qpid.AMQUnknownExchangeType; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.virtualhost.VirtualHost; - -public class DefaultExchangeFactory implements ExchangeFactory -{ - private static final Logger _logger = Logger.getLogger(DefaultExchangeFactory.class); - - private Map<AMQShortString, ExchangeType<? extends Exchange>> _exchangeClassMap = new HashMap<AMQShortString, ExchangeType<? extends Exchange>>(); - private final VirtualHost _host; - - public DefaultExchangeFactory(VirtualHost host) - { - _host = host; - registerExchangeType(DestNameExchange.TYPE); - registerExchangeType(DestWildExchange.TYPE); - registerExchangeType(HeadersExchange.TYPE); - registerExchangeType(FanoutExchange.TYPE); - - } - - public void registerExchangeType(ExchangeType<? extends Exchange> type) - { - _exchangeClassMap.put(type.getName(), type); - } - - public Exchange createExchange(AMQShortString exchange, AMQShortString type, boolean durable, boolean autoDelete, - int ticket) - throws AMQException - { - ExchangeType<? extends Exchange> exchType = _exchangeClassMap.get(type); - if (exchType == null) - { - - throw new AMQUnknownExchangeType("Unknown exchange type: " + type, null); - } - Exchange e = exchType.newInstance(_host, exchange, durable, autoDelete); - return e; - } - - public void initialise(Configuration hostConfig) - { - for(Object className : hostConfig.getList("custom-exchanges.class-name")) - { - try - { - Class<? extends ExchangeType> exchangeTypeClass = (Class<? extends ExchangeType>) Class.forName(String.valueOf(className)); - ExchangeType type = exchangeTypeClass.newInstance(); - registerExchangeType(type); - - } - catch (ClassNotFoundException e) - { - _logger.error("No such custom exchange class found: \""+String.valueOf(className)+"\""); - } - catch (ClassCastException classCastEx) - { - _logger.error("No custom exchange class: \""+String.valueOf(className)+"\" cannot be registered as it does not extend class \""+ExchangeType.class+"\""); - } - catch (IllegalAccessException e) - { - _logger.error("Cannot create custom exchange class: \""+String.valueOf(className)+"\"",e); - } - catch (InstantiationException e) - { - _logger.error("Cannot create custom exchange class: \""+String.valueOf(className)+"\"",e); - } - } - - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeRegistry.java deleted file mode 100644 index 23a4bec6bd..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeRegistry.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.exchange; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.exception.InternalErrorException; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.protocol.ExchangeInitialiser; -import org.apache.qpid.server.queue.AMQMessage; -import org.apache.qpid.server.virtualhost.VirtualHost; - -import java.util.Collection; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -public class DefaultExchangeRegistry implements ExchangeRegistry -{ - private static final Logger _log = Logger.getLogger(DefaultExchangeRegistry.class); - - /** - * Maps from exchange name to exchange instance - */ - private ConcurrentMap<AMQShortString, Exchange> _exchangeMap = new ConcurrentHashMap<AMQShortString, Exchange>(); - - private Exchange _defaultExchange; - private VirtualHost _host; - - public DefaultExchangeRegistry(VirtualHost host) - { - //create 'standard' exchanges: - _host = host; - - } - - public void initialise() throws AMQException - { - new ExchangeInitialiser().initialise(_host.getExchangeFactory(), this); - } - - public MessageStore getMessageStore() - { - return _host.getMessageStore(); - } - - public void registerExchange(Exchange exchange) throws AMQException - { - _exchangeMap.put(exchange.getName(), exchange); - if(exchange.isDurable()) - { - getMessageStore().createExchange(exchange); - //DTX MessageStore -// try -// { -// getMessageStore().createExchange(exchange); -// } catch (InternalErrorException e) -// { -// throw new AMQException(null, "problem registering excahgne " + exchange, e); -// } - } - } - - public void setDefaultExchange(Exchange exchange) - { - _defaultExchange = exchange; - } - - public Exchange getDefaultExchange() - { - return _defaultExchange; - } - - public Collection<AMQShortString> getExchangeNames() - { - return _exchangeMap.keySet(); - } - - public void unregisterExchange(AMQShortString name, boolean inUse) throws AMQException - { - // TODO: check inUse argument - Exchange e = _exchangeMap.remove(name); - if (e != null) - { - if (e.isDurable()) - { - getMessageStore().removeExchange(e); - //DTX MessageStore -// try -// { -// getMessageStore().removeExchange(e); -// } catch (InternalErrorException e1) -// { -// throw new AMQException(null, "Problem unregistering Exchange " + name, e1); -// } - } - e.close(); - } - else - { - throw new AMQException(null, "Unknown exchange " + name, null); - } - } - - public Exchange getExchange(AMQShortString name) - { - if((name == null) || name.length() == 0) - { - return getDefaultExchange(); - } - else - { - return _exchangeMap.get(name); - } - - } - - /** - * Routes content through exchanges, delivering it to 1 or more queues. - * @param payload - * @throws AMQException if something goes wrong delivering data - */ - public void routeContent(AMQMessage payload) throws AMQException - { - final AMQShortString exchange = payload.getMessagePublishInfo().getExchange(); - final Exchange exch = getExchange(exchange); - // there is a small window of opportunity for the exchange to be deleted in between - // the BasicPublish being received (where the exchange is validated) and the final - // content body being received (which triggers this method) - // TODO: check where the exchange is validated - if (exch == null) - { - throw new AMQException(null, "Exchange '" + exchange + "' does not exist", null); - } - exch.route(payload); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/DestNameExchange.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/DestNameExchange.java deleted file mode 100644 index d1cc9b892f..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/exchange/DestNameExchange.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.exchange; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.abstraction.MessagePublishInfo; -import org.apache.qpid.server.management.MBeanConstructor; -import org.apache.qpid.server.management.MBeanDescription; -import org.apache.qpid.server.queue.AMQMessage; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.virtualhost.VirtualHost; - -import javax.management.JMException; -import javax.management.MBeanException; -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.CompositeDataSupport; -import javax.management.openmbean.OpenDataException; -import javax.management.openmbean.TabularData; -import javax.management.openmbean.TabularDataSupport; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -public class DestNameExchange extends AbstractExchange -{ - private static final Logger _logger = Logger.getLogger(DestNameExchange.class); - - /** - * Maps from queue name to queue instances - */ - private final Index _index = new Index(); - - public static final ExchangeType<DestNameExchange> TYPE = new ExchangeType<DestNameExchange>() - { - - public AMQShortString getName() - { - return ExchangeDefaults.DIRECT_EXCHANGE_CLASS; - } - - public Class<DestNameExchange> getExchangeClass() - { - return DestNameExchange.class; - } - - public DestNameExchange newInstance(VirtualHost host, - AMQShortString name, - boolean durable, - boolean autoDelete) throws AMQException - { - DestNameExchange exch = new DestNameExchange(); - exch.initialise(host, name, durable, autoDelete); - return exch; - } - }; - - /** - * MBean class implementing the management interfaces. - */ - @MBeanDescription("Management Bean for Direct Exchange") - private final class DestNameExchangeMBean extends ExchangeMBean - { - @MBeanConstructor("Creates an MBean for AMQ direct exchange") - public DestNameExchangeMBean() throws JMException - { - super(); - _exchangeType = "direct"; - init(); - } - - public TabularData bindings() throws OpenDataException - { - Map<AMQShortString, List<AMQQueue>> bindings = _index.getBindingsMap(); - _bindingList = new TabularDataSupport(_bindinglistDataType); - - for (Map.Entry<AMQShortString, List<AMQQueue>> entry : bindings.entrySet()) - { - AMQShortString key = entry.getKey(); - List<String> queueList = new ArrayList<String>(); - - List<AMQQueue> queues = entry.getValue(); - for (AMQQueue q : queues) - { - queueList.add(q.getName().toString()); - } - - Object[] bindingItemValues = {key.toString(), queueList.toArray(new String[0])}; - CompositeData bindingData = new CompositeDataSupport(_bindingDataType, _bindingItemNames, bindingItemValues); - _bindingList.put(bindingData); - } - - return _bindingList; - } - - public void createNewBinding(String queueName, String binding) throws JMException - { - AMQQueue queue = getQueueRegistry().getQueue(new AMQShortString(queueName)); - if (queue == null) - { - throw new JMException("Queue \"" + queueName + "\" is not registered with the exchange."); - } - - try - { - queue.bind(new AMQShortString(binding), null, DestNameExchange.this); - } - catch (AMQException ex) - { - throw new MBeanException(ex); - } - } - - }// End of MBean class - - - protected ExchangeMBean createMBean() throws AMQException - { - try - { - return new DestNameExchangeMBean(); - } - catch (JMException ex) - { - _logger.error("Exception occured in creating the direct exchange mbean", ex); - throw new AMQException(null, "Exception occured in creating the direct exchange mbean", ex); - } - } - - public AMQShortString getType() - { - return ExchangeDefaults.DIRECT_EXCHANGE_CLASS; - } - - public void registerQueue(AMQShortString routingKey, AMQQueue queue, FieldTable args) throws AMQException - { - assert queue != null; - assert routingKey != null; - if (!_index.add(routingKey, queue)) - { - _logger.debug("Queue " + queue + " is already registered with routing key " + routingKey); - } - else - { - _logger.debug("Binding queue " + queue + " with routing key " + routingKey + " to exchange " + this); - } - } - - public void deregisterQueue(AMQShortString routingKey, AMQQueue queue, FieldTable args) throws AMQException - { - assert queue != null; - assert routingKey != null; - - if (!_index.remove(routingKey, queue)) - { - throw new AMQException(null, "Queue " + queue + " was not registered with exchange " + this.getName() + - " with routing key " + routingKey + ". No queue was registered with that routing key", null); - } - } - - public void route(AMQMessage payload) throws AMQException - { - final MessagePublishInfo info = payload.getMessagePublishInfo(); - final AMQShortString routingKey = info.getRoutingKey(); - final List<AMQQueue> queues = (routingKey == null) ? null : _index.get(routingKey); - if (queues == null || queues.isEmpty()) - { - String msg = "Routing key " + routingKey + " is not known to " + this; - if (info.isMandatory() || info.isImmediate()) - { - throw new NoRouteException(msg, payload, null); - } - else - { - _logger.error("MESSAGE LOSS: Message should be sent on a Dead Letter Queue"); - _logger.warn(msg); - } - } - else - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Publishing message to queue " + queues); - } - - for (AMQQueue q : queues) - { - payload.enqueue(q); - } - } - } - - public boolean isBound(AMQShortString routingKey, FieldTable arguments, AMQQueue queue) - { - return isBound(routingKey, queue); - } - - public boolean isBound(AMQShortString routingKey, AMQQueue queue) - { - final List<AMQQueue> queues = _index.get(routingKey); - return queues != null && queues.contains(queue); - } - - public boolean isBound(AMQShortString routingKey) - { - final List<AMQQueue> queues = _index.get(routingKey); - return queues != null && !queues.isEmpty(); - } - - public boolean isBound(AMQQueue queue) - { - Map<AMQShortString, List<AMQQueue>> bindings = _index.getBindingsMap(); - for (List<AMQQueue> queues : bindings.values()) - { - if (queues.contains(queue)) - { - return true; - } - } - return false; - } - - public boolean hasBindings() - { - return !_index.getBindingsMap().isEmpty(); - } - - public Map<AMQShortString, List<AMQQueue>> getBindings() - { - return _index.getBindingsMap(); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/DestWildExchange.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/DestWildExchange.java deleted file mode 100644 index 25dc32fd41..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/exchange/DestWildExchange.java +++ /dev/null @@ -1,453 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.exchange; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.abstraction.MessagePublishInfo; -import org.apache.qpid.server.management.MBeanConstructor; -import org.apache.qpid.server.management.MBeanDescription; -import org.apache.qpid.server.queue.AMQMessage; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.virtualhost.VirtualHost; - -import javax.management.JMException; -import javax.management.MBeanException; -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.CompositeDataSupport; -import javax.management.openmbean.OpenDataException; -import javax.management.openmbean.TabularData; -import javax.management.openmbean.TabularDataSupport; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.StringTokenizer; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CopyOnWriteArrayList; - -public class DestWildExchange extends AbstractExchange -{ - - public static final ExchangeType<DestWildExchange> TYPE = new ExchangeType<DestWildExchange>() - { - - public AMQShortString getName() - { - return ExchangeDefaults.TOPIC_EXCHANGE_CLASS; - } - - public Class<DestWildExchange> getExchangeClass() - { - return DestWildExchange.class; - } - - public DestWildExchange newInstance(VirtualHost host, - AMQShortString name, - boolean durable, - boolean autoDelete) throws AMQException - { - DestWildExchange exch = new DestWildExchange(); - exch.initialise(host, name, durable, autoDelete); - return exch; - } - }; - - - private static final Logger _logger = Logger.getLogger(DestWildExchange.class); - - private ConcurrentHashMap<AMQShortString, List<AMQQueue>> _routingKey2queues = - new ConcurrentHashMap<AMQShortString, List<AMQQueue>>(); - // private ConcurrentHashMap<AMQShortString, AMQQueue> _routingKey2queue = new ConcurrentHashMap<AMQShortString, AMQQueue>(); - private static final String TOPIC_SEPARATOR = "."; - private static final String AMQP_STAR = "*"; - private static final String AMQP_HASH = "#"; - - /** DestWildExchangeMBean class implements the management interface for the Topic exchanges. */ - @MBeanDescription("Management Bean for Topic Exchange") - private final class DestWildExchangeMBean extends ExchangeMBean - { - @MBeanConstructor("Creates an MBean for AMQ topic exchange") - public DestWildExchangeMBean() throws JMException - { - super(); - _exchangeType = "topic"; - init(); - } - - /** returns exchange bindings in tabular form */ - public TabularData bindings() throws OpenDataException - { - _bindingList = new TabularDataSupport(_bindinglistDataType); - for (Map.Entry<AMQShortString, List<AMQQueue>> entry : _routingKey2queues.entrySet()) - { - AMQShortString key = entry.getKey(); - List<String> queueList = new ArrayList<String>(); - - List<AMQQueue> queues = getMatchedQueues(key); - for (AMQQueue q : queues) - { - queueList.add(q.getName().toString()); - } - - Object[] bindingItemValues = {key.toString(), queueList.toArray(new String[0])}; - CompositeData bindingData = new CompositeDataSupport(_bindingDataType, _bindingItemNames, bindingItemValues); - _bindingList.put(bindingData); - } - - return _bindingList; - } - - public void createNewBinding(String queueName, String binding) throws JMException - { - AMQQueue queue = getQueueRegistry().getQueue(new AMQShortString(queueName)); - if (queue == null) - { - throw new JMException("Queue \"" + queueName + "\" is not registered with the exchange."); - } - - try - { - queue.bind(new AMQShortString(binding), null, DestWildExchange.this); - } - catch (AMQException ex) - { - throw new MBeanException(ex); - } - } - - } // End of MBean class - - public AMQShortString getType() - { - return ExchangeDefaults.TOPIC_EXCHANGE_CLASS; - } - - public synchronized void registerQueue(AMQShortString rKey, AMQQueue queue, FieldTable args) throws AMQException - { - assert queue != null; - assert rKey != null; - - AMQShortString routingKey = normalize(rKey); - - _logger.debug("Registering queue " + queue.getName() + " with routing key " + routingKey); - // we need to use putIfAbsent, which is an atomic operation, to avoid a race condition - List<AMQQueue> queueList = _routingKey2queues.putIfAbsent(routingKey, new CopyOnWriteArrayList<AMQQueue>()); - // if we got null back, no previous value was associated with the specified routing key hence - // we need to read back the new value just put into the map - if (queueList == null) - { - queueList = _routingKey2queues.get(routingKey); - } - - if (!queueList.contains(queue)) - { - queueList.add(queue); - } - else if (_logger.isDebugEnabled()) - { - _logger.debug("Queue " + queue + " is already registered with routing key " + routingKey); - } - - } - - private AMQShortString normalize(AMQShortString routingKey) - { - StringTokenizer routingTokens = new StringTokenizer(routingKey.toString(), TOPIC_SEPARATOR); - List<String> _subscription = new ArrayList<String>(); - - while (routingTokens.hasMoreTokens()) - { - _subscription.add(routingTokens.nextToken()); - } - - int size = _subscription.size(); - - for (int index = 0; index < size; index++) - { - // if there are more levels - if ((index + 1) < size) - { - if (_subscription.get(index).equals(AMQP_HASH)) - { - if (_subscription.get(index + 1).equals(AMQP_HASH)) - { - // we don't need #.# delete this one - _subscription.remove(index); - size--; - // redo this normalisation - index--; - } - - if (_subscription.get(index + 1).equals(AMQP_STAR)) - { - // we don't want #.* swap to *.# - // remove it and put it in at index + 1 - _subscription.add(index + 1, _subscription.remove(index)); - } - } - } // if we have more levels - } - - StringBuilder sb = new StringBuilder(); - - for (String s : _subscription) - { - sb.append(s); - sb.append(TOPIC_SEPARATOR); - } - - sb.deleteCharAt(sb.length() - 1); - - return new AMQShortString(sb.toString()); - } - - public void route(AMQMessage payload) throws AMQException - { - MessagePublishInfo info = payload.getMessagePublishInfo(); - - final AMQShortString routingKey = normalize(info.getRoutingKey()); - - List<AMQQueue> queues = getMatchedQueues(routingKey); - // if we have no registered queues we have nothing to do - // TODO: add support for the immediate flag - if ((queues == null) || queues.isEmpty()) - { - if (info.isMandatory() || info.isImmediate()) - { - String msg = "Topic " + routingKey + " is not known to " + this; - throw new NoRouteException(msg, payload, null); - } - else - { - _logger.warn("No queues found for routing key " + routingKey); - _logger.warn("Routing map contains: " + _routingKey2queues); - - return; - } - } - - for (AMQQueue q : queues) - { - // TODO: modify code generator to add clone() method then clone the deliver body - // without this addition we have a race condition - we will be modifying the body - // before the encoder has encoded the body for delivery - payload.enqueue(q); - } - } - - public boolean isBound(AMQShortString routingKey, FieldTable arguments, AMQQueue queue) - { - return isBound(routingKey, queue); - } - - public boolean isBound(AMQShortString routingKey, AMQQueue queue) - { - List<AMQQueue> queues = _routingKey2queues.get(normalize(routingKey)); - - return (queues != null) && queues.contains(queue); - } - - public boolean isBound(AMQShortString routingKey) - { - List<AMQQueue> queues = _routingKey2queues.get(normalize(routingKey)); - - return (queues != null) && !queues.isEmpty(); - } - - public boolean isBound(AMQQueue queue) - { - for (List<AMQQueue> queues : _routingKey2queues.values()) - { - if (queues.contains(queue)) - { - return true; - } - } - - return false; - } - - public boolean hasBindings() - { - return !_routingKey2queues.isEmpty(); - } - - public synchronized void deregisterQueue(AMQShortString rKey, AMQQueue queue, FieldTable args) throws AMQException - { - assert queue != null; - assert rKey != null; - - AMQShortString routingKey = normalize(rKey); - - List<AMQQueue> queues = _routingKey2queues.get(routingKey); - if (queues == null) - { - throw new AMQException(null, "Queue " + queue + " was not registered with exchange " + this.getName() + - " with routing key " + routingKey + ". No queue was registered with that routing key", null); - - } - - boolean removedQ = queues.remove(queue); - if (!removedQ) - { - throw new AMQException(null, "Queue " + queue + " was not registered with exchange " + this.getName() + - " with routing key " + routingKey, null); - } - - if (queues.isEmpty()) - { - _routingKey2queues.remove(routingKey); - } - } - - protected ExchangeMBean createMBean() throws AMQException - { - try - { - return new DestWildExchangeMBean(); - } - catch (JMException ex) - { - _logger.error("Exception occured in creating the topic exchenge mbean", ex); - throw new AMQException(null, "Exception occured in creating the topic exchenge mbean", ex); - } - } - - public Map<AMQShortString, List<AMQQueue>> getBindings() - { - return _routingKey2queues; - } - - private List<AMQQueue> getMatchedQueues(AMQShortString routingKey) - { - List<AMQQueue> list = new LinkedList<AMQQueue>(); - StringTokenizer routingTokens = new StringTokenizer(routingKey.toString(), TOPIC_SEPARATOR); - - ArrayList<String> routingkeyList = new ArrayList<String>(); - - while (routingTokens.hasMoreTokens()) - { - String next = routingTokens.nextToken(); - if (next.equals(AMQP_HASH) && routingkeyList.get(routingkeyList.size() - 1).equals(AMQP_HASH)) - { - continue; - } - - routingkeyList.add(next); - } - - for (AMQShortString queue : _routingKey2queues.keySet()) - { - StringTokenizer queTok = new StringTokenizer(queue.toString(), TOPIC_SEPARATOR); - - ArrayList<String> queueList = new ArrayList<String>(); - - while (queTok.hasMoreTokens()) - { - queueList.add(queTok.nextToken()); - } - - int depth = 0; - boolean matching = true; - boolean done = false; - int routingskip = 0; - int queueskip = 0; - - while (matching && !done) - { - if ((queueList.size() == (depth + queueskip)) || (routingkeyList.size() == (depth + routingskip))) - { - done = true; - - // if it was the routing key that ran out of digits - if (routingkeyList.size() == (depth + routingskip)) - { - if (queueList.size() > (depth + queueskip)) - { // a hash and it is the last entry - matching = - queueList.get(depth + queueskip).equals(AMQP_HASH) - && (queueList.size() == (depth + queueskip + 1)); - } - } - else if (routingkeyList.size() > (depth + routingskip)) - { - // There is still more routing key to check - matching = false; - } - - continue; - } - - // if the values on the two topics don't match - if (!queueList.get(depth + queueskip).equals(routingkeyList.get(depth + routingskip))) - { - if (queueList.get(depth + queueskip).equals(AMQP_STAR)) - { - depth++; - - continue; - } - else if (queueList.get(depth + queueskip).equals(AMQP_HASH)) - { - // Is this a # at the end - if (queueList.size() == (depth + queueskip + 1)) - { - done = true; - - continue; - } - - // otherwise # in the middle - while (routingkeyList.size() > (depth + routingskip)) - { - if (routingkeyList.get(depth + routingskip).equals(queueList.get(depth + queueskip + 1))) - { - queueskip++; - depth++; - - break; - } - - routingskip++; - } - - continue; - } - - matching = false; - } - - depth++; - } - - if (matching) - { - list.addAll(_routingKey2queues.get(queue)); - } - } - - return list; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/Exchange.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/Exchange.java deleted file mode 100644 index 78749de612..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/exchange/Exchange.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.exchange; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.server.queue.AMQMessage; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.virtualhost.VirtualHost; - -import java.util.List; -import java.util.Map; - -public interface Exchange -{ - AMQShortString getName(); - AMQShortString getType(); - - void initialise(VirtualHost host, AMQShortString name, boolean durable, boolean autoDelete) throws AMQException; - - boolean isDurable(); - - /** - * @return true if the exchange will be deleted after all queues have been detached - */ - boolean isAutoDelete(); - - void close() throws AMQException; - - void registerQueue(AMQShortString routingKey, AMQQueue queue, FieldTable args) throws AMQException; - - void deregisterQueue(AMQShortString routingKey, AMQQueue queue, FieldTable args) throws AMQException; - - void route(AMQMessage message) throws AMQException; - - - /** - * Determines whether a message would be isBound to a particular queue using a specific routing key and arguments - * @param routingKey - * @param arguments - * @param queue - * @return - * @throws AMQException - */ - boolean isBound(AMQShortString routingKey, FieldTable arguments, AMQQueue queue); - - /** - * Determines whether a message would be isBound to a particular queue using a specific routing key - * @param routingKey - * @param queue - * @return - * @throws AMQException - */ - boolean isBound(AMQShortString routingKey, AMQQueue queue); - - /** - * Determines whether a message is routing to any queue using a specific routing key - * @param routingKey - * @return - * @throws AMQException - */ - boolean isBound(AMQShortString routingKey); - - boolean isBound(AMQQueue queue); - - /** - * Returns true if this exchange has at least one binding associated with it. - * @return - * @throws AMQException - */ - boolean hasBindings(); - - Map<AMQShortString, List<AMQQueue>> getBindings(); - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeFactory.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeFactory.java deleted file mode 100644 index b7b88b9157..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeFactory.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.exchange; - -import org.apache.commons.configuration.Configuration; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; - - -public interface ExchangeFactory -{ - Exchange createExchange(AMQShortString exchange, AMQShortString type, boolean durable, boolean autoDelete, - int ticket) - throws AMQException; - - void initialise(Configuration hostConfig); -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeInUseException.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeInUseException.java deleted file mode 100644 index 07550dd808..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeInUseException.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.server.exchange; - -import org.apache.qpid.AMQException; - -/** - * ExchangeInUseRegistry indicates that an exchange cannot be unregistered because it is currently being used. - * - * <p/><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Represents failure to unregister exchange that is in use. - * </table> - * - * @todo Not an AMQP exception as no status code. - * - * @todo This exception is not used. However, it is part of the ExchangeRegistry interface, and looks like code is - * going to need to be added to throw/deal with this. Alternatively ExchangeResitries may be able to handle the - * issue internally. - */ -public class ExchangeInUseException extends AMQException -{ - public ExchangeInUseException(String exchangeName, Throwable cause) - { - super(null, "Exchange " + exchangeName + " is currently in use", cause); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeRegistry.java deleted file mode 100644 index 2e101beb84..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeRegistry.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.server.exchange; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; - -import java.util.Collection; - -public interface ExchangeRegistry extends MessageRouter -{ - void registerExchange(Exchange exchange) throws AMQException; - - /** - * Unregister an exchange - * @param name name of the exchange to delete - * @param inUse if true, do NOT delete the exchange if it is in use (has queues bound to it) - * @throws ExchangeInUseException when the exchange cannot be deleted because it is in use - * @throws AMQException - */ - void unregisterExchange(AMQShortString name, boolean inUse) throws ExchangeInUseException, AMQException; - - Exchange getExchange(AMQShortString name); - - void setDefaultExchange(Exchange exchange); - - Exchange getDefaultExchange(); - - Collection<AMQShortString> getExchangeNames(); - - void initialise() throws AMQException; -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeType.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeType.java deleted file mode 100644 index 472de2da5c..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeType.java +++ /dev/null @@ -1,34 +0,0 @@ -/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.exchange;
-
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-
-public interface ExchangeType<T extends Exchange>
-{
- public AMQShortString getName();
- public Class<T> getExchangeClass();
- public T newInstance(VirtualHost host, AMQShortString name,
- boolean durable, boolean autoDelete) throws AMQException;
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/FanoutExchange.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/FanoutExchange.java deleted file mode 100644 index 77590ea54d..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/exchange/FanoutExchange.java +++ /dev/null @@ -1,239 +0,0 @@ -/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.exchange;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.FieldTable;
-import org.apache.qpid.framing.abstraction.MessagePublishInfo;
-import org.apache.qpid.server.management.MBeanConstructor;
-import org.apache.qpid.server.management.MBeanDescription;
-import org.apache.qpid.server.queue.AMQMessage;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-import javax.management.JMException;
-import javax.management.MBeanException;
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.CompositeDataSupport;
-import javax.management.openmbean.OpenDataException;
-import javax.management.openmbean.TabularData;
-import javax.management.openmbean.TabularDataSupport;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.CopyOnWriteArraySet;
-
-public class FanoutExchange extends AbstractExchange
-{
-
-
- private static final Logger _logger = Logger.getLogger(FanoutExchange.class);
-
-
- public static final ExchangeType<FanoutExchange> TYPE = new ExchangeType<FanoutExchange>()
- {
-
- public AMQShortString getName()
- {
- return ExchangeDefaults.FANOUT_EXCHANGE_CLASS;
- }
-
- public Class<FanoutExchange> getExchangeClass()
- {
- return FanoutExchange.class;
- }
-
- public FanoutExchange newInstance(VirtualHost host,
- AMQShortString name,
- boolean durable,
- boolean autoDelete) throws AMQException
- {
- FanoutExchange exch = new FanoutExchange();
- exch.initialise(host, name, durable, autoDelete);
- return exch;
- }
- };
-
-
- /**
- * Maps from queue name to queue instances
- */
- private final CopyOnWriteArraySet<AMQQueue> _queues = new CopyOnWriteArraySet<AMQQueue>();
-
- /**
- * MBean class implementing the management interfaces.
- */
- @MBeanDescription("Management Bean for Fanout Exchange")
- private final class FanoutExchangeMBean extends ExchangeMBean
- {
- @MBeanConstructor("Creates an MBean for AMQ fanout exchange")
- public FanoutExchangeMBean() throws JMException
- {
- super();
- _exchangeType = "fanout";
- init();
- }
-
- public TabularData bindings() throws OpenDataException
- {
-
- _bindingList = new TabularDataSupport(_bindinglistDataType);
-
- for (AMQQueue queue : _queues)
- {
- String queueName = queue.getName().toString();
-
- Object[] bindingItemValues = {queueName, new String[]{queueName}};
- CompositeData bindingData = new CompositeDataSupport(_bindingDataType, _bindingItemNames, bindingItemValues);
- _bindingList.put(bindingData);
- }
-
- return _bindingList;
- }
-
- public void createNewBinding(String queueName, String binding) throws JMException
- {
- AMQQueue queue = getQueueRegistry().getQueue(new AMQShortString(queueName));
- if (queue == null)
- {
- throw new JMException("Queue \"" + queueName + "\" is not registered with the exchange.");
- }
-
- try
- {
- queue.bind(new AMQShortString(binding), null, FanoutExchange.this);
- }
- catch (AMQException ex)
- {
- throw new MBeanException(ex);
- }
- }
-
- } // End of MBean class
-
- protected ExchangeMBean createMBean() throws AMQException
- {
- try
- {
- return new FanoutExchange.FanoutExchangeMBean();
- }
- catch (JMException ex)
- {
- _logger.error("Exception occured in creating the direct exchange mbean", ex);
- throw new AMQException(null, "Exception occured in creating the direct exchange mbean", ex);
- }
- }
-
- public Map<AMQShortString, List<AMQQueue>> getBindings()
- {
- return null;
- }
-
- public AMQShortString getType()
- {
- return ExchangeDefaults.FANOUT_EXCHANGE_CLASS;
- }
-
- public void registerQueue(AMQShortString routingKey, AMQQueue queue, FieldTable args) throws AMQException
- {
- assert queue != null;
-
- if (_queues.contains(queue))
- {
- _logger.debug("Queue " + queue + " is already registered");
- }
- else
- {
- _queues.add(queue);
- _logger.debug("Binding queue " + queue + " with routing key " + routingKey + " to exchange " + this);
- }
- }
-
- public void deregisterQueue(AMQShortString routingKey, AMQQueue queue, FieldTable args) throws AMQException
- {
- assert queue != null;
-
- if (!_queues.remove(queue))
- {
- throw new AMQException(null, "Queue " + queue + " was not registered with exchange " + this.getName() +
- ". ", null);
- }
- }
-
- public void route(AMQMessage payload) throws AMQException
- {
- final MessagePublishInfo publishInfo = payload.getMessagePublishInfo();
- final AMQShortString routingKey = publishInfo.getRoutingKey();
- if ((_queues == null) || _queues.isEmpty())
- {
- String msg = "No queues bound to " + this;
- if (publishInfo.isMandatory() || publishInfo.isImmediate())
- {
- throw new NoRouteException(msg, payload, null);
- }
- else
- {
- _logger.warn(msg);
- }
- }
- else
- {
- if (_logger.isDebugEnabled())
- {
- _logger.debug("Publishing message to queue " + _queues);
- }
-
- for (AMQQueue q : _queues)
- {
- payload.enqueue(q);
- }
- }
- }
-
- public boolean isBound(AMQShortString routingKey, FieldTable fieldtable, AMQQueue queue)
- {
- return isBound(routingKey, queue);
- }
-
- public boolean isBound(AMQShortString routingKey, AMQQueue queue)
- {
- return _queues.contains(queue);
- }
-
- public boolean isBound(AMQShortString routingKey)
- {
-
- return (_queues != null) && !_queues.isEmpty();
- }
-
- public boolean isBound(AMQQueue queue)
- {
-
- return _queues.contains(queue);
- }
-
- public boolean hasBindings()
- {
- return !_queues.isEmpty();
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersBinding.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersBinding.java deleted file mode 100644 index 2b7df4361a..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersBinding.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.exchange; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.apache.log4j.Logger; -import org.apache.qpid.framing.AMQTypedValue; -import org.apache.qpid.framing.FieldTable; - -/** - * Defines binding and matching based on a set of headers. - */ -class HeadersBinding -{ - private static final Logger _logger = Logger.getLogger(HeadersBinding.class); - - private final FieldTable _mappings; - private final Set<String> required = new HashSet<String>(); - private final Map<String,Object> matches = new HashMap<String,Object>(); - private boolean matchAny; - - private final class MatchesOrProcessor implements FieldTable.FieldTableElementProcessor - { - private Boolean _result = Boolean.FALSE; - - public boolean processElement(String propertyName, AMQTypedValue value) - { - if((value != null) && (value.getValue() != null) && value.getValue().equals(matches.get(propertyName))) - { - _result = Boolean.TRUE; - return false; - } - return true; - } - - public Object getResult() - { - return _result; - } - } - - private final class RequiredOrProcessor implements FieldTable.FieldTableElementProcessor - { - Boolean _result = Boolean.FALSE; - - public boolean processElement(String propertyName, AMQTypedValue value) - { - if(required.contains(propertyName)) - { - _result = Boolean.TRUE; - return false; - } - return true; - } - - public Object getResult() - { - return _result; - } - } - - - - /** - * Creates a binding for a set of mappings. Those mappings whose value is - * null or the empty string are assumed only to be required headers, with - * no constraint on the value. Those with a non-null value are assumed to - * define a required match of value. - * @param mappings the defined mappings this binding should use - */ - - HeadersBinding(FieldTable mappings) - { - _mappings = mappings; - initMappings(); - } - - private void initMappings() - { - - _mappings.processOverElements(new FieldTable.FieldTableElementProcessor() - { - - public boolean processElement(String propertyName, AMQTypedValue value) - { - if (isSpecial(propertyName)) - { - processSpecial(propertyName, value.getValue()); - } - else if (value.getValue() == null || value.getValue().equals("")) - { - required.add(propertyName); - } - else - { - matches.put(propertyName,value.getValue()); - } - - return true; - } - - public Object getResult() - { - return null; - } - }); - } - - protected FieldTable getMappings() - { - return _mappings; - } - - /** - * Checks whether the supplied headers match the requirements of this binding - * @param headers the headers to check - * @return true if the headers define any required keys and match any required - * values - */ - public boolean matches(FieldTable headers) - { - if(headers == null) - { - return required.isEmpty() && matches.isEmpty(); - } - else - { - return matchAny ? or(headers) : and(headers); - } - } - - private boolean and(FieldTable headers) - { - if(headers.keys().containsAll(required)) - { - for(Map.Entry<String, Object> e : matches.entrySet()) - { - if(!e.getValue().equals(headers.getObject(e.getKey()))) - { - return false; - } - } - return true; - } - else - { - return false; - } - } - - - private boolean or(final FieldTable headers) - { - if(required.isEmpty() || !(Boolean) headers.processOverElements(new RequiredOrProcessor())) - { - return ((!matches.isEmpty()) && (Boolean) headers.processOverElements(new MatchesOrProcessor())) - || (required.isEmpty() && matches.isEmpty()); - } - else - { - return true; - } - } - - private void processSpecial(String key, Object value) - { - if("X-match".equalsIgnoreCase(key)) - { - matchAny = isAny(value); - } - else - { - _logger.warn("Ignoring special header: " + key); - } - } - - private boolean isAny(Object value) - { - if(value instanceof String) - { - if("any".equalsIgnoreCase((String) value)) return true; - if("all".equalsIgnoreCase((String) value)) return false; - } - _logger.warn("Ignoring unrecognised match type: " + value); - return false;//default to all - } - - static boolean isSpecial(Object key) - { - return key instanceof String && isSpecial((String) key); - } - - static boolean isSpecial(String key) - { - return key.startsWith("X-") || key.startsWith("x-"); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersExchange.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersExchange.java deleted file mode 100644 index 426cd090c1..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersExchange.java +++ /dev/null @@ -1,350 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.exchange; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.AMQTypedValue; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.server.management.MBeanConstructor; -import org.apache.qpid.server.management.MBeanDescription; -import org.apache.qpid.server.queue.AMQMessage; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.virtualhost.VirtualHost; - -import javax.management.JMException; -import javax.management.openmbean.ArrayType; -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.CompositeDataSupport; -import javax.management.openmbean.CompositeType; -import javax.management.openmbean.OpenDataException; -import javax.management.openmbean.OpenType; -import javax.management.openmbean.SimpleType; -import javax.management.openmbean.TabularData; -import javax.management.openmbean.TabularDataSupport; -import javax.management.openmbean.TabularType; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CopyOnWriteArrayList; - -/** - * An exchange that binds queues based on a set of required headers and header values - * and routes messages to these queues by matching the headers of the message against - * those with which the queues were bound. - * <p/> - * <pre> - * The Headers Exchange - * - * Routes messages according to the value/presence of fields in the message header table. - * (Basic and JMS content has a content header field called "headers" that is a table of - * message header fields). - * - * class = "headers" - * routing key is not used - * - * Has the following binding arguments: - * - * the X-match field - if "all", does an AND match (used for GRM), if "any", does an OR match. - * other fields prefixed with "X-" are ignored (and generate a console warning message). - * a field with no value or empty value indicates a match on presence only. - * a field with a value indicates match on field presence and specific value. - * - * Standard instances: - * - * amq.match - pub/sub on field content/value - * </pre> - */ -public class HeadersExchange extends AbstractExchange -{ - private static final Logger _logger = Logger.getLogger(HeadersExchange.class); - - - public static final ExchangeType<HeadersExchange> TYPE = new ExchangeType<HeadersExchange>() - { - - public AMQShortString getName() - { - return ExchangeDefaults.HEADERS_EXCHANGE_CLASS; - } - - public Class<HeadersExchange> getExchangeClass() - { - return HeadersExchange.class; - } - - public HeadersExchange newInstance(VirtualHost host, - AMQShortString name, - boolean durable, - boolean autoDelete) throws AMQException - { - HeadersExchange exch = new HeadersExchange(); - exch.initialise(host, name, durable, autoDelete); - return exch; - } - }; - - - private final List<Registration> _bindings = new CopyOnWriteArrayList<Registration>(); - - /** - * HeadersExchangeMBean class implements the management interface for the - * Header Exchanges. - */ - @MBeanDescription("Management Bean for Headers Exchange") - private final class HeadersExchangeMBean extends ExchangeMBean - { - @MBeanConstructor("Creates an MBean for AMQ Headers exchange") - public HeadersExchangeMBean() throws JMException - { - super(); - _exchangeType = "headers"; - init(); - } - - /** - * initialises the OpenType objects. - */ - protected void init() throws OpenDataException - { - _bindingItemNames = new String[]{"Binding No", "Queue Name", "Queue Bindings"}; - _bindingItemIndexNames = new String[]{_bindingItemNames[0]}; - - _bindingItemTypes = new OpenType[3]; - _bindingItemTypes[0] = SimpleType.INTEGER; - _bindingItemTypes[1] = SimpleType.STRING; - _bindingItemTypes[2] = new ArrayType(1, SimpleType.STRING); - _bindingDataType = new CompositeType("Exchange Binding", "Queue name and header bindings", - _bindingItemNames, _bindingItemNames, _bindingItemTypes); - _bindinglistDataType = new TabularType("Exchange Bindings", "List of exchange bindings for " + getName(), - _bindingDataType, _bindingItemIndexNames); - } - - public TabularData bindings() throws OpenDataException - { - _bindingList = new TabularDataSupport(_bindinglistDataType); - int count = 1; - for (Iterator<Registration> itr = _bindings.iterator(); itr.hasNext();) - { - Registration registration = itr.next(); - String queueName = registration.queue.getName().toString(); - - HeadersBinding headers = registration.binding; - FieldTable headerMappings = headers.getMappings(); - final List<String> mappingList = new ArrayList<String>(); - - headerMappings.processOverElements(new FieldTable.FieldTableElementProcessor() - { - - public boolean processElement(String propertyName, AMQTypedValue value) - { - mappingList.add(propertyName + "=" + value.getValue()); - return true; - } - - public Object getResult() - { - return mappingList; - } - }); - - - Object[] bindingItemValues = {count++, queueName, mappingList.toArray(new String[0])}; - CompositeData bindingData = new CompositeDataSupport(_bindingDataType, _bindingItemNames, bindingItemValues); - _bindingList.put(bindingData); - } - - return _bindingList; - } - - /** - * Creates bindings. Binding pattern is as follows- - * <attributename>=<value>,<attributename>=<value>,... - * @param queueName - * @param binding - * @throws javax.management.JMException - */ - public void createNewBinding(String queueName, String binding) throws JMException - { - AMQQueue queue = getQueueRegistry().getQueue(new AMQShortString(queueName)); - - if (queue == null) - { - throw new JMException("Queue \"" + queueName + "\" is not registered with the exchange."); - } - - String[] bindings = binding.split(","); - FieldTable bindingMap = new FieldTable(); - for (int i = 0; i < bindings.length; i++) - { - String[] keyAndValue = bindings[i].split("="); - if (keyAndValue == null || keyAndValue.length < 2) - { - throw new JMException("Format for headers binding should be \"<attribute1>=<value1>,<attribute2>=<value2>\" "); - } - bindingMap.setString(keyAndValue[0], keyAndValue[1]); - } - - _bindings.add(new Registration(new HeadersBinding(bindingMap), queue)); - } - - } // End of MBean class - - public AMQShortString getType() - { - return ExchangeDefaults.HEADERS_EXCHANGE_CLASS; - } - - public void registerQueue(AMQShortString routingKey, AMQQueue queue, FieldTable args) throws AMQException - { - _logger.debug("Exchange " + getName() + ": Binding " + queue.getName() + " with " + args); - _bindings.add(new Registration(new HeadersBinding(args), queue)); - } - - public void deregisterQueue(AMQShortString routingKey, AMQQueue queue, FieldTable args) throws AMQException - { - _logger.debug("Exchange " + getName() + ": Unbinding " + queue.getName()); - _bindings.remove(new Registration(new HeadersBinding(args), queue)); - } - - public void route(AMQMessage payload) throws AMQException - { - FieldTable headers = getHeaders(payload.getContentHeaderBody()); - if (_logger.isDebugEnabled()) - { - _logger.debug("Exchange " + getName() + ": routing message with headers " + headers); - } - boolean routed = false; - for (Registration e : _bindings) - { - if (e.binding.matches(headers)) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Exchange " + getName() + ": delivering message with headers " + - headers + " to " + e.queue.getName()); - } - payload.enqueue(e.queue); - routed = true; - } - } - if (!routed) - { - - String msg = "Exchange " + getName() + ": message not routable."; - - if (payload.getMessagePublishInfo().isMandatory() || payload.getMessagePublishInfo().isImmediate()) - { - throw new NoRouteException(msg, payload, null); - } - else - { - _logger.warn(msg); - } - - } - } - - public boolean isBound(AMQShortString routingKey, FieldTable arguments, AMQQueue queue) - { - //fixme isBound here should take the arguements in to consideration. - return isBound(routingKey, queue); - } - - public boolean isBound(AMQShortString routingKey, AMQQueue queue) - { - return isBound(queue); - } - - public boolean isBound(AMQShortString routingKey) - { - return hasBindings(); - } - - public boolean isBound(AMQQueue queue) - { - for (Registration r : _bindings) - { - if (r.queue.equals(queue)) - { - return true; - } - } - return false; - } - - public boolean hasBindings() - { - return !_bindings.isEmpty(); - } - - protected FieldTable getHeaders(ContentHeaderBody contentHeaderFrame) - { - //what if the content type is not 'basic'? 'file' and 'stream' content classes also define headers, - //but these are not yet implemented. - return ((BasicContentHeaderProperties) contentHeaderFrame.properties).getHeaders(); - } - - protected ExchangeMBean createMBean() throws AMQException - { - try - { - return new HeadersExchangeMBean(); - } - catch (JMException ex) - { - _logger.error("Exception occured in creating the HeadersExchangeMBean", ex); - throw new AMQException(null, "Exception occured in creating the HeadersExchangeMBean", ex); - } - } - - public Map<AMQShortString, List<AMQQueue>> getBindings() - { - return null; - } - - private static class Registration - { - private final HeadersBinding binding; - private final AMQQueue queue; - - Registration(HeadersBinding binding, AMQQueue queue) - { - this.binding = binding; - this.queue = queue; - } - - public int hashCode() - { - return queue.hashCode(); - } - - public boolean equals(Object o) - { - return o instanceof Registration && ((Registration) o).queue.equals(queue); - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/Index.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/Index.java deleted file mode 100644 index eacdad8a8e..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/exchange/Index.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.exchange; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.CopyOnWriteArrayList; - -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.queue.AMQQueue; - -/** - * An index of queues against routing key. Allows multiple queues to be stored - * against the same key. Used in the DestNameExchange. - */ -class Index -{ - private ConcurrentMap<AMQShortString, List<AMQQueue>> _index - = new ConcurrentHashMap<AMQShortString, List<AMQQueue>>(); - - synchronized boolean add(AMQShortString key, AMQQueue queue) - { - List<AMQQueue> queues = _index.get(key); - if(queues == null) - { - queues = new CopyOnWriteArrayList<AMQQueue>(); - //next call is atomic, so there is no race to create the list - List<AMQQueue> active = _index.putIfAbsent(key, queues); - if(active != null) - { - //someone added the new one in faster than we did, so use theirs - queues = active; - } - } - if(queues.contains(queue)) - { - return false; - } - else - { - return queues.add(queue); - } - } - - synchronized boolean remove(AMQShortString key, AMQQueue queue) - { - List<AMQQueue> queues = _index.get(key); - if (queues != null) - { - boolean removed = queues.remove(queue); - if (queues.size() == 0) - { - _index.remove(key); - } - return removed; - } - return false; - } - - List<AMQQueue> get(AMQShortString key) - { - return _index.get(key); - } - - Map<AMQShortString, List<AMQQueue>> getBindingsMap() - { - return new HashMap<AMQShortString, List<AMQQueue>>(_index); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/ManagedExchange.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/ManagedExchange.java deleted file mode 100644 index bb33341aef..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/exchange/ManagedExchange.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.exchange; - -import java.io.IOException; - -import javax.management.JMException; -import javax.management.MBeanOperationInfo; -import javax.management.openmbean.TabularData; - -import org.apache.qpid.server.management.MBeanAttribute; -import org.apache.qpid.server.management.MBeanOperation; -import org.apache.qpid.server.management.MBeanOperationParameter; -import org.apache.qpid.server.queue.ManagedQueue; - -/** - * The management interface exposed to allow management of an Exchange. - * @author Robert J. Greig - * @author Bhupendra Bhardwaj - * @version 0.1 - */ -public interface ManagedExchange -{ - static final String TYPE = "Exchange"; - - /** - * Returns the name of the managed exchange. - * @return the name of the exchange. - * @throws IOException - */ - @MBeanAttribute(name="Name", description=TYPE + " Name") - String getName() throws IOException; - - @MBeanAttribute(name="ExchangeType", description="Exchange Type") - String getExchangeType() throws IOException; - - /** - * Tells if the exchange is durable or not. - * @return true if the exchange is durable. - * @throws IOException - */ - @MBeanAttribute(name="Durable", description="true if Exchange is durable") - boolean isDurable() throws IOException; - - /** - * Tells if the exchange is set for autodelete or not. - * @return true if the exchange is set as autodelete. - * @throws IOException - */ - @MBeanAttribute(name="AutoDelete", description="true if Exchange is AutoDelete") - boolean isAutoDelete() throws IOException; - - // Operations - - /** - * Returns all the bindings this exchange has with the queues. - * @return the bindings with the exchange. - * @throws IOException - * @throws JMException - */ - @MBeanOperation(name="bindings", description="view the queue bindings for this exchange") - TabularData bindings() throws IOException, JMException; - - /** - * Creates new binding with the given queue and binding. - * @param queueName - * @param binding - * @throws JMException - */ - @MBeanOperation(name="createNewBinding", - description="create a new binding with this exchange", - impact= MBeanOperationInfo.ACTION) - void createNewBinding(@MBeanOperationParameter(name= ManagedQueue.TYPE, description="Queue name") String queueName, - @MBeanOperationParameter(name="Binding", description="New binding")String binding) - throws JMException; - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/MessageRouter.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/MessageRouter.java deleted file mode 100644 index 7508e80f7f..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/exchange/MessageRouter.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.exchange; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.queue.AMQMessage; - -/** - * Separated out from the ExchangeRegistry interface to allow components - * that use only this part to have a dependency with a reduced footprint. - * - */ -public interface MessageRouter -{ - /** - * Routes content through exchanges, delivering it to 1 or more queues. - * @param message the message to be routed - * - * @throws org.apache.qpid.AMQException if something goes wrong delivering data - */ - void routeContent(AMQMessage message) throws AMQException; -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/NoRouteException.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/NoRouteException.java deleted file mode 100644 index c787103c00..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/exchange/NoRouteException.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.exchange; - -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.RequiredDeliveryException; -import org.apache.qpid.server.queue.AMQMessage; - -/** - * NoRouteException is a {@link RequiredDeliveryException} that represents the failure case where a manadatory message - * cannot be delivered because there is no route for the message. The AMQP status code, 312, is always used to report - * this condition. - * - * <p/><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Represent failure to deliver a message that must be delivered. - * </table> - */ -public class NoRouteException extends RequiredDeliveryException -{ - public NoRouteException(String msg, AMQMessage message, Throwable cause) - { - super(msg, message, cause); - } - - public AMQConstant getReplyCode() - { - return AMQConstant.NO_ROUTE; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/ArithmeticExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/ArithmeticExpression.java deleted file mode 100644 index fb5220f4da..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/filter/ArithmeticExpression.java +++ /dev/null @@ -1,275 +0,0 @@ -/** - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.qpid.server.filter; -// -// Based on like named file from r450141 of the Apache ActiveMQ project <http://www.activemq.org/site/home.html> -// - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.queue.AMQMessage; - -/** - * An expression which performs an operation on two expression values - */ -public abstract class ArithmeticExpression extends BinaryExpression -{ - - protected static final int INTEGER = 1; - protected static final int LONG = 2; - protected static final int DOUBLE = 3; - - /** - * @param left - * @param right - */ - public ArithmeticExpression(Expression left, Expression right) - { - super(left, right); - } - - public static Expression createPlus(Expression left, Expression right) - { - return new ArithmeticExpression(left, right) - { - protected Object evaluate(Object lvalue, Object rvalue) - { - if (lvalue instanceof String) - { - String text = (String) lvalue; - String answer = text + rvalue; - - return answer; - } - else if (lvalue instanceof Number) - { - return plus((Number) lvalue, asNumber(rvalue)); - } - - throw new RuntimeException("Cannot call plus operation on: " + lvalue + " and: " + rvalue); - } - - public String getExpressionSymbol() - { - return "+"; - } - }; - } - - public static Expression createMinus(Expression left, Expression right) - { - return new ArithmeticExpression(left, right) - { - protected Object evaluate(Object lvalue, Object rvalue) - { - if (lvalue instanceof Number) - { - return minus((Number) lvalue, asNumber(rvalue)); - } - - throw new RuntimeException("Cannot call minus operation on: " + lvalue + " and: " + rvalue); - } - - public String getExpressionSymbol() - { - return "-"; - } - }; - } - - public static Expression createMultiply(Expression left, Expression right) - { - return new ArithmeticExpression(left, right) - { - - protected Object evaluate(Object lvalue, Object rvalue) - { - if (lvalue instanceof Number) - { - return multiply((Number) lvalue, asNumber(rvalue)); - } - - throw new RuntimeException("Cannot call multiply operation on: " + lvalue + " and: " + rvalue); - } - - public String getExpressionSymbol() - { - return "*"; - } - }; - } - - public static Expression createDivide(Expression left, Expression right) - { - return new ArithmeticExpression(left, right) - { - - protected Object evaluate(Object lvalue, Object rvalue) - { - if (lvalue instanceof Number) - { - return divide((Number) lvalue, asNumber(rvalue)); - } - - throw new RuntimeException("Cannot call divide operation on: " + lvalue + " and: " + rvalue); - } - - public String getExpressionSymbol() - { - return "/"; - } - }; - } - - public static Expression createMod(Expression left, Expression right) - { - return new ArithmeticExpression(left, right) - { - - protected Object evaluate(Object lvalue, Object rvalue) - { - if (lvalue instanceof Number) - { - return mod((Number) lvalue, asNumber(rvalue)); - } - - throw new RuntimeException("Cannot call mod operation on: " + lvalue + " and: " + rvalue); - } - - public String getExpressionSymbol() - { - return "%"; - } - }; - } - - protected Number plus(Number left, Number right) - { - switch (numberType(left, right)) - { - - case INTEGER: - return new Integer(left.intValue() + right.intValue()); - - case LONG: - return new Long(left.longValue() + right.longValue()); - - default: - return new Double(left.doubleValue() + right.doubleValue()); - } - } - - protected Number minus(Number left, Number right) - { - switch (numberType(left, right)) - { - - case INTEGER: - return new Integer(left.intValue() - right.intValue()); - - case LONG: - return new Long(left.longValue() - right.longValue()); - - default: - return new Double(left.doubleValue() - right.doubleValue()); - } - } - - protected Number multiply(Number left, Number right) - { - switch (numberType(left, right)) - { - - case INTEGER: - return new Integer(left.intValue() * right.intValue()); - - case LONG: - return new Long(left.longValue() * right.longValue()); - - default: - return new Double(left.doubleValue() * right.doubleValue()); - } - } - - protected Number divide(Number left, Number right) - { - return new Double(left.doubleValue() / right.doubleValue()); - } - - protected Number mod(Number left, Number right) - { - return new Double(left.doubleValue() % right.doubleValue()); - } - - private int numberType(Number left, Number right) - { - if (isDouble(left) || isDouble(right)) - { - return DOUBLE; - } - else if ((left instanceof Long) || (right instanceof Long)) - { - return LONG; - } - else - { - return INTEGER; - } - } - - private boolean isDouble(Number n) - { - return (n instanceof Float) || (n instanceof Double); - } - - protected Number asNumber(Object value) - { - if (value instanceof Number) - { - return (Number) value; - } - else - { - throw new RuntimeException("Cannot convert value: " + value + " into a number"); - } - } - - public Object evaluate(AMQMessage message) throws AMQException - { - Object lvalue = left.evaluate(message); - if (lvalue == null) - { - return null; - } - - Object rvalue = right.evaluate(message); - if (rvalue == null) - { - return null; - } - - return evaluate(lvalue, rvalue); - } - - /** - * @param lvalue - * @param rvalue - * @return - */ - protected abstract Object evaluate(Object lvalue, Object rvalue); - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/BinaryExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/BinaryExpression.java deleted file mode 100644 index 024257bea9..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/filter/BinaryExpression.java +++ /dev/null @@ -1,106 +0,0 @@ -/** - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.qpid.server.filter; -// -// Based on like named file from r450141 of the Apache ActiveMQ project <http://www.activemq.org/site/home.html> -// - -/** - * An expression which performs an operation on two expression values. - */ -public abstract class BinaryExpression implements Expression -{ - protected Expression left; - protected Expression right; - - public BinaryExpression(Expression left, Expression right) - { - this.left = left; - this.right = right; - } - - public Expression getLeft() - { - return left; - } - - public Expression getRight() - { - return right; - } - - /** - * @see java.lang.Object#toString() - */ - public String toString() - { - return "(" + left.toString() + " " + getExpressionSymbol() + " " + right.toString() + ")"; - } - - /** - * TODO: more efficient hashCode() - * - * @see java.lang.Object#hashCode() - */ - public int hashCode() - { - return toString().hashCode(); - } - - /** - * TODO: more efficient hashCode() - * - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object o) - { - - if ((o == null) || !this.getClass().equals(o.getClass())) - { - return false; - } - - return toString().equals(o.toString()); - - } - - /** - * Returns the symbol that represents this binary expression. For example, addition is - * represented by "+" - * - * @return - */ - public abstract String getExpressionSymbol(); - - /** - * @param expression - */ - public void setRight(Expression expression) - { - right = expression; - } - - /** - * @param expression - */ - public void setLeft(Expression expression) - { - left = expression; - } - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/BooleanExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/BooleanExpression.java deleted file mode 100644 index e28ff79820..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/filter/BooleanExpression.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.qpid.server.filter; -// -// Based on like named file from r450141 of the Apache ActiveMQ project <http://www.activemq.org/site/home.html> -// - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.queue.AMQMessage; - -/** - * A BooleanExpression is an expression that always - * produces a Boolean result. - */ -public interface BooleanExpression extends Expression -{ - - /** - * @param message - * @return true if the expression evaluates to Boolean.TRUE. - * @throws AMQException - */ - public boolean matches(AMQMessage message) throws AMQException; - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/ComparisonExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/ComparisonExpression.java deleted file mode 100644 index 72a9ef7969..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/filter/ComparisonExpression.java +++ /dev/null @@ -1,595 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.filter; -// -// Based on like named file from r450141 of the Apache ActiveMQ project <http://www.activemq.org/site/home.html> -// - -import java.util.HashSet; -import java.util.List; -import java.util.regex.Pattern; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.queue.AMQMessage; - -/** - * A filter performing a comparison of two objects - */ -public abstract class ComparisonExpression extends BinaryExpression implements BooleanExpression -{ - - public static BooleanExpression createBetween(Expression value, Expression left, Expression right) - { - return LogicExpression.createAND(createGreaterThanEqual(value, left), createLessThanEqual(value, right)); - } - - public static BooleanExpression createNotBetween(Expression value, Expression left, Expression right) - { - return LogicExpression.createOR(createLessThan(value, left), createGreaterThan(value, right)); - } - - private static final HashSet REGEXP_CONTROL_CHARS = new HashSet(); - - static - { - REGEXP_CONTROL_CHARS.add(new Character('.')); - REGEXP_CONTROL_CHARS.add(new Character('\\')); - REGEXP_CONTROL_CHARS.add(new Character('[')); - REGEXP_CONTROL_CHARS.add(new Character(']')); - REGEXP_CONTROL_CHARS.add(new Character('^')); - REGEXP_CONTROL_CHARS.add(new Character('$')); - REGEXP_CONTROL_CHARS.add(new Character('?')); - REGEXP_CONTROL_CHARS.add(new Character('*')); - REGEXP_CONTROL_CHARS.add(new Character('+')); - REGEXP_CONTROL_CHARS.add(new Character('{')); - REGEXP_CONTROL_CHARS.add(new Character('}')); - REGEXP_CONTROL_CHARS.add(new Character('|')); - REGEXP_CONTROL_CHARS.add(new Character('(')); - REGEXP_CONTROL_CHARS.add(new Character(')')); - REGEXP_CONTROL_CHARS.add(new Character(':')); - REGEXP_CONTROL_CHARS.add(new Character('&')); - REGEXP_CONTROL_CHARS.add(new Character('<')); - REGEXP_CONTROL_CHARS.add(new Character('>')); - REGEXP_CONTROL_CHARS.add(new Character('=')); - REGEXP_CONTROL_CHARS.add(new Character('!')); - } - - static class LikeExpression extends UnaryExpression implements BooleanExpression - { - - Pattern likePattern; - - /** - * @param right - */ - public LikeExpression(Expression right, String like, int escape) - { - super(right); - - StringBuffer regexp = new StringBuffer(like.length() * 2); - regexp.append("\\A"); // The beginning of the input - for (int i = 0; i < like.length(); i++) - { - char c = like.charAt(i); - if (escape == (0xFFFF & c)) - { - i++; - if (i >= like.length()) - { - // nothing left to escape... - break; - } - - char t = like.charAt(i); - regexp.append("\\x"); - regexp.append(Integer.toHexString(0xFFFF & t)); - } - else if (c == '%') - { - regexp.append(".*?"); // Do a non-greedy match - } - else if (c == '_') - { - regexp.append("."); // match one - } - else if (REGEXP_CONTROL_CHARS.contains(new Character(c))) - { - regexp.append("\\x"); - regexp.append(Integer.toHexString(0xFFFF & c)); - } - else - { - regexp.append(c); - } - } - - regexp.append("\\z"); // The end of the input - - likePattern = Pattern.compile(regexp.toString(), Pattern.DOTALL); - } - - /** - * org.apache.activemq.filter.UnaryExpression#getExpressionSymbol() - */ - public String getExpressionSymbol() - { - return "LIKE"; - } - - /** - * org.apache.activemq.filter.Expression#evaluate(MessageEvaluationContext) - */ - public Object evaluate(AMQMessage message) throws AMQException - { - - Object rv = this.getRight().evaluate(message); - - if (rv == null) - { - return null; - } - - if (!(rv instanceof String)) - { - return - Boolean.FALSE; - // throw new RuntimeException("LIKE can only operate on String identifiers. LIKE attemped on: '" + rv.getClass()); - } - - return likePattern.matcher((String) rv).matches() ? Boolean.TRUE : Boolean.FALSE; - } - - public boolean matches(AMQMessage message) throws AMQException - { - Object object = evaluate(message); - - return (object != null) && (object == Boolean.TRUE); - } - } - - public static BooleanExpression createLike(Expression left, String right, String escape) - { - if ((escape != null) && (escape.length() != 1)) - { - throw new RuntimeException( - "The ESCAPE string litteral is invalid. It can only be one character. Litteral used: " + escape); - } - - int c = -1; - if (escape != null) - { - c = 0xFFFF & escape.charAt(0); - } - - return new LikeExpression(left, right, c); - } - - public static BooleanExpression createNotLike(Expression left, String right, String escape) - { - return UnaryExpression.createNOT(createLike(left, right, escape)); - } - - public static BooleanExpression createInFilter(Expression left, List elements) - { - - if (!(left instanceof PropertyExpression)) - { - throw new RuntimeException("Expected a property for In expression, got: " + left); - } - - return UnaryExpression.createInExpression((PropertyExpression) left, elements, false); - - } - - public static BooleanExpression createNotInFilter(Expression left, List elements) - { - - if (!(left instanceof PropertyExpression)) - { - throw new RuntimeException("Expected a property for In expression, got: " + left); - } - - return UnaryExpression.createInExpression((PropertyExpression) left, elements, true); - - } - - public static BooleanExpression createIsNull(Expression left) - { - return doCreateEqual(left, ConstantExpression.NULL); - } - - public static BooleanExpression createIsNotNull(Expression left) - { - return UnaryExpression.createNOT(doCreateEqual(left, ConstantExpression.NULL)); - } - - public static BooleanExpression createNotEqual(Expression left, Expression right) - { - return UnaryExpression.createNOT(createEqual(left, right)); - } - - public static BooleanExpression createEqual(Expression left, Expression right) - { - checkEqualOperand(left); - checkEqualOperand(right); - checkEqualOperandCompatability(left, right); - - return doCreateEqual(left, right); - } - - private static BooleanExpression doCreateEqual(Expression left, Expression right) - { - return new ComparisonExpression(left, right) - { - - public Object evaluate(AMQMessage message) throws AMQException - { - Object lv = left.evaluate(message); - Object rv = right.evaluate(message); - - // Iff one of the values is null - if ((lv == null) ^ (rv == null)) - { - return Boolean.FALSE; - } - - if ((lv == rv) || lv.equals(rv)) - { - return Boolean.TRUE; - } - - if ((lv instanceof Comparable) && (rv instanceof Comparable)) - { - return compare((Comparable) lv, (Comparable) rv); - } - - return Boolean.FALSE; - } - - protected boolean asBoolean(int answer) - { - return answer == 0; - } - - public String getExpressionSymbol() - { - return "="; - } - }; - } - - public static BooleanExpression createGreaterThan(final Expression left, final Expression right) - { - checkLessThanOperand(left); - checkLessThanOperand(right); - - return new ComparisonExpression(left, right) - { - protected boolean asBoolean(int answer) - { - return answer > 0; - } - - public String getExpressionSymbol() - { - return ">"; - } - }; - } - - public static BooleanExpression createGreaterThanEqual(final Expression left, final Expression right) - { - checkLessThanOperand(left); - checkLessThanOperand(right); - - return new ComparisonExpression(left, right) - { - protected boolean asBoolean(int answer) - { - return answer >= 0; - } - - public String getExpressionSymbol() - { - return ">="; - } - }; - } - - public static BooleanExpression createLessThan(final Expression left, final Expression right) - { - checkLessThanOperand(left); - checkLessThanOperand(right); - - return new ComparisonExpression(left, right) - { - - protected boolean asBoolean(int answer) - { - return answer < 0; - } - - public String getExpressionSymbol() - { - return "<"; - } - - }; - } - - public static BooleanExpression createLessThanEqual(final Expression left, final Expression right) - { - checkLessThanOperand(left); - checkLessThanOperand(right); - - return new ComparisonExpression(left, right) - { - - protected boolean asBoolean(int answer) - { - return answer <= 0; - } - - public String getExpressionSymbol() - { - return "<="; - } - }; - } - - /** - * Only Numeric expressions can be used in >, >=, < or <= expressions.s - * - * @param expr - */ - public static void checkLessThanOperand(Expression expr) - { - if (expr instanceof ConstantExpression) - { - Object value = ((ConstantExpression) expr).getValue(); - if (value instanceof Number) - { - return; - } - - // Else it's boolean or a String.. - throw new RuntimeException("Value '" + expr + "' cannot be compared."); - } - - if (expr instanceof BooleanExpression) - { - throw new RuntimeException("Value '" + expr + "' cannot be compared."); - } - } - - /** - * Validates that the expression can be used in == or <> expression. - * Cannot not be NULL TRUE or FALSE litterals. - * - * @param expr - */ - public static void checkEqualOperand(Expression expr) - { - if (expr instanceof ConstantExpression) - { - Object value = ((ConstantExpression) expr).getValue(); - if (value == null) - { - throw new RuntimeException("'" + expr + "' cannot be compared."); - } - } - } - - /** - * - * @param left - * @param right - */ - private static void checkEqualOperandCompatability(Expression left, Expression right) - { - if ((left instanceof ConstantExpression) && (right instanceof ConstantExpression)) - { - if ((left instanceof BooleanExpression) && !(right instanceof BooleanExpression)) - { - throw new RuntimeException("'" + left + "' cannot be compared with '" + right + "'"); - } - } - } - - /** - * @param left - * @param right - */ - public ComparisonExpression(Expression left, Expression right) - { - super(left, right); - } - - public Object evaluate(AMQMessage message) throws AMQException - { - Comparable lv = (Comparable) left.evaluate(message); - if (lv == null) - { - return null; - } - - Comparable rv = (Comparable) right.evaluate(message); - if (rv == null) - { - return null; - } - - return compare(lv, rv); - } - - protected Boolean compare(Comparable lv, Comparable rv) - { - Class lc = lv.getClass(); - Class rc = rv.getClass(); - // If the the objects are not of the same type, - // try to convert up to allow the comparison. - if (lc != rc) - { - if (lc == Byte.class) - { - if (rc == Short.class) - { - lv = new Short(((Number) lv).shortValue()); - } - else if (rc == Integer.class) - { - lv = new Integer(((Number) lv).intValue()); - } - else if (rc == Long.class) - { - lv = new Long(((Number) lv).longValue()); - } - else if (rc == Float.class) - { - lv = new Float(((Number) lv).floatValue()); - } - else if (rc == Double.class) - { - lv = new Double(((Number) lv).doubleValue()); - } - else - { - return Boolean.FALSE; - } - } - else if (lc == Short.class) - { - if (rc == Integer.class) - { - lv = new Integer(((Number) lv).intValue()); - } - else if (rc == Long.class) - { - lv = new Long(((Number) lv).longValue()); - } - else if (rc == Float.class) - { - lv = new Float(((Number) lv).floatValue()); - } - else if (rc == Double.class) - { - lv = new Double(((Number) lv).doubleValue()); - } - else - { - return Boolean.FALSE; - } - } - else if (lc == Integer.class) - { - if (rc == Long.class) - { - lv = new Long(((Number) lv).longValue()); - } - else if (rc == Float.class) - { - lv = new Float(((Number) lv).floatValue()); - } - else if (rc == Double.class) - { - lv = new Double(((Number) lv).doubleValue()); - } - else - { - return Boolean.FALSE; - } - } - else if (lc == Long.class) - { - if (rc == Integer.class) - { - rv = new Long(((Number) rv).longValue()); - } - else if (rc == Float.class) - { - lv = new Float(((Number) lv).floatValue()); - } - else if (rc == Double.class) - { - lv = new Double(((Number) lv).doubleValue()); - } - else - { - return Boolean.FALSE; - } - } - else if (lc == Float.class) - { - if (rc == Integer.class) - { - rv = new Float(((Number) rv).floatValue()); - } - else if (rc == Long.class) - { - rv = new Float(((Number) rv).floatValue()); - } - else if (rc == Double.class) - { - lv = new Double(((Number) lv).doubleValue()); - } - else - { - return Boolean.FALSE; - } - } - else if (lc == Double.class) - { - if (rc == Integer.class) - { - rv = new Double(((Number) rv).doubleValue()); - } - else if (rc == Long.class) - { - rv = new Double(((Number) rv).doubleValue()); - } - else if (rc == Float.class) - { - rv = new Float(((Number) rv).doubleValue()); - } - else - { - return Boolean.FALSE; - } - } - else - { - return Boolean.FALSE; - } - } - - return asBoolean(lv.compareTo(rv)) ? Boolean.TRUE : Boolean.FALSE; - } - - protected abstract boolean asBoolean(int answer); - - public boolean matches(AMQMessage message) throws AMQException - { - Object object = evaluate(message); - - return (object != null) && (object == Boolean.TRUE); - } - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/ConstantExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/ConstantExpression.java deleted file mode 100644 index 0e729cc521..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/filter/ConstantExpression.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.filter; -// -// Based on like named file from r450141 of the Apache ActiveMQ project <http://www.activemq.org/site/home.html> -// - -import java.math.BigDecimal; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.queue.AMQMessage; - -/** - * Represents a constant expression - */ -public class ConstantExpression implements Expression -{ - - static class BooleanConstantExpression extends ConstantExpression implements BooleanExpression - { - public BooleanConstantExpression(Object value) - { - super(value); - } - - public boolean matches(AMQMessage message) throws AMQException - { - Object object = evaluate(message); - - return (object != null) && (object == Boolean.TRUE); - } - } - - public static final BooleanConstantExpression NULL = new BooleanConstantExpression(null); - public static final BooleanConstantExpression TRUE = new BooleanConstantExpression(Boolean.TRUE); - public static final BooleanConstantExpression FALSE = new BooleanConstantExpression(Boolean.FALSE); - - private Object value; - - public static ConstantExpression createFromDecimal(String text) - { - - // Strip off the 'l' or 'L' if needed. - if (text.endsWith("l") || text.endsWith("L")) - { - text = text.substring(0, text.length() - 1); - } - - Number value; - try - { - value = new Long(text); - } - catch (NumberFormatException e) - { - // The number may be too big to fit in a long. - value = new BigDecimal(text); - } - - long l = value.longValue(); - if ((Integer.MIN_VALUE <= l) && (l <= Integer.MAX_VALUE)) - { - value = new Integer(value.intValue()); - } - - return new ConstantExpression(value); - } - - public static ConstantExpression createFromHex(String text) - { - Number value = new Long(Long.parseLong(text.substring(2), 16)); - long l = value.longValue(); - if ((Integer.MIN_VALUE <= l) && (l <= Integer.MAX_VALUE)) - { - value = new Integer(value.intValue()); - } - - return new ConstantExpression(value); - } - - public static ConstantExpression createFromOctal(String text) - { - Number value = new Long(Long.parseLong(text, 8)); - long l = value.longValue(); - if ((Integer.MIN_VALUE <= l) && (l <= Integer.MAX_VALUE)) - { - value = new Integer(value.intValue()); - } - - return new ConstantExpression(value); - } - - public static ConstantExpression createFloat(String text) - { - Number value = new Double(text); - - return new ConstantExpression(value); - } - - public ConstantExpression(Object value) - { - this.value = value; - } - - public Object evaluate(AMQMessage message) throws AMQException - { - return value; - } - - public Object getValue() - { - return value; - } - - /** - * @see java.lang.Object#toString() - */ - public String toString() - { - if (value == null) - { - return "NULL"; - } - - if (value instanceof Boolean) - { - return ((Boolean) value).booleanValue() ? "TRUE" : "FALSE"; - } - - if (value instanceof String) - { - return encodeString((String) value); - } - - return value.toString(); - } - - /** - * TODO: more efficient hashCode() - * - * @see java.lang.Object#hashCode() - */ - public int hashCode() - { - return toString().hashCode(); - } - - /** - * TODO: more efficient hashCode() - * - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object o) - { - - if ((o == null) || !this.getClass().equals(o.getClass())) - { - return false; - } - - return toString().equals(o.toString()); - - } - - /** - * Encodes the value of string so that it looks like it would look like - * when it was provided in a selector. - * - * @param s - * @return - */ - public static String encodeString(String s) - { - StringBuffer b = new StringBuffer(); - b.append('\''); - for (int i = 0; i < s.length(); i++) - { - char c = s.charAt(i); - if (c == '\'') - { - b.append(c); - } - - b.append(c); - } - - b.append('\''); - - return b.toString(); - } - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/Expression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/Expression.java deleted file mode 100644 index 5f646c15db..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/filter/Expression.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.qpid.server.filter; -// -// Based on like named file from r450141 of the Apache ActiveMQ project <http://www.activemq.org/site/home.html> -// - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.queue.AMQMessage; - -/** - * Represents an expression - */ -public interface Expression -{ - - /** - * @return the value of this expression - */ - public Object evaluate(AMQMessage message) throws AMQException; - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/FilterManager.java b/java/broker/src/main/java/org/apache/qpid/server/filter/FilterManager.java deleted file mode 100644 index c82de9fa15..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/filter/FilterManager.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.filter; -// -// Based on like named file from r450141 of the Apache ActiveMQ project <http://www.activemq.org/site/home.html> -// - -import org.apache.qpid.server.queue.AMQMessage; - -public interface FilterManager -{ - void add(MessageFilter filter); - - void remove(MessageFilter filter); - - boolean allAllow(AMQMessage msg); - - boolean hasFilters(); -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/FilterManagerFactory.java b/java/broker/src/main/java/org/apache/qpid/server/filter/FilterManagerFactory.java deleted file mode 100644 index 311f0680ec..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/filter/FilterManagerFactory.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.filter; - -import org.apache.qpid.AMQException; -import org.apache.qpid.common.AMQPFilterTypes; -import org.apache.qpid.framing.FieldTable; - - -public class FilterManagerFactory -{ - //private final static Logger _logger = LoggerFactory.getLogger(FilterManagerFactory.class); - private final static org.apache.log4j.Logger _logger = org.apache.log4j.Logger.getLogger(FilterManagerFactory.class); - - //fixme move to a common class so it can be refered to from client code. - - public static FilterManager createManager(FieldTable filters) throws AMQException - { - FilterManager manager = null; - - if (filters != null) - { - - manager = new SimpleFilterManager(); - - if(filters.containsKey(AMQPFilterTypes.JMS_SELECTOR.getValue())) - { - String selector = filters.getString(AMQPFilterTypes.JMS_SELECTOR.getValue()); - - if (selector != null && !selector.equals("")) - { - manager.add(new JMSSelectorFilter(selector)); - } - - } - - if (filters.containsKey(AMQPFilterTypes.NO_CONSUME.getValue())) - { - manager.add(new NoConsumerFilter()); - } - - - - //If we added no filters don't bear the overhead of having an filter manager - if (!manager.hasFilters()) - { - manager = null; - } - } - else - { - _logger.debug("No Filters found."); - } - - - return manager; - - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/JMSSelectorFilter.java b/java/broker/src/main/java/org/apache/qpid/server/filter/JMSSelectorFilter.java deleted file mode 100644 index 2061803d65..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/filter/JMSSelectorFilter.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.filter; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.server.filter.jms.selector.SelectorParser; -import org.apache.qpid.server.queue.AMQMessage; - - - -public class JMSSelectorFilter implements MessageFilter -{ - private final static Logger _logger = org.apache.log4j.Logger.getLogger(JMSSelectorFilter.class); - - private String _selector; - private BooleanExpression _matcher; - - public JMSSelectorFilter(String selector) throws AMQException - { - _selector = selector; - _logger.info("Created JMSSelectorFilter with selector:" + _selector); - - - _matcher = new SelectorParser().parse(selector); - - - } - - public boolean matches(AMQMessage message) - { - try - { - boolean match = _matcher.matches(message); - _logger.info(message + " match(" + match + ") selector(" + System.identityHashCode(_selector) + "):" + _selector); - return match; - } - catch (AMQException e) - { - //fixme this needs to be sorted.. it shouldn't happen - e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. - } - return false; - } - - public String getSelector() - { - return _selector; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/LogicExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/LogicExpression.java deleted file mode 100644 index c8cbdb2125..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/filter/LogicExpression.java +++ /dev/null @@ -1,110 +0,0 @@ -/** - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.qpid.server.filter; -// -// Based on like named file from r450141 of the Apache ActiveMQ project <http://www.activemq.org/site/home.html> -// - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.queue.AMQMessage; - -/** - * A filter performing a comparison of two objects - */ -public abstract class LogicExpression extends BinaryExpression implements BooleanExpression -{ - - public static BooleanExpression createOR(BooleanExpression lvalue, BooleanExpression rvalue) - { - return new LogicExpression(lvalue, rvalue) - { - - public Object evaluate(AMQMessage message) throws AMQException - { - - Boolean lv = (Boolean) left.evaluate(message); - // Can we do an OR shortcut?? - if ((lv != null) && lv.booleanValue()) - { - return Boolean.TRUE; - } - - Boolean rv = (Boolean) right.evaluate(message); - - return (rv == null) ? null : rv; - } - - public String getExpressionSymbol() - { - return "OR"; - } - }; - } - - public static BooleanExpression createAND(BooleanExpression lvalue, BooleanExpression rvalue) - { - return new LogicExpression(lvalue, rvalue) - { - - public Object evaluate(AMQMessage message) throws AMQException - { - - Boolean lv = (Boolean) left.evaluate(message); - - // Can we do an AND shortcut?? - if (lv == null) - { - return null; - } - - if (!lv.booleanValue()) - { - return Boolean.FALSE; - } - - Boolean rv = (Boolean) right.evaluate(message); - - return (rv == null) ? null : rv; - } - - public String getExpressionSymbol() - { - return "AND"; - } - }; - } - - /** - * @param left - * @param right - */ - public LogicExpression(BooleanExpression left, BooleanExpression right) - { - super(left, right); - } - - public abstract Object evaluate(AMQMessage message) throws AMQException; - - public boolean matches(AMQMessage message) throws AMQException - { - Object object = evaluate(message); - - return (object != null) && (object == Boolean.TRUE); - } - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/MessageFilter.java b/java/broker/src/main/java/org/apache/qpid/server/filter/MessageFilter.java deleted file mode 100644 index e6bfe974d5..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/filter/MessageFilter.java +++ /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. - * - * - */ -package org.apache.qpid.server.filter; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.queue.AMQMessage; - -public interface MessageFilter -{ - boolean matches(AMQMessage message) throws AMQException; -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/NoConsumerFilter.java b/java/broker/src/main/java/org/apache/qpid/server/filter/NoConsumerFilter.java deleted file mode 100644 index 47ca930d12..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/filter/NoConsumerFilter.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.filter; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.server.queue.AMQMessage; - -public class NoConsumerFilter implements MessageFilter -{ - private final static Logger _logger = org.apache.log4j.Logger.getLogger(NoConsumerFilter.class); - - - public NoConsumerFilter() throws AMQException - { - _logger.info("Created NoConsumerFilter"); - } - - public boolean matches(AMQMessage message) - { - return true; - } - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/PropertyExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/PropertyExpression.java deleted file mode 100644 index 5ab360ca19..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/filter/PropertyExpression.java +++ /dev/null @@ -1,322 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.filter; -// -// Based on like named file from r450141 of the Apache ActiveMQ project <http://www.activemq.org/site/home.html> -// - -import java.util.HashMap; - -import org.apache.log4j.Logger; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.CommonContentHeaderProperties; -import org.apache.qpid.server.queue.AMQMessage; - -/** - * Represents a property expression - */ -public class PropertyExpression implements Expression -{ - // Constants - defined the same as JMS - private static final int NON_PERSISTENT = 1; - private static final int PERSISTENT = 2; - private static final int DEFAULT_PRIORITY = 4; - - private static final Logger _logger = org.apache.log4j.Logger.getLogger(PropertyExpression.class); - - private static final HashMap<String, Expression> JMS_PROPERTY_EXPRESSIONS = new HashMap<String, Expression>(); - - static - { - JMS_PROPERTY_EXPRESSIONS.put("JMSDestination", new Expression() - { - public Object evaluate(AMQMessage message) - { - //TODO - return null; - } - }); - JMS_PROPERTY_EXPRESSIONS.put("JMSReplyTo", new Expression() - { - public Object evaluate(AMQMessage message) - { - try - { - CommonContentHeaderProperties _properties = - (CommonContentHeaderProperties) - message.getContentHeaderBody().properties; - AMQShortString replyTo = _properties.getReplyTo(); - - return (replyTo == null) ? null : replyTo.toString(); - } - catch (AMQException e) - { - _logger.warn(e); - - return null; - } - - } - - }); - - JMS_PROPERTY_EXPRESSIONS.put("JMSType", new Expression() - { - public Object evaluate(AMQMessage message) - { - try - { - CommonContentHeaderProperties _properties = - (CommonContentHeaderProperties) - message.getContentHeaderBody().properties; - AMQShortString type = _properties.getType(); - - return (type == null) ? null : type.toString(); - } - catch (AMQException e) - { - _logger.warn(e); - - return null; - } - - } - }); - - JMS_PROPERTY_EXPRESSIONS.put("JMSDeliveryMode", new Expression() - { - public Object evaluate(AMQMessage message) - { - try - { - int mode = message.isPersistent() ? PERSISTENT : NON_PERSISTENT; - if (_logger.isDebugEnabled()) - { - _logger.debug("JMSDeliveryMode is :" + mode); - } - - return mode; - } - catch (AMQException e) - { - _logger.warn(e); - } - - return NON_PERSISTENT; - } - }); - - JMS_PROPERTY_EXPRESSIONS.put("JMSPriority", new Expression() - { - public Object evaluate(AMQMessage message) - { - try - { - CommonContentHeaderProperties _properties = - (CommonContentHeaderProperties) - message.getContentHeaderBody().properties; - - return (int) _properties.getPriority(); - } - catch (AMQException e) - { - _logger.warn(e); - } - - return DEFAULT_PRIORITY; - } - }); - - JMS_PROPERTY_EXPRESSIONS.put("AMQMessageID", new Expression() - { - public Object evaluate(AMQMessage message) - { - - try - { - CommonContentHeaderProperties _properties = - (CommonContentHeaderProperties) - message.getContentHeaderBody().properties; - AMQShortString messageId = _properties.getMessageId(); - - return (messageId == null) ? null : messageId; - } - catch (AMQException e) - { - _logger.warn(e); - - return null; - } - - } - }); - - JMS_PROPERTY_EXPRESSIONS.put("JMSTimestamp", new Expression() - { - public Object evaluate(AMQMessage message) - { - - try - { - CommonContentHeaderProperties _properties = - (CommonContentHeaderProperties) - message.getContentHeaderBody().properties; - - return _properties.getTimestamp(); - } - catch (AMQException e) - { - _logger.warn(e); - - return null; - } - - } - }); - - JMS_PROPERTY_EXPRESSIONS.put("JMSCorrelationID", new Expression() - { - public Object evaluate(AMQMessage message) - { - - try - { - CommonContentHeaderProperties _properties = - (CommonContentHeaderProperties) - message.getContentHeaderBody().properties; - AMQShortString correlationId = _properties.getCorrelationId(); - - return (correlationId == null) ? null : correlationId.toString(); - } - catch (AMQException e) - { - _logger.warn(e); - - return null; - } - - } - }); - - JMS_PROPERTY_EXPRESSIONS.put("JMSExpiration", new Expression() - { - public Object evaluate(AMQMessage message) - { - - try - { - CommonContentHeaderProperties _properties = - (CommonContentHeaderProperties) - message.getContentHeaderBody().properties; - - return _properties.getExpiration(); - } - catch (AMQException e) - { - _logger.warn(e); - - return null; - } - - } - }); - - JMS_PROPERTY_EXPRESSIONS.put("JMSRedelivered", new Expression() - { - public Object evaluate(AMQMessage message) - { - return message.isRedelivered(); - } - }); - - } - - private final String name; - private final Expression jmsPropertyExpression; - - public PropertyExpression(String name) - { - this.name = name; - jmsPropertyExpression = JMS_PROPERTY_EXPRESSIONS.get(name); - } - - public Object evaluate(AMQMessage message) throws AMQException - { - - if (jmsPropertyExpression != null) - { - return jmsPropertyExpression.evaluate(message); - } - else - { - - CommonContentHeaderProperties _properties = - (CommonContentHeaderProperties) message.getContentHeaderBody().properties; - - if (_logger.isDebugEnabled()) - { - _logger.debug("Looking up property:" + name); - _logger.debug("Properties are:" + _properties.getHeaders().keySet()); - } - - return _properties.getHeaders().getObject(name); - } - } - - public String getName() - { - return name; - } - - /** - * @see java.lang.Object#toString() - */ - public String toString() - { - return name; - } - - /** - * @see java.lang.Object#hashCode() - */ - public int hashCode() - { - return name.hashCode(); - } - - /** - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object o) - { - - if ((o == null) || !this.getClass().equals(o.getClass())) - { - return false; - } - - return name.equals(((PropertyExpression) o).name); - - } - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/SimpleFilterManager.java b/java/broker/src/main/java/org/apache/qpid/server/filter/SimpleFilterManager.java deleted file mode 100644 index 62a45f5420..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/filter/SimpleFilterManager.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.filter; - -import java.util.concurrent.ConcurrentLinkedQueue; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.server.queue.AMQMessage; - -public class SimpleFilterManager implements FilterManager -{ - private final Logger _logger = Logger.getLogger(SimpleFilterManager.class); - - private final ConcurrentLinkedQueue<MessageFilter> _filters; - - public SimpleFilterManager() - { - _logger.debug("Creating SimpleFilterManager"); - _filters = new ConcurrentLinkedQueue<MessageFilter>(); - } - - public void add(MessageFilter filter) - { - _filters.add(filter); - } - - public void remove(MessageFilter filter) - { - _filters.remove(filter); - } - - public boolean allAllow(AMQMessage msg) - { - for (MessageFilter filter : _filters) - { - try - { - if (!filter.matches(msg)) - { - return false; - } - } - catch (AMQException e) - { - //fixme - e.printStackTrace(); - return false; - } - } - return true; - } - - public boolean hasFilters() - { - return !_filters.isEmpty(); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/UnaryExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/UnaryExpression.java deleted file mode 100644 index 83b4ed5358..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/filter/UnaryExpression.java +++ /dev/null @@ -1,337 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.filter; -// -// Based on like named file from r450141 of the Apache ActiveMQ project <http://www.activemq.org/site/home.html> -// - -import java.math.BigDecimal; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.queue.AMQMessage; - -/** - * An expression which performs an operation on two expression values - */ -public abstract class UnaryExpression implements Expression -{ - - private static final BigDecimal BD_LONG_MIN_VALUE = BigDecimal.valueOf(Long.MIN_VALUE); - protected Expression right; - - public static Expression createNegate(Expression left) - { - return new UnaryExpression(left) - { - public Object evaluate(AMQMessage message) throws AMQException - { - Object rvalue = right.evaluate(message); - if (rvalue == null) - { - return null; - } - - if (rvalue instanceof Number) - { - return negate((Number) rvalue); - } - - return null; - } - - public String getExpressionSymbol() - { - return "-"; - } - }; - } - - public static BooleanExpression createInExpression(PropertyExpression right, List elements, final boolean not) - { - - // Use a HashSet if there are many elements. - Collection t; - if (elements.size() == 0) - { - t = null; - } - else if (elements.size() < 5) - { - t = elements; - } - else - { - t = new HashSet(elements); - } - - final Collection inList = t; - - return new BooleanUnaryExpression(right) - { - public Object evaluate(AMQMessage message) throws AMQException - { - - Object rvalue = right.evaluate(message); - if (rvalue == null) - { - return null; - } - - if (rvalue.getClass() != String.class) - { - return null; - } - - if (((inList != null) && inList.contains(rvalue)) ^ not) - { - return Boolean.TRUE; - } - else - { - return Boolean.FALSE; - } - - } - - public String toString() - { - StringBuffer answer = new StringBuffer(); - answer.append(right); - answer.append(" "); - answer.append(getExpressionSymbol()); - answer.append(" ( "); - - int count = 0; - for (Iterator i = inList.iterator(); i.hasNext();) - { - Object o = (Object) i.next(); - if (count != 0) - { - answer.append(", "); - } - - answer.append(o); - count++; - } - - answer.append(" )"); - - return answer.toString(); - } - - public String getExpressionSymbol() - { - if (not) - { - return "NOT IN"; - } - else - { - return "IN"; - } - } - }; - } - - abstract static class BooleanUnaryExpression extends UnaryExpression implements BooleanExpression - { - public BooleanUnaryExpression(Expression left) - { - super(left); - } - - public boolean matches(AMQMessage message) throws AMQException - { - Object object = evaluate(message); - - return (object != null) && (object == Boolean.TRUE); - } - } - ; - - public static BooleanExpression createNOT(BooleanExpression left) - { - return new BooleanUnaryExpression(left) - { - public Object evaluate(AMQMessage message) throws AMQException - { - Boolean lvalue = (Boolean) right.evaluate(message); - if (lvalue == null) - { - return null; - } - - return lvalue.booleanValue() ? Boolean.FALSE : Boolean.TRUE; - } - - public String getExpressionSymbol() - { - return "NOT"; - } - }; - } - - public static BooleanExpression createXPath(final String xpath) - { - return new XPathExpression(xpath); - } - - public static BooleanExpression createXQuery(final String xpath) - { - return new XQueryExpression(xpath); - } - - public static BooleanExpression createBooleanCast(Expression left) - { - return new BooleanUnaryExpression(left) - { - public Object evaluate(AMQMessage message) throws AMQException - { - Object rvalue = right.evaluate(message); - if (rvalue == null) - { - return null; - } - - if (!rvalue.getClass().equals(Boolean.class)) - { - return Boolean.FALSE; - } - - return ((Boolean) rvalue).booleanValue() ? Boolean.TRUE : Boolean.FALSE; - } - - public String toString() - { - return right.toString(); - } - - public String getExpressionSymbol() - { - return ""; - } - }; - } - - private static Number negate(Number left) - { - Class clazz = left.getClass(); - if (clazz == Integer.class) - { - return new Integer(-left.intValue()); - } - else if (clazz == Long.class) - { - return new Long(-left.longValue()); - } - else if (clazz == Float.class) - { - return new Float(-left.floatValue()); - } - else if (clazz == Double.class) - { - return new Double(-left.doubleValue()); - } - else if (clazz == BigDecimal.class) - { - // We ussually get a big deciamal when we have Long.MIN_VALUE constant in the - // Selector. Long.MIN_VALUE is too big to store in a Long as a positive so we store it - // as a Big decimal. But it gets Negated right away.. to here we try to covert it back - // to a Long. - BigDecimal bd = (BigDecimal) left; - bd = bd.negate(); - - if (BD_LONG_MIN_VALUE.compareTo(bd) == 0) - { - return new Long(Long.MIN_VALUE); - } - - return bd; - } - else - { - throw new RuntimeException("Don't know how to negate: " + left); - } - } - - public UnaryExpression(Expression left) - { - this.right = left; - } - - public Expression getRight() - { - return right; - } - - public void setRight(Expression expression) - { - right = expression; - } - - /** - * @see java.lang.Object#toString() - */ - public String toString() - { - return "(" + getExpressionSymbol() + " " + right.toString() + ")"; - } - - /** - * TODO: more efficient hashCode() - * - * @see java.lang.Object#hashCode() - */ - public int hashCode() - { - return toString().hashCode(); - } - - /** - * TODO: more efficient hashCode() - * - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object o) - { - - if ((o == null) || !this.getClass().equals(o.getClass())) - { - return false; - } - - return toString().equals(o.toString()); - - } - - /** - * Returns the symbol that represents this binary expression. For example, addition is - * represented by "+" - * - * @return - */ - public abstract String getExpressionSymbol(); - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/XPathExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/XPathExpression.java deleted file mode 100644 index 2fdea208f2..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/filter/XPathExpression.java +++ /dev/null @@ -1,127 +0,0 @@ -/** - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.qpid.server.filter; -// -// Based on like named file from r450141 of the Apache ActiveMQ project <http://www.activemq.org/site/home.html> -// - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.qpid.AMQException; -import org.apache.qpid.server.queue.AMQMessage; - -/** - * Used to evaluate an XPath Expression in a JMS selector. - */ -public final class XPathExpression implements BooleanExpression { - - private static final Log log = LogFactory.getLog(XPathExpression.class); - private static final String EVALUATOR_SYSTEM_PROPERTY = "org.apache.qpid.server.filter.XPathEvaluatorClassName"; - private static final String DEFAULT_EVALUATOR_CLASS_NAME=XalanXPathEvaluator.class.getName(); - - private static final Constructor EVALUATOR_CONSTRUCTOR; - - static { - String cn = System.getProperty(EVALUATOR_SYSTEM_PROPERTY, DEFAULT_EVALUATOR_CLASS_NAME); - Constructor m = null; - try { - try { - m = getXPathEvaluatorConstructor(cn); - } catch (Throwable e) { - log.warn("Invalid "+XPathEvaluator.class.getName()+" implementation: "+cn+", reason: "+e,e); - cn = DEFAULT_EVALUATOR_CLASS_NAME; - try { - m = getXPathEvaluatorConstructor(cn); - } catch (Throwable e2) { - log.error("Default XPath evaluator could not be loaded",e); - } - } - } finally { - EVALUATOR_CONSTRUCTOR = m; - } - } - - private static Constructor getXPathEvaluatorConstructor(String cn) throws ClassNotFoundException, SecurityException, NoSuchMethodException { - Class c = XPathExpression.class.getClassLoader().loadClass(cn); - if( !XPathEvaluator.class.isAssignableFrom(c) ) { - throw new ClassCastException(""+c+" is not an instance of "+XPathEvaluator.class); - } - return c.getConstructor(new Class[]{String.class}); - } - - private final String xpath; - private final XPathEvaluator evaluator; - - static public interface XPathEvaluator { - public boolean evaluate(AMQMessage message) throws AMQException; - } - - XPathExpression(String xpath) { - this.xpath = xpath; - this.evaluator = createEvaluator(xpath); - } - - private XPathEvaluator createEvaluator(String xpath2) { - try { - return (XPathEvaluator)EVALUATOR_CONSTRUCTOR.newInstance(new Object[]{xpath}); - } catch (InvocationTargetException e) { - Throwable cause = e.getCause(); - if( cause instanceof RuntimeException ) { - throw (RuntimeException)cause; - } - throw new RuntimeException("Invalid XPath Expression: "+xpath+" reason: "+e.getMessage(), e); - } catch (Throwable e) { - throw new RuntimeException("Invalid XPath Expression: "+xpath+" reason: "+e.getMessage(), e); - } - } - - public Object evaluate(AMQMessage message) throws AMQException { -// try { -//FIXME this is flow to disk work -// if( message.isDropped() ) -// return null; - return evaluator.evaluate(message) ? Boolean.TRUE : Boolean.FALSE; -// } catch (IOException e) { -// -// JMSException exception = new JMSException(e.getMessage()); -// exception.initCause(e); -// throw exception; -// -// } - - } - - public String toString() { - return "XPATH "+ConstantExpression.encodeString(xpath); - } - - /** - * @param message - * @return true if the expression evaluates to Boolean.TRUE. - * @throws AMQException - */ - public boolean matches(AMQMessage message) throws AMQException - { - Object object = evaluate(message); - return object!=null && object==Boolean.TRUE; - } - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/XQueryExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/XQueryExpression.java deleted file mode 100644 index f5debb607a..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/filter/XQueryExpression.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.qpid.server.filter; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.queue.AMQMessage; - -// -// Based on like named file from r450141 of the Apache ActiveMQ project <http://www.activemq.org/site/home.html> -// - -/** - * Used to evaluate an XQuery Expression in a JMS selector. - */ -public final class XQueryExpression implements BooleanExpression { - private final String xpath; - - XQueryExpression(String xpath) { - super(); - this.xpath = xpath; - } - - public Object evaluate(AMQMessage message) throws AMQException { - return Boolean.FALSE; - } - - public String toString() { - return "XQUERY "+ConstantExpression.encodeString(xpath); - } - - /** - * @param message - * @return true if the expression evaluates to Boolean.TRUE. - * @throws AMQException - */ - public boolean matches(AMQMessage message) throws AMQException - { - Object object = evaluate(message); - return object!=null && object==Boolean.TRUE; - } - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/XalanXPathEvaluator.java b/java/broker/src/main/java/org/apache/qpid/server/filter/XalanXPathEvaluator.java deleted file mode 100644 index 35d770fd5d..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/filter/XalanXPathEvaluator.java +++ /dev/null @@ -1,102 +0,0 @@ -/** - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.qpid.server.filter; -// -// Based on like named file from r450141 of the Apache ActiveMQ project <http://www.activemq.org/site/home.html> -// - -import java.io.ByteArrayInputStream; -import java.io.StringReader; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.queue.AMQMessage; -import org.apache.xpath.CachedXPathAPI; -import org.w3c.dom.Document; -import org.w3c.dom.traversal.NodeIterator; -import org.xml.sax.InputSource; - -public class XalanXPathEvaluator implements XPathExpression.XPathEvaluator { - - private final String xpath; - - public XalanXPathEvaluator(String xpath) { - this.xpath = xpath; - } - - public boolean evaluate(AMQMessage m) throws AMQException - { - // TODO - we would have to check the content type and then evaluate the content - // here... is this really a feature we wish to implement? - RobG - /* - - if( m instanceof TextMessage ) { - String text = ((TextMessage)m).getText(); - return evaluate(text); - } else if ( m instanceof BytesMessage ) { - BytesMessage bm = (BytesMessage) m; - byte data[] = new byte[(int) bm.getBodyLength()]; - bm.readBytes(data); - return evaluate(data); - } - */ - return false; - - } - - private boolean evaluate(byte[] data) { - try { - - InputSource inputSource = new InputSource(new ByteArrayInputStream(data)); - - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - DocumentBuilder dbuilder = factory.newDocumentBuilder(); - Document doc = dbuilder.parse(inputSource); - - CachedXPathAPI cachedXPathAPI = new CachedXPathAPI(); - NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc,xpath); - return iterator.nextNode()!=null; - - } catch (Throwable e) { - return false; - } - } - - private boolean evaluate(String text) { - try { - InputSource inputSource = new InputSource(new StringReader(text)); - - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - DocumentBuilder dbuilder = factory.newDocumentBuilder(); - Document doc = dbuilder.parse(inputSource); - - // We should associated the cachedXPathAPI object with the message being evaluated - // since that should speedup subsequent xpath expressions. - CachedXPathAPI cachedXPathAPI = new CachedXPathAPI(); - NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc,xpath); - return iterator.nextNode()!=null; - } catch (Throwable e) { - return false; - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicAckMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/BasicAckMethodHandler.java deleted file mode 100644 index a6972475a6..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicAckMethodHandler.java +++ /dev/null @@ -1,67 +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.handler; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.BasicAckBody; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.server.state.StateAwareMethodListener; - -public class BasicAckMethodHandler implements StateAwareMethodListener<BasicAckBody> -{ - private static final Logger _log = Logger.getLogger(BasicAckMethodHandler.class); - - private static final BasicAckMethodHandler _instance = new BasicAckMethodHandler(); - - public static BasicAckMethodHandler getInstance() - { - return _instance; - } - - private BasicAckMethodHandler() - { - } - - public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<BasicAckBody> evt) throws AMQException - { - AMQProtocolSession protocolSession = stateManager.getProtocolSession(); - BasicAckBody body = evt.getMethod(); - - if (_log.isDebugEnabled()) - { - _log.debug("Ack(Tag:" + body.deliveryTag + ":Mult:" + body.multiple + ") received on channel " + evt.getChannelId()); - } - - final AMQChannel channel = protocolSession.getChannel(evt.getChannelId()); - - if (channel == null) - { - throw body.getChannelNotFoundException(evt.getChannelId()); - } - - // this method throws an AMQException if the delivery tag is not known - channel.acknowledgeMessage(body.deliveryTag, body.multiple); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicCancelMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/BasicCancelMethodHandler.java deleted file mode 100644 index 8bab96a11b..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicCancelMethodHandler.java +++ /dev/null @@ -1,79 +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.handler; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQFrame; -import org.apache.qpid.framing.BasicCancelBody; -import org.apache.qpid.framing.BasicCancelOkBody; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.server.state.StateAwareMethodListener; -import org.apache.log4j.Logger; - -public class BasicCancelMethodHandler implements StateAwareMethodListener<BasicCancelBody> -{ - private static final Logger _log = Logger.getLogger(BasicCancelMethodHandler.class); - - private static final BasicCancelMethodHandler _instance = new BasicCancelMethodHandler(); - - public static BasicCancelMethodHandler getInstance() - { - return _instance; - } - - private BasicCancelMethodHandler() - { - } - - public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<BasicCancelBody> evt) throws AMQException - { - AMQProtocolSession protocolSession = stateManager.getProtocolSession(); - - final AMQChannel channel = protocolSession.getChannel(evt.getChannelId()); - final BasicCancelBody body = evt.getMethod(); - - if (channel == null) - { - throw body.getChannelNotFoundException(evt.getChannelId()); - } - - if (_log.isDebugEnabled()) - { - _log.debug("BasicCancel: for:" + body.consumerTag + - " nowait:" + body.nowait); - } - - channel.unsubscribeConsumer(protocolSession, body.consumerTag); - if (!body.nowait) - { - // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0) - // TODO: Connect this to the session version obtained from ProtocolInitiation for this session. - // Be aware of possible changes to parameter order as versions change. - final AMQFrame responseFrame = BasicCancelOkBody.createAMQFrame(evt.getChannelId(), - (byte) 8, (byte) 0, // AMQP version (major, minor) - body.consumerTag); // consumerTag - protocolSession.writeFrame(responseFrame); - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicConsumeMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/BasicConsumeMethodHandler.java deleted file mode 100644 index ab4f2c4e64..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicConsumeMethodHandler.java +++ /dev/null @@ -1,175 +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.handler; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicConsumeBody; -import org.apache.qpid.framing.BasicConsumeOkBody; -import org.apache.qpid.framing.ChannelCloseBody; -import org.apache.qpid.framing.ConnectionCloseBody; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.ConsumerTagNotUniqueException; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.ExistingExclusiveSubscriptionException; -import org.apache.qpid.server.queue.ExistingSubscriptionPreventsExclusiveException; -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.server.state.StateAwareMethodListener; -import org.apache.qpid.server.virtualhost.VirtualHost; - -public class BasicConsumeMethodHandler implements StateAwareMethodListener<BasicConsumeBody> -{ - private static final Logger _log = Logger.getLogger(BasicConsumeMethodHandler.class); - - private static final BasicConsumeMethodHandler _instance = new BasicConsumeMethodHandler(); - - public static BasicConsumeMethodHandler getInstance() - { - return _instance; - } - - private BasicConsumeMethodHandler() - { - } - - public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<BasicConsumeBody> evt) throws AMQException - { - AMQProtocolSession session = stateManager.getProtocolSession(); - - BasicConsumeBody body = evt.getMethod(); - final int channelId = evt.getChannelId(); - - AMQChannel channel = session.getChannel(channelId); - - VirtualHost vHost = session.getVirtualHost(); - - if (channel == null) - { - throw body.getChannelNotFoundException(evt.getChannelId()); - } - else - { - if (_log.isDebugEnabled()) - { - _log.debug("BasicConsume: from '" + body.queue + - "' for:" + body.consumerTag + - " nowait:" + body.nowait + - " args:" + body.arguments); - } - - AMQQueue queue = body.queue == null ? channel.getDefaultQueue() : vHost.getQueueRegistry().getQueue(body.queue); - - if (queue == null) - { - if (_log.isTraceEnabled()) - { - _log.trace("No queue for '" + body.queue + "'"); - } - if (body.queue != null) - { - String msg = "No such queue, '" + body.queue + "'"; - throw body.getChannelException(AMQConstant.NOT_FOUND, msg); - } - else - { - String msg = "No queue name provided, no default queue defined."; - throw body.getConnectionException(AMQConstant.NOT_ALLOWED, msg); - } - } - else - { - - if (body.consumerTag != null) - { - body.consumerTag = body.consumerTag.intern(); - } - - try - { - AMQShortString consumerTag = channel.subscribeToQueue(body.consumerTag, queue, session, !body.noAck, - body.arguments, body.noLocal, body.exclusive); - if (!body.nowait) - { - // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0) - // TODO: Connect this to the session version obtained from ProtocolInitiation for this session. - // Be aware of possible changes to parameter order as versions change. - session.writeFrame(BasicConsumeOkBody.createAMQFrame(channelId, - (byte) 8, (byte) 0, // AMQP version (major, minor) - consumerTag)); // consumerTag - } - - //now allow queue to start async processing of any backlog of messages - queue.deliverAsync(); - } - catch (org.apache.qpid.AMQInvalidArgumentException ise) - { - _log.debug("Closing connection due to invalid selector"); - // Why doesn't this ChannelException work. -// throw body.getChannelException(AMQConstant.INVALID_ARGUMENT, ise.getMessage()); - // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0) - // TODO: Connect this to the session version obtained from ProtocolInitiation for this session. - // Be aware of possible changes to parameter order as versions change. - session.writeFrame(ChannelCloseBody.createAMQFrame(channelId, - (byte) 8, (byte) 0, // AMQP version (major, minor) - BasicConsumeBody.getClazz((byte) 8, (byte) 0), // classId - BasicConsumeBody.getMethod((byte) 8, (byte) 0), // methodId - AMQConstant.INVALID_ARGUMENT.getCode(), // replyCode - new AMQShortString(ise.getMessage()))); // replyText - } - catch (ConsumerTagNotUniqueException e) - { - AMQShortString msg = new AMQShortString("Non-unique consumer tag, '" + body.consumerTag + "'"); - // If the above doesn't work then perhaps this is wrong too. -// throw body.getConnectionException(AMQConstant.NOT_ALLOWED, -// "Non-unique consumer tag, '" + body.consumerTag + "'"); - // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0) - // TODO: Connect this to the session version obtained from ProtocolInitiation for this session. - // Be aware of possible changes to parameter order as versions change. - session.writeFrame(ConnectionCloseBody.createAMQFrame(channelId, - (byte) 8, (byte) 0, // AMQP version (major, minor) - BasicConsumeBody.getClazz((byte) 8, (byte) 0), // classId - BasicConsumeBody.getMethod((byte) 8, (byte) 0), // methodId - AMQConstant.NOT_ALLOWED.getCode(), // replyCode - msg)); // replyText - } - catch (ExistingExclusiveSubscriptionException e) - { - throw body.getChannelException(AMQConstant.ACCESS_REFUSED, - "Cannot subscribe to queue " - + queue.getName() - + " as it already has an existing exclusive consumer"); - } - catch (ExistingSubscriptionPreventsExclusiveException e) - { - throw body.getChannelException(AMQConstant.ACCESS_REFUSED, - "Cannot subscribe to queue " - + queue.getName() - + " exclusively as it already has a consumer"); - } - - } - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicGetMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/BasicGetMethodHandler.java deleted file mode 100644 index 782a89c704..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicGetMethodHandler.java +++ /dev/null @@ -1,95 +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.handler;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.BasicGetBody;
-import org.apache.qpid.framing.BasicGetEmptyBody;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.server.AMQChannel;
-import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.state.AMQStateManager;
-import org.apache.qpid.server.state.StateAwareMethodListener;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-
-public class BasicGetMethodHandler implements StateAwareMethodListener<BasicGetBody>
-{
- private static final Logger _log = Logger.getLogger(BasicGetMethodHandler.class);
-
- private static final BasicGetMethodHandler _instance = new BasicGetMethodHandler();
-
- public static BasicGetMethodHandler getInstance()
- {
- return _instance;
- }
-
- private BasicGetMethodHandler()
- {
- }
-
- public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<BasicGetBody> evt) throws AMQException
- {
- AMQProtocolSession session = stateManager.getProtocolSession();
-
- BasicGetBody body = evt.getMethod();
- final int channelId = evt.getChannelId();
- VirtualHost vHost = session.getVirtualHost();
-
- AMQChannel channel = session.getChannel(channelId);
- if (channel == null)
- {
- throw body.getChannelNotFoundException(evt.getChannelId());
- }
- else
- {
- AMQQueue queue = body.queue == null ? channel.getDefaultQueue() : vHost.getQueueRegistry().getQueue(body.queue);
-
- if (queue == null)
- {
- _log.info("No queue for '" + body.queue + "'");
- if(body.queue!=null)
- {
- throw body.getConnectionException(AMQConstant.NOT_FOUND,
- "No such queue, '" + body.queue + "'");
- }
- else
- {
- throw body.getConnectionException(AMQConstant.NOT_ALLOWED,
- "No queue name provided, no default queue defined.");
- }
- }
- else
- {
- if(!queue.performGet(session, channel, !body.noAck))
- {
-
-
- // TODO - set clusterId
- session.writeFrame(BasicGetEmptyBody.createAMQFrame(channelId, body.getMajor(), body.getMinor(), null));
- }
- }
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicPublishMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/BasicPublishMethodHandler.java deleted file mode 100644 index 541d2afaf4..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicPublishMethodHandler.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.handler; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.BasicPublishBody; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.framing.abstraction.MessagePublishInfo; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.server.state.StateAwareMethodListener; -import org.apache.qpid.server.virtualhost.VirtualHost; - -public class BasicPublishMethodHandler implements StateAwareMethodListener<BasicPublishBody> -{ - private static final Logger _log = Logger.getLogger(BasicPublishMethodHandler.class); - - private static final BasicPublishMethodHandler _instance = new BasicPublishMethodHandler(); - - - public static BasicPublishMethodHandler getInstance() - { - return _instance; - } - - private BasicPublishMethodHandler() - { - } - - public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<BasicPublishBody> evt) throws AMQException - { - AMQProtocolSession session = stateManager.getProtocolSession(); - - final BasicPublishBody body = evt.getMethod(); - - if (_log.isDebugEnabled()) - { - _log.debug("Publish received on channel " + evt.getChannelId()); - } - - // TODO: check the delivery tag field details - is it unique across the broker or per subscriber? - if (body.exchange == null) - { - body.exchange = ExchangeDefaults.DEFAULT_EXCHANGE_NAME; - - } - else - { - body.exchange = body.exchange.intern(); - } - VirtualHost vHost = session.getVirtualHost(); - Exchange e = vHost.getExchangeRegistry().getExchange(body.exchange); - // if the exchange does not exist we raise a channel exception - if (e == null) - { - throw body.getChannelException(AMQConstant.NOT_FOUND, "Unknown exchange name"); - } - else - { - // The partially populated BasicDeliver frame plus the received route body - // is stored in the channel. Once the final body frame has been received - // it is routed to the exchange. - AMQChannel channel = session.getChannel(evt.getChannelId()); - - if (channel == null) - { - throw body.getChannelNotFoundException(evt.getChannelId()); - } - - if(body.routingKey != null) - { - body.routingKey = body.routingKey.intern(); - } - - MessagePublishInfo info = session.getRegistry().getProtocolVersionMethodConverter().convertToInfo(body); - channel.setPublishFrame(info, session); - } - } -} - - diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicQosHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/BasicQosHandler.java deleted file mode 100644 index 3cd6a87f64..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicQosHandler.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.handler; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.BasicQosBody; -import org.apache.qpid.framing.BasicQosOkBody; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.server.state.StateAwareMethodListener; -import org.apache.qpid.server.AMQChannel; - -public class BasicQosHandler implements StateAwareMethodListener<BasicQosBody> -{ - private static final BasicQosHandler _instance = new BasicQosHandler(); - - public static BasicQosHandler getInstance() - { - return _instance; - } - - public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<BasicQosBody> evt) throws AMQException - { - AMQProtocolSession session = stateManager.getProtocolSession(); - AMQChannel channel = session.getChannel(evt.getChannelId()); - if (channel == null) - { - throw evt.getMethod().getChannelNotFoundException(evt.getChannelId()); - } - - channel.setPrefetchCount(evt.getMethod().prefetchCount); - channel.setPrefetchSize(evt.getMethod().prefetchSize); - - // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0) - // TODO: Connect this to the session version obtained from ProtocolInitiation for this session. - // Be aware of possible changes to parameter order as versions change. - session.writeFrame(BasicQosOkBody.createAMQFrame(evt.getChannelId(), (byte) 8, (byte) 0)); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicRecoverMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/BasicRecoverMethodHandler.java deleted file mode 100644 index a436c35473..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicRecoverMethodHandler.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.handler; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.BasicRecoverBody; -import org.apache.qpid.framing.BasicRecoverOkBody; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.server.state.StateAwareMethodListener; - -public class BasicRecoverMethodHandler implements StateAwareMethodListener<BasicRecoverBody> -{ - private static final Logger _logger = Logger.getLogger(BasicRecoverMethodHandler.class); - - private static final BasicRecoverMethodHandler _instance = new BasicRecoverMethodHandler(); - - public static BasicRecoverMethodHandler getInstance() - { - return _instance; - } - - public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<BasicRecoverBody> evt) throws AMQException - { - AMQProtocolSession session = stateManager.getProtocolSession(); - - _logger.debug("Recover received on protocol session " + session + " and channel " + evt.getChannelId()); - AMQChannel channel = session.getChannel(evt.getChannelId()); - BasicRecoverBody body = evt.getMethod(); - - if (channel == null) - { - throw body.getChannelNotFoundException(evt.getChannelId()); - } - - channel.resend(body.requeue); - - // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0) - // TODO: Connect this to the session version obtained from ProtocolInitiation for this session. - // Be aware of possible changes to parameter order as versions change. - session.writeFrame(BasicRecoverOkBody.createAMQFrame(evt.getChannelId(), (byte) 8, (byte) 0)); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicRejectMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/BasicRejectMethodHandler.java deleted file mode 100644 index 32c840106f..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/BasicRejectMethodHandler.java +++ /dev/null @@ -1,115 +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.handler; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.BasicRejectBody; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.ack.UnacknowledgedMessage; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.server.state.StateAwareMethodListener; - -public class BasicRejectMethodHandler implements StateAwareMethodListener<BasicRejectBody> -{ - private static final Logger _logger = Logger.getLogger(BasicRejectMethodHandler.class); - - private static BasicRejectMethodHandler _instance = new BasicRejectMethodHandler(); - - public static BasicRejectMethodHandler getInstance() - { - return _instance; - } - - private BasicRejectMethodHandler() - { - } - - public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<BasicRejectBody> evt) throws AMQException - { - AMQProtocolSession session = stateManager.getProtocolSession(); - - int channelId = evt.getChannelId(); - -// if (_logger.isDebugEnabled()) -// { -// _logger.debug("Rejecting:" + evt.getMethod().deliveryTag + -// ": Requeue:" + evt.getMethod().requeue + -//// ": Resend:" + evt.getMethod().resend + -// " on channel:" + channelId); -// } - - AMQChannel channel = session.getChannel(channelId); - - if (channel == null) - { - throw evt.getMethod().getChannelNotFoundException(channelId); - } - - if (_logger.isDebugEnabled()) - { - _logger.debug("Rejecting:" + evt.getMethod().deliveryTag + - ": Requeue:" + evt.getMethod().requeue + - //": Resend:" + evt.getMethod().resend + - " on channel:" + channel.debugIdentity()); - } - - long deliveryTag = evt.getMethod().deliveryTag; - - UnacknowledgedMessage message = channel.getUnacknowledgedMessageMap().get(deliveryTag); - - if (message == null) - { - _logger.warn("Dropping reject request as message is null for tag:" + deliveryTag); -// throw evt.getMethod().getChannelException(AMQConstant.NOT_FOUND, "Delivery Tag(" + deliveryTag + ")not known"); - } - else - { - - if (_logger.isTraceEnabled()) - { - _logger.trace("Rejecting: DT:" + deliveryTag + "-" + message.message.debugIdentity() + - ": Requeue:" + evt.getMethod().requeue + - //": Resend:" + evt.getMethod().resend + - " on channel:" + channel.debugIdentity()); - } - - // If we haven't requested message to be resent to this consumer then reject it from ever getting it. -// if (!evt.getMethod().resend) - { - message.message.reject(message.message.getDeliveredSubscription(message.queue)); - } - - if (evt.getMethod().requeue) - { - channel.requeue(deliveryTag); - } - else - { - _logger.warn("Dropping message as requeue not required and there is no dead letter queue"); -// message.queue = channel.getDefaultDeadLetterQueue(); -// channel.requeue(deliveryTag); - } - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseHandler.java deleted file mode 100644 index 1f4f1f9221..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseHandler.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.handler; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQFrame; -import org.apache.qpid.framing.ChannelCloseBody; -import org.apache.qpid.framing.ChannelCloseOkBody; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.server.state.StateAwareMethodListener; -import org.apache.qpid.server.AMQChannel; - -public class ChannelCloseHandler implements StateAwareMethodListener<ChannelCloseBody> -{ - private static final Logger _logger = Logger.getLogger(ChannelCloseHandler.class); - - private static ChannelCloseHandler _instance = new ChannelCloseHandler(); - - public static ChannelCloseHandler getInstance() - { - return _instance; - } - - private ChannelCloseHandler() - { - } - - public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ChannelCloseBody> evt) throws AMQException - { - AMQProtocolSession session = stateManager.getProtocolSession(); - ChannelCloseBody body = evt.getMethod(); - if (_logger.isInfoEnabled()) - { - _logger.info("Received channel close for id " + evt.getChannelId() + " citing class " + body.classId + - " and method " + body.methodId); - } - int channelId = evt.getChannelId(); - - AMQChannel channel = session.getChannel(channelId); - - if (channel == null) - { - throw body.getConnectionException(AMQConstant.CHANNEL_ERROR, "Trying to close unknown channel"); - } - - session.closeChannel(channelId); - // Client requested closure so we don't wait for ok we send it - stateManager.getProtocolSession().closeChannelOk(channelId); - - // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0) - // TODO: Connect this to the session version obtained from ProtocolInitiation for this session. - // Be aware of possible changes to parameter order as versions change. - AMQFrame response = ChannelCloseOkBody.createAMQFrame(evt.getChannelId(), (byte) 8, (byte) 0); - session.writeFrame(response); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseOkHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseOkHandler.java deleted file mode 100644 index ad5604e7ea..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseOkHandler.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.handler; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.ChannelCloseOkBody; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.server.state.StateAwareMethodListener; - -public class ChannelCloseOkHandler implements StateAwareMethodListener<ChannelCloseOkBody> -{ - private static final Logger _logger = Logger.getLogger(ChannelCloseOkHandler.class); - - private static ChannelCloseOkHandler _instance = new ChannelCloseOkHandler(); - - public static ChannelCloseOkHandler getInstance() - { - return _instance; - } - - private ChannelCloseOkHandler() - { - } - - public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ChannelCloseOkBody> evt) throws AMQException - { - int channelId = evt.getChannelId(); - _logger.info("Received channel-close-ok for channel-id " + channelId); - - // Let the Protocol Session know the channel is now closed. - stateManager.getProtocolSession().closeChannelOk(channelId); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelFlowHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelFlowHandler.java deleted file mode 100644 index bfa170cfc5..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelFlowHandler.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.handler; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQFrame; -import org.apache.qpid.framing.ChannelFlowBody; -import org.apache.qpid.framing.ChannelFlowOkBody; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.server.state.StateAwareMethodListener; - -public class ChannelFlowHandler implements StateAwareMethodListener<ChannelFlowBody> -{ - private static final Logger _logger = Logger.getLogger(ChannelFlowHandler.class); - - private static ChannelFlowHandler _instance = new ChannelFlowHandler(); - - public static ChannelFlowHandler getInstance() - { - return _instance; - } - - private ChannelFlowHandler() - { - } - - public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ChannelFlowBody> evt) throws AMQException - { - AMQProtocolSession session = stateManager.getProtocolSession(); - ChannelFlowBody body = evt.getMethod(); - - AMQChannel channel = session.getChannel(evt.getChannelId()); - - if (channel == null) - { - throw body.getChannelNotFoundException(evt.getChannelId()); - } - - channel.setSuspended(!body.active); - _logger.debug("Channel.Flow for channel " + evt.getChannelId() + ", active=" + body.active); - - // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0) - // TODO: Connect this to the session version obtained from ProtocolInitiation for this session. - // Be aware of possible changes to parameter order as versions change. - AMQFrame response = ChannelFlowOkBody.createAMQFrame(evt.getChannelId(), - (byte)8, (byte)0, // AMQP version (major, minor) - body.active); // active - session.writeFrame(response); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelOpenHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelOpenHandler.java deleted file mode 100644 index e4abae4f28..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelOpenHandler.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.handler; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQFrame; -import org.apache.qpid.framing.ChannelOpenBody; -import org.apache.qpid.framing.ChannelOpenOkBody; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.server.state.StateAwareMethodListener; -import org.apache.qpid.server.virtualhost.VirtualHost; - -public class ChannelOpenHandler implements StateAwareMethodListener<ChannelOpenBody> -{ - private static ChannelOpenHandler _instance = new ChannelOpenHandler(); - - public static ChannelOpenHandler getInstance() - { - return _instance; - } - - private ChannelOpenHandler() - { - } - - public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ChannelOpenBody> evt) throws AMQException - { - AMQProtocolSession session = stateManager.getProtocolSession(); - VirtualHost virtualHost = session.getVirtualHost(); - - final AMQChannel channel = new AMQChannel(session,evt.getChannelId(), virtualHost.getTransactionManager(), - virtualHost.getMessageStore(), - virtualHost.getExchangeRegistry()); - session.addChannel(channel); - // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0) - // TODO: Connect this to the session version obtained from ProtocolInitiation for this session. - // Be aware of possible changes to parameter order as versions change. - AMQFrame response = ChannelOpenOkBody.createAMQFrame(evt.getChannelId(), (byte)8, (byte)0); - session.writeFrame(response); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseMethodHandler.java deleted file mode 100644 index b086cad67f..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseMethodHandler.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.handler; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQFrame; -import org.apache.qpid.framing.ConnectionCloseBody; -import org.apache.qpid.framing.ConnectionCloseOkBody; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.server.state.StateAwareMethodListener; - -public class ConnectionCloseMethodHandler implements StateAwareMethodListener<ConnectionCloseBody> -{ - private static final Logger _logger = Logger.getLogger(ConnectionCloseMethodHandler.class); - - private static ConnectionCloseMethodHandler _instance = new ConnectionCloseMethodHandler(); - - public static ConnectionCloseMethodHandler getInstance() - { - return _instance; - } - - private ConnectionCloseMethodHandler() - { - } - - public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ConnectionCloseBody> evt) throws AMQException - { - AMQProtocolSession session = stateManager.getProtocolSession(); - final ConnectionCloseBody body = evt.getMethod(); - if (_logger.isInfoEnabled()) - { - _logger.info("ConnectionClose received with reply code/reply text " + body.replyCode + "/" + - body.replyText + " for " + session); - } - try - { - session.closeSession(); - } - catch (Exception e) - { - _logger.error("Error closing protocol session: " + e, e); - } - // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0) - // TODO: Connect this to the session version obtained from ProtocolInitiation for this session. - // Be aware of possible changes to parameter order as versions change. - final AMQFrame response = ConnectionCloseOkBody.createAMQFrame(evt.getChannelId(), (byte) 8, (byte) 0); - session.writeFrame(response); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseOkMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseOkMethodHandler.java deleted file mode 100644 index 853f4df435..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseOkMethodHandler.java +++ /dev/null @@ -1,63 +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.handler; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.ConnectionCloseOkBody; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.state.AMQState; -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.server.state.StateAwareMethodListener; - -public class ConnectionCloseOkMethodHandler implements StateAwareMethodListener<ConnectionCloseOkBody> -{ - private static final Logger _logger = Logger.getLogger(ConnectionCloseOkMethodHandler.class); - - private static ConnectionCloseOkMethodHandler _instance = new ConnectionCloseOkMethodHandler(); - - public static ConnectionCloseOkMethodHandler getInstance() - { - return _instance; - } - - private ConnectionCloseOkMethodHandler() - { - } - - public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ConnectionCloseOkBody> evt) throws AMQException - { - AMQProtocolSession session = stateManager.getProtocolSession(); - //todo should this not do more than just log the method? - _logger.info("Received Connection-close-ok"); - - try - { - stateManager.changeState(AMQState.CONNECTION_CLOSED); - session.closeSession(); - } - catch (Exception e) - { - _logger.error("Error closing protocol session: " + e, e); - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionOpenMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionOpenMethodHandler.java deleted file mode 100644 index 30a40c5a75..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionOpenMethodHandler.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.handler; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQFrame; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.ConnectionOpenBody; -import org.apache.qpid.framing.ConnectionOpenOkBody; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.state.AMQState; -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.server.state.StateAwareMethodListener; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.security.access.AccessResult; -import org.apache.qpid.server.security.access.AccessRights; -import org.apache.log4j.Logger; - -public class ConnectionOpenMethodHandler implements StateAwareMethodListener<ConnectionOpenBody> -{ - private static final Logger _logger = Logger.getLogger(ConnectionOpenMethodHandler.class); - - private static ConnectionOpenMethodHandler _instance = new ConnectionOpenMethodHandler(); - - public static ConnectionOpenMethodHandler getInstance() - { - return _instance; - } - - private ConnectionOpenMethodHandler() - { - } - - private static AMQShortString generateClientID() - { - return new AMQShortString(Long.toString(System.currentTimeMillis())); - } - - public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ConnectionOpenBody> evt) throws AMQException - { - AMQProtocolSession session = stateManager.getProtocolSession(); - ConnectionOpenBody body = evt.getMethod(); - - //ignore leading '/' - String virtualHostName; - if ((body.virtualHost != null) && body.virtualHost.charAt(0) == '/') - { - virtualHostName = new StringBuilder(body.virtualHost.subSequence(1, body.virtualHost.length())).toString(); - } - else - { - virtualHostName = body.virtualHost == null ? null : String.valueOf(body.virtualHost); - } - - VirtualHost virtualHost = stateManager.getVirtualHostRegistry().getVirtualHost(virtualHostName); - - if (virtualHost == null) - { - throw body.getConnectionException(AMQConstant.NOT_FOUND, "Unknown virtual host: '" + virtualHostName + "'"); - } - else - { - session.setVirtualHost(virtualHost); - - AccessResult result = virtualHost.getAccessManager().isAuthorized(virtualHost, session.getAuthorizedID(), AccessRights.Rights.ANY); - - switch (result.getStatus()) - { - default: - case REFUSED: - String error = "Any access denied to vHost '" + virtualHostName + "' by " - + result.getAuthorizer(); - - _logger.warn(error); - - throw body.getConnectionException(AMQConstant.ACCESS_REFUSED, error); - case GRANTED: - _logger.info("Granted any access to vHost '" + virtualHostName + "' for " + session.getAuthorizedID() - + " by '" + result.getAuthorizer() + "'"); - } - - // See Spec (0.8.2). Section 3.1.2 Virtual Hosts - if (session.getContextKey() == null) - { - session.setContextKey(generateClientID()); - } - - // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0) - // TODO: Connect this to the session version obtained from ProtocolInitiation for this session. - // Be aware of possible changes to parameter order as versions change. - AMQFrame response = ConnectionOpenOkBody.createAMQFrame((short) 0, - (byte) 8, (byte) 0, // AMQP version (major, minor) - body.virtualHost); - stateManager.changeState(AMQState.CONNECTION_OPEN); - session.writeFrame(response); - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionSecureOkMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionSecureOkMethodHandler.java deleted file mode 100644 index 43986adea7..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionSecureOkMethodHandler.java +++ /dev/null @@ -1,141 +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.handler; - -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQFrame; -import org.apache.qpid.framing.ConnectionCloseBody; -import org.apache.qpid.framing.ConnectionSecureBody; -import org.apache.qpid.framing.ConnectionSecureOkBody; -import org.apache.qpid.framing.ConnectionTuneBody; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.protocol.HeartbeatConfig; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.security.auth.manager.AuthenticationManager; -import org.apache.qpid.server.security.auth.AuthenticationResult; -import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal; -import org.apache.qpid.server.state.AMQState; -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.server.state.StateAwareMethodListener; - -public class ConnectionSecureOkMethodHandler implements StateAwareMethodListener<ConnectionSecureOkBody> -{ - private static final Logger _logger = Logger.getLogger(ConnectionSecureOkMethodHandler.class); - - private static ConnectionSecureOkMethodHandler _instance = new ConnectionSecureOkMethodHandler(); - - public static ConnectionSecureOkMethodHandler getInstance() - { - return _instance; - } - - private ConnectionSecureOkMethodHandler() - { - } - - public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ConnectionSecureOkBody> evt) throws AMQException - { - AMQProtocolSession session = stateManager.getProtocolSession(); - ConnectionSecureOkBody body = evt.getMethod(); - - //fixme Vhost not defined yet - //session.getVirtualHost().getAuthenticationManager(); - AuthenticationManager authMgr = ApplicationRegistry.getInstance().getAuthenticationManager(); - - SaslServer ss = session.getSaslServer(); - if (ss == null) - { - throw new AMQException(null, "No SASL context set up in session", null); - } - - AuthenticationResult authResult = authMgr.authenticate(ss, body.response); - switch (authResult.status) - { - case ERROR: - // Can't do this as we violate protocol. Need to send Close - // throw new AMQException(AMQConstant.NOT_ALLOWED.getCode(), AMQConstant.NOT_ALLOWED.getName()); - _logger.info("Authentication failed"); - stateManager.changeState(AMQState.CONNECTION_CLOSING); - // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0) - // TODO: Connect this to the session version obtained from ProtocolInitiation for this session. - // Be aware of possible changes to parameter order as versions change. - AMQFrame close = ConnectionCloseBody.createAMQFrame(0, - (byte)8, (byte)0, // AMQP version (major, minor) - ConnectionCloseBody.getClazz((byte)8, (byte)0), // classId - ConnectionCloseBody.getMethod((byte)8, (byte)0), // methodId - AMQConstant.NOT_ALLOWED.getCode(), // replyCode - AMQConstant.NOT_ALLOWED.getName()); // replyText - session.writeFrame(close); - disposeSaslServer(session); - break; - case SUCCESS: - _logger.info("Connected as: " + ss.getAuthorizationID()); - stateManager.changeState(AMQState.CONNECTION_NOT_TUNED); - // TODO: Check the value of channelMax here: This should be the max - // value of a 2-byte unsigned integer (as channel is only 2 bytes on the wire), - // not Integer.MAX_VALUE (which is signed 4 bytes). - // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0) - // TODO: Connect this to the session version obtained from ProtocolInitiation for this session. - // Be aware of possible changes to parameter order as versions change. - AMQFrame tune = ConnectionTuneBody.createAMQFrame(0, - (byte)8, (byte)0, // AMQP version (major, minor) - Integer.MAX_VALUE, // channelMax - ConnectionStartOkMethodHandler.getConfiguredFrameSize(), // frameMax - HeartbeatConfig.getInstance().getDelay()); // heartbeat - session.writeFrame(tune); - session.setAuthorizedID(new UsernamePrincipal(ss.getAuthorizationID())); - disposeSaslServer(session); - break; - case CONTINUE: - stateManager.changeState(AMQState.CONNECTION_NOT_AUTH); - // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0) - // TODO: Connect this to the session version obtained from ProtocolInitiation for this session. - // Be aware of possible changes to parameter order as versions change. - AMQFrame challenge = ConnectionSecureBody.createAMQFrame(0, - (byte)8, (byte)0, // AMQP version (major, minor) - authResult.challenge); // challenge - session.writeFrame(challenge); - } - } - - private void disposeSaslServer(AMQProtocolSession ps) - { - SaslServer ss = ps.getSaslServer(); - if (ss != null) - { - ps.setSaslServer(null); - try - { - ss.dispose(); - } - catch (SaslException e) - { - _logger.error("Error disposing of Sasl server: " + e); - } - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionStartOkMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionStartOkMethodHandler.java deleted file mode 100644 index 5dbd1b18de..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionStartOkMethodHandler.java +++ /dev/null @@ -1,172 +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.handler; - -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; - -import org.apache.commons.configuration.Configuration; -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQFrame; -import org.apache.qpid.framing.ConnectionSecureBody; -import org.apache.qpid.framing.ConnectionStartOkBody; -import org.apache.qpid.framing.ConnectionTuneBody; -import org.apache.qpid.framing.ConnectionCloseBody; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.protocol.HeartbeatConfig; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.security.auth.manager.AuthenticationManager; -import org.apache.qpid.server.security.auth.AuthenticationResult; -import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal; -import org.apache.qpid.server.state.AMQState; -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.server.state.StateAwareMethodListener; - - -public class ConnectionStartOkMethodHandler implements StateAwareMethodListener<ConnectionStartOkBody> -{ - private static final Logger _logger = Logger.getLogger(ConnectionStartOkMethodHandler.class); - - private static ConnectionStartOkMethodHandler _instance = new ConnectionStartOkMethodHandler(); - - private static final int DEFAULT_FRAME_SIZE = 65536; - - public static StateAwareMethodListener<ConnectionStartOkBody> getInstance() - { - return _instance; - } - - private ConnectionStartOkMethodHandler() - { - } - - public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ConnectionStartOkBody> evt) throws AMQException - { - AMQProtocolSession session = stateManager.getProtocolSession(); - final ConnectionStartOkBody body = evt.getMethod(); - _logger.info("SASL Mechanism selected: " + body.mechanism); - _logger.info("Locale selected: " + body.locale); - - AuthenticationManager authMgr = ApplicationRegistry.getInstance().getAuthenticationManager();//session.getVirtualHost().getAuthenticationManager(); - - SaslServer ss = null; - try - { - ss = authMgr.createSaslServer(String.valueOf(body.mechanism), session.getLocalFQDN()); - - if (ss == null) - { - throw body.getConnectionException(AMQConstant.RESOURCE_ERROR, "Unable to create SASL Server:" + body.mechanism - ); - } - - session.setSaslServer(ss); - - AuthenticationResult authResult = authMgr.authenticate(ss, body.response); - - //save clientProperties - if (session.getClientProperties() == null) - { - session.setClientProperties(body.clientProperties); - } - - switch (authResult.status) - { - case ERROR: - _logger.info("Authentication failed"); - stateManager.changeState(AMQState.CONNECTION_CLOSING); - // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0) - // TODO: Connect this to the session version obtained from ProtocolInitiation for this session. - // Be aware of possible changes to parameter order as versions change. - AMQFrame close = ConnectionCloseBody.createAMQFrame(0, - (byte) 8, (byte) 0, // AMQP version (major, minor) - ConnectionCloseBody.getClazz((byte) 8, (byte) 0), // classId - ConnectionCloseBody.getMethod((byte) 8, (byte) 0), // methodId - AMQConstant.NOT_ALLOWED.getCode(), // replyCode - AMQConstant.NOT_ALLOWED.getName()); // replyText - session.writeFrame(close); - disposeSaslServer(session); - break; - - case SUCCESS: - _logger.info("Connected as: " + ss.getAuthorizationID()); - session.setAuthorizedID(new UsernamePrincipal(ss.getAuthorizationID())); - - stateManager.changeState(AMQState.CONNECTION_NOT_TUNED); - // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0) - // TODO: Connect this to the session version obtained from ProtocolInitiation for this session. - // Be aware of possible changes to parameter order as versions change. - AMQFrame tune = ConnectionTuneBody.createAMQFrame(0, - (byte) 8, (byte) 0, // AMQP version (major, minor) - Integer.MAX_VALUE, // channelMax - getConfiguredFrameSize(), // frameMax - HeartbeatConfig.getInstance().getDelay()); // heartbeat - session.writeFrame(tune); - break; - case CONTINUE: - stateManager.changeState(AMQState.CONNECTION_NOT_AUTH); - // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0) - // TODO: Connect this to the session version obtained from ProtocolInitiation for this session. - // Be aware of possible changes to parameter order as versions change. - AMQFrame challenge = ConnectionSecureBody.createAMQFrame(0, - (byte) 8, (byte) 0, // AMQP version (major, minor) - authResult.challenge); // challenge - session.writeFrame(challenge); - } - } - catch (SaslException e) - { - disposeSaslServer(session); - throw new AMQException(null, "SASL error: " + e, e); - } - } - - private void disposeSaslServer(AMQProtocolSession ps) - { - SaslServer ss = ps.getSaslServer(); - if (ss != null) - { - ps.setSaslServer(null); - try - { - ss.dispose(); - } - catch (SaslException e) - { - _logger.error("Error disposing of Sasl server: " + e); - } - } - } - - static int getConfiguredFrameSize() - { - final Configuration config = ApplicationRegistry.getInstance().getConfiguration(); - final int framesize = config.getInt("advanced.framesize", DEFAULT_FRAME_SIZE); - _logger.info("Framesize set to " + framesize); - return framesize; - } -} - - - diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionTuneOkMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionTuneOkMethodHandler.java deleted file mode 100644 index ab7695955c..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionTuneOkMethodHandler.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.handler; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.ConnectionTuneOkBody; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.state.AMQState; -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.server.state.StateAwareMethodListener; - -public class ConnectionTuneOkMethodHandler implements StateAwareMethodListener<ConnectionTuneOkBody> -{ - private static final Logger _logger = Logger.getLogger(ConnectionTuneOkMethodHandler.class); - - private static ConnectionTuneOkMethodHandler _instance = new ConnectionTuneOkMethodHandler(); - - public static ConnectionTuneOkMethodHandler getInstance() - { - return _instance; - } - - public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ConnectionTuneOkBody> evt) throws AMQException - { - AMQProtocolSession session = stateManager.getProtocolSession(); - ConnectionTuneOkBody body = evt.getMethod(); - if (_logger.isDebugEnabled()) - { - _logger.debug(body); - } - stateManager.changeState(AMQState.CONNECTION_NOT_OPENED); - session.initHeartbeats(body.heartbeat); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeBoundHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeBoundHandler.java deleted file mode 100644 index 0ff19bdf9e..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeBoundHandler.java +++ /dev/null @@ -1,205 +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.handler; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQFrame; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.ExchangeBoundBody; -import org.apache.qpid.framing.ExchangeBoundOkBody; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.QueueRegistry; -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.server.state.StateAwareMethodListener; -import org.apache.qpid.server.virtualhost.VirtualHost; - -/** - * @author Apache Software Foundation - */ -public class ExchangeBoundHandler implements StateAwareMethodListener<ExchangeBoundBody> -{ - private static final ExchangeBoundHandler _instance = new ExchangeBoundHandler(); - - public static final int OK = 0; - - public static final int EXCHANGE_NOT_FOUND = 1; - - public static final int QUEUE_NOT_FOUND = 2; - - public static final int NO_BINDINGS = 3; - - public static final int QUEUE_NOT_BOUND = 4; - - public static final int NO_QUEUE_BOUND_WITH_RK = 5; - - public static final int SPECIFIC_QUEUE_NOT_BOUND_WITH_RK = 6; - - public static ExchangeBoundHandler getInstance() - { - return _instance; - } - - private ExchangeBoundHandler() - { - } - - public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ExchangeBoundBody> evt) throws AMQException - { - AMQProtocolSession session = stateManager.getProtocolSession(); - VirtualHost virtualHost = session.getVirtualHost(); - QueueRegistry queueRegistry = virtualHost.getQueueRegistry(); - - // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0) - // TODO: Connect this to the session version obtained from ProtocolInitiation for this session. - byte major = (byte)8; - byte minor = (byte)0; - - ExchangeBoundBody body = evt.getMethod(); - - AMQShortString exchangeName = body.exchange; - AMQShortString queueName = body.queue; - AMQShortString routingKey = body.routingKey; - if (exchangeName == null) - { - throw new AMQException(null, "Exchange exchange must not be null", null); - } - Exchange exchange = virtualHost.getExchangeRegistry().getExchange(exchangeName); - AMQFrame response; - if (exchange == null) - { - // AMQP version change: Be aware of possible changes to parameter order as versions change. - response = ExchangeBoundOkBody.createAMQFrame(evt.getChannelId(), - major, minor, // AMQP version (major, minor) - EXCHANGE_NOT_FOUND, // replyCode - new AMQShortString("Exchange " + exchangeName + " not found")); // replyText - } - else if (routingKey == null) - { - if (queueName == null) - { - if (exchange.hasBindings()) - { - // AMQP version change: Be aware of possible changes to parameter order as versions change. - response = ExchangeBoundOkBody.createAMQFrame(evt.getChannelId(), - major, minor, // AMQP version (major, minor) - OK, // replyCode - null); // replyText - } - else - { - // AMQP version change: Be aware of possible changes to parameter order as versions change. - response = ExchangeBoundOkBody.createAMQFrame(evt.getChannelId(), - major, minor, // AMQP version (major, minor) - NO_BINDINGS, // replyCode - null); // replyText - } - } - else - { - - AMQQueue queue = queueRegistry.getQueue(queueName); - if (queue == null) - { - // AMQP version change: Be aware of possible changes to parameter order as versions change. - response = ExchangeBoundOkBody.createAMQFrame(evt.getChannelId(), - major, minor, // AMQP version (major, minor) - QUEUE_NOT_FOUND, // replyCode - new AMQShortString("Queue " + queueName + " not found")); // replyText - } - else - { - if (exchange.isBound(queue)) - { - // AMQP version change: Be aware of possible changes to parameter order as versions change. - response = ExchangeBoundOkBody.createAMQFrame(evt.getChannelId(), - major, minor, // AMQP version (major, minor) - OK, // replyCode - null); // replyText - } - else - { - // AMQP version change: Be aware of possible changes to parameter order as versions change. - response = ExchangeBoundOkBody.createAMQFrame(evt.getChannelId(), - major, minor, // AMQP version (major, minor) - QUEUE_NOT_BOUND, // replyCode - new AMQShortString("Queue " + queueName + " not bound to exchange " + exchangeName)); // replyText - } - } - } - } - else if (queueName != null) - { - AMQQueue queue = queueRegistry.getQueue(queueName); - if (queue == null) - { - // AMQP version change: Be aware of possible changes to parameter order as versions change. - response = ExchangeBoundOkBody.createAMQFrame(evt.getChannelId(), - major, minor, // AMQP version (major, minor) - QUEUE_NOT_FOUND, // replyCode - new AMQShortString("Queue " + queueName + " not found")); // replyText - } - else - { - if (exchange.isBound(body.routingKey, queue)) - { - // AMQP version change: Be aware of possible changes to parameter order as versions change. - response = ExchangeBoundOkBody.createAMQFrame(evt.getChannelId(), - major, minor, // AMQP version (major, minor) - OK, // replyCode - null); // replyText - } - else - { - // AMQP version change: Be aware of possible changes to parameter order as versions change. - response = ExchangeBoundOkBody.createAMQFrame(evt.getChannelId(), - major, minor, // AMQP version (major, minor) - SPECIFIC_QUEUE_NOT_BOUND_WITH_RK, // replyCode - new AMQShortString("Queue " + queueName + " not bound with routing key " + - body.routingKey + " to exchange " + exchangeName)); // replyText - } - } - } - else - { - if (exchange.isBound(body.routingKey)) - { - // AMQP version change: Be aware of possible changes to parameter order as versions change. - response = ExchangeBoundOkBody.createAMQFrame(evt.getChannelId(), - major, minor, // AMQP version (major, minor) - OK, // replyCode - null); // replyText - } - else - { - // AMQP version change: Be aware of possible changes to parameter order as versions change. - response = ExchangeBoundOkBody.createAMQFrame(evt.getChannelId(), - major, minor, // AMQP version (major, minor) - NO_QUEUE_BOUND_WITH_RK, // replyCode - new AMQShortString("No queue bound with routing key " + body.routingKey + - " to exchange " + exchangeName)); // replyText - } - } - session.writeFrame(response); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeDeclareHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeDeclareHandler.java deleted file mode 100644 index f0f6fde08c..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeDeclareHandler.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.handler; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQConnectionException; -import org.apache.qpid.AMQException; -import org.apache.qpid.AMQUnknownExchangeType; -import org.apache.qpid.framing.AMQFrame; -import org.apache.qpid.framing.ExchangeDeclareBody; -import org.apache.qpid.framing.ExchangeDeclareOkBody; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.exchange.ExchangeFactory; -import org.apache.qpid.server.exchange.ExchangeRegistry; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.server.state.StateAwareMethodListener; -import org.apache.qpid.server.virtualhost.VirtualHost; - -public class ExchangeDeclareHandler implements StateAwareMethodListener<ExchangeDeclareBody> -{ - private static final Logger _logger = Logger.getLogger(ExchangeDeclareHandler.class); - - private static final ExchangeDeclareHandler _instance = new ExchangeDeclareHandler(); - - public static ExchangeDeclareHandler getInstance() - { - return _instance; - } - - - - private ExchangeDeclareHandler() - { - } - - public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ExchangeDeclareBody> evt) throws AMQException - { - AMQProtocolSession session = stateManager.getProtocolSession(); - VirtualHost virtualHost = session.getVirtualHost(); - ExchangeRegistry exchangeRegistry = virtualHost.getExchangeRegistry(); - ExchangeFactory exchangeFactory = virtualHost.getExchangeFactory(); - - final ExchangeDeclareBody body = evt.getMethod(); - if (_logger.isDebugEnabled()) - { - _logger.debug("Request to declare exchange of type " + body.type + " with name " + body.exchange); - } - synchronized(exchangeRegistry) - { - Exchange exchange = exchangeRegistry.getExchange(body.exchange); - - - - if (exchange == null) - { - if(body.passive && ((body.type == null) || body.type.length() ==0)) - { - throw body.getChannelException(AMQConstant.NOT_FOUND, "Unknown exchange: " + body.exchange); - } - else - { - try - { - - exchange = exchangeFactory.createExchange(body.exchange == null ? null : body.exchange.intern(), - body.type == null ? null : body.type.intern(), - body.durable, - body.passive, body.ticket); - exchangeRegistry.registerExchange(exchange); - } - catch(AMQUnknownExchangeType e) - { - throw body.getConnectionException(AMQConstant.COMMAND_INVALID, "Unknown exchange: " + body.exchange,e); - } - } - } - else if (!exchange.getType().equals(body.type)) - { - - throw new AMQConnectionException(AMQConstant.NOT_ALLOWED, "Attempt to redeclare exchange: " + body.exchange + " of type " + exchange.getType() + " to " + body.type +".",body.getClazz(), body.getMethod(),body.getMajor(),body.getMinor(), null); - } - - } - if(!body.nowait) - { - // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0) - // TODO: Connect this to the session version obtained from ProtocolInitiation for this session. - // Be aware of possible changes to parameter order as versions change. - AMQFrame response = ExchangeDeclareOkBody.createAMQFrame(evt.getChannelId(), (byte)8, (byte)0); - session.writeFrame(response); - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeDeleteHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeDeleteHandler.java deleted file mode 100644 index f9926c399c..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeDeleteHandler.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.handler; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQFrame; -import org.apache.qpid.framing.ExchangeDeleteBody; -import org.apache.qpid.framing.ExchangeDeleteOkBody; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.server.exchange.ExchangeInUseException; -import org.apache.qpid.server.exchange.ExchangeRegistry; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.server.state.StateAwareMethodListener; -import org.apache.qpid.server.virtualhost.VirtualHost; - -public class ExchangeDeleteHandler implements StateAwareMethodListener<ExchangeDeleteBody> -{ - private static final ExchangeDeleteHandler _instance = new ExchangeDeleteHandler(); - - public static ExchangeDeleteHandler getInstance() - { - return _instance; - } - - private ExchangeDeleteHandler() - { - } - - public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ExchangeDeleteBody> evt) throws AMQException - { - AMQProtocolSession session = stateManager.getProtocolSession(); - VirtualHost virtualHost = session.getVirtualHost(); - ExchangeRegistry exchangeRegistry = virtualHost.getExchangeRegistry(); - - ExchangeDeleteBody body = evt.getMethod(); - try - { - exchangeRegistry.unregisterExchange(body.exchange, body.ifUnused); - // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0) - // TODO: Connect this to the session version obtained from ProtocolInitiation for this session. - // Be aware of possible changes to parameter order as versions change. - AMQFrame response = ExchangeDeleteOkBody.createAMQFrame(evt.getChannelId(), (byte)8, (byte)0); - session.writeFrame(response); - } - catch (ExchangeInUseException e) - { - // TODO: sort out consistent channel close mechanism that does all clean up etc. - } - - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/OnCurrentThreadExecutor.java b/java/broker/src/main/java/org/apache/qpid/server/handler/OnCurrentThreadExecutor.java deleted file mode 100644 index ac516b6133..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/OnCurrentThreadExecutor.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.handler; - -import java.util.concurrent.Executor; - -/** - * An executor that executes the task on the current thread. - */ -public class OnCurrentThreadExecutor implements Executor -{ - public void execute(Runnable command) - { - command.run(); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/QueueBindHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/QueueBindHandler.java deleted file mode 100644 index 3e68069838..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/QueueBindHandler.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.handler; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.AMQInvalidRoutingKeyException; -import org.apache.qpid.framing.AMQFrame; -import org.apache.qpid.framing.QueueBindBody; -import org.apache.qpid.framing.QueueBindOkBody; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.exchange.ExchangeRegistry; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.QueueRegistry; -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.server.state.StateAwareMethodListener; -import org.apache.qpid.server.virtualhost.VirtualHost; - -public class QueueBindHandler implements StateAwareMethodListener<QueueBindBody> -{ - private static final Logger _log = Logger.getLogger(QueueBindHandler.class); - - private static final QueueBindHandler _instance = new QueueBindHandler(); - - public static QueueBindHandler getInstance() - { - return _instance; - } - - private QueueBindHandler() - { - } - - public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<QueueBindBody> evt) throws AMQException - { - AMQProtocolSession session = stateManager.getProtocolSession(); - VirtualHost virtualHost = session.getVirtualHost(); - ExchangeRegistry exchangeRegistry = virtualHost.getExchangeRegistry(); - QueueRegistry queueRegistry = virtualHost.getQueueRegistry(); - - final QueueBindBody body = evt.getMethod(); - final AMQQueue queue; - if (body.queue == null) - { - AMQChannel channel = session.getChannel(evt.getChannelId()); - - if (channel == null) - { - throw body.getChannelNotFoundException(evt.getChannelId()); - } - - queue = channel.getDefaultQueue(); - - if (queue == null) - { - throw body.getChannelException(AMQConstant.NOT_FOUND, "No default queue defined on channel and queue was null"); - } - - if (body.routingKey == null) - { - body.routingKey = queue.getName(); - } - } - else - { - queue = queueRegistry.getQueue(body.queue); - } - - if (queue == null) - { - throw body.getChannelException(AMQConstant.NOT_FOUND, "Queue " + body.queue + " does not exist."); - } - final Exchange exch = exchangeRegistry.getExchange(body.exchange); - if (exch == null) - { - throw body.getChannelException(AMQConstant.NOT_FOUND, "Exchange " + body.exchange + " does not exist."); - } - - if (body.routingKey != null) - { - body.routingKey = body.routingKey.intern(); - } - - try - { - if (!exch.isBound(body.routingKey, body.arguments, queue)) - { - queue.bind(body.routingKey, body.arguments, exch); - } - } - catch (AMQInvalidRoutingKeyException rke) - { - throw body.getChannelException(AMQConstant.INVALID_ROUTING_KEY, body.routingKey.toString()); - } - catch (AMQException e) - { - throw body.getChannelException(AMQConstant.CHANNEL_ERROR, e.toString()); - } - - if (_log.isInfoEnabled()) - { - _log.info("Binding queue " + queue + " to exchange " + exch + " with routing key " + body.routingKey); - } - if (!body.nowait) - { - // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0) - // TODO: Connect this to the session version obtained from ProtocolInitiation for this session. - // Be aware of possible changes to parameter order as versions change. - final AMQFrame response = QueueBindOkBody.createAMQFrame(evt.getChannelId(), (byte) 8, (byte) 0); - session.writeFrame(response); - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/QueueDeclareHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/QueueDeclareHandler.java deleted file mode 100644 index 9be0dabb68..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/QueueDeclareHandler.java +++ /dev/null @@ -1,215 +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.handler; - -import java.text.MessageFormat; -import java.util.concurrent.atomic.AtomicInteger; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.configuration.Configured; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.AMQFrame; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.QueueDeclareBody; -import org.apache.qpid.framing.QueueDeclareOkBody; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.server.configuration.Configurator; -import org.apache.qpid.server.configuration.VirtualHostConfiguration; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.exchange.ExchangeRegistry; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.QueueRegistry; -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.server.state.StateAwareMethodListener; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.AMQChannel; -import org.apache.commons.configuration.Configuration; - -public class QueueDeclareHandler implements StateAwareMethodListener<QueueDeclareBody> -{ - private static final Logger _log = Logger.getLogger(QueueDeclareHandler.class); - - private static final QueueDeclareHandler _instance = new QueueDeclareHandler(); - - public static QueueDeclareHandler getInstance() - { - return _instance; - } - - @Configured(path = "queue.auto_register", defaultValue = "false") - public boolean autoRegister; - - private final AtomicInteger _counter = new AtomicInteger(); - - - protected QueueDeclareHandler() - { - Configurator.configure(this); - } - - public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<QueueDeclareBody> evt) throws AMQException - { - AMQProtocolSession session = stateManager.getProtocolSession(); - VirtualHost virtualHost = session.getVirtualHost(); - ExchangeRegistry exchangeRegistry = virtualHost.getExchangeRegistry(); - QueueRegistry queueRegistry = virtualHost.getQueueRegistry(); - MessageStore store = virtualHost.getMessageStore(); - - QueueDeclareBody body = evt.getMethod(); - - // if we aren't given a queue name, we create one which we return to the client - if (body.queue == null) - { - body.queue = createName(); - } - - AMQQueue queue; - //TODO: do we need to check that the queue already exists with exactly the same "configuration"? - - synchronized (queueRegistry) - { - - if (((queue = queueRegistry.getQueue(body.queue)) == null)) - { - if(body.queue != null) - { - body.queue = body.queue.intern(); - } - - if (body.passive) - { - String msg = "Queue: " + body.queue + " not found on VirtualHost(" + virtualHost + ")."; - throw body.getChannelException(AMQConstant.NOT_FOUND, msg); - } - else - { - queue = createQueue(body, virtualHost, session); - if (queue.isDurable() && !queue.isAutoDelete()) - { - //DTX MessageStore -// try -// { - store.createQueue(queue); -// } catch (Exception e) -// { -// throw new AMQException(null, "Problem when creating queue " + queue, e); -// } - } - queueRegistry.registerQueue(queue); - if (autoRegister) - { - Exchange defaultExchange = exchangeRegistry.getDefaultExchange(); - - queue.bind(body.queue, null, defaultExchange); - _log.info("Queue " + body.queue + " bound to default exchange(" + defaultExchange.getName() + ")"); - } - } - } - else if (queue.getOwner() != null && !session.getContextKey().equals(queue.getOwner())) - { - throw body.getChannelException(AMQConstant.ALREADY_EXISTS, "Cannot declare queue('" + body.queue + "')," - + " as exclusive queue with same name " - + "declared on another client ID('" - + queue.getOwner() + "')"); - } - - AMQChannel channel = session.getChannel(evt.getChannelId()); - - if (channel == null) - { - throw body.getChannelNotFoundException(evt.getChannelId()); - } - - //set this as the default queue on the channel: - channel.setDefaultQueue(queue); - } - - if (!body.nowait) - { - // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0) - // TODO: Connect this to the session version obtained from ProtocolInitiation for this session. - // Be aware of possible changes to parameter order as versions change. - AMQFrame response = QueueDeclareOkBody.createAMQFrame(evt.getChannelId(), - (byte) 8, (byte) 0, // AMQP version (major, minor) - queue.getConsumerCount(), // consumerCount - queue.getMessageCount(), // messageCount - body.queue); // queue - _log.info("Queue " + body.queue + " declared successfully"); - session.writeFrame(response); - } - } - - protected AMQShortString createName() - { - return new AMQShortString("tmp_" + pad(_counter.incrementAndGet())); - } - - protected static String pad(int value) - { - return MessageFormat.format("{0,number,0000000000000}", value); - } - - protected AMQQueue createQueue(QueueDeclareBody body, VirtualHost virtualHost, final AMQProtocolSession session) - throws AMQException - { - final QueueRegistry registry = virtualHost.getQueueRegistry(); - AMQShortString owner = body.exclusive ? session.getContextKey() : null; - final AMQQueue queue = new AMQQueue(body.queue, body.durable, owner, body.autoDelete, virtualHost); - final AMQShortString queueName = queue.getName(); - - if (body.exclusive && !body.durable) - { - final AMQProtocolSession.Task deleteQueueTask = - new AMQProtocolSession.Task() - { - public void doTask(AMQProtocolSession session) throws AMQException - { - if (registry.getQueue(queueName) == queue) - { - queue.delete(); - } - } - }; - - session.addSessionCloseTask(deleteQueueTask); - - queue.addQueueDeleteTask(new AMQQueue.Task() - { - public void doTask(AMQQueue queue) - { - session.removeSessionCloseTask(deleteQueueTask); - } - }); - }// if exclusive and not durable - - Configuration virtualHostDefaultQueueConfiguration = VirtualHostConfiguration.getDefaultQueueConfiguration(queue); - if (virtualHostDefaultQueueConfiguration != null) - { - Configurator.configure(queue, virtualHostDefaultQueueConfiguration); - } - - return queue; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/QueueDeleteHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/QueueDeleteHandler.java deleted file mode 100644 index edeb6f1f48..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/QueueDeleteHandler.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.handler; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.QueueDeleteBody; -import org.apache.qpid.framing.QueueDeleteOkBody; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.QueueRegistry; -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.server.state.StateAwareMethodListener; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.exception.InternalErrorException; -import org.apache.qpid.server.exception.QueueDoesntExistException; - -public class QueueDeleteHandler implements StateAwareMethodListener<QueueDeleteBody> -{ - private static final QueueDeleteHandler _instance = new QueueDeleteHandler(); - - public static QueueDeleteHandler getInstance() - { - return _instance; - } - - private final boolean _failIfNotFound; - - public QueueDeleteHandler() - { - this(true); - } - - public QueueDeleteHandler(boolean failIfNotFound) - { - _failIfNotFound = failIfNotFound; - - } - - public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<QueueDeleteBody> evt) throws AMQException - { - AMQProtocolSession session = stateManager.getProtocolSession(); - VirtualHost virtualHost = session.getVirtualHost(); - QueueRegistry queueRegistry = virtualHost.getQueueRegistry(); - MessageStore store = virtualHost.getMessageStore(); - - QueueDeleteBody body = evt.getMethod(); - AMQQueue queue; - if (body.queue == null) - { - AMQChannel channel = session.getChannel(evt.getChannelId()); - - if (channel == null) - { - throw body.getChannelNotFoundException(evt.getChannelId()); - } - - //get the default queue on the channel: - queue = channel.getDefaultQueue(); - } - else - { - queue = queueRegistry.getQueue(body.queue); - } - - if (queue == null) - { - if (_failIfNotFound) - { - throw body.getChannelException(AMQConstant.NOT_FOUND, "Queue " + body.queue + " does not exist."); - } - } - else - { - if (body.ifEmpty && !queue.isEmpty()) - { - throw body.getChannelException(AMQConstant.IN_USE, "Queue: " + body.queue + " is not empty."); - } - else if (body.ifUnused && !queue.isUnused()) - { - // TODO - Error code - throw body.getChannelException(AMQConstant.IN_USE, "Queue: " + body.queue + " is still used."); - - } - else - { - int purged = queue.delete(body.ifUnused, body.ifEmpty); - - if (queue.isDurable()) - { - try - { - //DTX MessageStore -// store.destroyQueue(queue); - store.removeQueue(queue.getName()); - } catch (Exception e) - { - throw new AMQException(null, "problem when destroying queue " + queue, e); - } - } - - // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0) - // TODO: Connect this to the session version obtained from ProtocolInitiation for this session. - // Be aware of possible changes to parameter order as versions change. - session.writeFrame(QueueDeleteOkBody.createAMQFrame(evt.getChannelId(), - (byte) 8, (byte) 0, // AMQP version (major, minor) - purged)); // messageCount - } - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/QueuePurgeHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/QueuePurgeHandler.java deleted file mode 100644 index 3e1937bb43..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/QueuePurgeHandler.java +++ /dev/null @@ -1,115 +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.handler;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.QueuePurgeBody;
-import org.apache.qpid.framing.QueuePurgeOkBody;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.queue.QueueRegistry;
-import org.apache.qpid.server.state.AMQStateManager;
-import org.apache.qpid.server.state.StateAwareMethodListener;
-import org.apache.qpid.server.virtualhost.VirtualHost;
-import org.apache.qpid.server.AMQChannel;
-
-public class QueuePurgeHandler implements StateAwareMethodListener<QueuePurgeBody>
-{
- private static final QueuePurgeHandler _instance = new QueuePurgeHandler();
-
- public static QueuePurgeHandler getInstance()
- {
- return _instance;
- }
-
- private final boolean _failIfNotFound;
-
- public QueuePurgeHandler()
- {
- this(true);
- }
-
- public QueuePurgeHandler(boolean failIfNotFound)
- {
- _failIfNotFound = failIfNotFound;
- }
-
- public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<QueuePurgeBody> evt) throws AMQException
- {
- AMQProtocolSession session = stateManager.getProtocolSession();
- VirtualHost virtualHost = session.getVirtualHost();
- QueueRegistry queueRegistry = virtualHost.getQueueRegistry();
-
- AMQChannel channel = session.getChannel(evt.getChannelId());
-
- QueuePurgeBody body = evt.getMethod();
- AMQQueue queue;
- if(body.queue == null)
- {
-
- if (channel == null)
- {
- throw body.getChannelNotFoundException(evt.getChannelId());
- }
-
- //get the default queue on the channel:
- queue = channel.getDefaultQueue();
-
- if(queue == null)
- {
- if(_failIfNotFound)
- {
- throw body.getConnectionException(AMQConstant.NOT_ALLOWED,"No queue specified.");
- }
- }
- }
- else
- {
- queue = queueRegistry.getQueue(body.queue);
- }
-
- if(queue == null)
- {
- if(_failIfNotFound)
- {
- throw body.getChannelException(AMQConstant.NOT_FOUND, "Queue " + body.queue + " does not exist.");
- }
- }
- else
- {
- long purged = queue.clearQueue(channel.getStoreContext());
-
-
- if(!body.nowait)
- {
- // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0)
- // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
- // Be aware of possible changes to parameter order as versions change.
- session.writeFrame(QueuePurgeOkBody.createAMQFrame(evt.getChannelId(),
- (byte)8, (byte)0, // AMQP version (major, minor)
- purged)); // messageCount
- }
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/TxCommitHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/TxCommitHandler.java deleted file mode 100644 index 3d7ec286f9..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/TxCommitHandler.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.handler; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.TxCommitBody; -import org.apache.qpid.framing.TxCommitOkBody; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.server.state.StateAwareMethodListener; - -public class TxCommitHandler implements StateAwareMethodListener<TxCommitBody> -{ - private static final Logger _log = Logger.getLogger(TxCommitHandler.class); - - private static TxCommitHandler _instance = new TxCommitHandler(); - - public static TxCommitHandler getInstance() - { - return _instance; - } - - private TxCommitHandler() - { - } - - public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<TxCommitBody> evt) throws AMQException - { - AMQProtocolSession session = stateManager.getProtocolSession(); - - try - { - if (_log.isDebugEnabled()) - { - _log.debug("Commit received on channel " + evt.getChannelId()); - } - AMQChannel channel = session.getChannel(evt.getChannelId()); - - if (channel == null) - { - throw evt.getMethod().getChannelNotFoundException(evt.getChannelId()); - } - - channel.commit(); - // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0) - // TODO: Connect this to the session version obtained from ProtocolInitiation for this session. - // Be aware of possible changes to parameter order as versions change. - session.writeFrame(TxCommitOkBody.createAMQFrame(evt.getChannelId(), (byte) 8, (byte) 0)); - channel.processReturns(session); - } - catch (AMQException e) - { - throw evt.getMethod().getChannelException(e.getErrorCode(), "Failed to commit: " + e.getMessage()); - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/TxRollbackHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/TxRollbackHandler.java deleted file mode 100644 index f747f7a840..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/TxRollbackHandler.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.handler; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.TxRollbackBody; -import org.apache.qpid.framing.TxRollbackOkBody; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.server.state.StateAwareMethodListener; - -public class TxRollbackHandler implements StateAwareMethodListener<TxRollbackBody> -{ - private static TxRollbackHandler _instance = new TxRollbackHandler(); - - public static TxRollbackHandler getInstance() - { - return _instance; - } - - private TxRollbackHandler() - { - } - - public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<TxRollbackBody> evt) throws AMQException - { - AMQProtocolSession session = stateManager.getProtocolSession(); - - try - { - AMQChannel channel = session.getChannel(evt.getChannelId()); - - if (channel == null) - { - throw evt.getMethod().getChannelNotFoundException(evt.getChannelId()); - } - - channel.rollback(); - // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0) - // TODO: Connect this to the session version obtained from ProtocolInitiation for this session. - // Be aware of possible changes to parameter order as versions change. - session.writeFrame(TxRollbackOkBody.createAMQFrame(evt.getChannelId(), (byte) 8, (byte) 0)); - //Now resend all the unacknowledged messages back to the original subscribers. - //(Must be done after the TxnRollback-ok response). - // Why, are we not allowed to send messages back to client before the ok method? - channel.resend(false); - } - catch (AMQException e) - { - throw evt.getMethod().getChannelException(e.getErrorCode(), "Failed to rollback: " + e.getMessage()); - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/TxSelectHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/TxSelectHandler.java deleted file mode 100644 index a9e478e301..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/TxSelectHandler.java +++ /dev/null @@ -1,63 +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.handler; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.TxSelectBody; -import org.apache.qpid.framing.TxSelectOkBody; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.server.state.StateAwareMethodListener; -import org.apache.qpid.server.AMQChannel; - -public class TxSelectHandler implements StateAwareMethodListener<TxSelectBody> -{ - private static TxSelectHandler _instance = new TxSelectHandler(); - - public static TxSelectHandler getInstance() - { - return _instance; - } - - private TxSelectHandler() - { - } - - public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<TxSelectBody> evt) throws AMQException - { - AMQProtocolSession session = stateManager.getProtocolSession(); - - AMQChannel channel = session.getChannel(evt.getChannelId()); - - if (channel == null) - { - throw evt.getMethod().getChannelNotFoundException(evt.getChannelId()); - } - - channel.setLocalTransactional(); - - // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0) - // TODO: Connect this to the session version obtained from ProtocolInitiation for this session. - // Be aware of possible changes to parameter order as versions change. - session.writeFrame(TxSelectOkBody.createAMQFrame(evt.getChannelId(), (byte) 8, (byte) 0)); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/jms/JmsConsumer.java b/java/broker/src/main/java/org/apache/qpid/server/jms/JmsConsumer.java deleted file mode 100644 index c08fae4e4e..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/jms/JmsConsumer.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.jms; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.protocol.AMQProtocolSession; - -public class JmsConsumer -{ - private int _prefetchValue; - - private PrefetchUnits _prefetchUnits; - - private boolean _noLocal; - - private boolean _autoAck; - - private boolean _exclusive; - - private AMQProtocolSession _protocolSession; - - public enum PrefetchUnits - { - OCTETS, - MESSAGES - } - - public int getPrefetchValue() - { - return _prefetchValue; - } - - public void setPrefetchValue(int prefetchValue) - { - _prefetchValue = prefetchValue; - } - - public PrefetchUnits getPrefetchUnits() - { - return _prefetchUnits; - } - - public void setPrefetchUnits(PrefetchUnits prefetchUnits) - { - _prefetchUnits = prefetchUnits; - } - - public boolean isNoLocal() - { - return _noLocal; - } - - public void setNoLocal(boolean noLocal) - { - _noLocal = noLocal; - } - - public boolean isAutoAck() - { - return _autoAck; - } - - public void setAutoAck(boolean autoAck) - { - _autoAck = autoAck; - } - - public boolean isExclusive() - { - return _exclusive; - } - - public void setExclusive(boolean exclusive) - { - _exclusive = exclusive; - } - - public AMQProtocolSession getProtocolSession() - { - return _protocolSession; - } - - public void setProtocolSession(AMQProtocolSession protocolSession) - { - _protocolSession = protocolSession; - } - - public void deliverMessage() throws AMQException - { - - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/management/AMQManagedObject.java b/java/broker/src/main/java/org/apache/qpid/server/management/AMQManagedObject.java deleted file mode 100644 index a2c2bd62a2..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/management/AMQManagedObject.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management; - -import javax.management.ListenerNotFoundException; -import javax.management.MBeanInfo; -import javax.management.MBeanNotificationInfo; -import javax.management.NotCompliantMBeanException; -import javax.management.NotificationBroadcaster; -import javax.management.NotificationBroadcasterSupport; -import javax.management.NotificationFilter; -import javax.management.NotificationListener; - -/** - * This class provides additinal feature of Notification Broadcaster to the - * DefaultManagedObject. - * @author Bhupendra Bhardwaj - * @version 0.1 - */ -public abstract class AMQManagedObject extends DefaultManagedObject - implements NotificationBroadcaster -{ - /** - * broadcaster support class - */ - protected NotificationBroadcasterSupport _broadcaster = new NotificationBroadcasterSupport(); - - /** - * sequence number for notifications - */ - protected long _notificationSequenceNumber = 0; - - protected MBeanInfo _mbeanInfo; - - protected AMQManagedObject(Class<?> managementInterface, String typeName) - throws NotCompliantMBeanException - { - super(managementInterface, typeName); - buildMBeanInfo(); - } - - @Override - public MBeanInfo getMBeanInfo() - { - return _mbeanInfo; - } - - private void buildMBeanInfo() throws NotCompliantMBeanException - { - _mbeanInfo = new MBeanInfo(this.getClass().getName(), - MBeanIntrospector.getMBeanDescription(this.getClass()), - MBeanIntrospector.getMBeanAttributesInfo(getManagementInterface()), - MBeanIntrospector.getMBeanConstructorsInfo(this.getClass()), - MBeanIntrospector.getMBeanOperationsInfo(getManagementInterface()), - this.getNotificationInfo()); - } - - - - // notification broadcaster implementation - - public void addNotificationListener(NotificationListener listener, - NotificationFilter filter, - Object handback) - { - _broadcaster.addNotificationListener(listener, filter, handback); - } - - public void removeNotificationListener(NotificationListener listener) - throws ListenerNotFoundException - { - _broadcaster.removeNotificationListener(listener); - } - - public MBeanNotificationInfo[] getNotificationInfo() - { - return null; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/management/DefaultManagedObject.java b/java/broker/src/main/java/org/apache/qpid/server/management/DefaultManagedObject.java deleted file mode 100644 index 31313cf024..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/management/DefaultManagedObject.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management; - -import javax.management.JMException; -import javax.management.MalformedObjectNameException; -import javax.management.NotCompliantMBeanException; -import javax.management.ObjectName; -import javax.management.StandardMBean; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.registry.ApplicationRegistry; - -/** - * Provides implementation of the boilerplate ManagedObject interface. Most managed objects should find it useful - * to extend this class rather than implementing ManagedObject from scratch. - * - */ -public abstract class DefaultManagedObject extends StandardMBean implements ManagedObject -{ - private Class<?> _managementInterface; - - private String _typeName; - - protected DefaultManagedObject(Class<?> managementInterface, String typeName) - throws NotCompliantMBeanException - { - super(managementInterface); - _managementInterface = managementInterface; - _typeName = typeName; - } - - public String getType() - { - return _typeName; - } - - public Class<?> getManagementInterface() - { - return _managementInterface; - } - - public ManagedObject getParentObject() - { - return null; - } - - public void register() throws AMQException - { - try - { - getManagedObjectRegistry().registerObject(this); - } - catch (JMException e) - { - throw new AMQException(null, "Error registering managed object " + this + ": " + e, e); - } - } - - protected ManagedObjectRegistry getManagedObjectRegistry() - { - return ApplicationRegistry.getInstance().getManagedObjectRegistry(); - } - - public void unregister() throws AMQException - { - try - { - getManagedObjectRegistry().unregisterObject(this); - } - catch (JMException e) - { - throw new AMQException(null, "Error unregistering managed object: " + this + ": " + e, e); - } - } - - public String toString() - { - return getObjectInstanceName() + "[" + getType() + "]"; - } - - - /** - * Created the ObjectName as per the JMX Specs - * @return ObjectName - * @throws MalformedObjectNameException - */ - public ObjectName getObjectName() throws MalformedObjectNameException - { - String name = getObjectInstanceName(); - StringBuffer objectName = new StringBuffer(ManagedObject.DOMAIN); - - objectName.append(":type="); - objectName.append(getHierarchicalType(this)); - - objectName.append(","); - objectName.append(getHierarchicalName(this)); - objectName.append("name=").append(name); - - return new ObjectName(objectName.toString()); - } - - protected ObjectName getObjectNameForSingleInstanceMBean() throws MalformedObjectNameException - { - StringBuffer objectName = new StringBuffer(ManagedObject.DOMAIN); - - objectName.append(":type="); - objectName.append(getHierarchicalType(this)); - - String hierarchyName = getHierarchicalName(this); - if (hierarchyName != null) - { - objectName.append(","); - objectName.append(hierarchyName.substring(0, hierarchyName.lastIndexOf(","))); - } - - return new ObjectName(objectName.toString()); - } - - protected String getHierarchicalType(ManagedObject obj) - { - if (obj.getParentObject() != null) - { - String parentType = getHierarchicalType(obj.getParentObject()).toString(); - return parentType + "." + obj.getType(); - } - else - return obj.getType(); - } - - protected String getHierarchicalName(ManagedObject obj) - { - if (obj.getParentObject() != null) - { - String parentName = obj.getParentObject().getType() + "=" + - obj.getParentObject().getObjectInstanceName() + ","+ - getHierarchicalName(obj.getParentObject()); - - return parentName; - } - else - return ""; - } - - protected static StringBuffer jmxEncode(StringBuffer jmxName, int attrPos) - { - for (int i = attrPos; i < jmxName.length(); i++) - { - if (jmxName.charAt(i) == ',') - { - jmxName.setCharAt(i, ';'); - } - else if (jmxName.charAt(i) == ':') - { - jmxName.setCharAt(i, '-'); - } - else if (jmxName.charAt(i) == '?' || - jmxName.charAt(i) == '*' || - jmxName.charAt(i) == '\\') - { - jmxName.insert(i, '\\'); - i++; - } - else if (jmxName.charAt(i) == '\n') - { - jmxName.insert(i, '\\'); - i++; - jmxName.setCharAt(i, 'n'); - } - } - return jmxName; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/management/JMXManagedObjectRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/management/JMXManagedObjectRegistry.java deleted file mode 100644 index 9dce752021..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/management/JMXManagedObjectRegistry.java +++ /dev/null @@ -1,283 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.registry.IApplicationRegistry; -import org.apache.qpid.server.security.auth.database.Base64MD5PasswordFilePrincipalDatabase; -import org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase; -import org.apache.qpid.server.security.auth.database.PrincipalDatabase; -import org.apache.qpid.server.security.auth.sasl.crammd5.CRAMMD5HashedInitialiser; - -import javax.management.JMException; -import javax.management.MBeanServer; -import javax.management.MBeanServerFactory; -import javax.management.remote.JMXConnectorServer; -import javax.management.remote.JMXConnectorServerFactory; -import javax.management.remote.JMXServiceURL; -import javax.management.remote.MBeanServerForwarder; -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.callback.NameCallback; -import javax.security.auth.callback.PasswordCallback; -import javax.security.auth.callback.UnsupportedCallbackException; -import javax.security.auth.login.AccountNotFoundException; -import javax.security.sasl.AuthorizeCallback; -import java.io.IOException; -import java.lang.management.ManagementFactory; -import java.rmi.RemoteException; -import java.rmi.registry.LocateRegistry; -import java.rmi.registry.Registry; -import java.rmi.server.UnicastRemoteObject; -import java.util.HashMap; -import java.util.Map; - -/** - * This class starts up an MBeanserver. If out of the box agent is being used then there are no security features - * implemented. To use the security features like user authentication, turn off the jmx options in the "QPID_OPTS" env - * variable and use JMXMP connector server. If JMXMP connector is not available, then the standard JMXConnector will be - * used, which again doesn't have user authentication. - */ -public class JMXManagedObjectRegistry implements ManagedObjectRegistry -{ - private static final Logger _log = Logger.getLogger(JMXManagedObjectRegistry.class); - - private final MBeanServer _mbeanServer; - private Registry _rmiRegistry; - private JMXServiceURL _jmxURL; - - public static final String MANAGEMENT_PORT_CONFIG_PATH = "management.jmxport"; - public static final int MANAGEMENT_PORT_DEFAULT = 8999; - - public JMXManagedObjectRegistry() throws AMQException - { - _log.info("Initialising managed object registry using platform MBean server"); - IApplicationRegistry appRegistry = ApplicationRegistry.getInstance(); - - // Retrieve the config parameters - boolean platformServer = appRegistry.getConfiguration().getBoolean("management.platform-mbeanserver", true); - - _mbeanServer = - platformServer ? ManagementFactory.getPlatformMBeanServer() - : MBeanServerFactory.createMBeanServer(ManagedObject.DOMAIN); - } - - - public void start() throws IOException - { - // Check if the "QPID_OPTS" is set to use Out of the Box JMXAgent - if (areOutOfTheBoxJMXOptionsSet()) - { - _log.info("JMX: Using the out of the box JMX Agent"); - return; - } - - IApplicationRegistry appRegistry = ApplicationRegistry.getInstance(); - - boolean security = appRegistry.getConfiguration().getBoolean("management.security-enabled", false); - int port = appRegistry.getConfiguration().getInt(MANAGEMENT_PORT_CONFIG_PATH, MANAGEMENT_PORT_DEFAULT); - - if (security) - { - // For SASL using JMXMP - _jmxURL = new JMXServiceURL("jmxmp", null, port); - - Map env = new HashMap(); - Map<String, PrincipalDatabase> map = appRegistry.getDatabaseManager().getDatabases(); - PrincipalDatabase db = null; - - for (Map.Entry<String, PrincipalDatabase> entry : map.entrySet()) - { - if (entry.getValue() instanceof Base64MD5PasswordFilePrincipalDatabase) - { - db = entry.getValue(); - break; - } - else if (entry.getValue() instanceof PlainPasswordFilePrincipalDatabase) - { - db = entry.getValue(); - } - } - - if (db instanceof Base64MD5PasswordFilePrincipalDatabase) - { - env.put("jmx.remote.profiles", "SASL/CRAM-MD5"); - CRAMMD5HashedInitialiser initialiser = new CRAMMD5HashedInitialiser(); - initialiser.initialise(db); - env.put("jmx.remote.sasl.callback.handler", initialiser.getCallbackHandler()); - } - else if (db instanceof PlainPasswordFilePrincipalDatabase) - { - env.put("jmx.remote.profiles", "SASL/PLAIN"); - env.put("jmx.remote.sasl.callback.handler", new UserCallbackHandler(db)); - } - - // Enable the SSL security and server authentication - /* - SslRMIClientSocketFactory csf = new SslRMIClientSocketFactory(); - SslRMIServerSocketFactory ssf = new SslRMIServerSocketFactory(); - env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, csf); - env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, ssf); - */ - - JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(_jmxURL, env, _mbeanServer); - MBeanServerForwarder mbsf = MBeanInvocationHandlerImpl.newProxyInstance(); - cs.setMBeanServerForwarder(mbsf); - cs.start(); - _log.warn("JMX: Started JMXConnector server on port '" + port + "' with SASL"); - - } - else - { - startJMXConnectorServer(port); - _log.warn("JMX: Started JMXConnector server on port '" + port + "' with security disabled"); - } - } - - /** - * Starts up an RMIRegistry at configured port and attaches a JMXConnectorServer to it. - * - * @param port - * - * @throws IOException - */ - private void startJMXConnectorServer(int port) throws IOException - { - startRMIRegistry(port); - _jmxURL = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:" + port + "/jmxrmi"); - JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(_jmxURL, null, _mbeanServer); - cs.start(); - } - - public void registerObject(ManagedObject managedObject) throws JMException - { - _mbeanServer.registerMBean(managedObject, managedObject.getObjectName()); - } - - public void unregisterObject(ManagedObject managedObject) throws JMException - { - _mbeanServer.unregisterMBean(managedObject.getObjectName()); - } - - /** - * Checks is the "QPID_OPTS" env variable is set to use the out of the box JMXAgent. - * - * @return - */ - private boolean areOutOfTheBoxJMXOptionsSet() - { - if (System.getProperty("com.sun.management.jmxremote") != null) - { - return true; - } - - if (System.getProperty("com.sun.management.jmxremote.port") != null) - { - return true; - } - - return false; - } - - /** - * Starts the rmi registry at given port - * - * @param port - * - * @throws RemoteException - */ - private void startRMIRegistry(int port) throws RemoteException - { - System.setProperty("java.rmi.server.randomIDs", "true"); - _rmiRegistry = LocateRegistry.createRegistry(port); - } - - // stops the RMIRegistry, if it was running and bound to a port - public void close() throws RemoteException - { - if (_rmiRegistry != null) - { - // Stopping the RMI registry - UnicastRemoteObject.unexportObject(_rmiRegistry, true); - } - } - - /** This class is used for SASL enabled JMXConnector for performing user authentication. */ - private class UserCallbackHandler implements CallbackHandler - { - private final PrincipalDatabase _principalDatabase; - - protected UserCallbackHandler(PrincipalDatabase database) - { - _principalDatabase = database; - } - - public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException - { - // Retrieve callbacks - NameCallback ncb = null; - PasswordCallback pcb = null; - for (int i = 0; i < callbacks.length; i++) - { - if (callbacks[i] instanceof NameCallback) - { - ncb = (NameCallback) callbacks[i]; - } - else if (callbacks[i] instanceof PasswordCallback) - { - pcb = (PasswordCallback) callbacks[i]; - } - else if (callbacks[i] instanceof AuthorizeCallback) - { - ((AuthorizeCallback) callbacks[i]).setAuthorized(true); - } - else - { - throw new UnsupportedCallbackException(callbacks[i]); - } - } - - boolean authorized = false; - // Process retrieval of password; can get password if username is available in NameCallback - if ((ncb != null) && (pcb != null)) - { - String username = ncb.getDefaultName(); - try - { - authorized = _principalDatabase.verifyPassword(username, pcb.getPassword()); - } - catch (AccountNotFoundException e) - { - IOException ioe = new IOException("User not authorized. " + e); - ioe.initCause(e); - throw ioe; - } - } - - if (!authorized) - { - throw new IOException("User not authorized."); - } - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/management/MBeanAttribute.java b/java/broker/src/main/java/org/apache/qpid/server/management/MBeanAttribute.java deleted file mode 100644 index 7d42297699..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/management/MBeanAttribute.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ - -package org.apache.qpid.server.management; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Annotation for MBean attributes. This should be used with getter or setter - * methods of attributes. - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.METHOD) -@Inherited -public @interface MBeanAttribute -{ - String name(); - String description(); -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/management/MBeanConstructor.java b/java/broker/src/main/java/org/apache/qpid/server/management/MBeanConstructor.java deleted file mode 100644 index 9138e03085..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/management/MBeanConstructor.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ - -package org.apache.qpid.server.management; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Annotation for MBean constructors. - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.CONSTRUCTOR) -@Inherited -public @interface MBeanConstructor -{ - String value(); -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/management/MBeanDescription.java b/java/broker/src/main/java/org/apache/qpid/server/management/MBeanDescription.java deleted file mode 100644 index 448fed3280..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/management/MBeanDescription.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ - -package org.apache.qpid.server.management; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Annotation for MBean class. - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.TYPE) -@Inherited -public @interface MBeanDescription { - String value(); -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/management/MBeanIntrospector.java b/java/broker/src/main/java/org/apache/qpid/server/management/MBeanIntrospector.java deleted file mode 100644 index 0c2ec2aebd..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/management/MBeanIntrospector.java +++ /dev/null @@ -1,388 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - -import javax.management.MBeanAttributeInfo; -import javax.management.MBeanConstructorInfo; -import javax.management.MBeanOperationInfo; -import javax.management.MBeanParameterInfo; -import javax.management.NotCompliantMBeanException; - -/** - * This class is a utility class to introspect the MBean class and the management - * interface class for various purposes. - * @author Bhupendra Bhardwaj - * @version 0.1 - */ -class MBeanIntrospector { - - private static final String _defaultAttributeDescription = "Management attribute"; - private static final String _defaultOerationDescription = "Management operation"; - private static final String _defaultConstructorDescription = "MBean constructor"; - private static final String _defaultMbeanDescription = "Management interface of the MBean"; - - /** - * Introspects the management interface class for MBean attributes. - * @param interfaceClass - * @return MBeanAttributeInfo[] - * @throws NotCompliantMBeanException - */ - static MBeanAttributeInfo[] getMBeanAttributesInfo(Class interfaceClass) - throws NotCompliantMBeanException - { - List<MBeanAttributeInfo> attributesList = new ArrayList<MBeanAttributeInfo>(); - - /** - * Using reflection, all methods of the managemetn interface will be analysed, - * and MBeanInfo will be created. - */ - for (Method method : interfaceClass.getMethods()) - { - String name = method.getName(); - Class<?> resultType = method.getReturnType(); - MBeanAttributeInfo attributeInfo = null; - - if (isAttributeGetterMethod(method)) - { - String desc = getAttributeDescription(method); - attributeInfo = new MBeanAttributeInfo(name.substring(3), - resultType.getName(), - desc, - true, - false, - false); - int index = getIndexIfAlreadyExists(attributeInfo, attributesList); - if (index == -1) - { - attributesList.add(attributeInfo); - } - else - { - attributeInfo = new MBeanAttributeInfo(name.substring(3), - resultType.getName(), - desc, - true, - true, - false); - attributesList.set(index, attributeInfo); - } - } - else if (isAttributeSetterMethod(method)) - { - String desc = getAttributeDescription(method); - attributeInfo = new MBeanAttributeInfo(name.substring(3), - method.getParameterTypes()[0].getName(), - desc, - false, - true, - false); - int index = getIndexIfAlreadyExists(attributeInfo, attributesList); - if (index == -1) - { - attributesList.add(attributeInfo); - } - else - { - attributeInfo = new MBeanAttributeInfo(name.substring(3), - method.getParameterTypes()[0].getName(), - desc, - true, - true, - false); - attributesList.set(index, attributeInfo); - } - } - else if (isAttributeBoolean(method)) - { - attributeInfo = new MBeanAttributeInfo(name.substring(2), - resultType.getName(), - getAttributeDescription(method), - true, - false, - true); - attributesList.add(attributeInfo); - } - } - - return attributesList.toArray(new MBeanAttributeInfo[0]); - } - - /** - * Introspects the management interface class for management operations. - * @param interfaceClass - * @return MBeanOperationInfo[] - */ - static MBeanOperationInfo[] getMBeanOperationsInfo(Class interfaceClass) - { - List<MBeanOperationInfo> operationsList = new ArrayList<MBeanOperationInfo>(); - - for (Method method : interfaceClass.getMethods()) - { - if (!isAttributeGetterMethod(method) && - !isAttributeSetterMethod(method) && - !isAttributeBoolean(method)) - { - operationsList.add(getOperationInfo(method)); - } - } - - return operationsList.toArray(new MBeanOperationInfo[0]); - } - - /** - * Checks if the method is an attribute getter method. - * @param method - * @return true if the method is an attribute getter method. - */ - private static boolean isAttributeGetterMethod(Method method) - { - if (!(method.getName().equals("get")) && - method.getName().startsWith("get") && - method.getParameterTypes().length == 0 && - !method.getReturnType().equals(void.class)) - { - return true; - } - - return false; - } - - /** - * Checks if the method is an attribute setter method. - * @param method - * @return true if the method is an attribute setter method. - */ - private static boolean isAttributeSetterMethod(Method method) - { - if (!(method.getName().equals("set")) && - method.getName().startsWith("set") && - method.getParameterTypes().length == 1 && - method.getReturnType().equals(void.class)) - { - return true; - } - - return false; - } - - /** - * Checks if the attribute is a boolean and the method is a isX kind og method. - * @param method - * @return true if the method is an attribute isX type of method - */ - private static boolean isAttributeBoolean(Method method) - { - if (!(method.getName().equals("is")) && - method.getName().startsWith("is") && - method.getParameterTypes().length == 0 && - method.getReturnType().equals(boolean.class)) - { - return true; - } - - return false; - } - - /** - * Helper method to retrieve the attribute index from the list of attributes. - * @param attribute - * @param list - * @return attribute index no. -1 if attribtue doesn't exist - * @throws NotCompliantMBeanException - */ - private static int getIndexIfAlreadyExists(MBeanAttributeInfo attribute, - List<MBeanAttributeInfo> list) - throws NotCompliantMBeanException - { - String exceptionMsg = "Conflicting attribute methods for attribute " + attribute.getName(); - - for (MBeanAttributeInfo memberAttribute : list) - { - if (attribute.getName().equals(memberAttribute.getName())) - { - if (!attribute.getType().equals(memberAttribute.getType())) - { - throw new NotCompliantMBeanException(exceptionMsg); - } - if (attribute.isReadable() && memberAttribute.isReadable()) - { - if (attribute.isIs() != memberAttribute.isIs()) - { - throw new NotCompliantMBeanException(exceptionMsg); - } - } - - return list.indexOf(memberAttribute); - } - } - - return -1; - } - - /** - * Retrieves the attribute description from annotation - * @param attributeMethod - * @return attribute description - */ - private static String getAttributeDescription(Method attributeMethod) - { - MBeanAttribute anno = attributeMethod.getAnnotation(MBeanAttribute.class); - if (anno != null) - { - return anno.description(); - } - return _defaultAttributeDescription; - } - - /** - * Introspects the method to retrieve the operation information. - * @param operation - * @return MBeanOperationInfo - */ - private static MBeanOperationInfo getOperationInfo(Method operation) - { - MBeanOperationInfo operationInfo = null; - Class<?> returnType = operation.getReturnType(); - - MBeanParameterInfo[] paramsInfo = getParametersInfo(operation.getParameterAnnotations(), - operation.getParameterTypes()); - - String operationDesc = _defaultOerationDescription; - int impact = MBeanOperationInfo.UNKNOWN; - - if (operation.getAnnotation(MBeanOperation.class) != null) - { - operationDesc = operation.getAnnotation(MBeanOperation.class).description(); - impact = operation.getAnnotation(MBeanOperation.class).impact(); - } - operationInfo = new MBeanOperationInfo(operation.getName(), - operationDesc, - paramsInfo, - returnType.getName(), - impact); - - return operationInfo; - } - - /** - * Constructs the parameter info. - * @param paramsAnno - * @param paramTypes - * @return MBeanParameterInfo[] - */ - private static MBeanParameterInfo[] getParametersInfo(Annotation[][] paramsAnno, - Class<?>[] paramTypes) - { - int noOfParams = paramsAnno.length; - - MBeanParameterInfo[] paramsInfo = new MBeanParameterInfo[noOfParams]; - - for (int i = 0; i < noOfParams; i++) - { - MBeanParameterInfo paramInfo = null; - String type = paramTypes[i].getName(); - for (Annotation anno : paramsAnno[i]) - { - String name,desc; - if (MBeanOperationParameter.class.isInstance(anno)) - { - name = MBeanOperationParameter.class.cast(anno).name(); - desc = MBeanOperationParameter.class.cast(anno).description(); - paramInfo = new MBeanParameterInfo(name, type, desc); - } - } - - - if (paramInfo == null) - { - paramInfo = new MBeanParameterInfo("p " + (i + 1), type, "parameter " + (i + 1)); - } - if (paramInfo != null) - paramsInfo[i] = paramInfo; - } - - return paramsInfo; - } - - /** - * Introspects the MBean class for constructors - * @param implClass - * @return MBeanConstructorInfo[] - */ - static MBeanConstructorInfo[] getMBeanConstructorsInfo(Class implClass) - { - List<MBeanConstructorInfo> constructors = new ArrayList<MBeanConstructorInfo>(); - - for (Constructor cons : implClass.getConstructors()) - { - MBeanConstructorInfo constructorInfo = getMBeanConstructorInfo(cons); - //MBeanConstructorInfo constructorInfo = new MBeanConstructorInfo("desc", cons); - if (constructorInfo != null) - constructors.add(constructorInfo); - } - - return constructors.toArray(new MBeanConstructorInfo[0]); - } - - /** - * Retrieves the constructor info from given constructor. - * @param cons - * @return MBeanConstructorInfo - */ - private static MBeanConstructorInfo getMBeanConstructorInfo(Constructor cons) - { - String desc = null; - Annotation anno = cons.getAnnotation(MBeanConstructor.class); - if (anno != null && MBeanConstructor.class.isInstance(anno)) - { - desc = MBeanConstructor.class.cast(anno).value(); - } - - //MBeanParameterInfo[] paramsInfo = getParametersInfo(cons.getParameterAnnotations(), - // cons.getParameterTypes()); - - return new MBeanConstructorInfo(cons.getName(), - desc != null ? _defaultConstructorDescription : desc , - null); - } - - /** - * Retrieves the description from the annotations of given class - * @param annotatedClass - * @return class description - */ - static String getMBeanDescription(Class annotatedClass) - { - Annotation anno = annotatedClass.getAnnotation(MBeanDescription.class); - if (anno != null && MBeanDescription.class.isInstance(anno)) - { - return MBeanDescription.class.cast(anno).value(); - } - return _defaultMbeanDescription; - } - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/management/MBeanInvocationHandlerImpl.java b/java/broker/src/main/java/org/apache/qpid/server/management/MBeanInvocationHandlerImpl.java deleted file mode 100644 index 4fb260472d..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/management/MBeanInvocationHandlerImpl.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management; - -import org.apache.qpid.server.security.access.UserManagement; -import org.apache.log4j.Logger; - -import javax.management.remote.MBeanServerForwarder; -import javax.management.remote.JMXPrincipal; -import javax.management.MBeanServer; -import javax.management.ObjectName; -import javax.management.MBeanInfo; -import javax.management.MBeanOperationInfo; -import javax.management.JMException; -import javax.security.auth.Subject; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Proxy; -import java.lang.reflect.Method; -import java.security.AccessController; -import java.security.Principal; -import java.security.AccessControlContext; -import java.util.Set; -import java.util.Properties; - -/** - * This class can be used by the JMXConnectorServer as an InvocationHandler for the mbean operations. This implements - * the logic for allowing the users to invoke MBean operations and implements the restrictions for readOnly, readWrite - * and admin users. - */ -public class MBeanInvocationHandlerImpl implements InvocationHandler -{ - private static final Logger _logger = Logger.getLogger(MBeanInvocationHandlerImpl.class); - - public final static String ADMIN = "admin"; - public final static String READWRITE = "readwrite"; - public final static String READONLY = "readonly"; - private final static String DELEGATE = "JMImplementation:type=MBeanServerDelegate"; - private MBeanServer mbs; - private static Properties _userRoles = new Properties(); - - public static MBeanServerForwarder newProxyInstance() - { - final InvocationHandler handler = new MBeanInvocationHandlerImpl(); - final Class[] interfaces = new Class[]{MBeanServerForwarder.class}; - - Object proxy = Proxy.newProxyInstance(MBeanServerForwarder.class.getClassLoader(), interfaces, handler); - return MBeanServerForwarder.class.cast(proxy); - } - - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable - { - final String methodName = method.getName(); - - if (methodName.equals("getMBeanServer")) - { - return mbs; - } - - if (methodName.equals("setMBeanServer")) - { - if (args[0] == null) - { - throw new IllegalArgumentException("Null MBeanServer"); - } - if (mbs != null) - { - throw new IllegalArgumentException("MBeanServer object already initialized"); - } - mbs = (MBeanServer) args[0]; - return null; - } - - // Retrieve Subject from current AccessControlContext - AccessControlContext acc = AccessController.getContext(); - Subject subject = Subject.getSubject(acc); - - // Allow operations performed locally on behalf of the connector server itself - if (subject == null) - { - return method.invoke(mbs, args); - } - - if (args == null || DELEGATE.equals(args[0])) - { - return method.invoke(mbs, args); - } - - // Restrict access to "createMBean" and "unregisterMBean" to any user - if (methodName.equals("createMBean") || methodName.equals("unregisterMBean")) - { - _logger.debug("User trying to create or unregister an MBean"); - throw new SecurityException("Access denied"); - } - - // Retrieve JMXPrincipal from Subject - Set<JMXPrincipal> principals = subject.getPrincipals(JMXPrincipal.class); - if (principals == null || principals.isEmpty()) - { - throw new SecurityException("Access denied"); - } - - Principal principal = principals.iterator().next(); - String identity = principal.getName(); - - if (isAdminMethod(args)) - { - if (isAdmin(identity)) - { - return method.invoke(mbs, args); - } - else - { - throw new SecurityException("Access denied"); - } - } - - // Following users can perform any operation other than "createMBean" and "unregisterMBean" - if (isAllowedToModify(identity)) - { - return method.invoke(mbs, args); - } - - // These users can only call "getAttribute" on the MBeanServerDelegate MBean - // Here we can add other fine grained permissions like specific method for a particular mbean - if (isReadOnlyUser(identity) && isReadOnlyMethod(method, args)) - { - return method.invoke(mbs, args); - } - - throw new SecurityException("Access denied"); - } - - private boolean isAdminMethod(Object[] args) - { - if (args[0] instanceof ObjectName) - { - ObjectName object = (ObjectName) args[0]; - return UserManagement.TYPE.equals(object.getKeyProperty("type")); - } - - return false; - } - - // Initialises the user roles - public static void setAccessRights(Properties accessRights) - { - _userRoles = accessRights; - } - - private boolean isAdmin(String userName) - { - if (ADMIN.equals(_userRoles.getProperty(userName))) - { - return true; - } - return false; - } - - private boolean isAllowedToModify(String userName) - { - if (ADMIN.equals(_userRoles.getProperty(userName)) - || READWRITE.equals(_userRoles.getProperty(userName))) - { - return true; - } - return false; - } - - private boolean isReadOnlyUser(String userName) - { - if (READONLY.equals(_userRoles.getProperty(userName))) - { - return true; - } - return false; - } - - private boolean isReadOnlyMethod(Method method, Object[] args) - { - String methodName = method.getName(); - if (methodName.startsWith("query") || methodName.startsWith("get")) - { - return true; - } - else if (methodName.startsWith("set")) - { - return false; - } - - if ((args[0] instanceof ObjectName) && (methodName.equals("invoke"))) - { - String mbeanMethod = (args.length > 1) ? (String) args[1] : null; - if (mbeanMethod == null) - { - return false; - } - - try - { - MBeanInfo mbeanInfo = mbs.getMBeanInfo((ObjectName) args[0]); - if (mbeanInfo != null) - { - MBeanOperationInfo[] opInfos = mbeanInfo.getOperations(); - for (MBeanOperationInfo opInfo : opInfos) - { - if (opInfo.getName().equals(mbeanMethod) && (opInfo.getImpact() == MBeanOperationInfo.INFO)) - { - return true; - } - } - } - } - catch (JMException ex) - { - ex.printStackTrace(); - } - } - - return false; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/management/MBeanOperation.java b/java/broker/src/main/java/org/apache/qpid/server/management/MBeanOperation.java deleted file mode 100644 index a2dca3e51d..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/management/MBeanOperation.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ - -package org.apache.qpid.server.management; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import javax.management.MBeanOperationInfo; - -/** - * Annotation for MBean operations. - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.METHOD) -@Inherited -public @interface MBeanOperation -{ - String name(); - String description(); - int impact() default MBeanOperationInfo.INFO; -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/management/MBeanOperationParameter.java b/java/broker/src/main/java/org/apache/qpid/server/management/MBeanOperationParameter.java deleted file mode 100644 index aba5ec70d8..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/management/MBeanOperationParameter.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ - -package org.apache.qpid.server.management; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Annotation for MBean operation parameters. - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.PARAMETER) -public @interface MBeanOperationParameter { - String name(); - String description(); -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/management/Managable.java b/java/broker/src/main/java/org/apache/qpid/server/management/Managable.java deleted file mode 100644 index 166a2a376d..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/management/Managable.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management; - -/** - * Any object that can return a related MBean should implement this interface. - * - * This enables other classes to get the managed object, which in turn is useful when - * constructing relationships between managed objects without having to maintain - * separate data structures containing MBeans. - * - */ -public interface Managable -{ - ManagedObject getManagedObject(); -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/management/ManagedBroker.java b/java/broker/src/main/java/org/apache/qpid/server/management/ManagedBroker.java deleted file mode 100644 index 45e2e91ed7..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/management/ManagedBroker.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.server.management; - -import java.io.IOException; - -import javax.management.JMException; -import javax.management.MBeanOperationInfo; - -import org.apache.qpid.server.exchange.ManagedExchange; -import org.apache.qpid.server.queue.ManagedQueue; - -/** - * The ManagedBroker is the management interface to expose management - * features of the Broker. - * - * @author Bhupendra Bhardwaj - * @version 0.1 - */ -public interface ManagedBroker -{ - static final String TYPE = "VirtualHostManager"; - - /** - * Creates a new Exchange. - * @param name - * @param type - * @param durable - * @param passive - * @throws IOException - * @throws JMException - */ - @MBeanOperation(name="createNewExchange", description="Creates a new Exchange", impact= MBeanOperationInfo.ACTION) - void createNewExchange(@MBeanOperationParameter(name="name", description="Name of the new exchange")String name, - @MBeanOperationParameter(name="ExchangeType", description="Type of the exchange")String type, - @MBeanOperationParameter(name="durable", description="true if the Exchang should be durable")boolean durable) - throws IOException, JMException; - - /** - * unregisters all the channels, queuebindings etc and unregisters - * this exchange from managed objects. - * @param exchange - * @throws IOException - * @throws JMException - */ - @MBeanOperation(name="unregisterExchange", - description="Unregisters all the related channels and queuebindings of this exchange", - impact= MBeanOperationInfo.ACTION) - void unregisterExchange(@MBeanOperationParameter(name= ManagedExchange.TYPE, description="Exchange Name")String exchange) - throws IOException, JMException; - - /** - * Create a new Queue on the Broker server - * @param queueName - * @param durable - * @param owner - * @param autoDelete - * @throws IOException - * @throws JMException - */ - @MBeanOperation(name="createNewQueue", description="Create a new Queue on the Broker server", impact= MBeanOperationInfo.ACTION) - void createNewQueue(@MBeanOperationParameter(name="queue name", description="Name of the new queue")String queueName, - @MBeanOperationParameter(name="owner", description="Owner name")String owner, - @MBeanOperationParameter(name="durable", description="true if the queue should be durable")boolean durable) - throws IOException, JMException; - - /** - * Unregisters the Queue bindings, removes the subscriptions and unregisters - * from the managed objects. - * @param queueName - * @throws IOException - * @throws JMException - */ - @MBeanOperation(name="deleteQueue", - description="Unregisters the Queue bindings, removes the subscriptions and deletes the queue", - impact= MBeanOperationInfo.ACTION) - void deleteQueue(@MBeanOperationParameter(name= ManagedQueue.TYPE, description="Queue Name")String queueName) - throws IOException, JMException; -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/management/ManagedObject.java b/java/broker/src/main/java/org/apache/qpid/server/management/ManagedObject.java deleted file mode 100644 index 42ea8921a4..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/management/ManagedObject.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management; - -import javax.management.MalformedObjectNameException; -import javax.management.ObjectName; - -import org.apache.qpid.AMQException; - -/** - * This should be implemented by all Managable objects. - */ -public interface ManagedObject -{ - static final String DOMAIN = "org.apache.qpid"; - - /** - * @return the name that uniquely identifies this object instance. It must be - * unique only among objects of this type at this level in the hierarchy so - * the uniqueness should not be too difficult to ensure. - */ - String getObjectInstanceName(); - - String getType(); - - Class<?> getManagementInterface(); - - ManagedObject getParentObject(); - - void register() throws AMQException; - - void unregister() throws AMQException; - - /** - * Returns the ObjectName required for the mbeanserver registration. - * @return ObjectName - * @throws MalformedObjectNameException - */ - ObjectName getObjectName() throws MalformedObjectNameException; -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/management/ManagedObjectRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/management/ManagedObjectRegistry.java deleted file mode 100644 index d8d87ef881..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/management/ManagedObjectRegistry.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management; - -import javax.management.JMException; -import java.rmi.RemoteException; -import java.io.IOException; - -/** - * Handles the registration (and unregistration and so on) of managed objects. - * - * Managed objects are responsible for exposting attributes, operations and notifications. They will expose - * these outside the JVM therefore it is important not to use implementation objects directly as managed objects. - * Instead, creating inner classes and exposing those is an effective way of exposing internal state in a - * controlled way. - * - * Although we do not explictly use them while targetting Java 5, the enhanced MXBean approach in Java 6 will - * be the obvious choice for managed objects. - * - */ -public interface ManagedObjectRegistry -{ - void start() throws IOException; - - void registerObject(ManagedObject managedObject) throws JMException; - - void unregisterObject(ManagedObject managedObject) throws JMException; - - void close() throws RemoteException; -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/management/ManagementConfiguration.java b/java/broker/src/main/java/org/apache/qpid/server/management/ManagementConfiguration.java deleted file mode 100644 index 042f626e8b..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/management/ManagementConfiguration.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management; - -import org.apache.qpid.configuration.Configured; - -public class ManagementConfiguration -{ - @Configured(path = "management.enabled", - defaultValue = "true") - public boolean enabled; -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/management/NoopManagedObjectRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/management/NoopManagedObjectRegistry.java deleted file mode 100644 index b4fbed6948..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/management/NoopManagedObjectRegistry.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management; - -import javax.management.JMException; - -import org.apache.log4j.Logger; - -import java.rmi.RemoteException; - -/** - * This managed object registry does not actually register MBeans. This can be used in tests when management is - * not required or when management has been disabled. - * - */ -public class NoopManagedObjectRegistry implements ManagedObjectRegistry -{ - private static final Logger _log = Logger.getLogger(NoopManagedObjectRegistry.class); - - public NoopManagedObjectRegistry() - { - _log.info("Management is disabled"); - } - - public void start() - { - //no-op - } - - public void registerObject(ManagedObject managedObject) throws JMException - { - } - - public void unregisterObject(ManagedObject managedObject) throws JMException - { - } - - public void close() throws RemoteException - { - - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/messageStore/JDBCStore.java b/java/broker/src/main/java/org/apache/qpid/server/messageStore/JDBCStore.java deleted file mode 100644 index 8c13473488..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/messageStore/JDBCStore.java +++ /dev/null @@ -1,1861 +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.messageStore; - -import org.apache.commons.configuration.Configuration; -import org.apache.log4j.Logger; -import org.apache.mina.common.ByteBuffer; -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.abstraction.MessagePublishInfo; -import org.apache.qpid.server.exception.InternalErrorException; -import org.apache.qpid.server.exception.InvalidXidException; -import org.apache.qpid.server.exception.MessageAlreadyStagedException; -import org.apache.qpid.server.exception.MessageDoesntExistException; -import org.apache.qpid.server.exception.QueueAlreadyExistsException; -import org.apache.qpid.server.exception.QueueDoesntExistException; -import org.apache.qpid.server.exception.UnknownXidException; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.queue.AMQMessage; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.MessageHandleFactory; -import org.apache.qpid.server.store.StoreContext; -import org.apache.qpid.server.txn.JDBCAbstractRecord; -import org.apache.qpid.server.txn.JDBCDequeueRecord; -import org.apache.qpid.server.txn.JDBCEnqueueRecord; -import org.apache.qpid.server.txn.JDBCTransaction; -import org.apache.qpid.server.txn.JDBCTransactionManager; -import org.apache.qpid.server.txn.Transaction; -import org.apache.qpid.server.txn.TransactionManager; -import org.apache.qpid.server.txn.TransactionRecord; -import org.apache.qpid.server.txn.TransactionalContext; -import org.apache.qpid.server.txn.XidImpl; -import org.apache.qpid.server.virtualhost.VirtualHost; - -import javax.transaction.xa.Xid; -import java.sql.Blob; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; - -/** - * Created by Arnaud Simon - * Date: 15-May-2007 - * Time: 09:59:12 - */ -public class JDBCStore implements MessageStore -{ - //======================================================================== - // Static Constants - //======================================================================== - // The logger for this class - private static final Logger _log = Logger.getLogger(JDBCStore.class); - // the database connection pool - public static ConnectionPool _connectionPool = null; - // the prepared statements - //==== IMPORTANT: remember to update if we add more prepared statements! - private static final int CREATE_EXCHANGE = 0; - private static final int DELETE_EXCHANGE = 1; - private static final int BIND_QUEUE = 2; - private static final int UNBIND_QUEUE = 3; - private static final int CREATE_QUEUE = 4; - private static final int DELETE_QUEUE = 5; - private static final int STAGE_MESSAGE = 6; - private static final int UPDATE_MESSAGE_PAYLOAD = 7; - private static final int SELECT_MESSAGE_PAYLOAD = 8; - private static final int DELETE_MESSAGE = 9; - private static final int ENQUEUE = 10; - private static final int DEQUEUE = 11; - private static final int GET_ALL_QUEUES = 12; - private static final int GET_ALL_MESSAGES = 13; - private static final int SAVE_RECORD = 14; - private static final int SAVE_XID = 15; - private static final int DELETE_RECORD = 16; - private static final int DELETE_XID = 17; - private static final int UPDATE_QMR = 18; - private static final int GET_CONTENT_HEADER = 19; - private static final int GET_MESSAGE_INFO = 20; - //==== size: - private static final int STATEMENT_SIZE = 21; - //======================================================================== - // field properties - //======================================================================== - //The default URL - protected String _connectionURL = "jdbc:derby:derbyDB;create=true"; - // The default driver - private String _driver = "org.apache.derby.jdbc.EmbeddedDriver"; - // The pool max size - private int _maxSize = 40; - // The tables - // the table containing the messages - private String _tableNameMessage = "MessageTable"; - private String _tableNameQueue = "QueueTable"; - private String _tableNameQueueMessageRelation = "QeueMessageRelation"; - private String _tableNameExchange = "Exchange"; - private String _tableNameExchangeQueueRelation = "ExchangeQueueRelation"; - private String _tableNameTransaction = "TransactionTable"; - private String _tableNameRecord = "RecordTable"; - - // The transaction maanger - private JDBCTransactionManager _tm; - // the message ID - private long _messageID = 0; - // the virtual host - private VirtualHost _virtualHost; - // indicate whether this store is recovering - private boolean _recovering = false; - // the recovered queues - private HashMap<Integer, AMQQueue> _queueMap; - - //======================================================================== - // Interface MessageStore - //======================================================================== - public void configure(VirtualHost virtualHost, TransactionManager tm, String base, Configuration config) - throws - InternalErrorException, - IllegalArgumentException - { - _log.info("Configuring Derby message store"); - // the virtual host - _virtualHost = virtualHost; - // Specify that the tables must be dropped. - // If true then this means that recovery is not possible. - boolean dropTables = true; - if (config != null) - { - dropTables = config.getBoolean(base + "dropTables", false); - _driver = config.getString(base + "driver", _driver); - _connectionURL = config.getString(base + "connectionURL", _connectionURL); - _maxSize = config.getInt(base + "connectionPoolSize", 20); - } - if (dropTables) - { - _log.info("Dropping table of Derby message store"); - } - if (!setupStore(dropTables)) - { - _log.error("Error configuration of Derby store failed"); - throw new InternalErrorException("Error configuration of Derby store failed"); - } - // recovery - _recovering = true; - _queueMap = recover(); //==> recover the queues and the messages - // recreate the excahnges and bind the queues - recoverExchanges(_queueMap); - _recovering = false; - _tm = (JDBCTransactionManager) tm; - _tm.configure(this, "txn", config); - _queueMap.clear(); - _queueMap = null; - } - - public void close() - throws - InternalErrorException - { - // nothing has to be done - } - - public void createExchange(Exchange exchange) - throws - InternalErrorException - { - if (!_recovering) - { - MyConnection connection = null; - try - { - connection = (MyConnection) _connectionPool.acquireInstance(); - PreparedStatement pstmt = connection.getStatements()[CREATE_EXCHANGE]; - if (pstmt == null) - { - pstmt = connection.getConnection().prepareStatement("INSERT INTO " + _tableNameExchange + - " (Name,Type) VALUES (?,?)"); - connection.getStatements()[CREATE_EXCHANGE] = pstmt; - } - pstmt.setString(1, exchange.getName().asString()); - pstmt.setString(2, exchange.getType().asString()); - pstmt.executeUpdate(); - } - catch (Exception e) - { - throw new InternalErrorException("Cannot create Exchange: " + exchange, e); - } - finally - { - if (connection != null) - { - try - { - connection.getConnection().commit(); - _connectionPool.releaseInstance(connection); - } - catch (SQLException e) - { - // we did not manage to commit this connection - // it is better to release it - _connectionPool.releaseDeadInstance(); - throw new InternalErrorException("Cannot create Exchange: " + exchange, e); - } - } - } - } - } - - public void removeExchange(Exchange exchange) - throws - InternalErrorException - { - if (!_recovering) - { - MyConnection connection = null; - try - { - connection = (MyConnection) _connectionPool.acquireInstance(); - PreparedStatement pstmt = connection.getStatements()[DELETE_EXCHANGE]; - if (pstmt == null) - { - pstmt = connection.getConnection().prepareStatement("DELETE FROM " + _tableNameExchange + - " WHERE Name = ?"); - connection.getStatements()[DELETE_EXCHANGE] = pstmt; - } - pstmt.setString(1, exchange.getName().asString()); - pstmt.executeUpdate(); - } - catch (Exception e) - { - throw new InternalErrorException("Cannot remove Exchange: " + exchange, e); - } - finally - { - if (connection != null) - { - try - { - connection.getConnection().commit(); - _connectionPool.releaseInstance(connection); - } - catch (SQLException e) - { - // we did not manage to commit this connection - // it is better to release it - _connectionPool.releaseDeadInstance(); - throw new InternalErrorException("Cannot remove Exchange: " + exchange, e); - } - } - } - } - } - - public void bindQueue(Exchange exchange, AMQShortString routingKey, StorableQueue queue, FieldTable args) - throws - InternalErrorException - { - if (!_recovering) - { - MyConnection connection = null; - try - { - connection = (MyConnection) _connectionPool.acquireInstance(); - PreparedStatement pstmt = connection.getStatements()[BIND_QUEUE]; - if (pstmt == null) - { - pstmt = connection.getConnection().prepareStatement("INSERT INTO " + _tableNameExchangeQueueRelation + - " (QueueID,Name,RoutingKey,fieldTable) VALUES (?,?,?,?)"); - connection.getStatements()[BIND_QUEUE] = pstmt; - } - pstmt.setInt(1, queue.getQueueID()); - pstmt.setString(2, exchange.getName().asString()); - pstmt.setString(3, routingKey.asString()); - if (args != null) - { - pstmt.setBytes(4, args.getDataAsBytes()); - } - else - { - pstmt.setBytes(4, null); - } - pstmt.executeUpdate(); - } - catch (Exception e) - { - throw new InternalErrorException("Cannot create Exchange: " + exchange, e); - } - finally - { - if (connection != null) - { - try - { - connection.getConnection().commit(); - _connectionPool.releaseInstance(connection); - } - catch (SQLException e) - { - // we did not manage to commit this connection - // it is better to release it - _connectionPool.releaseDeadInstance(); - throw new InternalErrorException("Cannot create Exchange: " + exchange, e); - } - } - } - } - } - - public void unbindQueue(Exchange exchange, AMQShortString routingKey, StorableQueue queue, FieldTable args) - throws - InternalErrorException - { - MyConnection connection = null; - try - { - connection = (MyConnection) _connectionPool.acquireInstance(); - PreparedStatement pstmt = connection.getStatements()[UNBIND_QUEUE]; - if (pstmt == null) - { - pstmt = connection.getConnection().prepareStatement("DELETE FROM " + _tableNameExchangeQueueRelation + - " WHERE QueueID = ? AND NAME = ? AND RoutingKey = ?"); - connection.getStatements()[UNBIND_QUEUE] = pstmt; - } - pstmt.setInt(1, queue.getQueueID()); - pstmt.setString(2, exchange.getName().asString()); - pstmt.setString(3, routingKey.asString()); - pstmt.executeUpdate(); - } - catch (Exception e) - { - throw new InternalErrorException("Cannot remove Exchange: " + exchange, e); - } - finally - { - if (connection != null) - { - try - { - connection.getConnection().commit(); - _connectionPool.releaseInstance(connection); - } - catch (SQLException e) - { - // we did not manage to commit this connection - // it is better to release it - _connectionPool.releaseDeadInstance(); - throw new InternalErrorException("Cannot remove Exchange: " + exchange, e); - } - } - } - } - - public void createQueue(StorableQueue queue) - throws - InternalErrorException, - QueueAlreadyExistsException - { - MyConnection connection = null; - try - { - connection = (MyConnection) _connectionPool.acquireInstance(); - PreparedStatement pstmt = connection.getStatements()[CREATE_QUEUE]; - if (pstmt == null) - { - pstmt = connection.getConnection().prepareStatement("INSERT INTO " + _tableNameQueue + - " (QueueID,Name,Owner) VALUES (?,?,?)"); - connection.getStatements()[CREATE_QUEUE] = pstmt; - } - pstmt.setInt(1, queue.getQueueID()); - pstmt.setString(2, queue.getName().asString()); - if (queue.getOwner() != null) - { - pstmt.setString(3, queue.getOwner().asString()); - } - else - { - pstmt.setString(3, null); - } - pstmt.executeUpdate(); - } - catch (Exception e) - { - throw new InternalErrorException("Cannot create Queue: " + queue, e); - } - finally - { - if (connection != null) - { - try - { - connection.getConnection().commit(); - _connectionPool.releaseInstance(connection); - } - catch (SQLException e) - { - // we did not manage to commit this connection - // it is better to release it - _connectionPool.releaseDeadInstance(); - throw new InternalErrorException("Cannot create Queue: " + queue, e); - } - } - } - } - - public void destroyQueue(StorableQueue queue) - throws - InternalErrorException, - QueueDoesntExistException - { - MyConnection connection = null; - try - { - connection = (MyConnection) _connectionPool.acquireInstance(); - PreparedStatement pstmt = connection.getStatements()[DELETE_QUEUE]; - if (pstmt == null) - { - pstmt = connection.getConnection().prepareStatement("DELETE FROM " + _tableNameQueue + - " WHERE QueueID = ?"); - connection.getStatements()[DELETE_QUEUE] = pstmt; - } - pstmt.setInt(1, queue.getQueueID()); - pstmt.executeUpdate(); - } - catch (Exception e) - { - throw new InternalErrorException("Cannot remove Queue: " + queue, e); - } - finally - { - if (connection != null) - { - try - { - connection.getConnection().commit(); - _connectionPool.releaseInstance(connection); - } - catch (SQLException e) - { - // we did not manage to commit this connection - // it is better to release it - _connectionPool.releaseDeadInstance(); - throw new InternalErrorException("Cannot remove Queue: " + queue, e); - } - } - } - } - - public void stage(StorableMessage m) - throws - InternalErrorException, - MessageAlreadyStagedException - { - if (m.isStaged() || m.isEnqueued()) - { - _log.error("Message with Id " + m.getMessageId() + " is already staged"); - throw new MessageAlreadyStagedException("Message eith Id " + m.getMessageId() + " is already staged"); - } - MyConnection connection = null; - try - { - connection = (MyConnection) _connectionPool.acquireInstance(); - stage(connection, m); - } - catch (Exception e) - { - throw new InternalErrorException("Cannot stage Message: " + m, e); - } - finally - { - if (connection != null) - { - try - { - connection.getConnection().commit(); - _connectionPool.releaseInstance(connection); - } - catch (SQLException e) - { - // we did not manage to commit this connection - // it is better to release it - _connectionPool.releaseDeadInstance(); - throw new InternalErrorException("Cannot stage Message: " + m, e); - } - } - } - } - - public void appendContent(StorableMessage m, byte[] data, int offset, int size) - throws - InternalErrorException, - MessageDoesntExistException - { - // The message must have been staged - if (!m.isStaged()) - { - _log.error("Cannot append content of message Id " - + m.getMessageId() + " as it has not been staged"); - throw new MessageDoesntExistException("Cannot append content of message Id " - + m.getMessageId() + " as it has not been staged"); - } - MyConnection connection = null; - try - { - connection = (MyConnection) _connectionPool.acquireInstance(); - appendContent(connection, m, data, offset, size); - } - catch (Exception e) - { - throw new InternalErrorException("Cannot stage Message: " + m, e); - } - finally - { - if (connection != null) - { - try - { - connection.getConnection().commit(); - _connectionPool.releaseInstance(connection); - } - catch (SQLException e) - { - // we did not manage to commit this connection - // it is better to release it - _connectionPool.releaseDeadInstance(); - throw new InternalErrorException("Cannot stage Message: " + m, e); - } - } - } - } - - public byte[] loadContent(StorableMessage m, int offset, int size) - throws - InternalErrorException, - MessageDoesntExistException - { - MyConnection connection = null; - try - { - byte[] result; - connection = (MyConnection) _connectionPool.acquireInstance(); - PreparedStatement pstmt = connection.getStatements()[SELECT_MESSAGE_PAYLOAD]; - if (pstmt == null) - { - pstmt = connection.getConnection().prepareStatement("SELECT Payload FROM " + _tableNameMessage + - " WHERE MessageID = ? "); - connection.getStatements()[SELECT_MESSAGE_PAYLOAD] = pstmt; - } - pstmt.setLong(1, m.getMessageId()); - ResultSet rs = pstmt.executeQuery(); - if (!rs.next()) - { - throw new MessageDoesntExistException("Cannot load content of message Id " - + m.getMessageId() + " as it has not been found"); - } - Blob myBlob = rs.getBlob(1); - - if (myBlob.length() > 0) - { - if (size == 0) - { - result = myBlob.getBytes(offset, (int) myBlob.length()); - } - else - { - result = myBlob.getBytes(offset, size); - } - } - else - { - throw new MessageDoesntExistException("Cannot load content of message Id " - + m.getMessageId() + " as it has not been found"); - } - rs.close(); - return result; - } - catch (Exception e) - { - throw new InternalErrorException("Cannot load Message: " + m, e); - } - finally - { - if (connection != null) - { - try - { - connection.getConnection().commit(); - _connectionPool.releaseInstance(connection); - } - catch (SQLException e) - { - // we did not manage to commit this connection - // it is better to release it - _connectionPool.releaseDeadInstance(); - throw new InternalErrorException("Cannot load Message: " + m, e); - } - } - } - } - - public void destroy(StorableMessage m) - throws - InternalErrorException, - MessageDoesntExistException - { - MyConnection connection = null; - try - { - connection = (MyConnection) _connectionPool.acquireInstance(); - destroy(connection, m); - } - catch (Exception e) - { - throw new InternalErrorException("Cannot destroy message: " + m, e); - } - finally - { - if (connection != null) - { - try - { - connection.getConnection().commit(); - _connectionPool.releaseInstance(connection); - } - catch (SQLException e) - { - // we did not manage to commit this connection - // it is better to release it - _connectionPool.releaseDeadInstance(); - throw new InternalErrorException("Cannot destroy message: " + m, e); - } - } - } - } - - public void enqueue(Xid xid, StorableMessage m, StorableQueue queue) - throws - InternalErrorException, - QueueDoesntExistException, - InvalidXidException, - UnknownXidException, - MessageDoesntExistException - { - MyConnection connection = null; - // Get the current tx - JDBCTransaction tx = getTx(xid); - // If this operation is transacted then we need to add a record - if (tx != null && !tx.isPrepared()) - { - // add an enqueue record - tx.addRecord(new JDBCEnqueueRecord(m, queue)); - } - else - { - try - { - if (tx != null) - { - connection = tx.getConnection(); - } - else - { - connection = (MyConnection) _connectionPool.acquireInstance(); - } - if (!m.isStaged() && !m.isEnqueued()) - { - //This is the first time this message is enqueued and it has not been staged. - stage(connection, m); - appendContent(connection, m, m.getData(), 0, m.getData().length); - } - PreparedStatement pstmt = connection.getStatements()[ENQUEUE]; - if (pstmt == null) - { - pstmt = connection.getConnection().prepareStatement("INSERT INTO " + _tableNameQueueMessageRelation + - " (QueueID,MessageID,Prepared) VALUES (?,?,0)"); - connection.getStatements()[ENQUEUE] = pstmt; - } - pstmt.setInt(1, queue.getQueueID()); - pstmt.setLong(2, m.getMessageId()); - pstmt.executeUpdate(); - m.enqueue(queue); - queue.enqueue(m); - } - catch (Exception e) - { - throw new InternalErrorException("Cannot enqueue message : " + m + " in queue: " + queue, e); - } - finally - { - if (tx == null && connection != null) - { - try - { - connection.getConnection().commit(); - _connectionPool.releaseInstance(connection); - } - catch (SQLException e) - { - // we did not manage to commit this connection - // it is better to release it - _connectionPool.releaseDeadInstance(); - throw new InternalErrorException("Cannot enqueue message : " + m + " in queue: " + queue, e); - } - } - } - } - } - - public void dequeue(Xid xid, StorableMessage m, StorableQueue queue) - throws - InternalErrorException, - QueueDoesntExistException, - InvalidXidException, - UnknownXidException - { - MyConnection connection = null; - // Get the current tx - JDBCTransaction tx = getTx(xid); - // If this operation is transacted then we need to add a record - if (tx != null && !tx.isPrepared()) - { - // add an dequeue record - tx.addRecord(new JDBCDequeueRecord(m, queue)); - } - else - { - try - { - if (tx != null) - { - connection = tx.getConnection(); - } - else - { - connection = (MyConnection) _connectionPool.acquireInstance(); - } - PreparedStatement pstmt = connection.getStatements()[DEQUEUE]; - if (pstmt == null) - { - pstmt = connection.getConnection().prepareStatement("DELETE FROM " + _tableNameQueueMessageRelation + - " WHERE QueueID = ? AND MessageID = ?"); - connection.getStatements()[DEQUEUE] = pstmt; - } - pstmt.setInt(1, queue.getQueueID()); - pstmt.setLong(2, m.getMessageId()); - pstmt.executeUpdate(); - m.dequeue(queue); - if (!m.isEnqueued()) - { - // delete this message from persistence store - destroy(connection, m); - } - queue.dequeue(m); - } - catch (Exception e) - { - throw new InternalErrorException("Cannot enqueue message : " + m + " in queue: " + queue, e); - } - finally - { - if (tx == null && connection != null) - { - try - { - connection.getConnection().commit(); - _connectionPool.releaseInstance(connection); - } - catch (SQLException e) - { - // we did not manage to commit this connection - // it is better to release it - _connectionPool.releaseDeadInstance(); - throw new InternalErrorException("Cannot enqueue message : " + m + " in queue: " + queue, e); - } - } - } - } - } - - public Collection<StorableQueue> getAllQueues() - throws - InternalErrorException - { - MyConnection connection = null; - List<StorableQueue> result = new ArrayList<StorableQueue>(); - try - { - connection = (MyConnection) _connectionPool.acquireInstance(); - PreparedStatement pstmt = connection.getStatements()[GET_ALL_QUEUES]; - if (pstmt == null) - { - pstmt = connection.getConnection().prepareStatement("SELECT * FROM " + _tableNameQueue); - connection.getStatements()[GET_ALL_QUEUES] = pstmt; - } - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) - { - //the queue owner may be null - AMQShortString queueOwner = null; - if (rs.getString(3) != null) - { - queueOwner = new AMQShortString(rs.getString(3)); - } - result.add(new AMQQueue(new AMQShortString(rs.getString(2)), true, queueOwner, - false, _virtualHost)); - } - rs.close(); - return result; - } - catch (Exception e) - { - throw new InternalErrorException("Cannot get all queues", e); - } - finally - { - if (connection != null) - { - try - { - connection.getConnection().commit(); - _connectionPool.releaseInstance(connection); - } - catch (SQLException e) - { - // we did not manage to commit this connection - // it is better to release it - _connectionPool.releaseDeadInstance(); - throw new InternalErrorException("Cannot get all queues", e); - } - } - } - } - - public Collection<StorableMessage> getAllMessages(StorableQueue queue) - throws - InternalErrorException - { - MyConnection connection = null; - try - { - connection = (MyConnection) _connectionPool.acquireInstance(); - return getAllMessages(connection, queue); - } - catch (Exception e) - { - throw new InternalErrorException("Cannot get all queues", e); - } - finally - { - if (connection != null) - { - try - { - connection.getConnection().commit(); - _connectionPool.releaseInstance(connection); - } - catch (SQLException e) - { - // we did not manage to commit this connection - // it is better to release it - _connectionPool.releaseDeadInstance(); - throw new InternalErrorException("Cannot get all queues", e); - } - } - } - } - - public HashMap<Xid, Transaction> getAllInddoubt() - throws - InternalErrorException - { - MyConnection connection = null; - HashMap<Xid, Transaction> result = new HashMap<Xid, Transaction>(); - try - { - //TransactionalContext txnContext = new NonTransactionalContext(this, new StoreContext(), null, null, null); - MessageHandleFactory messageHandleFactory = new MessageHandleFactory(); - // re-create all the tx - connection = (MyConnection) _connectionPool.acquireInstance(); - Statement stmt = connection.getConnection().createStatement(); - ResultSet rs = stmt.executeQuery("SELECT * FROM " + _tableNameTransaction); - JDBCTransaction foundTx; - Xid foundXid; - long foundXIDID; - while (rs.next()) - { - // set the XID_ID - foundXIDID = rs.getLong(1); - if (foundXIDID > JDBCTransaction._xidId) - { - JDBCTransaction._xidId = foundXIDID; - } - foundTx = new JDBCTransaction(); - foundXid = new XidImpl(rs.getBlob(3).getBytes(1, (int) rs.getBlob(3).length()), - rs.getInt(2), rs.getBlob(4).getBytes(1, (int) rs.getBlob(4).length())); - // get all the records - Statement stmtr = connection.getConnection().createStatement(); - ResultSet rsr = stmtr.executeQuery("SELECT * FROM " + _tableNameRecord + - " WHERE XID_ID = " + rs.getLong(1)); - int foundType; - AMQQueue foundQueue; - StorableMessage foundMessage; - TransactionRecord foundRecord; - while (rsr.next()) - { - // those messages were not recovered before so they need to be recreated - foundType = rsr.getInt(2); - foundQueue = _queueMap.get(new Integer(rsr.getInt(4))); - - //DTX MessageStore - this -> null , txContext -> null - foundMessage = new AMQMessage(rs.getLong(3), null, messageHandleFactory, null); - if (foundType == JDBCAbstractRecord.TYPE_DEQUEUE) - { - foundRecord = new JDBCDequeueRecord(foundMessage, foundQueue); - } - else - { - foundRecord = new JDBCEnqueueRecord(foundMessage, foundQueue); - } - foundTx.addRecord(foundRecord); - } - rsr.close(); - // add this tx to the map - result.put(foundXid, foundTx); - } - rs.close(); - return result; - } - catch (Exception e) - { - throw new InternalErrorException("Cannot recover: ", e); - } - finally - { - if (connection != null) - { - try - { - connection.getConnection().commit(); - _connectionPool.releaseInstance(connection); - } - catch (SQLException e) - { - // we did not manage to commit this connection - // it is better to release it - _connectionPool.releaseDeadInstance(); - throw new InternalErrorException("Cannot recover: ", e); - } - } - } - } - - - public long getNewMessageId() - { - return _messageID++; - } - - //======================================================================== - // Public methods - //======================================================================== - - public MyConnection getConnection() - throws - Exception - { - return (MyConnection) _connectionPool.acquireInstance(); - } - - public void commitConnection(MyConnection connection) - throws - InternalErrorException - { - try - { - connection.getConnection().commit(); - _connectionPool.releaseInstance(connection); - } - catch (SQLException e) - { - // we did not manage to commit this connection - // it is better to release it - _connectionPool.releaseDeadInstance(); - throw new InternalErrorException("Cannot commit connection =", e); - } - } - - public void rollbackConnection(MyConnection connection) - throws - InternalErrorException - { - try - { - connection.getConnection().rollback(); - _connectionPool.releaseInstance(connection); - } - catch (SQLException e) - { - // we did not manage to rollback this connection - // it is better to release it - _connectionPool.releaseDeadInstance(); - throw new InternalErrorException("Cannot rollback connection", e); - } - } - - public void appendContent(MyConnection connection, StorableMessage m, byte[] data, int offset, int size) - throws - SQLException, - MessageDoesntExistException - { - PreparedStatement pstmt = connection.getStatements()[SELECT_MESSAGE_PAYLOAD]; - if (pstmt == null) - { - pstmt = connection.getConnection().prepareStatement("SELECT Payload FROM " + _tableNameMessage + - " WHERE MessageID = ? "); - connection.getStatements()[SELECT_MESSAGE_PAYLOAD] = pstmt; - } - pstmt.setLong(1, m.getMessageId()); - ResultSet rs = pstmt.executeQuery(); - if (!rs.next()) - { - throw new MessageDoesntExistException("Cannot append content of message Id " - + m.getMessageId() + " as it has not been found"); - } - Blob myBlob = rs.getBlob(1); - byte[] oldPayload; - if (myBlob != null && myBlob.length() > 0) - { - oldPayload = myBlob.getBytes(1, (int) myBlob.length()); - } - else - { - oldPayload = new byte[0]; - } - rs.close(); - byte[] newPayload = new byte[oldPayload.length + size]; - ByteBuffer buffer = ByteBuffer.wrap(newPayload); - buffer.put(oldPayload); - buffer.put(data, offset, size); - PreparedStatement pstmtUpdate = connection.getStatements()[UPDATE_MESSAGE_PAYLOAD]; - if (pstmtUpdate == null) - { - pstmtUpdate = connection.getConnection().prepareStatement("UPDATE " + _tableNameMessage + - " SET Payload = ? WHERE MessageID = ?"); - connection.getStatements()[UPDATE_MESSAGE_PAYLOAD] = pstmtUpdate; - } - pstmtUpdate.setBytes(1, newPayload); - pstmtUpdate.setLong(2, m.getMessageId()); - pstmtUpdate.executeUpdate(); - } - - public void stage(MyConnection connection, StorableMessage m) - throws - Exception - { - PreparedStatement pstmt = connection.getStatements()[STAGE_MESSAGE]; - if (pstmt == null) - { - pstmt = connection.getConnection().prepareStatement("INSERT INTO " + _tableNameMessage + - " (MessageID,Header,ExchangeName,RoutingKey,Mandatory,Is_Immediate) VALUES (?,?,?,?,?,?)"); - connection.getStatements()[STAGE_MESSAGE] = pstmt; - } - pstmt.setLong(1, m.getMessageId()); - pstmt.setBytes(2, m.getHeaderBody()); - pstmt.setString(3, ((AMQMessage) m).getMessagePublishInfo().getExchange().asString()); - pstmt.setString(4, ((AMQMessage) m).getMessagePublishInfo().getRoutingKey().asString()); - pstmt.setBoolean(5, ((AMQMessage) m).getMessagePublishInfo().isMandatory()); - pstmt.setBoolean(6, ((AMQMessage) m).getMessagePublishInfo().isImmediate()); - pstmt.executeUpdate(); - m.staged(); - } - - public void saveRecord(MyConnection connection, JDBCTransaction tx, JDBCAbstractRecord record) - throws - InternalErrorException - { - try - { - PreparedStatement pstmt = connection.getStatements()[SAVE_RECORD]; - if (pstmt == null) - { - pstmt = connection.getConnection().prepareStatement("INSERT INTO " + _tableNameRecord + - " (XID_ID,Type,MessageID,QueueID) VALUES (?,?,?,?)"); - connection.getStatements()[SAVE_RECORD] = pstmt; - } - pstmt.setLong(1, tx.getXidID()); - pstmt.setInt(2, record.getType()); - pstmt.setLong(3, record.getMessageID()); - pstmt.setLong(4, record.getQueueID()); - pstmt.executeUpdate(); - } - catch (Exception e) - { - throw new InternalErrorException("Cannot save record: " + record, e); - } - } - - public void saveXID(MyConnection connection, JDBCTransaction tx, Xid xid) - throws - InternalErrorException - { - try - { - PreparedStatement pstmt = connection.getStatements()[SAVE_XID]; - if (pstmt == null) - { - pstmt = connection.getConnection().prepareStatement("INSERT INTO " + _tableNameTransaction + - " (XID_ID,FormatId, BranchQualifier,GlobalTransactionId) VALUES (?,?,?,?)"); - connection.getStatements()[SAVE_XID] = pstmt; - } - pstmt.setLong(1, tx.getXidID()); - pstmt.setInt(2, xid.getFormatId()); - pstmt.setBytes(3, xid.getBranchQualifier()); - pstmt.setBytes(4, xid.getGlobalTransactionId()); - pstmt.executeUpdate(); - } - catch (Exception e) - { - throw new InternalErrorException("Cannot save xid: " + xid, e); - } - } - - public void deleteRecords(MyConnection connection, JDBCTransaction tx) - throws - InternalErrorException - { - try - { - PreparedStatement pstmt = connection.getStatements()[DELETE_RECORD]; - if (pstmt == null) - { - pstmt = connection.getConnection().prepareStatement("DELETE FROM " + _tableNameRecord + - " WHERE XID_ID = ?"); - connection.getStatements()[DELETE_RECORD] = pstmt; - } - pstmt.setLong(1, tx.getXidID()); - pstmt.executeUpdate(); - } - catch (Exception e) - { - throw new InternalErrorException("Cannot delete record: " + tx.getXidID(), e); - } - } - - public void deleteXID(MyConnection connection, JDBCTransaction tx) - throws - InternalErrorException - { - try - { - PreparedStatement pstmt = connection.getStatements()[DELETE_XID]; - if (pstmt == null) - { - pstmt = connection.getConnection().prepareStatement("DELETE FROM " + _tableNameTransaction + - " WHERE XID_ID = ?"); - connection.getStatements()[DELETE_XID] = pstmt; - } - pstmt.setLong(1, tx.getXidID()); - pstmt.executeUpdate(); - } - catch (Exception e) - { - throw new InternalErrorException("Cannot delete xid: " + tx.getXidID(), e); - } - } - - public void prepareDequeu(Xid xid, StorableMessage m, StorableQueue queue) - throws - UnknownXidException, - InternalErrorException - { - JDBCTransaction tx = getTx(xid); - if (tx == null) - { - throw new UnknownXidException(xid, null); - } - updateQueueMessageRelation(tx.getConnection(), queue.getQueueID(), m.getMessageId(), 1); - - } - - public void rollbackDequeu(Xid xid, StorableMessage m, StorableQueue queue) - throws - UnknownXidException, - InternalErrorException - { - JDBCTransaction tx = getTx(xid); - if (tx == null) - { - throw new UnknownXidException(xid, null); - } - updateQueueMessageRelation(tx.getConnection(), queue.getQueueID(), m.getMessageId(), 0); - } - - //======================================================================== - // Private methods - //======================================================================== - - - private void updateQueueMessageRelation(MyConnection connection, - int queueID, long messageId, int prepared) - throws - InternalErrorException - { - try - { - PreparedStatement pstmt = connection.getStatements()[UPDATE_QMR]; - if (pstmt == null) - { - pstmt = connection.getConnection().prepareStatement("UPDATE " + _tableNameQueueMessageRelation + - " SET Prepared = ? WHERE MessageID = ? AND QueueID = ?"); - connection.getStatements()[UPDATE_QMR] = pstmt; - } - pstmt.setInt(1, prepared); - pstmt.setLong(2, messageId); - pstmt.setInt(3, queueID); - pstmt.executeUpdate(); - } - catch (Exception e) - { - throw new InternalErrorException("Cannot update QMR", e); - } - - } - - public MessagePublishInfo getMessagePublishInfo(StorableMessage m) - throws - InternalErrorException - { - MyConnection connection = null; - MessagePublishInfo result; - try - { - connection = (MyConnection) _connectionPool.acquireInstance(); - PreparedStatement pstmt = connection.getStatements()[GET_MESSAGE_INFO]; - if (pstmt == null) - { - pstmt = connection.getConnection().prepareStatement("SELECT ExchangeName, RoutingKey," + - " Mandatory, Is_Immediate from " + _tableNameMessage + - " WHERE MessageID = ?"); - connection.getStatements()[GET_MESSAGE_INFO] = pstmt; - } - pstmt.setLong(1, m.getMessageId()); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) - { - final AMQShortString exchange = new AMQShortString(rs.getString(1)); - final AMQShortString routingKey = new AMQShortString(rs.getString(2)); - final boolean mandatory = rs.getBoolean(3); - final boolean immediate = rs.getBoolean(4); - result = new MessagePublishInfo() - { - - public AMQShortString getExchange() - { - return exchange; - } - - public boolean isImmediate() - { - return immediate; - } - - public boolean isMandatory() - { - return mandatory; - } - - public AMQShortString getRoutingKey() - { - return routingKey; - } - }; - } - else - { - throw new InternalErrorException("Cannot get MessagePublishInfo of message: " + m); - } - rs.close(); - return result; - } - catch (Exception e) - { - throw new InternalErrorException("Cannot get MessagePublishInfo of message: " + m, e); - } - finally - { - if (connection != null) - { - try - { - connection.getConnection().commit(); - _connectionPool.releaseInstance(connection); - } - catch (SQLException e) - { - // we did not manage to commit this connection - // it is better to release it - _connectionPool.releaseDeadInstance(); - throw new InternalErrorException("Cannot get MessagePublishInfo of message: " + m, e); - } - } - } - } - - public ContentHeaderBody getContentHeaderBody(StorableMessage m) - throws - InternalErrorException - { - MyConnection connection = null; - ContentHeaderBody result; - try - { - connection = (MyConnection) _connectionPool.acquireInstance(); - PreparedStatement pstmt = connection.getStatements()[GET_CONTENT_HEADER]; - if (pstmt == null) - { - pstmt = connection.getConnection().prepareStatement("SELECT Header from " + _tableNameMessage + - " WHERE MessageID = ?"); - connection.getStatements()[GET_CONTENT_HEADER] = pstmt; - } - pstmt.setLong(1, m.getMessageId()); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) - { - result = new ContentHeaderBody(ByteBuffer.wrap(rs.getBlob(1).getBytes(1, (int) rs.getBlob(1).length())), 0); - } - else - { - throw new InternalErrorException("Cannot get Content Header of message: " + m); - } - rs.close(); - return result; - } - catch (Exception e) - { - throw new InternalErrorException("Cannot get Content Header of message: " + m, e); - } - finally - { - if (connection != null) - { - try - { - connection.getConnection().commit(); - _connectionPool.releaseInstance(connection); - } - catch (SQLException e) - { - // we did not manage to commit this connection - // it is better to release it - _connectionPool.releaseDeadInstance(); - throw new InternalErrorException("Cannot get Content Header of message: " + m, e); - } - } - } - } - - private List<StorableMessage> getAllMessages(MyConnection connection, StorableQueue queue) - throws - SQLException, - AMQException - { - List<StorableMessage> result = new ArrayList<StorableMessage>(); -// TransactionalContext txnContext = new NonTransactionalContext(this, new StoreContext(), null, null, null); - MessageHandleFactory messageHandleFactory = new MessageHandleFactory(); - PreparedStatement pstmt = connection.getStatements()[GET_ALL_MESSAGES]; - if (pstmt == null) - { - pstmt = connection.getConnection().prepareStatement("SELECT " + _tableNameMessage + ".MessageID, Header FROM " + - _tableNameMessage + - " INNER JOIN " + - _tableNameQueueMessageRelation + - " ON " + - _tableNameMessage + ".MessageID = " + _tableNameQueueMessageRelation + ".MessageID" + - " WHERE " + - _tableNameQueueMessageRelation + ".QueueID = ?" + - " AND " + - _tableNameQueueMessageRelation + ".Prepared = 0"); - connection.getStatements()[GET_ALL_MESSAGES] = pstmt; - } - pstmt.setInt(1, queue.getQueueID()); - ResultSet rs = pstmt.executeQuery(); - AMQMessage foundMessage; - // ContentHeaderBody hb; - while (rs.next()) - { - - //DTX MessageStore - this -> null , txContext -> null - foundMessage = new AMQMessage(rs.getLong(1), null, messageHandleFactory, null); - - result.add(foundMessage); - } - rs.close(); - return result; - } - - private HashMap<Integer, AMQQueue> recover() - throws - InternalErrorException - { - MyConnection connection = null; - HashMap<Integer, AMQQueue> result = new HashMap<Integer, AMQQueue>(); - try - { - // re-create all the queues - connection = (MyConnection) _connectionPool.acquireInstance(); - Statement stmt = connection.getConnection().createStatement(); - ResultSet rs = stmt.executeQuery("SELECT * FROM " + _tableNameQueue); - AMQQueue foundQueue; - List<StorableMessage> foundMessages; - StoreContext context = new StoreContext(); - while (rs.next()) - { - AMQShortString owner = null; - if (rs.getString(3) != null) - { - owner = new AMQShortString(rs.getString(3)); - } - foundQueue = new AMQQueue(new AMQShortString(rs.getString(2)), - true, owner, false, _virtualHost); - // get all the Messages of that queue - foundMessages = getAllMessages(connection, foundQueue); - // enqueue those messages - if (_log.isDebugEnabled()) - { - _log.debug("Recovering " + foundMessages.size() + " messages for queue " + foundQueue.getName()); - } - for (StorableMessage foundMessage : foundMessages) - { - foundMessage.staged(); - foundMessage.enqueue(foundQueue); - foundQueue.enqueue(foundMessage); - foundQueue.process(context, (AMQMessage) foundMessage, false); - } - // add the queue in the result map - result.put(foundQueue.getQueueID(), foundQueue); - // add it in the registry - _virtualHost.getQueueRegistry().registerQueue(foundQueue); - } - rs.close(); - return result; - } - catch (Exception e) - { - throw new InternalErrorException("Cannot recover: ", e); - } - finally - { - if (connection != null) - { - try - { - connection.getConnection().commit(); - _connectionPool.releaseInstance(connection); - } - catch (SQLException e) - { - // we did not manage to commit this connection - // it is better to release it - _connectionPool.releaseDeadInstance(); - throw new InternalErrorException("Cannot recover: ", e); - } - } - } - } - - private void recoverExchanges(HashMap<Integer, AMQQueue> queueMap) - throws - InternalErrorException - { - MyConnection connection = null; - try - { - // re-create all the exchanges - connection = (MyConnection) _connectionPool.acquireInstance(); - Statement stmt = connection.getConnection().createStatement(); - ResultSet rs = stmt.executeQuery("SELECT * FROM " + _tableNameExchange); - Exchange foundExchange; - AMQQueue foundQueue; - while (rs.next()) - { - foundExchange = _virtualHost.getExchangeFactory().createExchange( - new AMQShortString(rs.getString(1)), new AMQShortString(rs.getString(2)), true, false, 0); - // get all the bindings - Statement stmtb = connection.getConnection().createStatement(); - ResultSet rsb = stmtb.executeQuery("SELECT * FROM " + _tableNameExchangeQueueRelation + - " WHERE Name = '" + rs.getString(1) + "'"); - while (rsb.next()) - { - foundQueue = queueMap.get(new Integer(rsb.getInt(1))); - if (foundQueue != null) - { - // the field table - FieldTable ft = null; - if (rsb.getBlob(4) != null) - { - long length = rsb.getBlob(4).length(); - ByteBuffer buffer = ByteBuffer.wrap(rsb.getBlob(4).getBytes(1, (int) length)); - ft = new FieldTable(buffer, length); - } - foundQueue.bind(new AMQShortString(rsb.getString(3)), ft, foundExchange); - } - } - rsb.close(); - // register this exchange - _virtualHost.getExchangeRegistry().registerExchange(foundExchange); - } - rs.close(); - } - catch (Exception e) - { - throw new InternalErrorException("Cannot recover: ", e); - } - finally - { - if (connection != null) - { - try - { - connection.getConnection().commit(); - _connectionPool.releaseInstance(connection); - } - catch (SQLException e) - { - // we did not manage to commit this connection - // it is better to release it - _connectionPool.releaseDeadInstance(); - throw new InternalErrorException("Cannot recover: ", e); - } - } - } - } - - private void destroy(MyConnection connection, StorableMessage m) - throws - SQLException - { - PreparedStatement pstmt = connection.getStatements()[DELETE_MESSAGE]; - if (pstmt == null) - { - pstmt = connection.getConnection().prepareStatement("DELETE FROM " + _tableNameMessage + - " WHERE MessageID = ?"); - connection.getStatements()[DELETE_MESSAGE] = pstmt; - } - pstmt.setLong(1, m.getMessageId()); - pstmt.executeUpdate(); - } - - private JDBCTransaction getTx(Xid xid) - throws - UnknownXidException - { - JDBCTransaction tx = null; - if (xid != null) - { - tx = _tm.getTransaction(xid); - } - return tx; - } - - /** - * setupConnections - Initialize the connections - * - * @return true if ok - */ - private synchronized boolean setupConnections() - { - try - { - if (_connectionPool == null) - { - // In an embedded environment, loading the driver also starts Derby. - Class.forName(_driver).newInstance(); - _connectionPool = new ConnectionPool(_maxSize); - } - } - catch (Exception e) - { - _log.warn("Setup connections trouble", e); - return false; - } - return true; - } - - /** - * Try to create the connection and table. - * If this fails, then we will exit. - */ - protected synchronized boolean setupStore(boolean dropTables) - { - if (!setupConnections()) - { - return false; - } - MyConnection myconnection = null; - try - { - myconnection = (MyConnection) _connectionPool.acquireInstance(); - Statement stmt = myconnection._connection.createStatement(); - /* - * TODO Need some management interface to delete the table! - */ - if (dropTables) - { - try - { - stmt.executeUpdate("DROP TABLE " + _tableNameMessage); - myconnection._connection.commit(); - } - catch (SQLException ex) - { - // don't want to print error - chances are it - // just reports that the table does not exist - // ex.printStackTrace(); - } - try - { - stmt.executeUpdate("DROP TABLE " + _tableNameQueue); - myconnection._connection.commit(); - } - catch (SQLException ex) - { - // ex.printStackTrace(); - } - try - { - stmt.executeUpdate("DROP TABLE " + _tableNameQueueMessageRelation); - myconnection._connection.commit(); - } - catch (SQLException ex) - { - // ex.printStackTrace(); - } - try - { - stmt.executeUpdate("DROP TABLE " + _tableNameExchange); - myconnection._connection.commit(); - } - catch (SQLException ex) - { - // ex.printStackTrace(); - } - try - { - stmt.executeUpdate("DROP TABLE " + _tableNameExchangeQueueRelation); - myconnection._connection.commit(); - } - catch (SQLException ex) - { - // ex.printStackTrace(); - } - try - { - stmt.executeUpdate("DROP TABLE " + _tableNameRecord); - myconnection._connection.commit(); - } - catch (SQLException ex) - { - // ex.printStackTrace(); - } - try - { - stmt.executeUpdate("DROP TABLE " + _tableNameTransaction); - myconnection._connection.commit(); - } - catch (SQLException ex) - { - // ex.printStackTrace(); - } - } - // create the table for messages - try - { - stmt.executeUpdate("CREATE TABLE " + _tableNameMessage + " (MessageID FLOAT NOT NULL, Header BLOB," + - " Payload BLOB, ExchangeName VARCHAR(1024), RoutingKey VARCHAR(1024)," + - " Mandatory INTEGER, Is_Immediate INTEGER, PRIMARY KEY(MessageID))"); - myconnection._connection.commit(); - } - catch (SQLException ex) - { - // ex.printStackTrace(); - // assume this is reporting that the table already exists: - } - // create the table for queues - try - { - stmt.executeUpdate("CREATE TABLE " + _tableNameQueue + " (QueueID INTEGER NOT NULL, " + - "Name VARCHAR(1024) NOT NULL, Owner VARCHAR(1024), PRIMARY KEY(QueueID))"); - myconnection._connection.commit(); - } - catch (SQLException ex) - { - //ex.printStackTrace(); - // assume this is reporting that the table already exists: - } - // create the table for queue to message mapping - try - { - stmt.executeUpdate("CREATE TABLE " + _tableNameQueueMessageRelation + " (QueueID INTEGER NOT NULL, " + - "MessageID FLOAT NOT NULL, Prepared INTEGER)"); - myconnection._connection.commit(); - } - catch (SQLException ex) - { - //ex.printStackTrace(); - // assume this is reporting that the table already exists: - } - try - { - stmt.executeUpdate("CREATE TABLE " + _tableNameExchange + " (Name VARCHAR(1024) NOT NULL, " + - "Type VARCHAR(1024) NOT NULL, PRIMARY KEY(Name))"); - myconnection._connection.commit(); - } - catch (SQLException ex) - { - //ex.printStackTrace(); - // assume this is reporting that the table already exists: - } - try - { - stmt.executeUpdate("CREATE TABLE " + _tableNameExchangeQueueRelation + " (QueueID INTEGER NOT NULL, " + - "Name VARCHAR(1024) NOT NULL, RoutingKey VARCHAR(1024), FieldTable BLOB )"); - myconnection._connection.commit(); - } - catch (SQLException ex) - { - //ex.printStackTrace(); - // assume this is reporting that the table already exists: - } - try - { - stmt.executeUpdate("CREATE TABLE " + _tableNameRecord + " (XID_ID FLOAT, Type INTEGER, MessageID FLOAT, " + - "QueueID INTEGER, PRIMARY KEY(Type, MessageID, QueueID))"); - // we could alter the table with QueueID as foreign key - myconnection._connection.commit(); - } - catch (SQLException ex) - { - //ex.printStackTrace(); - // assume this is reporting that the table already exists: - } - try - { - stmt.executeUpdate("CREATE TABLE " + _tableNameTransaction + " (XID_ID FLOAT, FormatId INTEGER, " + - "BranchQualifier BLOB, GlobalTransactionId BLOB, PRIMARY KEY(XID_ID))"); - myconnection._connection.commit(); - } - catch (SQLException ex) - { - // ex.printStackTrace(); - // assume this is reporting that the table already exists: - } - } - catch (Throwable e) - { - _log.warn("Setup Store trouble: ", e); - return false; - } - finally - { - if (myconnection != null) - { - _connectionPool.releaseInstance(myconnection); - } - } - return true; - } - //======================================================================================== - //============== the connection pool ===================================================== - //======================================================================================== - - private class ConnectionPool extends Pool - { - - /** - * Create a pool of specified size. Negative or null pool sizes are - * disallowed. - * - * @param poolSize The size of the pool to create. Should be 1 or - * greater. - * @throws Exception If the pool size is less than 1. - */ - public ConnectionPool(int poolSize) - throws - Exception - { - super(poolSize); - } - - /** - * @return An instance of the pooled object. - * @throws Exception In case of internal error. - */ - protected MyConnection createInstance() - throws - Exception - { - try - { - // standard way to obtain a Connection object is to call the method DriverManager.getConnection, - // which takes a String containing a connection URL (uniform resource locator). - Connection conn = DriverManager.getConnection(_connectionURL); - //conn.setAutoCommit(true); - PreparedStatement[] st = new PreparedStatement[STATEMENT_SIZE]; - for (int j = 0; j < STATEMENT_SIZE; j++) - { - st[j] = null; - } - return new MyConnection(conn, st); - } - catch (SQLException e) - { - throw new Exception("sqlException when creating connection to " + _connectionURL, e); - } - } - } - - public class MyConnection - { - // the connection - private Connection _connection = null; - // its associated prepared statements - private PreparedStatement[] _preparedStatements = null; - - MyConnection(Connection con, PreparedStatement[] st) - { - _connection = con; - _preparedStatements = st; - } - - public Connection getConnection() - { - return _connection; - } - - public PreparedStatement[] getStatements() - { - return _preparedStatements; - } - - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/messageStore/MemoryMessageStore.java b/java/broker/src/main/java/org/apache/qpid/server/messageStore/MemoryMessageStore.java deleted file mode 100644 index 8954ffc4d7..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/messageStore/MemoryMessageStore.java +++ /dev/null @@ -1,273 +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.messageStore; - -import java.io.ByteArrayOutputStream; -import java.nio.ByteBuffer; -import java.util.*; - -import javax.transaction.xa.Xid; - -import org.apache.commons.configuration.Configuration; - -import org.apache.log4j.Logger; - -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.abstraction.MessagePublishInfo; -import org.apache.qpid.server.exception.*; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.txn.MemoryDequeueRecord; -import org.apache.qpid.server.txn.MemoryEnqueueRecord; -import org.apache.qpid.server.txn.TransactionManager; -import org.apache.qpid.server.txn.TransactionRecord; -import org.apache.qpid.server.virtualhost.VirtualHost; - -/** - * This a simple in-memory implementation of a message store i.e. nothing is persisted - * <p/> - * Created by Arnaud Simon - * Date: 26-Apr-2007 - * Time: 08:23:45 - */ -public class MemoryMessageStore implements MessageStore -{ - // ======================================================================== - // Static Constants - // ======================================================================== - // The logger for this class - private static final Logger _log = Logger.getLogger(MemoryMessageStore.class); - - // The table of message with its corresponding stream containing the message body - private Map<StorableMessage, ByteArrayOutputStream> _stagedMessages; - // The queue/messages association - protected Map<StorableQueue, List<StorableMessage>> _queueMap; - // the message ID - private long _messageID = 0; - // The transaction manager - private TransactionManager _txm; - - // ======================================================================== - // Interface MessageStore - // ======================================================================== - - public void removeExchange(Exchange exchange) throws InternalErrorException - { - // do nothing this is inmemory - } - - public void unbindQueue(Exchange exchange, AMQShortString routingKey, StorableQueue queue, FieldTable args) - throws InternalErrorException - { - // do nothing this is inmemory - } - - public void createExchange(Exchange exchange) throws InternalErrorException - { - // do nothing this is inmemory - } - - public void bindQueue(Exchange exchange, AMQShortString routingKey, StorableQueue queue, FieldTable args) - throws InternalErrorException - { - // do nothing this is inmemory - } - - public void configure(VirtualHost virtualHost, TransactionManager tm, String base, Configuration config) - throws InternalErrorException, IllegalArgumentException - { - _log.info("Configuring memory message store"); - // Initialise the maps - _stagedMessages = new HashMap<StorableMessage, ByteArrayOutputStream>(); - _queueMap = new HashMap<StorableQueue, List<StorableMessage>>(); - _txm = tm; - _txm.configure(this, "txn", config); - } - - public void close() throws InternalErrorException - { - _log.info("Closing memory message store"); - _stagedMessages.clear(); - _queueMap.clear(); - } - - public void createQueue(StorableQueue queue) throws InternalErrorException, QueueAlreadyExistsException - { - if (_queueMap.containsKey(queue)) - { - throw new QueueAlreadyExistsException("queue " + queue + " already exists"); - } - // add this queue into the map - _queueMap.put(queue, new LinkedList<StorableMessage>()); - } - - public void destroyQueue(StorableQueue queue) throws InternalErrorException, QueueDoesntExistException - { - if (!_queueMap.containsKey(queue)) - { - throw new QueueDoesntExistException("queue " + queue + " does not exist"); - } - // remove this queue from the map - _queueMap.remove(queue); - } - - public void stage(StorableMessage m) throws InternalErrorException, MessageAlreadyStagedException - { - if (_stagedMessages.containsKey(m)) - { - throw new MessageAlreadyStagedException("message " + m + " already staged"); - } - - _stagedMessages.put(m, new ByteArrayOutputStream()); - m.staged(); - } - - public void appendContent(StorableMessage m, byte[] data, int offset, int size) - throws InternalErrorException, MessageDoesntExistException - { - if (!_stagedMessages.containsKey(m)) - { - throw new MessageDoesntExistException("message " + m + " has not been staged"); - } - - _stagedMessages.get(m).write(data, offset, size); - } - - public byte[] loadContent(StorableMessage m, int offset, int size) - throws InternalErrorException, MessageDoesntExistException - { - if (!_stagedMessages.containsKey(m)) - { - throw new MessageDoesntExistException("message " + m + " has not been staged"); - } - - byte[] result = new byte[size]; - ByteBuffer buf = ByteBuffer.allocate(size); - buf.put(_stagedMessages.get(m).toByteArray(), offset, size); - buf.get(result); - - return result; - } - - public void destroy(StorableMessage m) throws InternalErrorException, MessageDoesntExistException - { - if (!_stagedMessages.containsKey(m)) - { - throw new MessageDoesntExistException("message " + m + " has not been staged"); - } - - _stagedMessages.remove(m); - } - - public void enqueue(Xid xid, StorableMessage m, StorableQueue queue) - throws InternalErrorException, QueueDoesntExistException, InvalidXidException, UnknownXidException, - MessageDoesntExistException - { - if (xid != null) - { - // this is a tx operation - TransactionRecord enqueueRecord = new MemoryEnqueueRecord(m, queue); - _txm.getTransaction(xid).addRecord(enqueueRecord); - } - else - { - if (!_stagedMessages.containsKey(m)) - { - try - { - stage(m); - } - catch (MessageAlreadyStagedException e) - { - throw new InternalErrorException(e.getMessage(), e); - } - - appendContent(m, m.getData(), 0, m.getPayloadSize()); - } - - if (!_queueMap.containsKey(queue)) - { - throw new QueueDoesntExistException("queue " + queue + " dos not exist"); - } - - _queueMap.get(queue).add(m); - m.enqueue(queue); - } - } - - public void dequeue(Xid xid, StorableMessage m, StorableQueue queue) - throws InternalErrorException, QueueDoesntExistException, InvalidXidException, UnknownXidException - { - if (xid != null) - { - // this is a tx operation - TransactionRecord dequeueRecord = new MemoryDequeueRecord(m, queue); - _txm.getTransaction(xid).addRecord(dequeueRecord); - } - else - { - if (!_queueMap.containsKey(queue)) - { - throw new QueueDoesntExistException("queue " + queue + " dos not exist"); - } - - m.dequeue(queue); - _queueMap.get(queue).remove(m); - if (!m.isEnqueued()) - { - // we can delete this message - _stagedMessages.remove(m); - } - } - } - - public Collection<StorableQueue> getAllQueues() throws InternalErrorException - { - return _queueMap.keySet(); - } - - public Collection<StorableMessage> getAllMessages(StorableQueue queue) throws InternalErrorException - { - return _queueMap.get(queue); - } - - public long getNewMessageId() - { - return _messageID++; - } - - - public ContentHeaderBody getContentHeaderBody(StorableMessage m) - throws - InternalErrorException, - MessageDoesntExistException - { - // do nothing this is only used during recovery - return null; - } - - public MessagePublishInfo getMessagePublishInfo(StorableMessage m) - throws - InternalErrorException, - MessageDoesntExistException - { - // do nothing this is only used during recovery - return null; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/messageStore/MessageStore.java b/java/broker/src/main/java/org/apache/qpid/server/messageStore/MessageStore.java deleted file mode 100644 index f5dc160fc6..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/messageStore/MessageStore.java +++ /dev/null @@ -1,308 +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.messageStore; - -import org.apache.commons.configuration.Configuration; -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.abstraction.MessagePublishInfo; -import org.apache.qpid.server.exception.InternalErrorException; -import org.apache.qpid.server.exception.InvalidXidException; -import org.apache.qpid.server.exception.MessageAlreadyStagedException; -import org.apache.qpid.server.exception.MessageDoesntExistException; -import org.apache.qpid.server.exception.QueueAlreadyExistsException; -import org.apache.qpid.server.exception.QueueDoesntExistException; -import org.apache.qpid.server.exception.UnknownXidException; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.store.StoreContext; -import org.apache.qpid.server.txn.TransactionManager; -import org.apache.qpid.server.virtualhost.VirtualHost; - -import javax.transaction.xa.Xid; -import java.util.Collection; - -/** - * Created by Arnaud Simon - * Date: 29-Mar-2007 - * Time: 17:34:02 - */ -public interface MessageStore -{ - /** - * Create a new exchange - * - * @param exchange the exchange to be persisted - * @throws InternalErrorException If an error occurs - */ - public void createExchange(Exchange exchange) - throws - InternalErrorException; - - /** - * Remove an exchange - * - * @param exchange The exchange to be removed - * @throws InternalErrorException If an error occurs - */ - public void removeExchange(Exchange exchange) - throws - InternalErrorException; - - /** - * Bind a queue with an exchange given a routing key - * - * @param exchange The exchange to bind the queue with - * @param routingKey The routing key - * @param queue The queue to be bound - * @param args Args - * @throws InternalErrorException If an error occurs - */ - public void bindQueue(Exchange exchange, - AMQShortString routingKey, - StorableQueue queue, FieldTable args) - throws - InternalErrorException; - - /** - * Unbind a queue from an exchange - * - * @param exchange The exchange the queue was bound to - * @param routingKey The routing queue - * @param queue The queue to unbind - * @param args args - * @throws InternalErrorException If an error occurs - */ - public void unbindQueue(Exchange exchange, - AMQShortString routingKey, - StorableQueue queue, FieldTable args) - throws - InternalErrorException; - - /** - * Called after instantiation in order to configure the message store. A particular implementation can define - * whatever parameters it wants. - * - * @param virtualHost The virtual host using by this store - * @param tm The transaction manager implementation - * @param base The base element identifier from which all configuration items are relative. For example, if the base - * element is "store", the all elements used by concrete classes will be "store.foo" etc. - * @param config The apache commons configuration object - * @throws InternalErrorException If an error occurs that means the store is unable to configure itself - * @throws IllegalArgumentException If the configuration arguments are illegal - */ - void configure(VirtualHost virtualHost, TransactionManager tm, String base, Configuration config) - throws - InternalErrorException, - IllegalArgumentException; - - /** - * Called to close and cleanup any resources used by the message store. - * - * @throws InternalErrorException if close fails - */ - void close() - throws - InternalErrorException; - - /** - * Create a queue - * - * @param queue the queue to be created - * @throws InternalErrorException In case of internal message store problem - * @throws QueueAlreadyExistsException If the queue already exists in the store - */ - public void createQueue(StorableQueue queue) - throws - InternalErrorException, - QueueAlreadyExistsException; - - /** - * Destroy a queue - * - * @param queue The queue to be destroyed - * @throws InternalErrorException In case of internal message store problem - * @throws QueueDoesntExistException If the queue does not exist in the store - */ - public void destroyQueue(StorableQueue queue) - throws - InternalErrorException, - QueueDoesntExistException; - - /** - * Stage the message before effective enqueue - * - * @param m The message to stage - * @throws InternalErrorException In case of internal message store problem - * @throws MessageAlreadyStagedException If the message is already staged - */ - public void stage(StorableMessage m) - throws - InternalErrorException, - MessageAlreadyStagedException; - - - /** - * Append more data with a previously staged message - * - * @param m The message to which data must be appended - * @param data Data to happen to the message - * @param offset The number of bytes from the beginning of the payload - * @param size The number of bytes to be written - * @throws InternalErrorException In case of internal message store problem - * @throws MessageDoesntExistException If the message has not been staged - */ - public void appendContent(StorableMessage m, byte[] data, int offset, int size) - throws - InternalErrorException, - MessageDoesntExistException; - - /** - * Get the content of previously staged or enqueued message. - * The message headers are also set. - * - * @param m The message for which the content must be loaded - * @param offset The number of bytes from the beginning of the payload - * @param size The number of bytes to be loaded - * @return The message content - * @throws InternalErrorException In case of internal message store problem - * @throws MessageDoesntExistException If the message does not exist - */ - public byte[] loadContent(StorableMessage m, int offset, int size) - throws - InternalErrorException, - MessageDoesntExistException; - - /** - * Get the content header of this message - * - * @param m The message - * @return The message content - * @throws InternalErrorException In case of internal message store problem - * @throws MessageDoesntExistException If the message does not exist - */ - public ContentHeaderBody getContentHeaderBody(StorableMessage m) - throws - InternalErrorException, - MessageDoesntExistException; - - /** - * Get the MessagePublishInfo of this message - * - * @param m The message - * @return The message content - * @throws InternalErrorException In case of internal message store problem - * @throws MessageDoesntExistException If the message does not exist - */ - public MessagePublishInfo getMessagePublishInfo(StorableMessage m) - throws - InternalErrorException, - MessageDoesntExistException; - - /** - * Destroy a previously staged message - * - * @param m the message to be destroyed - * @throws InternalErrorException In case of internal message store problem - * @throws MessageDoesntExistException If the message does not exist in the store - */ - public void destroy(StorableMessage m) - throws - InternalErrorException, - MessageDoesntExistException; - - /** - * Enqueue a message under the scope of the transaction branch - * identified by xid when specified. - * <p> This operation is propagated to the queue and the message. - * <p> A message that has been previously staged is assumed to have had - * its payload already added (see appendContent) - * - * @param xid The xid of the transaction branch under which the message must be enqueued. - * <p> It he xid is null then the message is enqueued outside the scope of any transaction. - * @param m The message to be enqueued - * @param queue The queue into which the message must be enqueued - * @throws InternalErrorException In case of internal message store problem - * @throws QueueDoesntExistException If the queue does not exist in the store - * @throws InvalidXidException The transaction branch is invalid - * @throws UnknownXidException The transaction branch is unknown - * @throws MessageDoesntExistException If the Message does not exist - */ - public void enqueue(Xid xid, StorableMessage m, StorableQueue queue) - throws - InternalErrorException, - QueueDoesntExistException, - InvalidXidException, - UnknownXidException, - MessageDoesntExistException; - - /** - * Dequeue a message under the scope of the transaction branch identified by xid - * if specified. - * <p> This operation is propagated to the queue and the message. - * - * @param xid The xid of the transaction branch under which the message must be dequeued. - * <p> It he xid is null then the message is dequeued outside the scope of any transaction. - * @param m The message to be dequeued - * @param queue The queue from which the message must be dequeued - * @throws InternalErrorException In case of internal message store problem - * @throws QueueDoesntExistException If the queue does not exist in the store - * @throws InvalidXidException The transaction branch is invalid - * @throws UnknownXidException The transaction branch is unknown - */ - public void dequeue(Xid xid, StorableMessage m, StorableQueue queue) - throws - InternalErrorException, - QueueDoesntExistException, - InvalidXidException, - UnknownXidException; - - //========================================================= - // Recovery specific methods - //========================================================= - - /** - * List all the persistent queues - * - * @return All the persistent queues - * @throws InternalErrorException In case of internal message store problem - */ - public Collection<StorableQueue> getAllQueues() - throws - InternalErrorException; - - /** - * All enqueued messages of a given queue - * - * @param queue The queue where the message are retrieved from - * @return The list all enqueued messages of a given queue - * @throws InternalErrorException In case of internal message store problem - */ - public Collection<StorableMessage> getAllMessages(StorableQueue queue) - throws - InternalErrorException; - - /** - * Get a new message ID - * - * @return A new message ID - */ - public long getNewMessageId(); -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/messageStore/Pool.java b/java/broker/src/main/java/org/apache/qpid/server/messageStore/Pool.java deleted file mode 100644 index 49af218b7a..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/messageStore/Pool.java +++ /dev/null @@ -1,135 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.messageStore; - -import java.util.ArrayList; - -/** - * Created by Arnaud Simon - * Date: 15-May-2007 - * Time: 10:11:49 - */ -public abstract class Pool -{ - // The maximum size of the pool. - private int _maxPoolSize = -1; - // The current size of the pool. - private int _currentPoolSize = 0; - // The pool objects. - private volatile ArrayList<Object> _poolObjects = new ArrayList<Object>(); - //The current number of created instances. - private int _instanceCount = 0; - - /** - * Create a pool of specified size. Negative or null pool sizes are - * disallowed. - * - * @param poolSize The size of the pool to create. Should be 1 or - * greater. - * @throws Exception If the pool size is less than 1. - */ - public Pool(int poolSize) throws Exception - { - if (poolSize <= 0) - { - throw new Exception("pool size is less than 1: " + poolSize); - } - _maxPoolSize = poolSize; - } - - /** - * Return the maximum size of this pool. - * - * @return The maximum size of this pool. - */ - public final int maxSize() - { - return _maxPoolSize; - } - - /** - * Return the current number of created instances. - * - * @return The current number of created instances in this pool. - */ - public final int numberOfInstances() - { - return _instanceCount; - } - - /** - * Extending classes MUST define how to create an instance of the object - * that they pool. - * - * @return An instance of the pooled object. - * @throws Exception In case of internal error. - */ - abstract protected Object createInstance() throws Exception; - - /** - * Remove the next available object from the pool or wait for one to become - * available. - * - * @return The next available instance. - * @throws Exception If the call is interrupted - */ - public final synchronized Object acquireInstance() throws Exception - { - while (_currentPoolSize == _maxPoolSize) - { - try - { - this.wait(); - } - catch (InterruptedException e) - { - throw new Exception("pool wait threw interrupted exception", e); - } - } - if (_poolObjects.size() == 0) - { - _poolObjects.add(createInstance()); - _instanceCount++; - } - _currentPoolSize++; - return _poolObjects.remove(0); - } - - /** - * Return an object back into this pool. - * - * @param object The returning object. - */ - public synchronized void releaseInstance(Object object) - { - _poolObjects.add(object); - _currentPoolSize--; - this.notify(); - } - - /** - * Return a dead object back into this pool. - * - */ - public synchronized void releaseDeadInstance() - { - _instanceCount--; - _currentPoolSize--; - this.notify(); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/messageStore/StorableMessage.java b/java/broker/src/main/java/org/apache/qpid/server/messageStore/StorableMessage.java deleted file mode 100644 index b228bb3027..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/messageStore/StorableMessage.java +++ /dev/null @@ -1,116 +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.messageStore;
-
-/**
- * A storable message can be persisted in the message store.
- *
- * Created by Arnaud Simon
- * Date: 03-Apr-2007
- * Time: 08:56:48
- */
-public interface StorableMessage
-{
- /**
- * The message ID is used by the store to identify a message.
- *
- * @return The message identifier
- */
- public long getMessageId();
-
- /**
- * Get the message header body that is saved when the message is staged.
- *
- * @return The message header body
- */
- public byte[] getHeaderBody();
-
- /**
- * Get the message header body size in bytes.
- *
- * @return The message header body size
- */
- public int getHeaderSize();
-
- /**
- * Get the message payload. This is required when the message is
- * enqueued without any prior staging.
- * <p> When the message is staged, the payload can be partial or even empty.
- *
- * @return The message payload
- */
- public byte[] getData();
-
- /**
- * Get the message payload size in bytes.
- *
- * @return The message payload size in bytes
- */
- public int getPayloadSize();
-
- /**
- * Specify whether this message has been enqueued
- *
- * @return true if this message is enqueued, false otherwise
- */
- public boolean isEnqueued();
-
- /**
- * This is called by the message store when this message is enqueued in the message store.
- *
- * @param queue The storable queue into which the message is enqueued
- */
- public void enqueue(StorableQueue queue);
-
- /**
- * This is called by the message store when this message is dequeued.
- *
- * @param queue The storable queue out of which the message is dequeued
- */
- public void dequeue(StorableQueue queue);
-
- /**
- * A message can be enqueued in several queues.
- * The queue position represents the index of the provided queue within the ordered
- * list of queues the message has been enqueued.
- * <p>For example:
- * <p> If the message is successively enqueued in queue Q1, Q2 and Q3 then
- * the position of Q1 is 0, position of Q2 is 1 and position of Q3 is 2.
- * <p> If the message is dequeud form Q2 then position of Q1 is stil 0 but position
- * of Q3 becomes 1.
- *
- * @param queue The storable queue for which the position should be determined
- *
- * @return The position of the specified storable queue
- */
- public int getQueuePosition(StorableQueue queue);
-
- /**
- * Indicates whether this message has been staged.
- *
- * @return True if the message has been staged, false otherwise
- */
- public boolean isStaged();
-
- /**
- * Call by the message store when this message is staged.
- */
- public void staged();
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/messageStore/StorableQueue.java b/java/broker/src/main/java/org/apache/qpid/server/messageStore/StorableQueue.java deleted file mode 100644 index 10a9a3b8b8..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/messageStore/StorableQueue.java +++ /dev/null @@ -1,75 +0,0 @@ -/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.qpid.server.messageStore;
-
-import org.apache.qpid.framing.AMQShortString;
-
-/**
- * A storable queue can store storable messages and can be persisted in the store.
- * Created by Arnaud Simon
- * Date: 03-Apr-2007
- * Time: 08:52:18
- */
-public interface StorableQueue
-{
- /**
- * Get This queue unique id.
- *
- * @return The queue ID
- */
- public int getQueueID();
-
- /**
- * Set the queue ID.
- *
- * @param id This queue ID
- */
- public void setQueueID(int id);
-
- /**
- * Get this queue owner.
- *
- * @return This queue owner
- */
- public AMQShortString getOwner();
-
- /**
- * Get this queue name.
- *
- * @return the name of this queue
- */
- public AMQShortString getName();
-
- /**
- * Signifies to this queue that a message is dequeued.
- * This operation is called by the store.
- *
- * @param m The dequeued message
- */
- public void dequeue(StorableMessage m);
-
- /**
- * Signifies to this queue that a message is enqueued.
- * This operation is called by the store.
- *
- * @param m The enqueued message
- */
- public void enqueue(StorableMessage m);
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverter.java b/java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverter.java deleted file mode 100644 index e01c5aabbf..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverter.java +++ /dev/null @@ -1,57 +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 auto-generated by Qpid Gentools v.0.1 - do not modify.
- * Supported AMQP versions:
- * 8-0
- */
-package org.apache.qpid.server.output;
-
-import org.apache.qpid.server.queue.AMQMessage;
-import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.framing.AMQShortString;
-import org.apache.qpid.framing.AMQDataBlock;
-import org.apache.qpid.AMQException;
-
-public interface ProtocolOutputConverter
-{
- void confirmConsumerAutoClose(int channelId, AMQShortString consumerTag);
-
- interface Factory
- {
- ProtocolOutputConverter newInstance(AMQProtocolSession session);
- }
-
- void writeDeliver(AMQMessage message, int channelId, long deliveryTag, AMQShortString consumerTag)
- throws AMQException;
-
- void writeGetOk(AMQMessage message, int channelId, long deliveryTag, int queueSize) throws AMQException;
-
- byte getProtocolMinorVersion();
-
- byte getProtocolMajorVersion();
-
- void writeReturn(AMQMessage message, int channelId, int replyCode, AMQShortString replyText)
- throws AMQException;
-
- void writeFrame(AMQDataBlock block);
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverterRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverterRegistry.java deleted file mode 100644 index 8366c426dd..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverterRegistry.java +++ /dev/null @@ -1,62 +0,0 @@ -/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-/*
- * This file is auto-generated by Qpid Gentools v.0.1 - do not modify.
- * Supported AMQP versions:
- * 8-0
- */
-package org.apache.qpid.server.output;
-
-import org.apache.qpid.server.output.ProtocolOutputConverter.Factory;
-import org.apache.qpid.server.output.amqp0_8.ProtocolOutputConverterImpl;
-import org.apache.qpid.server.protocol.AMQProtocolSession;
-
-import java.util.Map;
-import java.util.HashMap;
-
-public class ProtocolOutputConverterRegistry
-{
-
- private static final Map<Byte, Map<Byte, Factory>> _registry =
- new HashMap<Byte, Map<Byte, Factory>>();
-
-
- static
- {
- register((byte) 8, (byte) 0, ProtocolOutputConverterImpl.getInstanceFactory());
- }
-
- private static void register(byte major, byte minor, Factory converter)
- {
- if(!_registry.containsKey(major))
- {
- _registry.put(major, new HashMap<Byte, Factory>());
- }
- _registry.get(major).put(minor, converter);
- }
-
-
- public static ProtocolOutputConverter getConverter(AMQProtocolSession session)
- {
- return _registry.get(session.getProtocolMajorVersion()).get(session.getProtocolMinorVersion()).newInstance(session);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_8/ProtocolOutputConverterImpl.java b/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_8/ProtocolOutputConverterImpl.java deleted file mode 100644 index 8462ed9557..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_8/ProtocolOutputConverterImpl.java +++ /dev/null @@ -1,282 +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 auto-generated by Qpid Gentools v.0.1 - do not modify.
- * Supported AMQP versions:
- * 8-0
- */
-package org.apache.qpid.server.output.amqp0_8;
-
-import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.AMQMessage;
-import org.apache.qpid.server.queue.AMQMessageHandle;
-import org.apache.qpid.server.store.StoreContext;
-import org.apache.qpid.server.output.ProtocolOutputConverter;
-import org.apache.qpid.framing.*;
-import org.apache.qpid.framing.abstraction.ContentChunk;
-import org.apache.qpid.framing.abstraction.MessagePublishInfo;
-import org.apache.qpid.AMQException;
-
-import org.apache.mina.common.ByteBuffer;
-
-import java.util.Iterator;
-
-public class ProtocolOutputConverterImpl implements ProtocolOutputConverter
-{
-
- public static Factory getInstanceFactory()
- {
- return new Factory()
- {
-
- public ProtocolOutputConverter newInstance(AMQProtocolSession session)
- {
- return new ProtocolOutputConverterImpl(session);
- }
- };
- }
-
- private final AMQProtocolSession _protocolSession;
-
- private ProtocolOutputConverterImpl(AMQProtocolSession session)
- {
- _protocolSession = session;
- }
-
-
- public AMQProtocolSession getProtocolSession()
- {
- return _protocolSession;
- }
-
- public void writeDeliver(AMQMessage message, int channelId, long deliveryTag, AMQShortString consumerTag)
- throws AMQException
- {
- ByteBuffer deliver = createEncodedDeliverFrame(message, channelId, deliveryTag, consumerTag);
- AMQDataBlock contentHeader = ContentHeaderBody.createAMQFrame(channelId,
- message.getContentHeaderBody());
-
- final AMQMessageHandle messageHandle = message.getMessageHandle();
- final StoreContext storeContext = message.getStoreContext();
- final Long messageId = message.getMessageId();
-
- final int bodyCount = messageHandle.getBodyCount(storeContext,messageId);
-
- if(bodyCount == 0)
- {
- SmallCompositeAMQDataBlock compositeBlock = new SmallCompositeAMQDataBlock(deliver,
- contentHeader);
-
- writeFrame(compositeBlock);
- }
- else
- {
-
-
- //
- // Optimise the case where we have a single content body. In that case we create a composite block
- // so that we can writeDeliver out the deliver, header and body with a single network writeDeliver.
- //
- ContentChunk cb = messageHandle.getContentChunk(storeContext,messageId, 0);
-
- AMQDataBlock firstContentBody = new AMQFrame(channelId, getProtocolSession().getRegistry().getProtocolVersionMethodConverter().convertToBody(cb));
- AMQDataBlock[] headerAndFirstContent = new AMQDataBlock[]{contentHeader, firstContentBody};
- CompositeAMQDataBlock compositeBlock = new CompositeAMQDataBlock(deliver, headerAndFirstContent);
- writeFrame(compositeBlock);
-
- //
- // Now start writing out the other content bodies
- //
- for(int i = 1; i < bodyCount; i++)
- {
- cb = messageHandle.getContentChunk(storeContext,messageId, i);
- writeFrame(new AMQFrame(channelId, getProtocolSession().getRegistry().getProtocolVersionMethodConverter().convertToBody(cb)));
- }
-
-
- }
-
-
- }
-
-
- public void writeGetOk(AMQMessage message, int channelId, long deliveryTag, int queueSize) throws AMQException
- {
-
- final AMQMessageHandle messageHandle = message.getMessageHandle();
- final StoreContext storeContext = message.getStoreContext();
- final long messageId = message.getMessageId();
-
- ByteBuffer deliver = createEncodedGetOkFrame(message, channelId, deliveryTag, queueSize);
-
-
- AMQDataBlock contentHeader = ContentHeaderBody.createAMQFrame(channelId,
- message.getContentHeaderBody());
-
- final int bodyCount = messageHandle.getBodyCount(storeContext,messageId);
- if(bodyCount == 0)
- {
- SmallCompositeAMQDataBlock compositeBlock = new SmallCompositeAMQDataBlock(deliver,
- contentHeader);
- writeFrame(compositeBlock);
- }
- else
- {
-
-
- //
- // Optimise the case where we have a single content body. In that case we create a composite block
- // so that we can writeDeliver out the deliver, header and body with a single network writeDeliver.
- //
- ContentChunk cb = messageHandle.getContentChunk(storeContext,messageId, 0);
-
- AMQDataBlock firstContentBody = new AMQFrame(channelId, getProtocolSession().getRegistry().getProtocolVersionMethodConverter().convertToBody(cb));
- AMQDataBlock[] headerAndFirstContent = new AMQDataBlock[]{contentHeader, firstContentBody};
- CompositeAMQDataBlock compositeBlock = new CompositeAMQDataBlock(deliver, headerAndFirstContent);
- writeFrame(compositeBlock);
-
- //
- // Now start writing out the other content bodies
- //
- for(int i = 1; i < bodyCount; i++)
- {
- cb = messageHandle.getContentChunk(storeContext, messageId, i);
- writeFrame(new AMQFrame(channelId, getProtocolSession().getRegistry().getProtocolVersionMethodConverter().convertToBody(cb)));
- }
-
-
- }
-
-
- }
-
-
- private ByteBuffer createEncodedDeliverFrame(AMQMessage message, int channelId, long deliveryTag, AMQShortString consumerTag)
- throws AMQException
- {
- final MessagePublishInfo pb = message.getMessagePublishInfo();
- final AMQMessageHandle messageHandle = message.getMessageHandle();
-
- AMQFrame deliverFrame = BasicDeliverBody.createAMQFrame(channelId, getProtocolMajorVersion(),
- getProtocolMinorVersion(),
- consumerTag,
- deliveryTag, pb.getExchange(), messageHandle.isRedelivered(),
- pb.getRoutingKey());
-
-
- return deliverFrame.toByteBuffer();
- }
-
- private ByteBuffer createEncodedGetOkFrame(AMQMessage message, int channelId, long deliveryTag, int queueSize)
- throws AMQException
- {
- final MessagePublishInfo pb = message.getMessagePublishInfo();
- final AMQMessageHandle messageHandle = message.getMessageHandle();
-
- AMQFrame getOkFrame = BasicGetOkBody.createAMQFrame(channelId,
- getProtocolMajorVersion(),
- getProtocolMinorVersion(),
- deliveryTag, pb.getExchange(),
- queueSize,
- messageHandle.isRedelivered(),
- pb.getRoutingKey());
-
- return getOkFrame.toByteBuffer();
- }
-
- public byte getProtocolMinorVersion()
- {
- return getProtocolSession().getProtocolMinorVersion();
- }
-
- public byte getProtocolMajorVersion()
- {
- return getProtocolSession().getProtocolMajorVersion();
- }
-
- private ByteBuffer createEncodedReturnFrame(AMQMessage message, int channelId, int replyCode, AMQShortString replyText) throws AMQException
- {
- AMQFrame returnFrame = BasicReturnBody.createAMQFrame(channelId,
- getProtocolMajorVersion(),
- getProtocolMinorVersion(),
- message.getMessagePublishInfo().getExchange(),
- replyCode, replyText,
- message.getMessagePublishInfo().getRoutingKey());
-
- return returnFrame.toByteBuffer();
- }
-
- public void writeReturn(AMQMessage message, int channelId, int replyCode, AMQShortString replyText)
- throws AMQException
- {
- ByteBuffer returnFrame = createEncodedReturnFrame(message, channelId, replyCode, replyText);
-
- AMQDataBlock contentHeader = ContentHeaderBody.createAMQFrame(channelId,
- message.getContentHeaderBody());
-
- Iterator<AMQDataBlock> bodyFrameIterator = message.getBodyFrameIterator(getProtocolSession(), channelId);
- //
- // Optimise the case where we have a single content body. In that case we create a composite block
- // so that we can writeDeliver out the deliver, header and body with a single network writeDeliver.
- //
- if (bodyFrameIterator.hasNext())
- {
- AMQDataBlock firstContentBody = bodyFrameIterator.next();
- AMQDataBlock[] headerAndFirstContent = new AMQDataBlock[]{contentHeader, firstContentBody};
- CompositeAMQDataBlock compositeBlock = new CompositeAMQDataBlock(returnFrame, headerAndFirstContent);
- writeFrame(compositeBlock);
- }
- else
- {
- CompositeAMQDataBlock compositeBlock = new CompositeAMQDataBlock(returnFrame,
- new AMQDataBlock[]{contentHeader});
-
- writeFrame(compositeBlock);
- }
-
- //
- // Now start writing out the other content bodies
- // TODO: MINA needs to be fixed so the the pending writes buffer is not unbounded
- //
- while (bodyFrameIterator.hasNext())
- {
- writeFrame(bodyFrameIterator.next());
- }
- }
-
-
- public void writeFrame(AMQDataBlock block)
- {
- getProtocolSession().writeFrame(block);
- }
-
-
- public void confirmConsumerAutoClose(int channelId, AMQShortString consumerTag)
- {
-
- writeFrame(BasicCancelOkBody.createAMQFrame(channelId,
- getProtocolMajorVersion(),
- getProtocolMinorVersion(),
- consumerTag // consumerTag
- ));
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQMinaProtocolSession.java b/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQMinaProtocolSession.java deleted file mode 100644 index c9f5e42286..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQMinaProtocolSession.java +++ /dev/null @@ -1,773 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol; - -import org.apache.log4j.Logger; - -import org.apache.mina.common.IdleStatus; -import org.apache.mina.common.IoServiceConfig; -import org.apache.mina.common.IoSession; -import org.apache.mina.transport.vmpipe.VmPipeAddress; - -import org.apache.qpid.AMQChannelException; -import org.apache.qpid.AMQConnectionException; -import org.apache.qpid.AMQException; -import org.apache.qpid.codec.AMQCodecFactory; -import org.apache.qpid.codec.AMQDecoder; -import org.apache.qpid.common.ClientProperties; -import org.apache.qpid.framing.*; -import org.apache.qpid.pool.ReadWriteThreadModel; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.protocol.AMQMethodListener; -import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.management.Managable; -import org.apache.qpid.server.management.ManagedObject; -import org.apache.qpid.server.output.ProtocolOutputConverter; -import org.apache.qpid.server.output.ProtocolOutputConverterRegistry; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.state.AMQState; -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.virtualhost.VirtualHostRegistry; - -import javax.management.JMException; -import javax.security.sasl.SaslServer; - -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.security.Principal; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.CopyOnWriteArraySet; - -public class AMQMinaProtocolSession implements AMQProtocolSession, Managable -{ - private static final Logger _logger = Logger.getLogger(AMQProtocolSession.class); - - private static final String CLIENT_PROPERTIES_INSTANCE = ClientProperties.instance.toString(); - - // to save boxing the channelId and looking up in a map... cache in an array the low numbered - // channels. This value must be of the form 2^x - 1. - private static final int CHANNEL_CACHE_SIZE = 0xff; - - private final IoSession _minaProtocolSession; - - private AMQShortString _contextKey; - - private AMQShortString _clientVersion = null; - - private VirtualHost _virtualHost; - - private final Map<Integer, AMQChannel> _channelMap = new HashMap<Integer, AMQChannel>(); - - private final AMQChannel[] _cachedChannels = new AMQChannel[CHANNEL_CACHE_SIZE + 1]; - - private final CopyOnWriteArraySet<AMQMethodListener> _frameListeners = new CopyOnWriteArraySet<AMQMethodListener>(); - - private final AMQStateManager _stateManager; - - private AMQCodecFactory _codecFactory; - - private AMQProtocolSessionMBean _managedObject; - - private SaslServer _saslServer; - - private Object _lastReceived; - - private Object _lastSent; - - private boolean _closed; - // maximum number of channels this session should have - private long _maxNoOfChannels = 1000; - - /* AMQP Version for this session */ - private ProtocolVersion _protocolVersion = ProtocolVersion.getLatestSupportedVersion(); - - private FieldTable _clientProperties; - private final List<Task> _taskList = new CopyOnWriteArrayList<Task>(); - private VersionSpecificRegistry _registry = MainRegistry.getVersionSpecificRegistry(_protocolVersion); - private List<Integer> _closingChannelsList = new ArrayList<Integer>(); - private ProtocolOutputConverter _protocolOutputConverter; - private Principal _authorizedID; - - public ManagedObject getManagedObject() - { - return _managedObject; - } - - public AMQMinaProtocolSession(IoSession session, VirtualHostRegistry virtualHostRegistry, AMQCodecFactory codecFactory) - throws AMQException - { - _stateManager = new AMQStateManager(virtualHostRegistry, this); - _minaProtocolSession = session; - session.setAttachment(this); - - _codecFactory = codecFactory; - - try - { - IoServiceConfig config = session.getServiceConfig(); - ReadWriteThreadModel threadModel = (ReadWriteThreadModel) config.getThreadModel(); - threadModel.getAsynchronousReadFilter().createNewJobForSession(session); - threadModel.getAsynchronousWriteFilter().createNewJobForSession(session); - } - catch (RuntimeException e) - { - e.printStackTrace(); - // throw e; - - } - - // this(session, queueRegistry, exchangeRegistry, codecFactory, new AMQStateManager()); - } - - public AMQMinaProtocolSession(IoSession session, VirtualHostRegistry virtualHostRegistry, AMQCodecFactory codecFactory, - AMQStateManager stateManager) throws AMQException - { - _stateManager = stateManager; - _minaProtocolSession = session; - session.setAttachment(this); - - _codecFactory = codecFactory; - - } - - private AMQProtocolSessionMBean createMBean() throws AMQException - { - try - { - return new AMQProtocolSessionMBean(this); - } - catch (JMException ex) - { - _logger.error("AMQProtocolSession MBean creation has failed ", ex); - throw new AMQException(null, "AMQProtocolSession MBean creation has failed ", ex); - } - } - - public IoSession getIOSession() - { - return _minaProtocolSession; - } - - public static AMQProtocolSession getAMQProtocolSession(IoSession minaProtocolSession) - { - return (AMQProtocolSession) minaProtocolSession.getAttachment(); - } - - public void dataBlockReceived(AMQDataBlock message) throws Exception - { - _lastReceived = message; - if (message instanceof ProtocolInitiation) - { - protocolInitiationReceived((ProtocolInitiation) message); - - } - else if (message instanceof AMQFrame) - { - AMQFrame frame = (AMQFrame) message; - frameReceived(frame); - - } - else - { - throw new UnknnownMessageTypeException(message, null); - } - } - - private void frameReceived(AMQFrame frame) throws AMQException - { - int channelId = frame.getChannel(); - AMQBody body = frame.getBodyFrame(); - - if (_logger.isDebugEnabled()) - { - _logger.debug("Frame Received: " + frame); - } - - if (body instanceof AMQMethodBody) - { - methodFrameReceived(channelId, (AMQMethodBody) body); - } - else if (body instanceof ContentHeaderBody) - { - contentHeaderReceived(channelId, (ContentHeaderBody) body); - } - else if (body instanceof ContentBody) - { - contentBodyReceived(channelId, (ContentBody) body); - } - else if (body instanceof HeartbeatBody) - { - // NO OP - } - else - { - _logger.warn("Unrecognised frame " + frame.getClass().getName()); - } - } - - private void protocolInitiationReceived(ProtocolInitiation pi) - { - // this ensures the codec never checks for a PI message again - ((AMQDecoder) _codecFactory.getDecoder()).setExpectProtocolInitiation(false); - try - { - pi.checkVersion(); // Fails if not correct - - // This sets the protocol version (and hence framing classes) for this session. - setProtocolVersion(pi._protocolMajor, pi._protocolMinor); - - String mechanisms = ApplicationRegistry.getInstance().getAuthenticationManager().getMechanisms(); - - String locales = "en_US"; - - // Interfacing with generated code - be aware of possible changes to parameter order as versions change. - AMQFrame response = - ConnectionStartBody.createAMQFrame((short) 0, getProtocolMajorVersion(), getProtocolMinorVersion(), // AMQP version (major, minor) - locales.getBytes(), // locales - mechanisms.getBytes(), // mechanisms - null, // serverProperties - (short) getProtocolMajorVersion(), // versionMajor - (short) getProtocolMinorVersion()); // versionMinor - _minaProtocolSession.write(response); - } - catch (AMQException e) - { - _logger.error("Received incorrect protocol initiation", e); - - _minaProtocolSession.write(new ProtocolInitiation(ProtocolVersion.getLatestSupportedVersion())); - - // TODO: Close connection (but how to wait until message is sent?) - // ritchiem 2006-12-04 will this not do? - // WriteFuture future = _minaProtocolSession.write(new ProtocolInitiation(pv[i][PROTOCOLgetProtocolMajorVersion()], pv[i][PROTOCOLgetProtocolMinorVersion()])); - // future.join(); - // close connection - - } - } - - private void methodFrameReceived(int channelId, AMQMethodBody methodBody) - { - - final AMQMethodEvent<AMQMethodBody> evt = new AMQMethodEvent<AMQMethodBody>(channelId, methodBody); - - // Check that this channel is not closing - if (channelAwaitingClosure(channelId)) - { - if ((evt.getMethod() instanceof ChannelCloseOkBody)) - { - if (_logger.isInfoEnabled()) - { - _logger.info("Channel[" + channelId + "] awaiting closure - processing close-ok"); - } - } - else - { - if (_logger.isInfoEnabled()) - { - _logger.info("Channel[" + channelId + "] awaiting closure ignoring"); - } - - return; - } - } - - try - { - try - { - - boolean wasAnyoneInterested = _stateManager.methodReceived(evt); - - if (!_frameListeners.isEmpty()) - { - for (AMQMethodListener listener : _frameListeners) - { - wasAnyoneInterested = listener.methodReceived(evt) || wasAnyoneInterested; - } - } - - if (!wasAnyoneInterested) - { - throw new AMQNoMethodHandlerException(evt, null); - } - } - catch (AMQChannelException e) - { - if (getChannel(channelId) != null) - { - if (_logger.isInfoEnabled()) - { - _logger.info("Closing channel due to: " + e.getMessage()); - } - - writeFrame(e.getCloseFrame(channelId)); - closeChannel(channelId); - } - else - { - if (_logger.isDebugEnabled()) - { - _logger.debug("ChannelException occured on non-existent channel:" + e.getMessage()); - } - - if (_logger.isInfoEnabled()) - { - _logger.info("Closing connection due to: " + e.getMessage()); - } - - closeSession(); - - AMQConnectionException ce = - evt.getMethod().getConnectionException(AMQConstant.CHANNEL_ERROR, - AMQConstant.CHANNEL_ERROR.getName().toString()); - - _stateManager.changeState(AMQState.CONNECTION_CLOSING); - writeFrame(ce.getCloseFrame(channelId)); - } - } - catch (AMQConnectionException e) - { - if (_logger.isInfoEnabled()) - { - _logger.info("Closing connection due to: " + e.getMessage()); - } - - closeSession(); - _stateManager.changeState(AMQState.CONNECTION_CLOSING); - writeFrame(e.getCloseFrame(channelId)); - } - } - catch (Exception e) - { - _stateManager.error(e); - for (AMQMethodListener listener : _frameListeners) - { - listener.error(e); - } - - _minaProtocolSession.close(); - } - } - - private void contentHeaderReceived(int channelId, ContentHeaderBody body) throws AMQException - { - - AMQChannel channel = getAndAssertChannel(channelId); - - channel.publishContentHeader(body, this); - - } - - private void contentBodyReceived(int channelId, ContentBody body) throws AMQException - { - AMQChannel channel = getAndAssertChannel(channelId); - - channel.publishContentBody(body, this); - } - - /** - * Convenience method that writes a frame to the protocol session. Equivalent to calling - * getProtocolSession().write(). - * - * @param frame the frame to write - */ - public void writeFrame(AMQDataBlock frame) - { - _lastSent = frame; - _minaProtocolSession.write(frame); - } - - public AMQShortString getContextKey() - { - return _contextKey; - } - - public void setContextKey(AMQShortString contextKey) - { - _contextKey = contextKey; - } - - public List<AMQChannel> getChannels() - { - return new ArrayList<AMQChannel>(_channelMap.values()); - } - - public AMQChannel getAndAssertChannel(int channelId) throws AMQException - { - AMQChannel channel = getChannel(channelId); - if (channel == null) - { - throw new AMQException(AMQConstant.NOT_FOUND, "Channel not found with id:" + channelId, null); - } - - return channel; - } - - public AMQChannel getChannel(int channelId) throws AMQException - { - final AMQChannel channel = - ((channelId & CHANNEL_CACHE_SIZE) == channelId) ? _cachedChannels[channelId] : _channelMap.get(channelId); - if ((channel == null) || channel.isClosing()) - { - return null; - } - else - { - return channel; - } - } - - public boolean channelAwaitingClosure(int channelId) - { - return _closingChannelsList.contains(channelId); - } - - public void addChannel(AMQChannel channel) throws AMQException - { - if (_closed) - { - throw new AMQException(null, "Session is closed", null); - } - - final int channelId = channel.getChannelId(); - - if (_closingChannelsList.contains(channelId)) - { - throw new AMQException(null, "Session is marked awaiting channel close", null); - } - - if (_channelMap.size() == _maxNoOfChannels) - { - String errorMessage = - toString() + ": maximum number of channels has been reached (" + _maxNoOfChannels - + "); can't create channel"; - _logger.error(errorMessage); - throw new AMQException(AMQConstant.NOT_ALLOWED, errorMessage, null); - } - else - { - _channelMap.put(channel.getChannelId(), channel); - } - - if (((channelId & CHANNEL_CACHE_SIZE) == channelId)) - { - _cachedChannels[channelId] = channel; - } - - checkForNotification(); - } - - private void checkForNotification() - { - int channelsCount = _channelMap.size(); - if (channelsCount >= _maxNoOfChannels) - { - _managedObject.notifyClients("Channel count (" + channelsCount + ") has reached the threshold value"); - } - } - - public Long getMaximumNumberOfChannels() - { - return _maxNoOfChannels; - } - - public void setMaximumNumberOfChannels(Long value) - { - _maxNoOfChannels = value; - } - - public void commitTransactions(AMQChannel channel) throws AMQException - { - if ((channel != null) && channel.isTransactional()) - { - channel.commit(); - } - } - - public void rollbackTransactions(AMQChannel channel) throws AMQException - { - if ((channel != null) && channel.isTransactional()) - { - channel.rollback(); - } - } - - /** - * Close a specific channel. This will remove any resources used by the channel, including: <ul><li>any queue - * subscriptions (this may in turn remove queues if they are auto delete</li> </ul> - * - * @param channelId id of the channel to close - * - * @throws AMQException if an error occurs closing the channel - * @throws IllegalArgumentException if the channel id is not valid - */ - public void closeChannel(int channelId) throws AMQException - { - final AMQChannel channel = getChannel(channelId); - if (channel == null) - { - throw new IllegalArgumentException("Unknown channel id"); - } - else - { - try - { - channel.close(this); - markChannelawaitingCloseOk(channelId); - } - finally - { - removeChannel(channelId); - } - } - } - - public void closeChannelOk(int channelId) - { - _closingChannelsList.remove(new Integer(channelId)); - } - - private void markChannelawaitingCloseOk(int channelId) - { - _closingChannelsList.add(channelId); - } - - /** - * In our current implementation this is used by the clustering code. - * - * @param channelId The channel to remove - */ - public void removeChannel(int channelId) - { - _channelMap.remove(channelId); - if ((channelId & CHANNEL_CACHE_SIZE) == channelId) - { - _cachedChannels[channelId] = null; - } - } - - /** - * Initialise heartbeats on the session. - * - * @param delay delay in seconds (not ms) - */ - public void initHeartbeats(int delay) - { - if (delay > 0) - { - _minaProtocolSession.setIdleTime(IdleStatus.WRITER_IDLE, delay); - _minaProtocolSession.setIdleTime(IdleStatus.READER_IDLE, HeartbeatConfig.getInstance().getTimeout(delay)); - } - } - - /** - * Closes all channels that were opened by this protocol session. This frees up all resources used by the channel. - * - * @throws AMQException if an error occurs while closing any channel - */ - private void closeAllChannels() throws AMQException - { - for (AMQChannel channel : _channelMap.values()) - { - channel.close(this); - } - - _channelMap.clear(); - for (int i = 0; i <= CHANNEL_CACHE_SIZE; i++) - { - _cachedChannels[i] = null; - } - } - - /** This must be called when the session is _closed in order to free up any resources managed by the session. */ - public void closeSession() throws AMQException - { - if (!_closed) - { - _closed = true; - closeAllChannels(); - if (_managedObject != null) - { - _managedObject.unregister(); - } - - for (Task task : _taskList) - { - task.doTask(this); - } - } - } - - public String toString() - { - return "AMQProtocolSession(" + _minaProtocolSession.getRemoteAddress() + ")"; - } - - public String dump() - { - return this + " last_sent=" + _lastSent + " last_received=" + _lastReceived; - } - - /** @return an object that can be used to identity */ - public Object getKey() - { - return _minaProtocolSession.getRemoteAddress(); - } - - /** - * Get the fully qualified domain name of the local address to which this session is bound. Since some servers may - * be bound to multiple addresses this could vary depending on the acceptor this session was created from. - * - * @return a String FQDN - */ - public String getLocalFQDN() - { - SocketAddress address = _minaProtocolSession.getLocalAddress(); - // we use the vmpipe address in some tests hence the need for this rather ugly test. The host - // information is used by SASL primary. - if (address instanceof InetSocketAddress) - { - return ((InetSocketAddress) address).getHostName(); - } - else if (address instanceof VmPipeAddress) - { - return "vmpipe:" + ((VmPipeAddress) address).getPort(); - } - else - { - throw new IllegalArgumentException("Unsupported socket address class: " + address); - } - } - - public SaslServer getSaslServer() - { - return _saslServer; - } - - public void setSaslServer(SaslServer saslServer) - { - _saslServer = saslServer; - } - - public FieldTable getClientProperties() - { - return _clientProperties; - } - - public void setClientProperties(FieldTable clientProperties) - { - _clientProperties = clientProperties; - if (_clientProperties != null) - { - if (_clientProperties.getString(CLIENT_PROPERTIES_INSTANCE) != null) - { - setContextKey(new AMQShortString(_clientProperties.getString(CLIENT_PROPERTIES_INSTANCE))); - } - - if (_clientProperties.getString(ClientProperties.version.toString()) != null) - { - _clientVersion = new AMQShortString(_clientProperties.getString(ClientProperties.version.toString())); - } - } - } - - private void setProtocolVersion(byte major, byte minor) - { - _protocolVersion = new ProtocolVersion(major, minor); - - _registry = MainRegistry.getVersionSpecificRegistry(_protocolVersion); - - _protocolOutputConverter = ProtocolOutputConverterRegistry.getConverter(this); - } - - public byte getProtocolMajorVersion() - { - return _protocolVersion.getMajorVersion(); - } - - public byte getProtocolMinorVersion() - { - return _protocolVersion.getMinorVersion(); - } - - public boolean isProtocolVersion(byte major, byte minor) - { - return (getProtocolMajorVersion() == major) && (getProtocolMinorVersion() == minor); - } - - public VersionSpecificRegistry getRegistry() - { - return _registry; - } - - public Object getClientIdentifier() - { - return _minaProtocolSession.getRemoteAddress(); - } - - public VirtualHost getVirtualHost() - { - return _virtualHost; - } - - public void setVirtualHost(VirtualHost virtualHost) throws AMQException - { - _virtualHost = virtualHost; - _managedObject = createMBean(); - _managedObject.register(); - } - - public void addSessionCloseTask(Task task) - { - _taskList.add(task); - } - - public void removeSessionCloseTask(Task task) - { - _taskList.remove(task); - } - - public ProtocolOutputConverter getProtocolOutputConverter() - { - return _protocolOutputConverter; - } - - public void setAuthorizedID(Principal authorizedID) - { - _authorizedID = authorizedID; - } - - public Principal getAuthorizedID() - { - return _authorizedID; - } - - public String getClientVersion() - { - return (_clientVersion == null) ? null : _clientVersion.toString(); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQNoMethodHandlerException.java b/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQNoMethodHandlerException.java deleted file mode 100644 index ee6e090e24..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQNoMethodHandlerException.java +++ /dev/null @@ -1,46 +0,0 @@ -/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.protocol;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQMethodBody;
-import org.apache.qpid.protocol.AMQMethodEvent;
-
-/**
- * AMQNoMethodHandlerException represents the case where no method handler exists to handle an AQMP method.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represents failure to handle an AMQP method.
- * </table>
- *
- * @todo Not an AMQP exception as no status code.
- *
- * @todo Missing method handler. Unlikely to ever happen, and if it does its a coding error. Consider replacing with a
- * Runtime.
- */
-public class AMQNoMethodHandlerException extends AMQException
-{
- public AMQNoMethodHandlerException(AMQMethodEvent<AMQMethodBody> evt, Throwable cause)
- {
- super(null, "AMQMethodEvent " + evt + " was not processed by any listener on Broker.", cause);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQPFastProtocolHandler.java b/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQPFastProtocolHandler.java deleted file mode 100644 index 0c80414a3e..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQPFastProtocolHandler.java +++ /dev/null @@ -1,243 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol; - -import java.io.IOException; -import java.net.InetSocketAddress; -import org.apache.log4j.Logger; -import org.apache.mina.common.ByteBuffer; -import org.apache.mina.common.IdleStatus; -import org.apache.mina.common.IoHandlerAdapter; -import org.apache.mina.common.IoSession; -import org.apache.mina.filter.SSLFilter; -import org.apache.mina.filter.codec.ProtocolCodecFilter; -import org.apache.mina.util.SessionUtil; -import org.apache.qpid.AMQException; -import org.apache.qpid.codec.AMQCodecFactory; -import org.apache.qpid.framing.AMQDataBlock; -import org.apache.qpid.framing.AMQProtocolHeaderException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.ConnectionCloseBody; -import org.apache.qpid.framing.HeartbeatBody; -import org.apache.qpid.framing.ProtocolInitiation; -import org.apache.qpid.framing.ProtocolVersion; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.registry.IApplicationRegistry; -import org.apache.qpid.server.transport.ConnectorConfiguration; -import org.apache.qpid.ssl.SSLContextFactory; - -import java.io.IOException; -import java.net.InetSocketAddress; - -/** - * The protocol handler handles "protocol events" for all connections. The state - * associated with an individual connection is accessed through the protocol session. - * - * We delegate all frame (message) processing to the AMQProtocolSession which wraps - * the state for the connection. - * - */ -public class AMQPFastProtocolHandler extends IoHandlerAdapter -{ - private static final Logger _logger = Logger.getLogger(AMQPFastProtocolHandler.class); - - private final IApplicationRegistry _applicationRegistry; - - public AMQPFastProtocolHandler(Integer applicationRegistryInstance) - { - this(ApplicationRegistry.getInstance(applicationRegistryInstance)); - } - - public AMQPFastProtocolHandler(IApplicationRegistry applicationRegistry) - { - _applicationRegistry = applicationRegistry; - _logger.debug("AMQPFastProtocolHandler created"); - } - - protected AMQPFastProtocolHandler(AMQPFastProtocolHandler handler) - { - this(handler._applicationRegistry); - } - - public void sessionCreated(IoSession protocolSession) throws Exception - { - SessionUtil.initialize(protocolSession); - final AMQCodecFactory codecFactory = new AMQCodecFactory(true); - - createSession(protocolSession, _applicationRegistry, codecFactory); - _logger.info("Protocol session created for:" + protocolSession.getRemoteAddress()); - - final ProtocolCodecFilter pcf = new ProtocolCodecFilter(codecFactory); - - ConnectorConfiguration connectorConfig = ApplicationRegistry.getInstance(). - getConfiguredObject(ConnectorConfiguration.class); - if (connectorConfig.enableExecutorPool) - { - if (connectorConfig.enableSSL && isSSLClient(connectorConfig, protocolSession)) - { - String keystorePath = connectorConfig.keystorePath; - String keystorePassword = connectorConfig.keystorePassword; - String certType = connectorConfig.certType; - SSLContextFactory sslContextFactory = new SSLContextFactory(keystorePath, keystorePassword, certType); - protocolSession.getFilterChain().addAfter("AsynchronousReadFilter", "sslFilter", - new SSLFilter(sslContextFactory.buildServerContext())); - } - - protocolSession.getFilterChain().addBefore("AsynchronousWriteFilter", "protocolFilter", pcf); - } - else - { - protocolSession.getFilterChain().addLast("protocolFilter", pcf); - if (connectorConfig.enableSSL && isSSLClient(connectorConfig, protocolSession)) - { - String keystorePath = connectorConfig.keystorePath; - String keystorePassword = connectorConfig.keystorePassword; - String certType = connectorConfig.certType; - SSLContextFactory sslContextFactory = new SSLContextFactory(keystorePath, keystorePassword, certType); - protocolSession.getFilterChain().addBefore("protocolFilter", "sslFilter", - new SSLFilter(sslContextFactory.buildServerContext())); - } - - } - } - - /** - * Separated into its own, protected, method to allow easier reuse - */ - protected void createSession(IoSession session, IApplicationRegistry applicationRegistry, AMQCodecFactory codec) throws AMQException - { - new AMQMinaProtocolSession(session, applicationRegistry.getVirtualHostRegistry(), codec); - } - - public void sessionOpened(IoSession protocolSession) throws Exception - { - _logger.info("Session opened for:" + protocolSession.getRemoteAddress()); - } - - public void sessionClosed(IoSession protocolSession) throws Exception - { - _logger.info("Protocol Session closed for:" + protocolSession.getRemoteAddress()); - final AMQProtocolSession amqProtocolSession = AMQMinaProtocolSession.getAMQProtocolSession(protocolSession); - //fixme -- this can be null - if (amqProtocolSession != null) - { - amqProtocolSession.closeSession(); - } - } - - public void sessionIdle(IoSession session, IdleStatus status) throws Exception - { - _logger.debug("Protocol Session [" + this + "] idle: " + status + " :for:" + session.getRemoteAddress()); - if (IdleStatus.WRITER_IDLE.equals(status)) - { - //write heartbeat frame: - session.write(HeartbeatBody.FRAME); - } - else if (IdleStatus.READER_IDLE.equals(status)) - { - //failover: - throw new IOException("Timed out while waiting for heartbeat from peer."); - } - - } - - public void exceptionCaught(IoSession protocolSession, Throwable throwable) throws Exception - { - AMQProtocolSession session = AMQMinaProtocolSession.getAMQProtocolSession(protocolSession); - if (throwable instanceof AMQProtocolHeaderException) - { - - protocolSession.write(new ProtocolInitiation(ProtocolVersion.getLatestSupportedVersion())); - - protocolSession.close(); - - _logger.error("Error in protocol initiation " + session + ":" + protocolSession.getRemoteAddress() + " :" + throwable.getMessage(), throwable); - } - else if (throwable instanceof IOException) - { - _logger.error("IOException caught in" + session + ", session closed implictly: " + throwable, throwable); - } - else - { - _logger.error("Exception caught in" + session + ", closing session explictly: " + throwable, throwable); - - // Be aware of possible changes to parameter order as versions change. - protocolSession.write(ConnectionCloseBody.createAMQFrame(0, - session.getProtocolMajorVersion(), - session.getProtocolMinorVersion(), // AMQP version (major, minor) - 0, // classId - 0, // methodId - 200, // replyCode - new AMQShortString(throwable.getMessage()) // replyText - )); - protocolSession.close(); - } - } - - /** - * Invoked when a message is received on a particular protocol session. Note that a - * protocol session is directly tied to a particular physical connection. - * @param protocolSession the protocol session that received the message - * @param message the message itself (i.e. a decoded frame) - * @throws Exception if the message cannot be processed - */ - public void messageReceived(IoSession protocolSession, Object message) throws Exception - { - final AMQProtocolSession amqProtocolSession = AMQMinaProtocolSession.getAMQProtocolSession(protocolSession); - - if (message instanceof AMQDataBlock) - { - amqProtocolSession.dataBlockReceived((AMQDataBlock) message); - - } - else if (message instanceof ByteBuffer) - { - throw new IllegalStateException("Handed undecoded ByteBuffer buf = " + message); - } - else - { - throw new IllegalStateException("Handed unhandled message. message.class = " + message.getClass() + " message = " - + message); - } - } - - /** - * Called after a message has been sent out on a particular protocol session - * @param protocolSession the protocol session (i.e. connection) on which this - * message was sent - * @param object the message (frame) that was encoded and sent - * @throws Exception if we want to indicate an error - */ - public void messageSent(IoSession protocolSession, Object object) throws Exception - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Message sent: " + object); - } - } - - protected boolean isSSLClient(ConnectorConfiguration connectionConfig, IoSession protocolSession) - { - InetSocketAddress addr = (InetSocketAddress) protocolSession.getLocalAddress(); - - return addr.getPort() == connectionConfig.sslPort; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQPProtocolProvider.java b/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQPProtocolProvider.java deleted file mode 100644 index 07c153bfe8..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQPProtocolProvider.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol; - -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.registry.IApplicationRegistry; - -/** - * The protocol provide's role is to encapsulate the initialisation of the protocol handler. - * - * The protocol handler (see AMQPFastProtocolHandler class) handles protocol events - * such as connection closing or a frame being received. It can either do this directly - * or pass off to the protocol session in the cases where state information is required to - * deal with the event. - * - */ -public class AMQPProtocolProvider -{ - /** - * Handler for protocol events - */ - private AMQPFastProtocolHandler _handler; - - public AMQPProtocolProvider() - { - IApplicationRegistry registry = ApplicationRegistry.getInstance(); - _handler = new AMQPFastProtocolHandler(registry); - } - - public AMQPFastProtocolHandler getHandler() - { - return _handler; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSession.java b/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSession.java deleted file mode 100644 index 390117acf6..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSession.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol; - -import javax.security.sasl.SaslServer; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQDataBlock; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.protocol.AMQVersionAwareProtocolSession; -import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.output.ProtocolOutputConverter; -import org.apache.qpid.server.virtualhost.VirtualHost; - -import java.security.Principal; - - -public interface AMQProtocolSession extends AMQVersionAwareProtocolSession -{ - - public static interface Task - { - public void doTask(AMQProtocolSession session) throws AMQException; - } - - /** - * Called when a protocol data block is received - * - * @param message the data block that has been received - * - * @throws Exception if processing the datablock fails - */ - void dataBlockReceived(AMQDataBlock message) throws Exception; - - /** - * Get the context key associated with this session. Context key is described in the AMQ protocol specification (RFC - * 6). - * - * @return the context key - */ - AMQShortString getContextKey(); - - /** - * Set the context key associated with this session. Context key is described in the AMQ protocol specification (RFC - * 6). - * - * @param contextKey the context key - */ - void setContextKey(AMQShortString contextKey); - - /** - * Get the channel for this session associated with the specified id. A channel id is unique per connection (i.e. - * per session). - * - * @param channelId the channel id which must be valid - * - * @return null if no channel exists, the channel otherwise - */ - AMQChannel getChannel(int channelId) throws AMQException; - - /** - * Associate a channel with this session. - * - * @param channel the channel to associate with this session. It is an error to associate the same channel with more - * than one session but this is not validated. - */ - void addChannel(AMQChannel channel) throws AMQException; - - /** - * Close a specific channel. This will remove any resources used by the channel, including: <ul><li>any queue - * subscriptions (this may in turn remove queues if they are auto delete</li> </ul> - * - * @param channelId id of the channel to close - * - * @throws org.apache.qpid.AMQException if an error occurs closing the channel - * @throws IllegalArgumentException if the channel id is not valid - */ - void closeChannel(int channelId) throws AMQException; - - /** - * Markes the specific channel as closed. This will release the lock for that channel id so a new channel can be - * created on that id. - * - * @param channelId id of the channel to close - */ - void closeChannelOk(int channelId); - - /** - * Check to see if this chanel is closing - * - * @param channelId id to check - * @return boolean with state of channel awaiting closure - */ - boolean channelAwaitingClosure(int channelId); - - /** - * Remove a channel from the session but do not close it. - * - * @param channelId - */ - void removeChannel(int channelId); - - /** - * Initialise heartbeats on the session. - * - * @param delay delay in seconds (not ms) - */ - void initHeartbeats(int delay); - - /** This must be called when the session is _closed in order to free up any resources managed by the session. */ - void closeSession() throws AMQException; - - /** @return a key that uniquely identifies this session */ - Object getKey(); - - /** - * Get the fully qualified domain name of the local address to which this session is bound. Since some servers may - * be bound to multiple addresses this could vary depending on the acceptor this session was created from. - * - * @return a String FQDN - */ - String getLocalFQDN(); - - /** @return the sasl server that can perform authentication for this session. */ - SaslServer getSaslServer(); - - /** - * Set the sasl server that is to perform authentication for this session. - * - * @param saslServer - */ - void setSaslServer(SaslServer saslServer); - - - FieldTable getClientProperties(); - - void setClientProperties(FieldTable clientProperties); - - Object getClientIdentifier(); - - VirtualHost getVirtualHost(); - - void setVirtualHost(VirtualHost virtualHost) throws AMQException; - - void addSessionCloseTask(Task task); - - void removeSessionCloseTask(Task task); - - public ProtocolOutputConverter getProtocolOutputConverter(); - - void setAuthorizedID(Principal authorizedID); - - /** @return a Principal that was used to authorized this session */ - Principal getAuthorizedID(); - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBean.java b/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBean.java deleted file mode 100644 index 66f928a70e..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBean.java +++ /dev/null @@ -1,305 +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. - * - */ -/* - * - * Copyright (c) 2006 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.apache.qpid.server.protocol; - -import java.security.Principal; -import java.util.Date; -import java.util.List; - -import javax.management.JMException; -import javax.management.MBeanException; -import javax.management.MBeanNotificationInfo; -import javax.management.NotCompliantMBeanException; -import javax.management.Notification; -import javax.management.monitor.MonitorNotification; -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.CompositeDataSupport; -import javax.management.openmbean.CompositeType; -import javax.management.openmbean.OpenDataException; -import javax.management.openmbean.OpenType; -import javax.management.openmbean.SimpleType; -import javax.management.openmbean.TabularData; -import javax.management.openmbean.TabularDataSupport; -import javax.management.openmbean.TabularType; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQFrame; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.ConnectionCloseBody; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.management.AMQManagedObject; -import org.apache.qpid.server.management.MBeanConstructor; -import org.apache.qpid.server.management.MBeanDescription; -import org.apache.qpid.server.management.ManagedObject; - -/** - * This MBean class implements the management interface. In order to make more attributes, operations and notifications - * available over JMX simply augment the ManagedConnection interface and add the appropriate implementation here. - */ -@MBeanDescription("Management Bean for an AMQ Broker Connection") -public class AMQProtocolSessionMBean extends AMQManagedObject implements ManagedConnection -{ - private AMQMinaProtocolSession _session = null; - private String _name = null; - - // openmbean data types for representing the channel attributes - private static final String[] _channelAtttibuteNames = - { "Channel Id", "Transactional", "Default Queue", "Unacknowledged Message Count" }; - private static final String[] _indexNames = { _channelAtttibuteNames[0] }; - private static final OpenType[] _channelAttributeTypes = - { SimpleType.INTEGER, SimpleType.BOOLEAN, SimpleType.STRING, SimpleType.INTEGER }; - private static CompositeType _channelType = null; // represents the data type for channel data - private static TabularType _channelsType = null; // Data type for list of channels type - private static final AMQShortString BROKER_MANAGEMENT_CONSOLE_HAS_CLOSED_THE_CONNECTION = - new AMQShortString("Broker Management Console has closed the connection."); - - @MBeanConstructor("Creates an MBean exposing an AMQ Broker Connection") - public AMQProtocolSessionMBean(AMQMinaProtocolSession session) throws NotCompliantMBeanException, OpenDataException - { - super(ManagedConnection.class, ManagedConnection.TYPE); - _session = session; - String remote = getRemoteAddress(); - remote = "anonymous".equals(remote) ? (remote + hashCode()) : remote; - _name = jmxEncode(new StringBuffer(remote), 0).toString(); - init(); - } - - static - { - try - { - init(); - } - catch (JMException ex) - { - // This is not expected to ever occur. - throw new RuntimeException("Got JMException in static initializer.", ex); - } - } - - /** - * initialises the openmbean data types - */ - private static void init() throws OpenDataException - { - _channelType = - new CompositeType("Channel", "Channel Details", _channelAtttibuteNames, _channelAtttibuteNames, - _channelAttributeTypes); - _channelsType = new TabularType("Channels", "Channels", _channelType, _indexNames); - } - - public String getClientId() - { - return (_session.getContextKey() == null) ? null : _session.getContextKey().toString(); - } - - public String getAuthorizedId() - { - return (_session.getAuthorizedID() != null ) ? _session.getAuthorizedID().getName() : null; - } - - public String getVersion() - { - return (_session.getClientVersion() == null) ? null : _session.getClientVersion().toString(); - } - - public Date getLastIoTime() - { - return new Date(_session.getIOSession().getLastIoTime()); - } - - public String getRemoteAddress() - { - return _session.getIOSession().getRemoteAddress().toString(); - } - - public ManagedObject getParentObject() - { - return _session.getVirtualHost().getManagedObject(); - } - - public Long getWrittenBytes() - { - return _session.getIOSession().getWrittenBytes(); - } - - public Long getReadBytes() - { - return _session.getIOSession().getReadBytes(); - } - - public Long getMaximumNumberOfChannels() - { - return _session.getMaximumNumberOfChannels(); - } - - public void setMaximumNumberOfChannels(Long value) - { - _session.setMaximumNumberOfChannels(value); - } - - public String getObjectInstanceName() - { - return _name; - } - - /** - * commits transactions for a transactional channel - * - * @param channelId - * @throws JMException if channel with given id doesn't exist or if commit fails - */ - public void commitTransactions(int channelId) throws JMException - { - try - { - AMQChannel channel = _session.getChannel(channelId); - if (channel == null) - { - throw new JMException("The channel (channel Id = " + channelId + ") does not exist"); - } - - _session.commitTransactions(channel); - } - catch (AMQException ex) - { - throw new MBeanException(ex, ex.toString()); - } - } - - /** - * rollsback the transactions for a transactional channel - * - * @param channelId - * @throws JMException if channel with given id doesn't exist or if rollback fails - */ - public void rollbackTransactions(int channelId) throws JMException - { - try - { - AMQChannel channel = _session.getChannel(channelId); - if (channel == null) - { - throw new JMException("The channel (channel Id = " + channelId + ") does not exist"); - } - - _session.rollbackTransactions(channel); - } - catch (AMQException ex) - { - throw new MBeanException(ex, ex.toString()); - } - } - - /** - * Creates the list of channels in tabular form from the _channelMap. - * - * @return list of channels in tabular form. - * @throws OpenDataException - */ - public TabularData channels() throws OpenDataException - { - TabularDataSupport channelsList = new TabularDataSupport(_channelsType); - List<AMQChannel> list = _session.getChannels(); - - for (AMQChannel channel : list) - { - Object[] itemValues = - { - channel.getChannelId(), channel.isTransactional(), - (channel.getDefaultQueue() != null) ? channel.getDefaultQueue().getName().asString() : null, - channel.getUnacknowledgedMessageMap().size() - }; - - CompositeData channelData = new CompositeDataSupport(_channelType, _channelAtttibuteNames, itemValues); - channelsList.put(channelData); - } - - return channelsList; - } - - /** - * closes the connection. The administrator can use this management operation to close connection to free up - * resources. - * @throws JMException - */ - public void closeConnection() throws JMException - { - // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0) - // TODO: Connect this to the session version obtained from ProtocolInitiation for this session. - // Be aware of possible changes to parameter order as versions change. - final AMQFrame response = - ConnectionCloseBody.createAMQFrame(0, _session.getProtocolMajorVersion(), _session.getProtocolMinorVersion(), // AMQP version (major, minor) - 0, // classId - 0, // methodId - AMQConstant.REPLY_SUCCESS.getCode(), // replyCode - BROKER_MANAGEMENT_CONSOLE_HAS_CLOSED_THE_CONNECTION // replyText - ); - _session.writeFrame(response); - - try - { - _session.closeSession(); - } - catch (AMQException ex) - { - throw new MBeanException(ex, ex.toString()); - } - } - - @Override - public MBeanNotificationInfo[] getNotificationInfo() - { - String[] notificationTypes = new String[] { MonitorNotification.THRESHOLD_VALUE_EXCEEDED }; - String name = MonitorNotification.class.getName(); - String description = "Channel count has reached threshold value"; - MBeanNotificationInfo info1 = new MBeanNotificationInfo(notificationTypes, name, description); - - return new MBeanNotificationInfo[] { info1 }; - } - - public void notifyClients(String notificationMsg) - { - Notification n = - new Notification(MonitorNotification.THRESHOLD_VALUE_EXCEEDED, this, ++_notificationSequenceNumber, - System.currentTimeMillis(), notificationMsg); - _broadcaster.sendNotification(n); - } - -} // End of MBean class diff --git a/java/broker/src/main/java/org/apache/qpid/server/protocol/ExchangeInitialiser.java b/java/broker/src/main/java/org/apache/qpid/server/protocol/ExchangeInitialiser.java deleted file mode 100644 index 29d55ce763..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/protocol/ExchangeInitialiser.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol; - -import org.apache.qpid.AMQException; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.exchange.ExchangeFactory; -import org.apache.qpid.server.exchange.ExchangeRegistry; - -public class ExchangeInitialiser -{ - public void initialise(ExchangeFactory factory, ExchangeRegistry registry) throws AMQException{ - define(registry, factory, ExchangeDefaults.DEFAULT_EXCHANGE_NAME, ExchangeDefaults.DIRECT_EXCHANGE_CLASS); - define(registry, factory, ExchangeDefaults.DIRECT_EXCHANGE_NAME, ExchangeDefaults.DIRECT_EXCHANGE_CLASS); - define(registry, factory, ExchangeDefaults.TOPIC_EXCHANGE_NAME, ExchangeDefaults.TOPIC_EXCHANGE_CLASS); - define(registry, factory, ExchangeDefaults.HEADERS_EXCHANGE_NAME, ExchangeDefaults.HEADERS_EXCHANGE_CLASS); - define(registry, factory, ExchangeDefaults.FANOUT_EXCHANGE_NAME, ExchangeDefaults.FANOUT_EXCHANGE_CLASS); - - registry.setDefaultExchange(registry.getExchange(ExchangeDefaults.DEFAULT_EXCHANGE_NAME)); - } - - private void define(ExchangeRegistry r, ExchangeFactory f, - AMQShortString name, AMQShortString type) throws AMQException - { - if(r.getExchange(name)== null) - { - r.registerExchange(f.createExchange(name, type, true, false, 0)); - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/protocol/HeartbeatConfig.java b/java/broker/src/main/java/org/apache/qpid/server/protocol/HeartbeatConfig.java deleted file mode 100644 index 310deaaf55..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/protocol/HeartbeatConfig.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol; - -import org.apache.qpid.configuration.Configured; -import org.apache.qpid.server.registry.ApplicationRegistry; - -public class HeartbeatConfig -{ - @Configured(path = "heartbeat.delay", defaultValue = "5") - public int delay = 5;//in secs - @Configured(path = "heartbeat.timeoutFactor", defaultValue = "2.0") - public double timeoutFactor = 2; - - public double getTimeoutFactor() - { - return timeoutFactor; - } - - public void setTimeoutFactor(double timeoutFactor) - { - this.timeoutFactor = timeoutFactor; - } - - public int getDelay() - { - return delay; - } - - public void setDelay(int delay) - { - this.delay = delay; - } - - int getTimeout(int writeDelay) - { - return (int) (timeoutFactor * writeDelay); - } - - public static HeartbeatConfig getInstance() - { - return ApplicationRegistry.getInstance().getConfiguredObject(HeartbeatConfig.class); - } - - public String toString() - { - return "HeartBeatConfig{delay = " + delay + " timeoutFactor = " + timeoutFactor + "}"; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/protocol/ManagedConnection.java b/java/broker/src/main/java/org/apache/qpid/server/protocol/ManagedConnection.java deleted file mode 100644 index e6e713ac6d..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/protocol/ManagedConnection.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.server.protocol; - -import java.io.IOException; -import java.util.Date; -import java.security.Principal; - -import javax.management.JMException; -import javax.management.MBeanOperationInfo; -import javax.management.openmbean.TabularData; - -import org.apache.qpid.server.management.MBeanAttribute; -import org.apache.qpid.server.management.MBeanOperation; -import org.apache.qpid.server.management.MBeanOperationParameter; - -/** - * The management interface exposed to allow management of Connections. - * @author Bhupendra Bhardwaj - * @version 0.1 - */ -public interface ManagedConnection -{ - static final String TYPE = "Connection"; - - @MBeanAttribute(name = "ClientId", description = "Client Id") - String getClientId(); - - @MBeanAttribute(name = "AuthorizedId", description = "User Name") - String getAuthorizedId(); - - @MBeanAttribute(name = "Version", description = "Client Version") - String getVersion(); - - /** - * Tells the remote address of this connection. - * @return remote address - */ - @MBeanAttribute(name="RemoteAddress", description=TYPE + " Address") - String getRemoteAddress(); - - /** - * Tells the last time, the IO operation was done. - * @return last IO time. - */ - @MBeanAttribute(name="LastIOTime", description="The last time, the IO operation was done") - Date getLastIoTime(); - - /** - * Tells the total number of bytes written till now. - * @return number of bytes written. - * - @MBeanAttribute(name="WrittenBytes", description="The total number of bytes written till now") - Long getWrittenBytes(); - */ - /** - * Tells the total number of bytes read till now. - * @return number of bytes read. - * - @MBeanAttribute(name="ReadBytes", description="The total number of bytes read till now") - Long getReadBytes(); - */ - - /** - * Threshold high value for no of channels. This is useful in setting notifications or - * taking required action is there are more channels being created. - * @return threshold limit for no of channels - */ - Long getMaximumNumberOfChannels(); - - /** - * Sets the threshold high value for number of channels for a connection - * @param value - */ - @MBeanAttribute(name="MaximumNumberOfChannels", description="The threshold high value for number of channels for this connection") - void setMaximumNumberOfChannels(Long value); - - //********** Operations *****************// - - /** - * channel details of all the channels opened for this connection. - * @return general channel details - * @throws IOException - * @throws JMException - */ - @MBeanOperation(name="channels", description="Channel details for this connection") - TabularData channels() throws IOException, JMException; - - /** - * Commits the transactions if the channel is transactional. - * @param channelId - * @throws JMException - */ - @MBeanOperation(name="commitTransaction", - description="Commits the transactions for given channel Id, if the channel is transactional", - impact= MBeanOperationInfo.ACTION) - void commitTransactions(@MBeanOperationParameter(name="channel Id", description="channel Id")int channelId) throws JMException; - - /** - * Rollsback the transactions if the channel is transactional. - * @param channelId - * @throws JMException - */ - @MBeanOperation(name="rollbackTransactions", - description="Rollsback the transactions for given channel Id, if the channel is transactional", - impact= MBeanOperationInfo.ACTION) - void rollbackTransactions(@MBeanOperationParameter(name="channel Id", description="channel Id")int channelId) throws JMException; - - /** - * Closes all the related channels and unregisters this connection from managed objects. - */ - @MBeanOperation(name="closeConnection", - description="Closes this connection and all related channels", - impact= MBeanOperationInfo.ACTION) - void closeConnection() throws Exception; -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/protocol/UnknnownMessageTypeException.java b/java/broker/src/main/java/org/apache/qpid/server/protocol/UnknnownMessageTypeException.java deleted file mode 100644 index d053884e69..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/protocol/UnknnownMessageTypeException.java +++ /dev/null @@ -1,46 +0,0 @@ -/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.protocol;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQDataBlock;
-
-/**
- * UnknnownMessageTypeException represents a failure when Mina passes an unexpected frame type.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represents failure to cast a frame to its expected type.
- * </table>
- *
- * @todo Not an AMQP exception as no status code.
- *
- * @todo Seems like this exception was created to handle an unsafe type cast that will never happen in practice. Would
- * be better just to leave that as a ClassCastException. However, check the framing layer catches this error
- * first.
- */
-public class UnknnownMessageTypeException extends AMQException
-{
- public UnknnownMessageTypeException(AMQDataBlock message, Throwable cause)
- {
- super(null, "Unknown message type: " + message.getClass().getName() + ": " + message, cause);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/AMQMessage.java b/java/broker/src/main/java/org/apache/qpid/server/queue/AMQMessage.java deleted file mode 100644 index 7fa028df29..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/AMQMessage.java +++ /dev/null @@ -1,1108 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.queue; - -import org.apache.log4j.Logger; -import org.apache.mina.common.ByteBuffer; -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQBody; -import org.apache.qpid.framing.AMQDataBlock; -import org.apache.qpid.framing.AMQFrame; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.abstraction.ContentChunk; -import org.apache.qpid.framing.abstraction.MessagePublishInfo; -import org.apache.qpid.framing.abstraction.ProtocolVersionMethodConverter; -import org.apache.qpid.server.messageStore.StorableMessage; -import org.apache.qpid.server.messageStore.StorableQueue; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.StoreContext; -import org.apache.qpid.server.txn.TransactionalContext; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * Combines the information that make up a deliverable message into a more manageable form. - */ -public class AMQMessage implements StorableMessage -{ - /** Used for debugging purposes. */ - private static final Logger _log = Logger.getLogger(AMQMessage.class); - - // The ordered list of queues into which this message is enqueued. - private List<StorableQueue> _queues = new LinkedList<StorableQueue>(); - // Indicates whether this message is staged - private boolean _isStaged = false; - - /** - * Used in clustering - */ - private Set<Object> _tokens; - - /** - * Only use in clustering - //todo: should ideally be removed? - */ - private AMQProtocolSession _publisher; - - private final Long _messageId; - - private final AtomicInteger _referenceCount = new AtomicInteger(1); - - private AMQMessageHandle _messageHandle; - - /** Holds the transactional context in which this message is being processed. */ - // TODO: ideally this should be able to go into the transient message date - check this! (RG) - private TransactionalContext _txnContext; - - /** - * Flag to indicate whether this message has been delivered to a consumer. Used in implementing return functionality - * for messages published with the 'immediate' flag. - */ - private boolean _deliveredToConsumer; - /** - * We need to keep track of whether the message was 'immediate' as in extreme circumstances, when the - * checkDelieveredToConsumer is called, the message may already have been received and acknowledged, and the body - * removed from the store. - */ - - /** Flag to indicate that this message requires 'immediate' delivery. */ - private boolean _immediate; - - // private Subscription _takenBySubcription; - // private AtomicBoolean _taken = new AtomicBoolean(false); - private TransientMessageData _transientMessageData = new TransientMessageData(); - - //todo: this should be part of a messageOnQueue object - private Set<Subscription> _rejectedBy = null; - - //todo: this should be part of a messageOnQueue object - private Map<AMQQueue, AtomicBoolean> _takenMap = new HashMap<AMQQueue, AtomicBoolean>(); - //todo: this should be part of a messageOnQueue object - private Map<AMQQueue, Subscription> _takenBySubcriptionMap = new HashMap<AMQQueue, Subscription>(); - - private final int hashcode = System.identityHashCode(this); - - //todo: this should be part of a messageOnQueue object - private long _expiration; - - public String debugIdentity() - { - return "(HC:" + hashcode + " ID:" + _messageId + " Ref:" + _referenceCount.get() + ")"; - } - - public void setExpiration() - { - long expiration = - ((BasicContentHeaderProperties) _transientMessageData.getContentHeaderBody().properties).getExpiration(); - long timestamp = - ((BasicContentHeaderProperties) _transientMessageData.getContentHeaderBody().properties).getTimestamp(); - - if (ApplicationRegistry.getInstance().getConfiguration().getBoolean("advanced.synced-clocks", false)) - { - _expiration = expiration; - } - else - { - // Update TTL to be in broker time. - if (expiration != 0L) - { - if (timestamp != 0L) - { - // todo perhaps use arrival time - long diff = (System.currentTimeMillis() - timestamp); - - if ((diff > 1000L) || (diff < 1000L)) - { - _expiration = expiration + diff; - } - } - } - } - - } - - /** - * Used to iterate through all the body frames associated with this message. Will not keep all the data in memory - * therefore is memory-efficient. - */ - private class BodyFrameIterator implements Iterator<AMQDataBlock> - { - private int _channel; - - private int _index = -1; - private AMQProtocolSession _protocolSession; - - private BodyFrameIterator(AMQProtocolSession protocolSession, int channel) - { - _channel = channel; - _protocolSession = protocolSession; - } - - public boolean hasNext() - { - try - { - return _index < (_messageHandle.getBodyCount(getStoreContext(), _messageId) - 1); - } - catch (AMQException e) - { - _log.error("Unable to get body count: " + e, e); - - return false; - } - } - - public AMQDataBlock next() - { - try - { - - AMQBody cb = - getProtocolVersionMethodConverter().convertToBody(_messageHandle.getContentChunk(getStoreContext(), - _messageId, ++_index)); - - return new AMQFrame(_channel, cb); - } - catch (AMQException e) - { - // have no choice but to throw a runtime exception - throw new RuntimeException("Error getting content body: " + e, e); - } - - } - - private ProtocolVersionMethodConverter getProtocolVersionMethodConverter() - { - return _protocolSession.getRegistry().getProtocolVersionMethodConverter(); - } - - public void remove() - { - throw new UnsupportedOperationException(); - } - } - - public StoreContext getStoreContext() - { - return _txnContext.getStoreContext(); - } - - private class BodyContentIterator implements Iterator<ContentChunk> - { - - private int _index = -1; - - public boolean hasNext() - { - try - { - return _index < (_messageHandle.getBodyCount(getStoreContext(), _messageId) - 1); - } - catch (AMQException e) - { - _log.error("Error getting body count: " + e, e); - - return false; - } - } - - public ContentChunk next() - { - try - { - return _messageHandle.getContentChunk(getStoreContext(), _messageId, ++_index); - } - catch (AMQException e) - { - throw new RuntimeException("Error getting content body: " + e, e); - } - } - - public void remove() - { - throw new UnsupportedOperationException(); - } - } - - public AMQMessage(Long messageId, MessagePublishInfo info, TransactionalContext txnContext) - { - _messageId = messageId; - _txnContext = txnContext; - _immediate = info.isImmediate(); - _transientMessageData.setMessagePublishInfo(info); - - } - - /** - * Used when recovering, i.e. when the message store is creating references to messages. In that case, the normal - * enqueue/routingComplete is not done since the recovery process is responsible for routing the messages to - * queues. - * - * @param messageId - * @param store - * @param factory - * - * @throws AMQException - */ - public AMQMessage(Long messageId, MessageStore store, MessageHandleFactory factory, TransactionalContext txnConext) - throws AMQException - { - _messageId = messageId; - _messageHandle = factory.createMessageHandle(store, this, true); - _txnContext = txnConext; - _transientMessageData = null; - } - - /** - * Used in testing only. This allows the passing of the content header immediately on construction. - * - * @param messageId - * @param info - * @param txnContext - * @param contentHeader - */ - public AMQMessage(Long messageId, MessagePublishInfo info, TransactionalContext txnContext, - ContentHeaderBody contentHeader) throws AMQException - { - this(messageId, info, txnContext); - setContentHeaderBody(contentHeader); - } - - /** - * Used in testing only. This allows the passing of the content header and some body fragments on construction. - * - * @param messageId - * @param info - * @param txnContext - * @param contentHeader - * @param destinationQueues - * @param contentBodies - * - * @throws AMQException - */ - public AMQMessage(Long messageId, MessagePublishInfo info, TransactionalContext txnContext, - ContentHeaderBody contentHeader, List<AMQQueue> destinationQueues, List<ContentChunk> contentBodies, - MessageStore messageStore, StoreContext storeContext, MessageHandleFactory messageHandleFactory) throws AMQException - { - this(messageId, info, txnContext, contentHeader); - _transientMessageData.setDestinationQueues(destinationQueues); - routingComplete(messageStore, storeContext, messageHandleFactory); - for (ContentChunk cb : contentBodies) - { - addContentBodyFrame(storeContext, cb); - } - } - - protected AMQMessage(AMQMessage msg) throws AMQException - { - _messageId = msg._messageId; - _messageHandle = msg._messageHandle; - _txnContext = msg._txnContext; - _deliveredToConsumer = msg._deliveredToConsumer; - _transientMessageData = msg._transientMessageData; - } - - // ======================================================================== - // Interface StorableMessage - // ======================================================================== - - public long getMessageId() - { - return _messageId; - } - - public byte[] getHeaderBody() - { - byte[] result = null; - ContentHeaderBody headerBody; - ByteBuffer bufferedResult; - try - { - headerBody = _messageHandle.getContentHeaderBody(_txnContext.getStoreContext(), _messageId); - result = new byte[headerBody.getSize()]; - bufferedResult = ByteBuffer.wrap(result); - headerBody.writePayload(bufferedResult); - } - catch (AMQException e) - { - _log.error("Error when getting message header", e); - } - - return result; - } - - public int getHeaderSize() - { - int result = 0; - try - { - result = _messageHandle.getContentHeaderBody(_txnContext.getStoreContext(), _messageId).getSize(); - } - catch (AMQException e) - { - _log.error("Error when getting message header size", e); - } - - return result; - } - - public byte[] getData() - { - return _messageHandle.getMessagePayload(); - } - - public int getPayloadSize() - { - return _messageHandle.getMessagePayload().length; - } - - public boolean isEnqueued() - { - return _queues.size() > 0; - } - - public void enqueue(StorableQueue queue) - { - _queues.add(queue); - if (_log.isDebugEnabled()) - { - _log.debug("enqueued"); - } - } - - public void dequeue(StorableQueue queue) - { - _queues.remove(queue); - if (_log.isDebugEnabled()) - { - _log.debug("dequeued"); - } - } - - public int getQueuePosition(StorableQueue queue) - { - if (_log.isDebugEnabled()) - { - _log.debug("The queue position is " + _queues.indexOf(queue)); - } - - return _queues.indexOf(queue); - } - - public boolean isStaged() - { - return _isStaged; - } - - public void staged() - { - _isStaged = true; - } - - public Iterator<AMQDataBlock> getBodyFrameIterator(AMQProtocolSession protocolSession, int channel) - { - return new BodyFrameIterator(protocolSession, channel); - } - - public Iterator<ContentChunk> getContentBodyIterator() - { - return new BodyContentIterator(); - } - - public ContentHeaderBody getContentHeaderBody() throws AMQException - { - if (_transientMessageData != null) - { - return _transientMessageData.getContentHeaderBody(); - } - else - { - return _messageHandle.getContentHeaderBody(getStoreContext(), _messageId); - } - } - - public void setContentHeaderBody(ContentHeaderBody contentHeaderBody) throws AMQException - { - _transientMessageData.setContentHeaderBody(contentHeaderBody); - } - - public void routingComplete(MessageStore store, StoreContext storeContext, MessageHandleFactory factory) - throws AMQException - { - final boolean persistent = isPersistent(); - _messageHandle = factory.createMessageHandle(store, this, persistent); - if (persistent) //DTX was removed - { - _txnContext.beginTranIfNecessary(); - } - - // enqueuing the messages ensure that if required the destinations are recorded to a - // persistent store - - //DTX was removed - for (AMQQueue q : _transientMessageData.getDestinationQueues()) - { - _messageHandle.enqueue(storeContext, _messageId, q); - } - - if (_transientMessageData.getContentHeaderBody().bodySize == 0) - { - deliver(storeContext); - } - } - - public boolean addContentBodyFrame(StoreContext storeContext, ContentChunk contentChunk) throws AMQException - { - _transientMessageData.addBodyLength(contentChunk.getSize()); - final boolean allContentReceived = isAllContentReceived(); - _messageHandle.addContentBodyFrame(storeContext, _messageId, contentChunk, allContentReceived); - if (allContentReceived) - { - deliver(storeContext); - - return true; - } - else - { - return false; - } - } - - public boolean isAllContentReceived() throws AMQException - { - return _transientMessageData.isAllContentReceived(); - } - - /** - * Creates a long-lived reference to this message, and increments the count of such references, as an atomic - * operation. - */ - public AMQMessage takeReference() - { - incrementReference(); // _referenceCount.incrementAndGet(); - - return this; - } - - - /** - * Threadsafe. Increment the reference count on the message. - */ - protected void incrementReference() - { - _referenceCount.incrementAndGet(); - // if (_log.isDebugEnabled()) - // { - // _log.debug("Ref count on message " + debugIdentity() + " incremented " + Arrays.asList(Thread.currentThread().getStackTrace()).subList(3, 6)); - // } - } - - /** - * Threadsafe. This will decrement the reference count and when it reaches zero will remove the message from the - * message store. - * - * @param storeContext - * - * @throws MessageCleanupException when an attempt was made to remove the message from the message store and that - * failed - */ - public void decrementReference(StoreContext storeContext) throws MessageCleanupException - { - int count = _referenceCount.decrementAndGet(); - - // note that the operation of decrementing the reference count and then removing the message does not - // have to be atomic since the ref count starts at 1 and the exchange itself decrements that after - // the message has been passed to all queues. i.e. we are - // not relying on the all the increments having taken place before the delivery manager decrements. - if (count == 0) - { - try - { - // if (_log.isDebugEnabled()) - // { - // _log.debug("Decremented ref count on message " + debugIdentity() + " is zero; removing message" + Arrays.asList(Thread.currentThread().getStackTrace()).subList(3, 6)); - // } - - // must check if the handle is null since there may be cases where we decide to throw away a message - // and the handle has not yet been constructed - if (_messageHandle != null) - { - _messageHandle.removeMessage(storeContext, _messageId); - } - } - catch (AMQException e) - { - // to maintain consistency, we revert the count - incrementReference(); - throw new MessageCleanupException("Failed to cleanup message with id " + _messageId, e); - } - } - else - { - if (count < 0) - { - throw new MessageCleanupException("Reference count for message id " + debugIdentity() + " has gone below 0.", - null); - } - } - } - - public void setPublisher(AMQProtocolSession publisher) - { - _publisher = publisher; - } - - public AMQProtocolSession getPublisher() - { - return _publisher; - } - - /** - * Called selectors to determin if the message has already been sent - * - * @return _deliveredToConsumer - */ - public boolean getDeliveredToConsumer() - { - return _deliveredToConsumer; - } - - public boolean isTaken(AMQQueue queue) - { - // return _taken.get(); - - synchronized (this) - { - AtomicBoolean taken = _takenMap.get(queue); - if (taken == null) - { - taken = new AtomicBoolean(false); - _takenMap.put(queue, taken); - } - - return taken.get(); - } - } - - public boolean taken(AMQQueue queue, Subscription sub) - { - // if (_taken.getAndSet(true)) - // { - // return true; - // } - // else - // { - // _takenBySubcription = sub; - // return false; - // } - - synchronized (this) - { - AtomicBoolean taken = _takenMap.get(queue); - if (taken == null) - { - taken = new AtomicBoolean(false); - } - - if (taken.getAndSet(true)) - { - return true; - } - else - { - _takenMap.put(queue, taken); - _takenBySubcriptionMap.put(queue, sub); - - return false; - } - } - } - - public void release(AMQQueue queue) - { - if (_log.isTraceEnabled()) - { - _log.trace("Releasing Message:" + debugIdentity()); - } - - // _taken.set(false); - // _takenBySubcription = null; - - synchronized (this) - { - AtomicBoolean taken = _takenMap.get(queue); - if (taken == null) - { - taken = new AtomicBoolean(false); - } - else - { - taken.set(false); - } - - _takenMap.put(queue, taken); - _takenBySubcriptionMap.put(queue, null); - } - } - - public boolean checkToken(Object token) - { - - if (_tokens == null) - { - _tokens = new HashSet<Object>(); - } - - if (_tokens.contains(token)) - { - return true; - } - else - { - _tokens.add(token); - - return false; - } - } - - /** - * Registers a queue to which this message is to be delivered. This is called from the exchange when it is routing - * the message. This will be called before any content bodies have been received so that the choice of - * AMQMessageHandle implementation can be picked based on various criteria. - * - * @param queue the queue - * - * @throws org.apache.qpid.AMQException if there is an error enqueuing the message - */ - public void enqueue(AMQQueue queue) throws AMQException - { - _transientMessageData.addDestinationQueue(queue); - } - - public void dequeue(StoreContext storeContext, AMQQueue queue) throws AMQException - { - _messageHandle.dequeue(storeContext, _messageId, queue); - } - - public boolean isPersistent() throws AMQException - { - if (_transientMessageData != null) - { - return _transientMessageData.isPersistent(); - } - else - { - return _messageHandle.isPersistent(getStoreContext(), _messageId); - } - } - - /** - * Called to enforce the 'immediate' flag. - * - * @throws NoConsumersException if the message is marked for immediate delivery but has not been marked as delivered - * to a consumer - */ - public void checkDeliveredToConsumer() throws NoConsumersException - { - - if (_immediate && !_deliveredToConsumer) - { - throw new NoConsumersException(this, null); - } - } - - public MessagePublishInfo getMessagePublishInfo() throws AMQException - { - MessagePublishInfo pb; - if (_transientMessageData != null) - { - pb = _transientMessageData.getMessagePublishInfo(); - } - else - { - pb = _messageHandle.getMessagePublishInfo(getStoreContext(), _messageId); - } - - return pb; - } - - public boolean isRedelivered() - { - return _messageHandle.isRedelivered(); - } - - public void setRedelivered(boolean redelivered) - { - _messageHandle.setRedelivered(redelivered); - } - - public long getArrivalTime() - { - return _messageHandle.getArrivalTime(); - } - - /** - * Checks to see if the message has expired. If it has the message is dequeued. - * - * @param queue The queue to check the expiration against. (Currently not used) - * - * @return true if the message has expire - * - * @throws AMQException - */ - public boolean expired(AMQQueue queue) throws AMQException - { - // note: If the storecontext isn't need then we can remove the getChannel() from Subscription. - - if (_expiration != 0L) - { - long now = System.currentTimeMillis(); - - return (now > _expiration); - } - - return false; - } - - /** Called when this message is delivered to a consumer. (used to implement the 'immediate' flag functionality). */ - public void setDeliveredToConsumer() - { - _deliveredToConsumer = true; - } - - private void deliver(StoreContext storeContext) throws AMQException - { - // we get a reference to the destination queues now so that we can clear the - // transient message data as quickly as possible - List<AMQQueue> destinationQueues = _transientMessageData.getDestinationQueues(); - if (_log.isDebugEnabled()) - { - _log.debug("Delivering message " + debugIdentity() + " to " + destinationQueues); - } - - try - { - // first we allow the handle to know that the message has been fully received. This is useful if it is - // maintaining any calculated values based on content chunks - _messageHandle.setPublishAndContentHeaderBody(storeContext, _messageId, - _transientMessageData.getMessagePublishInfo(), _transientMessageData.getContentHeaderBody()); - - // we then allow the transactional context to do something with the message content - // now that it has all been received, before we attempt delivery - _txnContext.messageFullyReceived(isPersistent()); - - _transientMessageData = null; - - for (AMQQueue q : destinationQueues) - { - // Increment the references to this message for each queue delivery. - incrementReference(); - // normal deliver so add this message at the end. - _txnContext.deliver(this, q, false); - } - } - finally - { - destinationQueues.clear(); - // Remove refence for routing process . Reference count should now == delivered queue count - decrementReference(storeContext); - } - } - - /* - public void writeDeliver(AMQProtocolSession protocolSession, int channelId, long deliveryTag, AMQShortString consumerTag) - throws AMQException - { - ByteBuffer deliver = createEncodedDeliverFrame(protocolSession, channelId, deliveryTag, consumerTag); - AMQDataBlock contentHeader = ContentHeaderBody.createAMQFrame(channelId, - getContentHeaderBody()); - - final int bodyCount = _messageHandle.getBodyCount(getStoreContext(), _messageId); - if (bodyCount == 0) - { - SmallCompositeAMQDataBlock compositeBlock = new SmallCompositeAMQDataBlock(deliver, - contentHeader); - - protocolSession.writeFrame(compositeBlock); - } - else - { - - // - // Optimise the case where we have a single content body. In that case we create a composite block - // so that we can writeDeliver out the deliver, header and body with a single network writeDeliver. - // - ContentChunk cb = _messageHandle.getContentChunk(getStoreContext(), _messageId, 0); - - AMQDataBlock firstContentBody = new AMQFrame(channelId, protocolSession.getRegistry().getProtocolVersionMethodConverter().convertToBody(cb)); - AMQDataBlock[] headerAndFirstContent = new AMQDataBlock[]{contentHeader, firstContentBody}; - CompositeAMQDataBlock compositeBlock = new CompositeAMQDataBlock(deliver, headerAndFirstContent); - protocolSession.writeFrame(compositeBlock); - - // - // Now start writing out the other content bodies - // - for (int i = 1; i < bodyCount; i++) - { - cb = _messageHandle.getContentChunk(getStoreContext(), _messageId, i); - protocolSession.writeFrame(new AMQFrame(channelId, protocolSession.getRegistry().getProtocolVersionMethodConverter().convertToBody(cb))); - } - - - } - - - } - - public void writeGetOk(AMQProtocolSession protocolSession, int channelId, long deliveryTag, int queueSize) throws AMQException - { - ByteBuffer deliver = createEncodedGetOkFrame(protocolSession, channelId, deliveryTag, queueSize); - AMQDataBlock contentHeader = ContentHeaderBody.createAMQFrame(channelId, - getContentHeaderBody()); - - final int bodyCount = _messageHandle.getBodyCount(getStoreContext(), _messageId); - if (bodyCount == 0) - { - SmallCompositeAMQDataBlock compositeBlock = new SmallCompositeAMQDataBlock(deliver, - contentHeader); - protocolSession.writeFrame(compositeBlock); - } - else - { - - // - // Optimise the case where we have a single content body. In that case we create a composite block - // so that we can writeDeliver out the deliver, header and body with a single network writeDeliver. - // - ContentChunk cb = _messageHandle.getContentChunk(getStoreContext(), _messageId, 0); - - AMQDataBlock firstContentBody = new AMQFrame(channelId, protocolSession.getRegistry().getProtocolVersionMethodConverter().convertToBody(cb)); - AMQDataBlock[] headerAndFirstContent = new AMQDataBlock[]{contentHeader, firstContentBody}; - CompositeAMQDataBlock compositeBlock = new CompositeAMQDataBlock(deliver, headerAndFirstContent); - protocolSession.writeFrame(compositeBlock); - - // - // Now start writing out the other content bodies - // - for (int i = 1; i < bodyCount; i++) - { - cb = _messageHandle.getContentChunk(getStoreContext(), _messageId, i); - protocolSession.writeFrame(new AMQFrame(channelId, protocolSession.getRegistry().getProtocolVersionMethodConverter().convertToBody(cb))); - } - - - } - - - } - - - private ByteBuffer createEncodedDeliverFrame(AMQProtocolSession protocolSession, int channelId, long deliveryTag, AMQShortString consumerTag) - throws AMQException - { - MessagePublishInfo pb = getMessagePublishInfo(); - AMQFrame deliverFrame = BasicDeliverBody.createAMQFrame(channelId, protocolSession.getProtocolMajorVersion(), (byte) 0, consumerTag, - deliveryTag, pb.getExchange(), _messageHandle.isRedelivered(), - pb.getRoutingKey()); - ByteBuffer buf = ByteBuffer.allocate((int) deliverFrame.getSize()); // XXX: Could cast be a problem? - deliverFrame.writePayload(buf); - buf.flip(); - return buf; - } - - private ByteBuffer createEncodedGetOkFrame(AMQProtocolSession protocolSession, int channelId, long deliveryTag, int queueSize) - throws AMQException - { - MessagePublishInfo pb = getMessagePublishInfo(); - AMQFrame getOkFrame = BasicGetOkBody.createAMQFrame(channelId, - protocolSession.getProtocolMajorVersion(), - protocolSession.getProtocolMinorVersion(), - deliveryTag, pb.getExchange(), - queueSize, - _messageHandle.isRedelivered(), - pb.getRoutingKey()); - ByteBuffer buf = ByteBuffer.allocate((int) getOkFrame.getSize()); // XXX: Could cast be a problem? - getOkFrame.writePayload(buf); - buf.flip(); - return buf; - } - - private ByteBuffer createEncodedReturnFrame(AMQProtocolSession protocolSession, int channelId, int replyCode, AMQShortString replyText) throws AMQException - { - AMQFrame returnFrame = BasicReturnBody.createAMQFrame(channelId, - protocolSession.getProtocolMajorVersion(), - protocolSession.getProtocolMinorVersion(), - getMessagePublishInfo().getExchange(), - replyCode, replyText, - getMessagePublishInfo().getRoutingKey()); - ByteBuffer buf = ByteBuffer.allocate((int) returnFrame.getSize()); // XXX: Could cast be a problem? - returnFrame.writePayload(buf); - buf.flip(); - return buf; - } - - public void writeReturn(AMQProtocolSession protocolSession, int channelId, int replyCode, AMQShortString replyText) - throws AMQException - { - ByteBuffer returnFrame = createEncodedReturnFrame(protocolSession, channelId, replyCode, replyText); - - AMQDataBlock contentHeader = ContentHeaderBody.createAMQFrame(channelId, - getContentHeaderBody()); - - Iterator<AMQDataBlock> bodyFrameIterator = getBodyFrameIterator(protocolSession, channelId); - // - // Optimise the case where we have a single content body. In that case we create a composite block - // so that we can writeDeliver out the deliver, header and body with a single network writeDeliver. - // - if (bodyFrameIterator.hasNext()) - { - AMQDataBlock firstContentBody = bodyFrameIterator.next(); - AMQDataBlock[] headerAndFirstContent = new AMQDataBlock[]{contentHeader, firstContentBody}; - CompositeAMQDataBlock compositeBlock = new CompositeAMQDataBlock(returnFrame, headerAndFirstContent); - protocolSession.writeFrame(compositeBlock); - } - else - { - CompositeAMQDataBlock compositeBlock = new CompositeAMQDataBlock(returnFrame, - new AMQDataBlock[]{contentHeader}); - protocolSession.writeFrame(compositeBlock); - } - - // - // Now start writing out the other content bodies - // TODO: MINA needs to be fixed so the the pending writes buffer is not unbounded - // - while (bodyFrameIterator.hasNext()) - { - protocolSession.writeFrame(bodyFrameIterator.next()); - } - } - */ - - public AMQMessageHandle getMessageHandle() - { - return _messageHandle; - } - - public long getSize() - { - try - { - long size = getContentHeaderBody().bodySize; - - return size; - } - catch (AMQException e) - { - _log.error(e.toString(), e); - - return 0; - } - - } - - public void restoreTransientMessageData() throws AMQException - { - TransientMessageData transientMessageData = new TransientMessageData(); - transientMessageData.setMessagePublishInfo(getMessagePublishInfo()); - transientMessageData.setContentHeaderBody(getContentHeaderBody()); - transientMessageData.addBodyLength(getContentHeaderBody().getSize()); - _transientMessageData = transientMessageData; - } - - public void clearTransientMessageData() - { - _transientMessageData = null; - } - - public String toString() - { - // return "Message[" + debugIdentity() + "]: " + _messageId + "; ref count: " + _referenceCount + "; taken : " + - // _taken + " by :" + _takenBySubcription; - - return "Message[" + debugIdentity() + "]: " + _messageId + "; ref count: " + _referenceCount + "; taken for queues: " - + _takenMap.toString() + " by Subs:" + _takenBySubcriptionMap.toString(); - } - - public Subscription getDeliveredSubscription(AMQQueue queue) - { - // return _takenBySubcription; - synchronized (this) - { - return _takenBySubcriptionMap.get(queue); - } - } - - public void reject(Subscription subscription) - { - - if (subscription != null) - { - if (_rejectedBy == null) - { - _rejectedBy = new HashSet<Subscription>(); - } - - _rejectedBy.add(subscription); - } - else - { - _log.warn("Requesting rejection by null subscriber:" + debugIdentity()); - } - } - - public boolean isRejectedBy(Subscription subscription) - { - boolean rejected = _rejectedBy != null; - - if (rejected) // We have subscriptions that rejected this message - { - return _rejectedBy.contains(subscription); - } - else // This messasge hasn't been rejected yet. - { - return rejected; - } - } - - public String getBodyAsString() - { - StringBuilder b = new StringBuilder(); - for (Iterator<ContentChunk> it = getContentBodyIterator(); it.hasNext(); ) - { - ByteBuffer buf = it.next().getData(); - byte[] bytes = new byte[buf.remaining()]; - buf.duplicate().get(bytes); - b.append(new String(bytes)); - } - return b.toString(); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/AMQMessageHandle.java b/java/broker/src/main/java/org/apache/qpid/server/queue/AMQMessageHandle.java deleted file mode 100644 index 296e61bfa9..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/AMQMessageHandle.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.queue; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.server.store.StoreContext; -import org.apache.qpid.framing.abstraction.ContentChunk; -import org.apache.qpid.framing.abstraction.MessagePublishInfo; - -/** - * A pluggable way of getting message data. Implementations can provide intelligent caching for example or - * even no caching at all to minimise the broker memory footprint. - * - * The method all take a messageId to avoid having to store it in the instance - the AMQMessage container - * must already keen the messageId so it is pointless storing it twice. - */ -public interface AMQMessageHandle -{ - ContentHeaderBody getContentHeaderBody(StoreContext context, Long messageId) throws AMQException; - - /** - * @return the number of body frames associated with this message - */ - int getBodyCount(StoreContext context, Long messageId) throws AMQException; - - /** - * @return the size of the body - */ - long getBodySize(StoreContext context, Long messageId) throws AMQException; - - /** - * Get a particular content body - * @param index the index of the body to retrieve, must be between 0 and getBodyCount() - 1 - * @return a content body - * @throws IllegalArgumentException if the index is invalid - */ - ContentChunk getContentChunk(StoreContext context, Long messageId, int index) throws IllegalArgumentException, AMQException; - - void addContentBodyFrame(StoreContext storeContext, Long messageId, ContentChunk contentBody, boolean isLastContentBody) throws AMQException; - - MessagePublishInfo getMessagePublishInfo(StoreContext context, Long messageId) throws AMQException; - - boolean isRedelivered(); - - void setRedelivered(boolean redelivered); - - boolean isPersistent(StoreContext context, Long messageId) throws AMQException; - - void setPublishAndContentHeaderBody(StoreContext storeContext, Long messageId, MessagePublishInfo messagePublishInfo, - ContentHeaderBody contentHeaderBody) - throws AMQException; - - void removeMessage(StoreContext storeContext, Long messageId) throws AMQException; - - void enqueue(StoreContext storeContext, Long messageId, AMQQueue queue) throws AMQException; - - void dequeue(StoreContext storeContext, Long messageId, AMQQueue queue) throws AMQException; - - long getArrivalTime(); - - // added by Arnaud - byte[] getMessagePayload(); -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueue.java b/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueue.java deleted file mode 100644 index b4a92b3483..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueue.java +++ /dev/null @@ -1,1052 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.queue; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.configuration.Configured; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.management.Managable; -import org.apache.qpid.server.management.ManagedObject; -import org.apache.qpid.server.messageStore.StorableMessage; -import org.apache.qpid.server.messageStore.StorableQueue; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.StoreContext; -import org.apache.qpid.server.virtualhost.VirtualHost; - -import javax.management.JMException; -import java.text.MessageFormat; -import java.util.Collection; -import java.util.Hashtable; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.Executor; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; - -/** - * This is an AMQ Queue, and should not be confused with a JMS queue or any other abstraction like that. It is described - * fully in RFC 006. - */ -public class AMQQueue implements Managable, Comparable, StorableQueue -{ - //FROM M2 - think these have been replaced by *Exception in the broker exception package -// /** -// * ExistingExclusiveSubscription signals a failure to create a subscription, because an exclusive subscription -// * already exists. -// * -// * <p/><table id="crc"><caption>CRC Card</caption> -// * <tr><th> Responsibilities <th> Collaborations -// * <tr><td> Represent failure to create a subscription, because an exclusive subscription already exists. -// * </table> -// * -// * @todo Not an AMQP exception as no status code. -// * -// * @todo Move to top level, used outside this class. -// */ -// public static final class ExistingExclusiveSubscription extends AMQException -// { -// -// public ExistingExclusiveSubscription() -// { -// super(""); -// } -// } -// -// /** -// * ExistingSubscriptionPreventsExclusive signals a failure to create an exclusize subscription, as a subscription -// * already exists. -// * -// * <p/><table id="crc"><caption>CRC Card</caption> -// * <tr><th> Responsibilities <th> Collaborations -// * <tr><td> Represent failure to create an exclusize subscription, as a subscription already exists. -// * </table> -// * -// * @todo Not an AMQP exception as no status code. -// * -// * @todo Move to top level, used outside this class. -// */ -// public static final class ExistingSubscriptionPreventsExclusive extends AMQException -// { -// public ExistingSubscriptionPreventsExclusive() -// { -// super(""); - // } - // } - public static int s_queueID = 0; - - private static final Logger _logger = Logger.getLogger(AMQQueue.class); - - private final AMQShortString _name; - - // The queueu ID - int _queueId; - // The list of enqueued messages. - Hashtable<Long, StorableMessage> _messages = new Hashtable<Long, StorableMessage>(); - - /** - * null means shared - */ - private final AMQShortString _owner; - - private final boolean _durable; - - /** - * If true, this queue is deleted when the last subscriber is removed - */ - private final boolean _autoDelete; - - /** - * Holds subscribers to the queue. - */ - private final SubscriptionSet _subscribers; - - private final SubscriptionFactory _subscriptionFactory; - - private final AtomicInteger _subscriberCount = new AtomicInteger(); - - private final AtomicBoolean _isExclusive = new AtomicBoolean(); - - private final AtomicBoolean _deleted = new AtomicBoolean(false); - - private List<Task> _deleteTaskList = new CopyOnWriteArrayList<Task>(); - - /** - * Manages message delivery. - */ - private final DeliveryManager _deliveryMgr; - - /** - * Used to track bindings to exchanges so that on deletion they can easily be cancelled. - */ - private final ExchangeBindings _bindings = new ExchangeBindings(this); - - /** - * Executor on which asynchronous delivery will be carriedout where required - */ - private final Executor _asyncDelivery; - - private final AMQQueueMBean _managedObject; - - private final VirtualHost _virtualHost; - - /** - * max allowed size(KB) of a single message - */ - @Configured(path = "maximumMessageSize", defaultValue = "0") - public long _maximumMessageSize; - - /** - * max allowed number of messages on a queue. - */ - @Configured(path = "maximumMessageCount", defaultValue = "0") - public long _maximumMessageCount; - - /** - * max queue depth for the queue - */ - @Configured(path = "maximumQueueDepth", defaultValue = "0") - public long _maximumQueueDepth; - - /** - * maximum message age before alerts occur - */ - @Configured(path = "maximumMessageAge", defaultValue = "0") - public long _maximumMessageAge; - - /** - * the minimum interval between sending out consequetive alerts of the same type - */ - @Configured(path = "minimumAlertRepeatGap", defaultValue = "0") - public long _minimumAlertRepeatGap; - - /** - * total messages received by the queue since startup. - */ - public AtomicLong _totalMessagesReceived = new AtomicLong(); - - public int compareTo(Object o) - { - return _name.compareTo(((AMQQueue) o).getName()); - } - - public AMQQueue(AMQShortString name, boolean durable, AMQShortString owner, boolean autoDelete, VirtualHost virtualHost) - throws AMQException - { - this(name, durable, owner, autoDelete, virtualHost, AsyncDeliveryConfig.getAsyncDeliveryExecutor(), - new SubscriptionSet(), new SubscriptionImpl.Factory()); - } - - protected AMQQueue(AMQShortString name, boolean durable, AMQShortString owner, boolean autoDelete, - VirtualHost virtualHost, SubscriptionSet subscribers) throws AMQException - { - this(name, durable, owner, autoDelete, virtualHost, AsyncDeliveryConfig.getAsyncDeliveryExecutor(), subscribers, - new SubscriptionImpl.Factory()); - } - - protected AMQQueue(AMQShortString name, boolean durable, AMQShortString owner, boolean autoDelete, - VirtualHost virtualHost, Executor asyncDelivery, SubscriptionSet subscribers, - SubscriptionFactory subscriptionFactory) throws AMQException - { - if (name == null) - { - throw new IllegalArgumentException("Queue name must not be null"); - } - - if (virtualHost == null) - { - throw new IllegalArgumentException("Virtual Host must not be null"); - } - - _name = name; - _durable = durable; - _owner = owner; - _autoDelete = autoDelete; - _virtualHost = virtualHost; - _asyncDelivery = asyncDelivery; - - _managedObject = createMBean(); - _managedObject.register(); - - _subscribers = subscribers; - _subscriptionFactory = subscriptionFactory; - _deliveryMgr = new ConcurrentSelectorDeliveryManager(_subscribers, this); - _queueId = s_queueID++; - } - - private AMQQueueMBean createMBean() throws AMQException - { - try - { - return new AMQQueueMBean(this); - } - catch (JMException ex) - { - throw new AMQException(null, "AMQQueue MBean creation has failed ", ex); - } - } - - public AMQShortString getName() - { - return _name; - } - - public boolean isShared() - { - return _owner == null; - } - - public boolean isDurable() - { - return _durable; - } - - public AMQShortString getOwner() - { - return _owner; - } - - public boolean isAutoDelete() - { - return _autoDelete; - } - - /** - * @return no of messages(undelivered) on the queue. - */ - public int getMessageCount() - { - return _deliveryMgr.getQueueMessageCount(); - } - - /** - * @return List of messages(undelivered) on the queue. - */ - public List<AMQMessage> getMessagesOnTheQueue() - { - return _deliveryMgr.getMessages(); - } - - /** - * Returns messages within the given range of message Ids - * - * @param fromMessageId - * @param toMessageId - * @return List of messages - */ - public List<AMQMessage> getMessagesOnTheQueue(long fromMessageId, long toMessageId) - { - return _deliveryMgr.getMessages(fromMessageId, toMessageId); - } - - public long getQueueDepth() - { - return _deliveryMgr.getTotalMessageSize(); - } - - /** - * @param messageId - * @return AMQMessage with give id if exists. null if AMQMessage with given id doesn't exist. - */ - public AMQMessage getMessageOnTheQueue(long messageId) - { - List<AMQMessage> list = getMessagesOnTheQueue(messageId, messageId); - if ((list == null) || (list.size() == 0)) - { - return null; - } - - return list.get(0); - } - - /** - * moves messages from this queue to another queue. to do this the approach is following- - setup the queue for - * moving messages (stop the async delivery) - get all the messages available in the given message id range - setup - * the other queue for moving messages (stop the async delivery) - send these available messages to the other queue - * (enqueue in other queue) - Once sending to other Queue is successful, remove messages from this queue - remove - * locks from both queues and start async delivery - * - * @param fromMessageId The first message id to move. - * @param toMessageId The last message id to move. - * @param queueName The queue to move the messages to. - * @param storeContext The context of the message store under which to perform the move. This is associated with - * the stores transactional context. - */ - public synchronized void moveMessagesToAnotherQueue(long fromMessageId, long toMessageId, String queueName, - StoreContext storeContext) - { - AMQQueue toQueue = getVirtualHost().getQueueRegistry().getQueue(new AMQShortString(queueName)); - - MessageStore fromStore = getVirtualHost().getMessageStore(); - MessageStore toStore = toQueue.getVirtualHost().getMessageStore(); - - if (toStore != fromStore) - { - throw new RuntimeException("Can only move messages between queues on the same message store."); - } - - try - { - // Obtain locks to prevent activity on the queues being moved between. - startMovingMessages(); - toQueue.startMovingMessages(); - - // Get the list of messages to move. - List<AMQMessage> foundMessagesList = getMessagesOnTheQueue(fromMessageId, toMessageId); - - try - { - fromStore.beginTran(storeContext); - - // Move the messages in on the message store. - for (AMQMessage message : foundMessagesList) - { - fromStore.dequeueMessage(storeContext, _name, message.getMessageId()); - toStore.enqueueMessage(storeContext, toQueue._name, message.getMessageId()); - } - - // Commit and flush the move transcations. - try - { - fromStore.commitTran(storeContext); - } - catch (AMQException e) - { - throw new RuntimeException("Failed to commit transaction whilst moving messages on message store.", e); - } - - // Move the messages on the in-memory queues. - toQueue.enqueueMovedMessages(storeContext, foundMessagesList); - _deliveryMgr.removeMovedMessages(foundMessagesList); - } - // Abort the move transactions on move failures. - catch (AMQException e) - { - try - { - fromStore.abortTran(storeContext); - } - catch (AMQException ae) - { - throw new RuntimeException("Failed to abort transaction whilst moving messages on message store.", ae); - } - } - } - // Release locks to allow activity on the queues being moved between to continue. - finally - { - toQueue.stopMovingMessages(); - stopMovingMessages(); - } - } - - /** - * Copies messages on this queue to another queue, and also commits the move on the message store. Delivery activity - * on the queues being moved between is suspended during the move. - * - * @param fromMessageId The first message id to move. - * @param toMessageId The last message id to move. - * @param queueName The queue to move the messages to. - * @param storeContext The context of the message store under which to perform the move. This is associated with - * the stores transactional context. - */ - public synchronized void copyMessagesToAnotherQueue(long fromMessageId, long toMessageId, String queueName, - StoreContext storeContext) - { - AMQQueue toQueue = getVirtualHost().getQueueRegistry().getQueue(new AMQShortString(queueName)); - - MessageStore fromStore = getVirtualHost().getMessageStore(); - MessageStore toStore = toQueue.getVirtualHost().getMessageStore(); - - if (toStore != fromStore) - { - throw new RuntimeException("Can only move messages between queues on the same message store."); - } - - try - { - // Obtain locks to prevent activity on the queues being moved between. - startMovingMessages(); - toQueue.startMovingMessages(); - - // Get the list of messages to move. - List<AMQMessage> foundMessagesList = getMessagesOnTheQueue(fromMessageId, toMessageId); - - try - { - fromStore.beginTran(storeContext); - - // Move the messages in on the message store. - for (AMQMessage message : foundMessagesList) - { - toStore.enqueueMessage(storeContext, toQueue._name, message.getMessageId()); - message.takeReference(); - } - - // Commit and flush the move transcations. - try - { - fromStore.commitTran(storeContext); - } - catch (AMQException e) - { - throw new RuntimeException("Failed to commit transaction whilst moving messages on message store.", e); - } - - // Move the messages on the in-memory queues. - toQueue.enqueueMovedMessages(storeContext, foundMessagesList); - } - // Abort the move transactions on move failures. - catch (AMQException e) - { - try - { - fromStore.abortTran(storeContext); - } - catch (AMQException ae) - { - throw new RuntimeException("Failed to abort transaction whilst moving messages on message store.", ae); - } - } - } - // Release locks to allow activity on the queues being moved between to continue. - finally - { - toQueue.stopMovingMessages(); - stopMovingMessages(); - } - } - - /** - * Removes messages from this queue, and also commits the remove on the message store. Delivery activity - * on the queues being moved between is suspended during the remove. - * - * @param fromMessageId The first message id to move. - * @param toMessageId The last message id to move. - * @param storeContext The context of the message store under which to perform the move. This is associated with - * the stores transactional context. - */ - public synchronized void removeMessagesFromQueue(long fromMessageId, long toMessageId, StoreContext storeContext) - { - MessageStore fromStore = getVirtualHost().getMessageStore(); - - try - { - // Obtain locks to prevent activity on the queues being moved between. - startMovingMessages(); - - // Get the list of messages to move. - List<AMQMessage> foundMessagesList = getMessagesOnTheQueue(fromMessageId, toMessageId); - - try - { - fromStore.beginTran(storeContext); - - // remove the messages in on the message store. - for (AMQMessage message : foundMessagesList) - { - fromStore.dequeueMessage(storeContext, _name, message.getMessageId()); - } - - // Commit and flush the move transcations. - try - { - fromStore.commitTran(storeContext); - } - catch (AMQException e) - { - throw new RuntimeException("Failed to commit transaction whilst moving messages on message store.", e); - } - - // remove the messages on the in-memory queues. - _deliveryMgr.removeMovedMessages(foundMessagesList); - } - // Abort the move transactions on move failures. - catch (AMQException e) - { - try - { - fromStore.abortTran(storeContext); - } - catch (AMQException ae) - { - throw new RuntimeException("Failed to abort transaction whilst moving messages on message store.", ae); - } - } - } - // Release locks to allow activity on the queues being moved between to continue. - finally - { - stopMovingMessages(); - } - } - - public void startMovingMessages() - { - _deliveryMgr.startMovingMessages(); - } - - private void enqueueMovedMessages(StoreContext storeContext, List<AMQMessage> messageList) - { - _deliveryMgr.enqueueMovedMessages(storeContext, messageList); - _totalMessagesReceived.addAndGet(messageList.size()); - } - - public void stopMovingMessages() - { - _deliveryMgr.stopMovingMessages(); - _deliveryMgr.processAsync(_asyncDelivery); - } - - /** - * @return MBean object associated with this Queue - */ - public ManagedObject getManagedObject() - { - return _managedObject; - } - - public long getMaximumMessageSize() - { - return _maximumMessageSize; - } - - public void setMaximumMessageSize(long value) - { - _maximumMessageSize = value; - } - - public int getConsumerCount() - { - return _subscribers.size(); - } - - public int getActiveConsumerCount() - { - return _subscribers.getWeight(); - } - - public long getReceivedMessageCount() - { - return _totalMessagesReceived.get(); - } - - public long getMaximumMessageCount() - { - return _maximumMessageCount; - } - - public void setMaximumMessageCount(long value) - { - _maximumMessageCount = value; - } - - public long getMaximumQueueDepth() - { - return _maximumQueueDepth; - } - - // Sets the queue depth, the max queue size - public void setMaximumQueueDepth(long value) - { - _maximumQueueDepth = value; - } - - public long getOldestMessageArrivalTime() - { - return _deliveryMgr.getOldestMessageArrival(); - - } - - /** - * Removes the AMQMessage from the top of the queue. - */ - public synchronized void deleteMessageFromTop(StoreContext storeContext) throws AMQException - { - _deliveryMgr.removeAMessageFromTop(storeContext); - } - - /** - * removes all the messages from the queue. - */ - public synchronized long clearQueue(StoreContext storeContext) throws AMQException - { - return _deliveryMgr.clearAllMessages(storeContext); - } - - public void bind(AMQShortString routingKey, FieldTable arguments, Exchange exchange) throws AMQException - { - exchange.registerQueue(routingKey, this, arguments); - if (isDurable() && exchange.isDurable()) - { - _virtualHost.getMessageStore().bindQueue(exchange, routingKey, this, arguments); - //DTX MessageStore -// try -// { -// _virtualHost.getMessageStore().bindQueue(exchange, routingKey, this, arguments); -// } -// catch (InternalErrorException e) -// { -// throw new AMQException(null, "Problem binding queue ", e); -// } - } - - _bindings.addBinding(routingKey, arguments, exchange); - } - - public void unBind(AMQShortString routingKey, FieldTable arguments, Exchange exchange) throws AMQException - { - exchange.deregisterQueue(routingKey, this, arguments); - if (isDurable() && exchange.isDurable()) - { - - _virtualHost.getMessageStore().unbindQueue(exchange, routingKey, this, arguments); - //DTX MessageStore -// try -// { -// _virtualHost.getMessageStore().unbindQueue(exchange, routingKey, this, arguments); -// } -// catch (InternalErrorException e) -// { -// throw new AMQException(null, "problem unbinding queue", e); -// } - } - - _bindings.remove(routingKey, arguments, exchange); - } - - public void registerProtocolSession(AMQProtocolSession ps, int channel, AMQShortString consumerTag, boolean acks, - FieldTable filters, boolean noLocal, boolean exclusive) throws AMQException - { - if (incrementSubscriberCount() > 1) - { - if (isExclusive()) - { - decrementSubscriberCount(); - throw new ExistingExclusiveSubscriptionException(); - } - else if (exclusive) - { - decrementSubscriberCount(); - throw new ExistingSubscriptionPreventsExclusiveException(); - } - - } - else if (exclusive) - { - setExclusive(true); - } - - if (_logger.isDebugEnabled()) - { - _logger.debug(MessageFormat.format( - "Registering protocol session {0} with channel {1} and " + "consumer tag {2} with {3}", ps, channel, - consumerTag, this)); - } - - Subscription subscription = - _subscriptionFactory.createSubscription(channel, ps, consumerTag, acks, filters, noLocal, this); - - if (subscription.filtersMessages()) - { - if (_deliveryMgr.hasQueuedMessages()) - { - _deliveryMgr.populatePreDeliveryQueue(subscription); - } - } - - _subscribers.addSubscriber(subscription); - } - - private boolean isExclusive() - { - return _isExclusive.get(); - } - - private void setExclusive(boolean exclusive) - { - _isExclusive.set(exclusive); - } - - private int incrementSubscriberCount() - { - return _subscriberCount.incrementAndGet(); - } - - private int decrementSubscriberCount() - { - return _subscriberCount.decrementAndGet(); - } - - public void unregisterProtocolSession(AMQProtocolSession ps, int channel, AMQShortString consumerTag) throws AMQException - { - if (_logger.isDebugEnabled()) - { - _logger.debug(MessageFormat.format( - "Unregistering protocol session {0} with channel {1} and consumer tag {2} from {3}", ps, channel, - consumerTag, this)); - } - - Subscription removedSubscription; - - if ((removedSubscription = - _subscribers.removeSubscriber(_subscriptionFactory.createSubscription(channel, ps, consumerTag))) - == null) - { - throw new AMQException(null, "Protocol session with channel " + channel + " and consumer tag " + consumerTag - + " and protocol session key " + ps.getKey() + " not registered with queue " + this, null); - } - - removedSubscription.close(); - setExclusive(false); - decrementSubscriberCount(); - - // if we are eligible for auto deletion, unregister from the queue registry - if (_autoDelete && _subscribers.isEmpty()) - { - if (_logger.isInfoEnabled()) - { - _logger.info("Auto-deleteing queue:" + this); - } - - autodelete(); - // we need to manually fire the event to the removed subscription (which was the last one left for this - // queue. This is because the delete method uses the subscription set which has just been cleared - removedSubscription.queueDeleted(this); - } - } - - public boolean isUnused() - { - return _subscribers.isEmpty(); - } - - public boolean isEmpty() - { - return !_deliveryMgr.hasQueuedMessages(); - } - - public int delete(boolean checkUnused, boolean checkEmpty) throws AMQException - { - if (checkUnused && !_subscribers.isEmpty()) - { - _logger.info("Will not delete " + this + " as it is in use."); - - return 0; - } - else if (checkEmpty && _deliveryMgr.hasQueuedMessages()) - { - _logger.info("Will not delete " + this + " as it is not empty."); - - return 0; - } - else - { - delete(); - - return _deliveryMgr.getQueueMessageCount(); - } - } - - public void delete() throws AMQException - { - if (!_deleted.getAndSet(true)) - { - _subscribers.queueDeleted(this); - _bindings.deregister(); - _virtualHost.getQueueRegistry().unregisterQueue(_name); - _managedObject.unregister(); - for (Task task : _deleteTaskList) - { - task.doTask(this); - } - - _deleteTaskList.clear(); - } - } - - protected void autodelete() throws AMQException - { - if (_logger.isDebugEnabled()) - { - _logger.debug(MessageFormat.format("autodeleting {0}", this)); - } - - delete(); - } - - /*public void processGet(StoreContext storeContext, AMQMessage msg, boolean deliverFirst) throws AMQException - { - // fixme not sure what this is doing. should we be passing deliverFirst through here? - // This code is not used so when it is perhaps it should - _deliveryMgr.deliver(storeContext, getName(), msg, deliverFirst); - try - { - msg.checkDeliveredToConsumer(); - updateReceivedMessageCount(msg); - } - catch (NoConsumersException e) - { - // as this message will be returned, it should be removed - // from the queue: - dequeue(storeContext, msg); - } - }*/ - - // public DeliveryManager getDeliveryManager() - // { - // return _deliveryMgr; - // } - - public void process(StoreContext storeContext, AMQMessage msg, boolean deliverFirst) throws AMQException - { - _deliveryMgr.deliver(storeContext, getName(), msg, deliverFirst); - try - { - msg.checkDeliveredToConsumer(); - updateReceivedMessageCount(msg); - } - catch (NoConsumersException e) - { - // as this message will be returned, it should be removed - // from the queue: - dequeue(storeContext, msg); - } - } - - void dequeue(StoreContext storeContext, AMQMessage msg) throws FailedDequeueException - { - try - { - msg.dequeue(storeContext, this); - } - catch (MessageCleanupException e) - { - // Message was dequeued, but could not then be deleted - // though it is no longer referenced. This should be very - // rare and can be detected and cleaned up on recovery or - // done through some form of manual intervention. - _logger.error(e, e); - } - catch (AMQException e) - { - throw new FailedDequeueException(_name.toString(), e); - } - } - - public void deliverAsync() - { - _deliveryMgr.processAsync(_asyncDelivery); - } - - protected SubscriptionManager getSubscribers() - { - return _subscribers; - } - - protected void updateReceivedMessageCount(AMQMessage msg) throws AMQException - { - if (!msg.isRedelivered()) - { - _totalMessagesReceived.incrementAndGet(); - } - - try - { - _managedObject.checkForNotification(msg); - } - catch (JMException e) - { - throw new AMQException(null, "Unable to get notification from manage queue: " + e, e); - } - } - - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - - if ((o == null) || (getClass() != o.getClass())) - { - return false; - } - - final AMQQueue amqQueue = (AMQQueue) o; - - return (_name.equals(amqQueue._name)); - } - - public int hashCode() - { - return _name.hashCode(); - } - - public String toString() - { - return "Queue(" + _name + ")@" + System.identityHashCode(this); - } - - public boolean performGet(AMQProtocolSession session, AMQChannel channel, boolean acks) throws AMQException - { - return _deliveryMgr.performGet(session, channel, acks); - } - - public QueueRegistry getQueueRegistry() - { - return _virtualHost.getQueueRegistry(); - } - - public VirtualHost getVirtualHost() - { - return _virtualHost; - } - - public static interface Task - { - public void doTask(AMQQueue queue) throws AMQException; - } - - public void addQueueDeleteTask(Task task) - { - _deleteTaskList.add(task); - } - - public long getMinimumAlertRepeatGap() - { - return _minimumAlertRepeatGap; - } - - public void setMinimumAlertRepeatGap(long minimumAlertRepeatGap) - { - _minimumAlertRepeatGap = minimumAlertRepeatGap; - } - - public long getMaximumMessageAge() - { - return _maximumMessageAge; - } - - public void setMaximumMessageAge(long maximumMessageAge) - { - _maximumMessageAge = maximumMessageAge; - } - - public void subscriberHasPendingResend(boolean hasContent, SubscriptionImpl subscription, AMQMessage msg) - { - _deliveryMgr.subscriberHasPendingResend(hasContent, subscription, msg); - } - - // ======================================================================== - // Interface StorableQueue - // ======================================================================== - - public int getQueueID() - { - return _queueId; - } - - public void setQueueID(int id) - { - _queueId = id; - } - - public void dequeue(StorableMessage m) - { - _messages.remove(m.getMessageId()); - } - - public void enqueue(StorableMessage m) - { - _messages.put(m.getMessageId(), m); - } - - // ======================================================================== - // Used by the Store - // ======================================================================== - - /** - * Get the list of enqueud messages - * - * @return The list of enqueud messages - */ - public Collection<StorableMessage> getAllEnqueuedMessages() - { - return _messages.values(); - } - - /** - * Get the enqueued message identified by messageID - * - * @param messageId the id of the enqueued message to recover - * @return The enqueued message with the specified id - */ - public StorableMessage getEnqueuedMessage(long messageId) - { - return _messages.get(messageId); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueueMBean.java b/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueueMBean.java deleted file mode 100644 index 4331d8d870..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueueMBean.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.queue; - -import org.apache.log4j.Logger; - -import org.apache.mina.common.ByteBuffer; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.CommonContentHeaderProperties; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.abstraction.ContentChunk; -import org.apache.qpid.server.management.AMQManagedObject; -import org.apache.qpid.server.management.MBeanConstructor; -import org.apache.qpid.server.management.MBeanDescription; -import org.apache.qpid.server.management.ManagedObject; -import org.apache.qpid.server.store.StoreContext; - -import javax.management.JMException; -import javax.management.MBeanException; -import javax.management.MBeanNotificationInfo; -import javax.management.Notification; -import javax.management.OperationsException; -import javax.management.monitor.MonitorNotification; -import javax.management.openmbean.ArrayType; -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.CompositeDataSupport; -import javax.management.openmbean.CompositeType; -import javax.management.openmbean.OpenDataException; -import javax.management.openmbean.OpenType; -import javax.management.openmbean.SimpleType; -import javax.management.openmbean.TabularData; -import javax.management.openmbean.TabularDataSupport; -import javax.management.openmbean.TabularType; - -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.Iterator; -import java.util.List; - -/** - * MBean class for AMQQueue. It implements all the management features exposed - * for an AMQQueue. - * <p/><tablse id="crc"><caption>CRC Caption</caption> - * <tr><th> Responsibilities <th> Collaborations - * </table> - */ -@MBeanDescription("Management Interface for AMQQueue") -public class AMQQueueMBean extends AMQManagedObject implements ManagedQueue, QueueNotificationListener -{ - /** Used for debugging purposes. */ - private static final Logger _logger = Logger.getLogger(AMQQueueMBean.class); - - private static final SimpleDateFormat _dateFormat = new SimpleDateFormat("MM-dd-yy HH:mm:ss.SSS z"); - - /** - * Since the MBean is not associated with a real channel we can safely create our own store context - * for use in the few methods that require one. - */ - private StoreContext _storeContext = new StoreContext(); - - private AMQQueue _queue = null; - private String _queueName = null; - // OpenMBean data types for viewMessages method - private static final String[] _msgAttributeNames = { "AMQ MessageId", "Header", "Size(bytes)", "Redelivered" }; - private static String[] _msgAttributeIndex = { _msgAttributeNames[0] }; - private static OpenType[] _msgAttributeTypes = new OpenType[4]; // AMQ message attribute types. - private static CompositeType _messageDataType = null; // Composite type for representing AMQ Message data. - private static TabularType _messagelistDataType = null; // Datatype for representing AMQ messages list. - - // OpenMBean data types for viewMessageContent method - private static CompositeType _msgContentType = null; - private static final String[] _msgContentAttributes = { "AMQ MessageId", "MimeType", "Encoding", "Content" }; - private static OpenType[] _msgContentAttributeTypes = new OpenType[4]; - - private final long[] _lastNotificationTimes = new long[NotificationCheck.values().length]; - private Notification _lastNotification = null; - - @MBeanConstructor("Creates an MBean exposing an AMQQueue") - public AMQQueueMBean(AMQQueue queue) throws JMException - { - super(ManagedQueue.class, ManagedQueue.TYPE); - _queue = queue; - _queueName = jmxEncode(new StringBuffer(queue.getName()), 0).toString(); - } - - public ManagedObject getParentObject() - { - return _queue.getVirtualHost().getManagedObject(); - } - - static - { - try - { - init(); - } - catch (JMException ex) - { - // This is not expected to ever occur. - throw new RuntimeException("Got JMException in static initializer.", ex); - } - } - - /** - * initialises the openmbean data types - */ - private static void init() throws OpenDataException - { - _msgContentAttributeTypes[0] = SimpleType.LONG; // For message id - _msgContentAttributeTypes[1] = SimpleType.STRING; // For MimeType - _msgContentAttributeTypes[2] = SimpleType.STRING; // For Encoding - _msgContentAttributeTypes[3] = new ArrayType(1, SimpleType.BYTE); // For message content - _msgContentType = - new CompositeType("Message Content", "AMQ Message Content", _msgContentAttributes, _msgContentAttributes, - _msgContentAttributeTypes); - - _msgAttributeTypes[0] = SimpleType.LONG; // For message id - _msgAttributeTypes[1] = new ArrayType(1, SimpleType.STRING); // For header attributes - _msgAttributeTypes[2] = SimpleType.LONG; // For size - _msgAttributeTypes[3] = SimpleType.BOOLEAN; // For redelivered - - _messageDataType = - new CompositeType("Message", "AMQ Message", _msgAttributeNames, _msgAttributeNames, _msgAttributeTypes); - _messagelistDataType = new TabularType("Messages", "List of messages", _messageDataType, _msgAttributeIndex); - } - - public String getObjectInstanceName() - { - return _queueName; - } - - public String getName() - { - return _queueName; - } - - public boolean isDurable() - { - return _queue.isDurable(); - } - - public String getOwner() - { - return String.valueOf(_queue.getOwner()); - } - - public boolean isAutoDelete() - { - return _queue.isAutoDelete(); - } - - public Integer getMessageCount() - { - return _queue.getMessageCount(); - } - - public Long getMaximumMessageSize() - { - return _queue.getMaximumMessageSize(); - } - - public Long getMaximumMessageAge() - { - return _queue.getMaximumMessageAge(); - } - - public void setMaximumMessageAge(Long maximumMessageAge) - { - _queue.setMaximumMessageAge(maximumMessageAge); - } - - public void setMaximumMessageSize(Long value) - { - _queue.setMaximumMessageSize(value); - } - - public Integer getConsumerCount() - { - return _queue.getConsumerCount(); - } - - public Integer getActiveConsumerCount() - { - return _queue.getActiveConsumerCount(); - } - - public Long getReceivedMessageCount() - { - return _queue.getReceivedMessageCount(); - } - - public Long getMaximumMessageCount() - { - return _queue.getMaximumMessageCount(); - } - - public void setMaximumMessageCount(Long value) - { - _queue.setMaximumMessageCount(value); - } - - public Long getMaximumQueueDepth() - { - long queueDepthInBytes = _queue.getMaximumQueueDepth(); - - return queueDepthInBytes >> 10; - } - - public void setMaximumQueueDepth(Long value) - { - _queue.setMaximumQueueDepth(value); - } - - /** - * returns the size of messages(KB) in the queue. - */ - public Long getQueueDepth() throws JMException - { - long queueBytesSize = _queue.getQueueDepth(); - - return queueBytesSize >> 10; - } - - /** - * Checks if there is any notification to be send to the listeners - */ - public void checkForNotification(AMQMessage msg) throws AMQException, JMException - { - - final long currentTime = System.currentTimeMillis(); - final long thresholdTime = currentTime - _queue.getMinimumAlertRepeatGap(); - - for (NotificationCheck check : NotificationCheck.values()) - { - if (check.isMessageSpecific() || (_lastNotificationTimes[check.ordinal()] < thresholdTime)) - { - if (check.notifyIfNecessary(msg, _queue, this)) - { - _lastNotificationTimes[check.ordinal()] = currentTime; - } - } - } - - } - - /** - * Sends the notification to the listeners - */ - public void notifyClients(NotificationCheck notification, AMQQueue queue, String notificationMsg) - { - // important : add log to the log file - monitoring tools may be looking for this - _logger.info(notification.name() + " On Queue " + queue.getName() + " - " + notificationMsg); - notificationMsg = notification.name() + " " + notificationMsg; - - _lastNotification = - new Notification(MonitorNotification.THRESHOLD_VALUE_EXCEEDED, this, ++_notificationSequenceNumber, - System.currentTimeMillis(), notificationMsg); - - _broadcaster.sendNotification(_lastNotification); - } - - public Notification getLastNotification() - { - return _lastNotification; - } - - /** - * @see org.apache.qpid.server.queue.AMQQueue#deleteMessageFromTop - */ - public void deleteMessageFromTop() throws JMException - { - try - { - _queue.deleteMessageFromTop(_storeContext); - } - catch (AMQException ex) - { - throw new MBeanException(ex, ex.toString()); - } - } - - /** - * @see org.apache.qpid.server.queue.AMQQueue#clearQueue - */ - public void clearQueue() throws JMException - { - try - { - _queue.clearQueue(_storeContext); - } - catch (AMQException ex) - { - throw new MBeanException(ex, ex.toString()); - } - } - - /** - * returns message content as byte array and related attributes for the given message id. - */ - public CompositeData viewMessageContent(long msgId) throws JMException - { - AMQMessage msg = _queue.getMessageOnTheQueue(msgId); - if (msg == null) - { - throw new OperationsException("AMQMessage with message id = " + msgId + " is not in the " + _queueName); - } - // get message content - Iterator<ContentChunk> cBodies = msg.getContentBodyIterator(); - List<Byte> msgContent = new ArrayList<Byte>(); - while (cBodies.hasNext()) - { - ContentChunk body = cBodies.next(); - if (body.getSize() != 0) - { - if (body.getSize() != 0) - { - ByteBuffer slice = body.getData().slice(); - for (int j = 0; j < slice.limit(); j++) - { - msgContent.add(slice.get()); - } - } - } - } - - try - { - // Create header attributes list - CommonContentHeaderProperties headerProperties = - (CommonContentHeaderProperties) msg.getContentHeaderBody().properties; - String mimeType = null, encoding = null; - if (headerProperties != null) - { - AMQShortString mimeTypeShortSting = headerProperties.getContentType(); - mimeType = (mimeTypeShortSting == null) ? null : mimeTypeShortSting.toString(); - encoding = (headerProperties.getEncoding() == null) ? "" : headerProperties.getEncoding().toString(); - } - - Object[] itemValues = { msgId, mimeType, encoding, msgContent.toArray(new Byte[0]) }; - - return new CompositeDataSupport(_msgContentType, _msgContentAttributes, itemValues); - } - catch (AMQException e) - { - JMException jme = new JMException("Error creating header attributes list: " + e); - jme.initCause(e); - throw jme; - } - } - - /** - * Returns the header contents of the messages stored in this queue in tabular form. - */ - public TabularData viewMessages(int beginIndex, int endIndex) throws JMException - { - if ((beginIndex > endIndex) || (beginIndex < 1)) - { - throw new OperationsException("From Index = " + beginIndex + ", To Index = " + endIndex - + "\n\"From Index\" should be greater than 0 and less than \"To Index\""); - } - - List<AMQMessage> list = _queue.getMessagesOnTheQueue(); - TabularDataSupport _messageList = new TabularDataSupport(_messagelistDataType); - - try - { - // Create the tabular list of message header contents - for (int i = beginIndex; (i <= endIndex) && (i <= list.size()); i++) - { - AMQMessage msg = list.get(i - 1); - ContentHeaderBody headerBody = msg.getContentHeaderBody(); - // Create header attributes list - String[] headerAttributes = getMessageHeaderProperties(headerBody); - Object[] itemValues = { msg.getMessageId(), headerAttributes, headerBody.bodySize, msg.isRedelivered() }; - CompositeData messageData = new CompositeDataSupport(_messageDataType, _msgAttributeNames, itemValues); - _messageList.put(messageData); - } - } - catch (AMQException e) - { - JMException jme = new JMException("Error creating message contents: " + e); - jme.initCause(e); - throw jme; - } - - return _messageList; - } - - private String[] getMessageHeaderProperties(ContentHeaderBody headerBody) - { - List<String> list = new ArrayList<String>(); - BasicContentHeaderProperties headerProperties = (BasicContentHeaderProperties) headerBody.properties; - list.add("reply-to = " + headerProperties.getReplyToAsString()); - list.add("propertyFlags = " + headerProperties.getPropertyFlags()); - list.add("ApplicationID = " + headerProperties.getAppIdAsString()); - list.add("ClusterID = " + headerProperties.getClusterIdAsString()); - list.add("UserId = " + headerProperties.getUserIdAsString()); - list.add("JMSMessageID = " + headerProperties.getMessageIdAsString()); - list.add("JMSCorrelationID = " + headerProperties.getCorrelationIdAsString()); - - int delMode = headerProperties.getDeliveryMode(); - list.add("JMSDeliveryMode = " + ((delMode == 1) ? "Persistent" : "Non_Persistent")); - - list.add("JMSPriority = " + headerProperties.getPriority()); - list.add("JMSType = " + headerProperties.getType()); - - long longDate = headerProperties.getExpiration(); - String strDate = (longDate != 0) ? _dateFormat.format(new Date(longDate)) : null; - list.add("JMSExpiration = " + strDate); - - longDate = headerProperties.getTimestamp(); - strDate = (longDate != 0) ? _dateFormat.format(new Date(longDate)) : null; - list.add("JMSTimestamp = " + strDate); - - return list.toArray(new String[list.size()]); - } - - /** - * @see ManagedQueue#moveMessages - * @param fromMessageId - * @param toMessageId - * @param toQueueName - * @throws JMException - */ - public void moveMessages(long fromMessageId, long toMessageId, String toQueueName) throws JMException - { - if ((fromMessageId > toMessageId) || (fromMessageId < 1)) - { - throw new OperationsException("\"From MessageId\" should be greater then 0 and less then \"To MessageId\""); - } - - _queue.moveMessagesToAnotherQueue(fromMessageId, toMessageId, toQueueName, _storeContext); - } - - /** - * returns Notifications sent by this MBean. - */ - @Override - public MBeanNotificationInfo[] getNotificationInfo() - { - String[] notificationTypes = new String[] { MonitorNotification.THRESHOLD_VALUE_EXCEEDED }; - String name = MonitorNotification.class.getName(); - String description = "Either Message count or Queue depth or Message size has reached threshold high value"; - MBeanNotificationInfo info1 = new MBeanNotificationInfo(notificationTypes, name, description); - - return new MBeanNotificationInfo[] { info1 }; - } - -} // End of AMQQueueMBean class diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/AsyncDeliveryConfig.java b/java/broker/src/main/java/org/apache/qpid/server/queue/AsyncDeliveryConfig.java deleted file mode 100644 index 290fedcf7b..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/AsyncDeliveryConfig.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.queue; - -import java.util.concurrent.Executor; -import java.util.concurrent.Executors; - -import org.apache.qpid.configuration.Configured; -import org.apache.qpid.server.registry.ApplicationRegistry; - -public class AsyncDeliveryConfig -{ - private Executor _executor; - - @Configured(path = "delivery.poolsize", defaultValue = "0") - public int poolSize; - - public Executor getExecutor() - { - if (_executor == null) - { - if (poolSize > 0) - { - _executor = Executors.newFixedThreadPool(poolSize); - } - else - { - _executor = Executors.newCachedThreadPool(); - } - } - return _executor; - } - - public static Executor getAsyncDeliveryExecutor() - { - return ApplicationRegistry.getInstance().getConfiguredObject(AsyncDeliveryConfig.class).getExecutor(); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/ConcurrentSelectorDeliveryManager.java b/java/broker/src/main/java/org/apache/qpid/server/queue/ConcurrentSelectorDeliveryManager.java deleted file mode 100644 index f3b8f0de35..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/ConcurrentSelectorDeliveryManager.java +++ /dev/null @@ -1,923 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.queue; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Queue; -import java.util.Set; -import java.util.Collections; -import java.util.HashSet; -import java.util.concurrent.Executor; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.locks.ReentrantLock; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.configuration.Configured; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.abstraction.ContentChunk; -import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.configuration.Configurator; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.store.StoreContext; -import org.apache.qpid.util.MessageQueue; -import org.apache.qpid.util.ConcurrentLinkedMessageQueueAtomicSize; - - -/** Manages delivery of messages on behalf of a queue */ -public class ConcurrentSelectorDeliveryManager implements DeliveryManager -{ - private static final Logger _log = Logger.getLogger(ConcurrentSelectorDeliveryManager.class); - - @Configured(path = "advanced.compressBufferOnQueue", - defaultValue = "false") - public boolean compressBufferOnQueue; - /** Holds any queued messages */ - private final MessageQueue<AMQMessage> _messages = new ConcurrentLinkedMessageQueueAtomicSize<AMQMessage>(); - - /** Ensures that only one asynchronous task is running for this manager at any time. */ - private final AtomicBoolean _processing = new AtomicBoolean(); - /** The subscriptions on the queue to whom messages are delivered */ - private final SubscriptionManager _subscriptions; - - /** - * A reference to the queue we are delivering messages for. We need this to be able to pass the code that handles - * acknowledgements a handle on the queue. - */ - private final AMQQueue _queue; - - /** - * Flag used while moving messages from this queue to another. For moving messages the async delivery should also - * stop. This flat should be set to true to stop async delivery and set to false to enable async delivery again. - */ - private AtomicBoolean _movingMessages = new AtomicBoolean(); - - /** - * Lock used to ensure that an channel that becomes unsuspended during the start of the queueing process is forced - * to wait till the first message is added to the queue. This will ensure that the _queue has messages to be - * delivered via the async thread. <p/> Lock is used to control access to hasQueuedMessages() and over the addition - * of messages to the queue. - */ - private ReentrantLock _lock = new ReentrantLock(); - private AtomicLong _totalMessageSize = new AtomicLong(); - private AtomicInteger _extraMessages = new AtomicInteger(); - private Set<Subscription> _hasContent = Collections.synchronizedSet(new HashSet<Subscription>()); - private final Object _queueHeadLock = new Object(); - private String _processingThreadName = ""; - - - /** Used by any reaping thread to purge messages */ - private StoreContext _reapingStoreContext = new StoreContext(); - - ConcurrentSelectorDeliveryManager(SubscriptionManager subscriptions, AMQQueue queue) - { - - //Set values from configuration - Configurator.configure(this); - - if (compressBufferOnQueue) - { - _log.warn("Compressing Buffers on queue."); - } - - _subscriptions = subscriptions; - _queue = queue; - } - - - private boolean addMessageToQueue(AMQMessage msg, boolean deliverFirst) - { - // Shrink the ContentBodies to their actual size to save memory. - if (compressBufferOnQueue) - { - Iterator<ContentChunk> it = msg.getContentBodyIterator(); - while (it.hasNext()) - { - ContentChunk cb = it.next(); - cb.reduceToFit(); - } - } - - if (deliverFirst) - { - synchronized (_queueHeadLock) - { - _messages.pushHead(msg); - } - } - else - { - _messages.offer(msg); - } - - _totalMessageSize.addAndGet(msg.getSize()); - - return true; - } - - - public boolean hasQueuedMessages() - { - _lock.lock(); - try - { - return !(_messages.isEmpty() && _hasContent.isEmpty()); - } - finally - { - _lock.unlock(); - } - } - - public int getQueueMessageCount() - { - return getMessageCount(); - } - - /** - * This is an EXPENSIVE opperation to perform with a ConcurrentLinkedQueue as it must run the queue to determine - * size. The ConcurrentLinkedQueueAtomicSize uses an AtomicInteger to record the number of elements on the queue. - * - * @return int the number of messages in the delivery queue. - */ - private int getMessageCount() - { - return _messages.size() + _extraMessages.get(); - } - - - public long getTotalMessageSize() - { - return _totalMessageSize.get(); - } - - public long getOldestMessageArrival() - { - AMQMessage msg = _messages.peek(); - return msg == null ? Long.MAX_VALUE : msg.getArrivalTime(); - } - - public void subscriberHasPendingResend(boolean hasContent, Subscription subscription, AMQMessage msg) - { - _lock.lock(); - try - { - if (hasContent) - { - _log.debug("Queue has adding subscriber content"); - _hasContent.add(subscription); - _totalMessageSize.addAndGet(msg.getSize()); - _extraMessages.addAndGet(1); - } - else - { - _log.debug("Queue has removing subscriber content"); - if (msg == null) - { - _hasContent.remove(subscription); - } - else - { - _totalMessageSize.addAndGet(-msg.getSize()); - _extraMessages.addAndGet(-1); - } - } - } - finally - { - _lock.unlock(); - } - } - - /** - * Returns all the messages in the Queue - * - * @return List of messages - */ - public List<AMQMessage> getMessages() - { - _lock.lock(); - List<AMQMessage> list = new ArrayList<AMQMessage>(); - - for (AMQMessage message : _messages) - { - list.add(message); - } - _lock.unlock(); - - return list; - } - - /** - * Returns messages within the range of given messageIds - * - * @param fromMessageId - * @param toMessageId - * - * @return - */ - public List<AMQMessage> getMessages(long fromMessageId, long toMessageId) - { - if (fromMessageId <= 0 || toMessageId <= 0) - { - return null; - } - - long maxMessageCount = toMessageId - fromMessageId + 1; - - _lock.lock(); - - List<AMQMessage> foundMessagesList = new ArrayList<AMQMessage>(); - - for (AMQMessage message : _messages) - { - long msgId = message.getMessageId(); - if (msgId >= fromMessageId && msgId <= toMessageId) - { - foundMessagesList.add(message); - } - // break if the no of messages are found - if (foundMessagesList.size() == maxMessageCount) - { - break; - } - } - _lock.unlock(); - - return foundMessagesList; - } - - public void populatePreDeliveryQueue(Subscription subscription) - { - if (_log.isTraceEnabled()) - { - _log.trace("Populating PreDeliveryQueue for Subscription(" + System.identityHashCode(subscription) + ")"); - } - - Iterator<AMQMessage> currentQueue = _messages.iterator(); - - while (currentQueue.hasNext()) - { - AMQMessage message = currentQueue.next(); - if (subscription.hasInterest(message)) - { - subscription.enqueueForPreDelivery(message, false); - } - } - } - - public boolean performGet(AMQProtocolSession protocolSession, AMQChannel channel, boolean acks) throws AMQException - { - AMQMessage msg = getNextMessage(); - if (msg == null) - { - return false; - } - else - { - - try - { - // if we do not need to wait for client acknowledgements - // we can decrement the reference count immediately. - - // By doing this _before_ the send we ensure that it - // doesn't get sent if it can't be dequeued, preventing - // duplicate delivery on recovery. - - // The send may of course still fail, in which case, as - // the message is unacked, it will be lost. - if (!acks) - { - if (_log.isDebugEnabled()) - { - _log.debug("No ack mode so dequeuing message immediately: " + msg.getMessageId()); - } - _queue.dequeue(channel.getStoreContext(), msg); - } - synchronized (channel) - { - long deliveryTag = channel.getNextDeliveryTag(); - - if (acks) - { - channel.addUnacknowledgedMessage(msg, deliveryTag, null, _queue); - } - - protocolSession.getProtocolOutputConverter().writeGetOk(msg, channel.getChannelId(), - deliveryTag, _queue.getMessageCount()); - _totalMessageSize.addAndGet(-msg.getSize()); - } - } - finally - { - msg.setDeliveredToConsumer(); - } - return true; - - } - } - - /** - * For feature of moving messages, this method is used. It sets the lock and sets the movingMessages flag, so that - * the asyn delivery is also stopped. - */ - public void startMovingMessages() - { - _movingMessages.set(true); - } - - /** - * Once moving messages to another queue is done or aborted, remove lock and unset the movingMessages flag, so that - * the async delivery can start again. - */ - public void stopMovingMessages() - { - _movingMessages.set(false); - if (_lock.isHeldByCurrentThread()) - { - _lock.unlock(); - } - } - - /** - * Messages will be removed from this queue and all preDeliveryQueues - * - * @param messageList - */ - public void removeMovedMessages(List<AMQMessage> messageList) - { - // Remove from the - boolean hasSubscribers = _subscriptions.hasActiveSubscribers(); - if (hasSubscribers) - { - for (Subscription sub : _subscriptions.getSubscriptions()) - { - if (!sub.isSuspended() && sub.filtersMessages()) - { - Queue<AMQMessage> preDeliveryQueue = sub.getPreDeliveryQueue(); - for (AMQMessage msg : messageList) - { - preDeliveryQueue.remove(msg); - } - } - } - } - - for (AMQMessage msg : messageList) - { - if (_messages.remove(msg)) - { - _totalMessageSize.getAndAdd(-msg.getSize()); - } - } - } - - /** - * Now with implementation of predelivery queues, this method will mark the message on the top as taken. - * - * @param storeContext - * - * @throws AMQException - */ - public void removeAMessageFromTop(StoreContext storeContext) throws AMQException - { - _lock.lock(); - - AMQMessage message = _messages.poll(); - if (message != null) - { - _totalMessageSize.addAndGet(-message.getSize()); - } - - _lock.unlock(); - } - - public long clearAllMessages(StoreContext storeContext) throws AMQException - { - long count = 0; - _lock.lock(); - - synchronized (_queueHeadLock) - { - AMQMessage msg = getNextMessage(); - while (msg != null) - { - //and remove it - _messages.poll(); - - _queue.dequeue(storeContext, msg); - msg = getNextMessage(); - count++; - } - _totalMessageSize.set(0L); - } - _lock.unlock(); - return count; - } - - /** - * This can only be used to clear the _messages queue. Any subscriber resend queue will not be purged. - * - * @return the next message or null - * - * @throws org.apache.qpid.AMQException - */ - private AMQMessage getNextMessage() throws AMQException - { - return getNextMessage(_messages, null); - } - - private AMQMessage getNextMessage(Queue<AMQMessage> messages, Subscription sub) throws AMQException - { - AMQMessage message = messages.peek(); - - //while (we have a message) && ((The subscriber is not a browser or message is taken ) or we are clearing) && (Check message is taken.) - while (purgeMessage(message, sub)) - { - // if we are purging then ensure we mark this message taken for the current subscriber - // the current subscriber may be null in the case of a get or a purge but this is ok. -// boolean alreadyTaken = message.taken(_queue, sub); - - //remove the already taken message or expired - AMQMessage removed = messages.poll(); - - assert removed == message; - - // if the message expired then the _totalMessageSize needs adjusting - if (message.expired(_queue)) - { - _totalMessageSize.addAndGet(-message.getSize()); - - // Use the reapingStoreContext as any sub(if we have one) may be in a tx. - message.dequeue(_reapingStoreContext, _queue); - - if (_log.isInfoEnabled()) - { - _log.info(debugIdentity() + " Doing clean up of the main _message queue."); - } - } - - //else the clean up is not required as the message has already been taken for this queue therefore - // it was the responsibility of the code that took the message to ensure the _totalMessageSize was updated. - - if (_log.isTraceEnabled()) - { - _log.trace("Removed taken message:" + message.debugIdentity()); - } - - // try the next message - message = messages.peek(); - } - - return message; - } - - /** - * This method will return true if the message is to be purged from the queue. - * - * - * SIDE-EFFECT: The message will be taken by the Subscription(sub) for the current Queue(_queue) - * @param message - * @param sub - * @return - * @throws AMQException - */ - private boolean purgeMessage(AMQMessage message, Subscription sub) throws AMQException - { - //Original.. complicated while loop control -// (message != null -// && ( -// ((sub != null && !sub.isBrowser()) || message.isTaken(_queue)) -// || sub == null) -// && message.taken(_queue, sub)); - - boolean purge = false; - - // if the message is null then don't purge as we have no messagse. - if (message != null) - { - // Check that the message hasn't expired. - if (message.expired(_queue)) - { - return true; - } - - // if we have a subscriber perform message checks - if (sub != null) - { - // if we have a queue browser(we don't purge) so check mark the message as taken - purge = ((!sub.isBrowser() || message.isTaken(_queue))); - } - else - { - // if there is no subscription we are doing - // a get or purging so mark message as taken. - message.isTaken(_queue); - // and then ensure that it gets purged - purge = true; - } - } - - // if we are purging then ensure we mark this message taken for the current subscriber - // the current subscriber may be null in the case of a get or a purge but this is ok. - return purge && message.taken(_queue, sub); - } - - public void sendNextMessage(Subscription sub, AMQQueue queue)//Queue<AMQMessage> messageQueue) - { - - Queue<AMQMessage> messageQueue = sub.getNextQueue(_messages); - - if (_log.isTraceEnabled()) - { - _log.trace(debugIdentity() + "Async sendNextMessage for sub (" + System.identityHashCode(sub) + - ") from queue (" + System.identityHashCode(messageQueue) + - ") AMQQueue (" + System.identityHashCode(queue) + ")"); - } - - if (messageQueue == null) - { - // There is no queue with messages currently. This is ok... just means the queue has no msgs matching selector - if (_log.isInfoEnabled()) - { - _log.info(debugIdentity() + sub + ": asked to send messages but has none on given queue:" + queue); - } - return; - } - - AMQMessage message = null; - AMQMessage removed = null; - try - { - synchronized (_queueHeadLock) - { - message = getNextMessage(messageQueue, sub); - - // message will be null if we have no messages in the messageQueue. - if (message == null) - { - if (_log.isTraceEnabled()) - { - _log.trace(debugIdentity() + "No messages for Subscriber(" + System.identityHashCode(sub) + ") from queue; (" + System.identityHashCode(messageQueue) + ")"); - } - return; - } - if (_log.isDebugEnabled()) - { - _log.debug(debugIdentity() + "Async Delivery Message :" + message + "(" + System.identityHashCode(message) + - ") by :" + System.identityHashCode(this) + - ") to :" + System.identityHashCode(sub)); - } - - sub.send(message, _queue); - - //remove sent message from our queue. - removed = messageQueue.poll(); - //If we don't remove the message from _messages - // Otherwise the Async send will never end - } - - if (removed != message) - { - _log.error("Just send message:" + message.debugIdentity() + " BUT removed this from queue:" + removed); - } - - if (_log.isDebugEnabled()) - { - _log.debug(debugIdentity() + "Async Delivered Message r:" + removed.debugIdentity() + "d:" + message + - ") by :" + System.identityHashCode(this) + - ") to :" + System.identityHashCode(sub)); - } - - - if (messageQueue == sub.getResendQueue()) - { - if (_log.isTraceEnabled()) - { - _log.trace(debugIdentity() + "All messages sent from resendQueue for " + sub); - } - if (messageQueue.isEmpty()) - { - subscriberHasPendingResend(false, sub, null); - //better to use the above method as this keeps all the tracking in one location. - // _hasContent.remove(sub); - } - - _extraMessages.decrementAndGet(); - } - else if (messageQueue == sub.getPreDeliveryQueue() && !sub.isBrowser()) - { - if (_log.isInfoEnabled()) - { - //fixme - we should do the clean up as the message remains on the _message queue - // this is resulting in the next consumer receiving the message and then attempting to purge it - // - _log.info(debugIdentity() + "We should do clean up of the main _message queue here"); - } - } - - if ((message != null) && (messageQueue == _messages)) - { - _totalMessageSize.addAndGet(-message.getSize()); - } - } - catch (AMQException e) - { - if (message != null) - { - message.release(_queue); - } - else - { - _log.error(debugIdentity() + "Unable to release message as it is null. " + e, e); - } - _log.error(debugIdentity() + "Unable to deliver message as dequeue failed: " + e, e); - } - } - - /** - * enqueues the messages in the list on the queue and all required predelivery queues - * - * @param storeContext - * @param movedMessageList - */ - public void enqueueMovedMessages(StoreContext storeContext, List<AMQMessage> movedMessageList) - { - _lock.lock(); - for (AMQMessage msg : movedMessageList) - { - addMessageToQueue(msg, false); - } - - // enqueue on the pre delivery queues - for (Subscription sub : _subscriptions.getSubscriptions()) - { - for (AMQMessage msg : movedMessageList) - { - // Only give the message to those that want them. - if (sub.hasInterest(msg)) - { - sub.enqueueForPreDelivery(msg, true); - } - } - } - _lock.unlock(); - } - - /** - * Only one thread should ever execute this method concurrently, but it can do so while other threads invoke - * deliver(). - */ - private void processQueue() - { - //record thread name - if (_log.isDebugEnabled()) - { - _processingThreadName = Thread.currentThread().getName(); - } - - if (_log.isDebugEnabled()) - { - _log.debug(debugIdentity() + "Running process Queue." + currentStatus()); - } - - // Continue to process delivery while we haveSubscribers and messages - boolean hasSubscribers = _subscriptions.hasActiveSubscribers(); - - while (hasSubscribers && hasQueuedMessages() && !_movingMessages.get()) - { - hasSubscribers = false; - - for (Subscription sub : _subscriptions.getSubscriptions()) - { - synchronized (sub.getSendLock()) - { - if (!sub.isSuspended()) - { - sendNextMessage(sub, _queue); - - hasSubscribers = true; - } - } - } - } - - if (_log.isDebugEnabled()) - { - _log.debug(debugIdentity() + "Done process Queue." + currentStatus()); - } - - } - - public void deliver(StoreContext context, AMQShortString name, AMQMessage msg, boolean deliverFirst) throws AMQException - { - - final boolean debugEnabled = _log.isDebugEnabled(); - if (debugEnabled) - { - _log.debug(debugIdentity() + "deliver :first(" + deliverFirst + ") :" + msg); - } - - //Check if we have someone to deliver the message to. - _lock.lock(); - try - { - Subscription s = _subscriptions.nextSubscriber(msg); - - if (s == null || hasQueuedMessages()) //no-one can take the message right now or we're queueing - { - if (debugEnabled) - { - _log.debug(debugIdentity() + "Testing Message(" + msg + ") for Queued Delivery:" + currentStatus()); - } - if (!msg.getMessagePublishInfo().isImmediate()) - { - addMessageToQueue(msg, deliverFirst); - - //release lock now message is on queue. - _lock.unlock(); - - //Pre Deliver to all subscriptions - if (debugEnabled) - { - _log.debug(debugIdentity() + "We have " + _subscriptions.getSubscriptions().size() + - " subscribers to give the message to:" + currentStatus()); - } - for (Subscription sub : _subscriptions.getSubscriptions()) - { - - // stop if the message gets delivered whilst PreDelivering if we have a shared queue. - if (_queue.isShared() && msg.getDeliveredToConsumer()) - { - if (debugEnabled) - { - _log.debug(debugIdentity() + "Stopping PreDelivery as message(" + System.identityHashCode(msg) + - ") is already delivered."); - } - continue; - } - - // Only give the message to those that want them. - if (sub.hasInterest(msg)) - { - if (debugEnabled) - { - _log.debug(debugIdentity() + "Queuing message(" + System.identityHashCode(msg) + - ") for PreDelivery for subscriber(" + System.identityHashCode(sub) + ")"); - } - sub.enqueueForPreDelivery(msg, deliverFirst); - } - } - } - } - else - { - - if (_messages.size() > 0) - { - _log.error("Direct delivery with queued msgs:" + _messages.size()); - } - - //release lock now - _lock.unlock(); - synchronized (s.getSendLock()) - { - if (!s.isSuspended()) - { - if (_log.isTraceEnabled()) - { - _log.trace(debugIdentity() + "Delivering Message:" + msg.debugIdentity() + " to(" + - System.identityHashCode(s) + ") :" + s); - } - msg.taken(_queue, s); - //Deliver the message - s.send(msg, _queue); - } - else - { - if (debugEnabled) - { - _log.debug(debugIdentity() + " Subscription(" + System.identityHashCode(s) + ") became " + - "suspended between nextSubscriber and send for message:" + msg.debugIdentity()); - } - } - } - - if (!msg.isTaken(_queue)) - { - if (debugEnabled) - { - _log.debug(debugIdentity() + " Message(" + msg.debugIdentity() + ") has not been taken so recursing!:" + - " Subscriber:" + System.identityHashCode(s)); - } - - deliver(context, name, msg, deliverFirst); - } - else - { - if (debugEnabled) - { - _log.debug(debugIdentity() + " Message(" + msg.toString() + - ") has been taken so disregarding deliver request to Subscriber:" + - System.identityHashCode(s)); - } - } - } - - } - finally - { - //ensure lock is released - if (_lock.isHeldByCurrentThread()) - { - _lock.unlock(); - } - } - } - - private final String id = "(" + String.valueOf(System.identityHashCode(this)) + ")"; - - private String debugIdentity() - { - return id; - } - - Runner asyncDelivery = new Runner(); - - private class Runner implements Runnable - { - public void run() - { - boolean running = true; - while (running && !_movingMessages.get()) - { - processQueue(); - - //Check that messages have not been added since we did our last peek(); - // Synchronize with the thread that adds to the queue. - // If the queue is still empty then we can exit - - if (!(hasQueuedMessages() && _subscriptions.hasActiveSubscribers())) - { - running = false; - _processing.set(false); - } - } - } - } - - public void processAsync(Executor executor) - { - if (_log.isDebugEnabled()) - { - _log.debug(debugIdentity() + "Processing Async." + currentStatus()); - } - - if (hasQueuedMessages() && _subscriptions.hasActiveSubscribers()) - { - //are we already running? if so, don't re-run - if (_processing.compareAndSet(false, true)) - { - if (_log.isDebugEnabled()) - { - _log.debug(debugIdentity() + "Executing Async process."); - } - executor.execute(asyncDelivery); - } - } - } - - private String currentStatus() - { - return " Queued:" + (_messages.isEmpty() ? "Empty " : "Contains(M:H)") + - "(" + _messages.size() + ":" + ((ConcurrentLinkedMessageQueueAtomicSize) _messages).headSize() + ") " + - " Extra: " + (_hasContent.isEmpty() ? "Empty " : "Contains") + - "(" + _hasContent.size() + ":" + _extraMessages.get() + ") " + - " Active:" + _subscriptions.hasActiveSubscribers() + - " Processing:" + (_processing.get() ? " true : Processing Thread: " + _processingThreadName : " false"); - } - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/DefaultQueueRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/queue/DefaultQueueRegistry.java deleted file mode 100644 index cbe9246f09..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/DefaultQueueRegistry.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.queue; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.virtualhost.VirtualHost; - -import java.util.Collection; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -public class DefaultQueueRegistry implements QueueRegistry -{ - private ConcurrentMap<AMQShortString, AMQQueue> _queueMap = new ConcurrentHashMap<AMQShortString, AMQQueue>(); - - private final VirtualHost _virtualHost; - - public DefaultQueueRegistry(VirtualHost virtualHost) - { - _virtualHost = virtualHost; - } - - public VirtualHost getVirtualHost() - { - return _virtualHost; - } - - public void registerQueue(AMQQueue queue) throws AMQException - { - _queueMap.put(queue.getName(), queue); - } - - public void unregisterQueue(AMQShortString name) throws AMQException - { - _queueMap.remove(name); - } - - public AMQQueue getQueue(AMQShortString name) - { - return _queueMap.get(name); - } - - public Collection<AMQShortString> getQueueNames() - { - return _queueMap.keySet(); - } - - public Collection<AMQQueue> getQueues() - { - return _queueMap.values(); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/DeliveryManager.java b/java/broker/src/main/java/org/apache/qpid/server/queue/DeliveryManager.java deleted file mode 100644 index 10ba48552c..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/DeliveryManager.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.queue; - -import java.util.List; -import java.util.concurrent.Executor; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.store.StoreContext; - -interface DeliveryManager -{ - /** - * Determines whether there are queued messages. Sets _queueing to false if there are no queued messages. This needs - * to be atomic. - * - * @return true if there are queued messages - */ - boolean hasQueuedMessages(); - - /** - * This method should not be used to determin if there are messages in the queue. - * - * @return int The number of messages in the queue - * - * @use hasQueuedMessages() for all controls relating to having messages on the queue. - */ - int getQueueMessageCount(); - - /** - * Requests that the delivery manager start processing the queue asynchronously if there is work that can be done - * (i.e. there are messages queued up and subscribers that can receive them. <p/> This should be called when - * subscribers are added, but only after the consume-ok message has been returned as message delivery may start - * immediately. It should also be called after unsuspending a client. <p/> - * - * @param executor the executor on which the delivery should take place - */ - void processAsync(Executor executor); - - /** - * Handles message delivery. The delivery manager is always in one of two modes; it is either queueing messages for - * asynchronous delivery or delivering directly. - * - * @param storeContext - * @param name the name of the entity on whose behalf we are delivering the message - * @param msg the message to deliver - * @param deliverFirst - * - * @throws org.apache.qpid.server.queue.FailedDequeueException - * if the message could not be dequeued - */ - void deliver(StoreContext storeContext, AMQShortString name, AMQMessage msg, boolean deliverFirst) throws FailedDequeueException, AMQException; - - void removeAMessageFromTop(StoreContext storeContext) throws AMQException; - - long clearAllMessages(StoreContext storeContext) throws AMQException; - - void startMovingMessages(); - - void enqueueMovedMessages(StoreContext context, List<AMQMessage> messageList); - - void stopMovingMessages(); - - void removeMovedMessages(List<AMQMessage> messageListToRemove); - - List<AMQMessage> getMessages(); - - List<AMQMessage> getMessages(long fromMessageId, long toMessageId); - - void populatePreDeliveryQueue(Subscription subscription); - - boolean performGet(AMQProtocolSession session, AMQChannel channel, boolean acks) throws AMQException; - - long getTotalMessageSize(); - - long getOldestMessageArrival(); - - void subscriberHasPendingResend(boolean hasContent, Subscription subscription, AMQMessage msg); -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/ExchangeBindings.java b/java/broker/src/main/java/org/apache/qpid/server/queue/ExchangeBindings.java deleted file mode 100644 index a950678487..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/ExchangeBindings.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.queue; - -import java.util.HashSet; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.server.exchange.Exchange; - -/** - * When a queue is deleted, it should be deregistered from any - * exchange it has been bound to. This class assists in this task, - * by keeping track of all bindings for a given queue. - */ -class ExchangeBindings -{ - private static final FieldTable EMPTY_ARGUMENTS = new FieldTable(); - - static class ExchangeBinding - { - private final Exchange _exchange; - private final AMQShortString _routingKey; - private final FieldTable _arguments; - - ExchangeBinding(AMQShortString routingKey, Exchange exchange) - { - this(routingKey, exchange,EMPTY_ARGUMENTS); - } - - ExchangeBinding(AMQShortString routingKey, Exchange exchange, FieldTable arguments) - { - _routingKey = routingKey; - _exchange = exchange; - _arguments = arguments == null ? EMPTY_ARGUMENTS : arguments; - } - - void unbind(AMQQueue queue) throws AMQException - { - _exchange.deregisterQueue(_routingKey, queue, _arguments); - } - - public Exchange getExchange() - { - return _exchange; - } - - public AMQShortString getRoutingKey() - { - return _routingKey; - } - - public int hashCode() - { - return (_exchange == null ? 0 : _exchange.hashCode()) - + (_routingKey == null ? 0 : _routingKey.hashCode()) - + (_arguments == null ? 0 : _arguments.hashCode()); - } - - public boolean equals(Object o) - { - if (!(o instanceof ExchangeBinding)) - { - return false; - } - ExchangeBinding eb = (ExchangeBinding) o; - return _exchange.equals(eb._exchange) - && _routingKey.equals(eb._routingKey) - && _arguments.equals(eb._arguments); - } - } - - private final List<ExchangeBinding> _bindings = new CopyOnWriteArrayList<ExchangeBinding>(); - private final AMQQueue _queue; - - ExchangeBindings(AMQQueue queue) - { - _queue = queue; - } - - /** - * Adds the specified binding to those being tracked. - * @param routingKey the routing key with which the queue whose bindings - * are being tracked by the instance has been bound to the exchange - * @param exchange the exchange bound to - */ - void addBinding(AMQShortString routingKey, FieldTable arguments, Exchange exchange) - { - _bindings.add(new ExchangeBinding(routingKey, exchange, arguments)); - } - - - public void remove(AMQShortString routingKey, FieldTable arguments, Exchange exchange) - { - _bindings.remove(new ExchangeBinding(routingKey, exchange, arguments)); - } - - - /** - * Deregisters this queue from any exchange it has been bound to - */ - void deregister() throws AMQException - { - //remove duplicates at this point - HashSet<ExchangeBinding> copy = new HashSet<ExchangeBinding>(_bindings); - for (ExchangeBinding b : copy) - { - b.unbind(_queue); - } - } - - List<ExchangeBinding> getExchangeBindings() - { - return _bindings; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/ExistingExclusiveSubscriptionException.java b/java/broker/src/main/java/org/apache/qpid/server/queue/ExistingExclusiveSubscriptionException.java deleted file mode 100644 index a5ff9e6326..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/ExistingExclusiveSubscriptionException.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.apache.qpid.server.queue;
-
-import org.apache.qpid.AMQException;
-
-/**
- * ExistingExclusiveSubscriptionException signals a failure to create a subscription, because an exclusive subscription
- * already exists.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represent failure to create a subscription, because an exclusive subscription already exists.
- * </table>
- *
- * @todo Not an AMQP exception as no status code.
- */
-public final class ExistingExclusiveSubscriptionException extends AMQException
-{
- public ExistingExclusiveSubscriptionException()
- {
- super(null, "", null);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/ExistingSubscriptionPreventsExclusiveException.java b/java/broker/src/main/java/org/apache/qpid/server/queue/ExistingSubscriptionPreventsExclusiveException.java deleted file mode 100644 index a13686eb56..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/ExistingSubscriptionPreventsExclusiveException.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.apache.qpid.server.queue;
-
-import org.apache.qpid.AMQException;
-
-/**
- * ExistingSubscriptionPreventsExclusiveException signals a failure to create an exclusize subscription, as a subscription
- * already exists.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Represent failure to create an exclusize subscription, as a subscription already exists.
- * </table>
- *
- * @todo Not an AMQP exception as no status code.
- */
-public final class ExistingSubscriptionPreventsExclusiveException extends AMQException
-{
- public ExistingSubscriptionPreventsExclusiveException()
- {
- super(null, "", null);
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/FailedDequeueException.java b/java/broker/src/main/java/org/apache/qpid/server/queue/FailedDequeueException.java deleted file mode 100644 index d5c34152a8..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/FailedDequeueException.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.server.queue; - -import org.apache.qpid.AMQException; - -/** - * Signals that the dequeue of a message from a queue failed. - * - * <p/><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Indicates the a message could not be dequeued from a queue. - * <tr><td> - * </table> - * - * @todo Not an AMQP exception as no status code. - * - * @todo Happens as a consequence of a message store failure, or reference counting error. Both of which migh become - * runtime exceptions, as unrecoverable conditions? In which case this one might be dropped too. - */ -public class FailedDequeueException extends AMQException -{ - public FailedDequeueException(String queue, Throwable cause) - { - super(null, "Failed to dequeue message from " + queue, cause); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/InMemoryMessageHandle.java b/java/broker/src/main/java/org/apache/qpid/server/queue/InMemoryMessageHandle.java deleted file mode 100644 index c81360e7d4..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/InMemoryMessageHandle.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.queue; - -import java.util.LinkedList; -import java.util.List; -import java.nio.ByteBuffer; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.ContentBody; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.abstraction.MessagePublishInfo; -import org.apache.qpid.framing.abstraction.ContentChunk; -import org.apache.qpid.server.store.StoreContext; - -/** - */ -public class InMemoryMessageHandle implements AMQMessageHandle -{ - - private ContentHeaderBody _contentHeaderBody; - - private MessagePublishInfo _messagePublishInfo; - - private List<ContentChunk> _contentBodies = new LinkedList<ContentChunk>(); - - private boolean _redelivered; - - private long _arrivalTime; - - // the message payload - private byte[] _payload; - // a buffer to write the payload - ByteBuffer _buffer; - - public InMemoryMessageHandle() - { - } - - public ContentHeaderBody getContentHeaderBody(StoreContext context, Long messageId) throws AMQException - { - return _contentHeaderBody; - } - - public int getBodyCount(StoreContext context, Long messageId) - { - return _contentBodies.size(); - } - - public long getBodySize(StoreContext context, Long messageId) throws AMQException - { - return getContentHeaderBody(context, messageId).bodySize; - } - - public ContentChunk getContentChunk(StoreContext context, Long messageId, int index) throws AMQException, IllegalArgumentException - { - if (index > _contentBodies.size() - 1) - { - throw new IllegalArgumentException("Index " + index + " out of valid range 0 to " + - (_contentBodies.size() - 1)); - } - return _contentBodies.get(index); - } - - public void addContentBodyFrame(StoreContext storeContext, Long messageId, ContentChunk contentBody, boolean isLastContentBody) - throws AMQException - { - _contentBodies.add(contentBody); - } - - public MessagePublishInfo getMessagePublishInfo(StoreContext context, Long messageId) throws AMQException - { - return _messagePublishInfo; - } - - public boolean isRedelivered() - { - return _redelivered; - } - - - public void setRedelivered(boolean redelivered) - { - _redelivered = redelivered; - } - - public boolean isPersistent(StoreContext context, Long messageId) throws AMQException - { - //todo remove literal values to a constant file such as AMQConstants in common - ContentHeaderBody chb = getContentHeaderBody(context, messageId); - return chb.properties instanceof BasicContentHeaderProperties && - ((BasicContentHeaderProperties) chb.properties).getDeliveryMode() == 2; - } - - /** - * This is called when all the content has been received. - * @param messagePublishInfo - * @param contentHeaderBody - * @throws AMQException - */ - public void setPublishAndContentHeaderBody(StoreContext storeContext, Long messageId, MessagePublishInfo messagePublishInfo, - ContentHeaderBody contentHeaderBody) - throws AMQException - { - _messagePublishInfo = messagePublishInfo; - _contentHeaderBody = contentHeaderBody; - _arrivalTime = System.currentTimeMillis(); - } - - public void removeMessage(StoreContext storeContext, Long messageId) throws AMQException - { - // NO OP - } - - public void enqueue(StoreContext storeContext, Long messageId, AMQQueue queue) throws AMQException - { - // NO OP - } - - public void dequeue(StoreContext storeContext, Long messageId, AMQQueue queue) throws AMQException - { - // NO OP - } - - public long getArrivalTime() - { - return _arrivalTime; - } - - - // added by Arnaud - public byte[] getMessagePayload() - { - if (_payload == null) - { - int bodySize = (int) _contentHeaderBody.bodySize; - _buffer = ByteBuffer.allocate(bodySize); - _payload = new byte[bodySize]; - for (ContentChunk contentBody : _contentBodies) - { - int chunkSize = contentBody.getSize(); - byte[] chunk = new byte[chunkSize]; - contentBody.getData().get(chunk); - _buffer.put(chunk); - } - _buffer.get(_payload); - } - return _payload; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/ManagedQueue.java b/java/broker/src/main/java/org/apache/qpid/server/queue/ManagedQueue.java deleted file mode 100644 index 061ab56024..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/ManagedQueue.java +++ /dev/null @@ -1,245 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.queue; - -import java.io.IOException; - -import javax.management.JMException; -import javax.management.MBeanOperationInfo; -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.TabularData; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.management.MBeanAttribute; -import org.apache.qpid.server.management.MBeanOperation; -import org.apache.qpid.server.management.MBeanOperationParameter; - -/** - * The management interface exposed to allow management of a queue. - * @author Robert J. Greig - * @author Bhupendra Bhardwaj - * @version 0.1 - */ -public interface ManagedQueue -{ - static final String TYPE = "Queue"; - - /** - * Returns the Name of the ManagedQueue. - * @return the name of the managedQueue. - * @throws IOException - */ - @MBeanAttribute(name="Name", description = TYPE + " Name") - String getName() throws IOException; - - /** - * Total number of messages on the queue, which are yet to be delivered to the consumer(s). - * @return number of undelivered message in the Queue. - * @throws IOException - */ - @MBeanAttribute(name="MessageCount", description = "Total number of undelivered messages on the queue") - Integer getMessageCount() throws IOException; - - /** - * Tells the total number of messages receieved by the queue since startup. - * @return total number of messages received. - * @throws IOException - */ - @MBeanAttribute(name="ReceivedMessageCount", description="The total number of messages receieved by the queue since startup") - Long getReceivedMessageCount() throws IOException; - - /** - * Size of messages in the queue - * @return - * @throws IOException - */ - @MBeanAttribute(name="QueueDepth", description="Size of messages(KB) in the queue") - Long getQueueDepth() throws IOException, JMException; - - /** - * Returns the total number of active subscribers to the queue. - * @return the number of active subscribers - * @throws IOException - */ - @MBeanAttribute(name="ActiveConsumerCount", description="The total number of active subscribers to the queue") - Integer getActiveConsumerCount() throws IOException; - - /** - * Returns the total number of subscribers to the queue. - * @return the number of subscribers. - * @throws IOException - */ - @MBeanAttribute(name="ConsumerCount", description="The total number of subscribers to the queue") - Integer getConsumerCount() throws IOException; - - /** - * Tells the Owner of the ManagedQueue. - * @return the owner's name. - * @throws IOException - */ - @MBeanAttribute(name="Owner", description = "Owner") - String getOwner() throws IOException; - - /** - * Tells whether this ManagedQueue is durable or not. - * @return true if this ManagedQueue is a durable queue. - * @throws IOException - */ - @MBeanAttribute(name="Durable", description = "true if the AMQQueue is durable") - boolean isDurable() throws IOException; - - /** - * Tells if the ManagedQueue is set to AutoDelete. - * @return true if the ManagedQueue is set to AutoDelete. - * @throws IOException - */ - @MBeanAttribute(name="AutoDelete", description = "true if the AMQQueue is AutoDelete") - boolean isAutoDelete() throws IOException; - - /** - * Returns the maximum age of a message (expiration time) - * @return the maximum age - * @throws IOException - */ - Long getMaximumMessageAge() throws IOException; - - /** - * Sets the maximum age of a message - * @param age maximum age of message. - * @throws IOException - */ - @MBeanAttribute(name="MaximumMessageAge", description="Threshold high value for message age on thr broker") - void setMaximumMessageAge(Long age) throws IOException; - - /** - * Returns the maximum size of a message (in kbytes) allowed to be accepted by the - * ManagedQueue. This is useful in setting notifications or taking - * appropriate action, if the size of the message received is more than - * the allowed size. - * @return the maximum size of a message allowed to be aceepted by the - * ManagedQueue. - * @throws IOException - */ - Long getMaximumMessageSize() throws IOException; - - /** - * Sets the maximum size of the message (in kbytes) that is allowed to be - * accepted by the Queue. - * @param size maximum size of message. - * @throws IOException - */ - @MBeanAttribute(name="MaximumMessageSize", description="Threshold high value(KB) for a message size") - void setMaximumMessageSize(Long size) throws IOException; - - /** - * Tells the maximum number of messages that can be stored in the queue. - * This is useful in setting the notifications or taking required - * action is the number of message increase this limit. - * @return maximum muber of message allowed to be stored in the queue. - * @throws IOException - */ - Long getMaximumMessageCount() throws IOException; - - /** - * Sets the maximum number of messages allowed to be stored in the queue. - * @param value the maximum number of messages allowed to be stored in the queue. - * @throws IOException - */ - @MBeanAttribute(name="MaximumMessageCount", description="Threshold high value for number of undelivered messages in the queue") - void setMaximumMessageCount(Long value) throws IOException; - - /** - * This is useful for setting notifications or taking required action if the size of messages - * stored in the queue increases over this limit. - * @return threshold high value for Queue Depth - * @throws IOException - */ - Long getMaximumQueueDepth() throws IOException; - - /** - * Sets the maximum size of all the messages together, that can be stored - * in the queue. - * @param value - * @throws IOException - */ - @MBeanAttribute(name="MaximumQueueDepth", description="The threshold high value(KB) for Queue Depth") - void setMaximumQueueDepth(Long value) throws IOException; - - - - //********** Operations *****************// - - - /** - * Returns a subset of all the messages stored in the queue. The messages - * are returned based on the given index numbers. - * @param fromIndex - * @param toIndex - * @return - * @throws IOException - * @throws JMException - */ - @MBeanOperation(name="viewMessages", - description="Message headers for messages in this queue within given index range. eg. from index 1 - 100") - TabularData viewMessages(@MBeanOperationParameter(name="from index", description="from index")int fromIndex, - @MBeanOperationParameter(name="to index", description="to index")int toIndex) - throws IOException, JMException, AMQException; - - @MBeanOperation(name="viewMessageContent", description="The message content for given Message Id") - CompositeData viewMessageContent(@MBeanOperationParameter(name="Message Id", description="Message Id")long messageId) - throws IOException, JMException; - - /** - * Deletes the first message from top. - * @throws IOException - * @throws JMException - */ - @MBeanOperation(name="deleteMessageFromTop", description="Deletes the first message from top", - impact= MBeanOperationInfo.ACTION) - void deleteMessageFromTop() throws IOException, JMException; - - /** - * Clears the queue by deleting all the undelivered messages from the queue. - * @throws IOException - * @throws JMException - */ - @MBeanOperation(name="clearQueue", - description="Clears the queue by deleting all the undelivered messages from the queue", - impact= MBeanOperationInfo.ACTION) - void clearQueue() throws IOException, JMException; - - /** - * Moves the messages in given range of message Ids to given Queue. QPID-170 - * @param fromMessageId first in the range of message ids - * @param toMessageId last in the range of message ids - * @param toQueue where the messages are to be moved - * @throws IOException - * @throws JMException - * @throws AMQException - */ - @MBeanOperation(name="moveMessages", - description="You can move messages to another queue from this queue ", - impact= MBeanOperationInfo.ACTION) - void moveMessages(@MBeanOperationParameter(name="from MessageId", description="from MessageId")long fromMessageId, - @MBeanOperationParameter(name="to MessageId", description="to MessageId")long toMessageId, - @MBeanOperationParameter(name= ManagedQueue.TYPE, description="to Queue Name")String toQueue) - throws IOException, JMException, AMQException; -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/MessageCleanupException.java b/java/broker/src/main/java/org/apache/qpid/server/queue/MessageCleanupException.java deleted file mode 100644 index 2fdd2791b1..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/MessageCleanupException.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.queue; - -import org.apache.qpid.AMQException; - -/** - * MessageCleanupException represents the failure to perform reference counting on messages correctly. This should not - * happen, but there may be programming errors giving race conditions that cause the reference counting to go wrong. - * - * <p/><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Signals that the reference count of a message has gone below zero. - * <tr><td> Indicates that a message store has lost a message which is still referenced. - * </table> - * - * @todo Not an AMQP exception as no status code. - * - * @todo The race conditions leading to this error should be cleaned up, and a runtime exception used instead. If the - * message store loses messages, then something is seriously wrong and it would be sensible to terminate the - * broker. This may be disguising out of memory errors. - */ -public class MessageCleanupException extends AMQException -{ - public MessageCleanupException(String message, Throwable cause) - { - super(null, message, cause); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/MessageHandleFactory.java b/java/broker/src/main/java/org/apache/qpid/server/queue/MessageHandleFactory.java deleted file mode 100644 index 35e43aa412..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/MessageHandleFactory.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.queue; - -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.messageStore.StorableMessage; - -/** - * Constructs a message handle based on the publish body, the content header and the queue to which the message - * has been routed. - * - */ -public class MessageHandleFactory -{ - - public AMQMessageHandle createMessageHandle(MessageStore store, StorableMessage m, boolean persistent) - { - // just hardcoded for now - if (persistent) - { - return new WeakReferenceMessageHandle(store); - //DTX MessageStore -// return new StorableMessageHandle(store, m); - } - else - { - return new InMemoryMessageHandle(); - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/MessageMetaData.java b/java/broker/src/main/java/org/apache/qpid/server/queue/MessageMetaData.java deleted file mode 100644 index 6118a4c11f..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/MessageMetaData.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.queue; - -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.abstraction.MessagePublishInfo; - -/** - * Encapsulates a publish body and a content header. In the context of the message store these are treated as a - * single unit. - */ -public class MessageMetaData -{ - private MessagePublishInfo _messagePublishInfo; - - private ContentHeaderBody _contentHeaderBody; - - private int _contentChunkCount; - - private long _arrivalTime; - - public MessageMetaData(MessagePublishInfo publishBody, ContentHeaderBody contentHeaderBody, int contentChunkCount) - { - this(publishBody,contentHeaderBody, contentChunkCount, System.currentTimeMillis()); - } - - public MessageMetaData(MessagePublishInfo publishBody, ContentHeaderBody contentHeaderBody, int contentChunkCount, long arrivalTime) - { - _contentHeaderBody = contentHeaderBody; - _messagePublishInfo = publishBody; - _contentChunkCount = contentChunkCount; - _arrivalTime = arrivalTime; - } - - public int getContentChunkCount() - { - return _contentChunkCount; - } - - public void setContentChunkCount(int contentChunkCount) - { - _contentChunkCount = contentChunkCount; - } - - public ContentHeaderBody getContentHeaderBody() - { - return _contentHeaderBody; - } - - public void setContentHeaderBody(ContentHeaderBody contentHeaderBody) - { - _contentHeaderBody = contentHeaderBody; - } - - public MessagePublishInfo getMessagePublishInfo() - { - return _messagePublishInfo; - } - - public void setMessagePublishInfo(MessagePublishInfo messagePublishInfo) - { - _messagePublishInfo = messagePublishInfo; - } - - public long getArrivalTime() - { - return _arrivalTime; - } - - public void setArrivalTime(long arrivalTime) - { - _arrivalTime = arrivalTime; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/NoConsumersException.java b/java/broker/src/main/java/org/apache/qpid/server/queue/NoConsumersException.java deleted file mode 100644 index afcdf062de..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/NoConsumersException.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.queue; - -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.RequiredDeliveryException; - -/** - * NoConsumersException is a {@link RequiredDeliveryException} that represents the failure case where an immediate - * message cannot be delivered because there are presently no consumers for the message. The AMQP status code, 313, is - * always used to report this condition. - * - * <p/><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Represent failure to deliver a message that must be delivered. - * </table> - */ -public class NoConsumersException extends RequiredDeliveryException -{ - public NoConsumersException(AMQMessage message, Throwable cause) - { - super("Immediate delivery is not possible.", message, cause); - } - - public AMQConstant getReplyCode() - { - return AMQConstant.NO_CONSUMERS; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/NotificationCheck.java b/java/broker/src/main/java/org/apache/qpid/server/queue/NotificationCheck.java deleted file mode 100644 index 6b3d65661f..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/NotificationCheck.java +++ /dev/null @@ -1,138 +0,0 @@ -/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import org.apache.qpid.AMQException;
-
-public enum NotificationCheck
-{
-
- MESSAGE_COUNT_ALERT
- {
- boolean notifyIfNecessary(AMQMessage msg, AMQQueue queue, QueueNotificationListener listener)
- {
- int msgCount = queue.getMessageCount();
- final long maximumMessageCount = queue.getMaximumMessageCount();
- if (maximumMessageCount!= 0 && msgCount >= maximumMessageCount)
- {
- listener.notifyClients(this, queue, msgCount + ": Maximum count on queue threshold ("+ maximumMessageCount +") breached.");
- return true;
- }
- return false;
- }
- },
- MESSAGE_SIZE_ALERT(true)
- {
- boolean notifyIfNecessary(AMQMessage msg, AMQQueue queue, QueueNotificationListener listener)
- {
- final long maximumMessageSize = queue.getMaximumMessageSize();
- if(maximumMessageSize != 0)
- {
- // Check for threshold message size
- long messageSize;
- try
- {
- messageSize = (msg == null) ? 0 : msg.getContentHeaderBody().bodySize;
- }
- catch (AMQException e)
- {
- messageSize = 0;
- }
-
-
- if (messageSize >= maximumMessageSize)
- {
- listener.notifyClients(this, queue, messageSize + "b : Maximum message size threshold ("+ maximumMessageSize +") breached. [Message ID=" + msg.getMessageId() + "]");
- return true;
- }
- }
- return false;
- }
-
- },
- QUEUE_DEPTH_ALERT
- {
- boolean notifyIfNecessary(AMQMessage msg, AMQQueue queue, QueueNotificationListener listener)
- {
- // Check for threshold queue depth in bytes
- final long maximumQueueDepth = queue.getMaximumQueueDepth();
-
- if(maximumQueueDepth != 0)
- {
- final long queueDepth = queue.getQueueDepth();
-
- if (queueDepth >= maximumQueueDepth)
- {
- listener.notifyClients(this, queue, (queueDepth>>10) + "Kb : Maximum queue depth threshold ("+(maximumQueueDepth>>10)+"Kb) breached.");
- return true;
- }
- }
- return false;
- }
-
- },
- MESSAGE_AGE_ALERT
- {
- boolean notifyIfNecessary(AMQMessage msg, AMQQueue queue, QueueNotificationListener listener)
- {
-
- final long maxMessageAge = queue.getMaximumMessageAge();
- if(maxMessageAge != 0)
- {
- final long currentTime = System.currentTimeMillis();
- final long thresholdTime = currentTime - maxMessageAge;
- final long firstArrivalTime = queue.getOldestMessageArrivalTime();
-
- if(firstArrivalTime < thresholdTime)
- {
- long oldestAge = currentTime - firstArrivalTime;
- listener.notifyClients(this, queue, (oldestAge/1000) + "s : Maximum age on queue threshold ("+(maxMessageAge /1000)+"s) breached.");
-
- return true;
- }
- }
- return false;
-
- }
-
- }
- ;
-
- private final boolean _messageSpecific;
-
- NotificationCheck()
- {
- this(false);
- }
-
- NotificationCheck(boolean messageSpecific)
- {
- _messageSpecific = messageSpecific;
- }
-
- public boolean isMessageSpecific()
- {
- return _messageSpecific;
- }
-
- abstract boolean notifyIfNecessary(AMQMessage msg, AMQQueue queue, QueueNotificationListener listener);
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/QueueNotificationListener.java b/java/broker/src/main/java/org/apache/qpid/server/queue/QueueNotificationListener.java deleted file mode 100644 index d2680ffcc8..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/QueueNotificationListener.java +++ /dev/null @@ -1,26 +0,0 @@ -/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-public interface QueueNotificationListener
-{
- void notifyClients(NotificationCheck notification, AMQQueue queue, String notificationMsg);
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/QueueRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/queue/QueueRegistry.java deleted file mode 100644 index 1210f0e97c..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/QueueRegistry.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.queue; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.virtualhost.VirtualHost; - -import java.util.Collection; - -public interface QueueRegistry -{ - VirtualHost getVirtualHost(); - - void registerQueue(AMQQueue queue) throws AMQException; - - void unregisterQueue(AMQShortString name) throws AMQException; - - AMQQueue getQueue(AMQShortString name); - - Collection<AMQShortString> getQueueNames(); - - Collection<AMQQueue> getQueues(); - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/StorableMessageHandle.java b/java/broker/src/main/java/org/apache/qpid/server/queue/StorableMessageHandle.java deleted file mode 100644 index 8c20050027..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/StorableMessageHandle.java +++ /dev/null @@ -1,304 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.queue; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.abstraction.ContentChunk; -import org.apache.qpid.framing.abstraction.MessagePublishInfo; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.messageStore.MessageStore; -import org.apache.qpid.server.messageStore.StorableMessage; -import org.apache.qpid.server.store.StoreContext; - -import javax.transaction.xa.Xid; -import java.nio.ByteBuffer; -import java.util.LinkedList; -import java.util.List; - -/** - * Created by Arnaud Simon - * Date: 25-Apr-2007 - * Time: 14:26:34 - */ -public class StorableMessageHandle implements AMQMessageHandle -{ - //======================================================================== - // Static Constants - //======================================================================== - // The logger for this class - private static final Logger _log = Logger.getLogger(StorableMessageHandle.class); - - //======================================================================== - // Instance Fields - //======================================================================== - // the message store - final private MessageStore _messageStore; - // A reference on the message itself - final private StorableMessage _message; - // the message payload - private byte[] _payload; - // a buffer to write the payload - ByteBuffer _buffer; - // the ContentHeaderBody - private ContentHeaderBody _contentHeaderBody; - // the arrival time - private long _arrivalTime; - // Specify if this messag is redelivered - private boolean _redelivered; - // MessagePublishInfo - private MessagePublishInfo _messagePublishInfo; - // list of chunks - private List<ContentChunk> _chunks; - - //======================================================================== - // Constructors - //======================================================================== - - public StorableMessageHandle(MessageStore messageStore, StorableMessage message) - { - _messageStore = messageStore; - _message = message; - } - - //======================================================================== - // Interface AMQMessageHandle - //======================================================================== - public ContentHeaderBody getContentHeaderBody(StoreContext context, Long messageId) - throws - AMQException - { - if (_contentHeaderBody == null) - { - // load it from the store - try - { - _contentHeaderBody = _messageStore.getContentHeaderBody(_message); - } - catch (Exception e) - { - throw new AMQException(AMQConstant.INTERNAL_ERROR, e.getMessage(), e); - } - } - return _contentHeaderBody; - } - - public int getBodyCount(StoreContext context, Long messageId) - throws - AMQException - { - if (_chunks == null) - { - if (_message.isStaged()) - { - loadChunks(); - } - else - { - return 0; - } - } - return _chunks.size(); - } - - public long getBodySize(StoreContext context, Long messageId) - throws - AMQException - { - return _payload.length; - } - - public ContentChunk getContentChunk(StoreContext context, Long messageId, int index) - throws - IllegalArgumentException, - AMQException - { - if (_chunks == null) - { - loadChunks(); - } - return _chunks.get(index); - } - - private void loadChunks() - throws - AMQException - { - try - { - _chunks = new LinkedList<ContentChunk>(); - byte[] underlying = _messageStore.loadContent(_message, 1, 0); - final int size = underlying.length; - final org.apache.mina.common.ByteBuffer data = - org.apache.mina.common.ByteBuffer.wrap(underlying); - ContentChunk cb = new ContentChunk() - { - - public int getSize() - { - return size; - } - - public org.apache.mina.common.ByteBuffer getData() - { - return data; - } - - public void reduceToFit() - { - - } - }; - _chunks.add(cb); - } - catch (Exception e) - { - throw new AMQException(AMQConstant.INTERNAL_ERROR, e.getMessage(), e); - } - } - - public void addContentBodyFrame(StoreContext storeContext, Long messageId, ContentChunk contentBody, boolean isLastContentBody) - throws - AMQException - { - if (_chunks == null) - { - _chunks = new LinkedList<ContentChunk>(); - } - _chunks.add(contentBody); - // if rquired this message can be added to the store - //_messageStore.appendContent(_message, _payload, 0, 10); - - } - - public MessagePublishInfo getMessagePublishInfo(StoreContext context, Long messageId) - throws - AMQException - { - if (_messagePublishInfo == null) - { - // read it from the store - try - { - - _messagePublishInfo = _messageStore.getMessagePublishInfo(_message); - } - catch (Exception e) - { - throw new AMQException(AMQConstant.INTERNAL_ERROR, e.getMessage(), e); - } - } - return _messagePublishInfo; - } - - public boolean isRedelivered() - { - return _redelivered; - } - - public void setRedelivered(boolean redelivered) - { - _redelivered = redelivered; - } - - public boolean isPersistent(StoreContext context, Long messageId) - throws - AMQException - { - return _contentHeaderBody.properties instanceof BasicContentHeaderProperties && - ((BasicContentHeaderProperties) _contentHeaderBody.properties).getDeliveryMode() == 2; - } - - public void setPublishAndContentHeaderBody(StoreContext storeContext, Long messageId, - MessagePublishInfo messagePublishInfo, - ContentHeaderBody contentHeaderBody) - throws - AMQException - { - _contentHeaderBody = contentHeaderBody; - _arrivalTime = System.currentTimeMillis(); - _messagePublishInfo = messagePublishInfo; - } - - public void removeMessage(StoreContext storeContext, Long messageId) - throws - AMQException - { - // This is already handled by the store but we can possibly do: - // _messageStore.destroy(_message); - } - - public void enqueue(StoreContext storeContext, Long messageId, AMQQueue queue) - throws - AMQException - { - try - { - if (queue.isDurable()) - { - _messageStore.enqueue((Xid) storeContext.getPayload(), _message, queue); - } - } - catch (Exception e) - { - throw new AMQException(null, "PRoblem during message enqueue", e); - } - } - - public void dequeue(StoreContext storeContext, Long messageId, AMQQueue queue) - throws - AMQException - { - try - { - if (queue.isDurable()) - { - _messageStore.dequeue((Xid) storeContext.getPayload(), _message, queue); - } - } - catch (Exception e) - { - throw new AMQException(null, "PRoblem during message dequeue", e); - } - } - - public long getArrivalTime() - { - return _arrivalTime; - } - - public byte[] getMessagePayload() - { - if (_payload == null) - { - int bodySize = (int) _contentHeaderBody.bodySize; - _payload = new byte[bodySize]; - _buffer = ByteBuffer.wrap(_payload); - for (ContentChunk contentBody : _chunks) - { - int chunkSize = contentBody.getSize(); - byte[] chunk = new byte[chunkSize]; - contentBody.getData().get(chunk); - _buffer.put(chunk); - } - } - return _payload; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/Subscription.java b/java/broker/src/main/java/org/apache/qpid/server/queue/Subscription.java deleted file mode 100644 index 77688f19be..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/Subscription.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.queue; - -import java.util.Queue; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.AMQChannel; - -public interface Subscription -{ - void send(AMQMessage msg, AMQQueue queue) throws AMQException; - - boolean isSuspended(); - - void queueDeleted(AMQQueue queue) throws AMQException; - - boolean filtersMessages(); - - boolean hasInterest(AMQMessage msg); - - Queue<AMQMessage> getPreDeliveryQueue(); - - Queue<AMQMessage> getResendQueue(); - - Queue<AMQMessage> getNextQueue(Queue<AMQMessage> messages); - - void enqueueForPreDelivery(AMQMessage msg, boolean deliverFirst); - - boolean isAutoClose(); - - void close(); - - boolean isClosed(); - - boolean isBrowser(); - - boolean wouldSuspend(AMQMessage msg); - - void addToResendQueue(AMQMessage msg); - - Object getSendLock(); - - AMQChannel getChannel(); -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/SubscriptionFactory.java b/java/broker/src/main/java/org/apache/qpid/server/queue/SubscriptionFactory.java deleted file mode 100644 index 917f7c4e97..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/SubscriptionFactory.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.queue; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.server.protocol.AMQProtocolSession; - -/** - * Allows the customisation of the creation of a subscription. This is typically done within an AMQQueue. This factory - * primarily assists testing although in future more sophisticated subscribers may need a different subscription - * implementation. - * - * @see org.apache.qpid.server.queue.AMQQueue - */ -public interface SubscriptionFactory -{ - Subscription createSubscription(int channel, AMQProtocolSession protocolSession, AMQShortString consumerTag, boolean acks, - FieldTable filters, boolean noLocal, AMQQueue queue) throws AMQException; - - - Subscription createSubscription(int channel, AMQProtocolSession protocolSession, AMQShortString consumerTag) - throws AMQException; -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/SubscriptionImpl.java b/java/broker/src/main/java/org/apache/qpid/server/queue/SubscriptionImpl.java deleted file mode 100644 index 1cebf08fa6..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/SubscriptionImpl.java +++ /dev/null @@ -1,676 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.queue; - -import java.util.Queue; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.common.AMQPFilterTypes; -import org.apache.qpid.common.ClientProperties; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.output.ProtocolOutputConverter; -import org.apache.qpid.server.filter.FilterManager; -import org.apache.qpid.server.filter.FilterManagerFactory; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.store.StoreContext; -import org.apache.qpid.util.ConcurrentLinkedQueueAtomicSize; -import org.apache.qpid.util.MessageQueue; -import org.apache.qpid.util.ConcurrentLinkedMessageQueueAtomicSize; - -/** - * Encapsulation of a supscription to a queue. <p/> Ties together the protocol session of a subscriber, the consumer tag - * that was given out by the broker and the channel id. <p/> - */ -public class SubscriptionImpl implements Subscription -{ - - private static final Logger _suspensionlogger = Logger.getLogger("Suspension"); - private static final Logger _logger = Logger.getLogger(SubscriptionImpl.class); - - public final AMQChannel channel; - - public final AMQProtocolSession protocolSession; - - public final AMQShortString consumerTag; - - private final Object _sessionKey; - - private MessageQueue<AMQMessage> _messages; - - private Queue<AMQMessage> _resendQueue; - - private final boolean _noLocal; - - /** True if messages need to be acknowledged */ - private final boolean _acks; - private FilterManager _filters; - private final boolean _isBrowser; - private final Boolean _autoClose; - private boolean _sentClose = false; - - private static final String CLIENT_PROPERTIES_INSTANCE = ClientProperties.instance.toString(); - - private AMQQueue _queue; - private final AtomicBoolean _sendLock = new AtomicBoolean(false); - - - public static class Factory implements SubscriptionFactory - { - public Subscription createSubscription(int channel, AMQProtocolSession protocolSession, - AMQShortString consumerTag, boolean acks, FieldTable filters, - boolean noLocal, AMQQueue queue) throws AMQException - { - return new SubscriptionImpl(channel, protocolSession, consumerTag, acks, filters, noLocal, queue); - } - - public SubscriptionImpl createSubscription(int channel, AMQProtocolSession protocolSession, AMQShortString consumerTag) - throws AMQException - { - return new SubscriptionImpl(channel, protocolSession, consumerTag, false, null, false, null); - } - } - - public SubscriptionImpl(int channelId, AMQProtocolSession protocolSession, - AMQShortString consumerTag, boolean acks) - throws AMQException - { - this(channelId, protocolSession, consumerTag, acks, null, false, null); - } - - public SubscriptionImpl(int channelId, AMQProtocolSession protocolSession, - AMQShortString consumerTag, boolean acks, FieldTable filters, - boolean noLocal, AMQQueue queue) - throws AMQException - { - AMQChannel channel = protocolSession.getChannel(channelId); - if (channel == null) - { - throw new AMQException(AMQConstant.NOT_FOUND, "channel :" + channelId + " not found in protocol session", null); - } - - this.channel = channel; - this.protocolSession = protocolSession; - this.consumerTag = consumerTag; - _sessionKey = protocolSession.getKey(); - _acks = acks; - _noLocal = noLocal; - _queue = queue; - - _filters = FilterManagerFactory.createManager(filters); - - - if (_filters != null) - { - Object isBrowser = filters.get(AMQPFilterTypes.NO_CONSUME.getValue()); - if (isBrowser != null) - { - _isBrowser = (Boolean) isBrowser; - } - else - { - _isBrowser = false; - } - } - else - { - _isBrowser = false; - } - - - if (_filters != null) - { - Object autoClose = filters.get(AMQPFilterTypes.AUTO_CLOSE.getValue()); - if (autoClose != null) - { - _autoClose = (Boolean) autoClose; - } - else - { - _autoClose = false; - } - } - else - { - _autoClose = false; - } - - - if (filtersMessages()) - { - _messages = new ConcurrentLinkedMessageQueueAtomicSize<AMQMessage>(); - } - else - { - // Reference the DeliveryManager - _messages = null; - } - } - - - public SubscriptionImpl(int channel, AMQProtocolSession protocolSession, - AMQShortString consumerTag) - throws AMQException - { - this(channel, protocolSession, consumerTag, false); - } - - public boolean equals(Object o) - { - return (o instanceof SubscriptionImpl) && equals((SubscriptionImpl) o); - } - - /** - * Equality holds if the session matches and the channel and consumer tag are the same. - * - * @param psc The subscriptionImpl to compare - * - * @return equality - */ - private boolean equals(SubscriptionImpl psc) - { - return _sessionKey.equals(psc._sessionKey) - && psc.channel == channel - && psc.consumerTag.equals(consumerTag); - } - - public int hashCode() - { - return _sessionKey.hashCode(); - } - - public String toString() - { - String subscriber = "[channel=" + channel + - ", consumerTag=" + consumerTag + - ", session=" + protocolSession.getKey() + - ", resendQueue=" + (_resendQueue != null); - - if (_resendQueue != null) - { - subscriber += ", resendSize=" + _resendQueue.size(); - } - - - return subscriber + "]"; - } - - /** - * This method can be called by each of the publisher threads. As a result all changes to the channel object must be - * thread safe. - * - * @param msg The message to send - * @param queue the Queue it has been sent from - * - * @throws AMQException - */ - public void send(AMQMessage msg, AMQQueue queue) throws AMQException - { - if (msg != null) - { - if (_isBrowser) - { - sendToBrowser(msg, queue); - } - else - { - sendToConsumer(channel.getStoreContext(), msg, queue); - } - } - else - { - _logger.error("Attempt to send Null message", new NullPointerException()); - } - } - - private void sendToBrowser(AMQMessage msg, AMQQueue queue) throws AMQException - { - // We don't decrement the reference here as we don't want to consume the message - // but we do want to send it to the client. - - synchronized (channel) - { - long deliveryTag = channel.getNextDeliveryTag(); - - // We don't need to add the message to the unacknowledgedMap as we don't need to know if the client - // received the message. If it is lost in transit that is not important. -// if (_acks) -// { -// channel.addUnacknowledgedBrowsedMessage(msg, deliveryTag, consumerTag, queue); -// } - - if (_sendLock.get()) - { - _logger.error("Sending " + msg + " when subscriber(" + this + ") is closed!"); - } - - protocolSession.getProtocolOutputConverter().writeDeliver(msg, channel.getChannelId(), deliveryTag, consumerTag); - } - } - - private void sendToConsumer(StoreContext storeContext, AMQMessage msg, AMQQueue queue) - throws AMQException - { - try - { // if we do not need to wait for client acknowledgements - // we can decrement the reference count immediately. - - // By doing this _before_ the send we ensure that it - // doesn't get sent if it can't be dequeued, preventing - // duplicate delivery on recovery. - - // The send may of course still fail, in which case, as - // the message is unacked, it will be lost. - if (!_acks) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("No ack mode so dequeuing message immediately: " + msg.getMessageId()); - } - queue.dequeue(storeContext, msg); - } - - synchronized (channel) - { - long deliveryTag = channel.getNextDeliveryTag(); - - if (_sendLock.get()) - { - _logger.error("Sending " + msg + " when subscriber(" + this + ") is closed!"); - } - - if (_acks) - { - channel.addUnacknowledgedMessage(msg, deliveryTag, consumerTag, queue); - } - - protocolSession.getProtocolOutputConverter().writeDeliver(msg, channel.getChannelId(), deliveryTag, consumerTag); - - } - } - finally - { - //Only set delivered if it actually was writen successfully.. - // using a try->finally would set it even if an error occured. - // Is this what we want? - - msg.setDeliveredToConsumer(); - } - } - - public boolean isSuspended() - { -// if (_suspensionlogger.isInfoEnabled()) -// { -// if (channel.isSuspended()) -// { -// _suspensionlogger.debug("Subscription(" + debugIdentity() + ") channel's is susupended"); -// } -// if (_sendLock.get()) -// { -// _suspensionlogger.debug("Subscription(" + debugIdentity() + ") has sendLock set so closing."); -// } -// } - return channel.isSuspended() || _sendLock.get(); - } - - /** - * Callback indicating that a queue has been deleted. - * - * @param queue The queue to delete - */ - public void queueDeleted(AMQQueue queue) throws AMQException - { - channel.queueDeleted(queue); - } - - public boolean filtersMessages() - { - return _filters != null || _noLocal; - } - - public boolean hasInterest(AMQMessage msg) - { - //check that the message hasn't been rejected - if (msg.isRejectedBy(this)) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Subscription:" + debugIdentity() + " rejected message:" + msg.debugIdentity()); - } -// return false; - } - - final AMQProtocolSession publisher = msg.getPublisher(); - - //todo - client id should be recoreded and this test removed but handled below - if (_noLocal && publisher != null) - { - // We don't want local messages so check to see if message is one we sent - Object localInstance; - Object msgInstance; - - if ((protocolSession.getClientProperties() != null) && - (localInstance = protocolSession.getClientProperties().getObject(CLIENT_PROPERTIES_INSTANCE)) != null) - { - - if ((publisher.getClientProperties() != null) && - (msgInstance = publisher.getClientProperties().getObject(CLIENT_PROPERTIES_INSTANCE)) != null) - { - if (localInstance == msgInstance || localInstance.equals(msgInstance)) - { -// if (_logger.isTraceEnabled()) -// { -// _logger.trace("(" + debugIdentity() + ") has no interest as it is a local message(" + -// msg.debugIdentity() + ")"); -// } - return false; - } - } - } - else - { - - localInstance = protocolSession.getClientIdentifier(); - //todo - client id should be recoreded and this test removed but handled here - - msgInstance = publisher.getClientIdentifier(); - if (localInstance == msgInstance || ((localInstance != null) && localInstance.equals(msgInstance))) - { -// if (_logger.isTraceEnabled()) -// { -// _logger.trace("(" + debugIdentity() + ") has no interest as it is a local message(" + -// msg.debugIdentity() + ")"); -// } - return false; - } - } - - - } - - - if (_logger.isTraceEnabled()) - { - _logger.trace("(" + debugIdentity() + ") checking filters for message (" + msg.debugIdentity()); - } - return checkFilters(msg); - - } - - private String id = String.valueOf(System.identityHashCode(this)); - - private String debugIdentity() - { - return id; - } - - private boolean checkFilters(AMQMessage msg) - { - if (_filters != null) - { -// if (_logger.isTraceEnabled()) -// { -// _logger.trace("(" + debugIdentity() + ") has filters."); -// } - return _filters.allAllow(msg); - } - else - { -// if (_logger.isTraceEnabled()) -// { -// _logger.trace("(" + debugIdentity() + ") has no filters"); -// } - - return true; - } - } - - public Queue<AMQMessage> getPreDeliveryQueue() - { - return _messages; - } - - public void enqueueForPreDelivery(AMQMessage msg, boolean deliverFirst) - { - if (_messages != null) - { - if (deliverFirst) - { - _messages.pushHead(msg); - } - else - { - _messages.offer(msg); - } - } - } - - public boolean isAutoClose() - { - return _autoClose; - } - - public void close() - { - boolean closed = false; - synchronized (_sendLock) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Setting SendLock true:" + debugIdentity()); - } - - closed = _sendLock.getAndSet(true); - } - - if (closed) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Called close() on a closed subscription"); - } - - return; - } - - if (_logger.isInfoEnabled()) - { - _logger.info("Closing subscription (" + debugIdentity() + "):" + this); - } - - if (_resendQueue != null && !_resendQueue.isEmpty()) - { - if (_logger.isInfoEnabled()) - { - _logger.info("Requeuing closing subscription (" + debugIdentity() + "):" + this); - } - requeue(); - } - - //remove references in PDQ - if (_messages != null) - { - if (_logger.isInfoEnabled()) - { - _logger.info("Clearing PDQ (" + debugIdentity() + "):" + this); - } - - _messages.clear(); - } - } - - private void autoclose() - { - close(); - - if (_autoClose && !_sentClose) - { - _logger.info("Closing autoclose subscription (" + debugIdentity() + "):" + this); - - ProtocolOutputConverter converter = protocolSession.getProtocolOutputConverter(); - converter.confirmConsumerAutoClose(channel.getChannelId(), consumerTag); - _sentClose = true; - - //fixme JIRA do this better - try - { - channel.unsubscribeConsumer(protocolSession, consumerTag); - } - catch (AMQException e) - { - // Occurs if we cannot find the subscriber in the channel with protocolSession and consumerTag. - } - } - } - - private void requeue() - { - if (_queue != null) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Requeuing :" + _resendQueue.size() + " messages"); - } - - while (!_resendQueue.isEmpty()) - { - AMQMessage resent = _resendQueue.poll(); - - if (_logger.isTraceEnabled()) - { - _logger.trace("Removed for resending:" + resent.debugIdentity()); - } - - resent.release(_queue); - _queue.subscriberHasPendingResend(false, this, resent); - - try - { - channel.getTransactionalContext().deliver(resent, _queue, true); - } - catch (AMQException e) - { - _logger.error("MESSAGE LOSS : Unable to re-deliver messages", e); - } - } - - if (!_resendQueue.isEmpty()) - { - _logger.error("[MESSAGES LOST]Unable to re-deliver messages as queue is null."); - } - - _queue.subscriberHasPendingResend(false, this, null); - } - else - { - if (!_resendQueue.isEmpty()) - { - _logger.error("Unable to re-deliver messages as queue is null."); - } - } - - // Clear the messages - _resendQueue = null; - } - - - public boolean isClosed() - { - return _sendLock.get(); // This rather than _close is used to signify the subscriber is now closed. - } - - public boolean isBrowser() - { - return _isBrowser; - } - - public boolean wouldSuspend(AMQMessage msg) - { - return channel.wouldSuspend(msg); - } - - public Queue<AMQMessage> getResendQueue() - { - if (_resendQueue == null) - { - _resendQueue = new ConcurrentLinkedQueueAtomicSize<AMQMessage>(); - } - return _resendQueue; - } - - - public Queue<AMQMessage> getNextQueue(Queue<AMQMessage> messages) - { - if (_resendQueue != null && !_resendQueue.isEmpty()) - { - return _resendQueue; - } - - if (filtersMessages()) - { - if (isAutoClose()) - { - if (_messages.isEmpty()) - { - autoclose(); - return null; - } - } - return _messages; - } - else // we want the DM queue - { - return messages; - } - } - - public void addToResendQueue(AMQMessage msg) - { - // add to our resend queue - getResendQueue().add(msg); - - // Mark Queue has having content. - if (_queue == null) - { - _logger.error("Queue is null won't be able to resend messages"); - } - else - { - _queue.subscriberHasPendingResend(true, this, msg); - } - } - - public Object getSendLock() - { - return _sendLock; - } - - public AMQChannel getChannel() - { - return channel; - } - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/SubscriptionManager.java b/java/broker/src/main/java/org/apache/qpid/server/queue/SubscriptionManager.java deleted file mode 100644 index 4df88baebc..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/SubscriptionManager.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.queue; - -import java.util.List; - -/** - * Abstraction of actor that will determine the subscriber to whom - * a message will be sent. - */ -public interface SubscriptionManager -{ - public List<Subscription> getSubscriptions(); - public boolean hasActiveSubscribers(); - public Subscription nextSubscriber(AMQMessage msg); -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/SubscriptionSet.java b/java/broker/src/main/java/org/apache/qpid/server/queue/SubscriptionSet.java deleted file mode 100644 index b500247fa4..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/SubscriptionSet.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.queue; - -import java.util.List; -import java.util.ListIterator; -import java.util.concurrent.CopyOnWriteArrayList; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; - -/** Holds a set of subscriptions for a queue and manages the round robin-ing of deliver etc. */ -class SubscriptionSet implements WeightedSubscriptionManager -{ - private static final Logger _log = Logger.getLogger(SubscriptionSet.class); - - /** List of registered subscribers */ - private List<Subscription> _subscriptions = new CopyOnWriteArrayList<Subscription>(); - - /** Used to control the round robin delivery of content */ - private int _currentSubscriber; - private final Object _subscriptionsChange = new Object(); - - - /** Accessor for unit tests. */ - int getCurrentSubscriber() - { - return _currentSubscriber; - } - - public void addSubscriber(Subscription subscription) - { - synchronized (_subscriptionsChange) - { - _subscriptions.add(subscription); - } - } - - /** - * Remove the subscription, returning it if it was found - * - * @param subscription - * - * @return null if no match was found - */ - public Subscription removeSubscriber(Subscription subscription) - { - // TODO: possibly need O(1) operation here. - - Subscription sub = null; - synchronized (_subscriptionsChange) - { - int subIndex = _subscriptions.indexOf(subscription); - - if (subIndex != -1) - { - //we can't just return the passed in subscription as it is a new object - // and doesn't contain the stored state we need. - //NOTE while this may be removed now anyone with an iterator will still have it in the list!! - sub = _subscriptions.remove(subIndex); - } - else - { - _log.error("Unable to remove from index(" + subIndex + ")subscription:" + subscription); - } - } - if (sub != null) - { - return sub; - } - else - { - debugDumpSubscription(subscription); - return null; - } - } - - private void debugDumpSubscription(Subscription subscription) - { - if (_log.isDebugEnabled()) - { - _log.debug("Subscription " + subscription + " not found. Dumping subscriptions:"); - for (Subscription s : _subscriptions) - { - _log.debug("Subscription: " + s); - } - _log.debug("Subscription dump complete"); - } - } - - /** - * Return the next unsuspended subscription or null if not found. <p/> Performance note: This method can scan all - * items twice when looking for a subscription that is not suspended. The worst case occcurs when all subscriptions - * are suspended. However, it is does this without synchronisation and subscriptions may be added and removed - * concurrently. Also note that because of race conditions and when subscriptions are removed between calls to - * nextSubscriber, the IndexOutOfBoundsException also causes the scan to start at the beginning. - */ - public Subscription nextSubscriber(AMQMessage msg) - { - if (_subscriptions.isEmpty()) - { - return null; - } - - try - { - final Subscription result = nextSubscriberImpl(msg); - if (result == null) - { - _currentSubscriber = 0; - return nextSubscriberImpl(msg); - } - else - { - return result; - } - } - catch (IndexOutOfBoundsException e) - { - _currentSubscriber = 0; - return nextSubscriber(msg); - } - } - - private Subscription nextSubscriberImpl(AMQMessage msg) - { - final ListIterator<Subscription> iterator = _subscriptions.listIterator(_currentSubscriber); - while (iterator.hasNext()) - { - Subscription subscription = iterator.next(); - ++_currentSubscriber; - subscriberScanned(); - - if (!(subscription.isSuspended() || subscription.wouldSuspend(msg))) - { - if (subscription.hasInterest(msg)) - { - // if the queue is not empty then this client is ready to receive a message. - //FIXME the queue could be full of sent messages. - // Either need to clean all PDQs after sending a message - // OR have a clean up thread that runs the PDQs expunging the messages. - if (!subscription.filtersMessages() || subscription.getPreDeliveryQueue().isEmpty()) - { - return subscription; - } - } - } - } - - return null; - } - - /** Overridden in test classes. */ - protected void subscriberScanned() - { - } - - public boolean isEmpty() - { - return _subscriptions.isEmpty(); - } - - public List<Subscription> getSubscriptions() - { - return _subscriptions; - } - - public boolean hasActiveSubscribers() - { - for (Subscription s : _subscriptions) - { - if (!s.isSuspended()) - { - return true; - } - } - return false; - } - - public int getWeight() - { - int count = 0; - for (Subscription s : _subscriptions) - { - if (!s.isSuspended()) - { - count++; - } - } - return count; - } - - /** - * Notification that a queue has been deleted. This is called so that the subscription can inform the channel, which - * in turn can update its list of unacknowledged messages. - * - * @param queue - */ - public void queueDeleted(AMQQueue queue) throws AMQException - { - for (Subscription s : _subscriptions) - { - s.queueDeleted(queue); - } - } - - int size() - { - return _subscriptions.size(); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/TransientMessageData.java b/java/broker/src/main/java/org/apache/qpid/server/queue/TransientMessageData.java deleted file mode 100644 index 79ee6b93a3..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/TransientMessageData.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.queue; - -import java.util.LinkedList; -import java.util.List; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.abstraction.MessagePublishInfo; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.ContentHeaderBody; - -/** - * Contains data that is only used in AMQMessage transiently, e.g. while the content - * body fragments are arriving. - * - * Having this data stored in a separate class means that the AMQMessage class avoids - * the small overhead of numerous guaranteed-null references. - * - * @author Apache Software Foundation - */ -public class TransientMessageData -{ - /** - * Stored temporarily until the header has been received at which point it is used when - * constructing the handle - */ - private MessagePublishInfo _messagePublishInfo; - - /** - * Also stored temporarily. - */ - private ContentHeaderBody _contentHeaderBody; - - /** - * Keeps a track of how many bytes we have received in body frames - */ - private long _bodyLengthReceived = 0; - - /** - * This is stored during routing, to know the queues to which this message should immediately be - * delivered. It is <b>cleared after delivery has been attempted</b>. Any persistent record of destinations is done - * by the message handle. - */ - private List<AMQQueue> _destinationQueues = new LinkedList<AMQQueue>(); - - public MessagePublishInfo getMessagePublishInfo() - { - return _messagePublishInfo; - } - - public void setMessagePublishInfo(MessagePublishInfo messagePublishInfo) - { - _messagePublishInfo = messagePublishInfo; - } - - public List<AMQQueue> getDestinationQueues() - { - return _destinationQueues; - } - - public void setDestinationQueues(List<AMQQueue> destinationQueues) - { - _destinationQueues = destinationQueues; - } - - public ContentHeaderBody getContentHeaderBody() - { - return _contentHeaderBody; - } - - public void setContentHeaderBody(ContentHeaderBody contentHeaderBody) - { - _contentHeaderBody = contentHeaderBody; - } - - public long getBodyLengthReceived() - { - return _bodyLengthReceived; - } - - public void addBodyLength(int value) - { - _bodyLengthReceived += value; - } - - public boolean isAllContentReceived() throws AMQException - { - return _bodyLengthReceived == _contentHeaderBody.bodySize; - } - - public void addDestinationQueue(AMQQueue queue) - { - _destinationQueues.add(queue); - } - - public boolean isPersistent() - { - //todo remove literal values to a constant file such as AMQConstants in common - return _contentHeaderBody.properties instanceof BasicContentHeaderProperties && - ((BasicContentHeaderProperties) _contentHeaderBody.properties).getDeliveryMode() == 2; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/WeakReferenceMessageHandle.java b/java/broker/src/main/java/org/apache/qpid/server/queue/WeakReferenceMessageHandle.java deleted file mode 100644 index 88eb891a20..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/WeakReferenceMessageHandle.java +++ /dev/null @@ -1,232 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.queue; - -import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.abstraction.MessagePublishInfo; -import org.apache.qpid.framing.abstraction.ContentChunk; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.StoreContext; - -/** - */ -public class WeakReferenceMessageHandle implements AMQMessageHandle -{ - private WeakReference<ContentHeaderBody> _contentHeaderBody; - - private WeakReference<MessagePublishInfo> _messagePublishInfo; - - private List<WeakReference<ContentChunk>> _contentBodies; - - private boolean _redelivered; - - private final MessageStore _messageStore; - - private long _arrivalTime; - - - public WeakReferenceMessageHandle(MessageStore messageStore) - { - _messageStore = messageStore; - } - - public ContentHeaderBody getContentHeaderBody(StoreContext context, Long messageId) throws AMQException - { - ContentHeaderBody chb = (_contentHeaderBody != null ? _contentHeaderBody.get() : null); - if (chb == null) - { - MessageMetaData mmd = loadMessageMetaData(context, messageId); - chb = mmd.getContentHeaderBody(); - } - return chb; - } - - private MessageMetaData loadMessageMetaData(StoreContext context, Long messageId) - throws AMQException - { - MessageMetaData mmd = _messageStore.getMessageMetaData(context, messageId); - populateFromMessageMetaData(mmd); - return mmd; - } - - private void populateFromMessageMetaData(MessageMetaData mmd) - { - _arrivalTime = mmd.getArrivalTime(); - _contentHeaderBody = new WeakReference<ContentHeaderBody>(mmd.getContentHeaderBody()); - _messagePublishInfo = new WeakReference<MessagePublishInfo>(mmd.getMessagePublishInfo()); - } - - public int getBodyCount(StoreContext context, Long messageId) throws AMQException - { - if (_contentBodies == null) - { - MessageMetaData mmd = _messageStore.getMessageMetaData(context, messageId); - int chunkCount = mmd.getContentChunkCount(); - _contentBodies = new ArrayList<WeakReference<ContentChunk>>(chunkCount); - for (int i = 0; i < chunkCount; i++) - { - _contentBodies.add(new WeakReference<ContentChunk>(null)); - } - } - return _contentBodies.size(); - } - - public long getBodySize(StoreContext context, Long messageId) throws AMQException - { - return getContentHeaderBody(context, messageId).bodySize; - } - - public ContentChunk getContentChunk(StoreContext context, Long messageId, int index) throws AMQException, IllegalArgumentException - { - if (index > _contentBodies.size() - 1) - { - throw new IllegalArgumentException("Index " + index + " out of valid range 0 to " + - (_contentBodies.size() - 1)); - } - WeakReference<ContentChunk> wr = _contentBodies.get(index); - ContentChunk cb = wr.get(); - if (cb == null) - { - cb = _messageStore.getContentBodyChunk(context, messageId, index); - _contentBodies.set(index, new WeakReference<ContentChunk>(cb)); - } - return cb; - } - - /** - * Content bodies are set <i>before</i> the publish and header frames - * - * @param storeContext - * @param messageId - * @param contentChunk - * @param isLastContentBody - * @throws AMQException - */ - public void addContentBodyFrame(StoreContext storeContext, Long messageId, ContentChunk contentChunk, boolean isLastContentBody) throws AMQException - { - if (_contentBodies == null && isLastContentBody) - { - _contentBodies = new ArrayList<WeakReference<ContentChunk>>(1); - } - else - { - if (_contentBodies == null) - { - _contentBodies = new LinkedList<WeakReference<ContentChunk>>(); - } - } - _contentBodies.add(new WeakReference<ContentChunk>(contentChunk)); - _messageStore.storeContentBodyChunk(storeContext, messageId, _contentBodies.size() - 1, - contentChunk, isLastContentBody); - } - - public MessagePublishInfo getMessagePublishInfo(StoreContext context, Long messageId) throws AMQException - { - MessagePublishInfo bpb = (_messagePublishInfo != null ? _messagePublishInfo.get() : null); - if (bpb == null) - { - MessageMetaData mmd = loadMessageMetaData(context, messageId); - - bpb = mmd.getMessagePublishInfo(); - } - return bpb; - } - - public boolean isRedelivered() - { - return _redelivered; - } - - public void setRedelivered(boolean redelivered) - { - _redelivered = redelivered; - } - - public boolean isPersistent(StoreContext context, Long messageId) throws AMQException - { - //todo remove literal values to a constant file such as AMQConstants in common - ContentHeaderBody chb = getContentHeaderBody(context, messageId); - return chb.properties instanceof BasicContentHeaderProperties && - ((BasicContentHeaderProperties) chb.properties).getDeliveryMode() == 2; - } - - /** - * This is called when all the content has been received. - * - * @param publishBody - * @param contentHeaderBody - * @throws AMQException - */ - public void setPublishAndContentHeaderBody(StoreContext storeContext, Long messageId, MessagePublishInfo publishBody, - ContentHeaderBody contentHeaderBody) - throws AMQException - { - // if there are no content bodies the list will be null so we must - // create en empty list here - if (contentHeaderBody.bodySize == 0) - { - _contentBodies = new LinkedList<WeakReference<ContentChunk>>(); - } - - final long arrivalTime = System.currentTimeMillis(); - - - MessageMetaData mmd = new MessageMetaData(publishBody, contentHeaderBody, _contentBodies.size(), arrivalTime); - - _messageStore.storeMessageMetaData(storeContext, messageId, mmd); - - populateFromMessageMetaData(mmd); - } - - public void removeMessage(StoreContext storeContext, Long messageId) throws AMQException - { - _messageStore.removeMessage(storeContext, messageId); - } - - public void enqueue(StoreContext storeContext, Long messageId, AMQQueue queue) throws AMQException - { - _messageStore.enqueueMessage(storeContext, queue.getName(), messageId); - } - - public void dequeue(StoreContext storeContext, Long messageId, AMQQueue queue) throws AMQException - { - _messageStore.dequeueMessage(storeContext, queue.getName(), messageId); - } - - public long getArrivalTime() - { - return _arrivalTime; - } - - - // added by Arnaud - public byte[] getMessagePayload() - { - return new byte[0]; //To change body of implemented methods use File | Settings | File Templates. - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/WeightedSubscriptionManager.java b/java/broker/src/main/java/org/apache/qpid/server/queue/WeightedSubscriptionManager.java deleted file mode 100644 index 6c71571807..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/WeightedSubscriptionManager.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.queue; - -public interface WeightedSubscriptionManager extends SubscriptionManager -{ - public int getWeight(); -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/registry/ApplicationRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/registry/ApplicationRegistry.java deleted file mode 100644 index a70505ff6c..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/registry/ApplicationRegistry.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.registry; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import org.apache.commons.configuration.Configuration; -import org.apache.log4j.Logger; -import org.apache.qpid.server.configuration.Configurator; -import org.apache.qpid.server.virtualhost.VirtualHost; - -/** - * An abstract application registry that provides access to configuration information and handles the - * construction and caching of configurable objects. - * <p/> - * Subclasses should handle the construction of the "registered objects" such as the exchange registry. - */ -public abstract class ApplicationRegistry implements IApplicationRegistry -{ - private static final Logger _logger = Logger.getLogger(ApplicationRegistry.class); - - private static Map<Integer, IApplicationRegistry> _instanceMap = new HashMap<Integer, IApplicationRegistry>(); - - private final Map<Class<?>, Object> _configuredObjects = new HashMap<Class<?>, Object>(); - - protected final Configuration _configuration; - - public static final int DEFAULT_INSTANCE = 1; - public static final String DEFAULT_APPLICATION_REGISTRY = "org.apache.qpid.server.util.NullApplicationRegistry"; - public static String _APPLICATION_REGISTRY = DEFAULT_APPLICATION_REGISTRY; - - static - { - Runtime.getRuntime().addShutdownHook(new Thread(new ShutdownService())); - } - - private static class ShutdownService implements Runnable - { - public void run() - { - _logger.info("Shutting down application registries..."); - try - { - synchronized (_instanceMap) - { - Iterator<IApplicationRegistry> keyIterator = _instanceMap.values().iterator(); - - while (keyIterator.hasNext()) - { - IApplicationRegistry instance = keyIterator.next(); - - instance.close(); - } - } - } - catch (Exception e) - { - _logger.error("Error shutting down message store: " + e, e); - } - } - } - - public static void initialise(IApplicationRegistry instance) throws Exception - { - initialise(instance, DEFAULT_INSTANCE); - } - - public static void initialise(IApplicationRegistry instance, int instanceID) throws Exception - { - synchronized (_instanceMap) - { - if (instance != null) - { - _logger.info("Initialising Application Registry:" + instanceID); - _instanceMap.put(instanceID, instance); - - try - { - instance.initialise(); - } - catch (Exception e) - { - _instanceMap.remove(instanceID); - throw e; - } - } - else - { - remove(instanceID); - } - } - } - - public static void remove(int instanceID) - { - synchronized (_instanceMap) - { - try - { - _instanceMap.get(instanceID).close(); - } - catch (Exception e) - { - - } - finally - { - _instanceMap.remove(instanceID); - } - } - } - - - protected ApplicationRegistry(Configuration configuration) - { - _configuration = configuration; - } - - public static IApplicationRegistry getInstance() - { - return getInstance(DEFAULT_INSTANCE); - } - - public static IApplicationRegistry getInstance(int instanceID) - { - synchronized (_instanceMap) - { - IApplicationRegistry instance = _instanceMap.get(instanceID); - - if (instance == null) - { - try - { - _logger.info("Creating DEFAULT_APPLICATION_REGISTRY: " + _APPLICATION_REGISTRY + " : Instance:" + instanceID); - IApplicationRegistry registry = (IApplicationRegistry) Class.forName(_APPLICATION_REGISTRY).getConstructor((Class[]) null).newInstance((Object[]) null); - ApplicationRegistry.initialise(registry, instanceID); - _logger.info("Initialised Application Registry:" + instanceID); - return registry; - } - catch (Exception e) - { - _logger.error("Error configuring application: " + e, e); - //throw new AMQBrokerCreationException(instanceID, "Unable to create Application Registry instance " + instanceID); - throw new RuntimeException("Unable to create Application Registry", e); - } - } - else - { - return instance; - } - } - } - - public void close() throws Exception - { - for(VirtualHost virtualHost : getVirtualHostRegistry().getVirtualHosts()) - { - virtualHost.close(); - } - - // close the rmi registry(if any) started for management - if (getInstance().getManagedObjectRegistry() != null) - { - getInstance().getManagedObjectRegistry().close(); - } - } - - public Configuration getConfiguration() - { - return _configuration; - } - - public <T> T getConfiguredObject(Class<T> instanceType) - { - T instance = (T) _configuredObjects.get(instanceType); - if (instance == null) - { - try - { - instance = instanceType.newInstance(); - } - catch (Exception e) - { - _logger.error("Unable to instantiate configuration class " + instanceType + " - ensure it has a public default constructor"); - throw new IllegalArgumentException("Unable to instantiate configuration class " + instanceType + " - ensure it has a public default constructor", e); - } - Configurator.configure(instance); - _configuredObjects.put(instanceType, instance); - } - return instance; - } - - - - public static void setDefaultApplicationRegistry(String clazz) - { - _APPLICATION_REGISTRY = clazz; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/registry/ConfigurationFileApplicationRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/registry/ConfigurationFileApplicationRegistry.java deleted file mode 100644 index 1cca259a8d..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/registry/ConfigurationFileApplicationRegistry.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.registry; - -import java.io.File; -import java.util.Collection; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.apache.commons.configuration.CompositeConfiguration; -import org.apache.commons.configuration.Configuration; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.configuration.SystemConfiguration; -import org.apache.commons.configuration.XMLConfiguration; -import org.apache.qpid.server.management.JMXManagedObjectRegistry; -import org.apache.qpid.server.management.ManagedObjectRegistry; -import org.apache.qpid.server.management.ManagementConfiguration; -import org.apache.qpid.server.management.NoopManagedObjectRegistry; -import org.apache.qpid.server.security.auth.manager.AuthenticationManager; -import org.apache.qpid.server.security.auth.database.ConfigurationFilePrincipalDatabaseManager; -import org.apache.qpid.server.security.auth.database.PrincipalDatabaseManager; -import org.apache.qpid.server.security.auth.manager.PrincipalDatabaseAuthenticationManager; -import org.apache.qpid.server.security.access.AccessManager; -import org.apache.qpid.server.security.access.AccessManagerImpl; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.virtualhost.VirtualHostRegistry; -import org.apache.qpid.AMQException; - -public class ConfigurationFileApplicationRegistry extends ApplicationRegistry -{ - - private ManagedObjectRegistry _managedObjectRegistry; - - private AuthenticationManager _authenticationManager; - - private AccessManager _accessManager; - - private PrincipalDatabaseManager _databaseManager; - - private VirtualHostRegistry _virtualHostRegistry; - - - private final Map<String, VirtualHost> _virtualHosts = new ConcurrentHashMap<String, VirtualHost>(); - - - public ConfigurationFileApplicationRegistry(File configurationURL) throws ConfigurationException - { - super(config(configurationURL)); - } - - // Our configuration class needs to make the interpolate method - // public so it can be called below from the config method. - private static class MyConfiguration extends CompositeConfiguration - { - public String interpolate(String obj) - { - return super.interpolate(obj); - } - } - - private static final Configuration config(File url) throws ConfigurationException - { - // We have to override the interpolate methods so that - // interpolation takes place accross the entirety of the - // composite configuration. Without doing this each - // configuration object only interpolates variables defined - // inside itself. - final MyConfiguration conf = new MyConfiguration(); - conf.addConfiguration(new SystemConfiguration() - { - protected String interpolate(String o) - { - return conf.interpolate(o); - } - }); - conf.addConfiguration(new XMLConfiguration(url) - { - protected String interpolate(String o) - { - return conf.interpolate(o); - } - }); - return conf; - } - - public void initialise() throws Exception - { - initialiseManagedObjectRegistry(); - - _virtualHostRegistry = new VirtualHostRegistry(); - - _accessManager = new AccessManagerImpl("default", _configuration); - - _databaseManager = new ConfigurationFilePrincipalDatabaseManager(); - - _authenticationManager = new PrincipalDatabaseAuthenticationManager(null, null); - - _databaseManager.initialiseManagement(_configuration); - - _managedObjectRegistry.start(); - - initialiseVirtualHosts(); - - } - - private void initialiseVirtualHosts() throws Exception - { - for (String name : getVirtualHostNames()) - { - - _virtualHostRegistry.registerVirtualHost(new VirtualHost(name, getConfiguration().subset("virtualhosts.virtualhost." + name))); - } - } - - private void initialiseManagedObjectRegistry() throws AMQException - { - ManagementConfiguration config = getConfiguredObject(ManagementConfiguration.class); - if (config.enabled) - { - _managedObjectRegistry = new JMXManagedObjectRegistry(); - } - else - { - _managedObjectRegistry = new NoopManagedObjectRegistry(); - } - } - - - public VirtualHostRegistry getVirtualHostRegistry() - { - return _virtualHostRegistry; - } - - public AccessManager getAccessManager() - { - return _accessManager; - } - - public ManagedObjectRegistry getManagedObjectRegistry() - { - return _managedObjectRegistry; - } - - public PrincipalDatabaseManager getDatabaseManager() - { - return _databaseManager; - } - - public AuthenticationManager getAuthenticationManager() - { - return _authenticationManager; - } - - public Collection<String> getVirtualHostNames() - { - return getConfiguration().getList("virtualhosts.virtualhost.name"); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/registry/IApplicationRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/registry/IApplicationRegistry.java deleted file mode 100644 index 5a48431288..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/registry/IApplicationRegistry.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.registry; - -import java.util.Collection; - -import org.apache.commons.configuration.Configuration; -import org.apache.qpid.server.management.ManagedObjectRegistry; -import org.apache.qpid.server.security.auth.manager.AuthenticationManager; -import org.apache.qpid.server.security.auth.database.PrincipalDatabaseManager; -import org.apache.qpid.server.security.access.AccessManager; -import org.apache.qpid.server.virtualhost.VirtualHostRegistry; - -public interface IApplicationRegistry -{ - /** - * Initialise the application registry. All initialisation must be done in this method so that any components - * that need access to the application registry itself for initialisation are able to use it. Attempting to - * initialise in the constructor will lead to failures since the registry reference will not have been set. - */ - void initialise() throws Exception; - - void close() throws Exception; - - /** - * This gets access to a "configured object". A configured object has fields populated from a the configuration - * object (Commons Configuration) automatically, where it has the appropriate attributes defined on fields. - * Application registry implementations can choose the refresh strategy or caching approach. - * @param instanceType the type of object you want initialised. This must be unique - i.e. you can only - * have a single object of this type in the system. - * @return the configured object - */ - <T> T getConfiguredObject(Class<T> instanceType); - - /** - * Get the low level configuration. For use cases where the configured object approach is not required - * you can get the complete configuration information. - * @return a Commons Configuration instance - */ - Configuration getConfiguration(); - - ManagedObjectRegistry getManagedObjectRegistry(); - - PrincipalDatabaseManager getDatabaseManager(); - - AuthenticationManager getAuthenticationManager(); - - Collection<String> getVirtualHostNames(); - - VirtualHostRegistry getVirtualHostRegistry(); - - AccessManager getAccessManager(); -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/Passwd.java b/java/broker/src/main/java/org/apache/qpid/server/security/Passwd.java deleted file mode 100644 index f9e093dba7..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/Passwd.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.security; - -import org.apache.commons.codec.binary.Base64; - -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.DigestException; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.PrintStream; - -public class Passwd -{ - public static void main(String args[]) throws NoSuchAlgorithmException, DigestException, IOException - { - if (args.length != 2) - { - System.out.println("Passwd <username> <password>"); - System.exit(0); - } - - byte[] data = args[1].getBytes("utf-8"); - - MessageDigest md = MessageDigest.getInstance("MD5"); - - for (byte b : data) - { - md.update(b); - } - - byte[] digest = md.digest(); - - Base64 b64 = new Base64(); - - byte[] encoded = b64.encode(digest); - - output(args[0], encoded); - } - - private static void output(String user, byte[] encoded) throws IOException - { - -// File passwdFile = new File("qpid.passwd"); - - PrintStream ps = new PrintStream(System.out); - - user += ":"; - ps.write(user.getBytes("utf-8")); - - for (byte b : encoded) - { - ps.write(b); - } - - ps.println(); - - ps.flush(); - ps.close(); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/access/AMQUserManagementMBean.java b/java/broker/src/main/java/org/apache/qpid/server/security/access/AMQUserManagementMBean.java deleted file mode 100644 index 2dc7fcbc1e..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/access/AMQUserManagementMBean.java +++ /dev/null @@ -1,467 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.security.access; - -import org.apache.qpid.server.management.MBeanDescription; -import org.apache.qpid.server.management.AMQManagedObject; -import org.apache.qpid.server.management.MBeanOperation; -import org.apache.qpid.server.management.MBeanInvocationHandlerImpl; -import org.apache.qpid.server.security.auth.database.PrincipalDatabase; -import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal; -import org.apache.log4j.Logger; -import org.apache.commons.configuration.ConfigurationException; - -import javax.management.JMException; -import javax.management.remote.JMXPrincipal; -import javax.management.openmbean.TabularData; -import javax.management.openmbean.TabularDataSupport; -import javax.management.openmbean.TabularType; -import javax.management.openmbean.SimpleType; -import javax.management.openmbean.CompositeType; -import javax.management.openmbean.OpenType; -import javax.management.openmbean.OpenDataException; -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.CompositeDataSupport; -import javax.security.auth.login.AccountNotFoundException; -import javax.security.auth.Subject; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.FileOutputStream; -import java.util.Properties; -import java.util.List; -import java.util.Enumeration; -import java.util.Set; -import java.util.concurrent.locks.ReentrantLock; -import java.security.Principal; -import java.security.AccessControlContext; -import java.security.AccessController; - -/** MBean class for AMQUserManagementMBean. It implements all the management features exposed for managing users. */ -@MBeanDescription("User Management Interface") -public class AMQUserManagementMBean extends AMQManagedObject implements UserManagement -{ - - private static final Logger _logger = Logger.getLogger(AMQUserManagementMBean.class); - - private PrincipalDatabase _principalDatabase; - private String _accessFileName; - private Properties _accessRights; - // private File _accessFile; - private ReentrantLock _accessRightsUpdate = new ReentrantLock(); - - // Setup for the TabularType - static TabularType _userlistDataType; // Datatype for representing User Lists - - static CompositeType _userDataType; // Composite type for representing User - static String[] _userItemNames = {"Username", "read", "write", "admin"}; - - static - { - String[] userItemDesc = {"Broker Login username", "Management Console Read Permission", - "Management Console Write Permission", "Management Console Admin Permission"}; - - OpenType[] userItemTypes = new OpenType[4]; // User item types. - userItemTypes[0] = SimpleType.STRING; // For Username - userItemTypes[1] = SimpleType.BOOLEAN; // For Rights - Read - userItemTypes[2] = SimpleType.BOOLEAN; // For Rights - Write - userItemTypes[3] = SimpleType.BOOLEAN; // For Rights - Admin - String[] userDataIndex = {_userItemNames[0]}; - - try - { - _userDataType = - new CompositeType("User", "User Data", _userItemNames, userItemDesc, userItemTypes); - - _userlistDataType = new TabularType("Users", "List of users", _userDataType, userDataIndex); - } - catch (OpenDataException e) - { - _logger.error("Tabular data setup for viewing users incorrect."); - _userlistDataType = null; - } - } - - - public AMQUserManagementMBean() throws JMException - { - super(UserManagement.class, UserManagement.TYPE); - } - - public String getObjectInstanceName() - { - return UserManagement.TYPE; - } - - public boolean setPassword(String username, char[] password) - { - try - { - //delegate password changes to the Principal Database - return _principalDatabase.updatePassword(new UsernamePrincipal(username), password); - } - catch (AccountNotFoundException e) - { - _logger.warn("Attempt to set password of non-existant user'" + username + "'"); - return false; - } - } - - public boolean setRights(String username, boolean read, boolean write, boolean admin) - { - - if (_accessRights.get(username) == null) - { - // If the user doesn't exist in the user rights file check that they at least have an account. - if (_principalDatabase.getUser(username) == null) - { - return false; - } - } - - try - { - - _accessRightsUpdate.lock(); - - // Update the access rights - if (admin) - { - _accessRights.put(username, MBeanInvocationHandlerImpl.ADMIN); - } - else - { - if (read | write) - { - if (read) - { - _accessRights.put(username, MBeanInvocationHandlerImpl.READONLY); - } - if (write) - { - _accessRights.put(username, MBeanInvocationHandlerImpl.READWRITE); - } - } - else - { - _accessRights.remove(username); - } - } - - saveAccessFile(); - } - finally - { - if (_accessRightsUpdate.isHeldByCurrentThread()) - { - _accessRightsUpdate.unlock(); - } - } - - return true; - } - - public boolean createUser(String username, char[] password, boolean read, boolean write, boolean admin) - { - if (_principalDatabase.createPrincipal(new UsernamePrincipal(username), password)) - { - _accessRights.put(username, ""); - - return setRights(username, read, write, admin); - } - - return false; - } - - public boolean deleteUser(String username) - { - - try - { - if (_principalDatabase.deletePrincipal(new UsernamePrincipal(username))) - { - try - { - _accessRightsUpdate.lock(); - - _accessRights.remove(username); - saveAccessFile(); - } - finally - { - if (_accessRightsUpdate.isHeldByCurrentThread()) - { - _accessRightsUpdate.unlock(); - } - } - return true; - } - } - catch (AccountNotFoundException e) - { - _logger.warn("Attempt to delete user (" + username + ") that doesn't exist"); - } - - return false; - } - - public boolean reloadData() - { - try - { - try - { - loadAccessFile(); - } - catch (ConfigurationException e) - { - _logger.info("Reload failed due to:" + e); - return false; - } - - // Reload successful - return true; - } - catch (IOException e) - { - _logger.info("Reload failed due to:" + e); - // Reload unsuccessful - return false; - } - } - - - @MBeanOperation(name = "viewUsers", description = "All users with access rights to the system.") - public TabularData viewUsers() - { - // Table of users - // Username(string), Access rights Read,Write,Admin(bool,bool,bool) - - if (_userlistDataType == null) - { - _logger.warn("TabluarData not setup correctly"); - return null; - } - - List<Principal> users = _principalDatabase.getUsers(); - - TabularDataSupport userList = new TabularDataSupport(_userlistDataType); - - try - { - // Create the tabular list of message header contents - for (Principal user : users) - { - // Create header attributes list - - String rights = (String) _accessRights.get(user.getName()); - - Boolean read = false; - Boolean write = false; - Boolean admin = false; - - if (rights != null) - { - read = rights.equals(MBeanInvocationHandlerImpl.READONLY) - || rights.equals(MBeanInvocationHandlerImpl.READWRITE); - write = rights.equals(MBeanInvocationHandlerImpl.READWRITE); - admin = rights.equals(MBeanInvocationHandlerImpl.ADMIN); - } - - Object[] itemData = {user.getName(), read, write, admin}; - CompositeData messageData = new CompositeDataSupport(_userDataType, _userItemNames, itemData); - userList.put(messageData); - } - } - catch (OpenDataException e) - { - _logger.warn("Unable to create user list due to :" + e); - return null; - } - - return userList; - } - - /*** Broker Methods **/ - - /** - * setPrincipalDatabase - * - * @param database set The Database to use for user lookup - */ - public void setPrincipalDatabase(PrincipalDatabase database) - { - _principalDatabase = database; - } - - /** - * setAccessFile - * - * @param accessFile the file to use for updating. - * - * @throws java.io.IOException If the file cannot be accessed - * @throws org.apache.commons.configuration.ConfigurationException - * if checks on the file fail. - */ - public void setAccessFile(String accessFile) throws IOException, ConfigurationException - { - _accessFileName = accessFile; - - if (_accessFileName != null) - { - loadAccessFile(); - } - else - { - _logger.warn("Access rights file specified is null. Access rights not changed."); - } - } - - private void loadAccessFile() throws IOException, ConfigurationException - { - try - { - _accessRightsUpdate.lock(); - - Properties accessRights = new Properties(); - - File accessFile = new File(_accessFileName); - - if (!accessFile.exists()) - { - throw new ConfigurationException("'" + _accessFileName + "' does not exist"); - } - - if (!accessFile.canRead()) - { - throw new ConfigurationException("Cannot read '" + _accessFileName + "'."); - } - - if (!accessFile.canWrite()) - { - _logger.warn("Unable to write to access file '" + _accessFileName + "' changes will not be preserved."); - } - - accessRights.load(new FileInputStream(accessFile)); - checkAccessRights(accessRights); - setAccessRights(accessRights); - } - finally - { - if (_accessRightsUpdate.isHeldByCurrentThread()) - { - _accessRightsUpdate.unlock(); - } - } - } - - private void checkAccessRights(Properties accessRights) - { - Enumeration values = accessRights.propertyNames(); - - while (values.hasMoreElements()) - { - String user = (String) values.nextElement(); - - if (_principalDatabase.getUser(user) == null) - { - _logger.warn("Access rights contains user '" + user + "' but there is no authentication data for that user"); - } - } - } - - private void saveAccessFile() - { - try - { - _accessRightsUpdate.lock(); - try - { - // remove old temporary file - File tmp = new File(_accessFileName + ".tmp"); - if (tmp.exists()) - { - tmp.delete(); - } - - //remove old backup - File old = new File(_accessFileName + ".old"); - if (old.exists()) - { - old.delete(); - } - - // Rename current file - File rights = new File(_accessFileName); - rights.renameTo(old); - - FileOutputStream output = new FileOutputStream(tmp); - _accessRights.store(output, "Generated by AMQUserManagementMBean Console : Last edited by user:" + getCurrentJMXUser()); - output.close(); - - // Rename new file to main file - tmp.renameTo(rights); - - // delete tmp - tmp.delete(); - } - catch (IOException e) - { - _logger.warn("Problem occured saving '" + _accessFileName + "' changes may not be preserved. :" + e); - } - } - finally - { - if (_accessRightsUpdate.isHeldByCurrentThread()) - { - _accessRightsUpdate.unlock(); - } - } - } - - private String getCurrentJMXUser() - { - AccessControlContext acc = AccessController.getContext(); - Subject subject = Subject.getSubject(acc); - - // Retrieve JMXPrincipal from Subject - Set<JMXPrincipal> principals = subject.getPrincipals(JMXPrincipal.class); - if (principals == null || principals.isEmpty()) - { - return "Unknown user principals were null"; - } - - Principal principal = principals.iterator().next(); - return principal.getName(); - } - - /** - * user=read user=write user=readwrite user=admin - * - * @param accessRights The properties list of access rights to process - */ - private void setAccessRights(Properties accessRights) - { - _logger.debug("Setting Access Rights:" + accessRights); - _accessRights = accessRights; - MBeanInvocationHandlerImpl.setAccessRights(_accessRights); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/access/AccessManager.java b/java/broker/src/main/java/org/apache/qpid/server/security/access/AccessManager.java deleted file mode 100644 index d70a6dc8f4..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/access/AccessManager.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.security.access; - -import java.security.Principal; - -public interface AccessManager -{ - AccessResult isAuthorized(Accessable accessObject, Principal username, AccessRights.Rights rights); - - @Deprecated - AccessResult isAuthorized(Accessable accessObject, String username); - - String getName(); - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/access/AccessManagerImpl.java b/java/broker/src/main/java/org/apache/qpid/server/security/access/AccessManagerImpl.java deleted file mode 100644 index 35d036d20f..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/access/AccessManagerImpl.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.security.access; - -import org.apache.commons.configuration.Configuration; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal; -import org.apache.qpid.configuration.PropertyUtils; -import org.apache.log4j.Logger; - -import java.util.List; -import java.lang.reflect.Method; -import java.security.Principal; - -public class AccessManagerImpl implements AccessManager -{ - private static final Logger _logger = Logger.getLogger(AccessManagerImpl.class); - - AccessManager _accessManager; - - public AccessManagerImpl(String name, Configuration hostConfig) throws ConfigurationException - { - if (hostConfig == null) - { - _logger.warn("No Configuration specified. Using default access controls for VirtualHost:'" + name + "'"); - return; - } - - String accessClass = hostConfig.getString("security.access.class"); - if (accessClass == null) - { - _logger.warn("No access control specified. Using default access controls for VirtualHost:'" + name + "'"); - return; - } - - Object o; - try - { - o = Class.forName(accessClass).newInstance(); - } - catch (Exception e) - { - throw new ConfigurationException("Error initialising access control: " + e, e); - } - - if (!(o instanceof AccessManager)) - { - throw new ConfigurationException("Access control must implement the VirtualHostAccess interface"); - } - - initialiseAccessControl((AccessManager) o, hostConfig); - - _accessManager = (AccessManager) o; - - _logger.info("Initialised access control for virtualhost '" + name + "' successfully"); - - } - - - private void initialiseAccessControl(AccessManager accessManager, Configuration config) - throws ConfigurationException - { - String baseName = "security.access.attributes.attribute."; - List<String> argumentNames = config.getList(baseName + "name"); - List<String> argumentValues = config.getList(baseName + "value"); - for (int i = 0; i < argumentNames.size(); i++) - { - String argName = argumentNames.get(i); - if (argName == null || argName.length() == 0) - { - throw new ConfigurationException("Access Control argument names must have length >= 1 character"); - } - if (Character.isLowerCase(argName.charAt(0))) - { - argName = Character.toUpperCase(argName.charAt(0)) + argName.substring(1); - } - String methodName = "set" + argName; - Method method = null; - try - { - method = accessManager.getClass().getMethod(methodName, String.class); - } - catch (NoSuchMethodException e) - { - //do nothing as method will be null - } - - if (method == null) - { - throw new ConfigurationException("No method " + methodName + " found in class " + accessManager.getClass() + - " hence unable to configure access control. The method must be public and " + - "have a single String argument with a void return type"); - } - try - { - method.invoke(accessManager, PropertyUtils.replaceProperties(argumentValues.get(i))); - } - catch (Exception e) - { - ConfigurationException ce = new ConfigurationException(e.getMessage(), e.getCause()); - ce.initCause(e); - throw ce; - } - } - } - - public AccessResult isAuthorized(Accessable accessObject, String username) - { - return isAuthorized(accessObject, new UsernamePrincipal(username), AccessRights.Rights.READ); - } - - public AccessResult isAuthorized(Accessable accessObject, Principal user, AccessRights.Rights rights) - { - if (_accessManager == null) - { - if (ApplicationRegistry.getInstance().getAccessManager() == this) - { - _logger.warn("No Default access manager specified DENYING ALL ACCESS"); - return new AccessResult(this, AccessResult.AccessStatus.REFUSED); - } - else - { - return ApplicationRegistry.getInstance().getAccessManager().isAuthorized(accessObject, user, rights); - } - } - else - { - return _accessManager.isAuthorized(accessObject, user, rights); - } - } - - public String getName() - { - return "AccessManagerImpl"; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/access/AccessResult.java b/java/broker/src/main/java/org/apache/qpid/server/security/access/AccessResult.java deleted file mode 100644 index b8d8fc605a..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/access/AccessResult.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.security.access; - -public class AccessResult -{ - public enum AccessStatus - { - GRANTED, REFUSED - } - - StringBuilder _authorizer; - AccessStatus _status; - - public AccessResult(AccessManager authorizer, AccessStatus status) - { - _status = status; - _authorizer = new StringBuilder(authorizer.getName()); - } - - public void setAuthorizer(AccessManager authorizer) - { - _authorizer.append(authorizer.getName()); - } - - public String getAuthorizer() - { - return _authorizer.toString(); - } - - public void setStatus(AccessStatus status) - { - _status = status; - } - - public AccessStatus getStatus() - { - return _status; - } - - public void addAuthorizer(AccessManager accessManager) - { - _authorizer.insert(0, "->"); - _authorizer.insert(0, accessManager.getName()); - } - - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/access/AccessRights.java b/java/broker/src/main/java/org/apache/qpid/server/security/access/AccessRights.java deleted file mode 100644 index 1b79a5a0e0..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/access/AccessRights.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.security.access; - -public class AccessRights -{ - public enum Rights - { - ANY, - READ, - WRITE, - READWRITE - } - - Rights _right; - - public AccessRights(Rights right) - { - _right = right; - } - - public boolean allows(Rights rights) - { - switch (_right) - { - case ANY: - return (rights.equals(Rights.WRITE) - || rights.equals(Rights.READ) - || rights.equals(Rights.READWRITE) - || rights.equals(Rights.ANY)); - case READ: - return rights.equals(Rights.READ) || rights.equals(Rights.ANY); - case WRITE: - return rights.equals(Rights.WRITE) || rights.equals(Rights.ANY); - case READWRITE: - return true; - } - return false; - } - - public Rights getRights() - { - return _right; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/access/Accessable.java b/java/broker/src/main/java/org/apache/qpid/server/security/access/Accessable.java deleted file mode 100644 index f51cf24caa..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/access/Accessable.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.security.access; - -public interface Accessable -{ - void setAccessableName(String name); - String getAccessableName(); -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/access/AllowAll.java b/java/broker/src/main/java/org/apache/qpid/server/security/access/AllowAll.java deleted file mode 100644 index 1ddca3a64e..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/access/AllowAll.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.security.access; - -import java.security.Principal; - -public class AllowAll implements AccessManager -{ - - public AccessResult isAuthorized(Accessable accessObject, Principal username, AccessRights.Rights rights) - { - return new AccessResult(this, AccessResult.AccessStatus.GRANTED); - } - - public AccessResult isAuthorized(Accessable accessObject, String username) - { - return new AccessResult(this, AccessResult.AccessStatus.GRANTED); - } - - public String getName() - { - return "AllowAll"; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/access/DenyAll.java b/java/broker/src/main/java/org/apache/qpid/server/security/access/DenyAll.java deleted file mode 100644 index bf40eeba4e..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/access/DenyAll.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.security.access; - -import java.security.Principal; - -public class DenyAll implements AccessManager -{ - public AccessResult isAuthorized(Accessable accessObject, Principal username, AccessRights.Rights rights) - { - return new AccessResult(this, AccessResult.AccessStatus.REFUSED); - } - - public AccessResult isAuthorized(Accessable accessObject, String username) - { - return new AccessResult(this, AccessResult.AccessStatus.REFUSED); - } - - public String getName() - { - return "DenyAll"; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/access/FileAccessManager.java b/java/broker/src/main/java/org/apache/qpid/server/security/access/FileAccessManager.java deleted file mode 100644 index 291bc714ed..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/access/FileAccessManager.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.security.access; - -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal; -import org.apache.log4j.Logger; - -import java.io.IOException; -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.FileNotFoundException; -import java.io.File; -import java.util.regex.Pattern; -import java.security.Principal; - -/** - * Represents a user database where the account information is stored in a simple flat file. - * - * The file is expected to be in the form: username:password username1:password1 ... usernamen:passwordn - * - * where a carriage return separates each username/password pair. Passwords are assumed to be in plain text. - */ -public class FileAccessManager implements AccessManager -{ - private static final Logger _logger = Logger.getLogger(FileAccessManager.class); - - protected File _accessFile; - - protected Pattern _regexp = Pattern.compile(":"); - - private static final short USER_INDEX = 0; - private static final short VIRTUALHOST_INDEX = 1; - - public void setAccessFile(String accessFile) throws FileNotFoundException - { - File f = new File(accessFile); - _logger.info("FileAccessManager using file " + f.getAbsolutePath()); - _accessFile = f; - if (!f.exists()) - { - throw new FileNotFoundException("Cannot find access file " + f); - } - if (!f.canRead()) - { - throw new FileNotFoundException("Cannot read access file " + f + - ". Check permissions."); - } - } - - /** - * Looks up the virtual hosts for a specified user in the access file. - * - * @param user The user to lookup - * - * @return a list of virtualhosts - */ - private VirtualHostAccess[] lookupVirtualHost(String user) - { - String[] results = lookup(user, VIRTUALHOST_INDEX); - VirtualHostAccess vhosts[] = new VirtualHostAccess[results.length]; - - for (int index = 0; index < results.length; index++) - { - vhosts[index] = new VirtualHostAccess(results[index]); - } - - return vhosts; - } - - - private String[] lookup(String user, int index) - { - try - { - BufferedReader reader = null; - try - { - reader = new BufferedReader(new FileReader(_accessFile)); - String line; - - while ((line = reader.readLine()) != null) - { - String[] result = _regexp.split(line); - if (result == null || result.length < (index + 1)) - { - continue; - } - - if (user.equals(result[USER_INDEX])) - { - return result[index].split(","); - } - } - return null; - } - finally - { - if (reader != null) - { - reader.close(); - } - } - } - catch (IOException ioe) - { - //ignore - } - return null; - } - - public AccessResult isAuthorized(Accessable accessObject, String username) - { - return isAuthorized(accessObject, new UsernamePrincipal(username), AccessRights.Rights.READ); - } - - public AccessResult isAuthorized(Accessable accessObject, Principal user, AccessRights.Rights rights) - { - if (accessObject instanceof VirtualHost) - { - VirtualHostAccess[] hosts = lookupVirtualHost(user.getName()); - - if (hosts != null) - { - for (VirtualHostAccess host : hosts) - { - if (accessObject.getAccessableName().equals(host.getVirtualHost())) - { - if (host.getAccessRights().allows(rights)) - { - return new AccessResult(this, AccessResult.AccessStatus.GRANTED); - } - else - { - return new AccessResult(this, AccessResult.AccessStatus.REFUSED); - } - } - } - } - } -// else if (accessObject instanceof AMQQueue) -// { -// String[] queues = lookupQueue(username, ((AMQQueue) accessObject).getVirtualHost()); -// -// if (queues != null) -// { -// for (String queue : queues) -// { -// if (accessObject.getAccessableName().equals(queue)) -// { -// return new AccessResult(this, AccessResult.AccessStatus.GRANTED); -// } -// } -// } -// } - - return new AccessResult(this, AccessResult.AccessStatus.REFUSED); - } - - public String getName() - { - return "FileAccessManager"; - } - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/access/PrincipalDatabaseAccessManager.java b/java/broker/src/main/java/org/apache/qpid/server/security/access/PrincipalDatabaseAccessManager.java deleted file mode 100644 index 6ccadb2e7d..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/access/PrincipalDatabaseAccessManager.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.security.access; - -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.security.auth.database.PrincipalDatabase; -import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal; -import org.apache.log4j.Logger; - -import java.security.Principal; - -public class PrincipalDatabaseAccessManager implements AccessManager -{ - private static final Logger _logger = Logger.getLogger(PrincipalDatabaseAccessManager.class); - - PrincipalDatabase _database; - AccessManager _default; - - public PrincipalDatabaseAccessManager() - { - _default = null; - } - - public void setDefaultAccessManager(String defaultAM) - { - if (defaultAM.equals("AllowAll")) - { - _default = new AllowAll(); - } - - if (defaultAM.equals("DenyAll")) - { - _default = new DenyAll(); - } - } - - public void setPrincipalDatabase(String database) - { - _database = ApplicationRegistry.getInstance().getDatabaseManager().getDatabases().get(database); - if (!(_database instanceof AccessManager)) - { - _logger.warn("Database '" + database + "' cannot perform access management"); - } - } - - - public AccessResult isAuthorized(Accessable accessObject, String username) - { - return isAuthorized(accessObject, new UsernamePrincipal(username), AccessRights.Rights.READ); - } - - public AccessResult isAuthorized(Accessable accessObject, Principal username, AccessRights.Rights rights) - { - AccessResult result; - - if (_database == null) - { - if (_default != null) - { - result = _default.isAuthorized(accessObject, username, rights); - } - else - { - throw new RuntimeException("Principal Database and default Access Manager are both null unable to perform Access Control"); - } - } - else - { - if (!(_database instanceof AccessManager)) - { - _logger.warn("Specified PrincipalDatabase is not an AccessManager so using default AccessManager"); - result = _default.isAuthorized(accessObject, username, rights); - } - else - { - result = ((AccessManager) _database).isAuthorized(accessObject, username, rights); - } - } - - result.addAuthorizer(this); - - return result; - } - - public String getName() - { - return "PrincipalDatabaseFileAccessManager"; - } - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/access/UserManagement.java b/java/broker/src/main/java/org/apache/qpid/server/security/access/UserManagement.java deleted file mode 100644 index b8762aa43b..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/access/UserManagement.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.security.access; - -import org.apache.qpid.server.management.MBeanOperation; -import org.apache.qpid.server.management.MBeanOperationParameter; -import org.apache.qpid.server.management.MBeanAttribute; -import org.apache.qpid.AMQException; - -import javax.management.openmbean.TabularData; -import javax.management.openmbean.CompositeData; -import javax.management.JMException; -import javax.management.MBeanOperationInfo; -import java.io.IOException; - -public interface UserManagement -{ - String TYPE = "UserManagement"; - - //********** Operations *****************// - /** - * set password for user - * - * @param username The username to create - * @param password The password for the user - * - * @return The result of the operation - */ - @MBeanOperation(name = "setPassword", description = "Set password for user.", - impact = MBeanOperationInfo.ACTION) - boolean setPassword(@MBeanOperationParameter(name = "username", description = "Username")String username, - @MBeanOperationParameter(name = "password", description = "Password")char[] password); - - /** - * set rights for users with given details - * - * @param username The username to create - * @param read The set of permission to give the new user - * @param write The set of permission to give the new user - * @param admin The set of permission to give the new user - * - * @return The result of the operation - */ - @MBeanOperation(name = "setRights", description = "Set access rights for user.", - impact = MBeanOperationInfo.ACTION) - boolean setRights(@MBeanOperationParameter(name = "username", description = "Username")String username, - @MBeanOperationParameter(name = "read", description = "Administration read")boolean read, - @MBeanOperationParameter(name = "readAndWrite", description = "Administration write")boolean write, - @MBeanOperationParameter(name = "admin", description = "Administration rights")boolean admin); - - /** - * Create users with given details - * - * @param username The username to create - * @param password The password for the user - * @param read The set of permission to give the new user - * @param write The set of permission to give the new user - * @param admin The set of permission to give the new user - * - * @return The result of the operation - */ - @MBeanOperation(name = "createUser", description = "Create new user from system.", - impact = MBeanOperationInfo.ACTION) - boolean createUser(@MBeanOperationParameter(name = "username", description = "Username")String username, - @MBeanOperationParameter(name = "password", description = "Password")char[] password, - @MBeanOperationParameter(name = "read", description = "Administration read")boolean read, - @MBeanOperationParameter(name = "readAndWrite", description = "Administration write")boolean write, - @MBeanOperationParameter(name = "admin", description = "Administration rights")boolean admin); - - /** - * View users returns all the users that are currently available to the system. - * - * @param username The user to delete - * - * @return The result of the operation - */ - @MBeanOperation(name = "deleteUser", description = "Delete user from system.", - impact = MBeanOperationInfo.ACTION) - boolean deleteUser(@MBeanOperationParameter(name = "username", description = "Username")String username); - - - /** - * Reload the date from disk - * - * @return The result of the operation - */ - @MBeanOperation(name = "reloadData", description = "Reload the authentication file from disk.", - impact = MBeanOperationInfo.ACTION) - boolean reloadData(); - - /** - * View users returns all the users that are currently available to the system. - * - * @return a table of users data (Username, read, write, admin) - */ - @MBeanOperation(name = "viewUsers", description = "All users with access rights to the system.", - impact = MBeanOperationInfo.INFO) - TabularData viewUsers(); - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/access/VirtualHostAccess.java b/java/broker/src/main/java/org/apache/qpid/server/security/access/VirtualHostAccess.java deleted file mode 100644 index 13151a66b8..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/access/VirtualHostAccess.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.security.access; - -public class VirtualHostAccess -{ - private String _vhost; - private AccessRights _rights; - - public VirtualHostAccess(String vhostaccess) - { - //format <vhost>(<rights>) - int hostend = vhostaccess.indexOf('('); - - if (hostend == -1) - { - throw new IllegalArgumentException("VirtualHostAccess format string contains no access _rights"); - } - - _vhost = vhostaccess.substring(0, hostend); - - String rights = vhostaccess.substring(hostend); - - if (rights.indexOf('r') != -1) - { - if (rights.indexOf('w') != -1) - { - _rights = new AccessRights(AccessRights.Rights.READWRITE); - } - else - { - _rights = new AccessRights(AccessRights.Rights.READ); - } - } - else if (rights.indexOf('w') != -1) - { - _rights = new AccessRights(AccessRights.Rights.WRITE); - } - } - - public AccessRights getAccessRights() - { - return _rights; - } - - public String getVirtualHost() - { - return _vhost; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/AuthenticationResult.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/AuthenticationResult.java deleted file mode 100644 index 0e3aea4de0..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/AuthenticationResult.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.security.auth; - -public class AuthenticationResult -{ - public enum AuthenticationStatus - { - SUCCESS, CONTINUE, ERROR - } - - public AuthenticationStatus status; - public byte[] challenge; - - public AuthenticationResult(byte[] challenge, AuthenticationStatus status) - { - this.status = status; - this.challenge = challenge; - } - - public AuthenticationResult(AuthenticationStatus status) - { - this.status = status; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabase.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabase.java deleted file mode 100644 index 10adfdd9fc..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabase.java +++ /dev/null @@ -1,599 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.security.auth.database; - -import org.apache.log4j.Logger; -import org.apache.qpid.server.security.auth.sasl.AuthenticationProviderInitialiser; -import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal; -import org.apache.qpid.server.security.auth.sasl.crammd5.CRAMMD5HashedInitialiser; -import org.apache.qpid.server.security.access.AMQUserManagementMBean; -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.codec.EncoderException; - -import javax.security.auth.callback.PasswordCallback; -import javax.security.auth.login.AccountNotFoundException; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.UnsupportedEncodingException; -import java.io.PrintStream; -import java.util.regex.Pattern; -import java.util.Map; -import java.util.HashMap; -import java.util.List; -import java.util.LinkedList; -import java.util.concurrent.locks.ReentrantLock; -import java.security.Principal; -import java.security.NoSuchAlgorithmException; -import java.security.MessageDigest; - -/** - * Represents a user database where the account information is stored in a simple flat file. - * - * The file is expected to be in the form: username:password username1:password1 ... usernamen:passwordn - * - * where a carriage return separates each username/password pair. Passwords are assumed to be in plain text. - */ -public class Base64MD5PasswordFilePrincipalDatabase implements PrincipalDatabase -{ - private static final Logger _logger = Logger.getLogger(Base64MD5PasswordFilePrincipalDatabase.class); - - private File _passwordFile; - - private Pattern _regexp = Pattern.compile(":"); - - private Map<String, AuthenticationProviderInitialiser> _saslServers; - - AMQUserManagementMBean _mbean; - private static final String DEFAULT_ENCODING = "utf-8"; - private Map<String, User> _users = new HashMap<String, User>(); - private ReentrantLock _userUpdate = new ReentrantLock(); - - public Base64MD5PasswordFilePrincipalDatabase() - { - _saslServers = new HashMap<String, AuthenticationProviderInitialiser>(); - - /** - * Create Authenticators for MD5 Password file. - */ - - // Accept Plain incomming and hash it for comparison to the file. - CRAMMD5HashedInitialiser cram = new CRAMMD5HashedInitialiser(); - cram.initialise(this); - _saslServers.put(cram.getMechanismName(), cram); - - //fixme The PDs should setup a PD Mangement MBean -// try -// { -// _mbean = new AMQUserManagementMBean(); -// _mbean.setPrincipalDatabase(this); -// } -// catch (JMException e) -// { -// _logger.warn("User management disabled as unable to create MBean:" + e); -// } - } - - public void setPasswordFile(String passwordFile) throws IOException - { - File f = new File(passwordFile); - _logger.info("PasswordFilePrincipalDatabase using file " + f.getAbsolutePath()); - _passwordFile = f; - if (!f.exists()) - { - throw new FileNotFoundException("Cannot find password file " + f); - } - if (!f.canRead()) - { - throw new FileNotFoundException("Cannot read password file " + f + - ". Check permissions."); - } - - loadPasswordFile(); - } - - /** - * SASL Callback Mechanism - sets the Password in the PasswordCallback based on the value in the PasswordFile - * - * @param principal The Principal to set the password for - * @param callback The PasswordCallback to call setPassword on - * - * @throws AccountNotFoundException If the Principal cannont be found in this Database - */ - public void setPassword(Principal principal, PasswordCallback callback) throws AccountNotFoundException - { - if (_passwordFile == null) - { - throw new AccountNotFoundException("Unable to locate principal since no password file was specified during initialisation"); - } - if (principal == null) - { - throw new IllegalArgumentException("principal must not be null"); - } - - char[] pwd = lookupPassword(principal.getName()); - - if (pwd != null) - { - callback.setPassword(pwd); - } - else - { - throw new AccountNotFoundException("No account found for principal " + principal); - } - } - - /** - * Used to verify that the presented Password is correct. Currently only used by Management Console - * - * @param principal The principal to authenticate - * @param password The password to check - * - * @return true if password is correct - * - * @throws AccountNotFoundException if the principal cannot be found - */ - public boolean verifyPassword(String principal, char[] password) throws AccountNotFoundException - { - char[] pwd = lookupPassword(principal); - - int index = 0; - boolean verified = true; - - while (verified & index < password.length) - { - verified = (pwd[index] == password[index]); - index++; - } - return verified; - } - - public boolean updatePassword(Principal principal, char[] password) throws AccountNotFoundException - { - User user = _users.get(principal.getName()); - - if (user == null) - { - throw new AccountNotFoundException(principal.getName()); - } - - try - { - try - { - _userUpdate.lock(); - char[] orig = user.getPassword(); - user.setPassword(password); - - try - { - savePasswordFile(); - } - catch (IOException e) - { - _logger.error("Unable to save password file, password change for user'" - + principal + "' will revert at restart"); - //revert the password change - user.setPassword(orig); - return false; - } - return true; - } - finally - { - if (_userUpdate.isHeldByCurrentThread()) - { - _userUpdate.unlock(); - } - } - } - catch (Exception e) - { - return false; - } - } - - public boolean createPrincipal(Principal principal, char[] password) - { - if (_users.get(principal.getName()) != null) - { - return false; - } - - User user = new User(principal.getName(), password); - - try - { - _userUpdate.lock(); - _users.put(user.getName(), user); - - try - { - savePasswordFile(); - return true; - } - catch (IOException e) - { - //remove the use on failure. - _users.remove(user.getName()); - return false; - } - } - finally - { - if (_userUpdate.isHeldByCurrentThread()) - { - _userUpdate.unlock(); - } - } - } - - public boolean deletePrincipal(Principal principal) throws AccountNotFoundException - { - User user = _users.get(principal.getName()); - - if (user == null) - { - throw new AccountNotFoundException(principal.getName()); - } - - try - { - _userUpdate.lock(); - user.delete(); - - try - { - savePasswordFile(); - } - catch (IOException e) - { - _logger.warn("Unable to remove user '" + user.getName() + "' from password file."); - return false; - } - - _users.remove(user.getName()); - } - finally - { - if (_userUpdate.isHeldByCurrentThread()) - { - _userUpdate.unlock(); - } - } - - return true; - } - - - public Map<String, AuthenticationProviderInitialiser> getMechanisms() - { - return _saslServers; - } - - public List<Principal> getUsers() - { - return new LinkedList<Principal>(_users.values()); - } - - public Principal getUser(String username) - { - if (_users.containsKey(username)) - { - return new UsernamePrincipal(username); - } - return null; - } - - /** - * Looks up the password for a specified user in the password file. Note this code is <b>not</b> secure since it - * creates strings of passwords. It should be modified to create only char arrays which get nulled out. - * - * @param name The principal name to lookup - * - * @return a char[] for use in SASL. - */ - private char[] lookupPassword(String name) - { - User user = _users.get(name); - if (user == null) - { - return null; - } - else - { - return user.getPassword(); - } - } - - - private void loadPasswordFile() throws IOException - { - try - { - _userUpdate.lock(); - _users.clear(); - - BufferedReader reader = null; - try - { - reader = new BufferedReader(new FileReader(_passwordFile)); - String line; - - while ((line = reader.readLine()) != null) - { - String[] result = _regexp.split(line); - if (result == null || result.length < 2 || result[0].startsWith("#")) - { - continue; - } - - User user = new User(result); - _logger.info("Created user:" + user); - _users.put(user.getName(), user); - } - } - finally - { - if (reader != null) - { - reader.close(); - } - } - } - finally - { - if (_userUpdate.isHeldByCurrentThread()) - { - _userUpdate.unlock(); - } - } - } - - private void savePasswordFile() throws IOException - { - try - { - _userUpdate.lock(); - - BufferedReader reader = null; - PrintStream writer = null; - File tmp = new File(_passwordFile.getAbsolutePath() + ".tmp"); - if (tmp.exists()) - { - tmp.delete(); - } - try - { - writer = new PrintStream(tmp); - reader = new BufferedReader(new FileReader(_passwordFile)); - String line; - - while ((line = reader.readLine()) != null) - { - String[] result = _regexp.split(line); - if (result == null || result.length < 2 || result[0].startsWith("#")) - { - writer.write(line.getBytes(DEFAULT_ENCODING)); - continue; - } - - User user = _users.get(result[0]); - - if (user == null) - { - writer.write(line.getBytes(DEFAULT_ENCODING)); - writer.println(); - } - else if (!user.isDeleted()) - { - if (!user.isModified()) - { - writer.write(line.getBytes(DEFAULT_ENCODING)); - writer.println(); - } - else - { - try - { - byte[] encodedPassword = user.getEncodePassword(); - - writer.write((user.getName() + ":").getBytes(DEFAULT_ENCODING)); - writer.write(encodedPassword); - writer.println(); - - user.saved(); - } - catch (Exception e) - { - _logger.warn("Unable to encode new password reverting to old password."); - writer.write(line.getBytes(DEFAULT_ENCODING)); - writer.println(); - } - } - } - } - - for (User user : _users.values()) - { - if (user.isModified()) - { - byte[] encodedPassword; - try - { - encodedPassword = user.getEncodePassword(); - writer.write((user.getName() + ":").getBytes(DEFAULT_ENCODING)); - writer.write(encodedPassword); - writer.println(); - user.saved(); - } - catch (Exception e) - { - _logger.warn("Unable to get Encoded password for user'" + user.getName() + "' password not saved"); - } - } - } - } - finally - { - if (reader != null) - { - reader.close(); - } - - if (writer != null) - { - writer.close(); - } - - // Swap temp file to main password file. - File old = new File(_passwordFile.getAbsoluteFile() + ".old"); - if (old.exists()) - { - old.delete(); - } - _passwordFile.renameTo(old); - tmp.renameTo(_passwordFile); - tmp.delete(); - } - } - finally - { - if (_userUpdate.isHeldByCurrentThread()) - { - _userUpdate.unlock(); - } - } - } - - private class User implements Principal - { - String _name; - char[] _password; - byte[] _encodedPassword = null; - private boolean _modified = false; - private boolean _deleted = false; - - User(String[] data) throws UnsupportedEncodingException - { - if (data.length != 2) - { - throw new IllegalArgumentException("User Data should be lenght 2, username, password"); - } - - _name = data[0]; - - byte[] encoded_password = data[1].getBytes(DEFAULT_ENCODING); - - Base64 b64 = new Base64(); - byte[] decoded = b64.decode(encoded_password); - - _encodedPassword = encoded_password; - - _password = new char[decoded.length]; - - int index = 0; - for (byte c : decoded) - { - _password[index++] = (char) c; - } - } - - public User(String name, char[] password) - { - _name = name; - setPassword(password); - } - - public String getName() - { - return _name; - } - - public String toString() - { - if (_logger.isDebugEnabled()) - { - return getName() + ((_encodedPassword == null) ? "" : ":" + new String(_encodedPassword)); - } - else - { - return _name; - } - } - - char[] getPassword() - { - return _password; - } - - void setPassword(char[] password) - { - _password = password; - _modified = true; - _encodedPassword = null; - } - - - byte[] getEncodePassword() throws EncoderException, UnsupportedEncodingException, NoSuchAlgorithmException - { - if (_encodedPassword == null) - { - encodePassword(); - } - return _encodedPassword; - } - - private void encodePassword() throws EncoderException, UnsupportedEncodingException, NoSuchAlgorithmException - { - byte[] byteArray = new byte[_password.length]; - int index = 0; - for (char c : _password) - { - byteArray[index++] = (byte) c; - } - _encodedPassword = (new Base64()).encode(byteArray); - } - - public boolean isModified() - { - return _modified; - } - - public boolean isDeleted() - { - return _deleted; - } - - public void delete() - { - _deleted = true; - } - - public void saved() - { - _modified = false; - } - - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/ConfigurationFilePrincipalDatabaseManager.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/ConfigurationFilePrincipalDatabaseManager.java deleted file mode 100644 index 06eb9329a6..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/ConfigurationFilePrincipalDatabaseManager.java +++ /dev/null @@ -1,238 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.security.auth.database; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.management.JMException; - -import org.apache.commons.configuration.Configuration; -import org.apache.commons.configuration.ConfigurationException; - -import org.apache.log4j.Logger; - -import org.apache.qpid.AMQException; -import org.apache.qpid.configuration.PropertyException; -import org.apache.qpid.configuration.PropertyUtils; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.security.access.AMQUserManagementMBean; -import org.apache.qpid.server.security.auth.database.PrincipalDatabase; -import org.apache.qpid.server.security.auth.database.PrincipalDatabaseManager; - -public class ConfigurationFilePrincipalDatabaseManager implements PrincipalDatabaseManager -{ - private static final Logger _logger = Logger.getLogger(ConfigurationFilePrincipalDatabaseManager.class); - - private static final String _base = "security.principal-databases.principal-database"; - - Map<String, PrincipalDatabase> _databases; - - public ConfigurationFilePrincipalDatabaseManager() throws Exception - { - _logger.info("Initialising PrincipleDatabase authentication manager"); - _databases = initialisePrincipalDatabases(); - } - - private Map<String, PrincipalDatabase> initialisePrincipalDatabases() throws Exception - { - Configuration config = ApplicationRegistry.getInstance().getConfiguration(); - List<String> databaseNames = config.getList(_base + ".name"); - List<String> databaseClasses = config.getList(_base + ".class"); - Map<String, PrincipalDatabase> databases = new HashMap<String, PrincipalDatabase>(); - - if (databaseNames.size() == 0) - { - _logger.warn("No Principal databases specified. Broker running with NO AUTHENTICATION"); - } - - for (int i = 0; i < databaseNames.size(); i++) - { - Object o; - try - { - o = Class.forName(databaseClasses.get(i)).newInstance(); - } - catch (Exception e) - { - throw new Exception("Error initialising principal database: " + e, e); - } - - if (!(o instanceof PrincipalDatabase)) - { - throw new Exception("Principal databases must implement the PrincipalDatabase interface"); - } - - initialisePrincipalDatabase((PrincipalDatabase) o, config, i); - - String name = databaseNames.get(i); - if ((name == null) || (name.length() == 0)) - { - throw new Exception("Principal database names must have length greater than or equal to one character"); - } - - PrincipalDatabase pd = databases.get(name); - if (pd != null) - { - throw new Exception("Duplicate principal database name not provided"); - } - - _logger.info("Initialised principal database '" + name + "' successfully"); - databases.put(name, (PrincipalDatabase) o); - } - - return databases; - } - - private void initialisePrincipalDatabase(PrincipalDatabase principalDatabase, Configuration config, int index) - throws FileNotFoundException, ConfigurationException - { - String baseName = _base + "(" + index + ").attributes.attribute."; - List<String> argumentNames = config.getList(baseName + "name"); - List<String> argumentValues = config.getList(baseName + "value"); - for (int i = 0; i < argumentNames.size(); i++) - { - String argName = argumentNames.get(i); - if ((argName == null) || (argName.length() == 0)) - { - throw new ConfigurationException("Argument names must have length >= 1 character"); - } - - if (Character.isLowerCase(argName.charAt(0))) - { - argName = Character.toUpperCase(argName.charAt(0)) + argName.substring(1); - } - - String methodName = "set" + argName; - Method method = null; - try - { - method = principalDatabase.getClass().getMethod(methodName, String.class); - } - catch (Exception e) - { - // do nothing.. as on error method will be null - } - - if (method == null) - { - throw new ConfigurationException("No method " + methodName + " found in class " - + principalDatabase.getClass() - + " hence unable to configure principal database. The method must be public and " - + "have a single String argument with a void return type"); - } - - try - { - method.invoke(principalDatabase, PropertyUtils.replaceProperties(argumentValues.get(i))); - } - catch (Exception ite) - { - if (ite instanceof ConfigurationException) - { - throw(ConfigurationException) ite; - } - else - { - throw new ConfigurationException(ite.getMessage(), ite); - } - } - } - } - - public Map<String, PrincipalDatabase> getDatabases() - { - return _databases; - } - - public void initialiseManagement(Configuration config) throws ConfigurationException - { - try - { - AMQUserManagementMBean _mbean = new AMQUserManagementMBean(); - - String baseSecurity = "security.jmx"; - List<String> principalDBs = config.getList(baseSecurity + ".principal-database"); - - if (principalDBs.size() == 0) - { - throw new ConfigurationException("No principal-database specified for jmx security(" + baseSecurity - + ".principal-database)"); - } - - String databaseName = principalDBs.get(0); - - PrincipalDatabase database = getDatabases().get(databaseName); - - if (database == null) - { - throw new ConfigurationException("Principal-database '" + databaseName + "' not found"); - } - - _mbean.setPrincipalDatabase(database); - - List<String> jmxaccesslist = config.getList(baseSecurity + ".access"); - - if (jmxaccesslist.size() == 0) - { - throw new ConfigurationException("No access control files specified for jmx security(" + baseSecurity - + ".access)"); - } - - String jmxaccesssFile = null; - - try - { - jmxaccesssFile = PropertyUtils.replaceProperties(jmxaccesslist.get(0)); - } - catch (PropertyException e) - { - throw new ConfigurationException("Unable to parse access control filename '" + jmxaccesssFile + "'", e); - } - - try - { - _mbean.setAccessFile(jmxaccesssFile); - } - catch (IOException e) - { - _logger.warn("Unable to load access file:" + jmxaccesssFile); - } - - try - { - _mbean.register(); - } - catch (AMQException e) - { - _logger.warn("Unable to register user management MBean"); - } - } - catch (JMException e) - { - _logger.warn("User management disabled as unable to create MBean:" + e); - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PlainPasswordFilePrincipalDatabase.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PlainPasswordFilePrincipalDatabase.java deleted file mode 100644 index 352d41a0ba..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PlainPasswordFilePrincipalDatabase.java +++ /dev/null @@ -1,240 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.security.auth.database; - -import org.apache.log4j.Logger; -import org.apache.qpid.server.security.auth.sasl.AuthenticationProviderInitialiser; -import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal; -import org.apache.qpid.server.security.auth.sasl.amqplain.AmqPlainInitialiser; -import org.apache.qpid.server.security.auth.sasl.crammd5.CRAMMD5Initialiser; -import org.apache.qpid.server.security.auth.sasl.plain.PlainInitialiser; - -import javax.security.auth.callback.PasswordCallback; -import javax.security.auth.login.AccountNotFoundException; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.security.Principal; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.regex.Pattern; - -/** - * Represents a user database where the account information is stored in a simple flat file. - * - * The file is expected to be in the form: username:password username1:password1 ... usernamen:passwordn - * - * where a carriage return separates each username/password pair. Passwords are assumed to be in plain text. - */ -public class PlainPasswordFilePrincipalDatabase implements PrincipalDatabase -{ - private static final Logger _logger = Logger.getLogger(PlainPasswordFilePrincipalDatabase.class); - - protected File _passwordFile; - - protected Pattern _regexp = Pattern.compile(":"); - - protected Map<String, AuthenticationProviderInitialiser> _saslServers; - - public PlainPasswordFilePrincipalDatabase() - { - _saslServers = new HashMap<String, AuthenticationProviderInitialiser>(); - - /** - * Create Authenticators for Plain Password file. - */ - - // Accept AMQPlain incomming and compare it to the file. - AmqPlainInitialiser amqplain = new AmqPlainInitialiser(); - amqplain.initialise(this); - - // Accept Plain incomming and compare it to the file. - PlainInitialiser plain = new PlainInitialiser(); - plain.initialise(this); - - // Accept MD5 incomming and Hash file value for comparison - CRAMMD5Initialiser cram = new CRAMMD5Initialiser(); - cram.initialise(this); - - _saslServers.put(amqplain.getMechanismName(), amqplain); - _saslServers.put(plain.getMechanismName(), plain); - _saslServers.put(cram.getMechanismName(), cram); - } - - public void setPasswordFile(String passwordFile) throws FileNotFoundException - { - File f = new File(passwordFile); - _logger.info("PlainPasswordFile using file " + f.getAbsolutePath()); - _passwordFile = f; - if (!f.exists()) - { - throw new FileNotFoundException("Cannot find password file " + f); - } - if (!f.canRead()) - { - throw new FileNotFoundException("Cannot read password file " + f + - ". Check permissions."); - } - } - - public void setPassword(Principal principal, PasswordCallback callback) throws IOException, - AccountNotFoundException - { - if (_passwordFile == null) - { - throw new AccountNotFoundException("Unable to locate principal since no password file was specified during initialisation"); - } - if (principal == null) - { - throw new IllegalArgumentException("principal must not be null"); - } - char[] pwd = lookupPassword(principal.getName()); - if (pwd != null) - { - callback.setPassword(pwd); - } - else - { - throw new AccountNotFoundException("No account found for principal " + principal); - } - } - - public boolean verifyPassword(String principal, char[] password) throws AccountNotFoundException - { - try - { - char[] pwd = lookupPassword(principal); - - return compareCharArray(pwd, password); - } - catch (IOException e) - { - return false; - } - } - - public boolean updatePassword(Principal principal, char[] password) throws AccountNotFoundException - { - return false; // updates denied - } - - public boolean createPrincipal(Principal principal, char[] password) - { - return false; // updates denied - } - - public boolean deletePrincipal(Principal principal) throws AccountNotFoundException - { - return false; // updates denied - } - - public Map<String, AuthenticationProviderInitialiser> getMechanisms() - { - return _saslServers; - } - - public List<Principal> getUsers() - { - return new LinkedList<Principal>(); //todo - } - - public Principal getUser(String username) - { - try - { - if (lookupPassword(username) != null) - { - return new UsernamePrincipal(username); - } - } - catch (IOException e) - { - //fall through to null return - } - return null; - } - - private boolean compareCharArray(char[] a, char[] b) - { - boolean equal = false; - if (a.length == b.length) - { - equal = true; - int index = 0; - while (equal && index < a.length) - { - equal = a[index] == b[index]; - index++; - } - } - return equal; - } - - - /** - * Looks up the password for a specified user in the password file. Note this code is <b>not</b> secure since it - * creates strings of passwords. It should be modified to create only char arrays which get nulled out. - * - * @param name the name of the principal to lookup - * - * @return char[] of the password - * - * @throws java.io.IOException whilst accessing the file - */ - private char[] lookupPassword(String name) throws IOException - { - BufferedReader reader = null; - try - { - reader = new BufferedReader(new FileReader(_passwordFile)); - String line; - - while ((line = reader.readLine()) != null) - { - if (!line.startsWith("#")) - { - String[] result = _regexp.split(line); - if (result == null || result.length < 2) - { - continue; - } - - if (name.equals(result[0])) - { - return result[1].toCharArray(); - } - } - } - return null; - } - finally - { - if (reader != null) - { - reader.close(); - } - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PlainPasswordVhostFilePrincipalDatabase.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PlainPasswordVhostFilePrincipalDatabase.java deleted file mode 100644 index 5c372f6c2c..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PlainPasswordVhostFilePrincipalDatabase.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.security.auth.database; - -import org.apache.log4j.Logger; -import org.apache.qpid.server.security.access.AccessManager; -import org.apache.qpid.server.security.access.AccessResult; -import org.apache.qpid.server.security.access.AccessRights; -import org.apache.qpid.server.security.access.Accessable; -import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal; -import org.apache.qpid.server.virtualhost.VirtualHost; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; -import java.security.Principal; - -/** - * Represents a user database where the account information is stored in a simple flat file. - * - * The file is expected to be in the form: username:password username1:password1 ... usernamen:passwordn - * - * where a carriage return separates each username/password pair. Passwords are assumed to be in plain text. - */ -public class PlainPasswordVhostFilePrincipalDatabase extends PlainPasswordFilePrincipalDatabase implements AccessManager -{ - private static final Logger _logger = Logger.getLogger(PlainPasswordVhostFilePrincipalDatabase.class); - - /** - * Looks up the virtual hosts for a specified user in the password file. - * - * @param user The user to lookup - * - * @return a list of virtualhosts - */ - private String[] lookupVirtualHost(String user) - { - try - { - BufferedReader reader = null; - try - { - reader = new BufferedReader(new FileReader(_passwordFile)); - String line; - - while ((line = reader.readLine()) != null) - { - if (!line.startsWith("#")) - { - String[] result = _regexp.split(line); - if (result == null || result.length < 3) - { - continue; - } - - if (user.equals(result[0])) - { - return result[2].split(","); - } - } - } - return null; - } - finally - { - if (reader != null) - { - reader.close(); - } - } - } - catch (IOException ioe) - { - //ignore - } - return null; - } - - - public AccessResult isAuthorized(Accessable accessObject, String username) - { - return isAuthorized(accessObject, new UsernamePrincipal(username), AccessRights.Rights.READ); - } - - public AccessResult isAuthorized(Accessable accessObject, Principal user, AccessRights.Rights rights) - { - - if (accessObject instanceof VirtualHost) - { - String[] hosts = lookupVirtualHost(user.getName()); - - if (hosts != null) - { - for (String host : hosts) - { - if (accessObject.getAccessableName().equals(host)) - { - return new AccessResult(this, AccessResult.AccessStatus.GRANTED); - } - } - } - } - - return new AccessResult(this, AccessResult.AccessStatus.REFUSED); - } - - public String getName() - { - return "PlainPasswordVhostFile"; - } - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PrincipalDatabase.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PrincipalDatabase.java deleted file mode 100644 index a82f9ed40b..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PrincipalDatabase.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.security.auth.database; - -import org.apache.qpid.server.security.auth.sasl.AuthenticationProviderInitialiser; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.security.Principal; -import java.util.Map; -import java.util.List; - -import javax.security.auth.callback.PasswordCallback; -import javax.security.auth.login.AccountNotFoundException; - -/** Represents a "user database" which is really a way of storing principals (i.e. usernames) and passwords. */ -public interface PrincipalDatabase -{ - /** - * Set the password for a given principal in the specified callback. This is used for certain SASL providers. The - * user database implementation should look up the password in any way it chooses and set it in the callback by - * calling its setPassword method. - * - * @param principal the principal - * @param callback the password callback that wants to receive the password - * - * @throws AccountNotFoundException if the account for specified principal could not be found - * @throws IOException if there was an error looking up the principal - */ - void setPassword(Principal principal, PasswordCallback callback) - throws IOException, AccountNotFoundException; - - /** - * Used to verify that the presented Password is correct. Currently only used by Management Console - * @param principal The principal to authenticate - * @param password The password to check - * @return true if password is correct - * @throws AccountNotFoundException if the principal cannot be found - */ - boolean verifyPassword(String principal, char[] password) - throws AccountNotFoundException; - - /** - * Update(Change) the password for the given principal - * @param principal Who's password is to be changed - * @param password The new password to use - * @return True if change was successful - * @throws AccountNotFoundException If the given principal doesn't exist in the Database - */ - boolean updatePassword(Principal principal, char[] password) - throws AccountNotFoundException; - - /** - * Create a new principal in the database - * @param principal The principal to create - * @param password The password to set for the principal - * @return True on a successful creation - */ - boolean createPrincipal(Principal principal, char[] password); - - /** - * Delete a principal - * @param principal The principal to delete - * @return True on a successful creation - * @throws AccountNotFoundException If the given principal doesn't exist in the Database - */ - boolean deletePrincipal(Principal principal) - throws AccountNotFoundException; - - /** - * Get the principal from the database with the given username - * @param username of the principal to lookup - * @return The Principal object for the given username or null if not found. - */ - Principal getUser(String username); - - - public Map<String, AuthenticationProviderInitialiser> getMechanisms(); - - - List<Principal> getUsers(); -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PrincipalDatabaseManager.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PrincipalDatabaseManager.java deleted file mode 100644 index 2c553ae76a..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PrincipalDatabaseManager.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.security.auth.database; - -import org.apache.qpid.server.security.auth.database.PrincipalDatabase; -import org.apache.commons.configuration.Configuration; -import org.apache.commons.configuration.ConfigurationException; - -import java.util.Map; - -public interface PrincipalDatabaseManager -{ - public Map<String, PrincipalDatabase> getDatabases(); - - public void initialiseManagement(Configuration config) throws ConfigurationException; -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PropertiesPrincipalDatabase.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PropertiesPrincipalDatabase.java deleted file mode 100644 index 73d58ca489..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PropertiesPrincipalDatabase.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.security.auth.database; - -import org.apache.qpid.server.security.auth.sasl.AuthenticationProviderInitialiser; -import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal; -import org.apache.qpid.server.security.auth.sasl.crammd5.CRAMMD5Initialiser; -import org.apache.qpid.server.security.auth.sasl.plain.PlainInitialiser; - -import javax.security.auth.callback.PasswordCallback; -import javax.security.auth.login.AccountNotFoundException; -import java.util.Properties; -import java.util.Map; -import java.util.HashMap; -import java.util.List; -import java.util.LinkedList; -import java.security.Principal; -import java.io.IOException; -import java.io.UnsupportedEncodingException; - -public class PropertiesPrincipalDatabase implements PrincipalDatabase -{ - private Properties _users; - - private Map<String, AuthenticationProviderInitialiser> _saslServers; - - public PropertiesPrincipalDatabase(Properties users) - { - _users = users; - - _saslServers = new HashMap<String, AuthenticationProviderInitialiser>(); - - /** - * Create Authenticators for Properties Principal Database. - */ - - // Accept MD5 incomming and use plain comparison with the file - PlainInitialiser cram = new PlainInitialiser(); - cram.initialise(this); - // Accept Plain incomming and hash it for comparison to the file. - CRAMMD5Initialiser plain = new CRAMMD5Initialiser(); - plain.initialise(this, CRAMMD5Initialiser.HashDirection.INCOMMING); - - _saslServers.put(plain.getMechanismName(), cram); - _saslServers.put(cram.getMechanismName(), plain); - } - - public void setPassword(Principal principal, PasswordCallback callback) throws IOException, AccountNotFoundException - { - if (principal == null) - { - throw new IllegalArgumentException("principal must not be null"); - } - char[] pwd = _users.getProperty(principal.getName()).toCharArray(); - if (pwd != null) - { - callback.setPassword(pwd); - } - else - { - throw new AccountNotFoundException("No account found for principal " + principal); - } - } - - public boolean verifyPassword(String principal, char[] password) throws AccountNotFoundException - { - //fixme this is not correct as toCharArray is not safe based on the type of string. - char[] pwd = _users.getProperty(principal).toCharArray(); - - return compareCharArray(pwd, password); - } - - public boolean updatePassword(Principal principal, char[] password) throws AccountNotFoundException - { - return false; // updates denied - } - - public boolean createPrincipal(Principal principal, char[] password) - { - return false; // updates denied - } - - public boolean deletePrincipal(Principal principal) throws AccountNotFoundException - { - return false; // updates denied - } - - private boolean compareCharArray(char[] a, char[] b) - { - boolean equal = false; - if (a.length == b.length) - { - equal = true; - int index = 0; - while (equal && index < a.length) - { - equal = a[index] == b[index]; - index++; - } - } - return equal; - } - - private char[] convertPassword(String password) throws UnsupportedEncodingException - { - byte[] passwdBytes = password.getBytes("utf-8"); - - char[] passwd = new char[passwdBytes.length]; - - int index = 0; - - for (byte b : passwdBytes) - { - passwd[index++] = (char) b; - } - - return passwd; - } - - - public Map<String, AuthenticationProviderInitialiser> getMechanisms() - { - return _saslServers; - } - - public List<Principal> getUsers() - { - return new LinkedList<Principal>(); //todo - } - - public Principal getUser(String username) - { - if (_users.getProperty(username) != null) - { - return new UsernamePrincipal(username); - } - else - { - return null; - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PropertiesPrincipalDatabaseManager.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PropertiesPrincipalDatabaseManager.java deleted file mode 100644 index 6b86a46bd2..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PropertiesPrincipalDatabaseManager.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.security.auth.database; - -import org.apache.commons.configuration.Configuration; - -import java.util.Map; -import java.util.Properties; -import java.util.HashMap; - -public class PropertiesPrincipalDatabaseManager implements PrincipalDatabaseManager -{ - - Map<String, PrincipalDatabase> _databases = new HashMap<String, PrincipalDatabase>(); - - public PropertiesPrincipalDatabaseManager(String name, Properties users) - { - _databases.put(name, new PropertiesPrincipalDatabase(users)); - } - - public Map<String, PrincipalDatabase> getDatabases() - { - return _databases; - } - - public void initialiseManagement(Configuration config) - { - //todo - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/AuthenticationManager.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/AuthenticationManager.java deleted file mode 100644 index bb94e0b7bf..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/AuthenticationManager.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.security.auth.manager; - -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.security.auth.AuthenticationResult; - -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; - -public interface AuthenticationManager -{ - String getMechanisms(); - - SaslServer createSaslServer(String mechanism, String localFQDN) throws SaslException; - - AuthenticationResult authenticate(SaslServer server, byte[] response); - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManager.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManager.java deleted file mode 100644 index ce5e0cd748..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManager.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.security.auth.manager; - -import org.apache.log4j.Logger; -import org.apache.commons.configuration.Configuration; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.configuration.SubsetConfiguration; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.security.auth.manager.AuthenticationManager; -import org.apache.qpid.server.security.auth.database.PrincipalDatabase; -import org.apache.qpid.server.security.auth.sasl.JCAProvider; -import org.apache.qpid.server.security.auth.sasl.AuthenticationProviderInitialiser; -import org.apache.qpid.server.security.auth.AuthenticationResult; - -import javax.security.auth.callback.CallbackHandler; -import javax.security.sasl.SaslServerFactory; -import javax.security.sasl.SaslServer; -import javax.security.sasl.SaslException; -import javax.security.sasl.Sasl; -import java.util.Map; -import java.util.HashMap; -import java.util.TreeMap; -import java.security.Security; - -public class PrincipalDatabaseAuthenticationManager implements AuthenticationManager -{ - private static final Logger _logger = Logger.getLogger(PrincipalDatabaseAuthenticationManager.class); - - /** The list of mechanisms, in the order in which they are configured (i.e. preferred order) */ - private String _mechanisms; - - /** Maps from the mechanism to the callback handler to use for handling those requests */ - private Map<String, CallbackHandler> _callbackHandlerMap = new HashMap<String, CallbackHandler>(); - - /** - * Maps from the mechanism to the properties used to initialise the server. See the method Sasl.createSaslServer for - * details of the use of these properties. This map is populated during initialisation of each provider. - */ - private Map<String, Map<String, ?>> _serverCreationProperties = new HashMap<String, Map<String, ?>>(); - - private AuthenticationManager _default = null; - - public PrincipalDatabaseAuthenticationManager(String name, Configuration hostConfig) throws Exception - { - _logger.info("Initialising " + (name == null ? "Default" : "'" + name + "'") - + " PrincipleDatabase authentication manager."); - - // Fixme This should be done per Vhost but allowing global hack isn't right but ... - // required as authentication is done before Vhost selection - - Map<String, Class<? extends SaslServerFactory>> providerMap = new TreeMap<String, Class<? extends SaslServerFactory>>(); - - - if (name == null || hostConfig == null) - { - initialiseAuthenticationMechanisms(providerMap, ApplicationRegistry.getInstance().getDatabaseManager().getDatabases()); - } - else - { - String databaseName = hostConfig.getString("security.authentication.name"); - - if (databaseName == null) - { - - if (hostConfig instanceof SubsetConfiguration) - { - _logger.warn("No authentication specified for '" + ((SubsetConfiguration) hostConfig).getPrefix() + "'. Using Default authentication manager"); - } - else - { - _logger.warn("No authentication specified. Using Default authentication manager"); - } - _default = ApplicationRegistry.getInstance().getAuthenticationManager(); - return; - } - else - { - PrincipalDatabase database = ApplicationRegistry.getInstance().getDatabaseManager().getDatabases().get(databaseName); - - if (database == null) - { - throw new ConfigurationException("Requested database:" + databaseName + " was not found"); - } - - initialiseAuthenticationMechanisms(providerMap, database); - } - } - - if (providerMap.size() > 0) - { - // Ensure we are used before the defaults - if (Security.insertProviderAt(new JCAProvider(providerMap), 1) == -1) - { - _logger.warn("Unable to set order of providers."); - } - } - else - { - _logger.warn("No additional SASL providers registered."); - } - - } - - - private void initialiseAuthenticationMechanisms(Map<String, Class<? extends SaslServerFactory>> providerMap, Map<String, PrincipalDatabase> databases) throws Exception - { -// Configuration config = ApplicationRegistry.getInstance().getConfiguration(); -// List<String> mechanisms = config.getList("security.sasl.mechanisms.mechanism.initialiser.class"); -// -// // Maps from the mechanism to the properties used to initialise the server. See the method -// // Sasl.createSaslServer for details of the use of these properties. This map is populated during initialisation -// // of each provider. - - - if (databases.size() > 1) - { - _logger.warn("More than one principle database provided currently authentication mechanism will override each other."); - } - - for (Map.Entry<String, PrincipalDatabase> entry : databases.entrySet()) - { - - // fixme As the database now provide the mechanisms they support, they will ... - // overwrite each other in the map. There should only be one database per vhost. - // But currently we must have authentication before vhost definition. - initialiseAuthenticationMechanisms(providerMap, entry.getValue()); - } - - } - - private void initialiseAuthenticationMechanisms(Map<String, Class<? extends SaslServerFactory>> providerMap, PrincipalDatabase database) throws Exception - { - if (database == null || database.getMechanisms().size() == 0) - { - _logger.warn("No Database or no mechanisms to initialise authentication"); - return; - } - - for (Map.Entry<String, AuthenticationProviderInitialiser> mechanism : database.getMechanisms().entrySet()) - { - initialiseAuthenticationMechanism(mechanism.getKey(), mechanism.getValue(), providerMap); - } - } - - private void initialiseAuthenticationMechanism(String mechanism, AuthenticationProviderInitialiser initialiser, - Map<String, Class<? extends SaslServerFactory>> providerMap) - throws Exception - { - if (_mechanisms == null) - { - _mechanisms = mechanism; - } - else - { - // simple append should be fine since the number of mechanisms is small and this is a one time initialisation - _mechanisms = _mechanisms + " " + mechanism; - } - _callbackHandlerMap.put(mechanism, initialiser.getCallbackHandler()); - _serverCreationProperties.put(mechanism, initialiser.getProperties()); - Class<? extends SaslServerFactory> factory = initialiser.getServerFactoryClassForJCARegistration(); - if (factory != null) - { - providerMap.put(mechanism, factory); - } - _logger.info("Initialised " + mechanism + " SASL provider successfully"); - } - - public String getMechanisms() - { - if (_default != null) - { - // Use the default AuthenticationManager if present - return _default.getMechanisms(); - } - else - { - return _mechanisms; - } - } - - public SaslServer createSaslServer(String mechanism, String localFQDN) throws SaslException - { - if (_default != null) - { - // Use the default AuthenticationManager if present - return _default.createSaslServer(mechanism, localFQDN); - } - else - { - return Sasl.createSaslServer(mechanism, "AMQP", localFQDN, _serverCreationProperties.get(mechanism), - _callbackHandlerMap.get(mechanism)); - } - - } - - public AuthenticationResult authenticate(SaslServer server, byte[] response) - { - // Use the default AuthenticationManager if present - if (_default != null) - { - return _default.authenticate(server, response); - } - - - try - { - // Process response from the client - byte[] challenge = server.evaluateResponse(response != null ? response : new byte[0]); - - if (server.isComplete()) - { - return new AuthenticationResult(challenge, AuthenticationResult.AuthenticationStatus.SUCCESS); - } - else - { - return new AuthenticationResult(challenge, AuthenticationResult.AuthenticationStatus.CONTINUE); - } - } - catch (SaslException e) - { - return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR); - } - } - - public AuthenticationResult isAuthorize(VirtualHost vhost, String username) - { - return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/AuthenticationProviderInitialiser.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/AuthenticationProviderInitialiser.java deleted file mode 100644 index 89e545d6f5..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/AuthenticationProviderInitialiser.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.security.auth.sasl; - -import java.util.Map; - -import javax.security.auth.callback.CallbackHandler; -import javax.security.sasl.SaslServerFactory; - -import org.apache.commons.configuration.Configuration; -import org.apache.qpid.server.security.auth.database.PrincipalDatabase; - -public interface AuthenticationProviderInitialiser -{ - /** - * @return the mechanism's name. This will be used in the list of mechanism's advertised to the - * client. - */ - String getMechanismName(); - - /** - * Initialise the authentication provider. - * @param baseConfigPath the path in the config file that points to any config options for this provider. Each - * provider can have its own set of configuration options - * @param configuration the Apache Commons Configuration instance used to configure this provider - * @param principalDatabases the set of principal databases that are available - * @throws Exception needs refined Exception is too broad. - */ - void initialise(String baseConfigPath, Configuration configuration, - Map<String, PrincipalDatabase> principalDatabases) throws Exception; - - /** - * Initialise the authentication provider. - * @param db The principal database to initialise with - */ - void initialise(PrincipalDatabase db); - - - /** - * @return the callback handler that should be used to process authentication requests for this mechanism. This will - * be called after initialise and will be stored by the authentication manager. The callback handler <b>must</b> be - * fully threadsafe. - */ - CallbackHandler getCallbackHandler(); - - /** - * Get the properties that must be passed in to the Sasl.createSaslServer method. - * @return the properties, which may be null - */ - Map<String, ?> getProperties(); - - /** - * Get the class that is the server factory. This is used for the JCA registration. - * @return null if no JCA registration is required, otherwise return the class - * that will be used in JCA registration - */ - Class<? extends SaslServerFactory> getServerFactoryClassForJCARegistration(); -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/JCAProvider.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/JCAProvider.java deleted file mode 100644 index fd4ad86055..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/JCAProvider.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.security.auth.sasl; - -import java.security.Provider; -import java.security.Security; -import java.util.Map; - -import javax.security.sasl.SaslServerFactory; - -public final class JCAProvider extends Provider -{ - public JCAProvider(Map<String, Class<? extends SaslServerFactory>> providerMap) - { - super("AMQSASLProvider", 1.0, "A JCA provider that registers all " + - "AMQ SASL providers that want to be registered"); - register(providerMap); - //Security.addProvider(this); - } - - private void register(Map<String, Class<? extends SaslServerFactory>> providerMap) - { - for (Map.Entry<String, Class<? extends SaslServerFactory>> me : - providerMap.entrySet()) - { - put("SaslServerFactory." + me.getKey(), me.getValue().getName()); - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/UsernamePasswordInitialiser.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/UsernamePasswordInitialiser.java deleted file mode 100644 index dd0bd096c3..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/UsernamePasswordInitialiser.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.security.auth.sasl; - -import java.io.IOException; -import java.security.Principal; -import java.util.Map; - -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.callback.NameCallback; -import javax.security.auth.callback.PasswordCallback; -import javax.security.auth.callback.UnsupportedCallbackException; -import javax.security.auth.login.AccountNotFoundException; -import javax.security.sasl.AuthorizeCallback; - -import org.apache.commons.configuration.Configuration; - -import org.apache.log4j.Logger; - -import org.apache.qpid.server.security.auth.database.PrincipalDatabase; -import org.apache.qpid.server.security.auth.sasl.AuthenticationProviderInitialiser; -import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal; - -public abstract class UsernamePasswordInitialiser implements AuthenticationProviderInitialiser -{ - protected static final Logger _logger = Logger.getLogger(UsernamePasswordInitialiser.class); - - private ServerCallbackHandler _callbackHandler; - - private class ServerCallbackHandler implements CallbackHandler - { - private final PrincipalDatabase _principalDatabase; - - protected ServerCallbackHandler(PrincipalDatabase database) - { - _principalDatabase = database; - } - - public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException - { - Principal username = null; - for (Callback callback : callbacks) - { - if (callback instanceof NameCallback) - { - username = new UsernamePrincipal(((NameCallback) callback).getDefaultName()); - } - else if (callback instanceof PasswordCallback) - { - try - { - _principalDatabase.setPassword(username, (PasswordCallback) callback); - } - catch (AccountNotFoundException e) - { - // very annoyingly the callback handler does not throw anything more appropriate than - // IOException - IOException ioe = new IOException("Error looking up user " + e); - ioe.initCause(e); - throw ioe; - } - } - else if (callback instanceof AuthorizeCallback) - { - ((AuthorizeCallback) callback).setAuthorized(true); - } - else - { - throw new UnsupportedCallbackException(callback); - } - } - } - } - - public void initialise(String baseConfigPath, Configuration configuration, - Map<String, PrincipalDatabase> principalDatabases) throws Exception - { - String principalDatabaseName = configuration.getString(baseConfigPath + ".principal-database"); - PrincipalDatabase db = principalDatabases.get(principalDatabaseName); - - initialise(db); - } - - public void initialise(PrincipalDatabase db) - { - if (db == null) - { - throw new NullPointerException("Cannot initialise with a null Principal database."); - } - - _callbackHandler = new ServerCallbackHandler(db); - } - - public CallbackHandler getCallbackHandler() - { - return _callbackHandler; - } - - public Map<String, ?> getProperties() - { - // there are no properties required for the CRAM-MD5 implementation - return null; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/UsernamePrincipal.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/UsernamePrincipal.java deleted file mode 100644 index d7c8383690..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/UsernamePrincipal.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.server.security.auth.sasl; - -import java.security.Principal; - -/** A principal that is just a wrapper for a simple username. */ -public class UsernamePrincipal implements Principal -{ - private String _name; - - public UsernamePrincipal(String name) - { - _name = name; - } - - public String getName() - { - return _name; - } - - public String toString() - { - return _name; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainInitialiser.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainInitialiser.java deleted file mode 100644 index 7acc6322d1..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainInitialiser.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.security.auth.sasl.amqplain; - -import javax.security.sasl.SaslServerFactory; - -import org.apache.qpid.server.security.auth.sasl.UsernamePasswordInitialiser; - -public class AmqPlainInitialiser extends UsernamePasswordInitialiser -{ - public String getMechanismName() - { - return "AMQPLAIN"; - } - - public Class<? extends SaslServerFactory> getServerFactoryClassForJCARegistration() - { - return AmqPlainSaslServerFactory.class; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainSaslServer.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainSaslServer.java deleted file mode 100644 index 7842f376fb..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainSaslServer.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.security.auth.sasl.amqplain; - -import java.io.IOException; - -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.callback.NameCallback; -import javax.security.auth.callback.PasswordCallback; -import javax.security.auth.callback.UnsupportedCallbackException; -import javax.security.sasl.AuthorizeCallback; -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; - -import org.apache.mina.common.ByteBuffer; -import org.apache.qpid.framing.AMQFrameDecodingException; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.FieldTableFactory; - -public class AmqPlainSaslServer implements SaslServer -{ - public static final String MECHANISM = "AMQPLAIN"; - - private CallbackHandler _cbh; - - private String _authorizationId; - - private boolean _complete = false; - - public AmqPlainSaslServer(CallbackHandler cbh) - { - _cbh = cbh; - } - - public String getMechanismName() - { - return MECHANISM; - } - - public byte[] evaluateResponse(byte[] response) throws SaslException - { - try - { - final FieldTable ft = FieldTableFactory.newFieldTable(ByteBuffer.wrap(response), response.length); - String username = (String) ft.getString("LOGIN"); - // we do not care about the prompt but it throws if null - NameCallback nameCb = new NameCallback("prompt", username); - // we do not care about the prompt but it throws if null - PasswordCallback passwordCb = new PasswordCallback("prompt", false); - // TODO: should not get pwd as a String but as a char array... - String pwd = (String) ft.getString("PASSWORD"); - passwordCb.setPassword(pwd.toCharArray()); - AuthorizeCallback authzCb = new AuthorizeCallback(username, username); - Callback[] callbacks = new Callback[]{nameCb, passwordCb, authzCb}; - _cbh.handle(callbacks); - _complete = true; - if (authzCb.isAuthorized()) - { - _authorizationId = authzCb.getAuthenticationID(); - return null; - } - else - { - throw new SaslException("Authentication failed"); - } - } - catch (AMQFrameDecodingException e) - { - throw new SaslException("Unable to decode response: " + e, e); - } - catch (IOException e) - { - throw new SaslException("Error processing data: " + e, e); - } - catch (UnsupportedCallbackException e) - { - throw new SaslException("Unable to obtain data from callback handler: " + e, e); - } - } - - public boolean isComplete() - { - return _complete; - } - - public String getAuthorizationID() - { - return _authorizationId; - } - - public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException - { - throw new SaslException("Unsupported operation"); - } - - public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException - { - throw new SaslException("Unsupported operation"); - } - - public Object getNegotiatedProperty(String propName) - { - return null; - } - - public void dispose() throws SaslException - { - _cbh = null; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainSaslServerFactory.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainSaslServerFactory.java deleted file mode 100644 index 67d20136bf..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainSaslServerFactory.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.security.auth.sasl.amqplain; - -import java.util.Map; - -import javax.security.auth.callback.CallbackHandler; -import javax.security.sasl.Sasl; -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; -import javax.security.sasl.SaslServerFactory; - -public class AmqPlainSaslServerFactory implements SaslServerFactory -{ - public SaslServer createSaslServer(String mechanism, String protocol, String serverName, Map props, - CallbackHandler cbh) throws SaslException - { - if (AmqPlainSaslServer.MECHANISM.equals(mechanism)) - { - return new AmqPlainSaslServer(cbh); - } - else - { - return null; - } - } - - public String[] getMechanismNames(Map props) - { - if (props.containsKey(Sasl.POLICY_NOPLAINTEXT) || - props.containsKey(Sasl.POLICY_NODICTIONARY) || - props.containsKey(Sasl.POLICY_NOACTIVE)) - { - // returned array must be non null according to interface documentation - return new String[0]; - } - else - { - return new String[]{AmqPlainSaslServer.MECHANISM}; - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedInitialiser.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedInitialiser.java deleted file mode 100644 index 97f9a4e91a..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedInitialiser.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.server.security.auth.sasl.crammd5; - -import org.apache.qpid.server.security.auth.sasl.UsernamePasswordInitialiser; -import org.apache.qpid.server.security.auth.database.PrincipalDatabase; - -import javax.security.sasl.SaslServerFactory; -import java.util.Map; - -public class CRAMMD5HashedInitialiser extends UsernamePasswordInitialiser -{ - public String getMechanismName() - { - return CRAMMD5HashedSaslServer.MECHANISM; - } - - public Class<? extends SaslServerFactory> getServerFactoryClassForJCARegistration() - { - return CRAMMD5HashedServerFactory.class; - } - - public void initialise(PrincipalDatabase passwordFile) - { - super.initialise(passwordFile); - } - - public Map<String, ?> getProperties() - { - return null; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedSaslServer.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedSaslServer.java deleted file mode 100644 index f6cab084ea..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedSaslServer.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.security.auth.sasl.crammd5; - -import javax.security.sasl.SaslServer; -import javax.security.sasl.SaslException; -import javax.security.sasl.Sasl; -import javax.security.sasl.SaslServerFactory; -import javax.security.auth.callback.CallbackHandler; -import java.util.Enumeration; -import java.util.Map; - -public class CRAMMD5HashedSaslServer implements SaslServer -{ - public static final String MECHANISM = "CRAM-MD5-HASHED"; - - private SaslServer _realServer; - - public CRAMMD5HashedSaslServer(String mechanism, String protocol, String serverName, Map<String, ?> props, - CallbackHandler cbh) throws SaslException - { - Enumeration factories = Sasl.getSaslServerFactories(); - - while (factories.hasMoreElements()) - { - SaslServerFactory factory = (SaslServerFactory) factories.nextElement(); - - if (factory instanceof CRAMMD5HashedServerFactory) - { - continue; - } - - String[] mechs = factory.getMechanismNames(props); - - for (String mech : mechs) - { - if (mech.equals("CRAM-MD5")) - { - _realServer = factory.createSaslServer("CRAM-MD5", protocol, serverName, props, cbh); - return; - } - } - } - - throw new RuntimeException("No default SaslServer found for mechanism:" + "CRAM-MD5"); - } - - public String getMechanismName() - { - return MECHANISM; - } - - public byte[] evaluateResponse(byte[] response) throws SaslException - { - return _realServer.evaluateResponse(response); - } - - public boolean isComplete() - { - return _realServer.isComplete(); - } - - public String getAuthorizationID() - { - return _realServer.getAuthorizationID(); - } - - public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException - { - return _realServer.unwrap(incoming, offset, len); - } - - public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException - { - return _realServer.wrap(outgoing, offset, len); - } - - public Object getNegotiatedProperty(String propName) - { - return _realServer.getNegotiatedProperty(propName); - } - - public void dispose() throws SaslException - { - _realServer.dispose(); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedServerFactory.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedServerFactory.java deleted file mode 100644 index 5298b5cc63..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedServerFactory.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.security.auth.sasl.crammd5; - -import java.util.Map; - -import javax.security.auth.callback.CallbackHandler; -import javax.security.sasl.Sasl; -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; -import javax.security.sasl.SaslServerFactory; - -public class CRAMMD5HashedServerFactory implements SaslServerFactory -{ - public SaslServer createSaslServer(String mechanism, String protocol, String serverName, Map<String, ?> props, - CallbackHandler cbh) throws SaslException - { - if (mechanism.equals(CRAMMD5HashedSaslServer.MECHANISM)) - { - return new CRAMMD5HashedSaslServer(mechanism, protocol, serverName, props, cbh); - } - else - { - return null; - } - } - - public String[] getMechanismNames(Map props) - { - if (props != null) - { - if (props.containsKey(Sasl.POLICY_NOPLAINTEXT) || - props.containsKey(Sasl.POLICY_NODICTIONARY) || - props.containsKey(Sasl.POLICY_NOACTIVE)) - { - // returned array must be non null according to interface documentation - return new String[0]; - } - } - - return new String[]{CRAMMD5HashedSaslServer.MECHANISM}; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5Initialiser.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5Initialiser.java deleted file mode 100644 index 264832888d..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5Initialiser.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.security.auth.sasl.crammd5; - -import org.apache.qpid.server.security.auth.sasl.UsernamePasswordInitialiser; -import org.apache.qpid.server.security.auth.database.PrincipalDatabase; - -import javax.security.sasl.SaslServerFactory; - -public class CRAMMD5Initialiser extends UsernamePasswordInitialiser -{ - private HashDirection _hashDirection; - - public enum HashDirection - { - INCOMMING, PASSWORD_FILE - } - - - public String getMechanismName() - { - return "CRAM-MD5"; - } - - public Class<? extends SaslServerFactory> getServerFactoryClassForJCARegistration() - { - // since the CRAM-MD5 provider is registered as part of the JDK, we do not - // return the factory class here since we do not need to register it ourselves. - if (_hashDirection == HashDirection.PASSWORD_FILE) - { - return null; - } - else - { - //fixme we need a server that will correctly has the incomming plain text for comparison to file. - _logger.warn("we need a server that will correctly convert the incomming plain text for comparison to file."); - return null; - } - } - - public void initialise(PrincipalDatabase passwordFile) - { - initialise(passwordFile, HashDirection.PASSWORD_FILE); - } - - public void initialise(PrincipalDatabase passwordFile, HashDirection direction) - { - super.initialise(passwordFile); - - _hashDirection = direction; - } - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainInitialiser.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainInitialiser.java deleted file mode 100644 index 1d16cd8755..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainInitialiser.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.security.auth.sasl.plain; - -import javax.security.sasl.SaslServerFactory; - -import org.apache.qpid.server.security.auth.sasl.UsernamePasswordInitialiser; - -public class PlainInitialiser extends UsernamePasswordInitialiser -{ - public String getMechanismName() - { - return "PLAIN"; - } - - public Class<? extends SaslServerFactory> getServerFactoryClassForJCARegistration() - { - return PlainSaslServerFactory.class; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServer.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServer.java deleted file mode 100644 index 36aeb77fe1..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServer.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.security.auth.sasl.plain; - -import java.io.IOException; - -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.callback.NameCallback; -import javax.security.auth.callback.PasswordCallback; -import javax.security.auth.callback.UnsupportedCallbackException; -import javax.security.sasl.AuthorizeCallback; -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; - -public class PlainSaslServer implements SaslServer -{ - public static final String MECHANISM = "PLAIN"; - - private CallbackHandler _cbh; - - private String _authorizationId; - - private boolean _complete = false; - - public PlainSaslServer(CallbackHandler cbh) - { - _cbh = cbh; - } - - public String getMechanismName() - { - return MECHANISM; - } - - public byte[] evaluateResponse(byte[] response) throws SaslException - { - try - { - int authzidNullPosition = findNullPosition(response, 0); - if (authzidNullPosition < 0) - { - throw new SaslException("Invalid PLAIN encoding, authzid null terminator not found"); - } - int authcidNullPosition = findNullPosition(response, authzidNullPosition + 1); - if (authcidNullPosition < 0) - { - throw new SaslException("Invalid PLAIN encoding, authcid null terminator not found"); - } - - // we do not currently support authcid in any meaningful way - // String authcid = new String(response, 0, authzidNullPosition, "utf8"); - String authzid = new String(response, authzidNullPosition + 1, authcidNullPosition - 1, "utf8"); - - // we do not care about the prompt but it throws if null - NameCallback nameCb = new NameCallback("prompt", authzid); - // we do not care about the prompt but it throws if null - PasswordCallback passwordCb = new PasswordCallback("prompt", false); - // TODO: should not get pwd as a String but as a char array... - int passwordLen = response.length - authcidNullPosition - 1; - String pwd = new String(response, authcidNullPosition + 1, passwordLen, "utf8"); - passwordCb.setPassword(pwd.toCharArray()); - AuthorizeCallback authzCb = new AuthorizeCallback(authzid, authzid); - Callback[] callbacks = new Callback[]{nameCb, passwordCb, authzCb}; - _cbh.handle(callbacks); - _complete = true; - if (authzCb.isAuthorized()) - { - _authorizationId = authzCb.getAuthenticationID(); - return null; - } - else - { - throw new SaslException("Authentication failed"); - } - } - catch (IOException e) - { - throw new SaslException("Error processing data: " + e, e); - } - catch (UnsupportedCallbackException e) - { - throw new SaslException("Unable to obtain data from callback handler: " + e, e); - } - } - - private int findNullPosition(byte[] response, int startPosition) - { - int position = startPosition; - while (position < response.length) - { - if (response[position] == (byte) 0) - { - return position; - } - position++; - } - return -1; - } - - public boolean isComplete() - { - return _complete; - } - - public String getAuthorizationID() - { - return _authorizationId; - } - - public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException - { - throw new SaslException("Unsupported operation"); - } - - public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException - { - throw new SaslException("Unsupported operation"); - } - - public Object getNegotiatedProperty(String propName) - { - return null; - } - - public void dispose() throws SaslException - { - _cbh = null; - } - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServerFactory.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServerFactory.java deleted file mode 100644 index f0dd9eeb6d..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServerFactory.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.security.auth.sasl.plain; - -import java.util.Map; - -import javax.security.auth.callback.CallbackHandler; -import javax.security.sasl.Sasl; -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; -import javax.security.sasl.SaslServerFactory; - -public class PlainSaslServerFactory implements SaslServerFactory -{ - public SaslServer createSaslServer(String mechanism, String protocol, String serverName, Map props, - CallbackHandler cbh) throws SaslException - { - if (PlainSaslServer.MECHANISM.equals(mechanism)) - { - return new PlainSaslServer(cbh); - } - else - { - return null; - } - } - - public String[] getMechanismNames(Map props) - { - if (props.containsKey(Sasl.POLICY_NOPLAINTEXT) || - props.containsKey(Sasl.POLICY_NODICTIONARY) || - props.containsKey(Sasl.POLICY_NOACTIVE)) - { - // returned array must be non null according to interface documentation - return new String[0]; - } - else - { - return new String[]{PlainSaslServer.MECHANISM}; - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/state/AMQState.java b/java/broker/src/main/java/org/apache/qpid/server/state/AMQState.java deleted file mode 100644 index f427cc7206..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/state/AMQState.java +++ /dev/null @@ -1,36 +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.state; - -/** - * States used in the AMQ protocol. Used by the finite state machine to determine - * valid responses. - */ -public enum AMQState -{ - CONNECTION_NOT_STARTED, - CONNECTION_NOT_AUTH, - CONNECTION_NOT_TUNED, - CONNECTION_NOT_OPENED, - CONNECTION_OPEN, - CONNECTION_CLOSING, - CONNECTION_CLOSED -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/state/AMQStateManager.java b/java/broker/src/main/java/org/apache/qpid/server/state/AMQStateManager.java deleted file mode 100644 index f96900d0a9..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/state/AMQStateManager.java +++ /dev/null @@ -1,284 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.state; - -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.CopyOnWriteArraySet; - -import org.apache.log4j.Logger; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQMethodBody; -import org.apache.qpid.framing.BasicAckBody; -import org.apache.qpid.framing.BasicCancelBody; -import org.apache.qpid.framing.BasicConsumeBody; -import org.apache.qpid.framing.BasicGetBody; -import org.apache.qpid.framing.BasicPublishBody; -import org.apache.qpid.framing.BasicQosBody; -import org.apache.qpid.framing.BasicRecoverBody; -import org.apache.qpid.framing.BasicRejectBody; -import org.apache.qpid.framing.ChannelCloseBody; -import org.apache.qpid.framing.ChannelCloseOkBody; -import org.apache.qpid.framing.ChannelFlowBody; -import org.apache.qpid.framing.ChannelOpenBody; -import org.apache.qpid.framing.ConnectionCloseBody; -import org.apache.qpid.framing.ConnectionCloseOkBody; -import org.apache.qpid.framing.ConnectionOpenBody; -import org.apache.qpid.framing.ConnectionSecureOkBody; -import org.apache.qpid.framing.ConnectionStartOkBody; -import org.apache.qpid.framing.ConnectionTuneOkBody; -import org.apache.qpid.framing.ExchangeBoundBody; -import org.apache.qpid.framing.ExchangeDeclareBody; -import org.apache.qpid.framing.ExchangeDeleteBody; -import org.apache.qpid.framing.QueueBindBody; -import org.apache.qpid.framing.QueueDeclareBody; -import org.apache.qpid.framing.QueueDeleteBody; -import org.apache.qpid.framing.QueuePurgeBody; -import org.apache.qpid.framing.TxCommitBody; -import org.apache.qpid.framing.TxRollbackBody; -import org.apache.qpid.framing.TxSelectBody; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.protocol.AMQMethodListener; -import org.apache.qpid.server.handler.BasicAckMethodHandler; -import org.apache.qpid.server.handler.BasicCancelMethodHandler; -import org.apache.qpid.server.handler.BasicConsumeMethodHandler; -import org.apache.qpid.server.handler.BasicGetMethodHandler; -import org.apache.qpid.server.handler.BasicPublishMethodHandler; -import org.apache.qpid.server.handler.BasicQosHandler; -import org.apache.qpid.server.handler.BasicRecoverMethodHandler; -import org.apache.qpid.server.handler.BasicRejectMethodHandler; -import org.apache.qpid.server.handler.ChannelCloseHandler; -import org.apache.qpid.server.handler.ChannelCloseOkHandler; -import org.apache.qpid.server.handler.ChannelFlowHandler; -import org.apache.qpid.server.handler.ChannelOpenHandler; -import org.apache.qpid.server.handler.ConnectionCloseMethodHandler; -import org.apache.qpid.server.handler.ConnectionCloseOkMethodHandler; -import org.apache.qpid.server.handler.ConnectionOpenMethodHandler; -import org.apache.qpid.server.handler.ConnectionSecureOkMethodHandler; -import org.apache.qpid.server.handler.ConnectionStartOkMethodHandler; -import org.apache.qpid.server.handler.ConnectionTuneOkMethodHandler; -import org.apache.qpid.server.handler.ExchangeBoundHandler; -import org.apache.qpid.server.handler.ExchangeDeclareHandler; -import org.apache.qpid.server.handler.ExchangeDeleteHandler; -import org.apache.qpid.server.handler.QueueBindHandler; -import org.apache.qpid.server.handler.QueueDeclareHandler; -import org.apache.qpid.server.handler.QueueDeleteHandler; -import org.apache.qpid.server.handler.QueuePurgeHandler; -import org.apache.qpid.server.handler.TxCommitHandler; -import org.apache.qpid.server.handler.TxRollbackHandler; -import org.apache.qpid.server.handler.TxSelectHandler; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.virtualhost.VirtualHostRegistry; - -/** - * The state manager is responsible for managing the state of the protocol session. <p/> For each AMQProtocolHandler - * there is a separate state manager. - */ -public class AMQStateManager implements AMQMethodListener -{ - private static final Logger _logger = Logger.getLogger(AMQStateManager.class); - - private final VirtualHostRegistry _virtualHostRegistry; - private final AMQProtocolSession _protocolSession; - /** The current state */ - private AMQState _currentState; - - /** - * Maps from an AMQState instance to a Map from Class to StateTransitionHandler. The class must be a subclass of - * AMQFrame. - */ - private final EnumMap<AMQState, Map<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>> _state2HandlersMap = - new EnumMap<AMQState, Map<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>>( - AMQState.class); - - private CopyOnWriteArraySet<StateListener> _stateListeners = new CopyOnWriteArraySet<StateListener>(); - - public AMQStateManager(VirtualHostRegistry virtualHostRegistry, AMQProtocolSession protocolSession) - { - this(AMQState.CONNECTION_NOT_STARTED, true, virtualHostRegistry, protocolSession); - } - - protected AMQStateManager(AMQState initial, boolean register, VirtualHostRegistry virtualHostRegistry, - AMQProtocolSession protocolSession) - { - _virtualHostRegistry = virtualHostRegistry; - _protocolSession = protocolSession; - _currentState = initial; - if (register) - { - registerListeners(); - } - } - - protected void registerListeners() - { - Map<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>> frame2handlerMap; - - frame2handlerMap = new HashMap<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>(); - frame2handlerMap.put(ConnectionStartOkBody.class, ConnectionStartOkMethodHandler.getInstance()); - _state2HandlersMap.put(AMQState.CONNECTION_NOT_STARTED, frame2handlerMap); - - frame2handlerMap = new HashMap<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>(); - frame2handlerMap.put(ConnectionSecureOkBody.class, ConnectionSecureOkMethodHandler.getInstance()); - _state2HandlersMap.put(AMQState.CONNECTION_NOT_AUTH, frame2handlerMap); - - frame2handlerMap = new HashMap<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>(); - frame2handlerMap.put(ConnectionTuneOkBody.class, ConnectionTuneOkMethodHandler.getInstance()); - _state2HandlersMap.put(AMQState.CONNECTION_NOT_TUNED, frame2handlerMap); - - frame2handlerMap = new HashMap<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>(); - frame2handlerMap.put(ConnectionOpenBody.class, ConnectionOpenMethodHandler.getInstance()); - _state2HandlersMap.put(AMQState.CONNECTION_NOT_OPENED, frame2handlerMap); - - // - // ConnectionOpen handlers - // - frame2handlerMap = new HashMap<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>(); - frame2handlerMap.put(ChannelOpenBody.class, ChannelOpenHandler.getInstance()); - frame2handlerMap.put(ChannelCloseBody.class, ChannelCloseHandler.getInstance()); - frame2handlerMap.put(ChannelCloseOkBody.class, ChannelCloseOkHandler.getInstance()); - frame2handlerMap.put(ConnectionCloseBody.class, ConnectionCloseMethodHandler.getInstance()); - frame2handlerMap.put(ExchangeDeclareBody.class, ExchangeDeclareHandler.getInstance()); - frame2handlerMap.put(ExchangeDeleteBody.class, ExchangeDeleteHandler.getInstance()); - frame2handlerMap.put(ExchangeBoundBody.class, ExchangeBoundHandler.getInstance()); - frame2handlerMap.put(BasicAckBody.class, BasicAckMethodHandler.getInstance()); - frame2handlerMap.put(BasicRecoverBody.class, BasicRecoverMethodHandler.getInstance()); - frame2handlerMap.put(BasicConsumeBody.class, BasicConsumeMethodHandler.getInstance()); - frame2handlerMap.put(BasicGetBody.class, BasicGetMethodHandler.getInstance()); - frame2handlerMap.put(BasicCancelBody.class, BasicCancelMethodHandler.getInstance()); - frame2handlerMap.put(BasicPublishBody.class, BasicPublishMethodHandler.getInstance()); - frame2handlerMap.put(BasicQosBody.class, BasicQosHandler.getInstance()); - frame2handlerMap.put(QueueBindBody.class, QueueBindHandler.getInstance()); - frame2handlerMap.put(QueueDeclareBody.class, QueueDeclareHandler.getInstance()); - frame2handlerMap.put(QueueDeleteBody.class, QueueDeleteHandler.getInstance()); - frame2handlerMap.put(QueuePurgeBody.class, QueuePurgeHandler.getInstance()); - frame2handlerMap.put(ChannelFlowBody.class, ChannelFlowHandler.getInstance()); - frame2handlerMap.put(TxSelectBody.class, TxSelectHandler.getInstance()); - frame2handlerMap.put(TxCommitBody.class, TxCommitHandler.getInstance()); - frame2handlerMap.put(TxRollbackBody.class, TxRollbackHandler.getInstance()); - frame2handlerMap.put(BasicRejectBody.class, BasicRejectMethodHandler.getInstance()); - - _state2HandlersMap.put(AMQState.CONNECTION_OPEN, frame2handlerMap); - - frame2handlerMap = new HashMap<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>(); - frame2handlerMap.put(ConnectionCloseOkBody.class, ConnectionCloseOkMethodHandler.getInstance()); - _state2HandlersMap.put(AMQState.CONNECTION_CLOSING, frame2handlerMap); - - } - - public AMQState getCurrentState() - { - return _currentState; - } - - public void changeState(AMQState newState) throws AMQException - { - _logger.debug("State changing to " + newState + " from old state " + _currentState); - final AMQState oldState = _currentState; - _currentState = newState; - - for (StateListener l : _stateListeners) - { - l.stateChanged(oldState, newState); - } - } - - public void error(Exception e) - { - _logger.error("State manager received error notification[Current State:" + _currentState + "]: " + e, e); - for (StateListener l : _stateListeners) - { - l.error(e); - } - } - - public <B extends AMQMethodBody> boolean methodReceived(AMQMethodEvent<B> evt) throws AMQException - { - StateAwareMethodListener<B> handler = findStateTransitionHandler(_currentState, evt.getMethod()); - if (handler != null) - { - - checkChannel(evt, _protocolSession); - - handler.methodReceived(this, evt); - - return true; - } - - return false; - } - - private <B extends AMQMethodBody> void checkChannel(AMQMethodEvent<B> evt, AMQProtocolSession protocolSession) - throws AMQException - { - if ((evt.getChannelId() != 0) && !(evt.getMethod() instanceof ChannelOpenBody) - && (protocolSession.getChannel(evt.getChannelId()) == null) - && !protocolSession.channelAwaitingClosure(evt.getChannelId())) - { - throw evt.getMethod().getChannelNotFoundException(evt.getChannelId()); - } - } - - protected <B extends AMQMethodBody> StateAwareMethodListener<B> findStateTransitionHandler(AMQState currentState, - B frame) - // throws IllegalStateTransitionException - { - final Map<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>> classToHandlerMap = - _state2HandlersMap.get(currentState); - - final StateAwareMethodListener<B> handler = - (classToHandlerMap == null) ? null : (StateAwareMethodListener<B>) classToHandlerMap.get(frame.getClass()); - - if (handler == null) - { - _logger.debug("No state transition handler defined for receiving frame " + frame); - - return null; - } - else - { - return handler; - } - } - - public void addStateListener(StateListener listener) - { - _logger.debug("Adding state listener"); - _stateListeners.add(listener); - } - - public void removeStateListener(StateListener listener) - { - _stateListeners.remove(listener); - } - - public VirtualHostRegistry getVirtualHostRegistry() - { - return _virtualHostRegistry; - } - - public AMQProtocolSession getProtocolSession() - { - return _protocolSession; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/state/StateAwareMethodListener.java b/java/broker/src/main/java/org/apache/qpid/server/state/StateAwareMethodListener.java deleted file mode 100644 index e3af0bc486..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/state/StateAwareMethodListener.java +++ /dev/null @@ -1,35 +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.state; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQMethodBody; -import org.apache.qpid.protocol.AMQMethodEvent; - -/** - * A frame listener that is informed of the protocol state when invoked and has - * the opportunity to update state. - * - */ -public interface StateAwareMethodListener <B extends AMQMethodBody> -{ - void methodReceived(AMQStateManager stateManager, AMQMethodEvent<B> evt) throws AMQException; -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/state/StateListener.java b/java/broker/src/main/java/org/apache/qpid/server/state/StateListener.java deleted file mode 100644 index 00fc09867b..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/state/StateListener.java +++ /dev/null @@ -1,30 +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.state; - -import org.apache.qpid.AMQException; - -public interface StateListener -{ - void stateChanged(AMQState oldState, AMQState newState) throws AMQException; - - void error(Throwable t); -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/store/MemoryMessageStore.java b/java/broker/src/main/java/org/apache/qpid/server/store/MemoryMessageStore.java deleted file mode 100644 index 8ccb0be0a8..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/store/MemoryMessageStore.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.store; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.atomic.AtomicLong; - -import org.apache.commons.configuration.Configuration; -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.abstraction.ContentChunk; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.MessageMetaData; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.exchange.Exchange; - -/** - * A simple message store that stores the messages in a threadsafe structure in memory. - */ -public class MemoryMessageStore implements MessageStore -{ - private static final Logger _log = Logger.getLogger(MemoryMessageStore.class); - - private static final int DEFAULT_HASHTABLE_CAPACITY = 50000; - - private static final String HASHTABLE_CAPACITY_CONFIG = "hashtable-capacity"; - - protected ConcurrentMap<Long, MessageMetaData> _metaDataMap; - - protected ConcurrentMap<Long, List<ContentChunk>> _contentBodyMap; - - private final AtomicLong _messageId = new AtomicLong(1); - - public void configure() - { - _log.info("Using capacity " + DEFAULT_HASHTABLE_CAPACITY + " for hash tables"); - _metaDataMap = new ConcurrentHashMap<Long, MessageMetaData>(DEFAULT_HASHTABLE_CAPACITY); - _contentBodyMap = new ConcurrentHashMap<Long, List<ContentChunk>>(DEFAULT_HASHTABLE_CAPACITY); - } - - public void configure(String base, Configuration config) - { - int hashtableCapacity = config.getInt(base + "." + HASHTABLE_CAPACITY_CONFIG, DEFAULT_HASHTABLE_CAPACITY); - _log.info("Using capacity " + hashtableCapacity + " for hash tables"); - _metaDataMap = new ConcurrentHashMap<Long, MessageMetaData>(hashtableCapacity); - _contentBodyMap = new ConcurrentHashMap<Long, List<ContentChunk>>(hashtableCapacity); - } - - public void configure(VirtualHost virtualHost, String base, Configuration config) throws Exception - { - configure(base, config); - } - - public void close() throws Exception - { - if (_metaDataMap != null) - { - _metaDataMap.clear(); - _metaDataMap = null; - } - if (_contentBodyMap != null) - { - _contentBodyMap.clear(); - _contentBodyMap = null; - } - } - - public void removeMessage(StoreContext context, Long messageId) - { - if (_log.isDebugEnabled()) - { - _log.debug("Removing message with id " + messageId); - } - _metaDataMap.remove(messageId); - _contentBodyMap.remove(messageId); - } - - public void createExchange(Exchange exchange) throws AMQException - { - - } - - public void removeExchange(Exchange exchange) throws AMQException - { - - } - - public void bindQueue(Exchange exchange, AMQShortString routingKey, AMQQueue queue, FieldTable args) throws AMQException - { - - } - - public void unbindQueue(Exchange exchange, AMQShortString routingKey, AMQQueue queue, FieldTable args) throws AMQException - { - - } - - public void createQueue(AMQQueue queue) throws AMQException - { - // Not required to do anything - } - - public void removeQueue(AMQShortString name) throws AMQException - { - // Not required to do anything - } - - public void enqueueMessage(StoreContext context, AMQShortString name, Long messageId) throws AMQException - { - // Not required to do anything - } - - public void dequeueMessage(StoreContext context, AMQShortString name, Long messageId) throws AMQException - { - // Not required to do anything - } - - public void beginTran(StoreContext context) throws AMQException - { - // Not required to do anything - } - - public void commitTran(StoreContext context) throws AMQException - { - // Not required to do anything - } - - public void abortTran(StoreContext context) throws AMQException - { - // Not required to do anything - } - - public boolean inTran(StoreContext context) - { - return false; - } - - public List<AMQQueue> createQueues() throws AMQException - { - return null; - } - - public Long getNewMessageId() - { - return _messageId.getAndIncrement(); - } - - public void storeContentBodyChunk(StoreContext context, Long messageId, int index, ContentChunk contentBody, boolean lastContentBody) - throws AMQException - { - List<ContentChunk> bodyList = _contentBodyMap.get(messageId); - - if(bodyList == null && lastContentBody) - { - _contentBodyMap.put(messageId, Collections.singletonList(contentBody)); - } - else - { - if (bodyList == null) - { - bodyList = new ArrayList<ContentChunk>(); - _contentBodyMap.put(messageId, bodyList); - } - - bodyList.add(index, contentBody); - } - } - - public void storeMessageMetaData(StoreContext context, Long messageId, MessageMetaData messageMetaData) - throws AMQException - { - _metaDataMap.put(messageId, messageMetaData); - } - - public MessageMetaData getMessageMetaData(StoreContext context,Long messageId) throws AMQException - { - return _metaDataMap.get(messageId); - } - - public ContentChunk getContentBodyChunk(StoreContext context, Long messageId, int index) throws AMQException - { - List<ContentChunk> bodyList = _contentBodyMap.get(messageId); - return bodyList.get(index); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/store/MessageStore.java b/java/broker/src/main/java/org/apache/qpid/server/store/MessageStore.java deleted file mode 100644 index 2a83d9b649..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/store/MessageStore.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.server.store; - -import org.apache.commons.configuration.Configuration; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.abstraction.ContentChunk; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.MessageMetaData; -import org.apache.qpid.server.virtualhost.VirtualHost; - -/** - * MessageStore defines the interface to a storage area, which can be used to preserve the state of messages, queues - * and exchanges in a transactional manner. - * - * <p/>All message store, remove, enqueue and dequeue operations are carried out against a {@link StoreContext} which - * encapsulates the transactional context they are performed in. Many such operations can be carried out in a single - * transaction. - * - * <p/>The storage and removal of queues and exchanges, are not carried out in a transactional context. - * - * <p/><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities - * <tr><td> Accept transaction boundary demarcations: Begin, Commit, Abort. - * <tr><td> Store and remove queues. - * <tr><td> Store and remove exchanges. - * <tr><td> Store and remove messages. - * <tr><td> Bind and unbind queues to exchanges. - * <tr><td> Enqueue and dequeue messages to queues. - * <tr><td> Generate message identifiers. - * </table> - */ -public interface MessageStore -{ - /** - * Called after instantiation in order to configure the message store. A particular implementation can define - * whatever parameters it wants. - * - * @param virtualHost The virtual host using by this store - * @param base The base element identifier from which all configuration items are relative. For example, if - * the base element is "store", the all elements used by concrete classes will be "store.foo" etc. - * @param config The apache commons configuration object. - * - * @throws Exception If any error occurs that means the store is unable to configure itself. - */ - void configure(VirtualHost virtualHost, String base, Configuration config) throws Exception; - - /** - * Called to close and cleanup any resources used by the message store. - * - * @throws Exception If the close fails. - */ - void close() throws Exception; - - /** - * Removes the specified message from the store in the given transactional store context. - * - * @param storeContext The transactional context to remove the message in. - * @param messageId Identifies the message to remove. - * - * @throws AMQException If the operation fails for any reason. - */ - void removeMessage(StoreContext storeContext, Long messageId) throws AMQException; - - /** - * Makes the specified exchange persistent. - * - * @param exchange The exchange to persist. - * - * @throws AMQException If the operation fails for any reason. - */ - void createExchange(Exchange exchange) throws AMQException; - - /** - * Removes the specified persistent exchange. - * - * @param exchange The exchange to remove. - * - * @throws AMQException If the operation fails for any reason. - */ - void removeExchange(Exchange exchange) throws AMQException; - - /** - * Binds the specified queue to an exchange with a routing key. - * - * @param exchange The exchange to bind to. - * @param routingKey The routing key to bind by. - * @param queue The queue to bind. - * @param args Additional parameters. - * - * @throws AMQException If the operation fails for any reason. - */ - void bindQueue(Exchange exchange, AMQShortString routingKey, AMQQueue queue, FieldTable args) throws AMQException; - - /** - * Unbinds the specified from an exchange under a particular routing key. - * - * @param exchange The exchange to unbind from. - * @param routingKey The routing key to unbind. - * @param queue The queue to unbind. - * @param args Additonal parameters. - * - * @throws AMQException If the operation fails for any reason. - */ - void unbindQueue(Exchange exchange, AMQShortString routingKey, AMQQueue queue, FieldTable args) throws AMQException; - - /** - * Makes the specified queue persistent. - * - * @param queue The queue to store. - * - * @throws AMQException If the operation fails for any reason. - */ - void createQueue(AMQQueue queue) throws AMQException; - - /** - * Removes the specified queue from the persistent store. - * - * @param name The queue to remove. - * - * @throws AMQException If the operation fails for any reason. - */ - void removeQueue(AMQShortString name) throws AMQException; - - /** - * Places a message onto a specified queue, in a given transactional context. - * - * @param context The transactional context for the operation. - * @param name The name of the queue to place the message on. - * @param messageId The message to enqueue. - * - * @throws AMQException If the operation fails for any reason. - */ - void enqueueMessage(StoreContext context, AMQShortString name, Long messageId) throws AMQException; - - /** - * Extracts a message from a specified queue, in a given transactional context. - * - * @param context The transactional context for the operation. - * @param name The name of the queue to take the message from. - * @param messageId The message to dequeue. - * - * @throws AMQException If the operation fails for any reason, or if the specified message does not exist. - */ - void dequeueMessage(StoreContext context, AMQShortString name, Long messageId) throws AMQException; - - /** - * Begins a transactional context. - * - * @param context The transactional context to begin. - * - * @throws AMQException If the operation fails for any reason. - */ - void beginTran(StoreContext context) throws AMQException; - - /** - * Commits all operations performed within a given transactional context. - * - * @param context The transactional context to commit all operations for. - * - * @throws AMQException If the operation fails for any reason. - */ - void commitTran(StoreContext context) throws AMQException; - - /** - * Abandons all operations performed within a given transactional context. - * - * @param context The transactional context to abandon. - * - * @throws AMQException If the operation fails for any reason. - */ - void abortTran(StoreContext context) throws AMQException; - - /** - * Tests a transactional context to see if it has been begun but not yet committed or aborted. - * - * @param context The transactional context to test. - * - * @return <tt>true</tt> if the transactional context is live, <tt>false</tt> otherwise. - */ - boolean inTran(StoreContext context); - - /** - * Return a valid, currently unused message id. - * - * @return A fresh message id. - */ - Long getNewMessageId(); - - /** - * Stores a chunk of message data. - * - * @param context The transactional context for the operation. - * @param messageId The message to store the data for. - * @param index The index of the data chunk. - * @param contentBody The content of the data chunk. - * @param lastContentBody Flag to indicate that this is the last such chunk for the message. - * - * @throws AMQException If the operation fails for any reason, or if the specified message does not exist. - */ - void storeContentBodyChunk(StoreContext context, Long messageId, int index, ContentChunk contentBody, - boolean lastContentBody) throws AMQException; - - /** - * Stores message meta-data. - * - * @param context The transactional context for the operation. - * @param messageId The message to store the data for. - * @param messageMetaData The message meta data to store. - * - * @throws AMQException If the operation fails for any reason, or if the specified message does not exist. - */ - void storeMessageMetaData(StoreContext context, Long messageId, MessageMetaData messageMetaData) throws AMQException; - - /** - * Retrieves message meta-data. - * - * @param context The transactional context for the operation. - * @param messageId The message to get the meta-data for. - * - * @return The message meta data. - * - * @throws AMQException If the operation fails for any reason, or if the specified message does not exist. - */ - MessageMetaData getMessageMetaData(StoreContext context, Long messageId) throws AMQException; - - /** - * Retrieves a chunk of message data. - * - * @param context The transactional context for the operation. - * @param messageId The message to get the data chunk for. - * @param index The offset index of the data chunk within the message. - * - * @return A chunk of message data. - * - * @throws AMQException If the operation fails for any reason, or if the specified message does not exist. - */ - ContentChunk getContentBodyChunk(StoreContext context, Long messageId, int index) throws AMQException; -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/store/StoreContext.java b/java/broker/src/main/java/org/apache/qpid/server/store/StoreContext.java deleted file mode 100644 index 3ee49d58cf..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/store/StoreContext.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.store; - -import org.apache.log4j.Logger; - -/** - * A context that the store can use to associate with a transactional context. For example, it could store - * some kind of txn id. - * - * @author Apache Software Foundation - */ -public class StoreContext -{ - private static final Logger _logger = Logger.getLogger(StoreContext.class); - - private String _name; - private Object _payload; - - public StoreContext() - { - _name = super.toString(); - } - - public StoreContext(String name) - { - _name = name; - } - - public Object getPayload() - { - return _payload; - } - - public void setPayload(Object payload) - { - _logger.debug("public void setPayload(Object payload = " + payload + "): called"); - _payload = payload; - } - - /** - * Prints out the transactional context as a string, mainly for debugging purposes. - * - * @return The transactional context as a string. - */ - public String toString() - { - return "<_name = " + _name + ", _payload = " + _payload + ">"; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/transport/ConnectorConfiguration.java b/java/broker/src/main/java/org/apache/qpid/server/transport/ConnectorConfiguration.java deleted file mode 100644 index a4ed859fa7..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/transport/ConnectorConfiguration.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.transport; - -import org.apache.mina.common.IoAcceptor; -import org.apache.mina.util.NewThreadExecutor; -import org.apache.qpid.configuration.Configured; - -public class ConnectorConfiguration -{ - public static final String DEFAULT_PORT = "5672"; - - public static final String SSL_PORT = "8672"; - - @Configured(path = "connector.processors", - defaultValue = "4") - public int processors; - - @Configured(path = "connector.port", - defaultValue = DEFAULT_PORT) - public int port; - - @Configured(path = "connector.bind", - defaultValue = "wildcard") - public String bindAddress; - - @Configured(path = "connector.socketReceiveBuffer", - defaultValue = "32767") - public int socketReceiveBufferSize; - - @Configured(path = "connector.socketWriteBuffer", - defaultValue = "32767") - public int socketWriteBuferSize; - - @Configured(path = "connector.tcpNoDelay", - defaultValue = "true") - public boolean tcpNoDelay; - - @Configured(path = "advanced.filterchain[@enableExecutorPool]", - defaultValue = "false") - public boolean enableExecutorPool; - - @Configured(path = "advanced.enablePooledAllocator", - defaultValue = "false") - public boolean enablePooledAllocator; - - @Configured(path = "advanced.enableDirectBuffers", - defaultValue = "false") - public boolean enableDirectBuffers; - - @Configured(path = "connector.ssl.enabled", - defaultValue = "false") - public boolean enableSSL; - - @Configured(path = "connector.ssl.sslOnly", - defaultValue = "true") - public boolean sslOnly; - - @Configured(path = "connector.ssl.port", - defaultValue = SSL_PORT) - public int sslPort; - - @Configured(path = "connector.ssl.keystorePath", - defaultValue = "none") - public String keystorePath; - - @Configured(path = "connector.ssl.keystorePassword", - defaultValue = "none") - public String keystorePassword; - - @Configured(path = "connector.ssl.certType", - defaultValue = "SunX509") - public String certType; - - public IoAcceptor createAcceptor() - { - return new org.apache.mina.transport.socket.nio.SocketAcceptor(processors, new NewThreadExecutor()); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/transport/ThreadPoolFilter.java b/java/broker/src/main/java/org/apache/qpid/server/transport/ThreadPoolFilter.java deleted file mode 100644 index e6ee8891f6..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/transport/ThreadPoolFilter.java +++ /dev/null @@ -1,712 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.transport; - -import java.util.ArrayList; -import java.util.IdentityHashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.mina.common.IdleStatus; -import org.apache.mina.common.IoFilterAdapter; -import org.apache.mina.common.IoHandler; -import org.apache.mina.common.IoSession; -//import org.apache.mina.util.BlockingQueue; -//import org.apache.mina.util.ByteBufferUtil; -//import org.apache.mina.util.IdentityHashSet; -//import org.apache.mina.util.Queue; -//import org.apache.mina.util.Stack; -//import org.apache.mina.util.IdentityHashSet; - -/** - * A Thread-pooling filter. This filter forwards {@link IoHandler} events - * to its thread pool. - * <p/> - * This is an implementation of - * <a href="http://deuce.doc.wustl.edu/doc/pspdfs/lf.pdf">Leader/Followers - * thread pool</a> by Douglas C. Schmidt et al. - */ -public class ThreadPoolFilter extends IoFilterAdapter -{ - - /** - * Default maximum size of thread pool (2G). - */ - public static final int DEFAULT_MAXIMUM_POOL_SIZE = Integer.MAX_VALUE; - - /** - * Default keep-alive time of thread pool (1 min). - */ - public static final int DEFAULT_KEEP_ALIVE_TIME = 60 * 1000; - - /** - * A queue which contains {@link Integer}s which represents reusable - * thread IDs. {@link Worker} first checks this queue and then - * uses {@link #threadId} when no reusable thread ID is available. - */ - /* private static final Queue threadIdReuseQueue = new Queue(); - private static int threadId = 0; - - private static int acquireThreadId() - { - synchronized (threadIdReuseQueue) - { - Integer id = (Integer) threadIdReuseQueue.pop(); - if (id == null) - { - return ++ threadId; - } - else - { - return id.intValue(); - } - } - } - - private static void releaseThreadId(int id) - { - synchronized (threadIdReuseQueue) - { - threadIdReuseQueue.push(new Integer(id)); - } - } */ - - private final String threadNamePrefix = ""; - private final Map buffers = new IdentityHashMap(); - //private final BlockingQueue unfetchedSessionBuffers = new BlockingQueue(); - //private final Set allSessionBuffers = new IdentityHashSet(); - - //private Worker leader; - //private final Stack followers = new Stack(); - //private final Set allWorkers = new IdentityHashSet(); - - private int maximumPoolSize = DEFAULT_MAXIMUM_POOL_SIZE; - private int keepAliveTime = DEFAULT_KEEP_ALIVE_TIME; - - private boolean shuttingDown; - - private int poolSize; - private final Object poolSizeLock = new Object(); - - /** - * Creates a new instance of this filter with default thread pool settings. - */ - public ThreadPoolFilter() - { - this("IoThreadPool"); - } - - /** - * Creates a new instance of this filter with the specified thread name prefix - * and other default settings. - * - * @param threadNamePrefix the prefix of the thread names this pool will create. - */ - public ThreadPoolFilter(String threadNamePrefix) - { - if (threadNamePrefix == null) - { - throw new NullPointerException("threadNamePrefix"); - } - threadNamePrefix = threadNamePrefix.trim(); - if (threadNamePrefix.length() == 0) - { - throw new IllegalArgumentException("threadNamePrefix is empty."); - } - // this.threadNamePrefix = threadNamePrefix; - } - - public String getThreadNamePrefix() - { - return null; // threadNamePrefix; - } - - public int getPoolSize() - { - /* synchronized (poolSizeLock) - { - return poolSize; - }*/ - return 0; - } - - public int getMaximumPoolSize() - { - return maximumPoolSize; - } - - public int getKeepAliveTime() - { - return keepAliveTime; - } - - public void setMaximumPoolSize(int maximumPoolSize) - { - if (maximumPoolSize <= 0) - { - throw new IllegalArgumentException(); - } - this.maximumPoolSize = maximumPoolSize; - } - - public void setKeepAliveTime(int keepAliveTime) - { - this.keepAliveTime = keepAliveTime; - } - -/* public void init() - { - shuttingDown = false; - leader = new Worker(); - leader.start(); - leader.lead(); - } - - public void destroy() - { - shuttingDown = true; - int expectedPoolSize = 0; - while (getPoolSize() != expectedPoolSize) - { - List allWorkers; - synchronized (poolSizeLock) - { - // allWorkers = new ArrayList(this.allWorkers); - } - - // You may not interrupt the current thread. - if (allWorkers.remove(Thread.currentThread())) - { - expectedPoolSize = 1; - } - - for (Iterator i = allWorkers.iterator(); i.hasNext();) - { - Worker worker = (Worker) i.next(); - while (worker.isAlive()) - { - worker.interrupt(); - try - { - // This timeout will help us from - // infinite lock-up and interrupt workers again. - worker.join(100); - } - catch (InterruptedException e) - { - } - } - } - } - - // this.allSessionBuffers.clear(); - // this.unfetchedSessionBuffers.clear(); - this.buffers.clear(); - // this.followers.clear(); - this.leader = null; - } - - private void increasePoolSize(Worker worker) - { - synchronized (poolSizeLock) - { - poolSize++; - //allWorkers.add(worker); - } - } - - private void decreasePoolSize(Worker worker) - { - synchronized (poolSizeLock) - { - poolSize--; - //allWorkers.remove(worker); - } - } - - private void fireEvent(NextFilter nextFilter, IoSession session, - EventType type, Object data) - { - /* - final BlockingQueue unfetchedSessionBuffers = this.unfetchedSessionBuffers; - final Set allSessionBuffers = this.allSessionBuffers; - final Event event = new Event(type, nextFilter, data); - - synchronized (unfetchedSessionBuffers) - { - final SessionBuffer buf = getSessionBuffer(session); - final Queue eventQueue = buf.eventQueue; - - synchronized (buf) - { - eventQueue.push(event); - } - - if (!allSessionBuffers.contains(buf)) - { - allSessionBuffers.add(buf); - unfetchedSessionBuffers.push(buf); - } - } - */ - } - - /** - * Implement this method to fetch (or pop) a {@link SessionBuffer} from - * the given <tt>unfetchedSessionBuffers</tt>. The default implementation - * simply pops the buffer from it. You could prioritize the fetch order. - * - * @return A non-null {@link SessionBuffer} - */ - /* protected SessionBuffer fetchSessionBuffer(Queue unfetchedSessionBuffers) - { - return (SessionBuffer) unfetchedSessionBuffers.pop(); - } - - private SessionBuffer getSessionBuffer(IoSession session) - { - final Map buffers = this.buffers; - SessionBuffer buf = (SessionBuffer) buffers.get(session); - if (buf == null) - { - synchronized (buffers) - { - buf = (SessionBuffer) buffers.get(session); - if (buf == null) - { - buf = new SessionBuffer(session); - buffers.put(session, buf); - } - } - } - return buf; - } - - private void removeSessionBuffer(SessionBuffer buf) - { - final Map buffers = this.buffers; - final IoSession session = buf.session; - synchronized (buffers) - { - buffers.remove(session); - } - } - - protected static class SessionBuffer - { - private final IoSession session; - - //private final Queue eventQueue = new Queue(); - - private SessionBuffer(IoSession session) - { - this.session = session; - } - - public IoSession getSession() - { - return session; - } - - /* public Queue getEventQueue() - { - return eventQueue; - } - } - - private class Worker extends Thread - { - private final int id; - private final Object promotionLock = new Object(); - private boolean dead; - - private Worker() - { - int id = acquireThreadId(); - this.id = id; - this.setName(threadNamePrefix + '-' + id); - increasePoolSize(this); - } - - public boolean lead() - { - final Object promotionLock = this.promotionLock; - synchronized (promotionLock) - { - if (dead) - { - return false; - } - - leader = this; - promotionLock.notify(); - } - - return true; - } - - public void run() - { - for (; ;) - { - if (!waitForPromotion()) - { - break; - } - - SessionBuffer buf = fetchBuffer(); - giveUpLead(); - if (buf == null) - { - break; - } - - processEvents(buf); - follow(); - releaseBuffer(buf); - } - - decreasePoolSize(this); - releaseThreadId(id); - } - - private SessionBuffer fetchBuffer() - { - BlockingQueue unfetchedSessionBuffers = ThreadPoolFilter.this.unfetchedSessionBuffers; - synchronized (unfetchedSessionBuffers) - { - while (!shuttingDown) - { - try - { - unfetchedSessionBuffers.waitForNewItem(); - } - catch (InterruptedException e) - { - continue; - } - - return ThreadPoolFilter.this.fetchSessionBuffer(unfetchedSessionBuffers); - } - } - - return null; - } - - private void processEvents(SessionBuffer buf) - { - final IoSession session = buf.session; - final Queue eventQueue = buf.eventQueue; - for (; ;) - { - Event event; - synchronized (buf) - { - event = (Event) eventQueue.pop(); - if (event == null) - { - break; - } - } - processEvent(event.getNextFilter(), session, - event.getType(), event.getData()); - } - } - - private void follow() - { - final Object promotionLock = this.promotionLock; - final Stack followers = ThreadPoolFilter.this.followers; - synchronized (promotionLock) - { - if (this != leader) - { - synchronized (followers) - { - followers.push(this); - } - } - } - } - - private void releaseBuffer(SessionBuffer buf) - { - final BlockingQueue unfetchedSessionBuffers = ThreadPoolFilter.this.unfetchedSessionBuffers; - final Set allSessionBuffers = ThreadPoolFilter.this.allSessionBuffers; - final Queue eventQueue = buf.eventQueue; - - synchronized (unfetchedSessionBuffers) - { - if (eventQueue.isEmpty()) - { - allSessionBuffers.remove(buf); - removeSessionBuffer(buf); - } - else - { - unfetchedSessionBuffers.push(buf); - } - } - } - - private boolean waitForPromotion() - { - final Object promotionLock = this.promotionLock; - - long startTime = System.currentTimeMillis(); - long currentTime = System.currentTimeMillis(); - - synchronized (promotionLock) - { - while (this != leader && !shuttingDown) - { - // Calculate remaining keep-alive time - int keepAliveTime = getKeepAliveTime(); - if (keepAliveTime > 0) - { - keepAliveTime -= (currentTime - startTime); - } - else - { - keepAliveTime = Integer.MAX_VALUE; - } - - // Break the loop if there's no remaining keep-alive time. - if (keepAliveTime <= 0) - { - break; - } - - // Wait for promotion - try - { - promotionLock.wait(keepAliveTime); - } - catch (InterruptedException e) - { - } - - // Update currentTime for the next iteration - currentTime = System.currentTimeMillis(); - } - - boolean timeToLead = this == leader && !shuttingDown; - - if (!timeToLead) - { - // time to die - synchronized (followers) - { - followers.remove(this); - } - - // Mark as dead explicitly when we've got promotionLock. - dead = true; - } - - return timeToLead; - } - } - - private void giveUpLead() - { - final Stack followers = ThreadPoolFilter.this.followers; - Worker worker; - do - { - synchronized (followers) - { - worker = (Worker) followers.pop(); - } - - if (worker == null) - { - // Increase the number of threads if we - // are not shutting down and we can increase the number. - if (!shuttingDown - && getPoolSize() < getMaximumPoolSize()) - { - worker = new Worker(); - worker.lead(); - worker.start(); - } - - // This loop should end because: - // 1) lead() is called already, - // 2) or it is shutting down and there's no more threads left. - break; - } - } - while (!worker.lead()); - } - } - - protected static class EventType - { - public static final EventType OPENED = new EventType("OPENED"); - - public static final EventType CLOSED = new EventType("CLOSED"); - - public static final EventType READ = new EventType("READ"); - - public static final EventType WRITTEN = new EventType("WRITTEN"); - - public static final EventType RECEIVED = new EventType("RECEIVED"); - - public static final EventType SENT = new EventType("SENT"); - - public static final EventType IDLE = new EventType("IDLE"); - - public static final EventType EXCEPTION = new EventType("EXCEPTION"); - - private final String value; - - private EventType(String value) - { - this.value = value; - } - - public String toString() - { - return value; - } - } - - protected static class Event - { - private final EventType type; - private final NextFilter nextFilter; - private final Object data; - - public Event(EventType type, NextFilter nextFilter, Object data) - { - this.type = type; - this.nextFilter = nextFilter; - this.data = data; - } - - public Object getData() - { - return data; - } - - - public NextFilter getNextFilter() - { - return nextFilter; - } - - - public EventType getType() - { - return type; - } - } - - public void sessionCreated(NextFilter nextFilter, IoSession session) - { - nextFilter.sessionCreated(session); - } - - public void sessionOpened(NextFilter nextFilter, - IoSession session) - { - fireEvent(nextFilter, session, EventType.OPENED, null); - } - - public void sessionClosed(NextFilter nextFilter, - IoSession session) - { - fireEvent(nextFilter, session, EventType.CLOSED, null); - } - - public void sessionIdle(NextFilter nextFilter, - IoSession session, IdleStatus status) - { - fireEvent(nextFilter, session, EventType.IDLE, status); - } - - public void exceptionCaught(NextFilter nextFilter, - IoSession session, Throwable cause) - { - fireEvent(nextFilter, session, EventType.EXCEPTION, cause); - } - - public void messageReceived(NextFilter nextFilter, - IoSession session, Object message) - { - ByteBufferUtil.acquireIfPossible(message); - fireEvent(nextFilter, session, EventType.RECEIVED, message); - } - - public void messageSent(NextFilter nextFilter, - IoSession session, Object message) - { - ByteBufferUtil.acquireIfPossible(message); - fireEvent(nextFilter, session, EventType.SENT, message); - } - - protected void processEvent(NextFilter nextFilter, - IoSession session, EventType type, - Object data) - { - if (type == EventType.RECEIVED) - { - nextFilter.messageReceived(session, data); - ByteBufferUtil.releaseIfPossible(data); - } - else if (type == EventType.SENT) - { - nextFilter.messageSent(session, data); - ByteBufferUtil.releaseIfPossible(data); - } - else if (type == EventType.EXCEPTION) - { - nextFilter.exceptionCaught(session, (Throwable) data); - } - else if (type == EventType.IDLE) - { - nextFilter.sessionIdle(session, (IdleStatus) data); - } - else if (type == EventType.OPENED) - { - nextFilter.sessionOpened(session); - } - else if (type == EventType.CLOSED) - { - nextFilter.sessionClosed(session); - } - } - - public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) - { - nextFilter.filterWrite(session, writeRequest); - } - - public void filterClose(NextFilter nextFilter, IoSession session) throws Exception - { - nextFilter.filterClose(session); - } - - */ - diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/CleanupMessageOperation.java b/java/broker/src/main/java/org/apache/qpid/server/txn/CleanupMessageOperation.java deleted file mode 100644 index 988f589339..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/txn/CleanupMessageOperation.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.txn; - -import org.apache.log4j.Logger; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.RequiredDeliveryException; -import org.apache.qpid.server.queue.AMQMessage; -import org.apache.qpid.server.queue.NoConsumersException; -import org.apache.qpid.server.store.StoreContext; - -import java.util.List; - -/** - * @author Apache Software Foundation - */ -public class CleanupMessageOperation implements TxnOp -{ - private static final Logger _log = Logger.getLogger(CleanupMessageOperation.class); - - private final AMQMessage _msg; - - private final List<RequiredDeliveryException> _returns; - - public CleanupMessageOperation(AMQMessage msg, List<RequiredDeliveryException> returns) - { - _msg = msg; - _returns = returns; - } - - public void prepare(StoreContext context) throws AMQException - { } - - public void undoPrepare() - { - // don't need to do anything here, if the store's txn failed - // when processing prepare then the message was not stored - // or enqueued on any queues and can be discarded - } - - public void commit(StoreContext context) - { - // No-op can't be done here has this is before the message has been attempted to be delivered. - /*try - { - _msg.checkDeliveredToConsumer(); - } - catch (NoConsumersException e) - { - _returns.add(e); - }*/ - } - - public void rollback(StoreContext context) - { - // NO OP - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/DequeueRecord.java b/java/broker/src/main/java/org/apache/qpid/server/txn/DequeueRecord.java deleted file mode 100644 index d899bb972c..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/txn/DequeueRecord.java +++ /dev/null @@ -1,59 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.txn; - -import org.apache.qpid.server.messageStore.MessageStore; -import org.apache.qpid.server.exception.*; - -import javax.transaction.xa.Xid; - -/** - * Created by Arnaud Simon - * Date: 25-Apr-2007 - * Time: 17:13:07 - */ -public class DequeueRecord implements TransactionRecord -{ - - - public void commit(MessageStore store, Xid xid) - throws - InternalErrorException, - QueueDoesntExistException, - InvalidXidException, - UnknownXidException, - MessageDoesntExistException - { - // nothing - } - - public void rollback(MessageStore store) - throws - InternalErrorException - { - //To change body of implemented methods use File | Settings | File Templates. - } - - public void prepare(MessageStore store) - throws - InternalErrorException - { - //To change body of implemented methods use File | Settings | File Templates. - } -} - diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/DistributedTransactionalContext.java b/java/broker/src/main/java/org/apache/qpid/server/txn/DistributedTransactionalContext.java deleted file mode 100644 index 13f66fac5b..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/txn/DistributedTransactionalContext.java +++ /dev/null @@ -1,267 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.txn; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.queue.AMQMessage; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.ack.UnacknowledgedMessageMap; -import org.apache.qpid.server.ack.UnacknowledgedMessage; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.store.StoreContext; -import org.apache.qpid.server.messageStore.MessageStore; -import org.apache.qpid.server.RequiredDeliveryException; -import org.apache.log4j.Logger; - -import javax.transaction.xa.Xid; -import java.util.List; -import java.util.LinkedList; - -/** - * Created by Arnaud Simon - * Date: 25-Apr-2007 - * Time: 15:58:07 - */ -public class DistributedTransactionalContext implements TransactionalContext -{ - //======================================================================== - // Static Constants - //======================================================================== - // The logger for this class - private static final Logger _log = Logger.getLogger(DistributedTransactionalContext.class); - private static final Object _lockXID = new Object(); - private static int _count = 0; - //======================================================================== - // Instance Fields - //======================================================================== - // the message store - final private MessageStore _messageStore; - // The transaction manager - final private TransactionManager _transactionManager; - // the store context - final private StoreContext _storeContext; - // the returned messages - final private List<RequiredDeliveryException> _returnMessages; - // for generating xids - private byte[] _txId = ("txid").getBytes(); - - public DistributedTransactionalContext(TransactionManager transactionManager, MessageStore messageStore, StoreContext storeContext, - List<RequiredDeliveryException> returnMessages) - { - _messageStore = messageStore; - _storeContext = storeContext; - _returnMessages = returnMessages; - _transactionManager = transactionManager; - } - - public void beginTranIfNecessary() - throws - AMQException - { - if (_storeContext.getPayload() == null) - { - synchronized (_lockXID) - { - // begin the transaction and pass the XID through the context - Xid xid = new XidImpl(("branch" + _count++).getBytes(), 1, _txId); - try - { - _transactionManager.begin(xid); - _storeContext.setPayload(xid); - } catch (Exception e) - { - throw new AMQException(null, "Problem during transaction begin", e); - } - } - } - } - - public void commit() - throws - AMQException - { - try - { - if (_storeContext.getPayload() != null) - { - _transactionManager.commit_one_phase((Xid) _storeContext.getPayload()); - } - } catch (Exception e) - { - throw new AMQException(null, "Problem during transaction commit", e); - } - finally - { - _storeContext.setPayload(null); - } - } - - public void rollback() - throws - AMQException - { - try - { - if (_storeContext.getPayload() != null) - { - _transactionManager.rollback((Xid) _storeContext.getPayload()); - } - } catch (Exception e) - { - throw new AMQException(null, "Problem during transaction rollback", e); - } - finally - { - _storeContext.setPayload(null); - } - } - - public void messageFullyReceived(boolean persistent) - throws - AMQException - { - // The message is now fully received, we can stage it before enqueued if necessary - } - - public void deliver(AMQMessage message, AMQQueue queue, boolean deliverFirst) - throws - AMQException - { - try - { - //The message has been delivered to the queues - message.getMessageHandle().enqueue(_storeContext, message.getMessageId(), queue); - // add a record in the transaction - _transactionManager.getTransaction((Xid) _storeContext.getPayload()).addRecord(new EnqueueRecord(_storeContext, message, queue, deliverFirst)); - } catch (Exception e) - { - throw new AMQException(null, "Problem during transaction rollback", e); - } - } - - public void acknowledgeMessage(long deliveryTag, long lastDeliveryTag, - boolean multiple, - final UnacknowledgedMessageMap unacknowledgedMessageMap) - throws - AMQException - { - beginTranIfNecessary(); - if (multiple) - { - if (deliveryTag == 0) - { - //Spec 2.1.6.11 ... If the multiple field is 1, and the delivery tag is zero, - // tells the server to acknowledge all outstanding mesages. - _log.info("Multiple ack on delivery tag 0. ACKing all messages. Current count:" + - unacknowledgedMessageMap.size()); - unacknowledgedMessageMap.visit(new UnacknowledgedMessageMap.Visitor() - { - public boolean callback(UnacknowledgedMessage message) - throws - AMQException - { - if (_log.isDebugEnabled()) - { - _log.debug("Discarding message: " + message.message.getMessageId()); - } - - //Message has been ack so discard it. This will dequeue and decrement the reference. - dequeue(message); - return false; - } - - public void visitComplete() - { - unacknowledgedMessageMap.clear(); - } - }); - } else - { - if (!unacknowledgedMessageMap.contains(deliveryTag)) - { - throw new AMQException(null, "Multiple ack on delivery tag " + deliveryTag + " not known for channel", null); - } - - LinkedList<UnacknowledgedMessage> acked = new LinkedList<UnacknowledgedMessage>(); - unacknowledgedMessageMap.drainTo(acked, deliveryTag); - for (UnacknowledgedMessage msg : acked) - { - if (_log.isDebugEnabled()) - { - _log.debug("Discarding message: " + msg.message.getMessageId()); - } - //Message has been ack so discard it. This will dequeue and decrement the reference. - dequeue(msg); - } - } - } else - { - UnacknowledgedMessage msg; - msg = unacknowledgedMessageMap.remove(deliveryTag); - - if (msg == null) - { - _log.info("Single ack on delivery tag " + deliveryTag); - throw new AMQException(null, "Single ack on delivery tag " + deliveryTag, null); - } - - if (_log.isDebugEnabled()) - { - _log.debug("Discarding message: " + msg.message.getMessageId()); - } - - //Message has been ack so discard it. This will dequeue and decrement the reference. - dequeue(msg); - - if (_log.isDebugEnabled()) - { - _log.debug("Received non-multiple ack for messaging with delivery tag " + deliveryTag + " msg id " + - msg.message.getMessageId()); - } - } - } - - private void dequeue(UnacknowledgedMessage message) - throws - AMQException - { - // Dequeue the message from the strore - message.discard(_storeContext); - // Add a record - try - { - _transactionManager.getTransaction((Xid) _storeContext.getPayload()).addRecord(new DequeueRecord()); - } catch (Exception e) - { - throw new AMQException(null, "Problem during message dequeue", e); - } - } - - - public void messageProcessed(AMQProtocolSession protocolSession) - throws - AMQException - { - // The message has been sent - } - - public StoreContext getStoreContext() - { - return _storeContext; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/EnqueueRecord.java b/java/broker/src/main/java/org/apache/qpid/server/txn/EnqueueRecord.java deleted file mode 100644 index 6770d8a8dd..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/txn/EnqueueRecord.java +++ /dev/null @@ -1,72 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.txn; - -import javax.transaction.xa.Xid; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.exception.*; -import org.apache.qpid.server.messageStore.MessageStore; -import org.apache.qpid.server.queue.AMQMessage; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.store.StoreContext; - -/** - * Created by Arnaud Simon - * Date: 25-Apr-2007 - * Time: 17:01:06 - */ -public class EnqueueRecord implements TransactionRecord -{ - private final StoreContext _storeContext; - private final AMQMessage _msg; - private final AMQQueue _queue; - private final boolean _first; - - EnqueueRecord(StoreContext storeContext, AMQMessage msg, AMQQueue q, boolean firsr) - { - _storeContext = storeContext; - _msg = msg; - _queue = q; - _first = firsr; - } - - public void commit(MessageStore store, Xid xid) - throws InternalErrorException, QueueDoesntExistException, InvalidXidException, UnknownXidException, - MessageDoesntExistException - { - try - { - _queue.process(_storeContext, _msg, _first); - } - catch (AMQException e) - { - throw new InternalErrorException(e.getMessage(), e); - } - } - - public void rollback(MessageStore store) throws InternalErrorException - { - // To change body of implemented methods use File | Settings | File Templates. - } - - public void prepare(MessageStore store) throws InternalErrorException - { - // To change body of implemented methods use File | Settings | File Templates. - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/JDBCAbstractRecord.java b/java/broker/src/main/java/org/apache/qpid/server/txn/JDBCAbstractRecord.java deleted file mode 100644 index cc0cc7140b..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/txn/JDBCAbstractRecord.java +++ /dev/null @@ -1,93 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.txn; - -import org.apache.log4j.Logger; -import org.apache.qpid.server.messageStore.StorableQueue; -import org.apache.qpid.server.messageStore.StorableMessage; -import org.apache.qpid.server.messageStore.MessageStore; -import org.apache.qpid.server.exception.InternalErrorException; -import org.apache.qpid.server.exception.UnknownXidException; - -import javax.transaction.xa.Xid; - -/** - * Created by Arnaud Simon - * Date: 16-May-2007 - * Time: 15:15:18 - */ -public abstract class JDBCAbstractRecord implements TransactionRecord -{ - //======================================================================== - // Static Constants - //======================================================================== - // The logger for this class - private static final Logger _log = Logger.getLogger(JDBCEnqueueRecord.class); - // The record types - static public final int TYPE_DEQUEUE = 1; - static public final int TYPE_ENQUEUE = 2; - - // the queue - StorableQueue _queue; - // the message - StorableMessage _message; - - //======================================================================== - // Constructor - //======================================================================== - public JDBCAbstractRecord(StorableMessage m, StorableQueue queue) - { - _queue = queue; - _message = m; - } - - public abstract int getType(); - public long getMessageID() - { - return _message.getMessageId(); - } - - public int getQueueID() - { - return _queue.getQueueID(); - } - - public void rollback(MessageStore store) - throws - InternalErrorException - { - - } - - public void prepare(MessageStore store) - throws - InternalErrorException - { - } - - - public abstract void rollback(MessageStore store, Xid xid) - throws - InternalErrorException, - UnknownXidException; - - public abstract void prepare(MessageStore store, Xid xid) - throws - InternalErrorException, - UnknownXidException; -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/JDBCDequeueRecord.java b/java/broker/src/main/java/org/apache/qpid/server/txn/JDBCDequeueRecord.java deleted file mode 100644 index c18a6a7fcf..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/txn/JDBCDequeueRecord.java +++ /dev/null @@ -1,85 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.txn; - -import org.apache.log4j.Logger; -import org.apache.qpid.server.messageStore.StorableQueue; -import org.apache.qpid.server.messageStore.StorableMessage; -import org.apache.qpid.server.messageStore.MessageStore; -import org.apache.qpid.server.messageStore.JDBCStore; -import org.apache.qpid.server.exception.*; - -import javax.transaction.xa.Xid; - -/** - * Created by Arnaud Simon - * Date: 16-May-2007 - * Time: 14:50:34 - */ -public class JDBCDequeueRecord extends JDBCAbstractRecord -{ - //======================================================================== - // Static Constants - //======================================================================== - // The logger for this class - private static final Logger _log = Logger.getLogger(JDBCDequeueRecord.class); - - //======================================================================== - // Constructor - //======================================================================== - public JDBCDequeueRecord( StorableMessage m, StorableQueue queue) - { - super(m, queue); - } - - //======================================================================== - // Interface TransactionRecord - //======================================================================== - - public void commit(MessageStore store, Xid xid) - throws - InternalErrorException, - QueueDoesntExistException, - InvalidXidException, - UnknownXidException, - MessageDoesntExistException - { - store.dequeue(xid, _message, _queue); - } - - public void rollback(MessageStore store, Xid xid) - throws - InternalErrorException, - UnknownXidException - { - ((JDBCStore) store).rollbackDequeu(xid, _message, _queue); - } - - public void prepare(MessageStore store, Xid xid) - throws - InternalErrorException, - UnknownXidException - { - ((JDBCStore) store).prepareDequeu(xid, _message, _queue); - } - - public int getType() - { - return TYPE_DEQUEUE; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/JDBCEnqueueRecord.java b/java/broker/src/main/java/org/apache/qpid/server/txn/JDBCEnqueueRecord.java deleted file mode 100644 index 4a4a23153e..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/txn/JDBCEnqueueRecord.java +++ /dev/null @@ -1,106 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.txn; - -import org.apache.log4j.Logger; -import org.apache.qpid.server.messageStore.StorableQueue; -import org.apache.qpid.server.messageStore.StorableMessage; -import org.apache.qpid.server.messageStore.MessageStore; -import org.apache.qpid.server.messageStore.JDBCStore; -import org.apache.qpid.server.exception.*; - -import javax.transaction.xa.Xid; - -/** - * Created by Arnaud Simon - * Date: 16-May-2007 - * Time: 14:50:20 - */ -public class JDBCEnqueueRecord extends JDBCAbstractRecord -{ - //======================================================================== - // Static Constants - //======================================================================== - // The logger for this class - private static final Logger _log = Logger.getLogger(JDBCEnqueueRecord.class); - - //======================================================================== - // Constructor - //======================================================================== - public JDBCEnqueueRecord(StorableMessage m, StorableQueue queue) - { - super(m, queue); - } - - //======================================================================== - // Interface TransactionRecord - //======================================================================== - - public void commit(MessageStore store, Xid xid) - throws - InternalErrorException, - QueueDoesntExistException, - InvalidXidException, - UnknownXidException, - MessageDoesntExistException - { - store.enqueue(xid, _message, _queue); - } - - public void rollback(MessageStore store, Xid xid) - throws - InternalErrorException, - UnknownXidException - { - if (!_message.isEnqueued()) - { - // try to delete the message - try - { - store.destroy(_message); - } catch (Exception e) - { - throw new InternalErrorException("Problem when destoying message ", e); - } - } - } - - public void prepare(MessageStore store, Xid xid) - throws - InternalErrorException, - UnknownXidException - { - try - { - if (!_message.isEnqueued() && !_message.isStaged()) - { - store.stage(_message); - store.appendContent(_message, _message.getData(), 0, _message.getData().length); - } - } - catch (Exception e) - { - throw new InternalErrorException("Problem when persisting message ", e); - } - } - - public int getType() - { - return TYPE_ENQUEUE; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/JDBCTransaction.java b/java/broker/src/main/java/org/apache/qpid/server/txn/JDBCTransaction.java deleted file mode 100644 index cc35b50cc8..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/txn/JDBCTransaction.java +++ /dev/null @@ -1,196 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.txn; - -import org.apache.log4j.Logger; -import org.apache.qpid.server.messageStore.JDBCStore; - -import java.util.List; -import java.util.LinkedList; - -/** - * Created by Arnaud Simon - * Date: 16-May-2007 - * Time: 14:09:35 - */ -public class JDBCTransaction implements Transaction -{ - //======================================================================== - // Static Constants - //======================================================================== - // The logger for this class - private static final Logger _log = Logger.getLogger(JDBCTransaction.class); - public static long _xidId = 0; - //======================================================================== - // Instance Fields - //======================================================================== - // the associated connection - private JDBCStore.MyConnection _connection; - // Indicates whether this transaction is prepared - private boolean _prepared = false; - // Indicates that this transaction has heuristically rolled back - private boolean _heurRollBack = false; - // The list of records associated with this tx - private List<TransactionRecord> _records = new LinkedList<TransactionRecord>(); - // The date when this tx has been created. - private long _dateCreated; - // The timeout in seconds - private long _timeout; - // this instance xid id used as primary key - private long _thisxidId; - - //========================================================= - // Constructors - //========================================================= - - /** - * Create a transaction - * - */ - public JDBCTransaction() - { - _dateCreated = System.currentTimeMillis(); - _thisxidId = _xidId++; - } - - //========================================================= - // Getter and Setter methods - //========================================================= - - /** - * Notify that this tx has been prepared - */ - public void prepare() - { - _prepared = true; - } - - /** - * Specify whether this transaction is prepared - * - * @return true if this transaction is prepared, false otherwise - */ - public boolean isPrepared() - { - return _prepared; - } - - /** - * Notify that this tx has been heuristically rolled back - */ - public void heurRollback() - { - _heurRollBack = true; - } - - /** - * Specify whether this transaction has been heuristically rolled back - * - * @return true if this transaction has been heuristically rolled back , false otherwise - */ - public boolean isHeurRollback() - { - return _heurRollBack; - } - - /** - * Add an abstract record to this tx. - * - * @param record The record to be added - */ - public void addRecord(TransactionRecord record) - { - _records.add(record); - } - - /** - * Get the list of records associated with this tx. - * - * @return The list of records associated with this tx. - */ - public List<TransactionRecord> getrecords() - { - return _records; - } - - /** - * Set this tx timeout - * - * @param timeout This tx timeout in seconds - */ - public void setTimeout(long timeout) - { - _timeout = timeout; - } - - /** - * Get this tx timeout - * - * @return This tx timeout in seconds - */ - public long getTimeout() - { - return _timeout; - } - - /** - * Specify whether this tx has expired - * - * @return true if this tx has expired, false otherwise - */ - public boolean hasExpired() - { - long currentDate = System.currentTimeMillis(); - boolean result = currentDate - _dateCreated > _timeout * 1000; - if (_log.isDebugEnabled() && result) - { - _log.debug("transaction has expired"); - } - return result; - } - - /** - * Get the JDBC connection - * @return The JDBC connection - */ - public JDBCStore.MyConnection getConnection() - { - return _connection; - } - - /** - * Set the JDBC connection - * - * @param connection The new JDBC connection - */ - public void setConnection(JDBCStore.MyConnection connection) - { - _connection = connection; - } - - /** - * This tx xid id used as primary key - * - * @return this tx xid id - */ - public long getXidID() - { - return _thisxidId; - } - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/JDBCTransactionManager.java b/java/broker/src/main/java/org/apache/qpid/server/txn/JDBCTransactionManager.java deleted file mode 100644 index 26ddbc881d..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/txn/JDBCTransactionManager.java +++ /dev/null @@ -1,554 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.txn; - -import org.apache.log4j.Logger; -import org.apache.qpid.server.messageStore.MessageStore; -import org.apache.qpid.server.messageStore.JDBCStore; -import org.apache.qpid.server.exception.*; -import org.apache.commons.configuration.Configuration; - -import javax.transaction.xa.Xid; -import java.util.HashMap; -import java.util.Set; - - -/** - * Created by Arnaud Simon - * Date: 16-May-2007 - * Time: 14:05:45 - */ -public class JDBCTransactionManager implements TransactionManager -{ - //======================================================================== - // Static Constants - //======================================================================== - // The logger for this class - private static final Logger _log = Logger.getLogger(JDBCTransactionManager.class); - - private static final String ENVIRONMENT_TX_TIMEOUT = "environment-tx-timeout"; - - //======================================================================== - // Instance Fields - //======================================================================== - // The underlying jdbc message store - private JDBCStore _messagStore; - - // A map of XID/x - private HashMap<Xid, Transaction> _xidMap; - - // A map of in-doubt txs - private HashMap<Xid, Transaction> _indoubtXidMap; - - // A default tx timeout in sec - private int _defaultTimeout; // set to 10s if not specified in the config - - //=================================== - //=== Configuartion - //=================================== - - /** - * Configure this TM with the Message store implementation - * - * @param base The base element identifier from which all configuration items are relative. For example, if the base - * element is "store", the all elements used by concrete classes will be "store.foo" etc. - * @param config The apache commons configuration object - * @param messageStroe the message store associated with the TM - */ - public void configure(MessageStore messageStroe, String base, Configuration config) - { - _messagStore = (JDBCStore) messageStroe; - if (config != null) - { - _defaultTimeout = config.getInt(base + "." + ENVIRONMENT_TX_TIMEOUT, 120); - } else - { - _defaultTimeout = 120; - } - _log.info("Using transaction timeout of " + _defaultTimeout + " s"); - // get the list of in-doubt transactions - try - { - _indoubtXidMap = _messagStore.getAllInddoubt(); - _xidMap = _indoubtXidMap; - } catch (Exception e) - { - _log.fatal("Cannot recover in-doubt transactions", e); - } - } - - //=================================== - //=== TransactionManager interface - //=================================== - - /** - * Begin a transaction branch identified by Xid - * - * @param xid The xid of the branch to begin - * @return <ul> - * <li> <code>XAFlag.ok</code>: Normal execution. - * </ul> - * @throws InternalErrorException In case of internal problem - * @throws InvalidXidException The Xid is invalid - */ - public synchronized XAFlag begin(Xid xid) - throws - InternalErrorException, - InvalidXidException - { - if (xid == null) - { - throw new InvalidXidException(xid, "null xid"); - } - if (_xidMap.containsKey(xid)) - { - throw new InvalidXidException(xid, "Xid already exist"); - } - Transaction tx = new JDBCTransaction(); - tx.setTimeout(_defaultTimeout); - _xidMap.put(xid, tx); - return XAFlag.ok; - } - - /** - * Prepare the transaction branch identified by Xid - * - * @param xid The xid of the branch to prepare - * @return <ul> - * <li> <code>XAFlag.ok</code>: Normal execution. - * <li> <code>XAFlag.rdonly</code>: The transaction branch was read-only and has been committed. - * <li> <code>XAFlag.rbrollback</code>: The transaction branch was marked rollback-only for an unspecied reason. - * <li> <code>XAFlag.rbtimeout</code>: The work represented by this transaction branch took too long. - * </ul> - * @throws InternalErrorException In case of internal problem - * @throws CommandInvalidException Prepare has been call in an improper context - * @throws UnknownXidException The Xid is unknown - */ - public synchronized XAFlag prepare(Xid xid) - throws - InternalErrorException, - CommandInvalidException, - UnknownXidException - { - // get the transaction - JDBCTransaction tx = getTransaction(xid); - XAFlag result = XAFlag.ok; - if (tx.isHeurRollback()) - { - result = XAFlag.rdonly; - } else if (tx.hasExpired()) - { - result = XAFlag.rbtimeout; - // rollback this tx branch - rollback(xid); - } else - { - if (tx.isPrepared()) - { - throw new CommandInvalidException("TransactionImpl is already prepared"); - } - if (tx.getrecords().size() == 0) - { - // the tx was read only (no work has been done) - _xidMap.remove(xid); - result = XAFlag.rdonly; - } else - { - try - { - JDBCStore.MyConnection con = _messagStore.getConnection(); - tx.setConnection(con); - // save the xid - _messagStore.saveXID(con, tx, xid); - for (TransactionRecord record : tx.getrecords()) - { - if (record instanceof JDBCAbstractRecord) - { - ((JDBCAbstractRecord) record).prepare(_messagStore, xid); - _messagStore.saveRecord(con, tx, (JDBCAbstractRecord) record); - } else - { - record.prepare(_messagStore); - } - } - _messagStore.commitConnection(con); - tx.setConnection(null); - } catch (Exception e) - { - _log.error("Cannot prepare tx: " + xid); - throw new InternalErrorException("Cannot prepare tx: " + xid, e); - } - tx.prepare(); - } - } - return result; - } - - /** - * Rollback the transaction branch identified by Xid - * - * @param xid The xid of the branch to rollback - * @return <ul> - * <li> <code>XAFlag.ok</code>: Normal execution, - * <li> <code>NOT SUPPORTED XAFlag.heurhaz</code>: Due to some failure, the work done on behalf of the specified transaction branch may have been heuristically completed. - * <li> <code>NOT SUPPORTED XAFlag.heurcom</code>: Due to a heuristic decision, the work done on behalf of the speci?ed transaction branch was committed. - * <li> <code>XAFlag.heurrb</code>: Due to a heuristic decision, the work done on behalf of the speci?ed transaction branch was rolled back. - * <li> <code>NOT SUPPORTED XAFlag.heurmix</code>: Due to a heuristic decision, the work done on behalf of the speci?ed transaction branch was partially committed and partially rolled back. - * <li> <code>NOT SUPPORTED XAFlag.rbrollback</code>: The broker marked the transaction branch rollback-only for an unspeci?ed reason. - * <li> <code>XAFlag.rbtimeout</code>: The work represented by this transaction branch took too long. - * </ul> - * @throws InternalErrorException In case of internal problem - * @throws CommandInvalidException Rollback has been call in an improper context - * @throws UnknownXidException The Xid is unknown - */ - public synchronized XAFlag rollback(Xid xid) - throws - InternalErrorException, - CommandInvalidException, - UnknownXidException - { - // get the transaction - JDBCTransaction tx = getTransaction(xid); - XAFlag flag = XAFlag.ok; - if (tx.isHeurRollback()) - { - flag = XAFlag.heurrb; - } else - { - try - { - JDBCStore.MyConnection con = _messagStore.getConnection(); - tx.setConnection(con); - for (TransactionRecord record : tx.getrecords()) - { - if (record instanceof JDBCAbstractRecord) - { - ((JDBCAbstractRecord) record).rollback(_messagStore, xid); - } else - { - record.rollback(_messagStore); - } - } - if (tx.isPrepared()) - { - _messagStore.deleteRecords(con, tx); - _messagStore.deleteXID(con, tx); - _messagStore.commitConnection(con); - } - _messagStore.commitConnection(con); - tx.setConnection(null); - } - catch (Exception e) - { - // this should not happen - _log.error("Error when rolling back distributed transaction: " + xid); - throw new InternalErrorException("Error when rolling back distributed transaction: " + xid, e); - } - removeTransaction(xid); - } - if (tx.hasExpired()) - { - flag = XAFlag.rbtimeout; - } - return flag; - } - - /** - * Commit the transaction branch identified by Xid - * - * @param xid The xid of the branch to commit - * @return <ul> - * <li> <code>XAFlag.ok</code>: Normal execution, - * <li> <code>NOT SUPPORTED XAFlag.heurhaz</code>: Due to some failure, the work done on behalf of the specified transaction branch may have been heuristically completed. - * <li> <code>NOT SUPPORTED XAFlag.heurcom</code>: Due to a heuristic decision, the work done on behalf of the specied transaction branch was committed. - * <li> <code>XAFlag.heurrb</code>: Due to a heuristic decision, the work done on behalf of the speci?ed transaction branch was rolled back. - * <li> <code>XAFlag.heurmix</code>: Due to a heuristic decision, the work done on behalf of the speci?ed transaction branch was partially committed and partially rolled back. - * </ul> - * @throws InternalErrorException In case of internal problem - * @throws CommandInvalidException Commit has been call in an improper context - * @throws UnknownXidException The Xid is unknown - * @throws org.apache.qpid.server.exception.NotPreparedException - * The branch was not prepared prior to commit - */ - public synchronized XAFlag commit(Xid xid) - throws - InternalErrorException, - CommandInvalidException, - UnknownXidException, - NotPreparedException - { - // get the transaction - JDBCTransaction tx = getTransaction(xid); - XAFlag flag = XAFlag.ok; - if (tx.isHeurRollback()) - { - flag = XAFlag.heurrb; - } else if (tx.hasExpired()) - { - flag = XAFlag.rbtimeout; - // rollback this tx branch - rollback(xid); - } else - { - if (!tx.isPrepared()) - { - throw new NotPreparedException("TransactionImpl is not prepared"); - } - try - { - JDBCStore.MyConnection con = _messagStore.getConnection(); - tx.setConnection(con); - for (TransactionRecord record : tx.getrecords()) - { - try - { - record.commit(_messagStore, xid); - } catch (InvalidXidException e) - { - throw new UnknownXidException(xid, e); - } catch (Exception e) - { - // this should not happen as the queue and the message must exist - _log.error("Error when committing distributed transaction heurmix mode returned: " + xid); - flag = XAFlag.heurmix; - } - } - _messagStore.deleteRecords(con, tx); - _messagStore.deleteXID(con, tx); - _messagStore.commitConnection(con); - tx.setConnection(null); - } catch (Exception e) - { - // this should not happen - _log.error("Error when committing distributed transaction heurrb mode returned: " + xid); - throw new InternalErrorException("Error when committing distributed transaction: " + xid, e); - } - removeTransaction(xid); - } - return flag; - } - - /** - * One phase commit the transaction branch identified by Xid - * - * @param xid The xid of the branch to one phase commit - * @return <ul> - * <li> <code>XAFlag.ok</code>: Normal execution, - * <li> <code>NOT SUPPORTED XAFlag.heurhaz</code>: Due to some failure, the work done on behalf of the specified transaction branch may have been heuristically completed. - * <li> <code>NOT SUPPORTED XAFlag.heurcom</code>: Due to a heuristic decision, the work done on behalf of the speci?ed transaction branch was committed. - * <li> <code>XAFlag.heurrb</code>: Due to a heuristic decision, the work done on behalf of the speci?ed transaction branch was rolled back. - * <li> <code>NOT SUPPORTED XAFlag.heurmix</code>: Due to a heuristic decision, the work done on behalf of the speci?ed transaction branch was partially committed and partially rolled back. - * <li> <code>NOT SUPPORTED XAFlag.rbrollback</code>: The broker marked the transaction branch rollback-only for an unspeci?ed reason. - * <li> <code>XAFlag.rbtimeout</code>: The work represented by this transaction branch took too long. - * </ul> - * @throws InternalErrorException In case of internal problem - * @throws CommandInvalidException Commit has been call in an improper context - * @throws UnknownXidException The Xid is unknown - */ - public synchronized XAFlag commit_one_phase(Xid xid) - throws - InternalErrorException, - CommandInvalidException, - UnknownXidException - { - XAFlag flag = XAFlag.ok; - JDBCTransaction tx = getTransaction(xid); - if (tx.isHeurRollback()) - { - flag = XAFlag.heurrb; - } else if (tx.hasExpired()) - { - flag = XAFlag.rbtimeout; - // rollback this tx branch - rollback(xid); - } else - { - try - { - // we do not need to prepare the tx - tx.prepare(); - JDBCStore.MyConnection con = _messagStore.getConnection(); - tx.setConnection(con); - for (TransactionRecord record : tx.getrecords()) - { - try - { - record.commit(_messagStore, xid); - } catch (InvalidXidException e) - { - throw new UnknownXidException(xid, e); - } catch (Exception e) - { - // this should not happen as the queue and the message must exist - _log.error("Error when committing transaction heurmix mode returned: " + xid); - flag = XAFlag.heurmix; - } - } - _messagStore.commitConnection(con); - tx.setConnection(null); - } catch (Exception e) - { - e.printStackTrace(); - throw new InternalErrorException("cannot commit transaxtion with xid " + xid + " " + e, e); - } - finally - { - removeTransaction(xid); - } - } - return flag; - } - - /** - * Forget about the transaction branch identified by Xid - * - * @param xid The xid of the branch to forget - * @throws InternalErrorException In case of internal problem - * @throws CommandInvalidException Forget has been call in an improper context - * @throws UnknownXidException The Xid is unknown - */ - public void forget(Xid xid) - throws - InternalErrorException, - CommandInvalidException, - UnknownXidException - { - synchronized (xid) - { - getTransaction(xid); - removeTransaction(xid); - } - } - - /** - * Set the transaction branch timeout value in seconds - * - * @param xid The xid of the branch to set timeout - * @param timeout Timeout value in seconds - * @throws InternalErrorException In case of internal problem - * @throws UnknownXidException The Xid is unknown - */ - public void setTimeout(Xid xid, long timeout) - throws - InternalErrorException, - UnknownXidException - { - JDBCTransaction tx = getTransaction(xid); - tx.setTimeout(timeout); - } - - /** - * Get the transaction branch timeout - * - * @param xid The xid of the branch to get the timeout from - * @return The timeout associated with the branch identified with xid - * @throws InternalErrorException In case of internal problem - * @throws UnknownXidException The Xid is unknown - */ - public long getTimeout(Xid xid) - throws - InternalErrorException, - UnknownXidException - { - JDBCTransaction tx = getTransaction(xid); - return tx.getTimeout(); - } - - /** - * Get a set of Xids the RM has prepared or heuristically completed - * - * @param startscan Indicates that recovery scan should start - * @param endscan Indicates that the recovery scan should end after returning the Xids - * @return Set of Xids the RM has prepared or heuristically completed - * @throws InternalErrorException In case of internal problem - * @throws CommandInvalidException Recover has been call in an improper context - */ - public Set<Xid> recover(boolean startscan, boolean endscan) - throws - InternalErrorException, - CommandInvalidException - { - return _indoubtXidMap.keySet(); - } - - /** - * An error happened (for example the channel has been abruptly closed) - * with this Xid, TM must make a heuristical decision. - * - * @param xid The Xid of the transaction branch to be heuristically completed - * @throws UnknownXidException The Xid is unknown - * @throws InternalErrorException In case of internal problem - */ - public void HeuristicOutcome(Xid xid) - throws - UnknownXidException, - InternalErrorException - { - synchronized (xid) - { - JDBCTransaction tx = getTransaction(xid); - if (!tx.isPrepared()) - { - // heuristically rollback this tx - for (TransactionRecord record : tx.getrecords()) - { - record.rollback(_messagStore); - } - tx.heurRollback(); - } - // add this branch in the list of indoubt tx - _indoubtXidMap.put(xid, tx); - } - } - - - public JDBCTransaction getTransaction(Xid xid) - throws - UnknownXidException - { - Transaction tx = _xidMap.get(xid); - if (tx == null) - { - throw new UnknownXidException(xid, null); - } - return (JDBCTransaction) tx; - } - - //========================================================================== - //== Methods for Message Store - //========================================================================== - - /** - * Get the default tx timeout in seconds - * - * @return the default tx timeout in seconds - */ - public int getDefaultTimeout() - { - return _defaultTimeout; - } - //========================================================================== - //== Private Methods - //========================================================================== - - private void removeTransaction(Xid xid) - { - _xidMap.remove(xid); - _indoubtXidMap.remove(xid); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/LocalTransactionalContext.java b/java/broker/src/main/java/org/apache/qpid/server/txn/LocalTransactionalContext.java deleted file mode 100644 index 4e684098d0..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/txn/LocalTransactionalContext.java +++ /dev/null @@ -1,262 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.txn; - -import org.apache.log4j.Logger; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.RequiredDeliveryException; -import org.apache.qpid.server.ack.TxAck; -import org.apache.qpid.server.ack.UnacknowledgedMessageMap; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.queue.AMQMessage; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.NoConsumersException; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.StoreContext; - -import java.util.LinkedList; -import java.util.List; - -/** A transactional context that only supports local transactions. */ -public class LocalTransactionalContext implements TransactionalContext -{ - private static final Logger _log = Logger.getLogger(LocalTransactionalContext.class); - - private final TxnBuffer _txnBuffer = new TxnBuffer(); - - private final List<DeliveryDetails> _postCommitDeliveryList = new LinkedList<DeliveryDetails>(); - - /** - * We keep hold of the ack operation so that we can consolidate acks, i.e. multiple acks within a txn are - * consolidated into a single operation - */ - private TxAck _ackOp; - - private List<RequiredDeliveryException> _returnMessages; - - private final MessageStore _messageStore; - - private final StoreContext _storeContext; - - private boolean _inTran = false; - - /** Are there messages to deliver. NOT Has the message been delivered */ - private boolean _messageDelivered = false; - - private static class DeliveryDetails - { - public AMQMessage message; - public AMQQueue queue; - private boolean deliverFirst; - - public DeliveryDetails(AMQMessage message, AMQQueue queue, boolean deliverFirst) - { - this.message = message; - this.queue = queue; - this.deliverFirst = deliverFirst; - } - } - - public LocalTransactionalContext(MessageStore messageStore, StoreContext storeContext, - List<RequiredDeliveryException> returnMessages) - { - _messageStore = messageStore; - _storeContext = storeContext; - _returnMessages = returnMessages; - // _txnBuffer.enlist(new StoreMessageOperation(messageStore)); - } - - public StoreContext getStoreContext() - { - return _storeContext; - } - - public void rollback() throws AMQException - { - _txnBuffer.rollback(_storeContext); - // Hack to deal with uncommitted non-transactional writes - if (_messageStore.inTran(_storeContext)) - { - _messageStore.abortTran(_storeContext); - _inTran = false; - } - - _postCommitDeliveryList.clear(); - } - - public void deliver(AMQMessage message, AMQQueue queue, boolean deliverFirst) throws AMQException - { - // A publication will result in the enlisting of several - // TxnOps. The first is an op that will store the message. - // Following that (and ordering is important), an op will - // be added for every queue onto which the message is - // enqueued. Finally a cleanup op will be added to decrement - // the reference associated with the routing. - // message.incrementReference(); - _postCommitDeliveryList.add(new DeliveryDetails(message, queue, deliverFirst)); - _messageDelivered = true; - _txnBuffer.enlist(new CleanupMessageOperation(message, _returnMessages)); - /*_txnBuffer.enlist(new DeliverMessageOperation(message, queue)); - if (_log.isDebugEnabled()) - { - _log.debug("Incrementing ref count on message and enlisting cleanup operation - id " + - message.getMessageId()); - } - message.incrementReference(); - _messageDelivered = true; - - */ - } - - private void checkAck(long deliveryTag, UnacknowledgedMessageMap unacknowledgedMessageMap) throws AMQException - { - if (!unacknowledgedMessageMap.contains(deliveryTag)) - { - throw new AMQException(null, "Ack with delivery tag " + deliveryTag + " not known for channel", null); - } - } - - public void acknowledgeMessage(long deliveryTag, long lastDeliveryTag, boolean multiple, - UnacknowledgedMessageMap unacknowledgedMessageMap) throws AMQException - { - // check that the tag exists to give early failure - if (!multiple || (deliveryTag > 0)) - { - checkAck(deliveryTag, unacknowledgedMessageMap); - } - // we use a single txn op for all acks and update this op - // as new acks come in. If this is the first ack in the txn - // we will need to create and enlist the op. - if (_ackOp == null) - { - beginTranIfNecessary(); - _ackOp = new TxAck(unacknowledgedMessageMap); - _txnBuffer.enlist(_ackOp); - } - // update the op to include this ack request - if (multiple && (deliveryTag == 0)) - { - // if have signalled to ack all, that refers only - // to all at this time - _ackOp.update(lastDeliveryTag, multiple); - } - else - { - _ackOp.update(deliveryTag, multiple); - } - } - - public void messageFullyReceived(boolean persistent) throws AMQException - { - // Not required in this transactional context - } - - public void messageProcessed(AMQProtocolSession protocolSession) throws AMQException - { - // Not required in this transactional context - } - - public void beginTranIfNecessary() throws AMQException - { - if (!_inTran) - { - if (_log.isDebugEnabled()) - { - _log.debug("Starting transaction on message store: " + this); - } - - _messageStore.beginTran(_storeContext); - _inTran = true; - } - } - - public void commit() throws AMQException - { - if (_log.isDebugEnabled()) - { - _log.debug("Committing transactional context: " + this); - } - - if (_ackOp != null) - { - - _messageDelivered = true; - _ackOp.consolidate(); - // already enlisted, after commit will reset regardless of outcome - _ackOp = null; - } - - if (_messageDelivered && _inTran) - { - _txnBuffer.enlist(new StoreMessageOperation(_messageStore)); - } - // fixme fail commit here ... QPID-440 - try - { - _txnBuffer.commit(_storeContext); - } - finally - { - _messageDelivered = false; - _inTran = _messageStore.inTran(_storeContext); - } - - try - { - postCommitDelivery(_returnMessages); - } - catch (AMQException e) - { - // OK so what do we do now...? - _log.error("Failed to deliver messages following txn commit: " + e, e); - } - } - - private void postCommitDelivery(List<RequiredDeliveryException> returnMessages) throws AMQException - { - if (_log.isDebugEnabled()) - { - _log.debug("Performing post commit delivery"); - } - - try - { - for (DeliveryDetails dd : _postCommitDeliveryList) - { - dd.queue.process(_storeContext, dd.message, dd.deliverFirst); - - try - { - dd.message.checkDeliveredToConsumer(); - } - catch (NoConsumersException nce) - { - returnMessages.add(nce); - } - } - } - finally - { - _postCommitDeliveryList.clear(); - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/MemoryDequeueRecord.java b/java/broker/src/main/java/org/apache/qpid/server/txn/MemoryDequeueRecord.java deleted file mode 100644 index abbd2ad923..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/txn/MemoryDequeueRecord.java +++ /dev/null @@ -1,82 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.txn; - -import org.apache.qpid.server.messageStore.MessageStore; -import org.apache.qpid.server.messageStore.StorableMessage; -import org.apache.qpid.server.messageStore.StorableQueue; -import org.apache.qpid.server.exception.*; -import org.apache.log4j.Logger; - -import javax.transaction.xa.Xid; - -/** - * Created by Arnaud Simon - * Date: 03-May-2007 - * Time: 13:59:47 - */ -public class MemoryDequeueRecord implements TransactionRecord -{ - //======================================================================== - // Static Constants - //======================================================================== - // The logger for this class - private static final Logger _log = Logger.getLogger(MemoryDequeueRecord.class); - // the queue - StorableQueue _queue; - // the message - StorableMessage _message; - - //======================================================================== - // Constructor - //======================================================================== - public MemoryDequeueRecord( StorableMessage m, StorableQueue queue) - { - _queue = queue; - _message = m; - } - - //======================================================================== - // Interface TransactionRecord - //======================================================================== - - public void commit(MessageStore store, Xid xid) - throws - InternalErrorException, - QueueDoesntExistException, - InvalidXidException, - UnknownXidException, - MessageDoesntExistException - { - store.dequeue(null, _message, _queue); - } - - public void rollback(MessageStore store) - throws - InternalErrorException - { - // do nothing - } - - public void prepare(MessageStore store) - throws - InternalErrorException - { - // do nothing - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/MemoryEnqueueRecord.java b/java/broker/src/main/java/org/apache/qpid/server/txn/MemoryEnqueueRecord.java deleted file mode 100644 index 159a5a471c..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/txn/MemoryEnqueueRecord.java +++ /dev/null @@ -1,82 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.txn; - -import org.apache.qpid.server.messageStore.MessageStore; -import org.apache.qpid.server.messageStore.StorableMessage; -import org.apache.qpid.server.messageStore.StorableQueue; -import org.apache.qpid.server.exception.*; -import org.apache.log4j.Logger; - -import javax.transaction.xa.Xid; - -/** - * Created by Arnaud Simon - * Date: 03-May-2007 - * Time: 14:00:04 - */ -public class MemoryEnqueueRecord implements TransactionRecord -{ - //======================================================================== - // Static Constants - //======================================================================== - // The logger for this class - private static final Logger _log = Logger.getLogger(MemoryDequeueRecord.class); - - // the queue - StorableQueue _queue; - // the message - StorableMessage _message; - - //======================================================================== - // Constructor - //======================================================================== - public MemoryEnqueueRecord(StorableMessage m, StorableQueue queue) - { - _queue = queue; - _message = m; - } - //======================================================================== - // Interface TransactionRecord - //======================================================================== - - public void commit(MessageStore store, Xid xid) - throws - InternalErrorException, - QueueDoesntExistException, - InvalidXidException, - UnknownXidException, - MessageDoesntExistException - { - store.enqueue(null, _message, _queue); - } - - public void rollback(MessageStore store) - throws - InternalErrorException - { - // do nothing - } - - public void prepare(MessageStore store) - throws - InternalErrorException - { - // do nothing - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/MemoryTransaction.java b/java/broker/src/main/java/org/apache/qpid/server/txn/MemoryTransaction.java deleted file mode 100644 index 4cd52b1a72..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/txn/MemoryTransaction.java +++ /dev/null @@ -1,158 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.txn; - -import org.apache.log4j.Logger; - -import java.util.List; -import java.util.LinkedList; - -/** - * Created by Arnaud Simon - * Date: 03-May-2007 - * Time: 14:30:41 - */ -public class MemoryTransaction implements Transaction -{ - //======================================================================== - // Static Constants - //======================================================================== - // The logger for this class - private static final Logger _log = Logger.getLogger(MemoryTransaction.class); - - //======================================================================== - // Instance Fields - //======================================================================== - // Indicates whether this transaction is prepared - private boolean _prepared = false; - // Indicates that this transaction has heuristically rolled back - private boolean _heurRollBack = false; - // The list of Abstract records associated with this tx - private List<TransactionRecord> _records = new LinkedList<TransactionRecord>(); - // The date when this tx has been created. - private long _dateCreated; - // The timeout in seconds - private long _timeout; - - //========================================================= - // Constructors - //========================================================= - /** - * Create a transaction that wraps a BDB tx and set the creation date. - * - */ - public MemoryTransaction() - { - _dateCreated = System.currentTimeMillis(); - } - - //========================================================= - // Getter and Setter methods - //========================================================= - /** - * Notify that this tx has been prepared - */ - public void prepare() - { - _prepared = true; - } - - /** - * Specify whether this transaction is prepared - * - * @return true if this transaction is prepared, false otherwise - */ - public boolean isPrepared() - { - return _prepared; - } - - /** - * Notify that this tx has been heuristically rolled back - */ - public void heurRollback() - { - _heurRollBack = true; - } - - /** - * Specify whether this transaction has been heuristically rolled back - * - * @return true if this transaction has been heuristically rolled back , false otherwise - */ - public boolean isHeurRollback() - { - return _heurRollBack; - } - - /** - * Add an abstract record to this tx. - * - * @param record The record to be added - */ - public void addRecord(TransactionRecord record) - { - _records.add(record); - } - - /** - * Get the list of records associated with this tx. - * - * @return The list of records associated with this tx. - */ - public List<TransactionRecord> getrecords() - { - return _records; - } - - /** - * Set this tx timeout - * - * @param timeout This tx timeout in seconds - */ - public void setTimeout(long timeout) - { - _timeout = timeout; - } - - /** - * Get this tx timeout - * - * @return This tx timeout in seconds - */ - public long getTimeout() - { - return _timeout; - } - - /** - * Specify whether this tx has expired - * - * @return true if this tx has expired, false otherwise - */ - public boolean hasExpired() - { - long currentDate = System.currentTimeMillis(); - boolean result = currentDate - _dateCreated > _timeout * 1000; - if (_log.isDebugEnabled()) - { - _log.debug("transaction has expired"); - } - return result; - } - } diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/MemoryTransactionManager.java b/java/broker/src/main/java/org/apache/qpid/server/txn/MemoryTransactionManager.java deleted file mode 100644 index 8b0d986d4b..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/txn/MemoryTransactionManager.java +++ /dev/null @@ -1,321 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.txn; - -import java.util.HashMap; -import java.util.Set; -import javax.transaction.xa.Xid; -import org.apache.commons.configuration.Configuration; -import org.apache.log4j.Logger; -import org.apache.qpid.server.exception.*; -import org.apache.qpid.server.messageStore.MessageStore; - -/** - * Created by Arnaud Simon - * Date: 02-May-2007 - * Time: 08:41:33 - */ -public class MemoryTransactionManager implements TransactionManager -{ - // ======================================================================== - // Static Constants - // ======================================================================== - // The logger for this class - private static final Logger _log = Logger.getLogger(MemoryTransactionManager.class); - - private static final String ENVIRONMENT_TX_TIMEOUT = "environment-tx-timeout"; - - // ======================================================================== - // Instance Fields - // ======================================================================== - // The underlying BDB message store - private MessageStore _messagStore; - // A map of XID/BDBtx - private HashMap<Xid, Transaction> _xidMap; - // A map of in-doubt txs - private HashMap<Xid, MemoryTransaction> _indoubtXidMap; - - // A default tx timeout in sec - private int _defaultTimeout; // set to 10s if not specified in the config - - // ======================================================================== - // Interface TransactionManager - // ======================================================================== - public void configure(MessageStore messageStroe, String base, Configuration config) - { - _messagStore = messageStroe; - if (config != null) - { - _defaultTimeout = config.getInt(base + "." + ENVIRONMENT_TX_TIMEOUT, 10); - } - else - { - _defaultTimeout = 10; - } - - _log.info("Using transaction timeout of " + _defaultTimeout + " s"); - _xidMap = new HashMap<Xid, Transaction>(); - _indoubtXidMap = new HashMap<Xid, MemoryTransaction>(); - } - - public XAFlag begin(Xid xid) throws InternalErrorException, InvalidXidException - { - synchronized (xid) - { - if (xid == null) - { - throw new InvalidXidException(xid, "null xid"); - } - - if (_xidMap.containsKey(xid)) - { - throw new InvalidXidException(xid, "Xid already exist"); - } - - MemoryTransaction tx = new MemoryTransaction(); - tx.setTimeout(_defaultTimeout); - _xidMap.put(xid, tx); - - return XAFlag.ok; - } - } - - public XAFlag prepare(Xid xid) throws InternalErrorException, CommandInvalidException, UnknownXidException - { - synchronized (xid) - { - // get the transaction - MemoryTransaction tx = (MemoryTransaction) getTransaction(xid); - XAFlag result = XAFlag.ok; - if (tx.hasExpired()) - { - result = XAFlag.rbtimeout; - // rollback this tx branch - rollback(xid); - } - else - { - if (tx.isPrepared()) - { - throw new CommandInvalidException("TransactionImpl is already prepared", null); - } - - if (tx.getrecords().size() == 0) - { - // the tx was read only (no work has been done) - _xidMap.remove(xid); - result = XAFlag.rdonly; - } - else - { - // we need to persist the tx records - tx.prepare(); - } - } - - return result; - } - } - - public XAFlag rollback(Xid xid) throws InternalErrorException, CommandInvalidException, UnknownXidException - { - synchronized (xid) - { - // get the transaction - MemoryTransaction tx = (MemoryTransaction) getTransaction(xid); - XAFlag flag = XAFlag.ok; - if (tx.isHeurRollback()) - { - flag = XAFlag.heurrb; - } - else - { - for (TransactionRecord record : tx.getrecords()) - { - record.rollback(_messagStore); - } - - _xidMap.remove(xid); - } - - if (tx.hasExpired()) - { - flag = XAFlag.rbtimeout; - } - - return flag; - } - } - - public XAFlag commit(Xid xid) - throws InternalErrorException, CommandInvalidException, UnknownXidException, NotPreparedException - { - synchronized (xid) - { - // get the transaction - MemoryTransaction tx = (MemoryTransaction) getTransaction(xid); - XAFlag flag = XAFlag.ok; - if (tx.isHeurRollback()) - { - flag = XAFlag.heurrb; - } - else if (tx.hasExpired()) - { - flag = XAFlag.rbtimeout; - // rollback this tx branch - rollback(xid); - } - else - { - if (!tx.isPrepared()) - { - throw new NotPreparedException("TransactionImpl is not prepared"); - } - - for (TransactionRecord record : tx.getrecords()) - { - try - { - record.commit(_messagStore, xid); - } - catch (InvalidXidException e) - { - throw new UnknownXidException(xid, e); - } - catch (Exception e) - { - // this should not happen as the queue and the message must exist - _log.error("Error when committing distributed transaction heurmix mode returned: " + xid); - flag = XAFlag.heurmix; - } - } - - _xidMap.remove(xid); - } - - return flag; - } - } - - public XAFlag commit_one_phase(Xid xid) throws InternalErrorException, CommandInvalidException, UnknownXidException - { - synchronized (xid) - { - XAFlag flag = XAFlag.ok; - MemoryTransaction tx = (MemoryTransaction) getTransaction(xid); - if (tx.isHeurRollback()) - { - flag = XAFlag.heurrb; - } - else if (tx.hasExpired()) - { - flag = XAFlag.rbtimeout; - // rollback this tx branch - rollback(xid); - } - else - { - // we need to prepare the tx - tx.prepare(); - try - { - for (TransactionRecord record : tx.getrecords()) - { - try - { - record.commit(_messagStore, xid); - } - catch (InvalidXidException e) - { - throw new UnknownXidException(xid, e); - } - catch (Exception e) - { - // this should not happen as the queue and the message must exist - _log.error("Error when committing transaction heurmix mode returned: " + xid); - flag = XAFlag.heurmix; - } - } - } - finally - { - _xidMap.remove(xid); - } - } - - return flag; - } - } - - public void forget(Xid xid) throws InternalErrorException, CommandInvalidException, UnknownXidException - { - synchronized (xid) - { - _xidMap.remove(xid); - } - } - - public void setTimeout(Xid xid, long timeout) throws InternalErrorException, UnknownXidException - { - Transaction tx = getTransaction(xid); - tx.setTimeout(timeout); - } - - public long getTimeout(Xid xid) throws InternalErrorException, UnknownXidException - { - Transaction tx = getTransaction(xid); - - return tx.getTimeout(); - } - - public Set<Xid> recover(boolean startscan, boolean endscan) throws InternalErrorException, CommandInvalidException - { - return _indoubtXidMap.keySet(); - } - - public void HeuristicOutcome(Xid xid) throws UnknownXidException, InternalErrorException - { - synchronized (xid) - { - MemoryTransaction tx = (MemoryTransaction) getTransaction(xid); - if (!tx.isPrepared()) - { - // heuristically rollback this tx - for (TransactionRecord record : tx.getrecords()) - { - record.rollback(_messagStore); - } - - tx.heurRollback(); - } - // add this branch in the list of indoubt tx - _indoubtXidMap.put(xid, tx); - } - } - - public Transaction getTransaction(Xid xid) throws UnknownXidException - { - Transaction tx = _xidMap.get(xid); - if (tx == null) - { - throw new UnknownXidException(xid, null); - } - - return tx; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/NonTransactionalContext.java b/java/broker/src/main/java/org/apache/qpid/server/txn/NonTransactionalContext.java deleted file mode 100644 index 47c94114a3..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/txn/NonTransactionalContext.java +++ /dev/null @@ -1,234 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.txn; - -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.RequiredDeliveryException; -import org.apache.qpid.server.ack.UnacknowledgedMessage; -import org.apache.qpid.server.ack.UnacknowledgedMessageMap; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.queue.AMQMessage; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.NoConsumersException; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.StoreContext; - -/** @author Apache Software Foundation */ -public class NonTransactionalContext implements TransactionalContext -{ - private static final Logger _log = Logger.getLogger(NonTransactionalContext.class); - - /** Channel is useful for logging */ - private final AMQChannel _channel; - - /** Where to put undeliverable messages */ - private final List<RequiredDeliveryException> _returnMessages; - - private Set<Long> _browsedAcks; - - private final MessageStore _messageStore; - - private StoreContext _storeContext; - - /** Whether we are in a transaction */ - private boolean _inTran; - - public NonTransactionalContext(MessageStore messageStore, StoreContext storeContext, AMQChannel channel, - List<RequiredDeliveryException> returnMessages, Set<Long> browsedAcks) - { - _channel = channel; - _storeContext = storeContext; - _returnMessages = returnMessages; - _messageStore = messageStore; - _browsedAcks = browsedAcks; - } - - - public StoreContext getStoreContext() - { - return _storeContext; - } - - public void beginTranIfNecessary() throws AMQException - { - if (!_inTran) - { - _messageStore.beginTran(_storeContext); - _inTran = true; - } - } - - public void commit() throws AMQException - { - // Does not apply to this context - } - - public void rollback() throws AMQException - { - // Does not apply to this context - } - - public void deliver(AMQMessage message, AMQQueue queue, boolean deliverFirst) throws AMQException - { - try - { - //DTX removed - deliverFirst is to do with the position on the Queue not enqueuing!! - // This should be done in routingComplete -// if( ! deliverFirst ) -// { -// message.getMessageHandle().enqueue(_storeContext, message.getMessageId(), queue); -// } - queue.process(_storeContext, message, deliverFirst); - //following check implements the functionality - //required by the 'immediate' flag: - message.checkDeliveredToConsumer(); - } - catch (NoConsumersException e) - { - _returnMessages.add(e); - } - } - - public void acknowledgeMessage(final long deliveryTag, long lastDeliveryTag, - boolean multiple, final UnacknowledgedMessageMap unacknowledgedMessageMap) - throws AMQException - { - if (multiple) - { - if (deliveryTag == 0) - { - - //Spec 2.1.6.11 ... If the multiple field is 1, and the delivery tag is zero, - // tells the server to acknowledge all outstanding mesages. - _log.info("Multiple ack on delivery tag 0. ACKing all messages. Current count:" + - unacknowledgedMessageMap.size()); - unacknowledgedMessageMap.visit(new UnacknowledgedMessageMap.Visitor() - { - public boolean callback(UnacknowledgedMessage message) throws AMQException - { - if (!_browsedAcks.contains(deliveryTag)) - { - if (_log.isDebugEnabled()) - { - _log.debug("Discarding message: " + message.message.getMessageId()); - } - - //Message has been ack so discard it. This will dequeue and decrement the reference. - message.discard(_storeContext); - } - else - { - _browsedAcks.remove(deliveryTag); - } - return false; - } - - public void visitComplete() - { - unacknowledgedMessageMap.clear(); - } - }); - } - else - { - if (!unacknowledgedMessageMap.contains(deliveryTag)) - { - throw new AMQException(null, "Multiple ack on delivery tag " + deliveryTag + " not known for channel", null); - } - - LinkedList<UnacknowledgedMessage> acked = new LinkedList<UnacknowledgedMessage>(); - unacknowledgedMessageMap.drainTo(acked, deliveryTag); - for (UnacknowledgedMessage msg : acked) - { - if (!_browsedAcks.contains(deliveryTag)) - { - if (_log.isDebugEnabled()) - { - _log.debug("Discarding message: " + msg.message.getMessageId()); - } - - //Message has been ack so discard it. This will dequeue and decrement the reference. - msg.discard(_storeContext); - } - else - { - _browsedAcks.remove(deliveryTag); - } - } - } - } - else - { - UnacknowledgedMessage msg; - msg = unacknowledgedMessageMap.remove(deliveryTag); - - if (msg == null) - { - _log.info("Single ack on delivery tag " + deliveryTag + " not known for channel:" + - _channel.getChannelId()); - throw new AMQException(null, "Single ack on delivery tag " + deliveryTag + " not known for channel:" + - _channel.getChannelId(), null); - } - - if (!_browsedAcks.contains(deliveryTag)) - { - if (_log.isDebugEnabled()) - { - _log.debug("Discarding message: " + msg.message.getMessageId()); - } - - //Message has been ack so discard it. This will dequeue and decrement the reference. - msg.discard(_storeContext); - } - else - { - _browsedAcks.remove(deliveryTag); - } - - if (_log.isDebugEnabled()) - { - _log.debug("Received non-multiple ack for messaging with delivery tag " + deliveryTag + " msg id " + - msg.message.getMessageId()); - } - } - } - - public void messageFullyReceived(boolean persistent) throws AMQException - { - if (persistent) - { - //DTX removed this option. - _messageStore.commitTran(_storeContext); - _inTran = false; - } - } - - public void messageProcessed(AMQProtocolSession protocolSession) throws AMQException - { - _channel.processReturns(protocolSession); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/StoreMessageOperation.java b/java/broker/src/main/java/org/apache/qpid/server/txn/StoreMessageOperation.java deleted file mode 100644 index 0e4d6c2030..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/txn/StoreMessageOperation.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.txn; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.StoreContext; - -/** - * A transactional operation to store messages in an underlying persistent store. When this operation - * commits it will do everything to ensure that all messages are safely committed to persistent - * storage. - */ -public class StoreMessageOperation implements TxnOp -{ - private final MessageStore _messsageStore; - - public StoreMessageOperation(MessageStore messageStore) - { - _messsageStore = messageStore; - } - - public void prepare(StoreContext context) throws AMQException - { - } - - public void undoPrepare() - { - } - - public void commit(StoreContext context) throws AMQException - { - _messsageStore.commitTran(context); - } - - public void rollback(StoreContext context) throws AMQException - { - _messsageStore.abortTran(context); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/Transaction.java b/java/broker/src/main/java/org/apache/qpid/server/txn/Transaction.java deleted file mode 100644 index 2dc6ec2b77..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/txn/Transaction.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.txn; - -/** - * Created by Arnaud Simon - * Date: 25-Apr-2007 - * Time: 14:08:39 - */ -public interface Transaction -{ - - /** - * Add an abstract record to this tx. - * - * @param record The record to be added - */ - public void addRecord(TransactionRecord record); - - /** - * Set this tx timeout - * - * @param timeout This tx timeout in seconds - */ - public void setTimeout(long timeout); - - /** - * Get this tx timeout - * - * @return This tx timeout in seconds - */ - public long getTimeout(); -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/TransactionManager.java b/java/broker/src/main/java/org/apache/qpid/server/txn/TransactionManager.java deleted file mode 100644 index bcbf2c9de4..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/txn/TransactionManager.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.txn; - -import org.apache.qpid.server.exception.*; -import org.apache.qpid.server.messageStore.MessageStore; -import org.apache.commons.configuration.Configuration; - -import javax.transaction.xa.Xid; -import java.util.Set; - -/** - * Created by Arnaud Simon - * Date: 29-Mar-2007 - * Time: 13:29:31 - */ -public interface TransactionManager -{ - - /** - * Configure this TM with the Message store implementation - * - * @param base The base element identifier from which all configuration items are relative. For example, if the base - * element is "store", the all elements used by concrete classes will be "store.foo" etc. - * @param config The apache commons configuration object - * @param messageStroe the message store associated with the TM - */ - public void configure(MessageStore messageStroe, String base, Configuration config); - - /** - * Begin a transaction branch identified by Xid - * - * @param xid The xid of the branch to begin - * @return <ul> - * <li> <code>XAFlag.ok</code>: Normal execution. - * <li> <code>XAFlag.rbrollback</code>: The transaction branch was marked rollback-only for an unspecified reason. - * </ul> - * @throws InternalErrorException In case of internal problem - * @throws InvalidXidException The Xid is invalid - */ - public XAFlag begin(Xid xid) - throws - InternalErrorException, - InvalidXidException; - - /** - * Prepare the transaction branch identified by Xid - * - * @param xid The xid of the branch to prepare - * @return <ul> - * <li> <code>XAFlag.ok</code>: Normal execution. - * <li> <code>XAFlag.rdonly</code>: The transaction branch was read-only and has been committed. - * <li> <code>XAFlag.rbrollback</code>: The transaction branch was marked rollback-only for an unspeci?ed reason. - * <li> <code>XAFlag.rbtimeout</code>: The work represented by this transaction branch took too long. - * </ul> - * @throws InternalErrorException In case of internal problem - * @throws CommandInvalidException Prepare has been call in an improper context - * @throws UnknownXidException The Xid is unknown - */ - public XAFlag prepare(Xid xid) - throws - InternalErrorException, - CommandInvalidException, - UnknownXidException; - - /** - * Rollback the transaction branch identified by Xid - * - * @param xid The xid of the branch to rollback - * @return <ul> - * <li> <code>XAFlag.ok</code>: Normal execution, - * <li> <code>XAFlag.heurhaz</code>: Due to some failure, the work done on behalf of the specified transaction branch may have been heuristically completed. - * <li> <code>XAFlag.heurcom</code>: Due to a heuristic decision, the work done on behalf of the speci?ed transaction branch was committed. - * <li> <code>XAFlag.heurrb</code>: Due to a heuristic decision, the work done on behalf of the speci?ed transaction branch was rolled back. - * <li> <code>XAFlag.heurmix</code>: Due to a heuristic decision, the work done on behalf of the speci?ed transaction branch was partially committed and partially rolled back. - * <li> <code>XAFlag.rbrollback</code>: The broker marked the transaction branch rollback-only for an unspeci?ed reason. - * <li> <code>XAFlag.rbtimeout</code>: The work represented by this transaction branch took too long. - * </ul> - * @throws InternalErrorException In case of internal problem - * @throws CommandInvalidException Rollback has been call in an improper context - * @throws UnknownXidException The Xid is unknown - */ - public XAFlag rollback(Xid xid) - throws - InternalErrorException, - CommandInvalidException, - UnknownXidException; - - /** - * Commit the transaction branch identified by Xid - * - * @param xid The xid of the branch to commit - * @return <ul> - * <li> <code>XAFlag.ok</code>: Normal execution, - * <li> <code>XAFlag.heurhaz</code>: Due to some failure, the work done on behalf of the specified transaction branch may have been heuristically completed. - * <li> <code>XAFlag.heurcom</code>: Due to a heuristic decision, the work done on behalf of the speci?ed transaction branch was committed. - * <li> <code>XAFlag.heurrb</code>: Due to a heuristic decision, the work done on behalf of the speci?ed transaction branch was rolled back. - * <li> <code>XAFlag.heurmix</code>: Due to a heuristic decision, the work done on behalf of the speci?ed transaction branch was partially committed and partially rolled back. - * </ul> - * @throws InternalErrorException In case of internal problem - * @throws CommandInvalidException Commit has been call in an improper context - * @throws UnknownXidException The Xid is unknown - * @throws NotPreparedException The branch was not prepared prior to commit - */ - public XAFlag commit(Xid xid) - throws - InternalErrorException, - CommandInvalidException, - UnknownXidException, - NotPreparedException; - - /** - * One phase commit the transaction branch identified by Xid - * - * @param xid The xid of the branch to one phase commit - * @return <ul> - * <li> <code>XAFlag.ok</code>: Normal execution, - * <li> <code>XAFlag.heurhaz</code>: Due to some failure, the work done on behalf of the specified transaction branch may have been heuristically completed. - * <li> <code>XAFlag.heurcom</code>: Due to a heuristic decision, the work done on behalf of the speci?ed transaction branch was committed. - * <li> <code>XAFlag.heurrb</code>: Due to a heuristic decision, the work done on behalf of the speci?ed transaction branch was rolled back. - * <li> <code>XAFlag.heurmix</code>: Due to a heuristic decision, the work done on behalf of the speci?ed transaction branch was partially committed and partially rolled back. - * <li> <code>XAFlag.rbrollback</code>: The broker marked the transaction branch rollback-only for an unspeci?ed reason. - * <li> <code>XAFlag.rbtimeout</code>: The work represented by this transaction branch took too long. - * </ul> - * @throws InternalErrorException In case of internal problem - * @throws CommandInvalidException Commit has been call in an improper context - * @throws UnknownXidException The Xid is unknown - */ - public XAFlag commit_one_phase(Xid xid) - throws - InternalErrorException, - CommandInvalidException, - UnknownXidException; - - /** - * Forget about the transaction branch identified by Xid - * - * @param xid The xid of the branch to forget - * @throws InternalErrorException In case of internal problem - * @throws CommandInvalidException Forget has been call in an improper context - * @throws UnknownXidException The Xid is unknown - */ - public void forget(Xid xid) - throws - InternalErrorException, - CommandInvalidException, - UnknownXidException; - - /** - * Set the transaction branch timeout value in seconds - * - * @param xid The xid of the branch to set timeout - * @param timeout Timeout value in seconds - * @throws InternalErrorException In case of internal problem - * @throws UnknownXidException The Xid is unknown - */ - public void setTimeout(Xid xid, long timeout) - throws - InternalErrorException, - UnknownXidException; - - /** - * Get the transaction branch timeout - * - * @param xid The xid of the branch to get the timeout from - * @return The timeout associated with the branch identified with xid - * @throws InternalErrorException In case of internal problem - * @throws UnknownXidException The Xid is unknown - */ - public long getTimeout(Xid xid) - throws - InternalErrorException, - UnknownXidException; - - /** - * Get a set of Xids the RM has prepared or heuristically completed - * - * @param startscan Indicates that recovery scan should start - * @param endscan Indicates that the recovery scan should end after returning the Xids - * @return Set of Xids the RM has prepared or heuristically completed - * @throws InternalErrorException In case of internal problem - * @throws CommandInvalidException Recover has been call in an improper context - */ - public Set<Xid> recover(boolean startscan, boolean endscan) - throws - InternalErrorException, - CommandInvalidException; - - - /** - * An error happened (for example the channel has been abruptly closed) - * with this Xid, TM must make a heuristical decision. - * - * @param xid The Xid of the transaction branch to be heuristically completed - * @throws UnknownXidException The Xid is unknown - * @throws InternalErrorException In case of internal problem - */ - public void HeuristicOutcome(Xid xid) - throws - UnknownXidException, - InternalErrorException; - - /** - * Get the Transaction corresponding to the provided Xid - * @param xid The Xid of the transaction to ger - * @return The transaction with the provided Xid - * @throws UnknownXidException The Xid is unknown - */ - public Transaction getTransaction(Xid xid) - throws - UnknownXidException; -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/TransactionRecord.java b/java/broker/src/main/java/org/apache/qpid/server/txn/TransactionRecord.java deleted file mode 100644 index 3f6f1d6b8e..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/txn/TransactionRecord.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.txn; - -import org.apache.qpid.server.exception.*; -import org.apache.qpid.server.messageStore.MessageStore; - -import javax.transaction.xa.Xid; - -/** - * Created by Arnaud Simon - * Date: 25-Apr-2007 - * Time: 14:12:17 - */ -public interface TransactionRecord -{ - /** - * Commit this record. - * - * @param store the store to be used during commit - * @param xid the xid of the tx branch - * @throws org.apache.qpid.server.exception.InternalErrorException in case of internal problem - * @throws org.apache.qpid.server.exception.QueueDoesntExistException the queue does not exist - * @throws org.apache.qpid.server.exception.InvalidXidException the xid is invalid - * @throws org.apache.qpid.server.exception.UnknownXidException the xid is unknonw - * @throws org.apache.qpid.server.exception.MessageDoesntExistException the message does not exist - */ - public abstract void commit(MessageStore store, Xid xid) - throws - InternalErrorException, - QueueDoesntExistException, - InvalidXidException, - UnknownXidException, - MessageDoesntExistException; - - /** - * rollback this record - * - * @param store the store to be used - * @throws InternalErrorException In case of internal error - */ - public abstract void rollback(MessageStore store) - throws - InternalErrorException; - - /** - * Prepare this record - * - * @param store the store to be used - * @throws InternalErrorException In case of internal error - */ - public abstract void prepare(MessageStore store) - throws - InternalErrorException; - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/TransactionalContext.java b/java/broker/src/main/java/org/apache/qpid/server/txn/TransactionalContext.java deleted file mode 100644 index fee25c07df..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/txn/TransactionalContext.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.txn; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.ack.UnacknowledgedMessageMap; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.queue.AMQMessage; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.store.StoreContext; - -/** - * TransactionalContext provides a context in which transactional operations on {@link AMQMessage}s are performed. - * Different levels of transactional support for the delivery of messages may be provided by different implementations - * of this interface. - * - * <p/>The fundamental transactional operations that can be performed on a message queue are 'enqueue' and 'dequeue'. - * In this interface, these have been recast as the {@link #messageFullyReceived} and {@link #acknowledgeMessage} - * operations. This interface essentially provides a way to make enqueueing and dequeuing transactional. - * - * <p/><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities - * <tr><td> Explicitly accept a transaction start notification. - * <tr><td> Commit all pending operations in a transaction. - * <tr><td> Rollback all pending operations in a transaction. - * <tr><td> Deliver a message to a queue as part of a transaction. - * <tr><td> Redeliver a message to a queue as part of a transaction. - * <tr><td> Mark a message as acknowledged as part of a transaction. - * <tr><td> Accept notification that a message has been completely received as part of a transaction. - * <tr><td> Accept notification that a message has been fully processed as part of a transaction. - * <tr><td> Associate a message store context with this transaction context. - * </table> - * - * @todo The 'fullyReceived' and 'messageProcessed' events sit uncomfortably in the responsibilities of a transactional - * context. They are non-transactional operations, used to trigger other side-effects. Consider moving them - * somewhere else, a seperate interface for example. - * - * @todo This transactional context could be written as a wrapper extension to a Queue implementation, that provides - * transactional management of the enqueue and dequeue operations, with added commit/rollback methods. Any - * queue implementation could be made transactional by wrapping it as a transactional queue. This would mean - * that the enqueue/dequeue operations do not need to be recast as deliver/acknowledge operations, which may be - * conceptually neater. - * - * For example: - * <pre> - * public interface Transactional - * { - * public void commit(); - * public void rollback(); - * } - * - * public interface TransactionalQueue<E> extends Transactional, SizeableQueue<E> - * {} - * - * public class Queues - * { - * ... - * // For transactional messaging, take a transactional view onto the queue. - * public static <E> TransactionalQueue<E> getTransactionalQueue(SizeableQueue<E> queue) { ... } - * - * // For non-transactional messaging, take a non-transactional view onto the queue. - * public static <E> TransactionalQueue<E> getNonTransactionalQueue(SizeableQueue<E> queue) { ... } - * } - * </pre> - */ -public interface TransactionalContext -{ - /** - * Explicitly begins the transaction, if it has not already been started. {@link #commit} or {@link #rollback} - * should automatically begin the next transaction in the chain. - * - * @throws AMQException If the transaction cannot be started for any reason. - */ - void beginTranIfNecessary() throws AMQException; - - /** - * Makes all pending operations on the transaction permanent and visible. - * - * @throws AMQException If the transaction cannot be committed for any reason. - */ - void commit() throws AMQException; - - /** - * Erases all pending operations on the transaction. - * - * @throws AMQException If the transaction cannot be committed for any reason. - */ - void rollback() throws AMQException; - - /** - * Delivers the specified message to the specified queue. A 'deliverFirst' flag may be set if the message is a - * redelivery, and should be placed on the front of the queue. - * - * <p/>This is an 'enqueue' operation. - * - * @param message The message to deliver. - * @param queue The queue to deliver the message to. - * @param deliverFirst <tt>true</tt> to place the message on the front of the queue for redelivery, <tt>false</tt> - * for normal FIFO message ordering. - * - * @throws AMQException If the message cannot be delivered for any reason. - */ - void deliver(AMQMessage message, AMQQueue queue, boolean deliverFirst) throws AMQException; - - /** - * Acknowledges a message or many messages as delivered. All messages up to a specified one, may be acknowledged by - * setting the 'multiple' flag. It is also possible for the acknowledged message id to be zero, when the 'multiple' - * flag is set, in which case an acknowledgement up to the latest delivered message should be done. - * - * <p/>This is a 'dequeue' operation. - * - * @param deliveryTag The id of the message to acknowledge, or zero, if using multiple acknowledgement - * up to the latest message. - * @param lastDeliveryTag The latest message delivered. - * @param multiple <tt>true</tt> if all message ids up the acknowledged one or latest delivered, are - * to be acknowledged, <tt>false</tt> otherwise. - * @param unacknowledgedMessageMap The unacknowledged messages in the transaction, to remove the acknowledged message - * from. - * - * @throws AMQException If the message cannot be acknowledged for any reason. - */ - void acknowledgeMessage(long deliveryTag, long lastDeliveryTag, boolean multiple, - UnacknowledgedMessageMap unacknowledgedMessageMap) throws AMQException; - - /** - * Notifies the transactional context that a message has been fully received. The actual message that was received - * is not specified. This event may be used to trigger a process related to the receipt of the message, for example, - * flushing its data to disk. - * - * @param persistent <tt>true</tt> if the received message is persistent, <tt>false</tt> otherwise. - * - * @throws AMQException If the fully received event cannot be processed for any reason. - */ - void messageFullyReceived(boolean persistent) throws AMQException; - - /** - * Notifies the transactional context that a message has been delivered, succesfully or otherwise. The actual - * message that was delivered is not specified. This event may be used to trigger a process related to the - * outcome of the delivery of the message, for example, cleaning up failed deliveries. - * - * @param protocolSession The protocol session of the deliverable message. - * - * @throws AMQException If the message processed event cannot be handled for any reason. - */ - void messageProcessed(AMQProtocolSession protocolSession) throws AMQException; - - /** - * Gets the message store context associated with this transactional context. - * - * @return The message store context associated with this transactional context. - */ - StoreContext getStoreContext(); -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/TxnBuffer.java b/java/broker/src/main/java/org/apache/qpid/server/txn/TxnBuffer.java deleted file mode 100644 index 405c233552..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/txn/TxnBuffer.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.txn; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.server.store.StoreContext; - -/** Holds a list of TxnOp instance representing transactional operations. */ -public class TxnBuffer -{ - private final List<TxnOp> _ops = new ArrayList<TxnOp>(); - private static final Logger _log = Logger.getLogger(TxnBuffer.class); - - public TxnBuffer() - { - } - - public void commit(StoreContext context) throws AMQException - { - if (_log.isDebugEnabled()) - { - _log.debug("Committing " + _ops.size() + " ops to commit.:" + _ops); - } - - if (prepare(context)) - { - for (TxnOp op : _ops) - { - op.commit(context); - } - } - _ops.clear(); - } - - private boolean prepare(StoreContext context) - { - for (int i = 0; i < _ops.size(); i++) - { - TxnOp op = _ops.get(i); - try - { - op.prepare(context); - } - catch (Exception e) - { - //compensate previously prepared ops - for (int j = 0; j < i; j++) - { - _ops.get(j).undoPrepare(); - } - return false; - } - } - return true; - } - - public void rollback(StoreContext context) throws AMQException - { - for (TxnOp op : _ops) - { - op.rollback(context); - } - _ops.clear(); - } - - public void enlist(TxnOp op) - { - _ops.add(op); - } - - public void cancel(TxnOp op) - { - _ops.remove(op); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/TxnOp.java b/java/broker/src/main/java/org/apache/qpid/server/txn/TxnOp.java deleted file mode 100644 index 919c078cf0..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/txn/TxnOp.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.txn; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.store.StoreContext; - -/** - * This provides the abstraction of an individual operation within a - * transaction. It is used by the TxnBuffer class. - */ -public interface TxnOp -{ - /** - * Do the part of the operation that updates persistent state - */ - public void prepare(StoreContext context) throws AMQException; - /** - * Complete the operation started by prepare. Can now update in - * memory state or make netork transfers. - */ - public void commit(StoreContext context) throws AMQException; - /** - * This is not the same as rollback. Unfortunately the use of an - * in memory reference count as a locking mechanism and a test for - * whether a message should be deleted means that as things are, - * handling an acknowledgement unavoidably alters both memory and - * persistent state on prepare. This is needed to 'compensate' or - * undo the in-memory change if the peristent update of later ops - * fails. - */ - public void undoPrepare(); - /** - * Rolls back the operation. - */ - public void rollback(StoreContext context) throws AMQException; -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/XAFlag.java b/java/broker/src/main/java/org/apache/qpid/server/txn/XAFlag.java deleted file mode 100644 index 8214ab7dac..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/txn/XAFlag.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.apache.qpid.server.txn; - -/** - * Created by Arnaud Simon - * Date: 29-Mar-2007 - * Time: 14:57:01 - */ -public enum XAFlag -{ - rbrollback(1, "XA-RBROLLBACK", "The rollback was caused by an unspecified reason"), - rbtimeout(2, "XA-RBTIMEOUT", "The transaction branch took too long"), - heurhaz(3, "XA-HEURHAZ", "The transaction branch may have been heuristically completed"), - heurcom(4, "XA-HEURCOM", "The transaction branch has been heuristically committed"), - heurrb(5, "XA-HEURRB", "The transaction branch has been heuristically rolled back"), - heurmix(6, "XA-HEURMIX", "The transaction branch has been heuristically committed and rolled back"), - rdonly(7, "XA-RDONLY", "The transaction branch was read-only and has been committed"), - ok(8, "XA-OK", "Normal execution"); - - private final int _code; - - private final String _name; - - private final String _description; - - XAFlag(int code, String name, String description) - { - _code = code; - _name = name; - _description = description; - } - - //============================================== - // Getter methods - //============================================== - - public int getCode() - { - return _code; - } - - public String getName() - { - return _name; - } - - public String getDescription() - { - return _description; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/XidImpl.java b/java/broker/src/main/java/org/apache/qpid/server/txn/XidImpl.java deleted file mode 100644 index 91db1d97c0..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/txn/XidImpl.java +++ /dev/null @@ -1,210 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.txn; - - -import org.apache.log4j.Logger; - -import javax.transaction.xa.Xid; - -/** - * Created by Arnaud Simon - * Date: 03-Apr-2007 - * Time: 20:32:55 - */ -public class XidImpl implements Xid -{ - //======================================================================== - // Static Constants - //======================================================================== - // The logger for this class - private static final Logger _log = Logger.getLogger(XidImpl.class); - - //======================================================================== - // Instance Fields - //======================================================================== - - //the transaction branch identifier part of XID as an array of bytes - private byte[] m_branchQualifier; - - // the format identifier part of the XID. - private int m_formatID; - - // the global transaction identifier part of XID as an array of bytes. - private byte[] m_globalTransactionID; - - //======================================================================== - // Constructor(s) - //======================================================================== - - /** - * Create new Xid. - */ - public XidImpl() - { - - } - - /** - * Create new XidImpl from an existing Xid. - * <p/> - * This is usually called when an application server provides some implementation - * of the Xid interface and we need to cast this into our own XidImpl. - * - * @param xid the xid to cloning - */ - public XidImpl(Xid xid) - { - if (_log.isDebugEnabled()) - { - _log.debug("Cloning Xid"); - } - m_branchQualifier = xid.getBranchQualifier(); - m_formatID = xid.getFormatId(); - m_globalTransactionID = xid.getGlobalTransactionId(); - } - - /** - * Create a new Xid. - * - * @param branchQualifier The transaction branch identifier part of XID as an array of bytes. - * @param format The format identifier part of the XID. - * @param globalTransactionID The global transaction identifier part of XID as an array of bytes. - */ - public XidImpl(byte[] branchQualifier, int format, byte[] globalTransactionID) - { - if (_log.isDebugEnabled()) - { - _log.debug("creating Xid"); - } - m_branchQualifier = branchQualifier; - m_formatID = format; - m_globalTransactionID = globalTransactionID; - } - -//======================================================================== - - // Xid interface implementation - //======================================================================== - /** - * Format identifier. O means the OSI CCR format. - * - * @return Global transaction identifier. - */ - public byte[] getGlobalTransactionId() - { - return m_globalTransactionID; - } - - /** - * Obtain the transaction branch identifier part of XID as an array of bytes. - * - * @return Branch identifier part of XID. - */ - public byte[] getBranchQualifier() - { - return m_branchQualifier; - } - - /** - * Obtain the format identifier part of the XID. - * - * @return Format identifier. O means the OSI CCR format. - */ - public int getFormatId() - { - return m_formatID; - } - -//======================================================================== -// Object operations -//======================================================================== - - /** - * Indicates whether some other Xid is "equal to" this one. - * <p/> - * Two Xids are equal if and only if their three elementary parts are equal - * - * @param o the object to compare this <code>XidImpl</code> against. - * @return code>true</code> if the <code>XidImpl</code> are equal; <code>false</code> otherwise. - */ - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - if (o instanceof XidImpl) - { - XidImpl other = (XidImpl) o; - if (m_formatID == other.getFormatId()) - { - if (m_branchQualifier.length == other.getBranchQualifier().length) - { - for (int i = 0; i < m_branchQualifier.length; i++) - { - if (m_branchQualifier[i] != other.getBranchQualifier()[i]) - { - return false; - } - } - - if (m_globalTransactionID.length == other.getGlobalTransactionId().length) - { - for (int i = 0; i < m_globalTransactionID.length; i++) - { - if (m_globalTransactionID[i] != other.getGlobalTransactionId()[i]) - { - return false; - } - } - // everithing is equal - return true; - } - } - } - } - return false; - } - - /** - * Returns a hash code for this Xid. - * <p/> - * As this object is used as a key entry in a hashMap it is necessary to provide an implementation - * of hashcode in order to fulfill the following aspect of the general contract of - * {@link Object#hashCode()} that is: - * <ul> - * <li>If two objects are equal according to the <tt>equals(Object)</tt> - * method, then calling the <code>hashCode</code> method on each of - * the two objects must produce the same integer result. - * </ul> - * <p/> - * The hash code for a - * <code>XidImpl</code> object is computed as - * <blockquote><pre> - * hashcode( globalTransactionID ) + hashcode( branchQualifier ) + formatID - * </pre></blockquote> - * - * @return a hash code value for this object. - */ - public int hashCode() - { - return (new String(m_globalTransactionID)).hashCode() + (new String(m_branchQualifier)).hashCode() + m_formatID; - } - -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/util/CircularBuffer.java b/java/broker/src/main/java/org/apache/qpid/server/util/CircularBuffer.java deleted file mode 100644 index e730e2f3c3..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/util/CircularBuffer.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.util; - -import java.util.Iterator; - -import org.apache.log4j.Logger; - -public class CircularBuffer implements Iterable -{ - - private static final Logger _logger = Logger.getLogger(CircularBuffer.class); - - private final Object[] _log; - private int _size; - private int _index; - - public CircularBuffer(int size) - { - _log = new Object[size]; - } - - public void add(Object o) - { - _log[_index++] = o; - _size = Math.min(_size+1, _log.length); - if(_index >= _log.length) - { - _index = 0; - } - } - - public Object get(int i) - { - if(i >= _log.length) - { - throw new ArrayIndexOutOfBoundsException(i); - } - return _log[index(i)]; - } - - public int size() { - return _size; - } - - public Iterator iterator() - { - return new Iterator() - { - private int i = 0; - - public boolean hasNext() - { - return i < _size; - } - - public Object next() - { - return get(i++); - } - - public void remove() - { - throw new UnsupportedOperationException(); - } - }; - } - - public String toString() - { - StringBuilder s = new StringBuilder(); - boolean first = true; - for(Object o : this) - { - if(!first) - { - s.append(", "); - } - else - { - first = false; - } - s.append(o); - } - return s.toString(); - } - - public void dump() - { - for(Object o : this) - { - _logger.info(o); - } - } - - int index(int i) - { - return _size == _log.length ? (_index + i) % _log.length : i; - } - - public static void main(String[] artgv) - { - String[] items = new String[]{ - "A","B","C","D","E","F","G","H","I","J","K" - }; - CircularBuffer buffer = new CircularBuffer(5); - for(String s : items) - { - buffer.add(s); - _logger.info(buffer); - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/util/ConcurrentLinkedQueueNoSize.java b/java/broker/src/main/java/org/apache/qpid/server/util/ConcurrentLinkedQueueNoSize.java deleted file mode 100644 index cf5e71a6e2..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/util/ConcurrentLinkedQueueNoSize.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.util; - -import java.util.concurrent.ConcurrentLinkedQueue; - -public class ConcurrentLinkedQueueNoSize<E> extends ConcurrentLinkedQueue<E> -{ - public int size() - { - if (isEmpty()) - { - return 0; - } - else - { - return 1; - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/util/LoggingProxy.java b/java/broker/src/main/java/org/apache/qpid/server/util/LoggingProxy.java deleted file mode 100644 index eda97e0ed2..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/util/LoggingProxy.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.util; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.Arrays; - -/** - * Dynamic proxy that records invocations in a fixed size circular buffer, - * dumping details on hitting an exception. - * <p> - * Useful in debugging. - * <p> - */ -public class LoggingProxy implements InvocationHandler -{ - private final Object _target; - private final CircularBuffer _log; - - public LoggingProxy(Object target, int size) - { - _target = target; - _log = new CircularBuffer(size); - } - - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable - { - try - { - entered(method, args); - Object result = method.invoke(_target, args); - returned(method, result); - return result; - } - catch(InvocationTargetException e) - { - dump(); - throw e.getTargetException(); - } - } - - void dump() - { - _log.dump(); - } - - CircularBuffer getBuffer() - { - return _log; - } - - private synchronized void entered(Method method, Object[] args) - { - if (args == null) - { - _log.add(Thread.currentThread() + ": " + method.getName() + "() entered"); - } - else - { - _log.add(Thread.currentThread() + ": " + method.getName() + "(" + Arrays.toString(args) + ") entered"); - } - } - - private synchronized void returned(Method method, Object result) - { - if (method.getReturnType() == Void.TYPE) - { - _log.add(Thread.currentThread() + ": " + method.getName() + "() returned"); - } - else - { - _log.add(Thread.currentThread() + ": " + method.getName() + "() returned " + result); - } - } - - public Object getProxy(Class... c) - { - return Proxy.newProxyInstance(_target.getClass().getClassLoader(), c, this); - } - - public int getBufferSize() { - return _log.size(); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/server/util/NullApplicationRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/util/NullApplicationRegistry.java deleted file mode 100644 index 4985c12dbb..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/util/NullApplicationRegistry.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.util; - -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.Properties; - -import org.apache.commons.configuration.Configuration; -import org.apache.commons.configuration.MapConfiguration; -import org.apache.qpid.server.management.ManagedObjectRegistry; -import org.apache.qpid.server.management.NoopManagedObjectRegistry; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.security.auth.manager.AuthenticationManager; -import org.apache.qpid.server.security.auth.manager.PrincipalDatabaseAuthenticationManager; -import org.apache.qpid.server.security.auth.database.PrincipalDatabaseManager; -import org.apache.qpid.server.security.auth.database.PropertiesPrincipalDatabaseManager; -import org.apache.qpid.server.security.access.AccessManager; -import org.apache.qpid.server.security.access.AllowAll; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.virtualhost.VirtualHostRegistry; - -public class NullApplicationRegistry extends ApplicationRegistry -{ - private ManagedObjectRegistry _managedObjectRegistry; - - private AuthenticationManager _authenticationManager; - - private VirtualHostRegistry _virtualHostRegistry; - - private AccessManager _accessManager; - - private PrincipalDatabaseManager _databaseManager; - - - public NullApplicationRegistry() - { - super(new MapConfiguration(new HashMap())); - } - - public void initialise() throws Exception - { - //DTX MessageStore -// _configuration.addProperty("store.class", "org.apache.qpid.server.messageStore.MemoryMessageStore"); - _configuration.addProperty("store.class", "org.apache.qpid.server.store.MemoryMessageStore"); - _configuration.addProperty("txn.class", "org.apache.qpid.server.txn.MemoryTransactionManager"); - // _configuration.addProperty("store.class", "org.apache.qpid.server.messageStore.JDBCStore"); - // _configuration.addProperty("txn.class", "org.apache.qpid.server.txn.JDBCTransactionManager"); - - Properties users = new Properties(); - - users.put("guest", "guest"); - - _databaseManager = new PropertiesPrincipalDatabaseManager("default", users); - - _accessManager = new AllowAll(); - - _authenticationManager = new PrincipalDatabaseAuthenticationManager(null, null); - - _managedObjectRegistry = new NoopManagedObjectRegistry(); - _virtualHostRegistry = new VirtualHostRegistry(); - VirtualHost dummyHost = new VirtualHost("test", getConfiguration()); - _virtualHostRegistry.registerVirtualHost(dummyHost); - _virtualHostRegistry.setDefaultVirtualHostName("test"); - - _configuration.addProperty("heartbeat.delay", 10 * 60); // 10 minutes - - } - - public Configuration getConfiguration() - { - return _configuration; - } - - - public ManagedObjectRegistry getManagedObjectRegistry() - { - return _managedObjectRegistry; - } - - public PrincipalDatabaseManager getDatabaseManager() - { - return _databaseManager; - } - - public AuthenticationManager getAuthenticationManager() - { - return _authenticationManager; - } - - public Collection<String> getVirtualHostNames() - { - String[] hosts = {"test"}; - return Arrays.asList(hosts); - } - - public VirtualHostRegistry getVirtualHostRegistry() - { - return _virtualHostRegistry; - } - - public AccessManager getAccessManager() - { - return _accessManager; - } -} - - - diff --git a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/ManagedVirtualHost.java b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/ManagedVirtualHost.java deleted file mode 100644 index 85d804457e..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/ManagedVirtualHost.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.server.virtualhost;
-
-import java.io.IOException;
-
-import org.apache.qpid.server.management.MBeanAttribute;
-
-/**
- * The management interface exposed to allow management of an Exchange.
- * @version 0.1
- */
-public interface ManagedVirtualHost
-{
- static final String TYPE = "VirtualHost";
-
- /**
- * Returns the name of the managed virtualHost.
- * @return the name of the exchange.
- * @throws java.io.IOException
- */
- @MBeanAttribute(name="Name", description= TYPE + " Name")
- String getName() throws IOException;
-
-
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHost.java b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHost.java deleted file mode 100644 index 53844ccc4b..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHost.java +++ /dev/null @@ -1,289 +0,0 @@ -/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.virtualhost;
-
-import javax.management.NotCompliantMBeanException;
-
-import org.apache.commons.configuration.Configuration;
-import org.apache.log4j.Logger;
-import org.apache.qpid.server.AMQBrokerManagerMBean;
-import org.apache.qpid.server.txn.TransactionManager;
-import org.apache.qpid.server.security.access.AccessManager;
-import org.apache.qpid.server.security.access.AccessManagerImpl;
-import org.apache.qpid.server.security.access.Accessable;
-import org.apache.qpid.server.security.auth.manager.PrincipalDatabaseAuthenticationManager;
-import org.apache.qpid.server.security.auth.manager.AuthenticationManager;
-import org.apache.qpid.server.configuration.Configurator;
-import org.apache.qpid.server.exchange.DefaultExchangeFactory;
-import org.apache.qpid.server.exchange.DefaultExchangeRegistry;
-import org.apache.qpid.server.exchange.ExchangeFactory;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
-import org.apache.qpid.server.management.AMQManagedObject;
-import org.apache.qpid.server.management.ManagedObject;
-import org.apache.qpid.server.queue.DefaultQueueRegistry;
-import org.apache.qpid.server.queue.QueueRegistry;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.store.MessageStore;
-
-public class VirtualHost implements Accessable
-{
- private static final Logger _logger = Logger.getLogger(VirtualHost.class);
-
-
- private final String _name;
-
- private QueueRegistry _queueRegistry;
-
- private ExchangeRegistry _exchangeRegistry;
-
- private ExchangeFactory _exchangeFactory;
-
- private MessageStore _messageStore;
-
- private TransactionManager _transactionManager;
-
- protected VirtualHostMBean _virtualHostMBean;
-
- private AMQBrokerManagerMBean _brokerMBean;
-
- private AuthenticationManager _authenticationManager;
-
- private AccessManager _accessManager;
-
-
- public void setAccessableName(String name)
- {
- _logger.warn("Setting Accessable Name for VirualHost is not allowed. ("
- + name + ") ignored remains :" + getAccessableName());
- }
-
- public String getAccessableName()
- {
- return _name;
- }
-
-
- /**
- * Abstract MBean class. This has some of the methods implemented from management intrerface for exchanges. Any
- * implementaion of an Exchange MBean should extend this class.
- */
- public class VirtualHostMBean extends AMQManagedObject implements ManagedVirtualHost
- {
- public VirtualHostMBean() throws NotCompliantMBeanException
- {
- super(ManagedVirtualHost.class, "VirtualHost");
- }
-
- public String getObjectInstanceName()
- {
- return _name.toString();
- }
-
- public String getName()
- {
- return _name.toString();
- }
-
- public VirtualHost getVirtualHost()
- {
- return VirtualHost.this;
- }
-
-
- } // End of MBean class
-
- /**
- * Used for testing only
- * @param name
- * @param store
- *
- * @throws Exception
- */
- public VirtualHost(String name, MessageStore store) throws Exception
- {
- this(name, null, store);
- }
-
- /**
- * Normal Constructor
- *
- * @param name
- * @param hostConfig
- *
- * @throws Exception
- */
- public VirtualHost(String name, Configuration hostConfig) throws Exception
- {
- this(name, hostConfig, null);
- }
-
- private VirtualHost(String name, Configuration hostConfig, MessageStore store) throws Exception
- {
- _name = name;
-
- _virtualHostMBean = new VirtualHostMBean();
- // This isn't needed to be registered
- //_virtualHostMBean.register();
-
- _queueRegistry = new DefaultQueueRegistry(this);
- _exchangeFactory = new DefaultExchangeFactory(this);
- _exchangeFactory.initialise(hostConfig);
- _exchangeRegistry = new DefaultExchangeRegistry(this);
-
- if (store != null)
- {
- _messageStore = store;
- }
- else
- {
- if (hostConfig == null)
- {
- throw new IllegalAccessException("HostConfig and MessageStore cannot be null");
- }
- initialiseTransactionManager(hostConfig);
- initialiseMessageStore(hostConfig);
- }
-
- _exchangeRegistry.initialise();
-
- _authenticationManager = new PrincipalDatabaseAuthenticationManager(name, hostConfig);
-
- _accessManager = new AccessManagerImpl(name, hostConfig);
-
- _brokerMBean = new AMQBrokerManagerMBean(_virtualHostMBean);
- _brokerMBean.register();
- }
-
- private void initialiseMessageStore(Configuration config) throws Exception
- {
- String messageStoreClass = config.getString("store.class");
-
- Class clazz = Class.forName(messageStoreClass);
- Object o = clazz.newInstance();
-
- if (!(o instanceof MessageStore))
- {
- throw new ClassCastException("Message store class must implement " + MessageStore.class + ". Class " + clazz +
- " does not.");
- }
- _messageStore = (MessageStore) o;
- //DTX MessageStore
-// _messageStore.configure(this, _transactionManager, "store", config);
- _messageStore.configure(this, "store", config);
- }
-
- private void initialiseTransactionManager(Configuration config) throws Exception
- {
- String transactionManagerClass = config.getString("txn.class");
- Class clazz = Class.forName(transactionManagerClass);
- Object o = clazz.newInstance();
-
- if (!(o instanceof TransactionManager))
- {
- throw new ClassCastException("Transaction Manager class must implement " + TransactionManager.class + ". Class " + clazz +
- " does not.");
- }
- _transactionManager = (TransactionManager) o;
- }
-
-
- public <T> T getConfiguredObject(Class<T> instanceType, Configuration config)
- {
- T instance;
- try
- {
- instance = instanceType.newInstance();
- }
- catch (Exception e)
- {
- _logger.error("Unable to instantiate configuration class " + instanceType + " - ensure it has a public default constructor");
- throw new IllegalArgumentException("Unable to instantiate configuration class " + instanceType + " - ensure it has a public default constructor", e);
- }
- Configurator.configure(instance);
-
- return instance;
- }
-
-
- public String getName()
- {
- return _name;
- }
-
- public QueueRegistry getQueueRegistry()
- {
- return _queueRegistry;
- }
-
- public ExchangeRegistry getExchangeRegistry()
- {
- return _exchangeRegistry;
- }
-
- public ExchangeFactory getExchangeFactory()
- {
- return _exchangeFactory;
- }
-
- public ApplicationRegistry getApplicationRegistry()
- {
- throw new UnsupportedOperationException();
- }
-
- public MessageStore getMessageStore()
- {
- return _messageStore;
- }
-
- public TransactionManager getTransactionManager()
- {
- return _transactionManager;
- }
-
- public AuthenticationManager getAuthenticationManager()
- {
- return _authenticationManager;
- }
-
- public AccessManager getAccessManager()
- {
- return _accessManager;
- }
-
- public void close() throws Exception
- {
- if (_messageStore != null)
- {
- _messageStore.close();
- }
- }
-
- public ManagedObject getBrokerMBean()
- {
- return _brokerMBean;
- }
-
- public ManagedObject getManagedObject()
- {
- return _virtualHostMBean;
- }
-}
-
diff --git a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostRegistry.java deleted file mode 100644 index 27917fac8a..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostRegistry.java +++ /dev/null @@ -1,70 +0,0 @@ -/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.virtualhost;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-
-public class VirtualHostRegistry
-{
- private final Map<String, VirtualHost> _registry = new ConcurrentHashMap<String,VirtualHost>();
-
-
- private String _defaultVirtualHostName;
-
- public synchronized void registerVirtualHost(VirtualHost host) throws Exception
- {
- if(_registry.containsKey(host.getName()))
- {
- throw new Exception("Virtual Host with name " + host.getName() + " already registered.");
- }
- _registry.put(host.getName(),host);
- }
-
- public VirtualHost getVirtualHost(String name)
- {
- if(name == null || name.trim().length() == 0 )
- {
- name = getDefaultVirtualHostName();
- }
-
- return _registry.get(name);
- }
-
- private String getDefaultVirtualHostName()
- {
- return _defaultVirtualHostName;
- }
-
- public void setDefaultVirtualHostName(String defaultVirtualHostName)
- {
- _defaultVirtualHostName = defaultVirtualHostName;
- }
-
-
- public Collection<VirtualHost> getVirtualHosts()
- {
- return new ArrayList<VirtualHost>(_registry.values());
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/MessageStoreTool.java b/java/broker/src/main/java/org/apache/qpid/tools/messagestore/MessageStoreTool.java deleted file mode 100644 index edc900f401..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/MessageStoreTool.java +++ /dev/null @@ -1,652 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.tools.messagestore; - -import org.apache.commons.cli.Option; -import org.apache.commons.cli.OptionBuilder; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.qpid.configuration.Configuration; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.registry.ConfigurationFileApplicationRegistry; -import org.apache.qpid.server.store.MemoryMessageStore; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.tools.messagestore.commands.Clear; -import org.apache.qpid.tools.messagestore.commands.Command; -import org.apache.qpid.tools.messagestore.commands.Copy; -import org.apache.qpid.tools.messagestore.commands.Dump; -import org.apache.qpid.tools.messagestore.commands.Help; -import org.apache.qpid.tools.messagestore.commands.List; -import org.apache.qpid.tools.messagestore.commands.Load; -import org.apache.qpid.tools.messagestore.commands.Quit; -import org.apache.qpid.tools.messagestore.commands.Select; -import org.apache.qpid.tools.messagestore.commands.Show; -import org.apache.qpid.tools.messagestore.commands.Move; -import org.apache.qpid.tools.messagestore.commands.Purge; -import org.apache.qpid.tools.utils.CommandParser; -import org.apache.qpid.tools.utils.Console; -import org.apache.qpid.tools.utils.SimpleCommandParser; -import org.apache.qpid.tools.utils.SimpleConsole; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.Map; -import java.util.StringTokenizer; - -/** - * MessageStoreTool. - */ -public class MessageStoreTool -{ - /** Text outputted at the start of each console.*/ - private static final String BOILER_PLATE = "MessageStoreTool - for examining Persistent Qpid Broker MessageStore instances"; - - /** I/O Wrapper. */ - protected Console _console; - - /** Batch mode flag. */ - protected boolean _batchMode; - - /** Internal State object. */ - private State _state = new State(); - - private HashMap<String, Command> _commands = new HashMap<String, Command>(); - - /** SLF4J Logger. */ - private static Logger _devlog = LoggerFactory.getLogger(MessageStoreTool.class); - - /** Loaded configuration file. */ - private Configuration _config; - - /** Control used for main run loop. */ - private boolean _running = true; - private boolean _initialised = false; - - //---------------------------------------------------------------------------------------------------/ - - public static void main(String[] args) throws Configuration.InitException - { - - MessageStoreTool tool = new MessageStoreTool(args); - - tool.start(); - } - - - public MessageStoreTool(String[] args) throws Configuration.InitException - { - this(args, System.in, System.out); - } - - public MessageStoreTool(String[] args, InputStream in, OutputStream out) throws Configuration.InitException - { - BufferedReader consoleReader = new BufferedReader(new InputStreamReader(in)); - BufferedWriter consoleWriter = new BufferedWriter(new OutputStreamWriter(out)); - - Runtime.getRuntime().addShutdownHook(new Thread(new ShutdownHook(this))); - _batchMode = false; - - _console = new SimpleConsole(consoleWriter, consoleReader); - - _config = new Configuration(); - - setOptions(); - _config.processCommandline(args); - } - - - private void setOptions() - { - Option help = new Option("h", "help", false, "print this message"); - Option version = new Option("v", "version", false, "print the version information and exit"); - Option configFile = - OptionBuilder.withArgName("file").hasArg() - .withDescription("use given configuration file By " - + "default looks for a file named " - + Configuration.DEFAULT_CONFIG_FILE + " in " + Configuration.QPID_HOME) - .withLongOpt("config") - .create("c"); - - _config.setOption(help); - _config.setOption(version); - _config.setOption(configFile); - } - - public State getState() - { - return _state; - } - - public Map<String, Command> getCommands() - { - return _commands; - } - - public void setConfigurationFile(String configfile) throws Configuration.InitException - { - _config.loadConfig(new File(configfile)); - setup(); - } - - public Console getConsole() - { - return _console; - } - - public void setConsole(Console console) - { - _console = console; - } - - /** - * Simple ShutdownHook to cleanly shutdown the databases - */ - class ShutdownHook implements Runnable - { - MessageStoreTool _tool; - - ShutdownHook(MessageStoreTool messageStoreTool) - { - _tool = messageStoreTool; - } - - public void run() - { - _tool.quit(); - } - } - - public void quit() - { - _running = false; - - if (_initialised) - { - ApplicationRegistry.remove(1); - } - - _console.println("...exiting"); - - _console.close(); - } - - public void setBatchMode(boolean batchmode) - { - _batchMode = batchmode; - } - - /** - * Main loop - */ - protected void start() - { - setup(); - - if (!_initialised) - { - System.exit(1); - } - - _console.println(""); - - _console.println(BOILER_PLATE); - - runCLI(); - } - - private void setup() - { - loadDefaultVirtualHosts(); - - loadCommands(); - - _state.clearAll(); - } - - private void loadCommands() - { - _commands.clear(); - //todo Dynamically load the classes that exis in com.redhat.etp.qpid.commands - _commands.put("close", new Clear(this)); - _commands.put("copy", new Copy(this)); - _commands.put("dump", new Dump(this)); - _commands.put("help", new Help(this)); - _commands.put("list", new List(this)); - _commands.put("load", new Load(this)); - _commands.put("move", new Move(this)); - _commands.put("purge", new Purge(this)); - _commands.put("quit", new Quit(this)); - _commands.put("select", new Select(this)); - _commands.put("show", new Show(this)); - } - - private void loadDefaultVirtualHosts() - { - final File configFile = _config.getConfigFile(); - - loadVirtualHosts(configFile); - } - - private void loadVirtualHosts(File configFile) - { - - if (!configFile.exists()) - { - _devlog.error("Config file not found:" + configFile.getAbsolutePath()); - return; - } - else - { - _devlog.debug("using config file :" + configFile.getAbsolutePath()); - } - - try - { - ConfigurationFileApplicationRegistry registry = new ConfigurationFileApplicationRegistry(configFile); - - ApplicationRegistry.remove(1); - - ApplicationRegistry.initialise(registry); - - checkMessageStores(); - _initialised = true; - } - catch (ConfigurationException e) - { - _console.println("Unable to load configuration due to configuration error: " + e.getMessage()); - e.printStackTrace(); - } - catch (Exception e) - { - _console.println("Unable to load configuration due to: " + e.getMessage()); - e.printStackTrace(); - } - - - } - - private void checkMessageStores() - { - Collection<VirtualHost> vhosts = ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHosts(); - - boolean warning = false; - for (VirtualHost vhost : vhosts) - { - if (vhost.getMessageStore() instanceof MemoryMessageStore) - { - _console.println("WARNING: Virtualhost '" + vhost.getName() + "' is using a MemoryMessageStore. " - + "Changes will not persist."); - warning = true; - } - } - - if (warning) - { - _console.println(""); - _console.println("Please ensure you are using the correct config file currently using '" - + _config.getConfigFile().getAbsolutePath() + "'"); - _console.println("New config file can be specifed by 'load <config file>' or -c on the commandline."); - _console.println(""); - } - } - - private void runCLI() - { - while (_running) - { - if (!_batchMode) - { - printPrompt(); - } - - String[] args = _console.readCommand(); - - while (args != null) - { - exec(args); - - if (_running) - { - if (!_batchMode) - { - printPrompt(); - } - - args = _console.readCommand(); - } - } - } - } - - private void printPrompt() - { - _console.print(prompt()); - } - - - /** - * Execute a script (batch mode). - * - * @param script The file script - */ - protected void runScripts(String script) - { - //Store Current State - boolean oldBatch = _batchMode; - CommandParser oldParser = _console.getCommandParser(); - setBatchMode(true); - - try - { - _devlog.debug("Running script '" + script + "'"); - - _console.setCommandParser(new SimpleCommandParser(new BufferedReader(new FileReader(script)))); - - start(); - } - catch (java.io.FileNotFoundException e) - { - _devlog.error("Script not found: '" + script + "' due to:" + e.getMessage()); - } - - //Restore previous state - _console.setCommandParser(oldParser); - setBatchMode(oldBatch); - } - - public String prompt() - { - String state = _state.toString(); - if (state != null && state.length() != 0) - { - return state + ":bdb$ "; - } - else - { - return "bdb$ "; - } - } - - /** - * Execute the command. - * - * @param args [command, arg0, arg1...]. - */ - protected void exec(String[] args) - { - // Comment lines start with a # - if (args.length == 0 || args[0].startsWith("#")) - { - return; - } - - final String command = args[0]; - - Command cmd = _commands.get(command); - - if (cmd == null) - { - _console.println("Command not understood: " + command); - } - else - { - cmd.execute(args); - } - } - - - /** - * Displays usage info. - */ - protected static void help() - { - System.out.println(BOILER_PLATE); - System.out.println("Usage: java " + MessageStoreTool.class + " [Options]"); - System.out.println(" [-c <broker config file>] : Defaults to \"$QPID_HOME/etc/config.xml\""); - } - - - /** - * This class is used to store the current state of the tool. - * - * This is then interrogated by the various commands to augment their behaviour. - * - * - */ - public class State - { - private VirtualHost _vhost = null; - private AMQQueue _queue = null; - private Exchange _exchange = null; - private java.util.List<Long> _msgids = null; - - public State() - { - } - - public void setQueue(AMQQueue queue) - { - _queue = queue; - } - - public AMQQueue getQueue() - { - return _queue; - } - - public void setVhost(VirtualHost vhost) - { - _vhost = vhost; - } - - public VirtualHost getVhost() - { - return _vhost; - } - - public Exchange getExchange() - { - return _exchange; - } - - public void setExchange(Exchange exchange) - { - _exchange = exchange; - } - - public String toString() - { - StringBuilder status = new StringBuilder(); - - if (_vhost != null) - { - status.append(_vhost.getName()); - - if (_exchange != null) - { - status.append("["); - status.append(_exchange.getName()); - status.append("]"); - - if (_queue != null) - { - status.append("->'"); - status.append(_queue.getName()); - status.append("'"); - - if (_msgids != null) - { - status.append(printMessages()); - } - } - } - } - - return status.toString(); - } - - - public String printMessages() - { - StringBuilder sb = new StringBuilder(); - - Long previous = null; - - Long start = null; - for (Long id : _msgids) - { - if (previous != null) - { - if (id == previous + 1) - { - if (start == null) - { - start = previous; - } - } - else - { - if (start != null) - { - sb.append(","); - sb.append(start); - sb.append("-"); - sb.append(id); - start = null; - } - else - { - sb.append(","); - sb.append(previous); - } - } - } - - previous = id; - } - - if (start != null) - { - sb.append(","); - sb.append(start); - sb.append("-"); - sb.append(_msgids.get(_msgids.size() - 1)); - } - else - { - sb.append(","); - sb.append(previous); - } - - // surround list in () - sb.replace(0, 1, "("); - sb.append(")"); - return sb.toString(); - } - - public void clearAll() - { - _vhost = null; - clearExchange(); - } - - public void clearExchange() - { - _exchange = null; - clearQueue(); - } - - public void clearQueue() - { - _queue = null; - clearMessages(); - } - - public void clearMessages() - { - _msgids = null; - } - - /** - * A common location to provide parsing of the message id string - * utilised by a number of the commands. - * The String is comma separated list of ids that can be individual ids - * or a range (4-10) - * - * @param msgString string of msg ids to parse 1,2,4-10 - */ - public void setMessages(String msgString) - { - StringTokenizer tok = new StringTokenizer(msgString, ","); - - if (tok.hasMoreTokens()) - { - _msgids = new LinkedList<Long>(); - } - - while (tok.hasMoreTokens()) - { - String next = tok.nextToken(); - if (next.contains("-")) - { - Long start = Long.parseLong(next.substring(0, next.indexOf("-"))); - Long end = Long.parseLong(next.substring(next.indexOf("-") + 1)); - - if (end >= start) - { - for (long l = start; l <= end; l++) - { - _msgids.add(l); - } - } - } - else - { - _msgids.add(Long.parseLong(next)); - } - } - - } - - public void setMessages(java.util.List<Long> msgids) - { - _msgids = msgids; - } - - public java.util.List<Long> getMessages() - { - return _msgids; - } - }//Class State - -}//Class MessageStoreTool diff --git a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/AbstractCommand.java b/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/AbstractCommand.java deleted file mode 100644 index 5444197cb4..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/AbstractCommand.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.tools.messagestore.commands; - -import org.apache.qpid.tools.messagestore.MessageStoreTool; -import org.apache.qpid.tools.utils.Console; - -public abstract class AbstractCommand implements Command -{ - protected Console _console; - protected MessageStoreTool _tool; - - public AbstractCommand(MessageStoreTool tool) - { - _console = tool.getConsole(); - _tool = tool; - } - - public void setOutput(Console out) - { - _console = out; - } - - protected void commandError(String message, String[] args) - { - _console.print(getCommand() + " : " + message); - - if (args != null) - { - for (int i = 1; i < args.length; i++) - { - _console.print(args[i]); - } - } - _console.println(""); - _console.println(help()); - } - - - public abstract String help(); - - public abstract String usage(); - - public abstract String getCommand(); - - - public abstract void execute(String... args); -} diff --git a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Clear.java b/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Clear.java deleted file mode 100644 index b0006b3fe6..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Clear.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.tools.messagestore.commands; - -import org.apache.qpid.tools.messagestore.MessageStoreTool; - -public class Clear extends AbstractCommand -{ - public Clear(MessageStoreTool tool) - { - super(tool); - } - - public String help() - { - return "Clears any selection."; - } - - public String usage() - { - return "clear [ all | virtualhost | exchange | queue | msgs ]"; - } - - public String getCommand() - { - return "clear"; - } - - public void execute(String... args) - { - assert args.length > 0; - assert args[0].equals(getCommand()); - - if (args.length < 1) - { - doClose("all"); - } - else - { - doClose(args[1]); - } - } - - private void doClose(String type) - { - if (type.equals("virtualhost") - || type.equals("all")) - { - _tool.getState().clearAll(); - } - - if (type.equals("exchange")) - { - _tool.getState().clearExchange(); - } - - if (type.equals("queue")) - { - _tool.getState().clearQueue(); - } - - if (type.equals("msgs")) - { - _tool.getState().clearMessages(); - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Command.java b/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Command.java deleted file mode 100644 index bfa775a34a..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Command.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.tools.messagestore.commands; - -import org.apache.qpid.tools.utils.Console; - -public interface Command -{ - public void setOutput(Console out); - - public String help(); - - public abstract String usage(); - - String getCommand(); - - public void execute(String... args); -} diff --git a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Copy.java b/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Copy.java deleted file mode 100644 index a5b3a87616..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Copy.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.tools.messagestore.commands; - -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.tools.messagestore.MessageStoreTool; - -public class Copy extends Move -{ - public Copy(MessageStoreTool tool) - { - super(tool); - } - - public String help() - { - return "Copy messages between queues.";/*\n" + - "The currently selected message set will be copied to the specifed queue.\n" + - "Alternatively the values can be provided on the command line."; */ - } - - public String usage() - { - return "copy to=<queue> [from=<queue>] [msgids=<msgids eg, 1,2,4-10>]"; - } - - public String getCommand() - { - return "copy"; - } - - protected void doCommand(AMQQueue fromQueue, long start, long end, AMQQueue toQueue) - { - fromQueue.copyMessagesToAnotherQueue(start, end, toQueue.getName().toString(), _storeContext); - } - -} diff --git a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Dump.java b/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Dump.java deleted file mode 100644 index a0fe54994b..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Dump.java +++ /dev/null @@ -1,299 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.tools.messagestore.commands; - -import org.apache.commons.codec.binary.Hex; -import org.apache.mina.common.ByteBuffer; -import org.apache.qpid.framing.abstraction.ContentChunk; -import org.apache.qpid.server.queue.AMQMessage; -import org.apache.qpid.tools.messagestore.MessageStoreTool; -import org.apache.qpid.tools.utils.Console; - -import java.io.UnsupportedEncodingException; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; - -public class Dump extends Show -{ - private static final int LINE_SIZE = 8; - private static final String DEFAULT_ENCODING = "utf-8"; - private static final boolean SPACE_BYTES = true; - private static final String BYTE_SPACER = " "; - private static final String NON_PRINTING_ASCII_CHAR = "?"; - - protected boolean _content = true; - - public Dump(MessageStoreTool tool) - { - super(tool); - } - - public String help() - { - return "Dump selected message content. Default: show=content"; - } - - public String usage() - { - return getCommand() + " [show=[all],[msgheaders],[_amqHeaders],[routing],[content]] [id=<msgid e.g. 1,2,4-10>]"; - } - - public String getCommand() - { - return "dump"; - } - - public void execute(String... args) - { - assert args.length > 0; - assert args[0].equals(getCommand()); - - - if (args.length >= 2) - { - for (String arg : args) - { - if (arg.startsWith("show=")) - { - _content = arg.contains("content") || arg.contains("all"); - } - } - - parseArgs(args); - } - - performShow(); - } - - - protected List<List> createMessageData(java.util.List<Long> msgids, List<AMQMessage> messages, boolean showHeaders, boolean showRouting, - boolean showMessageHeaders) - { - - List<List> display = new LinkedList<List>(); - - List<String> hex = new LinkedList<String>(); - List<String> ascii = new LinkedList<String>(); - display.add(hex); - display.add(ascii); - - for (AMQMessage msg : messages) - { - if (!includeMsg(msg, msgids)) - { - continue; - } - - //Add divider between messages - hex.add(Console.ROW_DIVIDER); - ascii.add(Console.ROW_DIVIDER); - - // Show general message information - hex.add(Show.Columns.ID.name()); - ascii.add("" +msg.getMessageId()); - - hex.add(Console.ROW_DIVIDER); - ascii.add(Console.ROW_DIVIDER); - - if (showRouting) - { - addShowInformation(hex, ascii, msg, "Routing Details", true, false, false); - } - if (showHeaders) - { - addShowInformation(hex, ascii, msg, "Headers", false, true, false); - } - if (showMessageHeaders) - { - addShowInformation(hex, ascii, msg, null, false, false, true); - } - - // Add Content Body seciont - hex.add("Content Body"); - ascii.add(""); - hex.add(Console.ROW_DIVIDER); - ascii.add(Console.ROW_DIVIDER); - - Iterator bodies = msg.getContentBodyIterator(); - if (bodies.hasNext()) - { - - hex.add("Hex"); - hex.add(Console.ROW_DIVIDER); - - - ascii.add("ASCII"); - ascii.add(Console.ROW_DIVIDER); - - while (bodies.hasNext()) - { - ContentChunk chunk = (ContentChunk) bodies.next(); - - //Duplicate so we don't destroy original data :) - ByteBuffer hexBuffer = chunk.getData().duplicate(); - - ByteBuffer charBuffer = hexBuffer.duplicate(); - - Hex hexencoder = new Hex(); - - while (hexBuffer.hasRemaining()) - { - byte[] line = new byte[LINE_SIZE]; - - int bufsize = hexBuffer.remaining(); - if (bufsize < LINE_SIZE) - { - hexBuffer.get(line, 0, bufsize); - } - else - { - bufsize = line.length; - hexBuffer.get(line); - } - - byte[] encoded = hexencoder.encode(line); - - try - { - String encStr = new String(encoded, 0, bufsize * 2, DEFAULT_ENCODING); - String hexLine = ""; - - int strKength = encStr.length(); - for (int c = 0; c < strKength; c++) - { - hexLine += encStr.charAt(c); - - if (c % 2 == 1 && SPACE_BYTES) - { - hexLine += BYTE_SPACER; - } - } - - hex.add(hexLine); - } - catch (UnsupportedEncodingException e) - { - _console.println(e.getMessage()); - return null; - } - } - - while (charBuffer.hasRemaining()) - { - String asciiLine = ""; - - for (int pos = 0; pos < LINE_SIZE; pos++) - { - if (charBuffer.hasRemaining()) - { - byte ch = charBuffer.get(); - - if (isPrintable(ch)) - { - asciiLine += (char) ch; - } - else - { - asciiLine += NON_PRINTING_ASCII_CHAR; - } - - if (SPACE_BYTES) - { - asciiLine += BYTE_SPACER; - } - } - else - { - break; - } - } - - ascii.add(asciiLine); - } - } - } - else - { - List<String> result = new LinkedList<String>(); - - display.add(result); - result.add("No ContentBodies"); - } - } - - // if hex is empty then we have no data to display - if (hex.size() == 0) - { - return null; - } - - return display; - } - - private void addShowInformation(List<String> column1, List<String> column2, AMQMessage msg, - String title, boolean routing, boolean headers, boolean messageHeaders) - { - List<AMQMessage> single = new LinkedList<AMQMessage>(); - single.add(msg); - - List<List> routingData = super.createMessageData(null, single, headers, routing, messageHeaders); - - //Reformat data - if (title != null) - { - column1.add(title); - column2.add(""); - column1.add(Console.ROW_DIVIDER); - column2.add(Console.ROW_DIVIDER); - } - - // look at all columns in the routing Data - for (List item : routingData) - { - // the item should be: - // Title - // *divider - // value - // otherwise we can't reason about the correct value - if (item.size() == 3) - { - //Filter out the columns we are not interested in. - - String columnName = item.get(0).toString(); - - if (!(columnName.equals(Show.Columns.ID.name()) - || columnName.equals(Show.Columns.Size.name()))) - { - column1.add(columnName); - column2.add(item.get(2).toString()); - } - } - } - column1.add(Console.ROW_DIVIDER); - column2.add(Console.ROW_DIVIDER); - } - - private boolean isPrintable(byte c) - { - return c > 31 && c < 127; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Help.java b/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Help.java deleted file mode 100644 index 0f9546541b..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Help.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.tools.messagestore.commands; - -import org.apache.qpid.tools.messagestore.MessageStoreTool; -import org.apache.qpid.tools.utils.Console; - -import java.util.LinkedList; -import java.util.Map; - -public class Help extends AbstractCommand -{ - public Help(MessageStoreTool tool) - { - super(tool); - } - - public String help() - { - return "Provides detailed help on commands."; - } - - public String getCommand() - { - return "help"; - } - - public String usage() - { - return "help [<command>]"; - } - - public void execute(String... args) - { - assert args.length > 0; - assert args[0].equals(getCommand()); - - if (args.length > 1) - { - Command command = _tool.getCommands().get(args[1]); - if (command != null) - { - _console.println(command.help()); - _console.println("Usage:" + command.usage()); - } - else - { - commandError("Command not found: ", args); - } - } - else - { - java.util.List<java.util.List> data = new LinkedList<java.util.List>(); - - java.util.List<String> commandName = new LinkedList<String>(); - java.util.List<String> commandDescription = new LinkedList<String>(); - - data.add(commandName); - data.add(commandDescription); - - //Set up Headers - commandName.add("Command"); - commandDescription.add("Description"); - - commandName.add(Console.ROW_DIVIDER); - commandDescription.add(Console.ROW_DIVIDER); - - //Add current Commands with descriptions - Map<String, Command> commands = _tool.getCommands(); - - for (Command command : commands.values()) - { - commandName.add(command.getCommand()); - commandDescription.add(command.help()); - } - - _console.printMap("Available Commands", data); - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/List.java b/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/List.java deleted file mode 100644 index df8b59ec19..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/List.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.tools.messagestore.commands; - -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.tools.messagestore.MessageStoreTool; -import org.apache.qpid.tools.utils.Console; - -import java.util.Collection; -import java.util.LinkedList; - -public class List extends AbstractCommand -{ - - public List(MessageStoreTool tool) - { - super(tool); - } - - public void setOutput(Console out) - { - _console = out; - } - - public String help() - { - return "list available items."; - } - - public String usage() - { - return "list queues [<exchange>] | exchanges | bindings [<exchange>] | all"; - } - - public String getCommand() - { - return "list"; - } - - public void execute(String... args) - { - assert args.length > 0; - assert args[0].equals(getCommand()); - - if (args.length > 1) - { - if ((args[1].equals("exchanges")) - || (args[1].equals("queues")) - || (args[1].equals("bindings")) - || (args[1].equals("all"))) - { - if (args.length == 2) - { - doList(args[1]); - } - else if (args.length == 3) - { - doList(args[1], args[2]); - } - } - else - { - commandError("Unknown options. ", args); - } - } - else if (args.length < 2) - { - doList("all"); - } - else - { - doList(args[1]); - } - } - - private void doList(String... listItem) - { - if (_tool.getState().getVhost() == null) - { - _console.println("No Virtualhost open. Open a Virtualhost first."); - listVirtualHosts(); - return; - } - - VirtualHost vhost = _tool.getState().getVhost(); - - java.util.List<String> data = null; - - if (listItem[0].equals("queues")) - { - if (listItem.length > 1) - { - data = listQueues(vhost, new AMQShortString(listItem[1])); - } - else - { - Exchange exchange = _tool.getState().getExchange(); - data = listQueues(vhost, exchange); - } - } - - if (listItem[0].equals("exchanges")) - { - data = listExchanges(vhost); - } - - if (listItem[0].equals("bindings")) - { - - if (listItem.length > 1) - { - data = listBindings(vhost, new AMQShortString(listItem[1])); - } - else - { - Exchange exchange = _tool.getState().getExchange(); - - data = listBindings(vhost, exchange); - } - } - - if (data != null) - { - if (data.size() == 1) - { - _console.println("No '" + listItem[0] + "' to display,"); - } - else - { - _console.displayList(true, data.toArray(new String[0])); - } - } - - - if (listItem[0].equals("all")) - { - - boolean displayed = false; - Exchange exchange = _tool.getState().getExchange(); - - //Do the display here for each one so that they are pretty printed - data = listQueues(vhost, exchange); - if (data != null) - { - displayed = true; - _console.displayList(true, data.toArray(new String[0])); - } - - if (exchange == null) - { - data = listExchanges(vhost); - if (data != null) - { - displayed = true; - _console.displayList(true, data.toArray(new String[0])); - } - } - - data = listBindings(vhost, exchange); - if (data != null) - { - displayed = true; - _console.displayList(true, data.toArray(new String[0])); - } - - if (!displayed) - { - _console.println("Nothing to list"); - } - } - } - - private void listVirtualHosts() - { - Collection<VirtualHost> vhosts = ApplicationRegistry.getInstance() - .getVirtualHostRegistry().getVirtualHosts(); - - String[] data = new String[vhosts.size() + 1]; - - data[0] = "Available VirtualHosts"; - - int index = 1; - for (VirtualHost vhost : vhosts) - { - data[index] = vhost.getName(); - index++; - } - - _console.displayList(true, data); - } - - private java.util.List<String> listBindings(VirtualHost vhost, AMQShortString exchangeName) - { - return listBindings(vhost, vhost.getExchangeRegistry().getExchange(exchangeName)); - } - - private java.util.List<String> listBindings(VirtualHost vhost, Exchange exchange) - { - Collection<AMQShortString> queues = vhost.getQueueRegistry().getQueueNames(); - - if (queues == null || queues.size() == 0) - { - return null; - } - - java.util.List<String> data = new LinkedList<String>(); - - data.add("Current Bindings"); - - for (AMQShortString queue : queues) - { - if (exchange != null) - { - if (exchange.isBound(queue)) - { - data.add(queue.toString()); - } - } - else - { - data.add(queue.toString()); - } - } - - return data; - } - - private java.util.List<String> listExchanges(VirtualHost vhost) - { - Collection<AMQShortString> queues = vhost.getExchangeRegistry().getExchangeNames(); - - if (queues == null || queues.size() == 0) - { - return null; - } - - java.util.List<String> data = new LinkedList<String>(); - - data.add("Available Exchanges"); - - for (AMQShortString queue : queues) - { - data.add(queue.toString()); - } - - return data; - } - - private java.util.List<String> listQueues(VirtualHost vhost, AMQShortString exchangeName) - { - return listQueues(vhost, vhost.getExchangeRegistry().getExchange(exchangeName)); - } - - private java.util.List<String> listQueues(VirtualHost vhost, Exchange exchange) - { - Collection<AMQQueue> queues = vhost.getQueueRegistry().getQueues(); - - if (queues == null || queues.size() == 0) - { - return null; - } - - java.util.List<String> data = new LinkedList<String>(); - - data.add("Available Queues"); - - for (AMQQueue queue : queues) - { - if (exchange != null) - { - if (exchange.isBound(queue)) - { - data.add(queue.getName().toString()); - } - } - else - { - data.add(queue.getName().toString()); - } - } - - if (exchange != null) - { - if (queues.size() == 1) - { - return null; - } - } - - return data; - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Load.java b/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Load.java deleted file mode 100644 index 244a311c30..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Load.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.tools.messagestore.commands; - -import org.apache.qpid.configuration.Configuration; -import org.apache.qpid.tools.messagestore.MessageStoreTool; - -public class Load extends AbstractCommand -{ - public Load(MessageStoreTool tool) - { - super(tool); - } - - public String help() - { - return "Loads specified broker configuration file."; - } - - public String usage() - { - return "load <configuration file>"; - } - - public String getCommand() - { - return "load"; - } - - public void execute(String... args) - { - assert args.length > 0; - assert args[0].equals(getCommand()); - - if (args.length > 2) - { - _console.print("load " + args[1] + ": additional options not understood:"); - for (int i = 2; i < args.length; i++) - { - _console.print(args[i] + " "); - } - _console.println(""); - } - else if (args.length < 2) - { - _console.println("Enter Configuration file."); - String input = _console.readln(); - if (input != null) - { - doLoad(input); - } - else - { - _console.println("Did not recognise config file."); - } - } - else - { - doLoad(args[1]); - } - } - - private void doLoad(String configfile) - { - _console.println("Loading Configuration:" + configfile); - - try - { - _tool.setConfigurationFile(configfile); - } - catch (Configuration.InitException e) - { - _console.println("Unable to open config file due to: '" + e.getMessage() + "'"); - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Move.java b/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Move.java deleted file mode 100644 index 25cff27445..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Move.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.tools.messagestore.commands; - -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.queue.AMQMessage; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.store.StoreContext; -import org.apache.qpid.tools.messagestore.MessageStoreTool; - -import java.util.LinkedList; -import java.util.List; - -public class Move extends AbstractCommand -{ - - /** - * Since the Coopy command is not associated with a real channel we can safely create our own store context - * for use in the few methods that require one. - */ - protected StoreContext _storeContext = new StoreContext(); - - public Move(MessageStoreTool tool) - { - super(tool); - } - - public String help() - { - return "Move messages between queues.";/*\n" + - "The currently selected message set will be moved to the specifed queue.\n" + - "Alternatively the values can be provided on the command line.";*/ - } - - public String usage() - { - return "move to=<queue> [from=<queue>] [msgids=<msgids eg, 1,2,4-10>]"; - } - - public String getCommand() - { - return "move"; - } - - public void execute(String... args) - { - AMQQueue toQueue = null; - AMQQueue fromQueue = _tool.getState().getQueue(); - java.util.List<Long> msgids = _tool.getState().getMessages(); - - if (args.length >= 2) - { - for (String arg : args) - { - if (arg.startsWith("to=")) - { - String queueName = arg.substring(arg.indexOf("=") + 1); - toQueue = _tool.getState().getVhost().getQueueRegistry().getQueue(new AMQShortString(queueName)); - } - - if (arg.startsWith("from=")) - { - String queueName = arg.substring(arg.indexOf("=") + 1); - fromQueue = _tool.getState().getVhost().getQueueRegistry().getQueue(new AMQShortString(queueName)); - } - - if (arg.startsWith("msgids=")) - { - String msgidStr = arg.substring(arg.indexOf("=") + 1); - - // Record the current message selection - java.util.List<Long> currentIDs = _tool.getState().getMessages(); - - // Use the ToolState class to perform the messasge parsing - _tool.getState().setMessages(msgidStr); - msgids = _tool.getState().getMessages(); - - // Reset the original selection of messages - _tool.getState().setMessages(currentIDs); - } - } - } - - if (!checkRequirements(fromQueue, toQueue, msgids)) - { - return; - } - - processIDs(fromQueue, toQueue, msgids); - } - - private void processIDs(AMQQueue fromQueue, AMQQueue toQueue, java.util.List<Long> msgids) - { - Long previous = null; - Long start = null; - - if (msgids == null) - { - msgids = allMessageIDs(fromQueue); - } - - if (msgids == null || msgids.size() == 0) - { - _console.println("No Messages to move."); - return; - } - - for (long id : msgids) - { - if (previous != null) - { - if (id == previous + 1) - { - if (start == null) - { - start = previous; - } - } - else - { - if (start != null) - { - //move a range of ids - doCommand(fromQueue, start, id, toQueue); - start = null; - } - else - { - //move a single id - doCommand(fromQueue, id, id, toQueue); - } - } - } - - previous = id; - } - - if (start != null) - { - //move a range of ids - doCommand(fromQueue, start, previous, toQueue); - } - } - - private List<Long> allMessageIDs(AMQQueue fromQueue) - { - List<Long> ids = new LinkedList<Long>(); - - if (fromQueue != null) - { - List<AMQMessage> messages = fromQueue.getMessagesOnTheQueue(); - if (messages != null) - { - for (AMQMessage msg : messages) - { - ids.add(msg.getMessageId()); - } - } - } - - return ids; - } - - protected boolean checkRequirements(AMQQueue fromQueue, AMQQueue toQueue, List<Long> msgids) - { - if (toQueue == null) - { - _console.println("Destination queue not specifed."); - _console.println(usage()); - return false; - } - - if (fromQueue == null) - { - _console.println("Source queue not specifed."); - _console.println(usage()); - return false; - } - - return true; - } - - protected void doCommand(AMQQueue fromQueue, long start, long id, AMQQueue toQueue) - { - fromQueue.moveMessagesToAnotherQueue(start, id, toQueue.getName().toString(), _storeContext); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Purge.java b/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Purge.java deleted file mode 100644 index f187e26593..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Purge.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.tools.messagestore.commands; - -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.store.StoreContext; -import org.apache.qpid.tools.messagestore.MessageStoreTool; - -public class Purge extends Move -{ - public Purge(MessageStoreTool tool) - { - super(tool); - } - - public String help() - { - return "Purge messages from a queue.\n" + - "The currently selected message set will be purged from the specifed queue.\n" + - "Alternatively the values can be provided on the command line."; - } - - public String usage() - { - return "purge from=<queue> [msgids=<msgids eg, 1,2,4-10>]"; - } - - public String getCommand() - { - return "purge"; - } - - - protected boolean checkRequirements(AMQQueue fromQueue, AMQQueue toQueue, java.util.List<Long> msgids) - { - if (fromQueue == null) - { - _console.println("Source queue not specifed."); - _console.println(usage()); - return false; - } - - return true; - } - - protected void doCommand(AMQQueue fromQueue, long start, long end, AMQQueue toQueue) - { - fromQueue.removeMessagesFromQueue(start, end, _storeContext); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Quit.java b/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Quit.java deleted file mode 100644 index a81bc07c38..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Quit.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.tools.messagestore.commands; - -import org.apache.qpid.tools.messagestore.MessageStoreTool; - -public class Quit extends AbstractCommand -{ - public Quit(MessageStoreTool tool) - { - super(tool); - } - - public String help() - { - return "Quit the tool."; - } - - public String usage() - { - return "quit"; - } - - public String getCommand() - { - return "quit"; - } - - public void execute(String... args) - { - assert args.length > 0; - assert args[0].equals("quit"); - - _tool.quit(); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Select.java b/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Select.java deleted file mode 100644 index fd7d4c3f13..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Select.java +++ /dev/null @@ -1,233 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.tools.messagestore.commands; - -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.tools.messagestore.MessageStoreTool; - -import java.util.LinkedList; -import java.util.StringTokenizer; - -public class Select extends AbstractCommand -{ - - public Select(MessageStoreTool tool) - { - super(tool); - } - - public String help() - { - return "Perform a selection."; - } - - public String usage() - { - return "select virtualhost <name> |exchange <name> |queue <name> | msg id=<msgids eg. 1,2,4-10>"; - } - - public String getCommand() - { - return "select"; - } - - public void execute(String... args) - { - assert args.length > 2; - assert args[0].equals("select"); - - if (args.length < 3) - { - if (args[1].equals("show")) - { - doSelect(args[1], null); - } - else - { - _console.print("select : unknown command:"); - _console.println(help()); - } - } - else - { - if (args[1].equals("virtualhost") - || args[1].equals("vhost") - || args[1].equals("exchange") - || args[1].equals("queue") - || args[1].equals("msg") - ) - { - doSelect(args[1], args[2]); - } - else - { - _console.println(help()); - } - } - } - - private void doSelect(String type, String item) - { - if (type.equals("virtualhost")) - { - - VirtualHost vhost = ApplicationRegistry.getInstance() - .getVirtualHostRegistry().getVirtualHost(item); - - if (vhost == null) - { - _console.println("Virtualhost '" + item + "' not found."); - } - else - { - _tool.getState().setVhost(vhost); - } - } - - if (type.equals("exchange")) - { - - VirtualHost vhost = _tool.getState().getVhost(); - - if (vhost == null) - { - _console.println("No Virtualhost open. Open a Virtualhost first."); - return; - } - - - Exchange exchange = vhost.getExchangeRegistry().getExchange(new AMQShortString(item)); - - if (exchange == null) - { - _console.println("Exchange '" + item + "' not found."); - } - else - { - _tool.getState().setExchange(exchange); - } - - if (_tool.getState().getQueue() != null) - { - if (!exchange.isBound(_tool.getState().getQueue())) - { - _tool.getState().setQueue(null); - } - } - } - - if (type.equals("queue")) - { - VirtualHost vhost = _tool.getState().getVhost(); - - if (vhost == null) - { - _console.println("No Virtualhost open. Open a Virtualhost first."); - return; - } - - AMQQueue queue = vhost.getQueueRegistry().getQueue(new AMQShortString(item)); - - if (queue == null) - { - _console.println("Queue '" + item + "' not found."); - } - else - { - _tool.getState().setQueue(queue); - - if (_tool.getState().getExchange() == null) - { - for (AMQShortString exchangeName : vhost.getExchangeRegistry().getExchangeNames()) - { - Exchange exchange = vhost.getExchangeRegistry().getExchange(exchangeName); - if (exchange.isBound(queue)) - { - _tool.getState().setExchange(exchange); - break; - } - } - } - - //remove the message selection - _tool.getState().setMessages((java.util.List<Long>) null); - } - } - - if (type.equals("msg")) - { - if (item.startsWith("id=")) - { - StringTokenizer tok = new StringTokenizer(item.substring(item.indexOf("=") + 1), ","); - - java.util.List<Long> msgids = null; - - if (tok.hasMoreTokens()) - { - msgids = new LinkedList<Long>(); - } - - while (tok.hasMoreTokens()) - { - String next = tok.nextToken(); - if (next.contains("-")) - { - Long start = Long.parseLong(next.substring(0, next.indexOf("-"))); - Long end = Long.parseLong(next.substring(next.indexOf("-") + 1)); - - if (end >= start) - { - for (long l = start; l <= end; l++) - { - msgids.add(l); - } - } - } - else - { - msgids.add(Long.parseLong(next)); - } - } - - _tool.getState().setMessages(msgids); - } - - } - - if (type.equals("show")) - { - _console.println(_tool.getState().toString()); - if (_tool.getState().getMessages() != null) - { - _console.print("Msgs:"); - for (Long l : _tool.getState().getMessages()) - { - _console.print(" " + l); - } - _console.println(""); - } - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Show.java b/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Show.java deleted file mode 100644 index 8487afba76..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/tools/messagestore/commands/Show.java +++ /dev/null @@ -1,512 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.tools.messagestore.commands; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.abstraction.MessagePublishInfo; -import org.apache.qpid.server.queue.AMQMessage; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.tools.messagestore.MessageStoreTool; -import org.apache.qpid.tools.utils.Console; - -import java.util.LinkedList; -import java.util.List; - -public class Show extends AbstractCommand -{ - protected boolean _amqHeaders = false; - protected boolean _routing = false; - protected boolean _msgHeaders = false; - - public Show(MessageStoreTool tool) - { - super(tool); - } - - public String help() - { - return "Shows the messages headers."; - } - - public String usage() - { - return getCommand() + " [show=[all],[msgheaders],[amqheaders],[routing]] [id=<msgid e.g. 1,2,4-10>]"; - } - - public String getCommand() - { - return "show"; - } - - public void execute(String... args) - { - assert args.length > 0; - assert args[0].equals(getCommand()); - - if (args.length < 2) - { - parseArgs("all"); - } - else - { - parseArgs(args); - } - - performShow(); - } - - protected void parseArgs(String... args) - { - List<Long> msgids = null; - - if (args.length >= 2) - { - for (String arg : args) - { - if (arg.startsWith("show=")) - { - _msgHeaders = arg.contains("msgheaders") || arg.contains("all"); - _amqHeaders = arg.contains("amqheaders") || arg.contains("all"); - _routing = arg.contains("routing") || arg.contains("all"); - } - - if (arg.startsWith("id=")) - { - _tool.getState().setMessages(msgids); - } - }//for args - }// if args > 2 - } - - protected void performShow() - { - if (_tool.getState().getVhost() == null) - { - _console.println("No Virtualhost selected. 'DuSelect' a Virtualhost first."); - return; - } - - AMQQueue _queue = _tool.getState().getQueue(); - - List<Long> msgids = _tool.getState().getMessages(); - - if (_queue != null) - { - List<AMQMessage> messages = _queue.getMessagesOnTheQueue(); - if (messages == null || messages.size() == 0) - { - _console.println("No messages on queue"); - return; - } - - List<List> data = createMessageData(msgids, messages, _amqHeaders, _routing, _msgHeaders); - if (data != null) - { - _console.printMap(null, data); - } - else - { - String message = "No data to display."; - if (msgids != null) - { - message += " Is message selection correct? " + _tool.getState().printMessages(); - } - _console.println(message); - } - - } - else - { - _console.println("No Queue specified to show."); - } - } - - /** - * Create the list data for display from the messages. - * - * @param msgids The list of message ids to display - * @param messages A list of messages to format and display. - * @param showHeaders should the header info be shown - * @param showRouting show the routing info be shown - * @param showMessageHeaders show the msg headers be shown - * @return the formated data lists for printing - */ - protected List<List> createMessageData(List<Long> msgids, List<AMQMessage> messages, boolean showHeaders, boolean showRouting, - boolean showMessageHeaders) - { - - // Currenly exposed message properties -// //Printing the content Body -// msg.getContentBodyIterator(); -// //Print the Headers -// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getAppId(); -// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getAppIdAsString(); -// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getClusterId(); -// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getContentType(); -// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getCorrelationId(); -// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getDeliveryMode(); -// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getEncoding(); -// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getExpiration(); -// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getHeaders(); -// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getMessageId(); -// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getPriority(); -// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getPropertyFlags(); -// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getReplyTo(); -// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getTimestamp(); -// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getType(); -// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getUserId(); -// -// //Print out all the property names -// ((BasicContentHeaderProperties)msg.getContentHeaderBody().properties).getHeaders().getPropertyNames(); -// -// msg.getMessageId(); -// msg.getSize(); -// msg.getArrivalTime(); - -// msg.getDeliveredSubscription(); -// msg.getDeliveredToConsumer(); -// msg.getMessageHandle(); -// msg.getMessageId(); -// msg.getMessagePublishInfo(); -// msg.getPublisher(); - -// msg.getStoreContext(); -// msg.isAllContentReceived(); -// msg.isPersistent(); -// msg.isRedelivered(); -// msg.isRejectedBy(); -// msg.isTaken(); - - //Header setup - - List<List> data = new LinkedList<List>(); - - List<String> id = new LinkedList<String>(); - data.add(id); - id.add(Columns.ID.name()); - id.add(Console.ROW_DIVIDER); - - List<String> exchange = new LinkedList<String>(); - List<String> routingkey = new LinkedList<String>(); - List<String> immediate = new LinkedList<String>(); - List<String> mandatory = new LinkedList<String>(); - if (showRouting) - { - data.add(exchange); - exchange.add(Columns.Exchange.name()); - exchange.add(Console.ROW_DIVIDER); - - data.add(routingkey); - routingkey.add(Columns.RoutingKey.name()); - routingkey.add(Console.ROW_DIVIDER); - - data.add(immediate); - immediate.add(Columns.isImmediate.name()); - immediate.add(Console.ROW_DIVIDER); - - data.add(mandatory); - mandatory.add(Columns.isMandatory.name()); - mandatory.add(Console.ROW_DIVIDER); - } - - List<String> size = new LinkedList<String>(); - List<String> appid = new LinkedList<String>(); - List<String> clusterid = new LinkedList<String>(); - List<String> contenttype = new LinkedList<String>(); - List<String> correlationid = new LinkedList<String>(); - List<String> deliverymode = new LinkedList<String>(); - List<String> encoding = new LinkedList<String>(); - List<String> arrival = new LinkedList<String>(); - List<String> expiration = new LinkedList<String>(); - List<String> priority = new LinkedList<String>(); - List<String> propertyflag = new LinkedList<String>(); - List<String> replyto = new LinkedList<String>(); - List<String> timestamp = new LinkedList<String>(); - List<String> type = new LinkedList<String>(); - List<String> userid = new LinkedList<String>(); - List<String> ispersitent = new LinkedList<String>(); - List<String> isredelivered = new LinkedList<String>(); - List<String> isdelivered = new LinkedList<String>(); - - data.add(size); - size.add(Columns.Size.name()); - size.add(Console.ROW_DIVIDER); - - if (showHeaders) - { - data.add(ispersitent); - ispersitent.add(Columns.isPersistent.name()); - ispersitent.add(Console.ROW_DIVIDER); - - data.add(isredelivered); - isredelivered.add(Columns.isRedelivered.name()); - isredelivered.add(Console.ROW_DIVIDER); - - data.add(isdelivered); - isdelivered.add(Columns.isDelivered.name()); - isdelivered.add(Console.ROW_DIVIDER); - - data.add(appid); - appid.add(Columns.App_ID.name()); - appid.add(Console.ROW_DIVIDER); - - data.add(clusterid); - clusterid.add(Columns.Cluster_ID.name()); - clusterid.add(Console.ROW_DIVIDER); - - data.add(contenttype); - contenttype.add(Columns.Content_Type.name()); - contenttype.add(Console.ROW_DIVIDER); - - data.add(correlationid); - correlationid.add(Columns.Correlation_ID.name()); - correlationid.add(Console.ROW_DIVIDER); - - data.add(deliverymode); - deliverymode.add(Columns.Delivery_Mode.name()); - deliverymode.add(Console.ROW_DIVIDER); - - data.add(encoding); - encoding.add(Columns.Encoding.name()); - encoding.add(Console.ROW_DIVIDER); - - data.add(arrival); - expiration.add(Columns.Arrival.name()); - expiration.add(Console.ROW_DIVIDER); - - data.add(expiration); - expiration.add(Columns.Expiration.name()); - expiration.add(Console.ROW_DIVIDER); - - data.add(priority); - priority.add(Columns.Priority.name()); - priority.add(Console.ROW_DIVIDER); - - data.add(propertyflag); - propertyflag.add(Columns.Property_Flag.name()); - propertyflag.add(Console.ROW_DIVIDER); - - data.add(replyto); - replyto.add(Columns.ReplyTo.name()); - replyto.add(Console.ROW_DIVIDER); - - data.add(timestamp); - timestamp.add(Columns.Timestamp.name()); - timestamp.add(Console.ROW_DIVIDER); - - data.add(type); - type.add(Columns.Type.name()); - type.add(Console.ROW_DIVIDER); - - data.add(userid); - userid.add(Columns.UserID.name()); - userid.add(Console.ROW_DIVIDER); - } - - List<String> msgHeaders = new LinkedList<String>(); - if (showMessageHeaders) - { - data.add(msgHeaders); - msgHeaders.add(Columns.MsgHeaders.name()); - msgHeaders.add(Console.ROW_DIVIDER); - } - - //Add create the table of data - for (AMQMessage msg : messages) - { - if (!includeMsg(msg, msgids)) - { - continue; - } - - id.add("" + msg.getMessageId()); - - size.add("" + msg.getSize()); - - arrival.add("" + msg.getArrivalTime()); - - try - { - ispersitent.add(msg.isPersistent() ? "true" : "false"); - } - catch (AMQException e) - { - ispersitent.add("n/a"); - } - - isredelivered.add(msg.isRedelivered() ? "true" : "false"); - - isdelivered.add(msg.getDeliveredToConsumer() ? "true" : "false"); - -// msg.getMessageHandle(); - - BasicContentHeaderProperties headers = null; - - try - { - headers = ((BasicContentHeaderProperties) msg.getContentHeaderBody().properties); - } - catch (AMQException e) - { - //ignore -// commandError("Unable to read properties for message: " + e.getMessage(), null); - } - - if (headers != null) - { - String appidS = headers.getAppIdAsString(); - appid.add(appidS == null ? "null" : appidS); - - String clusterS = headers.getClusterIdAsString(); - clusterid.add(clusterS == null ? "null" : clusterS); - - String contentS = headers.getContentTypeAsString(); - contenttype.add(contentS == null ? "null" : contentS); - - String correlationS = headers.getCorrelationIdAsString(); - correlationid.add(correlationS == null ? "null" : correlationS); - - deliverymode.add("" + headers.getDeliveryMode()); - - AMQShortString encodeSS = headers.getEncoding(); - encoding.add(encodeSS == null ? "null" : encodeSS.toString()); - - expiration.add("" + headers.getExpiration()); - - FieldTable headerFT = headers.getHeaders(); - msgHeaders.add(headerFT == null ? "none" : "" + headerFT.toString()); - - priority.add("" + headers.getPriority()); - propertyflag.add("" + headers.getPropertyFlags()); - - AMQShortString replytoSS = headers.getReplyTo(); - replyto.add(replytoSS == null ? "null" : replytoSS.toString()); - - timestamp.add("" + headers.getTimestamp()); - - AMQShortString typeSS = headers.getType(); - type.add(typeSS == null ? "null" : typeSS.toString()); - - AMQShortString useridSS = headers.getUserId(); - userid.add(useridSS == null ? "null" : useridSS.toString()); - - MessagePublishInfo info = null; - try - { - info = msg.getMessagePublishInfo(); - } - catch (AMQException e) - { - //ignore - } - - if (info != null) - { - AMQShortString exchangeSS = info.getExchange(); - exchange.add(exchangeSS == null ? "null" : exchangeSS.toString()); - - AMQShortString routingkeySS = info.getRoutingKey(); - routingkey.add(routingkeySS == null ? "null" : routingkeySS.toString()); - - immediate.add(info.isImmediate() ? "true" : "false"); - mandatory.add(info.isMandatory() ? "true" : "false"); - } - -// msg.getPublisher(); -- only used in clustering -// msg.getStoreContext(); -// msg.isAllContentReceived(); - - }// if headers!=null - -// need to access internal map and do lookups. -// msg.isTaken(); -// msg.getDeliveredSubscription(); -// msg.isRejectedBy(); - - } - - // if id only had the header and the divider in it then we have no data to display - if (id.size() == 2) - { - return null; - } - return data; - } - - protected boolean includeMsg(AMQMessage msg, List<Long> msgids) - { - if (msgids == null) - { - return true; - } - - Long msgid = msg.getMessageId(); - - boolean found = false; - - if (msgids != null) - { - //check msgid is in msgids - for (Long l : msgids) - { - if (l.equals(msgid)) - { - found = true; - break; - } - } - } - return found; - } - - public enum Columns - { - ID, - Size, - Exchange, - RoutingKey, - isImmediate, - isMandatory, - isPersistent, - isRedelivered, - isDelivered, - App_ID, - Cluster_ID, - Content_Type, - Correlation_ID, - Delivery_Mode, - Encoding, - Arrival, - Expiration, - Priority, - Property_Flag, - ReplyTo, - Timestamp, - Type, - UserID, - MsgHeaders - } -} - - diff --git a/java/broker/src/main/java/org/apache/qpid/tools/security/Passwd.java b/java/broker/src/main/java/org/apache/qpid/tools/security/Passwd.java deleted file mode 100644 index c27c52eb8e..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/tools/security/Passwd.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.tools.security; - -import org.apache.commons.codec.binary.Base64; - -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.DigestException; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.PrintStream; - -public class Passwd -{ - public static void main(String args[]) throws NoSuchAlgorithmException, DigestException, IOException - { - if (args.length != 2) - { - System.out.println("Passwd <username> <password>"); - System.exit(0); - } - - byte[] data = args[1].getBytes("utf-8"); - - MessageDigest md = MessageDigest.getInstance("MD5"); - - for (byte b : data) - { - md.update(b); - } - - byte[] digest = md.digest(); - - Base64 b64 = new Base64(); - - byte[] encoded = b64.encode(digest); - - output(args[0], encoded); - } - - private static void output(String user, byte[] encoded) throws IOException - { - -// File passwdFile = new File("qpid.passwd"); - - PrintStream ps = new PrintStream(System.out); - - user += ":"; - ps.write(user.getBytes("utf-8")); - - for (byte b : encoded) - { - ps.write(b); - } - - ps.println(); - - ps.flush(); - ps.close(); - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/tools/utils/CommandParser.java b/java/broker/src/main/java/org/apache/qpid/tools/utils/CommandParser.java deleted file mode 100644 index 986fea32cc..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/tools/utils/CommandParser.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.tools.utils; - -public interface CommandParser -{ - /** - * If there is more than one command received on the last parse request. - * - * Subsequent calls to parse will utilise this input rather than reading new data from the input source - * @return boolean - */ - boolean more(); - - /** - * True if the currently parsed command has been requested as a background operation - * - * @return boolean - */ - boolean isBackground(); - - /** - * Parses user commands, and groups tokens in the - * String[] format that all Java main's love. - * - * If more than one command is provided in one input line then the more() method will return true. - * A subsequent call to parse() will continue to parse that input line before reading new input. - * - * @return <code>input</code> split in args[] format; null if eof. - * @throws java.io.IOException if there is a problem reading from the input stream - */ - String[] parse() throws java.io.IOException; -} diff --git a/java/broker/src/main/java/org/apache/qpid/tools/utils/Console.java b/java/broker/src/main/java/org/apache/qpid/tools/utils/Console.java deleted file mode 100644 index cf457d1ea5..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/tools/utils/Console.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.tools.utils; - -import java.util.List; - -public interface Console -{ - public enum CellFormat - { - CENTRED, LEFT, RIGHT - } - - public static String ROW_DIVIDER = "*divider"; - - public void print(String... message); - - public void println(String... message); - - public String readln(); - - /** - * Reads and parses the command line. - * - * - * @return The next command or null - */ - public String[] readCommand(); - - public CommandParser getCommandParser(); - - public void setCommandParser(CommandParser parser); - - /** - * - * Prints the list of String nicely. - * - * +-------------+ - * | Heading | - * +-------------+ - * | Item 1 | - * | Item 2 | - * | Item 3 | - * +-------------+ - * - * @param hasTitle should list[0] be used as a heading - * @param list The list of Strings to display - */ - public void displayList(boolean hasTitle, String... list); - - /** - * - * Prints the list of String nicely. - * - * +----------------------------+ - * | Heading | - * +----------------------------+ - * | title | title | .. - * +----------------------------+ - * | Item 2 | value 2 | .. - * +----------------------------+ (*divider) - * | Item 3 | value 2 | .. - * +----------------------------+ - * - * @param title The title to display if any - * @param entries the entries to display in a map. - */ - void printMap(String title, List<List> entries); - - - public void close(); -} diff --git a/java/broker/src/main/java/org/apache/qpid/tools/utils/SimpleCommandParser.java b/java/broker/src/main/java/org/apache/qpid/tools/utils/SimpleCommandParser.java deleted file mode 100644 index 09444ccdd7..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/tools/utils/SimpleCommandParser.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.tools.utils; - -import java.io.BufferedReader; -import java.io.IOException; -import java.util.StringTokenizer; - -public class SimpleCommandParser implements CommandParser -{ - private static final String COMMAND_SEPERATOR = ";"; - - /** Input source of commands */ - protected BufferedReader _reader; - - /** The next list of commands from the command line */ - private StringBuilder _nextCommand = null; - - public SimpleCommandParser(BufferedReader reader) - { - _reader = reader; - } - - public boolean more() - { - return _nextCommand != null; - } - - public boolean isBackground() - { - return false; - } - - public String[] parse() throws IOException - { - String[] commands = null; - - String input = null; - - if (_nextCommand == null) - { - input = _reader.readLine(); - } - else - { - input = _nextCommand.toString(); - _nextCommand = null; - } - - if (input == null) - { - return null; - } - - StringTokenizer tok = new StringTokenizer(input, " "); - - int tokenCount = tok.countTokens(); - int index = 0; - - if (tokenCount > 0) - { - commands = new String[tokenCount]; - boolean commandComplete = false; - - while (tok.hasMoreTokens()) - { - String next = tok.nextToken(); - - if (next.equals(COMMAND_SEPERATOR)) - { - commandComplete = true; - _nextCommand = new StringBuilder(); - continue; - } - - if (commandComplete) - { - _nextCommand.append(next); - _nextCommand.append(" "); - } - else - { - commands[index] = next; - index++; - } - } - - } - - //Reduce the String[] if not all the tokens were used in this command. - // i.e. there is more than one command on the line. - if (index != tokenCount) - { - String[] shortCommands = new String[index]; - System.arraycopy(commands, 0, shortCommands, 0, index); - return shortCommands; - } - else - { - return commands; - } - } -} diff --git a/java/broker/src/main/java/org/apache/qpid/tools/utils/SimpleConsole.java b/java/broker/src/main/java/org/apache/qpid/tools/utils/SimpleConsole.java deleted file mode 100644 index ec080a4611..0000000000 --- a/java/broker/src/main/java/org/apache/qpid/tools/utils/SimpleConsole.java +++ /dev/null @@ -1,363 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.tools.utils; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.IOException; -import java.util.LinkedList; -import java.util.List; - -public class SimpleConsole implements Console -{ - /** SLF4J Logger. */ - private static Logger _devlog = LoggerFactory.getLogger(SimpleConsole.class); - - /** Console Writer. */ - protected static BufferedWriter _consoleWriter; - - /** Console Reader. */ - protected static BufferedReader _consoleReader; - - /** Parser for command-line input. */ - protected CommandParser _parser; - - public SimpleConsole(BufferedWriter writer, BufferedReader reader) - { - _consoleWriter = writer; - _consoleReader = reader; - _parser = new SimpleCommandParser(_consoleReader); - } - - public void print(String... message) - { - try - { - for (String s : message) - { - _consoleWriter.write(s); - } - _consoleWriter.flush(); - } - catch (IOException e) - { - _devlog.error(e.getMessage() + ": Occured whilst trying to write:" + message); - } - - } - - public void println(String... message) - { - print(message); - print(System.getProperty("line.separator")); - } - - - public String readln() - { - try - { - return _consoleReader.readLine(); - } - catch (IOException e) - { - _devlog.debug("Unable to read input due to:" + e.getMessage()); - return null; - } - } - - public String[] readCommand() - { - try - { - return _parser.parse(); - } - catch (IOException e) - { - _devlog.error("Error reading command:" + e.getMessage()); - return new String[0]; - } - } - - public CommandParser getCommandParser() - { - return _parser; - } - - public void setCommandParser(CommandParser parser) - { - _parser = parser; - } - - public void displayList(boolean hasTitle, String... list) - { - java.util.List<java.util.List> data = new LinkedList<List>(); - - java.util.List<String> values = new LinkedList<String>(); - - data.add(values); - - for (String value : list) - { - values.add(value); - } - - if (hasTitle) - { - values.add(1, "*divider"); - } - - printMap(null, data); - } - - /** - * - * Prints the list of String nicely. - * - * +----------------------------+ - * | Heading | - * +----------------------------+ - * | title | title | .. - * +----------------------------+ - * | Item 2 | value 2 | .. - * | Item 3 | value 2 | .. - * +----------------------------+ - * - * @param title The title to display if any - * @param entries the entries to display in a map. - */ - public void printMap(String title, java.util.List<java.util.List> entries) - { - try - { - int columns = entries.size(); - - int[] columnWidth = new int[columns]; - - // calculate row count - int rowMax = 0; - - //the longest item - int itemMax = 0; - - for (int i = 0; i < columns; i++) - { - int columnIRowMax = entries.get(i).size(); - - if (columnIRowMax > rowMax) - { - rowMax = columnIRowMax; - } - for (Object values : entries.get(i)) - { - if (values.toString().equals(Console.ROW_DIVIDER)) - { - continue; - } - - int itemLength = values.toString().length(); - - //note for single width - if (itemLength > itemMax) - { - itemMax = itemLength; - } - - //note for mulit width - if (itemLength > columnWidth[i]) - { - columnWidth[i] = itemLength; - } - - } - } - - int tableWidth = 0; - - - for (int i = 0; i < columns; i++) - { - // plus 2 for the space padding - columnWidth[i] += 2; - } - for (int size : columnWidth) - { - tableWidth += size; - } - tableWidth += (columns - 1); - - if (title != null) - { - if (title.length() > tableWidth) - { - tableWidth = title.length(); - } - - printCellRow("+", "-", tableWidth); - - printCell(CellFormat.CENTRED, "|", tableWidth, " " + title + " ", 0); - _consoleWriter.newLine(); - - } - - //put top line | or bottom of title - printCellRow("+", "-", tableWidth); - - //print the table data - int row = 0; - - for (; row < rowMax; row++) - { - for (int i = 0; i < columns; i++) - { - java.util.List columnData = entries.get(i); - - String value; - // does this column have a value for this row - if (columnData.size() > row) - { - value = " " + columnData.get(row).toString() + " "; - } - else - { - value = " "; - } - - if (i == 0 && value.equals(" " + Console.ROW_DIVIDER + " ")) - { - printCellRow("+", "-", tableWidth); - //move on to the next row - break; - } - else - { - printCell(CellFormat.LEFT, "|", columnWidth[i], value, i); - } - - // if it is the last row then do a new line. - if (i == columns - 1) - { - _consoleWriter.newLine(); - } - } - } - - printCellRow("+", "-", tableWidth); - - } - catch (IOException e) - { - _devlog.error(e.getMessage() + ": Occured whilst trying to write."); - } - } - - public void close() - { - - try - { - _consoleReader.close(); - } - catch (IOException e) - { - _devlog.error(e.getMessage() + ": Occured whilst trying to close reader."); - } - - try - { - - _consoleWriter.close(); - } - catch (IOException e) - { - _devlog.error(e.getMessage() + ": Occured whilst trying to close writer."); - } - - } - - private void printCell(CellFormat format, String edge, int cellWidth, String cell, int column) throws IOException - { - int pad = cellWidth - cell.length(); - - if (column == 0) - { - _consoleWriter.write(edge); - } - - switch (format) - { - case CENTRED: - printPad(" ", pad / 2); - break; - case RIGHT: - printPad(" ", pad); - break; - } - - _consoleWriter.write(cell); - - - switch (format) - { - case CENTRED: - // if pad isn't even put the extra one on the right - if (pad % 2 == 0) - { - printPad(" ", pad / 2); - } - else - { - printPad(" ", (pad / 2) + 1); - } - break; - case LEFT: - printPad(" ", pad); - break; - } - - - _consoleWriter.write(edge); - - } - - private void printCellRow(String edge, String mid, int cellWidth) throws IOException - { - _consoleWriter.write(edge); - - printPad(mid, cellWidth); - - _consoleWriter.write(edge); - _consoleWriter.newLine(); - } - - private void printPad(String padChar, int count) throws IOException - { - for (int i = 0; i < count; i++) - { - _consoleWriter.write(padChar); - } - } - - -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/RunBrokerWithCommand.java b/java/broker/src/test/java/org/apache/qpid/server/RunBrokerWithCommand.java deleted file mode 100644 index 1ebecbacb6..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/RunBrokerWithCommand.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server; - -import org.apache.log4j.Logger; -import org.apache.log4j.Level; - -import java.io.InputStream; -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.io.IOException; - -public class RunBrokerWithCommand -{ - public static void main(String[] args) - { - //Start broker - - try - { - - String[] fudge = new String[1]; - fudge[0] = "-v"; - new Main(fudge).startup(); - } - catch (Exception e) - { - System.out.println("Unable to start broker due to: " + e.getMessage()); - - e.printStackTrace(); - exit(1); - } - - Logger.getRootLogger().setLevel(Level.ERROR); - - //run command - try - { - Process task = Runtime.getRuntime().exec(args[0]); - System.out.println("Started Proccess: " + args[0]); - - InputStream inputStream = task.getInputStream(); - - InputStream errorStream = task.getErrorStream(); - - Thread out = new Thread(new Outputter("[OUT]", new BufferedReader(new InputStreamReader(inputStream)))); - Thread err = new Thread(new Outputter("[ERR]", new BufferedReader(new InputStreamReader(errorStream)))); - - out.start(); - err.start(); - - out.join(); - err.join(); - - System.out.println("Waiting for process to exit: " + args[0]); - task.waitFor(); - System.out.println("Done Proccess: " + args[0]); - - } - catch (IOException e) - { - System.out.println("Proccess had problems: " + e.getMessage()); - exit(1); - } - catch (InterruptedException e) - { - System.out.println("Proccess had problems: " + e.getMessage()); - - exit(1); - } - - - exit(0); - } - - private static void exit(int i) - { - Logger.getRootLogger().setLevel(Level.INFO); - System.exit(i); - } - - static class Outputter implements Runnable - { - - BufferedReader reader; - String prefix; - - Outputter(String s, BufferedReader r) - { - prefix = s; - reader = r; - } - - public void run() - { - String line; - try - { - while ((line = reader.readLine()) != null) - { - System.out.println(prefix + line); - } - } - catch (IOException e) - { - System.out.println("Error occured reading; " + e.getMessage()); - } - } - - } - -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/configuration/TestPropertyUtils.java b/java/broker/src/test/java/org/apache/qpid/server/configuration/TestPropertyUtils.java deleted file mode 100644 index 3b83190e42..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/configuration/TestPropertyUtils.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.server.configuration; - -import org.apache.qpid.configuration.PropertyException; -import org.apache.qpid.configuration.PropertyUtils; - -import junit.framework.TestCase; - -// TODO: This belongs in the "common" module. -public class TestPropertyUtils extends TestCase -{ - public void testSimpleExpansion() throws PropertyException - { - System.setProperty("banana", "fruity"); - String expandedProperty = PropertyUtils.replaceProperties("${banana}"); - assertEquals(expandedProperty, "fruity"); - } - - public void testDualExpansion() throws PropertyException - { - System.setProperty("banana", "fruity"); - System.setProperty("concrete", "horrible"); - String expandedProperty = PropertyUtils.replaceProperties("${banana}xyz${concrete}"); - assertEquals(expandedProperty, "fruityxyzhorrible"); - } - - public static junit.framework.Test suite() - { - return new junit.framework.TestSuite(TestPropertyUtils.class); - } -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/exchange/DestWildExchangeTest.java b/java/broker/src/test/java/org/apache/qpid/server/exchange/DestWildExchangeTest.java deleted file mode 100644 index 3dbcb1c14b..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/exchange/DestWildExchangeTest.java +++ /dev/null @@ -1,583 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.exchange; - -import java.util.HashSet; -import java.util.LinkedList; - -import junit.framework.Assert; -import junit.framework.TestCase; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.abstraction.MessagePublishInfo; -import org.apache.qpid.server.RequiredDeliveryException; -import org.apache.qpid.server.store.MemoryMessageStore; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.queue.AMQMessage; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.MessageHandleFactory; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.store.StoreContext; -import org.apache.qpid.server.txn.NonTransactionalContext; -import org.apache.qpid.server.txn.TransactionalContext; -import org.apache.qpid.server.virtualhost.VirtualHost; - -public class DestWildExchangeTest extends TestCase -{ - - DestWildExchange _exchange; - - VirtualHost _vhost; - MessageStore _store; - StoreContext _context; - - public void setUp() throws AMQException - { - _exchange = new DestWildExchange(); - _vhost = ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHosts().iterator().next(); - _store = new MemoryMessageStore(); - _context = new StoreContext(); - } - - public void testNoRoute() throws AMQException - { - AMQQueue queue = new AMQQueue(new AMQShortString("a*#b"), false, null, false, _vhost); - _exchange.registerQueue(new AMQShortString("a.*.#.b"), queue, null); - - MessagePublishInfo info = new PublishInfo(new AMQShortString("a.b")); - - AMQMessage message = new AMQMessage(0L, info, null); - - try - { - _exchange.route(message); - fail("Message has no route and shouldn't be routed"); - } - catch (NoRouteException nre) - { - // normal - } - - Assert.assertEquals(0, queue.getMessageCount()); - } - - public void testDirectMatch() throws AMQException - { - AMQQueue queue = new AMQQueue(new AMQShortString("ab"), false, null, false, _vhost); - _exchange.registerQueue(new AMQShortString("a.b"), queue, null); - - AMQMessage message = createMessage("a.b"); - - try - { - _exchange.route(message); - message.routingComplete(_store, _context, new MessageHandleFactory()); - } - catch (AMQException nre) - { - fail("Message has route and should be routed"); - } - - Assert.assertEquals(1, queue.getMessageCount()); - - Assert.assertEquals("Wrong message recevied", message, queue.getMessagesOnTheQueue().get(0)); - - queue.deleteMessageFromTop(_context); - Assert.assertEquals(0, queue.getMessageCount()); - - message = createMessage("a.c"); - - try - { - _exchange.route(message); - message.routingComplete(_store, _context, new MessageHandleFactory()); - fail("Message has no route and should fail to be routed"); - } - catch (AMQException nre) - { - } - - Assert.assertEquals(0, queue.getMessageCount()); - } - - public void testStarMatch() throws AMQException - { - AMQQueue queue = new AMQQueue(new AMQShortString("a*"), false, null, false, _vhost); - _exchange.registerQueue(new AMQShortString("a.*"), queue, null); - - AMQMessage message = createMessage("a.b"); - - try - { - _exchange.route(message); - message.routingComplete(_store, _context, new MessageHandleFactory()); - } - catch (AMQException nre) - { - fail("Message has route and should be routed"); - } - - Assert.assertEquals(1, queue.getMessageCount()); - - Assert.assertEquals("Wrong message recevied", message, queue.getMessagesOnTheQueue().get(0)); - - queue.deleteMessageFromTop(_context); - Assert.assertEquals(0, queue.getMessageCount()); - - message = createMessage("a.c"); - - try - { - _exchange.route(message); - message.routingComplete(_store, _context, new MessageHandleFactory()); - } - catch (AMQException nre) - { - fail("Message has route and should be routed"); - } - - Assert.assertEquals(1, queue.getMessageCount()); - - Assert.assertEquals("Wrong message recevied", message, queue.getMessagesOnTheQueue().get(0)); - - queue.deleteMessageFromTop(_context); - Assert.assertEquals(0, queue.getMessageCount()); - - message = createMessage("a"); - - try - { - _exchange.route(message); - message.routingComplete(_store, _context, new MessageHandleFactory()); - fail("Message has no route and should fail to be routed"); - } - catch (AMQException nre) - { } - { - } - - Assert.assertEquals(0, queue.getMessageCount()); - } - - public void testHashMatch() throws AMQException - { - AMQQueue queue = new AMQQueue(new AMQShortString("a#"), false, null, false, _vhost); - _exchange.registerQueue(new AMQShortString("a.#"), queue, null); - - AMQMessage message = createMessage("a.b.c"); - - try - { - _exchange.route(message); - message.routingComplete(_store, _context, new MessageHandleFactory()); - } - catch (AMQException nre) - { - fail("Message has route and should be routed"); - } - - Assert.assertEquals(1, queue.getMessageCount()); - - Assert.assertEquals("Wrong message recevied", message, queue.getMessagesOnTheQueue().get(0)); - - queue.deleteMessageFromTop(_context); - Assert.assertEquals(0, queue.getMessageCount()); - - message = createMessage("a.b"); - - try - { - _exchange.route(message); - message.routingComplete(_store, _context, new MessageHandleFactory()); - } - catch (AMQException nre) - { - fail("Message has route and should be routed"); - } - - Assert.assertEquals(1, queue.getMessageCount()); - - Assert.assertEquals("Wrong message recevied", message, queue.getMessagesOnTheQueue().get(0)); - - queue.deleteMessageFromTop(_context); - Assert.assertEquals(0, queue.getMessageCount()); - - message = createMessage("a.c"); - - try - { - _exchange.route(message); - message.routingComplete(_store, _context, new MessageHandleFactory()); - } - catch (AMQException nre) - { - fail("Message has route and should be routed"); - } - - Assert.assertEquals(1, queue.getMessageCount()); - - Assert.assertEquals("Wrong message recevied", message, queue.getMessagesOnTheQueue().get(0)); - - queue.deleteMessageFromTop(_context); - Assert.assertEquals(0, queue.getMessageCount()); - - message = createMessage("a"); - - try - { - _exchange.route(message); - message.routingComplete(_store, _context, new MessageHandleFactory()); - } - catch (AMQException nre) - { - fail("Message has route and should be routed"); - } - - Assert.assertEquals(1, queue.getMessageCount()); - - Assert.assertEquals("Wrong message recevied", message, queue.getMessagesOnTheQueue().get(0)); - - queue.deleteMessageFromTop(_context); - Assert.assertEquals(0, queue.getMessageCount()); - - message = createMessage("b"); - - try - { - _exchange.route(message); - message.routingComplete(_store, _context, new MessageHandleFactory()); - fail("Message has no route and should fail to be routed"); - } - catch (AMQException nre) - { - } - - Assert.assertEquals(0, queue.getMessageCount()); - } - - public void testMidHash() throws AMQException - { - AMQQueue queue = new AMQQueue(new AMQShortString("a"), false, null, false, _vhost); - _exchange.registerQueue(new AMQShortString("a.*.#.b"), queue, null); - - AMQMessage message = createMessage("a.c.d.b"); - - try - { - _exchange.route(message); - message.routingComplete(_store, _context, new MessageHandleFactory()); - } - catch (AMQException nre) - { - fail("Message has no route and should be routed"); - } - - Assert.assertEquals(1, queue.getMessageCount()); - - Assert.assertEquals("Wrong message recevied", message, queue.getMessagesOnTheQueue().get(0)); - - queue.deleteMessageFromTop(_context); - Assert.assertEquals(0, queue.getMessageCount()); - - message = createMessage("a.c.b"); - - try - { - _exchange.route(message); - message.routingComplete(_store, _context, new MessageHandleFactory()); - } - catch (AMQException nre) - { - fail("Message has no route and should be routed"); - } - - Assert.assertEquals(1, queue.getMessageCount()); - - Assert.assertEquals("Wrong message recevied", message, queue.getMessagesOnTheQueue().get(0)); - - queue.deleteMessageFromTop(_context); - Assert.assertEquals(0, queue.getMessageCount()); - - } - - public void testMatchafterHash() throws AMQException - { - AMQQueue queue = new AMQQueue(new AMQShortString("a#"), false, null, false, _vhost); - _exchange.registerQueue(new AMQShortString("a.*.#.b.c"), queue, null); - - AMQMessage message = createMessage("a.c.b.b"); - - try - { - _exchange.route(message); - message.routingComplete(_store, _context, new MessageHandleFactory()); - fail("Message has route and should not be routed"); - } - catch (AMQException nre) - { - } - - Assert.assertEquals(0, queue.getMessageCount()); - - message = createMessage("a.a.b.c"); - - try - { - _exchange.route(message); - message.routingComplete(_store, _context, new MessageHandleFactory()); - } - catch (AMQException nre) - { - fail("Message has no route and should be routed"); - } - - Assert.assertEquals(1, queue.getMessageCount()); - - Assert.assertEquals("Wrong message recevied", message, queue.getMessagesOnTheQueue().get(0)); - - queue.deleteMessageFromTop(_context); - Assert.assertEquals(0, queue.getMessageCount()); - - message = createMessage("a.b.c.b"); - - try - { - _exchange.route(message); - message.routingComplete(_store, _context, new MessageHandleFactory()); - fail("Message has route and should not be routed"); - } - catch (AMQException nre) - { - } - - Assert.assertEquals(0, queue.getMessageCount()); - - message = createMessage("a.b.c.b.c"); - - try - { - _exchange.route(message); - message.routingComplete(_store, _context, new MessageHandleFactory()); - } - catch (AMQException nre) - { - fail("Message has no route and should be routed"); - - } - - Assert.assertEquals(1, queue.getMessageCount()); - - Assert.assertEquals("Wrong message recevied", message, queue.getMessagesOnTheQueue().get(0)); - - queue.deleteMessageFromTop(_context); - Assert.assertEquals(0, queue.getMessageCount()); - - } - - public void testHashAfterHash() throws AMQException - { - AMQQueue queue = new AMQQueue(new AMQShortString("a#"), false, null, false, _vhost); - _exchange.registerQueue(new AMQShortString("a.*.#.b.c.#.d"), queue, null); - - AMQMessage message = createMessage("a.c.b.b.c"); - - try - { - _exchange.route(message); - message.routingComplete(_store, _context, new MessageHandleFactory()); - fail("Message has route and should not be routed"); - } - catch (AMQException nre) - { - } - - Assert.assertEquals(0, queue.getMessageCount()); - - message = createMessage("a.a.b.c.d"); - - try - { - _exchange.route(message); - message.routingComplete(_store, _context, new MessageHandleFactory()); - } - catch (AMQException nre) - { - fail("Message has no route and should be routed"); - } - - Assert.assertEquals(1, queue.getMessageCount()); - - Assert.assertEquals("Wrong message recevied", message, queue.getMessagesOnTheQueue().get(0)); - - queue.deleteMessageFromTop(_context); - Assert.assertEquals(0, queue.getMessageCount()); - - } - - public void testHashHash() throws AMQException - { - AMQQueue queue = new AMQQueue(new AMQShortString("a#"), false, null, false, _vhost); - _exchange.registerQueue(new AMQShortString("a.#.*.#.d"), queue, null); - - AMQMessage message = createMessage("a.c.b.b.c"); - - try - { - _exchange.route(message); - message.routingComplete(_store, _context, new MessageHandleFactory()); - fail("Message has route and should not be routed"); - } - catch (AMQException nre) - { - } - - Assert.assertEquals(0, queue.getMessageCount()); - - message = createMessage("a.a.b.c.d"); - - try - { - _exchange.route(message); - message.routingComplete(_store, _context, new MessageHandleFactory()); - } - catch (AMQException nre) - { - fail("Message has no route and should be routed"); - } - - Assert.assertEquals(1, queue.getMessageCount()); - - Assert.assertEquals("Wrong message recevied", message, queue.getMessagesOnTheQueue().get(0)); - - queue.deleteMessageFromTop(_context); - Assert.assertEquals(0, queue.getMessageCount()); - - } - - public void testSubMatchFails() throws AMQException - { - AMQQueue queue = new AMQQueue(new AMQShortString("a"), false, null, false, _vhost); - _exchange.registerQueue(new AMQShortString("a.b.c.d"), queue, null); - - AMQMessage message = createMessage("a.b.c"); - - try - { - _exchange.route(message); - message.routingComplete(_store, _context, new MessageHandleFactory()); - fail("Message has route and should not be routed"); - } - catch (AMQException nre) - { - } - - Assert.assertEquals(0, queue.getMessageCount()); - - } - - public void testMoreRouting() throws AMQException - { - AMQQueue queue = new AMQQueue(new AMQShortString("a"), false, null, false, _vhost); - _exchange.registerQueue(new AMQShortString("a.b"), queue, null); - - AMQMessage message = createMessage("a.b.c"); - - try - { - _exchange.route(message); - message.routingComplete(_store, _context, new MessageHandleFactory()); - fail("Message has route and should not be routed"); - } - catch (AMQException nre) - { - } - - Assert.assertEquals(0, queue.getMessageCount()); - - } - - public void testMoreQueue() throws AMQException - { - AMQQueue queue = new AMQQueue(new AMQShortString("a"), false, null, false, _vhost); - _exchange.registerQueue(new AMQShortString("a.b"), queue, null); - - AMQMessage message = createMessage("a"); - - try - { - _exchange.route(message); - message.routingComplete(_store, _context, new MessageHandleFactory()); - fail("Message has route and should not be routed"); - } - catch (AMQException nre) - { - } - - Assert.assertEquals(0, queue.getMessageCount()); - - } - - private AMQMessage createMessage(String s) throws AMQException - { - MessagePublishInfo info = new PublishInfo(new AMQShortString(s)); - - TransactionalContext trancontext = new NonTransactionalContext(_store, _context, null, - new LinkedList<RequiredDeliveryException>(), - new HashSet<Long>()); - - AMQMessage message = new AMQMessage(0L, info, trancontext); - message.setContentHeaderBody(new ContentHeaderBody()); - - return message; - } - - class PublishInfo implements MessagePublishInfo - { - AMQShortString _routingkey; - - PublishInfo(AMQShortString routingkey) - { - _routingkey = routingkey; - } - - public AMQShortString getExchange() - { - return null; - } - - public boolean isImmediate() - { - return false; - } - - public boolean isMandatory() - { - return true; - } - - public AMQShortString getRoutingKey() - { - return _routingkey; - } - } -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/exchange/ExchangeMBeanTest.java b/java/broker/src/test/java/org/apache/qpid/server/exchange/ExchangeMBeanTest.java deleted file mode 100644 index e306f0449a..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/exchange/ExchangeMBeanTest.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.exchange; - -import junit.framework.TestCase; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.QueueRegistry; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.registry.IApplicationRegistry; -import org.apache.qpid.server.management.ManagedObject; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.AMQShortString; - -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.TabularData; -import java.util.ArrayList; - -/** - * Unit test class for testing different Exchange MBean operations - */ -public class ExchangeMBeanTest extends TestCase -{ - private AMQQueue _queue; - private QueueRegistry _queueRegistry; - private VirtualHost _virtualHost; - - /** - * Test for direct exchange mbean - * @throws Exception - */ - - public void testDirectExchangeMBean() throws Exception - { - DestNameExchange exchange = new DestNameExchange(); - exchange.initialise(_virtualHost, ExchangeDefaults.DIRECT_EXCHANGE_NAME, false, true); - ManagedObject managedObj = exchange.getManagedObject(); - ManagedExchange mbean = (ManagedExchange)managedObj; - - mbean.createNewBinding(_queue.getName().toString(), "binding1"); - mbean.createNewBinding(_queue.getName().toString(), "binding2"); - - TabularData data = mbean.bindings(); - ArrayList<Object> list = new ArrayList<Object>(data.values()); - assertTrue(list.size() == 2); - - // test general exchange properties - assertEquals(mbean.getName(), "amq.direct"); - assertEquals(mbean.getExchangeType(), "direct"); - assertTrue(!mbean.isDurable()); - assertTrue(mbean.isAutoDelete()); - } - - /** - * Test for "topic" exchange mbean - * @throws Exception - */ - - public void testTopicExchangeMBean() throws Exception - { - DestWildExchange exchange = new DestWildExchange(); - exchange.initialise(_virtualHost,ExchangeDefaults.TOPIC_EXCHANGE_NAME, false, true); - ManagedObject managedObj = exchange.getManagedObject(); - ManagedExchange mbean = (ManagedExchange)managedObj; - - mbean.createNewBinding(_queue.getName().toString(), "binding1"); - mbean.createNewBinding(_queue.getName().toString(), "binding2"); - - TabularData data = mbean.bindings(); - ArrayList<Object> list = new ArrayList<Object>(data.values()); - assertTrue(list.size() == 2); - - // test general exchange properties - assertEquals(mbean.getName(), "amq.topic"); - assertEquals(mbean.getExchangeType(), "topic"); - assertTrue(!mbean.isDurable()); - assertTrue(mbean.isAutoDelete()); - } - - /** - * Test for "Headers" exchange mbean - * @throws Exception - */ - - public void testHeadersExchangeMBean() throws Exception - { - HeadersExchange exchange = new HeadersExchange(); - exchange.initialise(_virtualHost,ExchangeDefaults.HEADERS_EXCHANGE_NAME, false, true); - ManagedObject managedObj = exchange.getManagedObject(); - ManagedExchange mbean = (ManagedExchange)managedObj; - - mbean.createNewBinding(_queue.getName().toString(), "key1=binding1,key2=binding2"); - mbean.createNewBinding(_queue.getName().toString(), "key3=binding3"); - - TabularData data = mbean.bindings(); - ArrayList<Object> list = new ArrayList<Object>(data.values()); - assertTrue(list.size() == 2); - - // test general exchange properties - assertEquals(mbean.getName(), "amq.match"); - assertEquals(mbean.getExchangeType(), "headers"); - assertTrue(!mbean.isDurable()); - assertTrue(mbean.isAutoDelete()); - } - - @Override - protected void setUp() throws Exception - { - super.setUp(); - - IApplicationRegistry applicationRegistry = ApplicationRegistry.getInstance(); - _virtualHost = applicationRegistry.getVirtualHostRegistry().getVirtualHost("test"); - _queueRegistry = _virtualHost.getQueueRegistry(); - _queue = new AMQQueue(new AMQShortString("testQueue"), false, new AMQShortString("ExchangeMBeanTest"), false, _virtualHost); - _queueRegistry.registerQueue(_queue); - } -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersBindingTest.java b/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersBindingTest.java deleted file mode 100644 index 86ba96bf5d..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersBindingTest.java +++ /dev/null @@ -1,199 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.exchange; - -import java.util.Map; -import java.util.HashMap; - -import junit.framework.TestCase; -import org.apache.qpid.framing.FieldTable; - -/** - */ -public class HeadersBindingTest extends TestCase -{ - private FieldTable bindHeaders = new FieldTable(); - private FieldTable matchHeaders = new FieldTable(); - - public void testDefault_1() - { - bindHeaders.setString("A", "Value of A"); - - matchHeaders.setString("A", "Value of A"); - - assertTrue(new HeadersBinding(bindHeaders).matches(matchHeaders)); - } - - public void testDefault_2() - { - bindHeaders.setString("A", "Value of A"); - - matchHeaders.setString("A", "Value of A"); - matchHeaders.setString("B", "Value of B"); - - assertTrue(new HeadersBinding(bindHeaders).matches(matchHeaders)); - } - - public void testDefault_3() - { - bindHeaders.setString("A", "Value of A"); - - matchHeaders.setString("A", "Altered value of A"); - - assertFalse(new HeadersBinding(bindHeaders).matches(matchHeaders)); - } - - public void testAll_1() - { - bindHeaders.setString("X-match", "all"); - bindHeaders.setString("A", "Value of A"); - - matchHeaders.setString("A", "Value of A"); - - assertTrue(new HeadersBinding(bindHeaders).matches(matchHeaders)); - } - - public void testAll_2() - { - bindHeaders.setString("X-match", "all"); - bindHeaders.setString("A", "Value of A"); - bindHeaders.setString("B", "Value of B"); - - matchHeaders.setString("A", "Value of A"); - - assertFalse(new HeadersBinding(bindHeaders).matches(matchHeaders)); - } - - public void testAll_3() - { - bindHeaders.setString("X-match", "all"); - bindHeaders.setString("A", "Value of A"); - bindHeaders.setString("B", "Value of B"); - - matchHeaders.setString("A", "Value of A"); - matchHeaders.setString("B", "Value of B"); - - assertTrue(new HeadersBinding(bindHeaders).matches(matchHeaders)); - } - - public void testAll_4() - { - bindHeaders.setString("X-match", "all"); - bindHeaders.setString("A", "Value of A"); - bindHeaders.setString("B", "Value of B"); - - matchHeaders.setString("A", "Value of A"); - matchHeaders.setString("B", "Value of B"); - matchHeaders.setString("C", "Value of C"); - - assertTrue(new HeadersBinding(bindHeaders).matches(matchHeaders)); - } - - public void testAll_5() - { - bindHeaders.setString("X-match", "all"); - bindHeaders.setString("A", "Value of A"); - bindHeaders.setString("B", "Value of B"); - - matchHeaders.setString("A", "Value of A"); - matchHeaders.setString("B", "Altered value of B"); - matchHeaders.setString("C", "Value of C"); - - assertFalse(new HeadersBinding(bindHeaders).matches(matchHeaders)); - } - - public void testAny_1() - { - bindHeaders.setString("X-match", "any"); - bindHeaders.setString("A", "Value of A"); - - matchHeaders.setString("A", "Value of A"); - - assertTrue(new HeadersBinding(bindHeaders).matches(matchHeaders)); - } - - public void testAny_2() - { - bindHeaders.setString("X-match", "any"); - bindHeaders.setString("A", "Value of A"); - bindHeaders.setString("B", "Value of B"); - - matchHeaders.setString("A", "Value of A"); - - assertTrue(new HeadersBinding(bindHeaders).matches(matchHeaders)); - } - - public void testAny_3() - { - bindHeaders.setString("X-match", "any"); - bindHeaders.setString("A", "Value of A"); - bindHeaders.setString("B", "Value of B"); - - matchHeaders.setString("A", "Value of A"); - matchHeaders.setString("B", "Value of B"); - - assertTrue(new HeadersBinding(bindHeaders).matches(matchHeaders)); - } - - public void testAny_4() - { - bindHeaders.setString("X-match", "any"); - bindHeaders.setString("A", "Value of A"); - bindHeaders.setString("B", "Value of B"); - - matchHeaders.setString("A", "Value of A"); - matchHeaders.setString("B", "Value of B"); - matchHeaders.setString("C", "Value of C"); - - assertTrue(new HeadersBinding(bindHeaders).matches(matchHeaders)); - } - - public void testAny_5() - { - bindHeaders.setString("X-match", "any"); - bindHeaders.setString("A", "Value of A"); - bindHeaders.setString("B", "Value of B"); - - matchHeaders.setString("A", "Value of A"); - matchHeaders.setString("B", "Altered value of B"); - matchHeaders.setString("C", "Value of C"); - - assertTrue(new HeadersBinding(bindHeaders).matches(matchHeaders)); - } - - public void testAny_6() - { - bindHeaders.setString("X-match", "any"); - bindHeaders.setString("A", "Value of A"); - bindHeaders.setString("B", "Value of B"); - - matchHeaders.setString("A", "Altered value of A"); - matchHeaders.setString("B", "Altered value of B"); - matchHeaders.setString("C", "Value of C"); - - assertFalse(new HeadersBinding(bindHeaders).matches(matchHeaders)); - } - - public static junit.framework.Test suite() - { - return new junit.framework.TestSuite(HeadersBindingTest.class); - } -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/protocol/TestIoSession.java b/java/broker/src/test/java/org/apache/qpid/server/protocol/TestIoSession.java deleted file mode 100644 index ff4d3ed9fb..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/protocol/TestIoSession.java +++ /dev/null @@ -1,295 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol; - -import org.apache.mina.common.*; -import org.apache.mina.transport.socket.nio.SocketAcceptorConfig; -import org.apache.qpid.pool.ReadWriteThreadModel; - -import java.net.SocketAddress; -import java.net.InetSocketAddress; -import java.util.Set; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Test implementation of IoSession, which is required for some tests. Methods not being used are not implemented, - * so if this class is being used and some methods are to be used, then please update those. - */ -public class TestIoSession implements IoSession -{ - private final ConcurrentMap attributes = new ConcurrentHashMap(); - - public TestIoSession() - { - } - - public IoService getService() - { - return null; - } - - public IoServiceConfig getServiceConfig() - { - return new TestIoConfig(); - } - - public IoHandler getHandler() - { - return null; - } - - public IoSessionConfig getConfig() - { - return null; - } - - public IoFilterChain getFilterChain() - { - return null; - } - - public WriteFuture write(Object message) - { - return null; - } - - public CloseFuture close() - { - return null; - } - - public Object getAttachment() - { - return getAttribute(""); - } - - public Object setAttachment(Object attachment) - { - return setAttribute("",attachment); - } - - public Object getAttribute(String key) - { - return attributes.get(key); - } - - public Object setAttribute(String key, Object value) - { - return attributes.put(key,value); - } - - public Object setAttribute(String key) - { - return attributes.put(key, Boolean.TRUE); - } - - public Object removeAttribute(String key) - { - return attributes.remove(key); - } - - public boolean containsAttribute(String key) - { - return attributes.containsKey(key); - } - - public Set getAttributeKeys() - { - return attributes.keySet(); - } - - public TransportType getTransportType() - { - return null; - } - - public boolean isConnected() - { - return false; - } - - public boolean isClosing() - { - return false; - } - - public CloseFuture getCloseFuture() - { - return null; - } - - public SocketAddress getRemoteAddress() - { - return new InetSocketAddress("127.0.0.1", 1234); - } - - public SocketAddress getLocalAddress() - { - return null; - } - - public SocketAddress getServiceAddress() - { - return null; - } - - public int getIdleTime(IdleStatus status) - { - return 0; - } - - public long getIdleTimeInMillis(IdleStatus status) - { - return 0; - } - - public void setIdleTime(IdleStatus status, int idleTime) - { - - } - - public int getWriteTimeout() - { - return 0; - } - - public long getWriteTimeoutInMillis() - { - return 0; - } - - public void setWriteTimeout(int writeTimeout) - { - - } - - public TrafficMask getTrafficMask() - { - return null; - } - - public void setTrafficMask(TrafficMask trafficMask) - { - - } - - public void suspendRead() - { - - } - - public void suspendWrite() - { - - } - - public void resumeRead() - { - - } - - public void resumeWrite() - { - - } - - public long getReadBytes() - { - return 0; - } - - public long getWrittenBytes() - { - return 0; - } - - public long getReadMessages() - { - return 0; - } - - public long getWrittenMessages() - { - return 0; - } - - public long getWrittenWriteRequests() - { - return 0; - } - - public int getScheduledWriteRequests() - { - return 0; - } - - public int getScheduledWriteBytes() - { - return 0; - } - - public long getCreationTime() - { - return 0; - } - - public long getLastIoTime() - { - return 0; - } - - public long getLastReadTime() - { - return 0; - } - - public long getLastWriteTime() - { - return 0; - } - - public boolean isIdle(IdleStatus status) - { - return false; - } - - public int getIdleCount(IdleStatus status) - { - return 0; - } - - public long getLastIdleTime(IdleStatus status) - { - return 0; - } - - /** - * Test implementation of IoServiceConfig - */ - private class TestIoConfig extends SocketAcceptorConfig - { - public ThreadModel getThreadModel() - { - return ReadWriteThreadModel.getInstance(); - } - } -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/protocol/TestMinaProtocolSession.java b/java/broker/src/test/java/org/apache/qpid/server/protocol/TestMinaProtocolSession.java deleted file mode 100644 index 0c0d8f471e..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/protocol/TestMinaProtocolSession.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol; - -import org.apache.qpid.AMQException; -import org.apache.qpid.codec.AMQCodecFactory; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.output.ProtocolOutputConverter; -import org.apache.qpid.server.output.ProtocolOutputConverterRegistry; - -public class TestMinaProtocolSession extends AMQMinaProtocolSession -{ - public TestMinaProtocolSession() throws AMQException - { - super(new TestIoSession(), - ApplicationRegistry.getInstance().getVirtualHostRegistry(), - new AMQCodecFactory(true)); - } - - public ProtocolOutputConverter getProtocolOutputConverter() - { - return ProtocolOutputConverterRegistry.getConverter(this); - } - - public byte getProtocolMajorVersion() - { - return (byte)8; - } - - public byte getProtocolMinorVersion() - { - return (byte)0; - } -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueAlertTest.java b/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueAlertTest.java deleted file mode 100644 index dd9f3e7723..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueAlertTest.java +++ /dev/null @@ -1,306 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.queue; - -import junit.framework.TestCase; -import org.apache.qpid.AMQException; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.MemoryMessageStore; -import org.apache.qpid.server.store.StoreContext; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.registry.IApplicationRegistry; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.txn.TransactionalContext; -import org.apache.qpid.server.txn.NonTransactionalContext; -import org.apache.qpid.server.txn.TransactionManager; -import org.apache.qpid.server.txn.MemoryTransactionManager; -import org.apache.qpid.server.RequiredDeliveryException; -import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.protocol.TestMinaProtocolSession; -import org.apache.qpid.server.protocol.AMQMinaProtocolSession; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.abstraction.MessagePublishInfo; - -import javax.management.Notification; -import java.util.LinkedList; -import java.util.HashSet; - -/** This class tests all the alerts an AMQQueue can throw based on threshold values of different parameters */ -public class AMQQueueAlertTest extends TestCase -{ - private final static long MAX_MESSAGE_COUNT = 50; - private final static long MAX_MESSAGE_AGE = 250; // 0.25 sec - private final static long MAX_MESSAGE_SIZE = 2000; // 2 KB - private final static long MAX_QUEUE_DEPTH = 10000; // 10 KB - private AMQQueue _queue; - private AMQQueueMBean _queueMBean; - private VirtualHost _virtualHost; - private AMQMinaProtocolSession protocolSession = null; - private MessageStore _messageStore = new MemoryMessageStore(); - private TransactionManager _txm = new MemoryTransactionManager(); - - private StoreContext _storeContext = new StoreContext(); - - private TransactionalContext _transactionalContext = new NonTransactionalContext(_messageStore, _storeContext, - null, - new LinkedList<RequiredDeliveryException>(), - new HashSet<Long>()); - - /** - * Tests if the alert gets thrown when message count increases the threshold limit - * - * @throws Exception - */ - public void testMessageCountAlert() throws Exception - { - _queue = new AMQQueue(new AMQShortString("testQueue1"), false, new AMQShortString("AMQueueAlertTest"), - false, _virtualHost); - _queueMBean = (AMQQueueMBean) _queue.getManagedObject(); - - _queueMBean.setMaximumMessageCount(MAX_MESSAGE_COUNT); - - sendMessages(MAX_MESSAGE_COUNT, 256l); - assertTrue(_queueMBean.getMessageCount() == MAX_MESSAGE_COUNT); - - Notification lastNotification = _queueMBean.getLastNotification(); - assertNotNull(lastNotification); - - String notificationMsg = lastNotification.getMessage(); - assertTrue(notificationMsg.startsWith(NotificationCheck.MESSAGE_COUNT_ALERT.name())); - } - - /** - * Tests if the Message Size alert gets thrown when message of higher than threshold limit is sent - * - * @throws Exception - */ - public void testMessageSizeAlert() throws Exception - { - _queue = new AMQQueue(new AMQShortString("testQueue2"), false, new AMQShortString("AMQueueAlertTest"), - false, _virtualHost); - _queueMBean = (AMQQueueMBean) _queue.getManagedObject(); - _queueMBean.setMaximumMessageCount(MAX_MESSAGE_COUNT); - _queueMBean.setMaximumMessageSize(MAX_MESSAGE_SIZE); - - sendMessages(1, MAX_MESSAGE_SIZE * 2); - assertTrue(_queueMBean.getMessageCount() == 1); - - Notification lastNotification = _queueMBean.getLastNotification(); - assertNotNull(lastNotification); - - String notificationMsg = lastNotification.getMessage(); - assertTrue(notificationMsg.startsWith(NotificationCheck.MESSAGE_SIZE_ALERT.name())); - } - - /** - * Tests if Queue Depth alert is thrown when queue depth reaches the threshold value - * - * Based on FT-402 subbmitted by client - * - * @throws Exception - */ - public void testQueueDepthAlertNoSubscriber() throws Exception - { - _queue = new AMQQueue(new AMQShortString("testQueue3"), false, new AMQShortString("AMQueueAlertTest"), - false, _virtualHost); - _queueMBean = (AMQQueueMBean) _queue.getManagedObject(); - _queueMBean.setMaximumMessageCount(MAX_MESSAGE_COUNT); - _queueMBean.setMaximumQueueDepth(MAX_QUEUE_DEPTH); - - while (_queue.getQueueDepth() < MAX_QUEUE_DEPTH) - { - sendMessages(1, MAX_MESSAGE_SIZE); - } - - Notification lastNotification = _queueMBean.getLastNotification(); - assertNotNull(lastNotification); - - String notificationMsg = lastNotification.getMessage(); - assertTrue(notificationMsg.startsWith(NotificationCheck.QUEUE_DEPTH_ALERT.name())); - } - - /** - * Tests if MESSAGE AGE alert is thrown, when a message is in the queue for time higher than threshold value of - * message age - * - * Alternative test to FT-401 provided by client - * - * @throws Exception - */ - public void testMessageAgeAlert() throws Exception - { - _queue = new AMQQueue(new AMQShortString("testQueue4"), false, new AMQShortString("AMQueueAlertTest"), - false, _virtualHost); - _queueMBean = (AMQQueueMBean) _queue.getManagedObject(); - _queueMBean.setMaximumMessageCount(MAX_MESSAGE_COUNT); - _queueMBean.setMaximumMessageAge(MAX_MESSAGE_AGE); - - sendMessages(1, MAX_MESSAGE_SIZE); - - // Ensure message sits on queue long enough to age. - Thread.sleep(MAX_MESSAGE_AGE * 2); - - sendMessages(1, MAX_MESSAGE_SIZE); - assertTrue(_queueMBean.getMessageCount() == 2); - - Notification lastNotification = _queueMBean.getLastNotification(); - assertNotNull(lastNotification); - - String notificationMsg = lastNotification.getMessage(); - assertTrue(notificationMsg.startsWith(NotificationCheck.MESSAGE_AGE_ALERT.name())); - } - - /* - This test sends some messages to the queue with subscribers needing message to be acknowledged. - The messages will not be acknowledged and will be required twice. Why we are checking this is because - the bug reported said that the queueDepth keeps increasing when messages are requeued. - The QueueDepth should decrease when messages are delivered from the queue (QPID-408) - */ - public void testQueueDepthAlertWithSubscribers() throws Exception - { - protocolSession = new TestMinaProtocolSession(); - AMQChannel channel = new AMQChannel(protocolSession, 2,_txm, _messageStore, null); - protocolSession.addChannel(channel); - - // Create queue - _queue = getNewQueue(); - _queue.registerProtocolSession(protocolSession, channel.getChannelId(), - new AMQShortString("consumer_tag"), true, null, false, false); - - _queueMBean = (AMQQueueMBean) _queue.getManagedObject(); - _queueMBean.setMaximumMessageCount(9999l); // Set a high value, because this is not being tested - _queueMBean.setMaximumQueueDepth(MAX_QUEUE_DEPTH); - - // Send messages(no of message to be little more than what can cause a Queue_Depth alert) - int messageCount = Math.round(MAX_QUEUE_DEPTH / MAX_MESSAGE_SIZE) + 10; - long totalSize = (messageCount * MAX_MESSAGE_SIZE) >> 10; - sendMessages(messageCount, MAX_MESSAGE_SIZE); - - // Check queueDepth. There should be no messages on the queue and as the subscriber is listening - // so there should be no Queue_Deoth alert raised - assertEquals(new Long(0), new Long(_queueMBean.getQueueDepth())); - Notification lastNotification = _queueMBean.getLastNotification(); - assertNull(lastNotification); - - // Kill the subscriber and check for the queue depth values. - // Messages are unacknowledged, so those should get requeued. All messages should be on the Queue - _queue.unregisterProtocolSession(protocolSession, channel.getChannelId(), new AMQShortString("consumer_tag")); - channel.requeue(); - - assertEquals(new Long(totalSize), new Long(_queueMBean.getQueueDepth())); - - lastNotification = _queueMBean.getLastNotification(); - assertNotNull(lastNotification); - String notificationMsg = lastNotification.getMessage(); - assertTrue(notificationMsg.startsWith(NotificationCheck.QUEUE_DEPTH_ALERT.name())); - - // Connect a consumer again and check QueueDepth values. The queue should get emptied. - // Messages will get delivered but still are unacknowledged. - _queue.registerProtocolSession(protocolSession, channel.getChannelId(), - new AMQShortString("consumer_tag"), true, null, false, false); - _queue.deliverAsync(); - while (_queue.getMessageCount() != 0) - { - Thread.sleep(100); - } - assertEquals(new Long(0), new Long(_queueMBean.getQueueDepth())); - - // Kill the subscriber again. Now those messages should get requeued again. Check if the queue depth - // value is correct. - _queue.unregisterProtocolSession(protocolSession, channel.getChannelId(), new AMQShortString("consumer_tag")); - channel.requeue(); - - assertEquals(new Long(totalSize), new Long(_queueMBean.getQueueDepth())); - protocolSession.closeSession(); - - // Check the clear queue - _queueMBean.clearQueue(); - assertEquals(new Long(0), new Long(_queueMBean.getQueueDepth())); - } - - protected AMQMessage message(final boolean immediate, long size) throws AMQException - { - MessagePublishInfo publish = new MessagePublishInfo() - { - - public AMQShortString getExchange() - { - return null; - } - - public boolean isImmediate() - { - return immediate; - } - - public boolean isMandatory() - { - return false; - } - - public AMQShortString getRoutingKey() - { - return null; - } - }; - - ContentHeaderBody contentHeaderBody = new ContentHeaderBody(); - contentHeaderBody.bodySize = size; // in bytes - AMQMessage message = new AMQMessage(_messageStore.getNewMessageId(), publish, _transactionalContext); - message.setContentHeaderBody(contentHeaderBody); - message.setPublisher(protocolSession); - return message; - } - - @Override - protected void setUp() throws Exception - { - super.setUp(); - IApplicationRegistry applicationRegistry = ApplicationRegistry.getInstance(); - _virtualHost = applicationRegistry.getVirtualHostRegistry().getVirtualHost("test"); - } - - private void sendMessages(long messageCount, long size) throws AMQException - { - AMQMessage[] messages = new AMQMessage[(int) messageCount]; - for (int i = 0; i < messages.length; i++) - { - messages[i] = message(false, size); - messages[i].enqueue(_queue); - messages[i].routingComplete(_messageStore, _storeContext, new MessageHandleFactory()); - } - - for (int i = 0; i < messageCount; i++) - { - _queue.process(_storeContext, messages[i], false); - } - } - - private AMQQueue getNewQueue() throws AMQException - { - return new AMQQueue(new AMQShortString("testQueue" + Math.random()), - false, - new AMQShortString("AMQueueAlertTest"), - false, - _virtualHost); - } -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueMBeanTest.java b/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueMBeanTest.java deleted file mode 100644 index 32dba5e15d..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueMBeanTest.java +++ /dev/null @@ -1,245 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.queue; - -import junit.framework.TestCase; -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.abstraction.MessagePublishInfo; -import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.RequiredDeliveryException; -import org.apache.qpid.server.protocol.TestMinaProtocolSession; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.registry.IApplicationRegistry; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.txn.TransactionalContext; -import org.apache.qpid.server.txn.NonTransactionalContext; -import org.apache.qpid.server.txn.TransactionManager; -import org.apache.qpid.server.txn.MemoryTransactionManager; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.StoreContext; -import org.apache.qpid.server.store.MemoryMessageStore; - -import javax.management.JMException; -import java.util.LinkedList; -import java.util.HashSet; - -/** - * Test class to test AMQQueueMBean attribtues and operations - */ -public class AMQQueueMBeanTest extends TestCase -{ - private static long MESSAGE_SIZE = 1000; - private AMQQueue _queue; - private AMQQueueMBean _queueMBean; - private MessageStore _messageStore = new MemoryMessageStore(); - private TransactionManager _txm = new MemoryTransactionManager(); - private StoreContext _storeContext = new StoreContext(); - private TransactionalContext _transactionalContext = new NonTransactionalContext(_messageStore, _storeContext, - null, - new LinkedList<RequiredDeliveryException>(), - new HashSet<Long>()); - private VirtualHost _virtualHost; - - public void testMessageCount() throws Exception - { - int messageCount = 10; - sendMessages(messageCount); - assertTrue(_queueMBean.getMessageCount() == messageCount); - assertTrue(_queueMBean.getReceivedMessageCount() == messageCount); - long queueDepth = (messageCount * MESSAGE_SIZE) >> 10; - assertTrue(_queueMBean.getQueueDepth() == queueDepth); - - _queueMBean.deleteMessageFromTop(); - assertTrue(_queueMBean.getMessageCount() == (messageCount - 1)); - assertTrue(_queueMBean.getReceivedMessageCount() == messageCount); - - _queueMBean.clearQueue(); - assertTrue(_queueMBean.getMessageCount() == 0); - assertTrue(_queueMBean.getReceivedMessageCount() == messageCount); - } - - public void testConsumerCount() throws AMQException - { - SubscriptionManager mgr = _queue.getSubscribers(); - assertFalse(mgr.hasActiveSubscribers()); - assertTrue(_queueMBean.getActiveConsumerCount() == 0); - - - TestMinaProtocolSession protocolSession = new TestMinaProtocolSession(); - AMQChannel channel = new AMQChannel(protocolSession, 1,_txm, _messageStore, null); - protocolSession.addChannel(channel); - - _queue.registerProtocolSession(protocolSession, 1, new AMQShortString("test"), false, null,false,false); - assertTrue(_queueMBean.getActiveConsumerCount() == 1); - - SubscriptionSet _subscribers = (SubscriptionSet) mgr; - SubscriptionFactory subscriptionFactory = new SubscriptionImpl.Factory(); - Subscription s1 = subscriptionFactory.createSubscription(channel.getChannelId(), - protocolSession, - new AMQShortString("S1"), - false, - null, - true, - _queue); - - Subscription s2 = subscriptionFactory.createSubscription(channel.getChannelId(), - protocolSession, - new AMQShortString("S2"), - false, - null, - true, - _queue); - _subscribers.addSubscriber(s1); - _subscribers.addSubscriber(s2); - assertTrue(_queueMBean.getActiveConsumerCount() == 3); - assertTrue(_queueMBean.getConsumerCount() == 3); - - s1.close(); - assertTrue(_queueMBean.getActiveConsumerCount() == 2); - assertTrue(_queueMBean.getConsumerCount() == 3); - } - - public void testGeneralProperties() - { - long maxQueueDepth = 1000; // in bytes - _queueMBean.setMaximumMessageCount(50000l); - _queueMBean.setMaximumMessageSize(2000l); - _queueMBean.setMaximumQueueDepth(maxQueueDepth); - - assertTrue(_queueMBean.getMaximumMessageCount() == 50000); - assertTrue(_queueMBean.getMaximumMessageSize() == 2000); - assertTrue(_queueMBean.getMaximumQueueDepth() == (maxQueueDepth >> 10)); - - assertTrue(_queueMBean.getName().equals("testQueue")); - assertTrue(_queueMBean.getOwner().equals("AMQueueMBeanTest")); - assertFalse(_queueMBean.isAutoDelete()); - assertFalse(_queueMBean.isDurable()); - } - - public void testExceptions() throws Exception - { - try - { - _queueMBean.viewMessages(0, 3); - fail(); - } - catch (JMException ex) - { - - } - - try - { - _queueMBean.viewMessages(2, 1); - fail(); - } - catch (JMException ex) - { - - } - - try - { - _queueMBean.viewMessages(-1, 1); - fail(); - } - catch (JMException ex) - { - - } - - AMQMessage msg = message(false); - long id = msg.getMessageId(); - _queue.clearQueue(_storeContext); - - msg.enqueue(_queue); - msg.routingComplete(_messageStore, _storeContext, new MessageHandleFactory()); - _queue.process(_storeContext, msg, false); - _queueMBean.viewMessageContent(id); - try - { - _queueMBean.viewMessageContent(id + 1); - fail(); - } - catch (JMException ex) - { - - } - } - - private AMQMessage message(final boolean immediate) throws AMQException - { - MessagePublishInfo publish = new MessagePublishInfo() - { - - public AMQShortString getExchange() - { - return null; - } - - public boolean isImmediate() - { - return immediate; - } - - public boolean isMandatory() - { - return false; - } - - public AMQShortString getRoutingKey() - { - return null; - } - }; - - ContentHeaderBody contentHeaderBody = new ContentHeaderBody(); - contentHeaderBody.bodySize = MESSAGE_SIZE; // in bytes - return new AMQMessage(_messageStore.getNewMessageId(), publish, _transactionalContext, contentHeaderBody); - } - - @Override - protected void setUp() throws Exception - { - super.setUp(); - IApplicationRegistry applicationRegistry = ApplicationRegistry.getInstance(); - _virtualHost = applicationRegistry.getVirtualHostRegistry().getVirtualHost("test"); - _queue = new AMQQueue(new AMQShortString("testQueue"), false, new AMQShortString("AMQueueMBeanTest"), false, _virtualHost); - _queueMBean = new AMQQueueMBean(_queue); - } - - private void sendMessages(int messageCount) throws AMQException - { - AMQMessage[] messages = new AMQMessage[messageCount]; - for (int i = 0; i < messages.length; i++) - { - messages[i] = message(false); - messages[i].enqueue(_queue); - messages[i].routingComplete(_messageStore, _storeContext, new MessageHandleFactory()); - } - for (int i = 0; i < messageCount; i++) - { - _queue.process(_storeContext, messages[i], false); - } - } -} diff --git a/java/broker/src/test/java/org/apache/qpid/server/util/LoggingProxyTest.java b/java/broker/src/test/java/org/apache/qpid/server/util/LoggingProxyTest.java deleted file mode 100644 index c7db51016e..0000000000 --- a/java/broker/src/test/java/org/apache/qpid/server/util/LoggingProxyTest.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.util; - -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - -import junit.framework.TestCase; - -public class LoggingProxyTest extends TestCase -{ - static interface IFoo { - void foo(); - void foo(int i, Collection c); - String bar(); - String bar(String s, List l); - } - - static class Foo implements IFoo { - public void foo() - { - } - - public void foo(int i, Collection c) - { - } - - public String bar() - { - return null; - } - - public String bar(String s, List l) - { - return "ha"; - } - } - - public void testSimple() { - LoggingProxy proxy = new LoggingProxy(new Foo(), 20); - IFoo foo = (IFoo)proxy.getProxy(IFoo.class); - foo.foo(); - assertEquals(2, proxy.getBufferSize()); - assertTrue(proxy.getBuffer().get(0).toString().matches(".*: foo\\(\\) entered$")); - assertTrue(proxy.getBuffer().get(1).toString().matches(".*: foo\\(\\) returned$")); - - foo.foo(3, Arrays.asList(0, 1, 2)); - assertEquals(4, proxy.getBufferSize()); - assertTrue(proxy.getBuffer().get(2).toString().matches(".*: foo\\(\\[3, \\[0, 1, 2\\]\\]\\) entered$")); - assertTrue(proxy.getBuffer().get(3).toString().matches(".*: foo\\(\\) returned$")); - - foo.bar(); - assertEquals(6, proxy.getBufferSize()); - assertTrue(proxy.getBuffer().get(4).toString().matches(".*: bar\\(\\) entered$")); - assertTrue(proxy.getBuffer().get(5).toString().matches(".*: bar\\(\\) returned null$")); - - foo.bar("hello", Arrays.asList(1, 2, 3)); - assertEquals(8, proxy.getBufferSize()); - assertTrue(proxy.getBuffer().get(6).toString().matches(".*: bar\\(\\[hello, \\[1, 2, 3\\]\\]\\) entered$")); - assertTrue(proxy.getBuffer().get(7).toString().matches(".*: bar\\(\\) returned ha$")); - - proxy.dump(); - } - - public static junit.framework.Test suite() - { - return new junit.framework.TestSuite(LoggingProxyTest.class); - } -} diff --git a/java/integrationtests/README.txt b/java/integrationtests/README.txt deleted file mode 100644 index 00a21883a9..0000000000 --- a/java/integrationtests/README.txt +++ /dev/null @@ -1,13 +0,0 @@ -This module contains integration tests, for testing a java client againt *any* broker
-implementation or against other clients. These tests must not rely on starting the
-Java broker in-vm but must depend on a broker being started independantly before running
-the tests in this module. By default tests in this module will expect the broker to be
-started on localhost on the default port, but this can be overridden by passing in a
-sys property to maven. Interop tests are in this module. Java broker specific tests that
-use an in-vm broker should go in the systests module.
-
-Don't set the tests in this module to run by default as part of the maven build, until
-there is a script to start and stop the broker; needed to fully automate these tests.
-Interop tests will always be run using a seperate script (not from maven) but it might
-be worthwile to script into the maven build starting of the Java broker, and running
-these tests against it.
\ No newline at end of file diff --git a/java/integrationtests/build.xml b/java/integrationtests/build.xml deleted file mode 100644 index c37dd4a893..0000000000 --- a/java/integrationtests/build.xml +++ /dev/null @@ -1,28 +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. - - - --> -<project name="Integration Tests" default="build"> - - <property name="module.depends" value="systests client common"/> - <property name="module.dist" value="false"/> - - <import file="../module.xml"/> - -</project> diff --git a/java/integrationtests/docs/RunningSustainedTests.txt b/java/integrationtests/docs/RunningSustainedTests.txt deleted file mode 100644 index 2b37f4c5a7..0000000000 --- a/java/integrationtests/docs/RunningSustainedTests.txt +++ /dev/null @@ -1,15 +0,0 @@ -In addition to the integration tests the framework provided by this package also allows for -sustained tests to be run. Currently avaible tests: -- org.apache.qpid.sustained.SustainedTestClient : Pub Sub test to determine steady state throughput. - - -Running Tests. - -Run the tests as per the integration tests. - - Start a broker - - Start at least one Client [java org.apache.qpid.sustained.TestClient], ensuring unique naming - - Start Test Controller [java org.apache.qpid.sustained.TestCoordinator] - - Additional Test clients can be started: - [java org.apache.qpid.sustained.TestClient -j org.apache.qpid.sustained.SustainedTestClient] - - diff --git a/java/integrationtests/jar-with-dependencies.xml b/java/integrationtests/jar-with-dependencies.xml deleted file mode 100644 index 3e95e7ab22..0000000000 --- a/java/integrationtests/jar-with-dependencies.xml +++ /dev/null @@ -1,47 +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 is an assembly descriptor that produces a jar file that contains all the
- dependencies, fully expanded into a single jar, required to run the tests of
- a maven project.
- -->
-<assembly>
- <id>all-test-deps</id>
- <formats>
- <format>jar</format>
- </formats>
- <includeBaseDirectory>false</includeBaseDirectory>
- <dependencySets>
- <dependencySet>
- <outputDirectory></outputDirectory>
- <outputFileNameMapping></outputFileNameMapping>
- <unpack>true</unpack>
- <scope>test</scope>
- </dependencySet>
- </dependencySets>
- <fileSets>
- <fileSet>
- <directory>target/classes</directory>
- <outputDirectory></outputDirectory>
- </fileSet>
- <fileSet>
- <directory>target/test-classes</directory>
- <outputDirectory></outputDirectory>
- </fileSet>
- </fileSets>
-</assembly>
diff --git a/java/integrationtests/pom.xml b/java/integrationtests/pom.xml deleted file mode 100644 index 78a05e4f28..0000000000 --- a/java/integrationtests/pom.xml +++ /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.
- -->
-<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>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid-integrationtests</artifactId>
- <packaging>jar</packaging>
- <version>1.0-incubating-M3-SNAPSHOT</version>
- <name>Qpid Integration Tests</name>
-
- <parent>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid</artifactId>
- <version>1.0-incubating-M3-SNAPSHOT</version>
- <relativePath>../pom.xml</relativePath>
- </parent>
-
- <properties>
- <topDirectoryLocation>..</topDirectoryLocation>
- </properties>
-
- <dependencies>
-
- <dependency>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid-client</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid-systests</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
- <version>1.4.0</version>
- </dependency>
-
- <dependency>
- <groupId>uk.co.thebadgerset</groupId>
- <artifactId>junit-toolkit</artifactId>
- <version>0.6-SNAPSHOT</version>
- <scope>compile</scope>
- </dependency>
-
- <!-- JUnit is a compile and runtime dependancy for these tests, not just a test time dependency. -->
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>compile</scope>
- </dependency>
-
- <!-- These need to be included at compile time only, for the retrotranslator verification to find them. -->
- <dependency>
- <groupId>net.sf.retrotranslator</groupId>
- <artifactId>retrotranslator-runtime</artifactId>
- <scope>provided</scope>
- </dependency>
-
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- </plugin>
-
- <!-- Backports the module to Java 1.4. This is done during the packaging phase as a transformation of the Jar. -->
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>retrotranslator-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>retro-intergration-tests</id>
- <phase>package</phase>
- <goals>
- <goal>translate-project</goal>
- </goals>
- <configuration>
- <!--<destdir>${project.build.directory}/retro-classes</destdir>-->
- <destjar>${project.build.directory}/${project.build.finalName}-java14.jar</destjar>
- <verify>${retrotranslator.verify}</verify>
- <verifyClasspath>
- <element>${retrotranslator.1.4-rt-path}</element>
- <element>${retrotranslator.1.4-jce-path}</element>
- <element>${retrotranslator.1.4-jsse-path}</element>
- <element>${retrotranslator.1.4-sasl-path}</element>
- </verifyClasspath>
- <failonwarning>false</failonwarning>
- <classifier>java14</classifier>
- <attach>true</attach>
- </configuration>
- </execution>
- </executions>
- </plugin>
-
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-assembly-plugin</artifactId>
- <version>2.2-SNAPSHOT</version>
- <configuration>
- <descriptors>
- <descriptor>jar-with-dependencies.xml</descriptor>
- </descriptors>
- <outputDirectory>target</outputDirectory>
- <workDirectory>target/assembly/work</workDirectory>
- </configuration>
- </plugin>
-
- </plugins>
-
- <resources>
- <!-- Ensure all resources defined in the resources directory are copied into the build jar. -->
- <resource>
- <targetPath></targetPath>
- <filtering>false</filtering>
- <directory>src/resources</directory>
- <includes>
- <include>**/*</include>
- </includes>
- </resource>
- </resources>
-
- </build>
-
-</project>
diff --git a/java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase1DummyRun.java b/java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase1DummyRun.java deleted file mode 100644 index db17c7aacc..0000000000 --- a/java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase1DummyRun.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.interop.clienttestcases; - -import org.apache.log4j.Logger; - -import org.apache.qpid.test.framework.distributedtesting.TestClientControlledTest; - -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.Session; - -/** - * Implements tet case 1, dummy run. This test case sends no test messages, it exists to confirm that the test harness - * is interacting with the coordinator correctly. - * - * <p><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Supply the name of the test case that this implements. - * <tr><td> Accept/Reject invites based on test parameters. - * <tr><td> Adapt to assigned roles. - * <tr><td> Perform test case actions. - * <tr><td> Generate test reports. - * </table> - */ -public class TestCase1DummyRun implements TestClientControlledTest -{ - /** Used for debugging. */ - private static final Logger log = Logger.getLogger(TestCase1DummyRun.class); - - /** - * Should provide the name of the test case that this class implements. The exact names are defined in the - * interop testing spec. - * - * @return The name of the test case that this implements. - */ - public String getName() - { - log.debug("public String getName(): called"); - - return "TC1_DummyRun"; - } - - /** - * Determines whether the test invite that matched this test case is acceptable. - * - * @param inviteMessage The invitation to accept or reject. - * - * @return <tt>true</tt> to accept the invitation, <tt>false</tt> to reject it. - * - * @throws JMSException Any JMSException resulting from reading the message are allowed to fall through. - */ - public boolean acceptInvite(Message inviteMessage) throws JMSException - { - log.debug("public boolean acceptInvite(Message inviteMessage): called"); - - // Test parameters don't matter, accept all invites. - return true; - } - - /** - * Assigns the role to be played by this test case. The test parameters are fully specified in the - * assignment message. When this method return the test case will be ready to execute. - * - * @param role The role to be played; sender or receivers. - * @param assignRoleMessage The role assingment message, contains the full test parameters. - * - * @throws JMSException Any JMSException resulting from reading the message are allowed to fall through. - */ - public void assignRole(Roles role, Message assignRoleMessage) throws JMSException - { - log.debug("public void assignRole(Roles role, Message assignRoleMessage): called"); - - // Do nothing, both roles are the same. - } - - /** - * Performs the test case actions. Returning from here, indicates that the sending role has completed its test. - * - * @param numMessages The number of test messages to send. - */ - public void start(int numMessages) - { - log.debug("public void start(): called"); - - // Do nothing. - } - - /** - * Gets a report on the actions performed by the test case in its assigned role. - * - * @param session The controlSession to create the report message in. - * - * @return The report message. - * - * @throws JMSException Any JMSExceptions resulting from creating the report are allowed to fall through. - */ - public Message getReport(Session session) throws JMSException - { - log.debug("public Message getReport(Session controlSession): called"); - - // Generate a dummy report, the coordinator expects a report but doesn't care what it is. - return session.createTextMessage("Dummy Run, Ok."); - } - - /** - * Handles incoming test messages. Does nothing. - * - * @param message The incoming test message. - */ - public void onMessage(Message message) - { - log.debug("public void onMessage(Message message = " + message + "): called"); - - // Ignore any messages. - } -} diff --git a/java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase2BasicP2P.java b/java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase2BasicP2P.java deleted file mode 100644 index 36d3cce7f7..0000000000 --- a/java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase2BasicP2P.java +++ /dev/null @@ -1,209 +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.interop.clienttestcases; - -import org.apache.log4j.Logger; - -import org.apache.qpid.test.framework.TestUtils; -import org.apache.qpid.test.framework.distributedtesting.TestClient; -import org.apache.qpid.test.framework.distributedtesting.TestClientControlledTest; - -import javax.jms.*; - -/** - * Implements test case 2, basic P2P. Sends/received a specified number of messages to a specified route on the - * default direct exchange. Produces reports on the actual number of messages sent/received. - * - * <p><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Supply the name of the test case that this implements. - * <tr><td> Accept/Reject invites based on test parameters. - * <tr><td> Adapt to assigned roles. - * <tr><td> Send required number of test messages. - * <tr><td> Generate test reports. - * </table> - */ -public class TestCase2BasicP2P implements TestClientControlledTest, MessageListener -{ - /** Used for debugging. */ - private static final Logger log = Logger.getLogger(TestCase2BasicP2P.class); - - /** Holds the count of test messages received. */ - private int messageCount; - - /** The role to be played by the test. */ - private Roles role; - - /** The number of test messages to send. */ - private int numMessages; - - /** The connection to send the test messages on. */ - private Connection connection; - - /** The controlSession to send the test messages on. */ - private Session session; - - /** The producer to send the test messages with. */ - MessageProducer producer; - - /** - * Should provide the name of the test case that this class implements. The exact names are defined in the - * interop testing spec. - * - * @return The name of the test case that this implements. - */ - public String getName() - { - log.debug("public String getName(): called"); - - return "TC2_BasicP2P"; - } - - /** - * Determines whether the test invite that matched this test case is acceptable. - * - * @param inviteMessage The invitation to accept or reject. - * - * @return <tt>true</tt> to accept the invitation, <tt>false</tt> to reject it. - * - * @throws JMSException Any JMSException resulting from reading the message are allowed to fall through. - */ - public boolean acceptInvite(Message inviteMessage) throws JMSException - { - log.debug("public boolean acceptInvite(Message inviteMessage = " + inviteMessage + "): called"); - - // All invites are acceptable. - return true; - } - - /** - * Assigns the role to be played by this test case. The test parameters are fully specified in the - * assignment message. When this method return the test case will be ready to execute. - * - * @param role The role to be played; sender or receivers. - * - * @param assignRoleMessage The role assingment message, contains the full test parameters. - * - * @throws JMSException Any JMSException resulting from reading the message are allowed to fall through. - */ - public void assignRole(Roles role, Message assignRoleMessage) throws JMSException - { - log.debug("public void assignRole(Roles role = " + role + ", Message assignRoleMessage = " + assignRoleMessage - + "): called"); - - // Reset the message count for a new test. - messageCount = 0; - - // Take note of the role to be played. - this.role = role; - - // Create a new connection to pass the test messages on. - connection = TestUtils.createConnection(TestClient.testContextProperties); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - // Extract and retain the test parameters. - numMessages = assignRoleMessage.getIntProperty("P2P_NUM_MESSAGES"); - Destination sendDestination = session.createQueue(assignRoleMessage.getStringProperty("P2P_QUEUE_AND_KEY_NAME")); - - log.debug("numMessages = " + numMessages); - log.debug("sendDestination = " + sendDestination); - log.debug("role = " + role); - - switch (role) - { - // Check if the sender role is being assigned, and set up a message producer if so. - case SENDER: - producer = session.createProducer(sendDestination); - break; - - // Otherwise the receivers role is being assigned, so set this up to listen for messages. - case RECEIVER: - MessageConsumer consumer = session.createConsumer(sendDestination); - consumer.setMessageListener(this); - break; - } - - connection.start(); - } - - /** - * Performs the test case actions. Returning from here, indicates that the sending role has completed its test. - * - * @param numMessages The number of test messages to send. - * - * @throws JMSException Any JMSException resulting from reading the message are allowed to fall through. - */ - public void start(int numMessages) throws JMSException - { - log.debug("public void start(): called"); - - // Check that the sender role is being performed. - if (role.equals(Roles.SENDER)) - { - Message testMessage = session.createTextMessage("test"); - - for (int i = 0; i < this.numMessages; i++) - { - producer.send(testMessage); - - // Increment the message count. - messageCount++; - } - } - } - - /** - * Gets a report on the actions performed by the test case in its assigned role. - * - * @param session The controlSession to create the report message in. - * - * @return The report message. - * - * @throws JMSException Any JMSExceptions resulting from creating the report are allowed to fall through. - */ - public Message getReport(Session session) throws JMSException - { - log.debug("public Message getReport(Session controlSession): called"); - - // Close the test connection. - connection.close(); - - // Generate a report message containing the count of the number of messages passed. - Message report = session.createMessage(); - report.setStringProperty("CONTROL_TYPE", "REPORT"); - report.setIntProperty("MESSAGE_COUNT", messageCount); - - return report; - } - - /** - * Counts incoming test messages. - * - * @param message The incoming test message. - */ - public void onMessage(Message message) - { - log.debug("public void onMessage(Message message = " + message + "): called"); - - // Increment the message count. - messageCount++; - } -} diff --git a/java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase3BasicPubSub.java b/java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase3BasicPubSub.java deleted file mode 100644 index 205472716b..0000000000 --- a/java/integrationtests/src/main/java/org/apache/qpid/interop/clienttestcases/TestCase3BasicPubSub.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.interop.clienttestcases; - -import org.apache.log4j.Logger; - -import org.apache.qpid.test.framework.TestUtils; -import org.apache.qpid.test.framework.distributedtesting.TestClient; -import org.apache.qpid.test.framework.distributedtesting.TestClientControlledTest; - -import javax.jms.*; - -/** - * Implements test case 3, basic pub/sub. Sends/received a specified number of messages to a specified route on the - * default topic exchange, using the specified number of receivers connections. Produces reports on the actual number of - * messages sent/received. - * - * <p><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Supply the name of the test case that this implements. - * <tr><td> Accept/Reject invites based on test parameters. - * <tr><td> Adapt to assigned roles. - * <tr><td> Send required number of test messages using pub/sub. - * <tr><td> Generate test reports. - * </table> - */ -public class TestCase3BasicPubSub implements TestClientControlledTest, MessageListener -{ - /** Used for debugging. */ - private static final Logger log = Logger.getLogger(TestCase3BasicPubSub.class); - - /** Holds the count of test messages received. */ - private int messageCount; - - /** The role to be played by the test. */ - private Roles role; - - /** The number of test messages to send. */ - private int numMessages; - - /** The connections to send/receive the test messages on. */ - private Connection[] connection; - - /** The sessions to send/receive the test messages on. */ - private Session[] session; - - /** The producer to send the test messages with. */ - MessageProducer producer; - - /** - * Should provide the name of the test case that this class implements. The exact names are defined in the - * interop testing spec. - * - * @return The name of the test case that this implements. - */ - public String getName() - { - log.debug("public String getName(): called"); - - return "TC3_BasicPubSub"; - } - - /** - * Determines whether the test invite that matched this test case is acceptable. - * - * @param inviteMessage The invitation to accept or reject. - * - * @return <tt>true</tt> to accept the invitation, <tt>false</tt> to reject it. - * - * @throws javax.jms.JMSException Any JMSException resulting from reading the message are allowed to fall through. - */ - public boolean acceptInvite(Message inviteMessage) throws JMSException - { - log.debug("public boolean acceptInvite(Message inviteMessage = " + inviteMessage + "): called"); - - // All invites are acceptable. - return true; - } - - /** - * Assigns the role to be played by this test case. The test parameters are fully specified in the - * assignment message. When this method return the test case will be ready to execute. - * - * @param role The role to be played; sender or receivers. - * - * @param assignRoleMessage The role assingment message, contains the full test parameters. - * - * @throws JMSException Any JMSException resulting from reading the message are allowed to fall through. - */ - public void assignRole(Roles role, Message assignRoleMessage) throws JMSException - { - log.debug("public void assignRole(Roles role = " + role + ", Message assignRoleMessage = " + assignRoleMessage - + "): called"); - - // Reset the message count for a new test. - messageCount = 0; - - // Take note of the role to be played. - this.role = role; - - // Extract and retain the test parameters. - numMessages = assignRoleMessage.getIntProperty("PUBSUB_NUM_MESSAGES"); - int numReceivers = assignRoleMessage.getIntProperty("PUBSUB_NUM_RECEIVERS"); - String sendKey = assignRoleMessage.getStringProperty("PUBSUB_KEY"); - - log.debug("numMessages = " + numMessages); - log.debug("numReceivers = " + numReceivers); - log.debug("sendKey = " + sendKey); - log.debug("role = " + role); - - switch (role) - { - // Check if the sender role is being assigned, and set up a single message producer if so. - case SENDER: - // Create a new connection to pass the test messages on. - connection = new Connection[1]; - session = new Session[1]; - - connection[0] = TestUtils.createConnection(TestClient.testContextProperties); - session[0] = connection[0].createSession(false, Session.AUTO_ACKNOWLEDGE); - - // Extract and retain the test parameters. - Destination sendDestination = session[0].createTopic(sendKey); - - producer = session[0].createProducer(sendDestination); - break; - - // Otherwise the receivers role is being assigned, so set this up to listen for messages on the required number - // of receivers connections. - case RECEIVER: - // Create the required number of receivers connections. - connection = new Connection[numReceivers]; - session = new Session[numReceivers]; - - for (int i = 0; i < numReceivers; i++) - { - connection[i] = TestUtils.createConnection(TestClient.testContextProperties); - session[i] = connection[i].createSession(false, Session.AUTO_ACKNOWLEDGE); - - sendDestination = session[i].createTopic(sendKey); - - MessageConsumer consumer = session[i].createConsumer(sendDestination); - consumer.setMessageListener(this); - } - - break; - } - - // Start all the connection dispatcher threads running. - for (Connection conn : connection) - { - conn.start(); - } - } - - /** - * Performs the test case actions. Returning from here, indicates that the sending role has completed its test. - * - * @param numMessages The number of test messages to send. - * - * @throws JMSException Any JMSException resulting from reading the message are allowed to fall through. - */ - public void start(int numMessages) throws JMSException - { - log.debug("public void start(): called"); - - // Check that the sender role is being performed. - if (role.equals(Roles.SENDER)) - { - Message testMessage = session[0].createTextMessage("test"); - - for (int i = 0; i < this.numMessages; i++) - { - producer.send(testMessage); - - // Increment the message count. - messageCount++; - } - } - } - - /** - * Gets a report on the actions performed by the test case in its assigned role. - * - * @param session The controlSession to create the report message in. - * - * @return The report message. - * - * @throws JMSException Any JMSExceptions resulting from creating the report are allowed to fall through. - */ - public Message getReport(Session session) throws JMSException - { - log.debug("public Message getReport(Session controlSession): called"); - - // Close the test connections. - for (Connection conn : connection) - { - conn.close(); - } - - // Generate a report message containing the count of the number of messages passed. - Message report = session.createMessage(); - report.setStringProperty("CONTROL_TYPE", "REPORT"); - report.setIntProperty("MESSAGE_COUNT", messageCount); - - return report; - } - - /** - * Counts incoming test messages. - * - * @param message The incoming test message. - */ - public void onMessage(Message message) - { - log.debug("public void onMessage(Message message = " + message + "): called"); - - // Increment the message count. - messageCount++; - } -} diff --git a/java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase1DummyRun.java b/java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase1DummyRun.java deleted file mode 100644 index a2e4a00aa6..0000000000 --- a/java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase1DummyRun.java +++ /dev/null @@ -1,84 +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.interop.testcases; - -import org.apache.log4j.Logger; - -import org.apache.qpid.test.framework.FrameworkBaseCase; - -import java.util.Properties; - -/** - * Coordinates test case 1, from the interop test specification. This test connects up the sender and receivers roles, - * and gets some dummy test reports from them, in order to check that the test framework itself is operational. - * - * <p><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Exercises the interop testing framework without actually sending any test messages. - * <td> {@link FrameworkBaseCase} - * </table> - */ -public class InteropTestCase1DummyRun extends FrameworkBaseCase -{ - /** Used for debugging. */ - private static final Logger log = Logger.getLogger(InteropTestCase1DummyRun.class); - - /** - * Creates a new coordinating test case with the specified name. - * - * @param name The test case name. - */ - public InteropTestCase1DummyRun(String name) - { - super(name); - } - - /** - * Performs the basic P2P test case, "Test Case 2" in the specification. - * - * @throws Exception Any exceptions are allowed to fall through and fail the test. - */ - public void testDummyRun() throws Exception - { - log.debug("public void testDummyRun(): called"); - - Properties testConfig = new Properties(); - testConfig.put("TEST_NAME", "TC1_DummyRun"); - - /*Message[] reports =*/ getCircuitFactory().sequenceTest(null, null, testConfig); - - // Compare sender and receivers reports. - // Assert.assertEquals("Expected to get 2 dummy reports.", 2, reports.length); - } - - /** - * Should provide a translation from the junit method name of a test to its test case name as defined in the - * interop testing specification. For example the method "testP2P" might map onto the interop test case name - * "TC2_BasicP2P". - * - * @param methodName The name of the JUnit test method. - * @return The name of the corresponding interop test case. - */ - public String getTestCaseNameForTestMethod(String methodName) - { - return "TC1_DummyRun"; - } -} diff --git a/java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase2BasicP2P.java b/java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase2BasicP2P.java deleted file mode 100644 index 6d6515f1fd..0000000000 --- a/java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase2BasicP2P.java +++ /dev/null @@ -1,90 +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.interop.testcases; - -import org.apache.log4j.Logger; - -import org.apache.qpid.test.framework.FrameworkBaseCase; - -import java.util.Properties; - -/** - * Implements test case 2, from the interop test specification. This test sets up the TC2_BasicP2P test for 50 - * messages. It checks that the sender and receivers reports both indicate that all the test messages were transmitted - * successfully. - * - * <p><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Setup p2p test parameters and compare with test output. <td> {@link FrameworkBaseCase} - * </table> - */ -public class InteropTestCase2BasicP2P extends FrameworkBaseCase -{ - /** Used for debugging. */ - private static final Logger log = Logger.getLogger(InteropTestCase2BasicP2P.class); - - /** - * Creates a new coordinating test case with the specified name. - * - * @param name The test case name. - */ - public InteropTestCase2BasicP2P(String name) - { - super(name); - } - - /** - * Performs the basic P2P test case, "Test Case 2" in the specification. - * - * @throws Exception Any exceptions are allowed to fall through and fail the test. - */ - public void testBasicP2P() throws Exception - { - log.debug("public void testBasicP2P(): called"); - - Properties testConfig = new Properties(); - testConfig.setProperty("TEST_NAME", "TC2_BasicP2P"); - testConfig.setProperty("P2P_QUEUE_AND_KEY_NAME", "tc2queue"); - testConfig.put("P2P_NUM_MESSAGES", 50); - - /*Message[] reports =*/ getCircuitFactory().sequenceTest(null, null, testConfig); - - // Compare sender and receivers reports. - /*int messagesSent = reports[0].getIntProperty("MESSAGE_COUNT"); - int messagesReceived = reports[1].getIntProperty("MESSAGE_COUNT"); - - Assert.assertEquals("The requested number of messages were not sent.", 50, messagesSent); - Assert.assertEquals("Sender and receivers messages sent did not match up.", messagesSent, messagesReceived);*/ - } - - /** - * Should provide a translation from the junit method name of a test to its test case name as defined in the - * interop testing specification. For example the method "testP2P" might map onto the interop test case name - * "TC2_BasicP2P". - * - * @param methodName The name of the JUnit test method. - * @return The name of the corresponding interop test case. - */ - public String getTestCaseNameForTestMethod(String methodName) - { - return "TC2_BasicP2P"; - } -} diff --git a/java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase3BasicPubSub.java b/java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase3BasicPubSub.java deleted file mode 100644 index 2faca91e73..0000000000 --- a/java/integrationtests/src/main/java/org/apache/qpid/interop/testcases/InteropTestCase3BasicPubSub.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.interop.testcases; - -import org.apache.log4j.Logger; - -import org.apache.qpid.test.framework.FrameworkBaseCase; - -import java.util.Properties; - -/** - * <p><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Setup pub/sub test parameters and compare with test output. <td> {@link FrameworkBaseCase} - * </table> - */ -public class InteropTestCase3BasicPubSub extends FrameworkBaseCase -{ - /** Used for debugging. */ - private static final Logger log = Logger.getLogger(InteropTestCase3BasicPubSub.class); - - /** - * Creates a new coordinating test case with the specified name. - * - * @param name The test case name. - */ - public InteropTestCase3BasicPubSub(String name) - { - super(name); - } - - /** - * Performs the basic P2P test case, "Test Case 2" in the specification. - * - * @throws Exception Any exceptions are allowed to fall through and fail the test. - */ - public void testBasicPubSub() throws Exception - { - log.debug("public void testBasicPubSub(): called"); - - Properties testConfig = new Properties(); - testConfig.put("TEST_NAME", "TC3_BasicPubSub"); - testConfig.put("PUBSUB_KEY", "tc3route"); - testConfig.put("PUBSUB_NUM_MESSAGES", 10); - testConfig.put("PUBSUB_NUM_RECEIVERS", 5); - - /*Message[] reports =*/ getCircuitFactory().sequenceTest(null, null, testConfig); - - // Compare sender and receivers reports. - /*int messagesSent = reports[0].getIntProperty("MESSAGE_COUNT"); - int messagesReceived = reports[1].getIntProperty("MESSAGE_COUNT"); - - Assert.assertEquals("The requested number of messages were not sent.", 10, messagesSent); - Assert.assertEquals("Received messages did not match up to num sent * num receivers.", messagesSent * 5, - messagesReceived);*/ - } - - /** - * Should provide a translation from the junit method name of a test to its test case name as defined in the - * interop testing specification. For example the method "testP2P" might map onto the interop test case name - * "TC2_BasicP2P". - * - * @param methodName The name of the JUnit test method. - * @return The name of the corresponding interop test case. - */ - public String getTestCaseNameForTestMethod(String methodName) - { - return "TC3_BasicPubSub"; - } -} diff --git a/java/integrationtests/src/main/java/org/apache/qpid/sustained/SustainedClientTestCase.java b/java/integrationtests/src/main/java/org/apache/qpid/sustained/SustainedClientTestCase.java deleted file mode 100644 index 642f91b772..0000000000 --- a/java/integrationtests/src/main/java/org/apache/qpid/sustained/SustainedClientTestCase.java +++ /dev/null @@ -1,906 +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.sustained; - -import org.apache.log4j.Logger; - -import org.apache.qpid.client.AMQNoConsumersException; -import org.apache.qpid.client.AMQNoRouteException; -import org.apache.qpid.test.framework.distributedtesting.TestClient; -import org.apache.qpid.interop.clienttestcases.TestCase3BasicPubSub; -import org.apache.qpid.test.framework.TestUtils; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.ExceptionListener; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.concurrent.CountDownLatch; - -/** - * Implements test case 3, basic pub/sub. Sends/received a specified number of messages to a specified route on the - * default topic exchange, using the specified number of receivers connections. Produces reports on the actual number of - * messages sent/received. - * - * <p><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Supply the name of the test case that this implements. - * <tr><td> Accept/Reject invites based on test parameters. - * <tr><td> Adapt to assigned roles. - * <tr><td> Send required number of test messages using pub/sub. <tr><td> Generate test reports. - * </table> - */ -public class SustainedClientTestCase extends TestCase3BasicPubSub implements ExceptionListener, MessageListener -{ - /** Used for debugging. */ - private static final Logger log = Logger.getLogger(SustainedClientTestCase.class); - - /** Used to log to the console. */ - private static final Logger console = Logger.getLogger("SustainedTest"); - - /** The role to be played by the test. */ - private Roles role; - - /** The number of receivers connection to use. */ - private int numReceivers; - - /** The routing key to send them to on the default direct exchange. */ - private Destination sendDestination; - - /** The routing key to send updates to on the default direct exchange. */ - private Destination sendUpdateDestination; - - /** The connections to send/receive the test messages on. */ - private Connection[] connection; - - /** The sessions to send/receive the test messages on. */ - private Session[] session; - - /** The producer to send the test messages with. */ - MessageProducer producer; - - /** Adapter that adjusts the send rate based on the updates from clients. */ - SustainedRateAdapter _rateAdapter; - - /** */ - int _batchSize; - - private static final long TEN_MILLI_SEC = 10000000; - private static final int DEBUG_LOG_UPATE_INTERVAL = 10; - private static final int LOG_UPATE_INTERVAL = 10; - private static final boolean SLEEP_PER_MESSAGE = Boolean.getBoolean("sleepPerMessage"); - - /** - * Should provide the name of the test case that this class implements. The exact names are defined in the interop - * testing spec. - * - * @return The name of the test case that this implements. - */ - public String getName() - { - log.debug("public String getName(): called"); - - return "Perf_SustainedPubSub"; - } - - /** - * Assigns the role to be played by this test case. The test parameters are fully specified in the assignment - * message. When this method return the test case will be ready to execute. - * - * @param role The role to be played; sender or receivers. - * @param assignRoleMessage The role assingment message, contains the full test parameters. - * - * @throws JMSException Any JMSException resulting from reading the message are allowed to fall through. - */ - public void assignRole(Roles role, Message assignRoleMessage) throws JMSException - { - log.debug("public void assignRole(Roles role = " + role + ", Message assignRoleMessage = " + assignRoleMessage - + "): called"); - - // Take note of the role to be played. - this.role = role; - - // Extract and retain the test parameters. - numReceivers = assignRoleMessage.getIntProperty("SUSTAINED_NUM_RECEIVERS"); - _batchSize = assignRoleMessage.getIntProperty("SUSTAINED_UPDATE_INTERVAL"); - String sendKey = assignRoleMessage.getStringProperty("SUSTAINED_KEY"); - String sendUpdateKey = assignRoleMessage.getStringProperty("SUSTAINED_UPDATE_KEY"); - int ackMode = assignRoleMessage.getIntProperty("ACKNOWLEDGE_MODE"); - String clientName = assignRoleMessage.getStringProperty("CLIENT_NAME"); - - if (log.isDebugEnabled()) - { - log.debug("numReceivers = " + numReceivers); - log.debug("_batchSize = " + _batchSize); - log.debug("ackMode = " + ackMode); - log.debug("sendKey = " + sendKey); - log.debug("sendUpdateKey = " + sendUpdateKey); - log.debug("role = " + role); - } - - switch (role) - { - // Check if the sender role is being assigned, and set up a single message producer if so. - case SENDER: - console.info("Creating Sender"); - // Create a new connection to pass the test messages on. - connection = new Connection[1]; - session = new Session[1]; - - connection[0] = TestUtils.createConnection(TestClient.testContextProperties); - session[0] = connection[0].createSession(false, ackMode); - - // Extract and retain the test parameters. - sendDestination = session[0].createTopic(sendKey); - - connection[0].setExceptionListener(this); - - producer = session[0].createProducer(sendDestination); - - sendUpdateDestination = session[0].createTopic(sendUpdateKey); - MessageConsumer updateConsumer = session[0].createConsumer(sendUpdateDestination); - - _rateAdapter = new SustainedRateAdapter(this); - updateConsumer.setMessageListener(_rateAdapter); - - break; - - // Otherwise the receivers role is being assigned, so set this up to listen for messages on the required number - // of receivers connections. - case RECEIVER: - console.info("Creating Receiver"); - // Create the required number of receivers connections. - connection = new Connection[numReceivers]; - session = new Session[numReceivers]; - - for (int i = 0; i < numReceivers; i++) - { - connection[i] = TestUtils.createConnection(TestClient.testContextProperties); - session[i] = connection[i].createSession(false, ackMode); - - sendDestination = session[i].createTopic(sendKey); - - sendUpdateDestination = session[i].createTopic(sendUpdateKey); - - MessageConsumer consumer = session[i].createConsumer(sendDestination); - - consumer.setMessageListener(new SustainedListener(clientName + "-" + i, _batchSize, session[i], - sendUpdateDestination)); - } - - break; - } - - // Start all the connection dispatcher threads running. - for (int i = 0; i < connection.length; i++) - { - connection[i].start(); - } - } - - /** Performs the test case actions. - * @param numMessages*/ - public void start(int numMessages) throws JMSException - { - log.debug("public void start(): called"); - - // Check that the sender role is being performed. - switch (role) - { - // Check if the sender role is being assigned, and set up a single message producer if so. - case SENDER: - _rateAdapter.run(); - break; - case RECEIVER: - - } - - // return from here when you have finished the test.. this will signal the controller and - } - - public void terminate() throws JMSException, InterruptedException - { - if (_rateAdapter != null) - { - _rateAdapter.stop(); - } - } - - /** - * Gets a report on the actions performed by the test case in its assigned role. - * - * @param session The controlSession to create the report message in. - * - * @return The report message. - * - * @throws JMSException Any JMSExceptions resulting from creating the report are allowed to fall through. - */ - public Message getReport(Session session) throws JMSException - { - log.debug("public Message getReport(Session controlSession): called"); - - // Close the test connections. - for (int i = 0; i < connection.length; i++) - { - connection[i].close(); - } - - Message report = session.createMessage(); - report.setStringProperty("CONTROL_TYPE", "REPORT"); - - return report; - } - - public void onException(JMSException jmsException) - { - Exception linked = jmsException.getLinkedException(); - - if (linked != null) - { - if (log.isDebugEnabled()) - { - log.debug("Linked Exception:" + linked); - } - - if ((linked instanceof AMQNoRouteException) || (linked instanceof AMQNoConsumersException)) - { - if (log.isDebugEnabled()) - { - if (linked instanceof AMQNoConsumersException) - { - log.warn("No clients currently available for message:" - + ((AMQNoConsumersException) linked).getUndeliveredMessage()); - } - else - { - log.warn("No route for message"); - } - } - - // Tell the rate adapter that there are no clients ready yet - _rateAdapter.NO_CLIENTS = true; - } - } - else - { - log.warn("Exception:" + linked); - } - } - - /** - * Inner class that listens for messages and sends a report for the time taken between receiving the 'start' and - * 'end' messages. - */ - class SustainedListener implements MessageListener - { - /** Number of messages received */ - private long _received = 0; - /** The number of messages in the batch */ - private int _batchSize = 0; - /** Record of the when the 'start' messagse was sen */ - private Long _startTime; - /** Message producer to use to send reports */ - MessageProducer _updater; - /** Session to create the report message on */ - Session _session; - /** Record of the client ID used for this SustainedListnener */ - String _client; - - /** - * Main Constructor - * - * @param clientname The _client id used to identify this connection. - * @param batchSize The number of messages that are to be sent per batch. Note: This is not used to - * control the interval between sending reports. - * @param session The controlSession used for communication. - * @param sendDestination The destination that update reports should be sent to. - * - * @throws JMSException My occur if creatingthe Producer fails - */ - public SustainedListener(String clientname, int batchSize, Session session, Destination sendDestination) - throws JMSException - { - _batchSize = batchSize; - _client = clientname; - _session = session; - _updater = session.createProducer(sendDestination); - } - - public void onMessage(Message message) - { - if (log.isTraceEnabled()) - { - log.trace("Message " + _received + "received in listener"); - } - - if (message instanceof TextMessage) - { - try - { - _received++; - if (((TextMessage) message).getText().equals("start")) - { - log.debug("Starting Batch"); - _startTime = System.nanoTime(); - } - else if (((TextMessage) message).getText().equals("end")) - { - if (_startTime != null) - { - long currentTime = System.nanoTime(); - sendStatus(currentTime - _startTime, _received, message.getIntProperty("BATCH")); - log.debug("End Batch"); - } - } - } - catch (JMSException e) - { - // ignore error - } - } - - } - - /** - * sendStatus creates and sends the report back to the publisher - * - * @param time taken for the the last batch - * @param received Total number of messages received. - * @param batchNumber the batch number - * @throws JMSException if an error occurs during the send - */ - private void sendStatus(long time, long received, int batchNumber) throws JMSException - { - Message updateMessage = _session.createTextMessage("update"); - updateMessage.setStringProperty("CLIENT_ID", ":" + _client); - updateMessage.setStringProperty("CONTROL_TYPE", "UPDATE"); - updateMessage.setLongProperty("RECEIVED", received); - updateMessage.setIntProperty("BATCH", batchNumber); - updateMessage.setLongProperty("DURATION", time); - - if (log.isInfoEnabled()) - { - log.info("**** SENDING [" + batchNumber + "]**** " + "CLIENT_ID:" + _client + " RECEIVED:" + received - + " BATCH:" + batchNumber + " DURATION:" + time); - } - - // Output on the main console.info the details of this batch - if ((batchNumber % 10) == 0) - { - console.info("Sending Report [" + batchNumber + "] " + "CLIENT_ID:" + _client + " RECEIVED:" + received - + " BATCH:" + batchNumber + " DURATION:" + time); - } - - _updater.send(updateMessage); - } - } - - /** - * This class is used here to adjust the _delay value which in turn is used to control the number of messages/second - * that are sent through the test system. - * - * By keeping a record of the messages recevied and the average time taken to process the batch size can be - * calculated and so the delay can be adjusted to maintain that rate. - * - * Given that delays of < 10ms can be rounded up the delay is only used between messages if the _delay > 10ms * no - * messages in the batch. Otherwise the delay is used at the end of the batch. - */ - class SustainedRateAdapter implements MessageListener, Runnable - { - private SustainedClientTestCase _client; - private long _batchVariance = Integer.getInteger("batchVariance", 3); // no. batches to allow drifting - private long _timeVariance = TEN_MILLI_SEC * 5; // no. nanos between send and report delay (10ms) - private volatile long _delay; // in nanos - private long _sent; - private Map<String, Long> _slowClients = new HashMap<String, Long>(); - private static final long PAUSE_SLEEP = TEN_MILLI_SEC / 1000; // 10 ms - private static final long NO_CLIENT_SLEEP = 1000; // 1s - private volatile boolean NO_CLIENTS = true; - private int _delayShifting; - private final int REPORTS_WITHOUT_CHANGE = Integer.getInteger("stableReportCount", 5); - private boolean _warmedup = false; - private static final long EXPECTED_TIME_PER_BATCH = 100000L; - private int _warmUpBatches = Integer.getInteger("warmUpBatches", 10); - - SustainedRateAdapter(SustainedClientTestCase client) - { - _client = client; - } - - public void onMessage(Message message) - { - if (log.isDebugEnabled()) - { - log.debug("SustainedRateAdapter onMessage(Message message = " + message + "): called"); - } - - try - { - String controlType = message.getStringProperty("CONTROL_TYPE"); - - // Check if the message is a test invite. - if ("UPDATE".equals(controlType)) - { - NO_CLIENTS = false; - long duration = message.getLongProperty("DURATION"); - long totalReceived = message.getLongProperty("RECEIVED"); - String client = message.getStringProperty("CLIENT_ID"); - int batchNumber = message.getIntProperty("BATCH"); - - if (log.isInfoEnabled() && ((batchNumber % DEBUG_LOG_UPATE_INTERVAL) == 0)) - { - log.info("Update Report: CLIENT_ID:" + client + " RECEIVED:" + totalReceived + " Recevied BATCH:" - + batchNumber + " DURATION:" + duration); - } - - recordSlow(client, totalReceived, batchNumber); - - adjustDelay(client, batchNumber, duration); - - // Warm up completes when: - // we haven't warmed up - // and the number of batches sent to each client is at least half of the required warmup batches - if (!_warmedup && (batchNumber >= _warmUpBatches)) - { - _warmedup = true; - _warmup.countDown(); - - } - } - } - catch (JMSException e) - { - // - } - } - - CountDownLatch _warmup = new CountDownLatch(1); - - int _numBatches = 10000; - - // long[] _timings = new long[_numBatches]; - private boolean _running = true; - - public void run() - { - console.info("Warming up"); - - doBatch(_warmUpBatches); - - try - { - // wait for warmup to complete. - _warmup.await(); - - // set delay to the average length of the batches - _delay = _totalDuration / _warmUpBatches / delays.size(); - - console.info("Warmup complete delay set : " + _delay + " based on _totalDuration: " + _totalDuration - + " over no. batches: " + _warmUpBatches + " with client count: " + delays.size()); - - _totalDuration = 0L; - _totalReceived = 0L; - _sent = 0L; - } - catch (InterruptedException e) - { - // - } - - doBatch(_numBatches); - - } - - private void doBatch(int batchSize) // long[] timings, - { - TextMessage testMessage = null; - try - { - testMessage = _client.session[0].createTextMessage("start"); - - for (int batch = 0; batch <= batchSize; batch++) - // while (_running) - { - long start = System.nanoTime(); - - testMessage.setText("start"); - testMessage.setIntProperty("BATCH", batch); - - _client.producer.send(testMessage); - _rateAdapter.sentMessage(); - - testMessage.setText("test"); - // start at 2 so start and end count as part of batch - for (int m = 2; m < _batchSize; m++) - { - _client.producer.send(testMessage); - _rateAdapter.sentMessage(); - } - - testMessage.setText("end"); - _client.producer.send(testMessage); - _rateAdapter.sentMessage(); - - long end = System.nanoTime(); - - long sendtime = end - start; - - if (log.isDebugEnabled()) - { - log.info("Sent batch[" + batch + "](" + _batchSize + ") in " + sendtime); // timings[batch]); - } - - if ((batch % LOG_UPATE_INTERVAL) == 0) - { - console.info("Sent Batch[" + batch + "](" + _batchSize + ")" + status()); - } - - _rateAdapter.sleepBatch(); - - } - } - catch (JMSException e) - { - console.error("Runner ended"); - } - } - - private String status() - { - return " TotalDuration: " + _totalDuration + " for " + delays.size() + " consumers" + " Delay is " + _delay - + " resulting in " - + ((_delay > (TEN_MILLI_SEC * _batchSize)) ? ((_delay / _batchSize) + "/msg") : (_delay + "/batch")); - } - - private void sleepBatch() - { - if (checkForSlowClients()) - { // if there werwe slow clients we have already slept so don't sleep anymore again. - return; - } - - if (!SLEEP_PER_MESSAGE) - { - // per batch sleep.. if sleep is to small to spread over the batch. - if (_delay <= (TEN_MILLI_SEC * _batchSize)) - { - sleepLong(_delay); - } - else - { - log.info("Not sleeping _delay > ten*batch is:" + _delay); - } - } - } - - public void stop() - { - _running = false; - } - - Map<String, Long> delays = new HashMap<String, Long>(); - Long _totalReceived = 0L; - Long _totalDuration = 0L; - int _skipUpdate = 0; - - /** - * Adjust the delay for sending messages based on this update from the client - * - * @param client The client that send this update - * @param duration The time taken for the last batch of messagse - * @param batchNumber The reported batchnumber from the client - */ - private void adjustDelay(String client, int batchNumber, long duration) - { - // Retrieve the current total time taken for this client. - Long currentTime = delays.get(client); - - // Add the new duration time to this client - if (currentTime == null) - { - currentTime = duration; - } - else - { - currentTime += duration; - } - - delays.put(client, currentTime); - - long batchesSent = _sent / _batchSize; - - // ensure we don't divide by zero - if (batchesSent == 0) - { - batchesSent = 1L; - } - - _totalReceived += _batchSize; - _totalDuration += duration; - - // calculate average duration accross clients per batch - long averageDuration = _totalDuration / delays.size() / batchesSent; - - // calculate the difference between current send delay and average report delay - long diff = (duration) - averageDuration; - - if (log.isInfoEnabled() && ((batchNumber % DEBUG_LOG_UPATE_INTERVAL) == 0)) - { - log.info("TotalDuration:" + _totalDuration + " for " + delays.size() + " consumers." + " on batch: " - + batchesSent + " received batch: " + batchNumber + " Batch Duration: " + duration + " Average: " - + averageDuration + " so diff: " + diff + " for : " + client + " Delay is " + _delay + " resulting in " - + ((_delay > (TEN_MILLI_SEC * _batchSize)) ? ((_delay / _batchSize) + "/msg") : (_delay + "/batch"))); - } - - // if the averageDuration differs from the current by more than the specified variane then adjust delay. - if (Math.abs(diff) > _timeVariance) - { - - // if the the _delay is larger than the required duration to send report - // speed up - if (diff > TEN_MILLI_SEC) - { - _delay -= TEN_MILLI_SEC; - - if (_delay < 0) - { - _delay = 0; - log.info("Reset _delay to 0"); - delayStable(); - } - else - { - delayChanged(); - } - - } - else if (diff < 0) // diff < 0 diff cannot be 0 as it is > _timeVariance - { - // the report took longer - _delay += TEN_MILLI_SEC; - delayChanged(); - } - } - else - { - delayStable(); - } - - // If we have a consumer that is behind with the batches. - if ((batchesSent - batchNumber) > _batchVariance) - { - log.debug("Increasing _delay as sending more than receiving"); - - _delay += 2 * TEN_MILLI_SEC; - delayChanged(); - } - - } - - /** Reset the number of iterations before we say the delay has stabilised. */ - private void delayChanged() - { - _delayShifting = REPORTS_WITHOUT_CHANGE; - } - - /** - * Record the fact that delay has stabilised If delay has stablised for REPORTS_WITHOUT_CHANGE then it will - * output Delay stabilised - */ - private void delayStable() - { - _delayShifting--; - - if (_delayShifting < 0) - { - _delayShifting = 0; - console.debug("Delay stabilised:" + _delay); - } - } - - /** - * Checks that the client has received enough messages. If the client has fallen behind then they are put in the - * _slowClients lists which will increase the delay. - * - * @param client The client identifier to check - * @param received the number of messages received by that client - * @param batchNumber - */ - private void recordSlow(String client, long received, int batchNumber) - { - if (Math.abs(batchNumber - (_sent / _batchSize)) > _batchVariance) - { - _slowClients.put(client, received); - } - else - { - _slowClients.remove(client); - } - } - - /** Incrment the number of sent messages and then sleep, if required. */ - public void sentMessage() - { - - _sent++; - - if (_delay > (TEN_MILLI_SEC * _batchSize)) - { - long batchDelay = _delay / _batchSize; - // less than 10ms sleep doesn't always work. - // _delay is in nano seconds - // if (batchDelay < (TEN_MILLI_SEC)) - // { - // sleep(0, (int) batchDelay); - // } - // else - { - // if (batchDelay < 30000000000L) - { - sleepLong(batchDelay); - } - } - } - else - { - if (SLEEP_PER_MESSAGE && (_delay > 0)) - { - sleepLong(_delay / _batchSize); - } - } - } - - /** - * Check at the end of each batch and pause sending messages to allow slow clients to catch up. - * - * @return true if there were slow clients that caught up. - */ - private boolean checkForSlowClients() - { - // This will allways be true as we are running this at the end of each batchSize - // if (_sent % _batchSize == 0) - { - // Cause test to pause when we have slow - if (!_slowClients.isEmpty() || NO_CLIENTS) - { - - while (!_slowClients.isEmpty()) - { - if (log.isInfoEnabled() && ((_sent / _batchSize % DEBUG_LOG_UPATE_INTERVAL) == 0)) - { - String clients = ""; - Iterator it = _slowClients.keySet().iterator(); - while (it.hasNext()) - { - clients += it.next(); - if (it.hasNext()) - { - clients += ", "; - } - } - - log.info("Pausing for slow clients:" + clients); - } - - if (console.isDebugEnabled() && ((_sent / _batchSize % LOG_UPATE_INTERVAL) == 0)) - { - console.debug(_slowClients.size() + " slow clients."); - } - - sleep(PAUSE_SLEEP); - } - - if (NO_CLIENTS) - { - sleep(NO_CLIENT_SLEEP); - } - - log.debug("Continuing"); - - return true; - } - else - { - if ((_sent / _batchSize % LOG_UPATE_INTERVAL) == 0) - { - console.info("Total Delay :" + _delay + " " - + ((_delayShifting == 0) ? "Stablised" : ("Not Stablised(" + _delayShifting + ")"))); - } - } - - } - - return false; - } - - /** - * Sleep normally takes micro-seconds this allows the use of a nano-second value. - * - * @param delay nanoseconds to sleep for. - */ - private void sleepLong(long delay) - { - sleep(delay / 1000000, (int) (delay % 1000000)); - } - - /** - * Sleep for the specified micro-seconds. - * @param sleep microseconds to sleep for. - */ - private void sleep(long sleep) - { - sleep(sleep, 0); - } - - /** - * Perform the sleep , swallowing any InteruptException. - * - * NOTE: If a sleep request is > 10s then reset only sleep for 5s - * - * @param milli to sleep for - * @param nano sub miliseconds to sleep for - */ - private void sleep(long milli, int nano) - { - try - { - log.debug("Sleep:" + milli + ":" + nano); - if (milli > 10000) - { - - if (_delay == milli) - { - _totalDuration = _totalReceived / _batchSize * EXPECTED_TIME_PER_BATCH; - log.error("Sleeping for more than 10 seconds adjusted to 5s!:" + (milli / 1000) - + "s. Reset _totalDuration:" + _totalDuration); - } - else - { - log.error("Sleeping for more than 10 seconds adjusted to 5s!:" + (milli / 1000) + "s"); - } - - milli = 5000; - } - - Thread.sleep(milli, nano); - } - catch (InterruptedException e) - { - // - } - } - - public void setClient(SustainedClientTestCase client) - { - _client = client; - } - } - -} diff --git a/java/integrationtests/src/main/java/org/apache/qpid/sustained/SustainedTestCase.java b/java/integrationtests/src/main/java/org/apache/qpid/sustained/SustainedTestCase.java deleted file mode 100644 index 0077b4727a..0000000000 --- a/java/integrationtests/src/main/java/org/apache/qpid/sustained/SustainedTestCase.java +++ /dev/null @@ -1,126 +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.sustained; - -import org.apache.log4j.Logger; - -import org.apache.qpid.client.AMQSession; -import org.apache.qpid.test.framework.DropInTest; -import org.apache.qpid.test.framework.FrameworkBaseCase; - -import javax.jms.JMSException; -import javax.jms.Message; - -import java.util.Properties; - -/** - * SustainedTestCase is a {@link FrameworkBaseCase} that runs the "Perf_SustainedPubSub" test case. This consists of one - * test client sending, and several receiving, and attempts to find the highest rate at which messages can be broadcast - * to the receivers. It is also a {@link DropInTest} to which more test clients may be added during a test run. - * - * <p/><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> - * </table> - */ -public class SustainedTestCase extends FrameworkBaseCase implements DropInTest -{ - /** Used for debugging. */ - Logger log = Logger.getLogger(SustainedTestCase.class); - - /** Holds the root name of the topic on which to send the test messages. */ - private static final String SUSTAINED_KEY = "Perf_SustainedPubSub"; - - /** - * Creates a new coordinating test case with the specified name. - * - * @param name The test case name. - */ - public SustainedTestCase(String name) - { - super(name); - } - - /** - * Performs a single test run of the sustained test. - * - * @throws Exception Any exceptions are allowed to fall through and fail the test. - */ - public void testBasicPubSub() throws Exception - { - log.debug("public void testSinglePubSubCycle(): called"); - - Properties testConfig = new Properties(); - testConfig.put("TEST_NAME", "Perf_SustainedPubSub"); - testConfig.put("SUSTAINED_KEY", SUSTAINED_KEY); - testConfig.put("SUSTAINED_NUM_RECEIVERS", Integer.getInteger("numReceives", 2)); - testConfig.put("SUSTAINED_UPDATE_INTERVAL", Integer.getInteger("batchSize", 1000)); - testConfig.put("SUSTAINED_UPDATE_KEY", SUSTAINED_KEY + ".UPDATE"); - testConfig.put("ACKNOWLEDGE_MODE", Integer.getInteger("ackMode", AMQSession.AUTO_ACKNOWLEDGE)); - - log.info("Created Config: " + testConfig.entrySet().toArray()); - - getCircuitFactory().sequenceTest(null, null, testConfig); - } - - /** - * Accepts a late joining client into this test case. The client will be enlisted with a control message - * with the 'CONTROL_TYPE' field set to the value 'LATEJOIN'. It should also provide values for the fields: - * - * <p/><table> - * <tr><td> CLIENT_NAME <td> A unique name for the new client. - * <tr><td> CLIENT_PRIVATE_CONTROL_KEY <td> The key for the route on which the client receives its control messages. - * </table> - * - * @param message The late joiners join message. - * - * @throws JMSException Any JMS Exception are allowed to fall through, indicating that the join failed. - */ - public void lateJoin(Message message) throws JMSException - { - throw new RuntimeException("Not implemented."); - /* - // Extract the joining clients details from its join request message. - TestClientDetails clientDetails = new TestClientDetails(); - clientDetails.clientName = message.getStringProperty("CLIENT_NAME"); - clientDetails.privateControlKey = message.getStringProperty("CLIENT_PRIVATE_CONTROL_KEY"); - - // Register the joining client, but do block for confirmation as cannot do a synchronous receivers during this - // method call, as it may have been called from an 'onMessage' method. - assignReceiverRole(clientDetails, new Properties(), false); - */ - } - - /** - * Should provide a translation from the junit method name of a test to its test case name as known to the test - * clients that will run the test. The purpose of this is to convert the JUnit method name into the correct test - * case name to place into the test invite. For example the method "testP2P" might map onto the interop test case - * name "TC2_BasicP2P". - * - * @param methodName The name of the JUnit test method. - * - * @return The name of the corresponding interop test case. - */ - public String getTestCaseNameForTestMethod(String methodName) - { - return "Perf_SustainedPubSub"; - } -} diff --git a/java/integrationtests/src/main/java/org/apache/qpid/test/framework/distributedtesting/TestClient.java b/java/integrationtests/src/main/java/org/apache/qpid/test/framework/distributedtesting/TestClient.java deleted file mode 100644 index 56cc0dbd98..0000000000 --- a/java/integrationtests/src/main/java/org/apache/qpid/test/framework/distributedtesting/TestClient.java +++ /dev/null @@ -1,464 +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.framework.distributedtesting; - -import org.apache.log4j.Logger; -import org.apache.log4j.NDC; - -import org.apache.qpid.interop.clienttestcases.TestCase1DummyRun; -import org.apache.qpid.interop.clienttestcases.TestCase2BasicP2P; -import org.apache.qpid.interop.clienttestcases.TestCase3BasicPubSub; -import org.apache.qpid.sustained.SustainedClientTestCase; -import org.apache.qpid.test.framework.MessagingTestConfigProperties; -import org.apache.qpid.test.framework.TestUtils; -import org.apache.qpid.test.framework.clocksynch.ClockSynchThread; -import org.apache.qpid.test.framework.clocksynch.ClockSynchronizer; -import org.apache.qpid.test.framework.clocksynch.UDPClockSynchronizer; -import org.apache.qpid.test.framework.distributedcircuit.TestClientCircuitEnd; - -import uk.co.thebadgerset.junit.extensions.SleepThrottle; -import uk.co.thebadgerset.junit.extensions.Throttle; -import uk.co.thebadgerset.junit.extensions.util.ParsedProperties; -import uk.co.thebadgerset.junit.extensions.util.TestContextProperties; - -import javax.jms.*; - -import java.util.*; - -/** - * Implements a test client as described in the interop testing spec - * (http://cwiki.apache.org/confluence/display/qpid/Interop+Testing+Specification). A test client is an agent that - * reacts to control message sequences send by the test {@link Coordinator}. - * - * <p/><table><caption>Messages Handled by SustainedTestClient</caption> - * <tr><th> Message <th> Action - * <tr><td> Invite(compulsory) <td> Reply with Enlist. - * <tr><td> Invite(test case) <td> Reply with Enlist if test case available. - * <tr><td> AssignRole(test case) <td> Reply with Accept Role if matches an enlisted test. Keep test parameters. - * <tr><td> Start <td> Send test messages defined by test parameters. Send report on messages sent. - * <tr><td> Status Request <td> Send report on messages received. - * <tr><td> Terminate <td> Terminate the test client. - * <tr><td> ClockSynch <td> Synch clock against the supplied UDP address. - * </table> - * - * <p><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Handle all incoming control messages. <td> {@link TestClientControlledTest} - * <tr><td> Configure and look up test cases by name. <td> {@link TestClientControlledTest} - * </table> - */ -public class TestClient implements MessageListener -{ - /** Used for debugging. */ - private static final Logger log = Logger.getLogger(TestClient.class); - - /** Used for reporting to the console. */ - private static final Logger console = Logger.getLogger("CONSOLE"); - - /** Holds the default identifying name of the test client. */ - public static final String CLIENT_NAME = "java"; - - /** Holds the URL of the broker to run the tests on. */ - public static String brokerUrl; - - /** Holds the virtual host to run the tests on. If <tt>null</tt>, then the default virtual host is used. */ - public static String virtualHost; - - /** - * Holds the test context properties that provides the default test parameters, plus command line overrides. - * This is initialized with the default test parameters, to which command line overrides may be applied. - */ - public static ParsedProperties testContextProperties = - TestContextProperties.getInstance(MessagingTestConfigProperties.defaults); - - /** Holds all the test cases loaded from the classpath. */ - Map<String, TestClientControlledTest> testCases = new HashMap<String, TestClientControlledTest>(); - - /** Holds the test case currently being run by this client. */ - protected TestClientControlledTest currentTestCase; - - /** Holds the connection to the broker that the test is being coordinated on. */ - protected Connection connection; - - /** Holds the message producer to hold the test coordination over. */ - protected MessageProducer producer; - - /** Holds the JMS controlSession for the test coordination. */ - protected Session session; - - /** Holds the name of this client, with a default value. */ - protected String clientName = CLIENT_NAME; - - /** This flag indicates that the test client should attempt to join the currently running test case on start up. */ - protected boolean join; - - /** Holds the clock synchronizer for the test node. */ - ClockSynchThread clockSynchThread; - - /** - * Creates a new interop test client, listenting to the specified broker and virtual host, with the specified client - * identifying name. - * - * @param brokerUrl The url of the broker to connect to. - * @param virtualHost The virtual host to conect to. - * @param clientName The client name to use. - * @param join Flag to indicate that this client should attempt to join running tests. - */ - public TestClient(String brokerUrl, String virtualHost, String clientName, boolean join) - { - log.debug("public TestClient(String brokerUrl = " + brokerUrl + ", String virtualHost = " + virtualHost - + ", String clientName = " + clientName + ", boolean join = " + join + "): called"); - - // Retain the connection parameters. - this.brokerUrl = brokerUrl; - this.virtualHost = virtualHost; - this.clientName = clientName; - this.join = join; - } - - /** - * The entry point for the interop test coordinator. This client accepts the following command line arguments: - * - * <p/><table> - * <tr><td> -b <td> The broker URL. <td> Optional. - * <tr><td> -h <td> The virtual host. <td> Optional. - * <tr><td> -n <td> The test client name. <td> Optional. - * <tr><td> name=value <td> Trailing argument define name/value pairs. Added to system properties. <td> Optional. - * </table> - * - * @param args The command line arguments. - */ - public static void main(String[] args) - { - log.debug("public static void main(String[] args = " + Arrays.toString(args) + "): called"); - console.info("Qpid Distributed Test Client."); - - // Override the default broker url to be localhost:5672. - testContextProperties.setProperty(MessagingTestConfigProperties.BROKER_PROPNAME, "tcp://localhost:5672"); - - // Use the command line parser to evaluate the command line with standard handling behaviour (print errors - // and usage then exist if there are errors). - // Any options and trailing name=value pairs are also injected into the test context properties object, - // to override any defaults that may have been set up. - ParsedProperties options = - new ParsedProperties(uk.co.thebadgerset.junit.extensions.util.CommandLineParser.processCommandLine(args, - new uk.co.thebadgerset.junit.extensions.util.CommandLineParser( - new String[][] - { - { "b", "The broker URL.", "broker", "false" }, - { "h", "The virtual host to use.", "virtual host", "false" }, - { "o", "The name of the directory to output test timings to.", "dir", "false" }, - { "n", "The name of the test client.", "name", "false" }, - { "j", "Join this test client to running test.", "false" } - }), testContextProperties)); - - // Extract the command line options. - String brokerUrl = options.getProperty("b"); - String virtualHost = options.getProperty("h"); - String clientName = options.getProperty("n"); - clientName = (clientName == null) ? CLIENT_NAME : clientName; - boolean join = options.getPropertyAsBoolean("j"); - - // To distinguish logging output set up an NDC on the client name. - NDC.push(clientName); - - // Create a test client and start it running. - TestClient client = new TestClient(brokerUrl, virtualHost, clientName, join); - - // Use a class path scanner to find all the interop test case implementations. - // Hard code the test classes till the classpath scanner is fixed. - Collection<Class<? extends TestClientControlledTest>> testCaseClasses = - new ArrayList<Class<? extends TestClientControlledTest>>(); - // ClasspathScanner.getMatches(TestClientControlledTest.class, "^TestCase.*", true); - Collections.addAll(testCaseClasses, TestCase1DummyRun.class, TestCase2BasicP2P.class, TestCase3BasicPubSub.class, - SustainedClientTestCase.class, TestClientCircuitEnd.class); - - try - { - client.start(testCaseClasses); - } - catch (Exception e) - { - log.error("The test client was unable to start.", e); - console.info(e.getMessage()); - System.exit(1); - } - } - - /** - * Starts the interop test client running. This causes it to start listening for incoming test invites. - * - * @param testCaseClasses The classes of the available test cases. The test case names from these are used to - * matchin incoming test invites against. - * - * @throws JMSException Any underlying JMSExceptions are allowed to fall through. - */ - protected void start(Collection<Class<? extends TestClientControlledTest>> testCaseClasses) throws JMSException - { - log.debug("protected void start(Collection<Class<? extends TestClientControlledTest>> testCaseClasses = " - + testCaseClasses + "): called"); - - // Create all the test case implementations and index them by the test names. - for (Class<? extends TestClientControlledTest> nextClass : testCaseClasses) - { - try - { - TestClientControlledTest testCase = nextClass.newInstance(); - testCases.put(testCase.getName(), testCase); - } - catch (InstantiationException e) - { - log.warn("Could not instantiate test case class: " + nextClass.getName(), e); - // Ignored. - } - catch (IllegalAccessException e) - { - log.warn("Could not instantiate test case class due to illegal access: " + nextClass.getName(), e); - // Ignored. - } - } - - // Open a connection to communicate with the coordinator on. - connection = TestUtils.createConnection(testContextProperties); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - // Set this up to listen for control messages. - Topic privateControlTopic = session.createTopic("iop.control." + clientName); - MessageConsumer consumer = session.createConsumer(privateControlTopic); - consumer.setMessageListener(this); - - Topic controlTopic = session.createTopic("iop.control"); - MessageConsumer consumer2 = session.createConsumer(controlTopic); - consumer2.setMessageListener(this); - - // Create a producer to send replies with. - producer = session.createProducer(null); - - // If the join flag was set, then broadcast a join message to notify the coordinator that a new test client - // is available to join the current test case, if it supports it. This message may be ignored, or it may result - // in this test client receiving a test invite. - if (join) - { - Message joinMessage = session.createMessage(); - - joinMessage.setStringProperty("CONTROL_TYPE", "JOIN"); - joinMessage.setStringProperty("CLIENT_NAME", clientName); - joinMessage.setStringProperty("CLIENT_PRIVATE_CONTROL_KEY", "iop.control." + clientName); - producer.send(controlTopic, joinMessage); - } - - // Start listening for incoming control messages. - connection.start(); - } - - /** - * Handles all incoming control messages. - * - * @param message The incoming message. - */ - public void onMessage(Message message) - { - NDC.push(clientName); - log.debug("public void onMessage(Message message = " + message + "): called"); - - try - { - String controlType = message.getStringProperty("CONTROL_TYPE"); - String testName = message.getStringProperty("TEST_NAME"); - - log.debug("Received control of type '" + controlType + "' for the test '" + testName + "'"); - - // Check if the message is a test invite. - if ("INVITE".equals(controlType)) - { - // Flag used to indicate that an enlist should be sent. Only enlist to compulsory invites or invites - // for which test cases exist. - boolean enlist = false; - - if (testName != null) - { - log.debug("Got an invite to test: " + testName); - - // Check if the requested test case is available. - TestClientControlledTest testCase = testCases.get(testName); - - if (testCase != null) - { - log.debug("Found implementing class for test '" + testName + "', enlisting for it."); - - // Check if the test case will accept the invitation. - enlist = testCase.acceptInvite(message); - - log.debug("The test case " - + (enlist ? " accepted the invite, enlisting for it." - : " did not accept the invite, not enlisting.")); - - // Make the requested test case the current test case. - currentTestCase = testCase; - } - else - { - log.debug("Received an invite to the test '" + testName + "' but this test is not known."); - } - } - else - { - log.debug("Got a compulsory invite, enlisting for it."); - - enlist = true; - } - - if (enlist) - { - // Reply with the client name in an Enlist message. - Message enlistMessage = session.createMessage(); - enlistMessage.setStringProperty("CONTROL_TYPE", "ENLIST"); - enlistMessage.setStringProperty("CLIENT_NAME", clientName); - enlistMessage.setStringProperty("CLIENT_PRIVATE_CONTROL_KEY", "iop.control." + clientName); - enlistMessage.setJMSCorrelationID(message.getJMSCorrelationID()); - - log.debug("Sending enlist message '" + enlistMessage + "' to " + message.getJMSReplyTo()); - - producer.send(message.getJMSReplyTo(), enlistMessage); - } - else - { - // Reply with the client name in an Decline message. - Message enlistMessage = session.createMessage(); - enlistMessage.setStringProperty("CONTROL_TYPE", "DECLINE"); - enlistMessage.setStringProperty("CLIENT_NAME", clientName); - enlistMessage.setStringProperty("CLIENT_PRIVATE_CONTROL_KEY", "iop.control." + clientName); - enlistMessage.setJMSCorrelationID(message.getJMSCorrelationID()); - - log.debug("Sending decline message '" + enlistMessage + "' to " + message.getJMSReplyTo()); - - producer.send(message.getJMSReplyTo(), enlistMessage); - } - } - else if ("ASSIGN_ROLE".equals(controlType)) - { - // Assign the role to the current test case. - String roleName = message.getStringProperty("ROLE"); - - log.debug("Got a role assignment to role: " + roleName); - - TestClientControlledTest.Roles role = Enum.valueOf(TestClientControlledTest.Roles.class, roleName); - - currentTestCase.assignRole(role, message); - - // Reply by accepting the role in an Accept Role message. - Message acceptRoleMessage = session.createMessage(); - acceptRoleMessage.setStringProperty("CLIENT_NAME", clientName); - acceptRoleMessage.setStringProperty("CONTROL_TYPE", "ACCEPT_ROLE"); - acceptRoleMessage.setJMSCorrelationID(message.getJMSCorrelationID()); - - log.debug("Sending accept role message '" + acceptRoleMessage + "' to " + message.getJMSReplyTo()); - - producer.send(message.getJMSReplyTo(), acceptRoleMessage); - } - else if ("START".equals(controlType) || "STATUS_REQUEST".equals(controlType)) - { - if ("START".equals(controlType)) - { - log.debug("Got a start notification."); - - // Extract the number of test messages to send from the start notification. - int numMessages; - - try - { - numMessages = message.getIntProperty("MESSAGE_COUNT"); - } - catch (NumberFormatException e) - { - // If the number of messages is not specified, use the default of one. - numMessages = 1; - } - - // Start the current test case. - currentTestCase.start(numMessages); - } - else - { - log.debug("Got a status request."); - } - - // Generate the report from the test case and reply with it as a Report message. - Message reportMessage = currentTestCase.getReport(session); - reportMessage.setStringProperty("CLIENT_NAME", clientName); - reportMessage.setStringProperty("CONTROL_TYPE", "REPORT"); - reportMessage.setJMSCorrelationID(message.getJMSCorrelationID()); - - log.debug("Sending report message '" + reportMessage + "' to " + message.getJMSReplyTo()); - - producer.send(message.getJMSReplyTo(), reportMessage); - } - else if ("TERMINATE".equals(controlType)) - { - console.info("Received termination instruction from coordinator."); - - // Is a cleaner shutdown needed? - connection.close(); - System.exit(0); - } - else if ("CLOCK_SYNCH".equals(controlType)) - { - log.debug("Received clock synch command."); - String address = message.getStringProperty("ADDRESS"); - - log.debug("address = " + address); - - // Re-create (if necessary) and start the clock synch thread to synch the clock every ten seconds. - if (clockSynchThread != null) - { - clockSynchThread.terminate(); - } - - SleepThrottle throttle = new SleepThrottle(); - throttle.setRate(0.1f); - - clockSynchThread = new ClockSynchThread(new UDPClockSynchronizer(address), throttle); - clockSynchThread.start(); - } - else - { - // Log a warning about this but otherwise ignore it. - log.warn("Got an unknown control message, controlType = " + controlType + ", message = " + message); - } - } - catch (JMSException e) - { - // Log a warning about this, but otherwise ignore it. - log.warn("Got JMSException whilst handling message: " + message, e); - } - // Log any runtimes that fall through this message handler. These are fatal errors for the test client. - catch (RuntimeException e) - { - log.error("The test client message handler got an unhandled exception: ", e); - console.info("The message handler got an unhandled exception, terminating the test client."); - System.exit(1); - } - finally - { - NDC.pop(); - } - } -} diff --git a/java/integrationtests/src/main/java/org/apache/qpid/util/ClasspathScanner.java b/java/integrationtests/src/main/java/org/apache/qpid/util/ClasspathScanner.java deleted file mode 100644 index bad49060ca..0000000000 --- a/java/integrationtests/src/main/java/org/apache/qpid/util/ClasspathScanner.java +++ /dev/null @@ -1,234 +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.util;
-
-import java.io.File;
-import java.util.*;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.apache.log4j.Logger;
-
-/**
- * An ClasspathScanner scans the classpath for classes that implement an interface or extend a base class and have names
- * that match a regular expression.
- *
- * <p/>In order to test whether a class implements an interface or extends a class, the class must be loaded (unless
- * the class files were to be scanned directly). Using this collector can cause problems when it scans the classpath,
- * because loading classes will initialize their statics, which in turn may cause undesired side effects. For this
- * reason, the collector should always be used with a regular expression, through which the class file names are
- * filtered, and only those that pass this filter will be tested. For example, if you define tests in classes that
- * end with the keyword "Test" then use the regular expression "Test$" to match this.
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Find all classes matching type and name pattern on the classpath.
- * </table>
- *
- * @todo Add logic to scan jars as well as directories.
- */
-public class ClasspathScanner
-{
- private static final Logger log = Logger.getLogger(ClasspathScanner.class);
-
- /**
- * Scans the classpath and returns all classes that extend a specified class and match a specified name.
- * There is an flag that can be used to indicate that only Java Beans will be matched (that is, only those classes
- * that have a default constructor).
- *
- * @param matchingClass The class or interface to match.
- * @param matchingRegexp The regular expression to match against the class name.
- * @param beanOnly Flag to indicate that onyl classes with default constructors should be matched.
- *
- * @return All the classes that match this collector.
- */
- public static <T> Collection<Class<? extends T>> getMatches(Class<T> matchingClass, String matchingRegexp,
- boolean beanOnly)
- {
- log.debug("public static <T> Collection<Class<? extends T>> getMatches(Class<T> matchingClass = " + matchingClass
- + ", String matchingRegexp = " + matchingRegexp + ", boolean beanOnly = " + beanOnly + "): called");
-
- // Build a compiled regular expression from the pattern to match.
- Pattern matchPattern = Pattern.compile(matchingRegexp);
-
- String classPath = System.getProperty("java.class.path");
- Map<String, Class<? extends T>> result = new HashMap<String, Class<? extends T>>();
-
- log.debug("classPath = " + classPath);
-
- // Find matching classes starting from all roots in the classpath.
- for (String path : splitClassPath(classPath))
- {
- gatherFiles(new File(path), "", result, matchPattern, matchingClass);
- }
-
- return result.values();
- }
-
- /**
- * Finds all matching classes rooted at a given location in the file system. If location is a directory it
- * is recursively examined.
- *
- * @param classRoot The root of the current point in the file system being examined.
- * @param classFileName The name of the current file or directory to examine.
- * @param result The accumulated mapping from class names to classes that match the scan.
- *
- * @todo Recursion ok as file system depth is not likely to exhaust the stack. Might be better to replace with
- * iteration.
- */
- private static <T> void gatherFiles(File classRoot, String classFileName, Map<String, Class<? extends T>> result,
- Pattern matchPattern, Class<? extends T> matchClass)
- {
- log.debug("private static <T> void gatherFiles(File classRoot = " + classRoot + ", String classFileName = "
- + classFileName + ", Map<String, Class<? extends T>> result, Pattern matchPattern = " + matchPattern
- + ", Class<? extends T> matchClass = " + matchClass + "): called");
-
- File thisRoot = new File(classRoot, classFileName);
-
- // If the current location is a file, check if it is a matching class.
- if (thisRoot.isFile())
- {
- // Check that the file has a matching name.
- if (matchesName(thisRoot.getName(), matchPattern))
- {
- String className = classNameFromFile(thisRoot.getName());
-
- // Check that the class has matching type.
- try
- {
- Class<?> candidateClass = Class.forName(className);
-
- Class matchedClass = matchesClass(candidateClass, matchClass);
-
- if (matchedClass != null)
- {
- result.put(className, matchedClass);
- }
- }
- catch (ClassNotFoundException e)
- {
- // Ignore this. The matching class could not be loaded.
- log.debug("Got ClassNotFoundException, ignoring.", e);
- }
- }
-
- return;
- }
- // Otherwise the current location is a directory, so examine all of its contents.
- else
- {
- String[] contents = thisRoot.list();
-
- if (contents != null)
- {
- for (String content : contents)
- {
- gatherFiles(classRoot, classFileName + File.separatorChar + content, result, matchPattern, matchClass);
- }
- }
- }
- }
-
- /**
- * Checks if the specified class file name corresponds to a class with name matching the specified regular expression.
- *
- * @param classFileName The class file name.
- * @param matchPattern The regular expression pattern to match.
- *
- * @return <tt>true</tt> if the class name matches, <tt>false</tt> otherwise.
- */
- private static boolean matchesName(String classFileName, Pattern matchPattern)
- {
- String className = classNameFromFile(classFileName);
- Matcher matcher = matchPattern.matcher(className);
-
- return matcher.matches();
- }
-
- /**
- * Checks if the specified class to compare extends the base class being scanned for.
- *
- * @param matchingClass The base class to match against.
- * @param toMatch The class to match against the base class.
- *
- * @return The class to check, cast as an instance of the class to match if the class extends the base class, or
- * <tt>null</tt> otherwise.
- */
- private static <T> Class<? extends T> matchesClass(Class<?> matchingClass, Class<? extends T> toMatch)
- {
- try
- {
- return matchingClass.asSubclass(toMatch);
- }
- catch (ClassCastException e)
- {
- return null;
- }
- }
-
- /**
- * Takes a classpath (which is a series of paths) and splits it into its component paths.
- *
- * @param classPath The classpath to split.
- *
- * @return A list of the component paths that make up the class path.
- */
- private static List<String> splitClassPath(String classPath)
- {
- List<String> result = new LinkedList<String>();
- String separator = System.getProperty("path.separator");
- StringTokenizer tokenizer = new StringTokenizer(classPath, separator);
-
- while (tokenizer.hasMoreTokens())
- {
- result.add(tokenizer.nextToken());
- }
-
- return result;
- }
-
- /**
- * Translates from the filename of a class to its fully qualified classname. Files are named using forward slash
- * seperators and end in ".class", whereas fully qualified class names use "." sperators and no ".class" ending.
- *
- * @param classFileName The filename of the class to translate to a class name.
- *
- * @return The fully qualified class name.
- */
- private static String classNameFromFile(String classFileName)
- {
- log.debug("private static String classNameFromFile(String classFileName = " + classFileName + "): called");
-
- // Remove the .class ending.
- String s = classFileName.substring(0, classFileName.length() - ".class".length());
-
- // Turn / seperators in . seperators.
- String s2 = s.replace(File.separatorChar, '.');
-
- // Knock off any leading . caused by a leading /.
- if (s2.startsWith("."))
- {
- return s2.substring(1);
- }
-
- return s2;
- }
-}
diff --git a/java/integrationtests/src/main/java/org/apache/qpid/util/ConversationFactory.java b/java/integrationtests/src/main/java/org/apache/qpid/util/ConversationFactory.java deleted file mode 100644 index 0090bec3d0..0000000000 --- a/java/integrationtests/src/main/java/org/apache/qpid/util/ConversationFactory.java +++ /dev/null @@ -1,479 +0,0 @@ -/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.util;
-
-import org.apache.log4j.Logger;
-
-import javax.jms.*;
-
-import java.util.*;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicLong;
-
-/**
- * A conversation helper, uses a message correlation id pattern to match up sent and received messages as a conversation
- * over JMS messaging. Incoming message traffic is divided up by correlation id. Each id has a queue (behaviour dependant
- * on the queue implementation). Clients of this de-multiplexer can wait on messages, defined by message correlation ids.
- *
- * <p/>One use of this is as a conversation synchronizer where multiple threads are carrying out conversations over a
- * multiplexed messaging route. This can be usefull, as JMS sessions are not multi-threaded. Setting up the conversation
- * with synchronous queues will allow these threads to be written in a synchronous style, but with their execution order
- * governed by the asynchronous message flow. For example, something like the following code could run a multi-threaded
- * conversation (the conversation methods can be called many times in parallel):
- *
- * <p/><pre>
- * class Initiator
- * {
- * ConversationHelper conversation = new ConversationHelper(connection, null,
- * java.util.concurrent.LinkedBlockingQueue.class);
- *
- * initiateConversation()
- * {
- * try {
- * // Exchange greetings.
- * conversation.send(sendDestination, conversation.getSession().createTextMessage("Hello."));
- * Message greeting = conversation.receive();
- *
- * // Exchange goodbyes.
- * conversation.send(conversation.getSession().createTextMessage("Goodbye."));
- * Message goodbye = conversation.receive();
- * } finally {
- * conversation.end();
- * }
- * }
- * }
- *
- * class Responder
- * {
- * ConversationHelper conversation = new ConversationHelper(connection, receiveDestination,
- * java.util.concurrent.LinkedBlockingQueue.class);
- *
- * respondToConversation()
- * {
- * try {
- * // Exchange greetings.
- * Message greeting = conversation.receive();
- * conversation.send(conversation.getSession().createTextMessage("Hello."));
- *
- * // Exchange goodbyes.
- * Message goodbye = conversation.receive();
- * conversation.send(conversation.getSession().createTextMessage("Goodbye."));
- * } finally {
- * conversation.end();
- * }
- * }
- * }
- * </pre>
- *
- * <p/>Conversation correlation id's are generated on a per thread basis.
- *
- * <p/>The same session is shared amongst all conversations. Calls to send are therefore synchronized because JMS
- * sessions are not multi-threaded.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><th> Associate messages to an ongoing conversation using correlation ids.
- * <tr><td> Auto manage sessions for conversations.
- * <tr><td> Store messages not in a conversation in dead letter box.
- * </table>
- */
-public class ConversationFactory
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(ConversationFactory.class);
-
- /** Holds a map from correlation id's to queues. */
- private Map<Long, BlockingQueue<Message>> idsToQueues = new HashMap<Long, BlockingQueue<Message>>();
-
- /** Holds the connection over which the conversation is conducted. */
- private Connection connection;
-
- /** Holds the session over which the conversation is conduxted. */
- private Session session;
-
- /** The message consumer for incoming messages. */
- MessageConsumer consumer;
-
- /** The message producer for outgoing messages. */
- MessageProducer producer;
-
- /** The well-known or temporary destination to receive replies on. */
- Destination receiveDestination;
-
- /** Holds the queue implementation class for the reply queue. */
- Class<? extends BlockingQueue> queueClass;
-
- /** Used to hold any replies that are received outside of the context of a conversation. */
- BlockingQueue<Message> deadLetterBox = new LinkedBlockingQueue<Message>();
-
- /* Used to hold conversation state on a per thread basis. */
- /*
- ThreadLocal<Conversation> threadLocals =
- new ThreadLocal<Conversation>()
- {
- protected Conversation initialValue()
- {
- Conversation settings = new Conversation();
- settings.conversationId = conversationIdGenerator.getAndIncrement();
-
- return settings;
- }
- };
- */
-
- /** Generates new coversation id's as needed. */
- AtomicLong conversationIdGenerator = new AtomicLong();
-
- /**
- * Creates a conversation helper on the specified connection with the default sending destination, and listening
- * to the specified receiving destination.
- *
- * @param connection The connection to build the conversation helper on.
- * @param receiveDestination The destination to listen to for incoming messages. This may be null to use a temporary
- * queue.
- * @param queueClass The queue implementation class.
- *
- * @throws JMSException All underlying JMSExceptions are allowed to fall through.
- */
- public ConversationFactory(Connection connection, Destination receiveDestination,
- Class<? extends BlockingQueue> queueClass) throws JMSException
- {
- log.debug("public ConversationFactory(Connection connection, Destination receiveDestination = " + receiveDestination
- + ", Class<? extends BlockingQueue> queueClass = " + queueClass + "): called");
-
- this.connection = connection;
- this.queueClass = queueClass;
-
- session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- // Check if a well-known receive destination has been provided, or use a temporary queue if not.
- this.receiveDestination = (receiveDestination != null) ? receiveDestination : session.createTemporaryQueue();
-
- consumer = session.createConsumer(receiveDestination);
- producer = session.createProducer(null);
-
- consumer.setMessageListener(new Receiver());
- }
-
- /**
- * Creates a new conversation context.
- *
- * @return A new conversation context.
- */
- public Conversation startConversation()
- {
- log.debug("public Conversation startConversation(): called");
-
- Conversation conversation = new Conversation();
- conversation.conversationId = conversationIdGenerator.getAndIncrement();
-
- return conversation;
- }
-
- /**
- * Ensures that the reply queue for a conversation exists.
- *
- * @param conversationId The conversation correlation id.
- */
- private void initQueueForId(long conversationId)
- {
- if (!idsToQueues.containsKey(conversationId))
- {
- idsToQueues.put(conversationId, ReflectionUtils.<BlockingQueue>newInstance(queueClass));
- }
- }
-
- /**
- * Clears the dead letter box, returning all messages that were in it.
- *
- * @return All messages in the dead letter box.
- */
- public Collection<Message> emptyDeadLetterBox()
- {
- log.debug("public Collection<Message> emptyDeadLetterBox(): called");
-
- Collection<Message> result = new ArrayList<Message>();
- deadLetterBox.drainTo(result);
-
- return result;
- }
-
- /**
- * Gets the session over which the conversation is conducted.
- *
- * @return The session over which the conversation is conducted.
- */
- public Session getSession()
- {
- // Conversation settings = threadLocals.get();
-
- return session;
- }
-
- /**
- * Used to hold a conversation context. This consists of a correlating id for the conversation, and a reply
- * destination automatically updated to the last received reply-to destination.
- */
- public class Conversation
- {
- /** Holds the correlation id for the context. */
- long conversationId;
-
- /**
- * Holds the send destination for the context. This will automatically be updated to the most recently received
- * reply-to destination.
- */
- Destination sendDestination;
-
- /**
- * Sends a message to the default sending location. The correlation id of the message will be assigned by this
- * method, overriding any previously set value.
- *
- * @param sendDestination The destination to send to. This may be null to use the last received reply-to
- * destination.
- * @param message The message to send.
- *
- * @throws JMSException All undelying JMSExceptions are allowed to fall through. This will also be thrown if no
- * send destination is specified and there is no most recent reply-to destination available
- * to use.
- */
- public void send(Destination sendDestination, Message message) throws JMSException
- {
- log.debug("public void send(Destination sendDestination = " + sendDestination + ", Message message = " + message
- + "): called");
-
- // Conversation settings = threadLocals.get();
- // long conversationId = conversationId;
- message.setJMSCorrelationID(Long.toString(conversationId));
- message.setJMSReplyTo(receiveDestination);
-
- // Ensure that the reply queue for this conversation exists.
- initQueueForId(conversationId);
-
- // Check if an overriding send to destination has been set or use the last reply-to if not.
- Destination sendTo = null;
-
- if (sendDestination != null)
- {
- sendTo = sendDestination;
- }
- else if (sendDestination != null)
- {
- sendTo = sendDestination;
- }
- else
- {
- throw new JMSException("The send destination was specified, and no most recent reply-to available to use.");
- }
-
- // Send the message.
- synchronized (this)
- {
- producer.send(sendTo, message);
- }
- }
-
- /**
- * Gets the next message in an ongoing conversation. This method may block until such a message is received.
- *
- * @return The next incoming message in the conversation.
- *
- * @throws JMSException All undelying JMSExceptions are allowed to fall through. Thrown if the received message
- * did not have its reply-to destination set up.
- */
- public Message receive() throws JMSException
- {
- log.debug("public Message receive(): called");
-
- // Conversation settings = threadLocals.get();
- // long conversationId = settings.conversationId;
-
- // Ensure that the reply queue for this conversation exists.
- initQueueForId(conversationId);
-
- BlockingQueue<Message> queue = idsToQueues.get(conversationId);
-
- try
- {
- Message result = queue.take();
-
- // Keep the reply-to destination to send replies to.
- sendDestination = result.getJMSReplyTo();
-
- return result;
- }
- catch (InterruptedException e)
- {
- return null;
- }
- }
-
- /**
- * Gets many messages in an ongoing conversation. If a limit is specified, then once that many messages are
- * received they will be returned. If a timeout is specified, then all messages up to the limit, received within
- * that timespan will be returned. At least one of the message count or timeout should be set to a value of
- * 1 or greater.
- *
- * @param num The number of messages to receive, or all if this is less than 1.
- * @param timeout The timeout in milliseconds to receive the messages in, or forever if this is less than 1.
- *
- * @return All messages received within the count limit and the timeout.
- *
- * @throws JMSException All undelying JMSExceptions are allowed to fall through.
- */
- public Collection<Message> receiveAll(int num, long timeout) throws JMSException
- {
- log.debug("public Collection<Message> receiveAll(int num = " + num + ", long timeout = " + timeout
- + "): called");
-
- // Check that a timeout or message count was set.
- if ((num < 1) && (timeout < 1))
- {
- throw new IllegalArgumentException("At least one of message count (num) or timeout must be set.");
- }
-
- // Ensure that the reply queue for this conversation exists.
- initQueueForId(conversationId);
- BlockingQueue<Message> queue = idsToQueues.get(conversationId);
-
- // Used to collect the received messages in.
- Collection<Message> result = new ArrayList<Message>();
-
- // Used to indicate when the timeout or message count has expired.
- boolean receiveMore = true;
-
- int messageCount = 0;
-
- // Receive messages until the timeout or message count expires.
- do
- {
- try
- {
- Message next = null;
-
- // Try to receive the message with a timeout if one has been set.
- if (timeout > 0)
- {
- next = queue.poll(timeout, TimeUnit.MILLISECONDS);
-
- // Check if the timeout expired, and stop receiving if so.
- if (next == null)
- {
- receiveMore = false;
- }
- }
- // Receive the message without a timeout.
- else
- {
- next = queue.take();
- }
-
- // Increment the message count if a message was received.
- messageCount += (next != null) ? 1 : 0;
-
- // Check if all the requested messages were received, and stop receiving if so.
- if ((num > 0) && (messageCount >= num))
- {
- receiveMore = false;
- }
-
- // Keep the reply-to destination to send replies to.
- sendDestination = (next != null) ? next.getJMSReplyTo() : sendDestination;
-
- if (next != null)
- {
- result.add(next);
- }
- }
- catch (InterruptedException e)
- {
- // Restore the threads interrupted status.
- Thread.currentThread().interrupt();
-
- // Stop receiving but return the messages received so far.
- receiveMore = false;
- }
- }
- while (receiveMore);
-
- return result;
- }
-
- /**
- * Completes the conversation. Any correlation id's pertaining to the conversation are no longer valid, and any
- * incoming messages using them will go to the dead letter box.
- */
- public void end()
- {
- log.debug("public void end(): called");
-
- // Ensure that the thread local for the current thread is cleaned up.
- // Conversation settings = threadLocals.get();
- // long conversationId = settings.conversationId;
- // threadLocals.remove();
-
- // Ensure that its queue is removed from the queue map.
- BlockingQueue<Message> queue = idsToQueues.remove(conversationId);
-
- // Move any outstanding messages on the threads conversation id into the dead letter box.
- queue.drainTo(deadLetterBox);
- }
- }
-
- /**
- * Implements the message listener for this conversation handler.
- */
- protected class Receiver implements MessageListener
- {
- /**
- * Handles all incoming messages in the ongoing conversations. These messages are split up by correaltion id
- * and placed into queues.
- *
- * @param message The incoming message.
- */
- public void onMessage(Message message)
- {
- log.debug("public void onMessage(Message message = " + message + "): called");
-
- try
- {
- Long conversationId = Long.parseLong(message.getJMSCorrelationID());
-
- // Find the converstaion queue to place the message on. If there is no conversation for the message id,
- // the the dead letter box queue is used.
- BlockingQueue<Message> queue = idsToQueues.get(conversationId);
- queue = (queue == null) ? deadLetterBox : queue;
-
- queue.put(message);
- }
- catch (JMSException e)
- {
- throw new RuntimeException(e);
- }
- catch (InterruptedException e)
- {
- throw new RuntimeException(e);
- }
- }
- }
-}
diff --git a/java/integrationtests/src/resources/org/apache/qpid/interop/connection.properties b/java/integrationtests/src/resources/org/apache/qpid/interop/connection.properties deleted file mode 100644 index a5fb611dfa..0000000000 --- a/java/integrationtests/src/resources/org/apache/qpid/interop/connection.properties +++ /dev/null @@ -1,20 +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.
-#
-java.naming.factory.initial = org.apache.qpid.jndi.PropertiesFileInitialContextFactory
-connectionfactory.broker = amqp://guest:guest@clientid/?brokerlist='tcp://localhost:5672'
diff --git a/java/integrationtests/src/resources/sustained-log4j.xml b/java/integrationtests/src/resources/sustained-log4j.xml deleted file mode 100644 index c5ab3137bf..0000000000 --- a/java/integrationtests/src/resources/sustained-log4j.xml +++ /dev/null @@ -1,69 +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. - - - --> -<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> -<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> - - - <appender name="FileAppender" class="org.apache.log4j.FileAppender"> - <param name="File" value="${QPID_WORK}/log/${logprefix}qpid${logsuffix}.log"/> - <param name="Append" value="false"/> - - <layout class="org.apache.log4j.PatternLayout"> - <param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/> - </layout> - </appender> - - <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender"> - - <layout class="org.apache.log4j.PatternLayout"> - <param name="ConversionPattern" value="%d %-5p (%F:%L) - %m%n"/> - <!--param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/--> - </layout> - </appender> - - <category name="SustainedTest"> - <priority value="${sustained.level}"/> - </category> - - <category name="org.apache"> - <priority value="warn"/> - </category> - - <category name="org.apache.qpid.interop"> - <priority value="${interop.logging.level}"/> - </category> - - - <category name="org.apache.qpid.sustained"> - <priority value="${amqj.logging.level}"/> - </category> - - <!--category name="org.apache.qpid.server.txn"> - <priority value="debug"/> - </category>--> - - <root> - <priority value="all"/> - <appender-ref ref="STDOUT"/> - <!--appender-ref ref="ArchivingFileAppender"/--> - </root> -</log4j:configuration> diff --git a/java/management/eclipse-plugin/META-INF/MANIFEST.MF b/java/management/eclipse-plugin/META-INF/MANIFEST.MF deleted file mode 100644 index 658fa2cb4c..0000000000 --- a/java/management/eclipse-plugin/META-INF/MANIFEST.MF +++ /dev/null @@ -1,14 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Qpid Management Console Plug-in -Bundle-SymbolicName: org.apache.qpid.management.ui; singleton:=true -Bundle-Version: 0.1.0 -Bundle-Activator: org.apache.qpid.management.ui.Activator -Bundle-Localization: plugin -Require-Bundle: org.eclipse.ui, - org.eclipse.core.runtime, - org.eclipse.ui.forms, - jmxremote.sasl, - org.apache.commons.codec -Eclipse-LazyStart: true -Bundle-Vendor: Apache Software Foundation diff --git a/java/management/eclipse-plugin/README.txt b/java/management/eclipse-plugin/README.txt deleted file mode 100644 index 5325bf27ec..0000000000 --- a/java/management/eclipse-plugin/README.txt +++ /dev/null @@ -1,21 +0,0 @@ - -Running the Qpid Management Console (eclipse-plugin) ----------------------------------------------------- - -To run the management console, set the QPIDMC_HOME environment variable to -qpid management console root directory (e.g. C:/qpidmc)and add $QPIDMC_HOME/bin to your PATH. -Then run the script to launch the management console- -For Windows: ------------- -qpidmc.bat -qpidmc.sh (using cygwin) - -Unix: ------ -qpidmc.sh <operating system> <windowing system> <platform achitecture> -eg. qpidms.sh linux motif x86 -qpidmc_motif.sh -qpidmc_gtk.sh - -Apache confluence page for latest information: -http://cwiki.apache.org/confluence/display/qpid/Qpid+Management+Console diff --git a/java/management/eclipse-plugin/bin/qpidmc.bat b/java/management/eclipse-plugin/bin/qpidmc.bat deleted file mode 100644 index 1f3207f043..0000000000 --- a/java/management/eclipse-plugin/bin/qpidmc.bat +++ /dev/null @@ -1,55 +0,0 @@ -@REM
-@REM Licensed to the Apache Software Foundation (ASF) under one
-@REM or more contributor license agreements. See the NOTICE file
-@REM distributed with this work for additional information
-@REM regarding copyright ownership. The ASF licenses this file
-@REM to you under the Apache License, Version 2.0 (the
-@REM "License"); you may not use this file except in compliance
-@REM with the License. You may obtain a copy of the License at
-@REM
-@REM http://www.apache.org/licenses/LICENSE-2.0
-@REM
-@REM Unless required by applicable law or agreed to in writing,
-@REM software distributed under the License is distributed on an
-@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-@REM KIND, either express or implied. See the License for the
-@REM specific language governing permissions and limitations
-@REM under the License.
-@REM
-
-@echo off
-REM Script to run the Qpid Management Console
-
-rem Guess QPIDMC_HOME if not defined
-set CURRENT_DIR=%cd%
-if not "%QPIDMC_HOME%" == "" goto gotHome
-set QPIDMC_HOME=%CURRENT_DIR%
-echo %QPIDMC_HOME%
-if exist "%QPIDMC_HOME%\bin\qpidmc.bat" goto okHome
-cd ..
-set QPIDMC_HOME=%cd%
-cd %CURRENT_DIR%
-:gotHome
-if exist "%QPIDMC_HOME%\bin\qpidmc.bat" goto okHome
-echo The QPIDMC_HOME environment variable is not defined correctly
-echo This environment variable is needed to run this program
-goto end
-:okHome
-
-if not "%JAVA_HOME%" == "" goto gotJavaHome
-echo The JAVA_HOME environment variable is not defined
-echo This environment variable is needed to run this program
-goto exit
-:gotJavaHome
-if not exist "%JAVA_HOME%\bin\java.exe" goto noJavaHome
-goto okJavaHome
-:noJavaHome
-echo The JAVA_HOME environment variable is not defined correctly
-echo This environment variable is needed to run this program.
-goto exit
-:okJavaHome
-
-rem Slurp the command line arguments. This loop allows for an unlimited number
-rem of agruments (up to the command line limit, anyway).
-
-"%JAVA_HOME%\bin\java" -Xms40m -Xmx256m -Declipse.consoleLog=false -jar %QPIDMC_HOME%\eclipse\startup.jar org.eclipse.core.launcher.Main -launcher %QPIDMC_HOME%\eclipse\eclipse -name "Qpid Management Console" -showsplash 600 -configuration "file:%QPIDMC_HOME%\configuration" -os win32 -ws win32 -arch x86
diff --git a/java/management/eclipse-plugin/bin/qpidmc.sh b/java/management/eclipse-plugin/bin/qpidmc.sh deleted file mode 100755 index 2472545a14..0000000000 --- a/java/management/eclipse-plugin/bin/qpidmc.sh +++ /dev/null @@ -1,64 +0,0 @@ -#!/bin/bash -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - -if [ "$JAVA_HOME" == "" ]; then - echo "The JAVA_HOME environment variable is not defined"; - exit 0; -fi - -if [ "$QPIDMC_HOME" == "" ]; then - echo "The QPIDMC_HOME environment variable is not defined correctly"; - exit 0; -fi - -# Test if we're running on cygwin. -cygwin=false -if [[ "$(uname -a | fgrep Cygwin)" != "" ]]; then - cygwin=true -fi - -if $cygwin; then - QPIDMC_HOME=$(cygpath -w $QPIDMC_HOME) -fi - -os=win32 -ws=win32 -arch=x86 - -##echo $os -##echo $ws -##echo $arch - -## If this is to be run on different platform other than windows then following parameters should be passed -## qpidmc.sh <operating system> <windowing system> <platform achitecture> -## eg. qpidmc.sh linux motif x86 -if [ $# -eq 3 ]; then - os=$1 - ws=$2 - arch=$3 -fi - -if [ $os = "SunOS" ]; then - os="solaris" -elif [ $os = "Linux" ]; then - os="linux" -fi - -"$JAVA_HOME/bin/java" -Xms40m -Xmx256m -Declipse.consoleLog=false -jar $QPIDMC_HOME/eclipse/startup.jar org.eclipse.core.launcher.Main -launcher $QPIDMC_HOME/eclipse/eclipse -name "Qpid Management Console" -showsplash 600 -configuration "file:$QPIDMC_HOME/configuration" -os $os -ws $ws -arch $arch diff --git a/java/management/eclipse-plugin/bin/qpidmc_gtk.sh b/java/management/eclipse-plugin/bin/qpidmc_gtk.sh deleted file mode 100755 index 10b463d63b..0000000000 --- a/java/management/eclipse-plugin/bin/qpidmc_gtk.sh +++ /dev/null @@ -1,24 +0,0 @@ -#!/bin/bash -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - -os=`uname | tr A-Z a-z` -arch=`uname -p` - -$QPIDMC_HOME/bin/qpidmc.sh $os gtk $arch diff --git a/java/management/eclipse-plugin/bin/qpidmc_motif.sh b/java/management/eclipse-plugin/bin/qpidmc_motif.sh deleted file mode 100755 index f53be75d87..0000000000 --- a/java/management/eclipse-plugin/bin/qpidmc_motif.sh +++ /dev/null @@ -1,24 +0,0 @@ -#!/bin/bash -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - -os=`uname | tr A-Z a-z` -arch=`uname -p` - -$QPIDMC_HOME/bin/qpidmc.sh $os motif $arch diff --git a/java/management/eclipse-plugin/build.xml b/java/management/eclipse-plugin/build.xml deleted file mode 100644 index 492783e574..0000000000 --- a/java/management/eclipse-plugin/build.xml +++ /dev/null @@ -1,27 +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. - - - --> -<project name="Eclipse Plugin" default="build"> - - <property name="module.depends" value="broker common"/> - - <import file="../../module.xml"/> - -</project> diff --git a/java/management/eclipse-plugin/icons/Thumbs.db b/java/management/eclipse-plugin/icons/Thumbs.db Binary files differdeleted file mode 100644 index 306bfb2eda..0000000000 --- a/java/management/eclipse-plugin/icons/Thumbs.db +++ /dev/null diff --git a/java/management/eclipse-plugin/icons/add.gif b/java/management/eclipse-plugin/icons/add.gif Binary files differdeleted file mode 100644 index 252d7ebcb8..0000000000 --- a/java/management/eclipse-plugin/icons/add.gif +++ /dev/null diff --git a/java/management/eclipse-plugin/icons/delete.gif b/java/management/eclipse-plugin/icons/delete.gif Binary files differdeleted file mode 100644 index 6f647666d3..0000000000 --- a/java/management/eclipse-plugin/icons/delete.gif +++ /dev/null diff --git a/java/management/eclipse-plugin/icons/icon_ClosedFolder.gif b/java/management/eclipse-plugin/icons/icon_ClosedFolder.gif Binary files differdeleted file mode 100644 index beb6ed134c..0000000000 --- a/java/management/eclipse-plugin/icons/icon_ClosedFolder.gif +++ /dev/null diff --git a/java/management/eclipse-plugin/icons/icon_OpenFolder.gif b/java/management/eclipse-plugin/icons/icon_OpenFolder.gif Binary files differdeleted file mode 100644 index a9c777343c..0000000000 --- a/java/management/eclipse-plugin/icons/icon_OpenFolder.gif +++ /dev/null diff --git a/java/management/eclipse-plugin/icons/mbean_view.png b/java/management/eclipse-plugin/icons/mbean_view.png Binary files differdeleted file mode 100644 index 9871b72bb8..0000000000 --- a/java/management/eclipse-plugin/icons/mbean_view.png +++ /dev/null diff --git a/java/management/eclipse-plugin/icons/notifications.gif b/java/management/eclipse-plugin/icons/notifications.gif Binary files differdeleted file mode 100644 index f1e585bdf7..0000000000 --- a/java/management/eclipse-plugin/icons/notifications.gif +++ /dev/null diff --git a/java/management/eclipse-plugin/icons/qpidConnections.gif b/java/management/eclipse-plugin/icons/qpidConnections.gif Binary files differdeleted file mode 100644 index 89489f11f2..0000000000 --- a/java/management/eclipse-plugin/icons/qpidConnections.gif +++ /dev/null diff --git a/java/management/eclipse-plugin/icons/qpidmc.gif b/java/management/eclipse-plugin/icons/qpidmc.gif Binary files differdeleted file mode 100644 index baf929fbc5..0000000000 --- a/java/management/eclipse-plugin/icons/qpidmc.gif +++ /dev/null diff --git a/java/management/eclipse-plugin/icons/qpidmc16.gif b/java/management/eclipse-plugin/icons/qpidmc16.gif Binary files differdeleted file mode 100644 index 4df535bb9a..0000000000 --- a/java/management/eclipse-plugin/icons/qpidmc16.gif +++ /dev/null diff --git a/java/management/eclipse-plugin/icons/qpidmc32.bmp b/java/management/eclipse-plugin/icons/qpidmc32.bmp Binary files differdeleted file mode 100644 index e42ce01dff..0000000000 --- a/java/management/eclipse-plugin/icons/qpidmc32.bmp +++ /dev/null diff --git a/java/management/eclipse-plugin/icons/qpidmc32.gif b/java/management/eclipse-plugin/icons/qpidmc32.gif Binary files differdeleted file mode 100644 index e42ce01dff..0000000000 --- a/java/management/eclipse-plugin/icons/qpidmc32.gif +++ /dev/null diff --git a/java/management/eclipse-plugin/icons/reconnect.gif b/java/management/eclipse-plugin/icons/reconnect.gif Binary files differdeleted file mode 100644 index e2f8c3e1fe..0000000000 --- a/java/management/eclipse-plugin/icons/reconnect.gif +++ /dev/null diff --git a/java/management/eclipse-plugin/icons/refresh.gif b/java/management/eclipse-plugin/icons/refresh.gif Binary files differdeleted file mode 100644 index a063c230ac..0000000000 --- a/java/management/eclipse-plugin/icons/refresh.gif +++ /dev/null diff --git a/java/management/eclipse-plugin/icons/splash.bmp b/java/management/eclipse-plugin/icons/splash.bmp Binary files differdeleted file mode 100644 index b528a508c5..0000000000 --- a/java/management/eclipse-plugin/icons/splash.bmp +++ /dev/null diff --git a/java/management/eclipse-plugin/icons/stop.gif b/java/management/eclipse-plugin/icons/stop.gif Binary files differdeleted file mode 100644 index dc47edf069..0000000000 --- a/java/management/eclipse-plugin/icons/stop.gif +++ /dev/null diff --git a/java/management/eclipse-plugin/plugin.properties b/java/management/eclipse-plugin/plugin.properties deleted file mode 100644 index 8507441886..0000000000 --- a/java/management/eclipse-plugin/plugin.properties +++ /dev/null @@ -1,20 +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. -############################################################################### -pluginName = Qpid Management Console Plug-in -providerName = Apache Software Foundation
\ No newline at end of file diff --git a/java/management/eclipse-plugin/plugin.xml b/java/management/eclipse-plugin/plugin.xml deleted file mode 100644 index 5774859b47..0000000000 --- a/java/management/eclipse-plugin/plugin.xml +++ /dev/null @@ -1,223 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<?eclipse version="3.2"?> -<!-- - Licensed to the Apache Software Foundation (ASF) under one - or more contributor license agreements. See the NOTICE file - distributed with this work for additional information - regarding copyright ownership. The ASF licenses this file - to you under the Apache License, Version 2.0 (the - "License"); you may not use this file except in compliance - with the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the - specific language governing permissions and limitations - under the License. ---> -<plugin> - - <extension - id="application" - point="org.eclipse.core.runtime.applications"> - <application> - <run - class="org.apache.qpid.management.ui.Application"> - </run> - </application> - </extension> - <extension - point="org.eclipse.ui.perspectives"> - <perspective - name="qpid.management.perspective" - class="org.apache.qpid.management.ui.Perspective" - id="org.apache.qpid.management.ui.perspective"> - </perspective> - </extension> - <extension - point="org.eclipse.ui.views"> - <category - id="org.apache.qpid.management.ui.viewcategory" - name="Qpid Management Console"/> - <view - allowMultiple="false" - category="org.apache.qpid.management.ui.viewcategory" - class="org.apache.qpid.management.ui.views.NavigationView" - icon="icons/qpidConnections.gif" - id="org.apache.qpid.management.ui.navigationView" - name="Qpid Connections"> - </view> - <view - allowMultiple="false" - category="org.apache.qpid.management.ui.viewcategory" - class="org.apache.qpid.management.ui.views.MBeanView" - icon="icons/mbean_view.png" - id="org.apache.qpid.management.ui.mbeanView" - name="Qpid Management"> - </view> - </extension> - <extension - point="org.eclipse.ui.commands"> - <category - name="qpid.manager.commands" - id="org.apache.qpid.management.ui.category"> - </category> - <command - name="New Connection" - description="Created a new Qpid server connection" - categoryId="org.apache.qpid.management.ui.category" - id="org.apache.qpid.management.ui.actions.cmd_add"> - </command> - <command - categoryId="org.apache.qpid.management.ui.category" - description="Reconnect the Qpid server connection" - id="org.apache.qpid.management.ui.actions.cmd_reconnect" - name="Reconnect"/> - <command - categoryId="org.apache.qpid.management.ui.category" - description="Disconnects the Qpid server connection" - id="org.apache.qpid.management.ui.actions.cmd_disconnect" - name="Disconnect"/> - <command - categoryId="org.apache.qpid.management.ui.category" - description="Removes the server from management console" - id="org.apache.qpid.management.ui.actions.cmd_remove" - name="Remove Connection"/> - <command - categoryId="org.apache.qpid.management.ui.category" - description="refreshes the views" - id="org.apache.qpid.management.ui.actions.cmd_refresh" - name="Refresh"/> - <command - categoryId="org.apache.qpid.management.ui.category" - description="pops up the window for editing selected attribute" - id="org.apache.qpid.management.ui.actions.cmd_editAttribute" - name="Edit Attribute"/> - <command - categoryId="org.apache.qpid.management.ui.category" - description="About Qpid Management Console" - id="qpidmc.about" - name="About"/> - </extension> - <extension - point="org.eclipse.ui.bindings"> - <key - commandId="org.apache.qpid.management.ui.actions.cmd_add" - schemeId="org.eclipse.ui.defaultAcceleratorConfiguration" - sequence="CTRL+Alt+N"> - </key> - <key - commandId="org.apache.qpid.management.ui.actions.cmd_reconnect" - schemeId="org.eclipse.ui.defaultAcceleratorConfiguration" - sequence="CTRL+Alt+C"/> - <key - commandId="org.apache.qpid.management.ui.actions.cmd_disconnect" - schemeId="org.eclipse.ui.defaultAcceleratorConfiguration" - sequence="CTRL+Alt+D"> - </key> - <key - commandId="org.apache.qpid.management.ui.actions.cmd_remove" - schemeId="org.eclipse.ui.defaultAcceleratorConfiguration" - sequence="CTRL+Alt+R"/> - <key - commandId="org.apache.qpid.management.ui.actions.cmd_refresh" - schemeId="org.eclipse.ui.defaultAcceleratorConfiguration" - sequence="CTRL+Alt+F5"/> - <key - commandId="org.apache.qpid.management.ui.actions.cmd_editAttribute" - schemeId="org.eclipse.ui.defaultAcceleratorConfiguration" - sequence="CTRL+Alt+E"/> - <key - commandId="org.eclipse.ui.file.exit" - schemeId="org.eclipse.ui.defaultAcceleratorConfiguration" - sequence="CTRL+Alt+X"> - </key> - </extension> - - <extension - id="product" - point="org.eclipse.core.runtime.products"> - <product - application="org.apache.qpid.management.ui.application" - name="Qpid Management Console"> - <property - name="windowImages" - value="icons/qpidmc16.gif,icons/qpidmc32.gif"> - </property> - <property - name="aboutText" - value="Qpid Management Console"/> - </product> - </extension> - <extension - point="org.eclipse.ui.actionSets"> - <actionSet - id="org.apache.qpid.management.ui.actionSet" - label="Qpid Action Set" - visible="true"> - <menu - id="qpidmanager" - label="&Qpid Manager"> - <separator name="qpidActionsGroup"/> - </menu> - <action - class="org.apache.qpid.management.ui.actions.EditAttribute" - definitionId="org.apache.qpid.management.ui.actions.cmd_editAttribute" - id="org.apache.qpid.management.ui.actions.editAttribute" - label="Edit Attribute" - menubarPath="qpidmanager/mbeanactions" - style="push" - tooltip="Edit Attribute"/> - <action - class="org.apache.qpid.management.ui.actions.Refresh" - definitionId="org.apache.qpid.management.ui.actions.cmd_refresh" - icon="icons/refresh.gif" - id="org.apache.qpid.management.ui.actions.refresh" - label="Refresh" - menubarPath="qpidmanager/additions" - style="push" - toolbarPath="qpidActionsGroup" - tooltip="Refresh"/> - <action - class="org.apache.qpid.management.ui.actions.RemoveServer" - definitionId="org.apache.qpid.management.ui.actions.cmd_remove" - icon="icons/delete.gif" - id="org.apache.qpid.management.ui.actions.remove" - label="Remove Connection" - menubarPath="qpidmanager/additions" - style="push" - toolbarPath="qpidActionsGroup"/> - <action - class="org.apache.qpid.management.ui.actions.CloseConnection" - definitionId="org.apache.qpid.management.ui.actions.cmd_disconnect" - icon="icons/stop.gif" - id="org.apache.qpid.management.ui.disconnect" - label="Disconnect" - menubarPath="qpidmanager/additions" - toolbarPath="qpidActionsGroup" - tooltip="Disconnect"/> - <action - class="org.apache.qpid.management.ui.actions.ReconnectServer" - definitionId="org.apache.qpid.management.ui.actions.cmd_reconnect" - icon="icons/reconnect.gif" - id="org.apache.qpid.management.ui.reconnect" - label="Reconnect" - menubarPath="qpidmanager/additions" - toolbarPath="qpidActionsGroup" - tooltip="Reconnect"/> - <action - class="org.apache.qpid.management.ui.actions.AddServer" - definitionId="org.apache.qpid.management.ui.actions.cmd_add" - icon="icons/add.gif" - id="org.apache.qpid.management.ui.add" - label="New Connection" - menubarPath="qpidmanager/additions" - toolbarPath="qpidActionsGroup" - tooltip="New Connection"/> - </actionSet> - </extension> - -</plugin> diff --git a/java/management/eclipse-plugin/pom.xml b/java/management/eclipse-plugin/pom.xml deleted file mode 100644 index 0c220104f8..0000000000 --- a/java/management/eclipse-plugin/pom.xml +++ /dev/null @@ -1,257 +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. - --> -<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> - <groupId>org.apache.qpid.management</groupId> - <artifactId>org.apache.qpid.management.ui</artifactId> - <packaging>jar</packaging> - <version>1.0-incubating-M3-SNAPSHOT</version> - <name>Qpid Management</name> - - <parent> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid</artifactId> - <version>1.0-incubating-M3-SNAPSHOT</version> - <relativePath>../../pom.xml</relativePath> - </parent> - - <properties> - <topDirectoryLocation>../..</topDirectoryLocation> - </properties> - - <repositories> - <repository> - <id>repo1.maven.org</id> - <name>Maven eclipse Repository</name> - <url>http://repo1.maven.org/eclipse</url> - </repository> - <repository> - <id>apache.snapshots</id> - <name>Apache SNAPSHOT Repository</name> - <url>http://people.apache.org/repo/m2-snapshot-repository</url> - <snapshots> - <enabled>true</enabled> - </snapshots> - </repository> - </repositories> - - <dependencies> - <dependency> - <groupId>commons-codec</groupId> - <artifactId>commons-codec</artifactId> - <version>1.3</version> - <scope>compile</scope> - </dependency> - <dependency> - <groupId>com.ibm.icu</groupId> - <artifactId>com.ibm.icu</artifactId> - <version>3.4.4</version> - <scope>compile</scope> - </dependency> - <dependency> - <groupId>org.eclipse.jface</groupId> - <artifactId>org.eclipse.jface</artifactId> - <version>3.2.0</version> - <scope>compile</scope> - </dependency> - <dependency> - <groupId>org.eclipse.core</groupId> - <artifactId>org.eclipse.core.commands</artifactId> - <version>3.2.0</version> - <scope>compile</scope> - </dependency> - <dependency> - <groupId>org.eclipse.core</groupId> - <artifactId>org.eclipse.core.contenttype</artifactId> - <version>3.2.0</version> - <scope>compile</scope> - </dependency> - <dependency> - <groupId>org.eclipse.core</groupId> - <artifactId>org.eclipse.core.expressions</artifactId> - <version>3.2.0</version> - <scope>compile</scope> - </dependency> - <dependency> - <groupId>org.eclipse.core</groupId> - <artifactId>org.eclipse.core.jobs</artifactId> - <version>3.2.0</version> - <scope>compile</scope> - </dependency> - <dependency> - <groupId>org.eclipse.core</groupId> - <artifactId>org.eclipse.core.runtime</artifactId> - <version>3.2.0</version> - <scope>compile</scope> - </dependency> - <dependency> - <groupId>org.eclipse.core</groupId> - <artifactId>org.eclipse.core.runtime.compatibility.auth</artifactId> - <version>3.2.0</version> - <scope>compile</scope> - </dependency> - <dependency> - <groupId>org.eclipse.core</groupId> - <artifactId>org.eclipse.core.runtime.compatibility.registry</artifactId> - <version>3.2.0</version> - <scope>runtime</scope> - </dependency> - <dependency> - <groupId>org.eclipse.equinox</groupId> - <artifactId>org.eclipse.equinox.common</artifactId> - <version>3.2.0</version> - <scope>compile</scope> - </dependency> - <dependency> - <groupId>org.eclipse.equinox</groupId> - <artifactId>org.eclipse.equinox.preferences</artifactId> - <version>3.2.0</version> - <scope>compile</scope> - </dependency> - <dependency> - <groupId>org.eclipse.equinox</groupId> - <artifactId>org.eclipse.equinox.registry</artifactId> - <version>3.2.0</version> - <scope>compile</scope> - </dependency> - <dependency> - <groupId>org.eclipse.help</groupId> - <artifactId>org.eclipse.help</artifactId> - <version>3.2.0</version> - <scope>compile</scope> - </dependency> - <dependency> - <groupId>org.eclipse.osgi</groupId> - <artifactId>org.eclipse.osgi</artifactId> - <version>3.2.0</version> - <scope>compile</scope> - </dependency> - <dependency> - <groupId>org.eclipse.swt</groupId> - <artifactId>org.eclipse.swt.win32.win32.x86</artifactId> - <version>3.2.0</version> - <scope>compile</scope> - </dependency> - <dependency> - <groupId>org.eclipse.swt</groupId> - <artifactId>org.eclipse.swt</artifactId> - <version>3.2.0</version> - <scope>compile</scope> - </dependency> - <dependency> - <groupId>org.eclipse.ui</groupId> - <artifactId>org.eclipse.ui.forms</artifactId> - <version>3.2.0</version> - <scope>compile</scope> - </dependency> - <dependency> - <groupId>org.eclipse.ui</groupId> - <artifactId>org.eclipse.ui.workbench</artifactId> - <version>3.2.1</version> - <scope>compile</scope> - </dependency> - <dependency> - <groupId>org.eclipse.ui</groupId> - <artifactId>org.eclipse.ui</artifactId> - <version>3.2.0</version> - <scope>compile</scope> - </dependency> - - <!-- Test Dependencies --> - <dependency> - <groupId>org.slf4j</groupId> - <artifactId>slf4j-log4j12</artifactId> - <version>1.4.0</version> - <scope>test</scope> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker</artifactId> - <scope>test</scope> - </dependency> - - <dependency> - <groupId>junit</groupId> - <artifactId>junit</artifactId> - <scope>test</scope> - </dependency> - - </dependencies> - - <build> - <resources> - <resource> - <directory>icons/</directory> - <targetPath>icons/</targetPath> - <includes> - <include>**</include> - </includes> - </resource> - <resource> - <directory>icons/</directory> - <targetPath>/</targetPath> - <includes> - <include>splash.bmp</include> - </includes> - </resource> - <resource> - <directory>${basedir}</directory> - <targetPath>/</targetPath> - <includes> - <include>plugin.xml</include> - <include>plugin.properties</include> - </includes> - </resource> - </resources> - <plugins> - <!-- - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-antrun-plugin</artifactId> - </plugin> - --> - - <!-- This is required to identify the JAR to eclipse as a plugin --> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-jar-plugin</artifactId> - <configuration> - <archive> - <manifestFile>META-INF/MANIFEST.MF</manifestFile> - </archive> - <finalName>${artifactId}_${version}</finalName> - </configuration> - </plugin> - - <!-- - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-surefire-plugin</artifactId> - <configuration> - <skip>false</skip> - </configuration> - </plugin> - --> - </plugins> - </build> - -</project> diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Activator.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Activator.java deleted file mode 100644 index 5eab267c28..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Activator.java +++ /dev/null @@ -1,84 +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.management.ui; - -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.ui.plugin.AbstractUIPlugin; -import org.osgi.framework.BundleContext; - -/** - * The activator class controls the plug-in life cycle - * @author Bhupendra Bhardwaj - */ -public class Activator extends AbstractUIPlugin -{ - // The plug-in ID - public static final String PLUGIN_ID = "org.apache.qpid.management.ui"; - - // The shared instance - private static Activator plugin; - - /** - * The constructor - */ - public Activator() - { - plugin = this; - } - - /* - * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) - */ - public void start(BundleContext context) throws Exception - { - super.start(context); - } - - /* - * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) - */ - public void stop(BundleContext context) throws Exception - { - plugin = null; - super.stop(context); - } - - /** - * Returns the shared instance - * - * @return the shared instance - */ - public static Activator getDefault() - { - return plugin; - } - - /** - * Returns an image descriptor for the image file at the given plug-in relative path - * - * @param path the path - * @return the image descriptor - */ - public static ImageDescriptor getImageDescriptor(String path) - { - return imageDescriptorFromPlugin(PLUGIN_ID, path); - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Application.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Application.java deleted file mode 100644 index a1c4b7ddb0..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Application.java +++ /dev/null @@ -1,63 +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.management.ui; - -import org.eclipse.core.runtime.IPlatformRunnable; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.PlatformUI; - -/** - * This class controls all aspects of the application's execution - * @author Bhupendra Bhardwaj - */ -public class Application implements IPlatformRunnable -{ - static Shell shell = null; - - /* - * The call to createAndRunWorkbench will not return until the workbench is closed. - * The SWT event loop and other low-level logistics are handled inside this method. - * @see org.eclipse.core.runtime.IPlatformRunnable#run(java.lang.Object) - */ - public Object run(Object args) throws Exception - { - Display display = PlatformUI.createDisplay(); - try - { - int returnCode = PlatformUI.createAndRunWorkbench(display, - new ApplicationWorkbenchAdvisor()); - if (returnCode == PlatformUI.RETURN_RESTART) - { - return IPlatformRunnable.EXIT_RESTART; - } - return IPlatformRunnable.EXIT_OK; - } finally - { - display.dispose(); - } - } - - static Shell getActiveShell() - { - return shell; - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApplicationActionBarAdvisor.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApplicationActionBarAdvisor.java deleted file mode 100644 index b5c1b5074a..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApplicationActionBarAdvisor.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.management.ui; - -import org.apache.qpid.management.ui.actions.VersionAction; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.GroupMarker; -import org.eclipse.jface.action.ICoolBarManager; -import org.eclipse.jface.action.IMenuManager; -import org.eclipse.jface.action.MenuManager; -import org.eclipse.jface.action.Separator; -import org.eclipse.ui.IWorkbenchActionConstants; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.actions.ActionFactory; -import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction; -import org.eclipse.ui.application.ActionBarAdvisor; -import org.eclipse.ui.application.IActionBarConfigurer; - -/** - * An action bar advisor is responsible for creating, adding, and disposing of the - * actions added to a workbench window. Each window will be populated with - * new actions. - */ -public class ApplicationActionBarAdvisor extends ActionBarAdvisor -{ - - // Actions - important to allocate these only in makeActions, and then use them - // in the fill methods. This ensures that the actions aren't recreated - // when fillActionBars is called with FILL_PROXY. - private IWorkbenchAction exitAction; - private Action _aboutAction; - - public ApplicationActionBarAdvisor(IActionBarConfigurer configurer) - { - super(configurer); - } - - protected void makeActions(final IWorkbenchWindow window) - { - // Creates the actions and registers them. - // Registering is needed to ensure that key bindings work. - // The corresponding commands keybindings are defined in the plugin.xml file. - // Registering also provides automatic disposal of the actions when - // the window is closed. - - exitAction = ActionFactory.QUIT.create(window); - register(exitAction); - - _aboutAction = new VersionAction(window); - register(_aboutAction); - } - - - protected void fillMenuBar(IMenuManager menuBar) - { - MenuManager fileMenu = new MenuManager("&Qpid Manager", "qpidmanager"); - MenuManager helpMenu = new MenuManager("&Help", IWorkbenchActionConstants.M_HELP); - - menuBar.add(fileMenu); - // Add a group marker indicating where action set menus will appear. - menuBar.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); - menuBar.add(helpMenu); - - fileMenu.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); - fileMenu.add(new Separator()); - fileMenu.add(new GroupMarker("mbeanactions")); - fileMenu.add(new Separator()); - fileMenu.add(exitAction); - - // Help - helpMenu.add(_aboutAction); - } - - protected void fillCoolBar(ICoolBarManager coolBar) - { - - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApplicationRegistry.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApplicationRegistry.java deleted file mode 100644 index 0ad85dbf33..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApplicationRegistry.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.management.ui; - -import java.util.HashMap; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - -import org.eclipse.jface.resource.FontRegistry; -import org.eclipse.jface.resource.ImageRegistry; -import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.Font; -import org.eclipse.swt.graphics.FontData; -import org.eclipse.swt.graphics.Image; -import org.eclipse.ui.ISharedImages; -import org.eclipse.ui.PlatformUI; - -/** - * Main Application Registry, which contains shared resources and map to all connected servers. - * @author Bhupendra Bhardwaj - */ -public abstract class ApplicationRegistry -{ - private static ImageRegistry imageRegistry = new ImageRegistry(); - private static FontRegistry fontRegistry = new FontRegistry(); - public static final boolean debug = Boolean.getBoolean("eclipse.consoleLog"); - public static final String securityMechanism = System.getProperty("security", null); - public static final String connectorClass = System.getProperty("jmxconnector"); - public static final long timeout = Long.parseLong(System.getProperty("timeout", "5000")); - - static - { - imageRegistry.put(Constants.CONSOLE_IMAGE, - org.apache.qpid.management.ui.Activator.getImageDescriptor("/icons/qpidmc.gif")); - imageRegistry.put(Constants.CLOSED_FOLDER_IMAGE, - org.apache.qpid.management.ui.Activator.getImageDescriptor("/icons/icon_ClosedFolder.gif")); - imageRegistry.put(Constants.OPEN_FOLDER_IMAGE, - PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER)); - imageRegistry.put(Constants.MBEAN_IMAGE, - PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT)); - imageRegistry.put(Constants.NOTIFICATION_IMAGE, - org.apache.qpid.management.ui.Activator.getImageDescriptor("/icons/notifications.gif")); - } - - static - { - fontRegistry.put(Constants.FONT_BUTTON, new FontData[]{new FontData("Arial", 8, SWT.BOLD)} ); - fontRegistry.put(Constants.FONT_BOLD, new FontData[]{new FontData("Bold", 9, SWT.BOLD)} ); - fontRegistry.put(Constants.FONT_ITALIC, new FontData[]{new FontData("Italic", 9, SWT.ITALIC)} ); - fontRegistry.put(Constants.FONT_TABLE_CELL, new FontData[]{new FontData("Tablecell", 8, SWT.NORMAL)} ); - fontRegistry.put(Constants.FONT_NORMAL, new FontData[]{new FontData("Normal", 9, SWT.NORMAL)} ); - } - - /* - * This maps all the managed servers to the respective server registry. - * Server can be JMX MBeanServer or a C++ server - */ - private static HashMap<ManagedServer, ServerRegistry> _serverRegistryMap = new HashMap<ManagedServer, ServerRegistry>(); - - // This map gets updated when a server connection closes. - private static List<ManagedServer> _closedServerList = new CopyOnWriteArrayList<ManagedServer>(); - - public static Image getImage(String key) - { - return imageRegistry.get(key); - } - - public static Font getFont(String key) - { - return fontRegistry.get(key); - } - - public static void addServer(ManagedServer server, ServerRegistry registry) - { - _serverRegistryMap.put(server, registry); - } - - public static void removeServer(ManagedServer server) - { - _serverRegistryMap.remove(server); - } - - public static ServerRegistry getServerRegistry(ManagedServer server) - { - return _serverRegistryMap.get(server); - } - - public static ServerRegistry getServerRegistry(ManagedBean mbean) - { - ManagedServer server = mbean.getServer(); - return getServerRegistry(server); - } - - public static boolean isServerConnected(ManagedServer server) - { - return _serverRegistryMap.containsKey(server); - } - - // remove the server from the registry - public static void serverConnectionClosed(ManagedServer server) - { - _closedServerList.add(server); - removeServer(server); - } - - /* - * Returns the lis of closed servers. The Thread in GUI, which keeps checking for closed connection - * will check this and will remove the server links from the GUI. - */ - public static List<ManagedServer> getClosedServers() - { - if (_closedServerList.isEmpty()) - return null; - - List<ManagedServer> list = new CopyOnWriteArrayList<ManagedServer>(_closedServerList); - _closedServerList.clear(); - return list; - } - - public static String getSecurityMechanism() - { - return securityMechanism; - } - - public static String getJMXConnectorClass() - { - return connectorClass; - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApplicationWorkbenchAdvisor.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApplicationWorkbenchAdvisor.java deleted file mode 100644 index a46fa870e4..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApplicationWorkbenchAdvisor.java +++ /dev/null @@ -1,46 +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.management.ui; - -import org.eclipse.ui.application.IWorkbenchWindowConfigurer; -import org.eclipse.ui.application.WorkbenchAdvisor; -import org.eclipse.ui.application.WorkbenchWindowAdvisor; - -/** - * This workbench advisor creates the window advisor, and specifies - * the perspective id for the initial window. - */ -public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor -{ - public static final String PERSPECTIVE_ID = "org.apache.qpid.management.ui.perspective"; - - public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) - { - return new ApplicationWorkbenchWindowAdvisor(configurer); - } - - - public String getInitialWindowPerspectiveId() - { - return PERSPECTIVE_ID; - } - -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApplicationWorkbenchWindowAdvisor.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApplicationWorkbenchWindowAdvisor.java deleted file mode 100644 index e3aedef28e..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ApplicationWorkbenchWindowAdvisor.java +++ /dev/null @@ -1,65 +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.management.ui; - -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.application.ActionBarAdvisor; -import org.eclipse.ui.application.IActionBarConfigurer; -import org.eclipse.ui.application.IWorkbenchWindowConfigurer; -import org.eclipse.ui.application.WorkbenchWindowAdvisor; - -/** - * - * @author Bhupendra Bhardwaj - */ -public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor -{ - public ApplicationWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) - { - super(configurer); - } - - public ActionBarAdvisor createActionBarAdvisor(IActionBarConfigurer configurer) - { - return new ApplicationActionBarAdvisor(configurer); - } - - public void preWindowOpen() - { - IWorkbenchWindowConfigurer configurer = getWindowConfigurer(); - int x = Display.getDefault().getBounds().width; - int y = Display.getDefault().getBounds().height; - configurer.setInitialSize(new Point(9*x/10, 8*y/10)); - configurer.setShowCoolBar(true); - configurer.setShowStatusLine(false); - - configurer.setTitle(Constants.APPLICATION_NAME); - } - - public void postWindowCreate() - { - IWorkbenchWindowConfigurer configurer = getWindowConfigurer(); - Shell shell = configurer.getWindow().getShell(); - shell.setImage(ApplicationRegistry.getImage(Constants.CONSOLE_IMAGE)); - } -}
\ No newline at end of file diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Constants.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Constants.java deleted file mode 100644 index d6f895b64a..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Constants.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.management.ui; - -/** - * Contains constants for the application - * @author Bhupendra Bhardwaj - * - */ -public class Constants -{ - public final static String APPLICATION_NAME = "Qpid Management Console"; - - public final static String ACTION_REMOVE_MBEANNODE = "Remove from list"; - public final static String VALUE = "value"; - public final static String TYPE = "type"; - public final static String NODE_TYPE_SERVER = "server"; - public final static String NODE_TYPE_DOMAIN = "domain"; - public final static String NODE_TYPE_MBEANTYPE = "mbeantype"; - // currently used only for virtual host instances, but will work as general also - public final static String NODE_TYPE_TYPEINSTANCE = "mbeantype_instance"; - public final static String MBEAN = "mbean"; - public final static String ATTRIBUTE = "Attribute"; - public final static String ATTRIBUTES = "Attributes"; - public final static String NOTIFICATIONS = "Notifications"; - public final static String RESULT = "Result"; - public final static String VIRTUAL_HOST = "VirtualHost"; - public final static String DEFAULT_VH = "Default"; - public final static String DEFAULT_USERNAME = "guest"; - public final static String DEFAULT_PASSWORD = "guest"; - - public final static String USERNAME = "Username"; - public final static String PASSWORD = "Password"; - - // Attributes and operations are used to customize the GUI for Qpid. If these are changes in the - // Qpid server, then these should be updated accordingly - public final static String ATTRIBUTE_QUEUE_OWNER = "owner"; - public final static String ATTRIBUTE_QUEUE_DEPTH = "QueueDepth"; - public final static String ATTRIBUTE_QUEUE_CONSUMERCOUNT = "ActiveConsumerCount"; - public final static String OPERATION_CREATE_QUEUE = "createNewQueue"; - public final static String OPERATION_CREATE_BINDING = "createNewBinding"; - public final static String OPERATION_MOVE_MESSAGES = "moveMessages"; - - public final static String OPERATION_CREATEUSER = "createUser"; - public final static String OPERATION_DELETEUSER = "deleteUser"; - public final static String OPERATION_VIEWUSERS = "viewUsers"; - public final static String OPERATION_PARAM_USERNAME = "username"; - - public final static String OPERATION_SUCCESSFUL = "Operation successful"; - public final static String OPERATION_UNSUCCESSFUL = "Operation unsuccessful"; - - public final static String ALL = "All"; - - public final static String NAVIGATION_ROOT = "Qpid Connections"; - public final static String DESCRIPTION = " Description"; - - public final static String ADMIN_MBEAN_TYPE = "UserManagement"; - public final static String QUEUE = "Queue"; - public final static String CONNECTION ="Connection"; - public final static String EXCHANGE = "Exchange"; - public final static String EXCHANGE_TYPE = "ExchangeType"; - public final static String[] EXCHANGE_TYPE_VALUES = {"direct", "fanout", "headers", "topic"}; - public final static String[] BOOLEAN_TYPE_VALUES = {"false", "true"}; - public final static String[] ATTRIBUTE_TABLE_TITLES = {"Attribute Name", "Value"}; - public static final String[] CONNECTION_PROTOCOLS ={"RMI"}; - public static final String DEFAULT_PROTOCOL = CONNECTION_PROTOCOLS[0]; - - public final static String ACTION_ADDSERVER = "New Connection"; - public final static String ACTION_RECONNECT = "Reconnect"; - public final static String ACTION_CLOSE = "Close Connection"; - public final static String ACTION_EDITATTRIBUTE = "Edit Attribute"; - public final static String ACTION_LOGIN = "Login"; - - public final static String QUEUE_SORT_BY_NAME = "Queue Name"; - public final static String QUEUE_SORT_BY_DEPTH = "Queue Depth"; - public final static String QUEUE_SORT_BY_CONSUMERCOUNT = "Consumer Count"; - public final static String QUEUE_SHOW_TEMP_QUEUES= "show temporary queues"; - - public final static String SUBSCRIBE_BUTTON = "Subscribe"; - public final static String UNSUBSCRIBE_BUTTON = "Unsubscribe"; - - public final static String CONSOLE_IMAGE = "ConsoelImage"; - public final static String CLOSED_FOLDER_IMAGE = "ClosedFolderImage"; - public final static String OPEN_FOLDER_IMAGE = "OpenFolderImage"; - public final static String MBEAN_IMAGE = "MBeanImage"; - public final static String NOTIFICATION_IMAGE = "NotificationImage"; - - public final static String FONT_BUTTON = "ButtonFont"; - public final static String FONT_BOLD = "BoldFont"; - public final static String FONT_ITALIC = "ItalicFont"; - public final static String FONT_TABLE_CELL = "TableCellFont"; - public final static String FONT_NORMAL = "Normal"; - - public final static String BUTTON_DETAILS = "Details"; - public final static String BUTTON_EDIT_ATTRIBUTE = "Edit Attribute"; - public final static String BUTTON_REFRESH = "Refresh"; - public final static String BUTTON_GRAPH = "Graph"; - public final static int TIMER_INTERVAL = 5000; - public final static String BUTTON_EXECUTE = "Execute"; - public final static String BUTTON_CLEAR = "Clear"; - public final static String BUTTON_CONNECT = "Connect"; - public final static String BUTTON_CANCEL = "Cancel"; - public final static String BUTTON_UPDATE = "Update"; - - - public final static int OPERATION_IMPACT_INFO = 0; - public final static int OPERATION_IMPACT_ACTION = 1; - public final static int OPERATION_IMPACT_ACTIONINFO = 2; - public final static int OPERATION_IMPACT_UNKNOWN = 3; - - public final static String ERROR_SERVER_CONNECTION = "Server Connection Failed"; - public final static String INFO_PROTOCOL = "Please select the protocol"; - public final static String INFO_HOST_ADDRESS = "Please enter the host address"; - public final static String INFO_HOST_PORT = "Please enter the port number"; - public final static String INFO_USERNAME = "Please enter the " + USERNAME; - public final static String INFO_PASSWORD = "Please enter the " + PASSWORD; - - public final static String MECH_CRAMMD5 = "CRAM-MD5"; - public final static String MECH_PLAIN = "PLAIN"; - public final static String SASL_CRAMMD5 = "SASL/CRAM-MD5"; - public final static String SASL_PLAIN = "SASL/PLAIN"; -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ManagedBean.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ManagedBean.java deleted file mode 100644 index 31825e925d..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ManagedBean.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.management.ui; - -import static org.apache.qpid.management.ui.Constants.*; -import java.util.HashMap; - -/** - * Class representing a managed bean on the managed server - * @author Bhupendra Bhardwaj - * - */ -public abstract class ManagedBean extends ManagedObject -{ - private String _uniqueName = ""; - private String _domain = ""; - private String _type = ""; - private String _virtualHostName = null; - private ManagedServer _server = null; - private HashMap _properties = null; - - public String getProperty(String key) - { - return (String)_properties.get(key); - } - - public HashMap getProperties() - { - return _properties; - } - public void setProperties(HashMap properties) - { - this._properties = properties; - setName(getProperty("name")); - setType(getProperty("type")); - _virtualHostName = getProperty(VIRTUAL_HOST); - } - public String getDomain() - { - return _domain; - } - public void setDomain(String domain) - { - this._domain = domain; - } - - public ManagedServer getServer() - { - return _server; - } - public void setServer(ManagedServer server) - { - this._server = server; - } - public String getType() - { - return _type; - } - public void setType(String type) - { - this._type = type; - } - public String getUniqueName() - { - return _uniqueName; - } - public void setUniqueName(String uniqueName) - { - this._uniqueName = uniqueName; - } - - public String getVirtualHostName() - { - // To make it work with the broker with no virtual host implementation - return _virtualHostName == null ? DEFAULT_VH : _virtualHostName; - } - - /** - * Returns mbean instance name. MBeans which have only one instance, the type attribute will be returned - * @return - */ - public String getInstanceName() - { - if (getName() != null) - return getName(); - else - return getType(); - } - - public boolean isQueue() - { - return _type.endsWith(QUEUE); - } - - public boolean isConnection() - { - return _type.endsWith(CONNECTION); - } - - public boolean isExchange() - { - return _type.endsWith(EXCHANGE); - } - - public boolean isTempQueue() - { - return (isQueue() && getName().startsWith("tmp_")); - } - - public boolean isAdmin() - { - return _type.endsWith(ADMIN_MBEAN_TYPE); - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ManagedObject.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ManagedObject.java deleted file mode 100644 index 96e0fa46c6..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ManagedObject.java +++ /dev/null @@ -1,40 +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.management.ui; - -/** - * Abstract class representing a managed object - * @author Bhupendra Bhardwaj - */ -public abstract class ManagedObject -{ - private String _name; - - public String getName() - { - return _name; - } - - public void setName(String name) - { - this._name = name; - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ManagedServer.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ManagedServer.java deleted file mode 100644 index 480fdb429a..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ManagedServer.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.management.ui; - -import static org.apache.qpid.management.ui.Constants.DEFAULT_PROTOCOL; -/** - * Class representing a server being managed eg. MBeanServer - * @author Bhupendra Bhardwaj - */ -public class ManagedServer extends ManagedObject -{ - private String _host; - private int _port; - private String _url; - private String _domain; - private String _user; - private String _password; - private String _protocol = DEFAULT_PROTOCOL; - - public ManagedServer(String host, int port, String domain) - { - this(host, port, domain, null, null); - } - - public ManagedServer(String host, int port, String domain, String user, String password) - { - setName(host + ":" + port); - _host = host; - _port = port; - _domain = domain; - _url = getRMIURL(host, port); - _user = user; - _password = password; - } - - public String getDomain() - { - return _domain; - } - - public String getHost() - { - return _host; - } - - public int getPort() - { - return _port; - } - - public String getUrl() - { - return _url; - } - - public String getProtocol() - { - return _protocol; - } - - public String getPassword() - { - return _password; - } - - public void setPassword(String password) - { - _password = password; - } - - public String getUser() - { - return _user; - } - - public void setUser(String user) - { - _user = user; - } - - private String getRMIURL(String host, int port) - { - return "service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi"; - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Perspective.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Perspective.java deleted file mode 100644 index f93200cadf..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Perspective.java +++ /dev/null @@ -1,46 +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.management.ui; - -import org.apache.qpid.management.ui.views.MBeanView; -import org.apache.qpid.management.ui.views.NavigationView; -import org.eclipse.ui.IPageLayout; -import org.eclipse.ui.IPerspectiveFactory; - -/** - * - * @author Bhupendra Bhardwaj - */ -public class Perspective implements IPerspectiveFactory -{ - public void createInitialLayout(IPageLayout layout) - { - String editorArea = layout.getEditorArea(); - layout.setEditorAreaVisible(false); - - // standalone view meaning it can't be docked or stacked with other views, and it doesn't have a title bar. - layout.addStandaloneView(NavigationView.ID, true, IPageLayout.LEFT, 0.30f, editorArea); - layout.addStandaloneView(MBeanView.ID, true, IPageLayout.RIGHT, 0.70f, editorArea); - - layout.getViewLayout(NavigationView.ID).setCloseable(false); - layout.getViewLayout(MBeanView.ID).setCloseable(false); - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ServerRegistry.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ServerRegistry.java deleted file mode 100644 index 313e143df5..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ServerRegistry.java +++ /dev/null @@ -1,172 +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.management.ui; - - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.apache.qpid.management.ui.jmx.ClientListener; -import org.apache.qpid.management.ui.model.ManagedAttributeModel; -import org.apache.qpid.management.ui.model.NotificationObject; -import org.apache.qpid.management.ui.model.OperationDataModel; - -public abstract class ServerRegistry -{ - private ManagedServer _managedServer = null; - - // list of virtual hosts for this server - private List<String> _virtualHosts = new ArrayList<String>(); - // map of all Connection mbeans - private ConcurrentMap<String,List<ManagedBean>> _connections = new ConcurrentHashMap<String,List<ManagedBean>>(); - // map of all exchange mbeans - private ConcurrentMap<String,List<ManagedBean>> _exchanges = new ConcurrentHashMap<String,List<ManagedBean>>(); - // map of all queue mbenas - private ConcurrentMap<String,List<ManagedBean>> _queues = new ConcurrentHashMap<String,List<ManagedBean>>(); - - public ServerRegistry() - { - - } - - public ServerRegistry(ManagedServer server) - { - _managedServer = server; - } - - public ManagedServer getManagedServer() - { - return _managedServer; - } - - public void setManagedServer(ManagedServer server) - { - _managedServer = server; - } - - protected void addConnectionMBean(ManagedBean mbean) - { - String vHost = mbean.getVirtualHostName(); - _connections.putIfAbsent(vHost, new ArrayList<ManagedBean>()); - _connections.get(vHost).add(mbean); - } - - protected void addExchangeMBean(ManagedBean mbean) - { - String vHost = mbean.getVirtualHostName(); - _exchanges.putIfAbsent(vHost, new ArrayList<ManagedBean>()); - _exchanges.get(vHost).add(mbean); - } - - protected void addQueueMBean(ManagedBean mbean) - { - String vHost = mbean.getVirtualHostName(); - _queues.putIfAbsent(vHost, new ArrayList<ManagedBean>()); - _queues.get(vHost).add(mbean); - } - - protected void removeConnectionMBean(ManagedBean mbean) - { - _connections.get(mbean.getVirtualHostName()).remove(mbean); - } - - protected void removeExchangeMBean(ManagedBean mbean) - { - _exchanges.get(mbean.getVirtualHostName()).remove(mbean); - } - - protected void removeQueueMBean(ManagedBean mbean) - { - _queues.get(mbean.getVirtualHostName()).remove(mbean); - } - - public List<ManagedBean> getConnections(String virtualHost) - { - return _connections.get(virtualHost); - } - - public List<ManagedBean> getExchanges(String virtualHost) - { - return _exchanges.get(virtualHost); - } - - public List<ManagedBean> getQueues(String virtualHost) - { - return _queues.get(virtualHost); - } - - public void addVirtualHost(String name) - { - if (!_virtualHosts.contains(name)) - { - _virtualHosts.add(name); - } - } - - public List<String> getVirtualHosts() - { - return _virtualHosts; - } - - public abstract void setUserList(List<String> list); - - public abstract List<String> getUsernames(); - - public abstract void addManagedObject(ManagedBean key); - - public abstract List<ManagedBean> getMBeans(); - - public abstract void removeManagedObject(ManagedBean mbean); - - public abstract List<ManagedBean> getObjectsToBeRemoved(); - - public abstract ManagedAttributeModel getAttributeModel(ManagedBean mbean); - - public abstract Object getServerConnection(); - - public abstract void closeServerConnection() throws Exception; - - public abstract OperationDataModel getOperationModel(ManagedBean mbean); - - public abstract List<String> getQueueNames(String vistualHostName); - - public abstract String[] getExchangeNames(String vistualHostName); - - public abstract String[] getConnectionNames(String vistualHostName); - - public abstract List<NotificationObject> getNotifications(ManagedBean mbean); - - public abstract boolean hasSubscribedForNotifications(ManagedBean mbean, String name, String type); - - public abstract void clearNotifications(ManagedBean mbean, List<NotificationObject> list); - - public ClientListener getNotificationListener() - { - return null; - } - - public ClientListener getClientListener() - { - return null; - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/AbstractAction.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/AbstractAction.java deleted file mode 100644 index 53aa927299..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/AbstractAction.java +++ /dev/null @@ -1,136 +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.management.ui.actions; - -import static org.apache.qpid.management.ui.Constants.ERROR_SERVER_CONNECTION; - -import java.io.IOException; - -import org.apache.qpid.management.ui.ApplicationRegistry; -import org.apache.qpid.management.ui.ApplicationWorkbenchAdvisor; -import org.apache.qpid.management.ui.Constants; -import org.apache.qpid.management.ui.jmx.MBeanUtility; -import org.apache.qpid.management.ui.views.NavigationView; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.dialogs.ErrorDialog; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.IWorkbenchWindowActionDelegate; - -public class AbstractAction -{ - private NavigationView _navigationView; - - protected IWorkbenchWindow _window; - - public static final String RMI_SASL_ERROR = "non-JRMP server"; - public static final String SECURITY_FAILURE = "User authentication has failed"; - public static final String SERVER_UNAVAILABLE = "Qpid server is not running"; - - /** - * We will cache window object in order to - * be able to provide parent shell for the message dialog. - * @see IWorkbenchWindowActionDelegate#init - */ - public void init(IWorkbenchWindow window) - { - this._window = window; - if (_window.getShell() != null) - { - _window.getShell().setImage(ApplicationRegistry.getImage(Constants.CONSOLE_IMAGE)); - } - } - - protected NavigationView getNavigationView() - { - if (_navigationView == null) - { - _navigationView = (NavigationView)_window.getActivePage().findView(NavigationView.ID); - } - - return _navigationView; - } - - - protected void handleException(Throwable ex, String title, String msg) - { - MBeanUtility.printStackTrace(ex); - if (msg == null) - { - if (ex instanceof IOException) - { - if ((ex.getMessage() != null) && (ex.getMessage().indexOf(RMI_SASL_ERROR) != -1)) - { - msg = SECURITY_FAILURE; - } - else - { - msg = SERVER_UNAVAILABLE; - } - } - else if (ex instanceof SecurityException) - { - msg = SECURITY_FAILURE; - } - else - { - msg = ex.getMessage(); - } - } - - if ((msg == null) && (ex.getCause() != null)) - { - msg = ex.getCause().getMessage(); - } - - if (msg == null) - { - msg = ERROR_SERVER_CONNECTION; - } - - if (title == null) - { - title = ERROR_SERVER_CONNECTION; - } - IStatus status = new Status(IStatus.ERROR, ApplicationWorkbenchAdvisor.PERSPECTIVE_ID, - IStatus.OK, msg, null); - ErrorDialog.openError(_window.getShell(), "Error", title, status); - } - - - /** - * Selection in the workbench has been changed. We can change the state of the 'real' action here - * if we want, but this can only happen after the delegate has been created. - * @see IWorkbenchWindowActionDelegate#selectionChanged - */ - public void selectionChanged(IAction action, ISelection selection) { - } - - /** - * We can use this method to dispose of any system resources we previously allocated. - * @see IWorkbenchWindowActionDelegate#dispose - */ - public void dispose() { - - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/AddServer.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/AddServer.java deleted file mode 100644 index 7a36ca6160..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/AddServer.java +++ /dev/null @@ -1,274 +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.management.ui.actions; - -import static org.apache.qpid.management.ui.Constants.*; - -import org.apache.qpid.management.ui.ApplicationRegistry; -import org.apache.qpid.management.ui.exceptions.InfoRequiredException; -import org.apache.qpid.management.ui.views.NumberVerifyListener; -import org.apache.qpid.management.ui.views.ViewUtility; -import org.eclipse.jface.action.IAction; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Combo; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.widgets.Text; -import org.eclipse.ui.IWorkbenchWindowActionDelegate; - -public class AddServer extends AbstractAction implements IWorkbenchWindowActionDelegate -{ - private static final String[] _domains ={"org.apache.qpid"}; - - private String _transport = DEFAULT_PROTOCOL; - private String _host; - private String _port; - private String _domain; - private String _user; - private String _password; - - private boolean _addServer; - - public AddServer() - { - - } - - public void run(IAction action) - { - if(_window == null) - return; - - reset(); - createAddServerPopup(); - try - { - if (_addServer) - { - getNavigationView().addNewServer(_transport, _host, Integer.parseInt(_port), _domain, _user, _password); - } - } - catch(InfoRequiredException ex) - { - ViewUtility.popupInfoMessage(ACTION_ADDSERVER, ex.getMessage()); - } - catch (Exception ex) - { - handleException(ex, null, null); - } - } - - private void reset() - { - _addServer = false; - _host = null; - _port = null; - _domain = null; - _user = null; - _password = null; - } - - /** - * Creates the shell and then opens the popup where user can enter new connection details. - * Connects to the new server and adds the server in the navigation page. - * Pops up any error occured in connecting to the new server - */ - private void createAddServerPopup() - { - Display display = Display.getCurrent(); - final Shell shell = new Shell(display, SWT.BORDER | SWT.CLOSE); - shell.setText(ACTION_ADDSERVER); - shell.setImage(ApplicationRegistry.getImage(CONSOLE_IMAGE)); - shell.setLayout(new GridLayout()); - - int x = display.getBounds().width; - int y = display.getBounds().height; - shell.setBounds(x/3, y/3, 425, 275); - - createWidgets(shell); - - shell.open(); - _window.getShell().setEnabled(false); - - while (!shell.isDisposed()) - { - if (!display.readAndDispatch()) - { - display.sleep(); - } - } - - // enable the main shell - _window.getShell().setEnabled(true); - _window.getShell().open(); - } - - // Creates SWT widgets for the user to add server connection details. - // Adds listeners to the widgets to take appropriate action - private void createWidgets(final Shell shell) - { - Composite composite = new Composite(shell, SWT.NONE); - composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - GridLayout layout = new GridLayout(2, false); - layout.horizontalSpacing = 10; - layout.verticalSpacing = 10; - layout.marginHeight = 20; - layout.marginWidth = 20; - composite.setLayout(layout); - - /* Commenting this, as there is only one protocol at the moment. - * This can be uncommented and enhanced, if more protocols are added in future - Label name = new Label(composite, SWT.NONE); - name.setText("Connection Type"); - GridData layoutData = new GridData(SWT.TRAIL, SWT.TOP, false, false); - name.setLayoutData(layoutData); - - final Combo comboTransport = new Combo(composite, SWT.READ_ONLY); - comboTransport.setItems(CONNECTION_PROTOCOLS); - comboTransport.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); - comboTransport.select(0); - */ - - Label host = new Label(composite, SWT.NONE); - host.setText("Host"); - host.setLayoutData(new GridData(SWT.TRAIL, SWT.TOP, false, false)); - - final Text textHost = new Text(composite, SWT.BORDER); - textHost.setText(""); - textHost.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); - textHost.setFocus(); - - Label port = new Label(composite, SWT.NONE); - port.setText("Port"); - port.setLayoutData(new GridData(SWT.TRAIL, SWT.TOP, false, false)); - - final Text textPort = new Text(composite, SWT.BORDER); - textPort.setText(""); - textPort.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); - // Verify if the value entered is numeric - textPort.addVerifyListener(new NumberVerifyListener()); - - - Label domain = new Label(composite, SWT.NONE); - domain.setText("Domain"); - domain.setLayoutData(new GridData(SWT.TRAIL, SWT.TOP, false, false)); - - final Combo comboDomain = new Combo(composite, SWT.DROP_DOWN | SWT.READ_ONLY); - comboDomain.setItems(_domains); - comboDomain.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); - comboDomain.select(0); - - - Label user = new Label(composite, SWT.NONE); - user.setText(USERNAME); - user.setLayoutData(new GridData(SWT.TRAIL, SWT.TOP, false, false)); - - final Text textUser = new Text(composite, SWT.BORDER); - textUser.setText(""); - textUser.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); - - Label password = new Label(composite, SWT.NONE); - password.setText(PASSWORD); - password.setLayoutData(new GridData(SWT.TRAIL, SWT.TOP, false, false)); - - final Text textPwd = new Text(composite, SWT.BORDER | SWT.SINGLE | SWT.PASSWORD); - textPwd.setText(""); - //textPwd.setEchoChar('*'); - textPwd.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); - - Composite buttonsComposite = new Composite(composite, SWT.NONE); - buttonsComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1)); - buttonsComposite.setLayout(new GridLayout(2, true)); - - - final Button connectButton = new Button(buttonsComposite, SWT.PUSH | SWT.CENTER); - connectButton.setText(BUTTON_CONNECT); - GridData gridData = new GridData (SWT.TRAIL, SWT.BOTTOM, true, true); - gridData.widthHint = 100; - connectButton.setLayoutData(gridData); - connectButton.setFont(ApplicationRegistry.getFont(FONT_BUTTON)); - connectButton.addSelectionListener(new SelectionAdapter(){ - public void widgetSelected(SelectionEvent event) - { - _host = textHost.getText(); - if ((_host == null) || (_host.trim().length() == 0)) - { - ViewUtility.popupInfoMessage(ACTION_ADDSERVER, INFO_HOST_ADDRESS); - textHost.setText(""); - textHost.setFocus(); - return; - } - - _port = textPort.getText(); - if ((_port == null) || (_port.trim().length() == 0)) - { - ViewUtility.popupInfoMessage(ACTION_ADDSERVER, INFO_HOST_PORT); - textPort.setText(""); - textPort.setFocus(); - return; - } - - _user = textUser.getText(); - if ((_user == null) || (_user.trim().length() == 0)) - { - ViewUtility.popupInfoMessage(ACTION_ADDSERVER, INFO_USERNAME); - textUser.setText(""); - textUser.setFocus(); - return; - } - - _password = textPwd.getText(); - if (_password == null) - { - ViewUtility.popupInfoMessage(ACTION_ADDSERVER, INFO_PASSWORD); - textPwd.setText(""); - textPwd.setFocus(); - return; - } - - _domain = comboDomain.getText(); - _addServer = true; - shell.dispose(); - } - }); - - final Button cancelButton = new Button(buttonsComposite, SWT.PUSH); - cancelButton.setText(BUTTON_CANCEL); - gridData = new GridData (SWT.LEAD, SWT.BOTTOM, true, true); - gridData.widthHint = 100; - cancelButton.setLayoutData(gridData); - cancelButton.setFont(ApplicationRegistry.getFont(FONT_BUTTON)); - cancelButton.addSelectionListener(new SelectionAdapter(){ - public void widgetSelected(SelectionEvent event) - { - shell.dispose(); - } - }); - } - -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/CloseConnection.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/CloseConnection.java deleted file mode 100644 index a3e52149df..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/CloseConnection.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.management.ui.actions; - -import static org.apache.qpid.management.ui.Constants.ACTION_CLOSE; -import org.apache.qpid.management.ui.exceptions.InfoRequiredException; -import org.apache.qpid.management.ui.views.NavigationView; -import org.apache.qpid.management.ui.views.ViewUtility; -import org.eclipse.jface.action.IAction; -import org.eclipse.ui.IWorkbenchWindowActionDelegate; - -public class CloseConnection extends AbstractAction implements IWorkbenchWindowActionDelegate -{ - public CloseConnection() - { - - } - - public void run(IAction action) - { - if(_window != null) - { - NavigationView view = (NavigationView)_window.getActivePage().findView(NavigationView.ID); - try - { - view.disconnect(); - } - catch(InfoRequiredException ex) - { - ViewUtility.popupInfoMessage(ACTION_CLOSE, ex.getMessage()); - } - catch(Exception ex) - { - handleException(ex, null, null); - } - } - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/EditAttribute.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/EditAttribute.java deleted file mode 100644 index d3af3661b0..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/EditAttribute.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.management.ui.actions; - -import static org.apache.qpid.management.ui.Constants.ACTION_EDITATTRIBUTE; -import org.apache.qpid.management.ui.exceptions.InfoRequiredException; -import org.apache.qpid.management.ui.views.MBeanView; -import org.apache.qpid.management.ui.views.ViewUtility; -import org.eclipse.jface.action.IAction; -import org.eclipse.ui.IWorkbenchWindowActionDelegate; - -public class EditAttribute extends AbstractAction implements IWorkbenchWindowActionDelegate -{ - public void run(IAction action) - { - if(_window != null) - { - MBeanView view = (MBeanView)_window.getActivePage().findView(MBeanView.ID); - try - { - view.editAttribute(); - } - catch(InfoRequiredException ex) - { - ViewUtility.popupInfoMessage(ACTION_EDITATTRIBUTE, ex.getMessage()); - } - catch(Exception ex) - { - handleException(ex, "Attribute could not be edited", null); - } - } - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/ReconnectServer.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/ReconnectServer.java deleted file mode 100644 index dd9e792912..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/ReconnectServer.java +++ /dev/null @@ -1,209 +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.management.ui.actions; - -import static org.apache.qpid.management.ui.Constants.ACTION_LOGIN; -import static org.apache.qpid.management.ui.Constants.CONSOLE_IMAGE; -import static org.apache.qpid.management.ui.Constants.INFO_PASSWORD; -import static org.apache.qpid.management.ui.Constants.INFO_USERNAME; -import static org.apache.qpid.management.ui.Constants.PASSWORD; -import static org.apache.qpid.management.ui.Constants.USERNAME; - -import org.apache.qpid.management.ui.ApplicationRegistry; -import org.apache.qpid.management.ui.Constants; -import org.apache.qpid.management.ui.exceptions.InfoRequiredException; -import org.apache.qpid.management.ui.views.TreeObject; -import org.apache.qpid.management.ui.views.ViewUtility; -import org.eclipse.jface.action.IAction; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.widgets.Text; -import org.eclipse.ui.IWorkbenchWindowActionDelegate; - -public class ReconnectServer extends AbstractAction implements IWorkbenchWindowActionDelegate -{ - private String _title; - private String _serverName; - private String _user; - private String _password; - private boolean _connect; - - public void run(IAction action) - { - if(_window == null) - return; - - try - { - reset(); - // Check if a server node is selected to be reconnected. - TreeObject serverNode = getNavigationView().getSelectedServerNode(); - _serverName = serverNode.getName(); - _title = ACTION_LOGIN + " (" + _serverName + ")"; - - // Get the login details(username/password) - createLoginPopup(); - - if (_connect) - { - // Connect the server - getNavigationView().reconnect(_user, _password); - } - } - catch(InfoRequiredException ex) - { - ViewUtility.popupInfoMessage("Reconnect Qpid server", ex.getMessage()); - } - catch (Exception ex) - { - handleException(ex, null, null); - } - } - - private void reset() - { - _connect = false; - _user = null; - _password = null; - } - - // Create the login popup fot th user to enter usernaem and password - private void createLoginPopup() - { - Display display = Display.getCurrent(); - final Shell shell = new Shell(display, SWT.BORDER | SWT.CLOSE); - shell.setText(_title); - shell.setImage(ApplicationRegistry.getImage(CONSOLE_IMAGE)); - shell.setLayout(new GridLayout()); - - int x = display.getBounds().width; - int y = display.getBounds().height; - shell.setBounds(x/3, y/3, 350, 200); - - createWidgets(shell); - - shell.open(); - _window.getShell().setEnabled(false); - - while (!shell.isDisposed()) - { - if (!display.readAndDispatch()) - { - display.sleep(); - } - } - - // enable the main shell - _window.getShell().setEnabled(true); - _window.getShell().open(); - } - - // Creates the SWT widgets in the popup shell, to enter username and password. - // Adds listeners to the widgets to take appropriate action - private void createWidgets(final Shell shell) - { - Composite composite = new Composite(shell, SWT.NONE); - composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - GridLayout layout = new GridLayout(2, false); - layout.horizontalSpacing = 10; - layout.verticalSpacing = 10; - layout.marginHeight = 20; - layout.marginWidth = 20; - composite.setLayout(layout); - - Label user = new Label(composite, SWT.NONE); - user.setText(USERNAME); - user.setLayoutData(new GridData(SWT.TRAIL, SWT.TOP, false, false)); - - final Text textUser = new Text(composite, SWT.BORDER); - textUser.setText(""); - textUser.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); - // Put cursor on this field - textUser.setFocus(); - - Label password = new Label(composite, SWT.NONE); - password.setText(PASSWORD); - password.setLayoutData(new GridData(SWT.TRAIL, SWT.TOP, false, false)); - - final Text textPwd = new Text(composite, SWT.BORDER | SWT.SINGLE | SWT.PASSWORD); - textPwd.setText(""); - textPwd.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); - - Composite buttonsComposite = new Composite(composite, SWT.NONE); - buttonsComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1)); - buttonsComposite.setLayout(new GridLayout(2, true)); - - - final Button connectButton = new Button(buttonsComposite, SWT.PUSH | SWT.CENTER); - connectButton.setText(Constants.BUTTON_CONNECT); - GridData gridData = new GridData (SWT.TRAIL, SWT.BOTTOM, true, true); - gridData.widthHint = 100; - connectButton.setLayoutData(gridData); - connectButton.setFont(ApplicationRegistry.getFont(Constants.FONT_BUTTON)); - connectButton.addSelectionListener(new SelectionAdapter(){ - public void widgetSelected(SelectionEvent event) - { - _user = textUser.getText(); - if ((_user == null) || (_user.trim().length() == 0)) - { - ViewUtility.popupInfoMessage(_title, INFO_USERNAME); - textUser.setText(""); - textUser.setFocus(); - return; - } - - _password = textPwd.getText(); - if (_password == null) - { - ViewUtility.popupInfoMessage(_title, INFO_PASSWORD); - textPwd.setText(""); - textPwd.setFocus(); - return; - } - - _connect = true; - shell.dispose(); - } - }); - - final Button cancelButton = new Button(buttonsComposite, SWT.PUSH); - cancelButton.setText(Constants.BUTTON_CANCEL); - gridData = new GridData (SWT.LEAD, SWT.BOTTOM, true, true); - gridData.widthHint = 100; - cancelButton.setLayoutData(gridData); - cancelButton.setFont(ApplicationRegistry.getFont(Constants.FONT_BUTTON)); - cancelButton.addSelectionListener(new SelectionAdapter(){ - public void widgetSelected(SelectionEvent event) - { - shell.dispose(); - } - }); - } - -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/Refresh.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/Refresh.java deleted file mode 100644 index 34251c12d7..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/Refresh.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.management.ui.actions; - -import org.apache.qpid.management.ui.jmx.MBeanUtility; -import org.apache.qpid.management.ui.views.MBeanView; -import org.apache.qpid.management.ui.views.NavigationView; -import org.eclipse.jface.action.IAction; -import org.eclipse.ui.IWorkbenchWindowActionDelegate; - -/** - * This action refreshes both the views -Navigation and MBeanView - * @author Bhupendra Bhardwaj - */ -public class Refresh extends AbstractAction implements IWorkbenchWindowActionDelegate -{ - public void run(IAction action) - { - if(_window != null) - { - NavigationView view = (NavigationView)_window.getActivePage().findView(NavigationView.ID); - view.refresh(); - - MBeanView mbeanview = (MBeanView)_window.getActivePage().findView(MBeanView.ID); - try - { - mbeanview.refreshMBeanView(); - } - catch (Exception ex) - { - MBeanUtility.handleException(ex); - } - } - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/RemoveServer.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/RemoveServer.java deleted file mode 100644 index e329255414..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/RemoveServer.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.management.ui.actions; - -import org.apache.qpid.management.ui.exceptions.InfoRequiredException; -import org.apache.qpid.management.ui.views.NavigationView; -import org.apache.qpid.management.ui.views.ViewUtility; -import org.eclipse.jface.action.IAction; -import org.eclipse.ui.IWorkbenchWindowActionDelegate; - -public class RemoveServer extends AbstractAction implements IWorkbenchWindowActionDelegate -{ - public void run(IAction action) - { - if(_window != null) - { - NavigationView view = (NavigationView)_window.getActivePage().findView(NavigationView.ID); - try - { - view.removeServer(); - } - catch(InfoRequiredException ex) - { - ViewUtility.popupInfoMessage("Remove Qpid server", ex.getMessage()); - } - catch(Exception ex) - { - handleException(ex, "Server could not be removed", null); - } - } - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/VersionAction.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/VersionAction.java deleted file mode 100644 index 11db02f5a2..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/actions/VersionAction.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.management.ui.actions; - -import java.io.InputStream; -import java.util.Properties; - -import org.apache.qpid.management.ui.Constants; -import org.apache.qpid.management.ui.jmx.MBeanUtility; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.ui.IWorkbenchWindow; - -public class VersionAction extends Action -{ - private IWorkbenchWindow _window; - public static final String VERSION_RESOURCE = "qpidversion.properties"; - - public static final String PRODUCT_NAME_PROPERTY = "qpid.name"; - public static final String RELEASE_VERSION_PROPERTY = "qpid.version"; - public static final String BUILD_VERSION_PROPERTY = "qpid.svnversion"; - - private static final String DEFAULT = "unknown"; - private static String _releaseVersion; - private static String _buildVersion; - private static String _text; - - static - { - Properties props = new Properties(); - try - { - InputStream propertyStream = VersionAction.class.getClassLoader().getResourceAsStream(VERSION_RESOURCE); - if (propertyStream != null) - { - props.load(propertyStream); - _releaseVersion = readPropertyValue(props, RELEASE_VERSION_PROPERTY); - _buildVersion = readPropertyValue(props, BUILD_VERSION_PROPERTY); - _text = "Build Version : " + _buildVersion + "\n" + - "Release Version : " + _releaseVersion; - } - } - catch (Exception ex) - { - MBeanUtility.printStackTrace(ex); - } - } - - public VersionAction(IWorkbenchWindow window) - { - _window = window; - setText("About " + Constants.APPLICATION_NAME); - setId("qpidmc.about"); - setActionDefinitionId("qpidmc.about"); - } - - private static String readPropertyValue(Properties props, String propertyName) - { - String retVal = (String) props.get(propertyName); - if (retVal == null) - { - retVal = DEFAULT; - } - return retVal; - } - - public void run() - { - MessageDialog.openInformation(_window.getShell(), Constants.APPLICATION_NAME, _text); - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/exceptions/InfoRequiredException.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/exceptions/InfoRequiredException.java deleted file mode 100644 index 672426a59d..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/exceptions/InfoRequiredException.java +++ /dev/null @@ -1,36 +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.management.ui.exceptions; - -public class InfoRequiredException extends Exception -{ - private static final long serialVersionUID = 1L; - - public InfoRequiredException(String message) - { - super(message); - } - - public InfoRequiredException(String msg, Throwable t) - { - super(msg, t); - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/exceptions/ManagementConsoleException.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/exceptions/ManagementConsoleException.java deleted file mode 100644 index 17c127c01a..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/exceptions/ManagementConsoleException.java +++ /dev/null @@ -1,31 +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.management.ui.exceptions; - -@SuppressWarnings("serial") -public class ManagementConsoleException extends Exception -{ - public ManagementConsoleException(String message) - { - super(message); - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/ClientListener.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/ClientListener.java deleted file mode 100644 index 2be0ddbebf..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/ClientListener.java +++ /dev/null @@ -1,77 +0,0 @@ - -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */package org.apache.qpid.management.ui.jmx; - -import javax.management.MBeanServerNotification; -import javax.management.Notification; -import javax.management.NotificationListener; -import javax.management.ObjectName; -import javax.management.remote.JMXConnectionNotification; - -import org.apache.qpid.management.ui.ApplicationRegistry; -import org.apache.qpid.management.ui.ManagedServer; - - -public class ClientListener implements NotificationListener -{ - protected ManagedServer server = null; - protected JMXServerRegistry serverRegistry = null; - - public ClientListener(ManagedServer server) - { - this.server = server; - serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(server); - } - - public void handleNotification(Notification notification, Object handback) - { - ObjectName objName = null; - String type = notification.getType(); - MBeanUtility.printOutput(type + ":" + objName); - - if (MBeanServerNotification.REGISTRATION_NOTIFICATION.equals(type)) - { - objName = ((MBeanServerNotification)notification).getMBeanName(); - getServerRegistry().registerManagedObject(objName); - } - else if (MBeanServerNotification.UNREGISTRATION_NOTIFICATION.equals(type)) - { - objName = ((MBeanServerNotification)notification).getMBeanName(); - getServerRegistry().unregisterManagedObject(objName); - } - else if (JMXConnectionNotification.FAILED.equals(type)) - { - ApplicationRegistry.serverConnectionClosed(server); - } - } - - protected JMXServerRegistry getServerRegistry() - { - if (serverRegistry == null) - serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(server); - - return serverRegistry; - } - public ManagedServer getServer() - { - return server; - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/ClientNotificationListener.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/ClientNotificationListener.java deleted file mode 100644 index c6ecda4b4c..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/ClientNotificationListener.java +++ /dev/null @@ -1,41 +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.management.ui.jmx; - -import javax.management.Notification; -import javax.management.ObjectName; - -import org.apache.qpid.management.ui.ManagedServer; - -public class ClientNotificationListener extends ClientListener -{ - public ClientNotificationListener(ManagedServer server) - { - super(server); - } - - public void handleNotification(Notification notification, Object handback) - { - ObjectName objName = (ObjectName)notification.getSource(); - //String type = notification.getType(); - getServerRegistry().addNotification(objName, notification); - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/JMXManagedObject.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/JMXManagedObject.java deleted file mode 100644 index 3561e16098..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/JMXManagedObject.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.management.ui.jmx; - -import java.util.HashMap; - -import javax.management.ObjectName; - -import org.apache.qpid.management.ui.ManagedBean; - - -public class JMXManagedObject extends ManagedBean -{ - private ObjectName _objName; - - @SuppressWarnings("unchecked") - public JMXManagedObject(ObjectName objName) - { - super(); - this._objName = objName; - setUniqueName(_objName.toString()); - setDomain(_objName.getDomain()); - super.setProperties(new HashMap(_objName.getKeyPropertyList())); - } - - public ObjectName getObjectName() - { - return _objName; - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/JMXServerRegistry.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/JMXServerRegistry.java deleted file mode 100644 index f671a1dc9a..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/JMXServerRegistry.java +++ /dev/null @@ -1,628 +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.management.ui.jmx; - -import static org.apache.qpid.management.ui.Constants.*; - -import java.lang.reflect.Constructor; -import java.security.Security; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CopyOnWriteArrayList; - -import javax.management.ListenerNotFoundException; -import javax.management.MBeanInfo; -import javax.management.MBeanServerConnection; -import javax.management.Notification; -import javax.management.ObjectName; -import javax.management.remote.JMXConnector; -import javax.management.remote.JMXConnectorFactory; -import javax.management.remote.JMXServiceURL; -import javax.security.auth.callback.CallbackHandler; -import javax.security.sasl.SaslClientFactory; - -import org.apache.qpid.management.ui.ApplicationRegistry; -import org.apache.qpid.management.ui.ManagedBean; -import org.apache.qpid.management.ui.ManagedServer; -import org.apache.qpid.management.ui.ServerRegistry; -import org.apache.qpid.management.ui.model.ManagedAttributeModel; -import org.apache.qpid.management.ui.model.NotificationInfoModel; -import org.apache.qpid.management.ui.model.NotificationObject; -import org.apache.qpid.management.ui.model.OperationDataModel; -import org.apache.qpid.management.ui.sasl.JCAProvider; -import org.apache.qpid.management.ui.sasl.SaslProvider; -import org.apache.qpid.management.ui.sasl.UserPasswordCallbackHandler; -import org.apache.qpid.management.ui.sasl.UsernameHashedPasswordCallbackHandler; - - -public class JMXServerRegistry extends ServerRegistry -{ - private boolean _connected = false; - private ObjectName _serverObjectName = null; - private Map<String, Object> _env = null; - private JMXServiceURL _jmxUrl = null; - private JMXConnector _jmxc = null; - private MBeanServerConnection _mbsc = null; - private Exception _connectionException = null; - - private List<String> _usersList; - // When an mbean gets removed from mbean server, then the notification listener - // will add that mbean in this list. - private List<ManagedBean> _mbeansToBeRemoved = new ArrayList<ManagedBean>(); - - // Map containing all managed beans and mapped with unique mbean name - private HashMap<String, ManagedBean> _mbeansMap = new HashMap<String, ManagedBean>(); - // Map containing MBeanInfo for all mbeans and mapped with unique mbean name - private HashMap<String, MBeanInfo> _mbeanInfoMap = new HashMap<String, MBeanInfo>(); - // Map containing attribute model for all mbeans and mapped with unique mbean name - private HashMap<String, ManagedAttributeModel> _attributeModelMap = new HashMap<String, ManagedAttributeModel>(); - // Map containing operation model for all mbeans and mapped with unique mbean name - private HashMap<String, OperationDataModel> _operationModelMap = new HashMap<String, OperationDataModel>(); - // Map containing NotificationInfo for all mbeans and mapped with unique mbean name - private HashMap<String, List<NotificationInfoModel>> _notificationInfoMap = new HashMap<String, List<NotificationInfoModel>>(); - // Map containing all notifications sent for all mbeans, which are registered for notification - private HashMap<String, List<NotificationObject>> _notificationsMap = new HashMap<String, List<NotificationObject>>(); - // For mbeans which have subscribed for a notification type - // mbean unique name mapped with notification map. Notification map contains list of notification type - // mapped with notification name. Notification type list contains those notification types, - // which are subscribed for notification. - private HashMap<String, HashMap<String, List<String>>> _subscribedNotificationMap = new HashMap<String, HashMap<String, List<String>>>(); - - // listener for registration or unregistratioj of mbeans on mbean server - private ClientNotificationListener _notificationListener = null; - // listener for server connection. Receives notification if server connection goes down - private ClientListener _clientListener = null; - - public JMXServerRegistry(ManagedServer server) throws Exception - { - super(server); - String securityMechanism = ApplicationRegistry.getSecurityMechanism(); - String connectorClassName = ApplicationRegistry.getJMXConnectorClass(); - - if ((securityMechanism != null) && (connectorClassName != null)) - { - createSASLConnector(securityMechanism, connectorClassName); - } - else - { - _jmxUrl = new JMXServiceURL(server.getUrl()); - _jmxc = JMXConnectorFactory.connect(_jmxUrl, null); - } - - _mbsc = _jmxc.getMBeanServerConnection(); - - _clientListener = new ClientListener(server); - _notificationListener = new ClientNotificationListener(server); - - _jmxc.addConnectionNotificationListener(_clientListener, null, null); - _serverObjectName = new ObjectName("JMImplementation:type=MBeanServerDelegate"); - _mbsc.addNotificationListener(_serverObjectName, _clientListener, null, null); - } - - public MBeanServerConnection getServerConnection() - { - return _mbsc; - } - - private void createSASLConnector(String mech, String className) throws Exception - { - String text = "Security mechanism " + mech + " is not supported."; - // Check if the given connector, which supports SASL is available - Class connectorClass = Class.forName(className); - - _jmxUrl = new JMXServiceURL("jmxmp", getManagedServer().getHost(), getManagedServer().getPort()); - _env = new HashMap<String, Object>(); - CallbackHandler handler; - if (MECH_CRAMMD5.equals(mech)) - { - // For SASL/CRAM-MD5 - Map<String, Class<? extends SaslClientFactory>> map = new HashMap<String, Class<? extends SaslClientFactory>>(); - Class<?> clazz = Class.forName("org.apache.qpid.management.ui.sasl.CRAMMD5HashedSaslClientFactory"); - map.put("CRAM-MD5-HASHED", (Class<? extends SaslClientFactory>) clazz); - - Security.addProvider(new JCAProvider(map)); - handler = new UsernameHashedPasswordCallbackHandler(getManagedServer().getUser(), - getManagedServer().getPassword()); - _env.put("jmx.remote.profiles", SASL_CRAMMD5); - _env.put("jmx.remote.sasl.callback.handler", handler); - - } - else if (MECH_PLAIN.equals(mech)) - { - // For SASL/PLAIN - Security.addProvider(new SaslProvider()); - handler = new UserPasswordCallbackHandler(getManagedServer().getUser(), getManagedServer().getPassword()); - _env.put("jmx.remote.profiles", SASL_PLAIN); - _env.put("jmx.remote.sasl.callback.handler", handler); - } - else - { - MBeanUtility.printOutput(text); - throw new Exception(text); - } - // Now create the instance of JMXMPConnector - Class[] paramTypes = {JMXServiceURL.class, Map.class}; - Constructor cons = connectorClass.getConstructor(paramTypes); - - Object[] args = {_jmxUrl, _env}; - Object theObject = cons.newInstance(args); - - _jmxc = (JMXConnector)theObject; - - Thread connectorThread = new Thread(new ConnectorThread()); - connectorThread.start(); - long timeNow = System.currentTimeMillis(); - connectorThread.join(ApplicationRegistry.timeout); - - if (_connectionException != null) - { - throw _connectionException; - } - if (!_connected) - { - if (System.currentTimeMillis() - timeNow >= ApplicationRegistry.timeout) - throw new Exception("Qpid server connection timed out"); - else - throw new Exception("Qpid server connection failed"); - } - } - - private class ConnectorThread implements Runnable - { - public void run() - { - try - { - _connected = false; - _connectionException = null; - - _jmxc.connect(); - _connected = true; - } - catch (Exception ex) - { - _connectionException = ex; - MBeanUtility.printStackTrace(ex); - } - } - } - /** - * removes all listeners from the mbean server. This is required when user - * disconnects the Qpid server connection - */ - public void closeServerConnection() throws Exception - { - try - { - if (_jmxc != null && _clientListener != null) - _jmxc.removeConnectionNotificationListener(_clientListener); - - if (_mbsc != null && _clientListener != null) - _mbsc.removeNotificationListener(_serverObjectName, _clientListener); - - // remove mbean notification listeners - for (String mbeanName : _subscribedNotificationMap.keySet()) - { - _mbsc.removeNotificationListener(new ObjectName(mbeanName), _notificationListener); - } - } - catch (ListenerNotFoundException ex) - { - MBeanUtility.printOutput(ex.toString()); - } - } - - public ManagedBean getManagedObject(String uniqueName) - { - return _mbeansMap.get(uniqueName); - } - - public void addManagedObject(ManagedBean mbean) - { - if (mbean.isQueue()) - { - addQueueMBean(mbean); - } - else if (mbean.isExchange()) - { - addExchangeMBean(mbean); - } - else if (mbean.isConnection()) - { - addConnectionMBean(mbean); - } - - addVirtualHost(mbean.getVirtualHostName()); - _mbeansMap.put(mbean.getUniqueName(), mbean); - } - - public void removeManagedObject(ManagedBean mbean) - { - MBeanUtility.printOutput("Removing MBean:" + mbean.getUniqueName()); - - if (mbean.isQueue()) - { - removeQueueMBean(mbean); - } - else if (mbean.isExchange()) - { - removeExchangeMBean(mbean); - } - else if (mbean.isConnection()) - { - removeConnectionMBean(mbean); - } - - _mbeansMap.remove(mbean.getUniqueName()); - } - - public void putMBeanInfo(ManagedBean mbean, MBeanInfo mbeanInfo) - { - _mbeanInfoMap.put(mbean.getUniqueName(), mbeanInfo); - } - public MBeanInfo getMBeanInfo(ManagedBean mbean) - { - return _mbeanInfoMap.get(mbean.getUniqueName()); - } - - public List<ManagedBean> getMBeans() - { - return new ArrayList<ManagedBean>(_mbeansMap.values()); - } - - public void setNotificationInfo(ManagedBean mbean, List<NotificationInfoModel>value) - { - _notificationInfoMap.put(mbean.getUniqueName(), value); - } - - public List<NotificationInfoModel> getNotificationInfo(ManagedBean mbean) - { - return _notificationInfoMap.get(mbean.getUniqueName()); - } - - public void addNotification(ObjectName objName, Notification notification) - { - List<NotificationObject> list = _notificationsMap.get(objName.toString()); - NotificationObject obj = new NotificationObject(notification.getSequenceNumber(), - new Date(notification.getTimeStamp()), - notification.getMessage(), - notification.getSource(), - notification.getType()); - - if (list == null) - { - list = new ArrayList<NotificationObject>(); - _notificationsMap.put(objName.toString(), list); - } - - list.add(obj); - } - - /** - * Returns all the notification objects for a given mbean. If mbean is null, it returns - * notification objects for all the mbeans. - */ - public List<NotificationObject> getNotifications(ManagedBean mbean) - { - if (mbean == null) - { - List<NotificationObject> totalList = new ArrayList<NotificationObject>(); - for (List<NotificationObject> list : _notificationsMap.values()) - { - totalList.addAll(list); - } - return totalList; - } - else - { - return _notificationsMap.get(mbean.getUniqueName()); - } - } - - public void clearNotifications(ManagedBean mbean, List<NotificationObject> list) - { - if (mbean == null) - { - if (list == null || list.isEmpty()) - { - // All notifications of all mbeans to be cleared - _notificationsMap.clear(); - } - else - { - // Clear the selected notifications - for (NotificationObject obj : list) - { - mbean = _mbeansMap.get(obj.getSource().toString()); - List<NotificationObject> nList = _notificationsMap.get(mbean.getUniqueName()); - if (nList != null && !nList.isEmpty()) - { - nList.remove(obj); - } - } - } - } - else - { - if (list == null || list.isEmpty()) - { - // All notifications of this mbean to be cleared - List<NotificationObject> nList = _notificationsMap.get(mbean.getUniqueName()); - if (nList != null && !nList.isEmpty()) - { - nList.clear(); - } - } - else - { - // Clear the selected notifications - for (NotificationObject obj : list) - { - List<NotificationObject> nList = _notificationsMap.get(mbean.getUniqueName()); - if (nList != null && !nList.isEmpty()) - { - nList.remove(obj); - } - } - } - } - } - - - - /** - * Adds notification name and type to the map. The map contains all the notification names, - * subscribed for an mbean. - * @param mbean - * @param name - * @param type - */ - public void addNotificationListener(ManagedBean mbean, String name, String type) - { - // Get the subscribed notifications map for given mbean. If map is null then create a new one. - HashMap<String, List<String>> map = _subscribedNotificationMap.get(mbean.getUniqueName()); - if (map == null) - { - map = new HashMap<String, List<String>>(); - _subscribedNotificationMap.put(mbean.getUniqueName(),map); - } - - // Get the list of notification types for given notification name. If null, then create a new list. - List<String> list = map.get(name); - if (list == null) - { - list = new ArrayList<String>(); - map.put(name, list); - } - // Now add the notification type to the list - if (ALL.equals(type)) - { - List<NotificationInfoModel> infoList = _notificationInfoMap.get(mbean.getUniqueName()); - for (NotificationInfoModel model : infoList) - { - if (model.getName().equals(name)) - { - String[] types = model.getTypes(); - for (int i = 0; i < types.length; i++) - { - list.add(types[i]); - } - } - } - } - else - { - list.add(type); - } - - //System.out.println("Subscribed for notification :" + mbean.getUniqueName()); - } - - /** - * Checks if the given notification name and type are subscribed for the mbean. - */ - public boolean hasSubscribedForNotifications(ManagedBean mbean, String name, String type) - { - if (_subscribedNotificationMap.containsKey(mbean.getUniqueName())) - { - HashMap<String, List<String>> map = _subscribedNotificationMap.get(mbean.getUniqueName()); - if (map.containsKey(name)) - { - if (map.get(name).contains(type)) - { - return true; - } - } - } - return false; - } - - /** - * Clears the notification name and type information from the subscribed notifications map - * and removes the listener from mbeanserver connection - * @param mbean - * @param name - * @param type - * @throws Exception - */ - public void removeNotificationListener(ManagedBean mbean, String name, String type) throws Exception - { - //System.out.println("Removed notification listener :" + mbean.getUniqueName() + name +type); - if (_subscribedNotificationMap.containsKey(mbean.getUniqueName())) - { - // get the notifications map. This map contains the notification name mapped with the notification types - HashMap<String, List<String>> map = _subscribedNotificationMap.get(mbean.getUniqueName()); - if (map.containsKey(name)) - { - if (ALL.equals(type)) - { - map.remove(name); - } - else if (type != null) - { - map.get(name).remove(type); - if (map.get(name).isEmpty()) - { - map.remove(name); - } - } - } - if (map.size() == 0) - { - _subscribedNotificationMap.remove(mbean.getUniqueName()); - } - - JMXManagedObject jmxbean = (JMXManagedObject)mbean; - _mbsc.removeNotificationListener(jmxbean.getObjectName(), _notificationListener); - } - } - - /** - * When the mbean registration request is received from the mbean server, then the client listener - * can use this method. It will add the mbean to a list, which will be used to add the mbean to - * the registry and gui - * @param objName - */ - public void registerManagedObject(ObjectName objName) - { - JMXManagedObject managedObject = new JMXManagedObject(objName); - managedObject.setServer(getManagedServer()); - addManagedObject(managedObject); - } - - /** - * When mbean unregistration notification is received from the mbean server, then client listener - * can invoke this method. It will add the mbean to the list of mbeans to be removed from registry - * @param objName - */ - public void unregisterManagedObject(ObjectName objName) - { - ManagedBean mbean = _mbeansMap.get(objName.toString()); - removeManagedObject(mbean); - // Check if mbean was not available in the map. It can happen if mbean unregistration - // notification is received and the mbean is not added in the map. - if (mbean != null) - { - _mbeansToBeRemoved.add(mbean); - } - } - - public List<ManagedBean> getObjectsToBeRemoved() - { - if (_mbeansToBeRemoved.isEmpty()) - return null; - else - { - List<ManagedBean> list = new CopyOnWriteArrayList<ManagedBean>(_mbeansToBeRemoved); - _mbeansToBeRemoved.clear(); - return list; - } - } - - public void setAttributeModel(ManagedBean mbean, ManagedAttributeModel value) - { - _attributeModelMap.put(mbean.getUniqueName(), value); - } - - public ManagedAttributeModel getAttributeModel(ManagedBean mbean) - { - return _attributeModelMap.get(mbean.getUniqueName()); - } - - public void setOperationModel(ManagedBean mbean, OperationDataModel value) - { - _operationModelMap.put(mbean.getUniqueName(), value); - } - - public OperationDataModel getOperationModel(ManagedBean mbean) - { - return _operationModelMap.get(mbean.getUniqueName()); - } - - public List<String> getQueueNames(String virtualHostName) - { - List<ManagedBean> list = getQueues(virtualHostName); - if (list == null) - return null; - - List<String> queueNames = new ArrayList<String>(); - for (ManagedBean mbean : list) - { - queueNames.add(mbean.getName()); - } - return queueNames; - } - - public String[] getExchangeNames(String virtualHostName) - { - List<ManagedBean> list = getExchanges(virtualHostName); - if (list == null) - return null; - - String[] exchanges = new String[list.size()]; - int i = 0; - for (ManagedBean mbean : list) - { - exchanges[i++] = mbean.getName(); - } - return exchanges; - } - - public String[] getConnectionNames(String virtualHostName) - { - List<ManagedBean> list = getExchanges(virtualHostName); - if (list == null) - return null; - - String[] connections = new String[list.size()]; - int i = 0; - for (ManagedBean mbean : list) - { - connections[i++] = mbean.getName(); - } - return connections; - } - - public void setUserList(List<String> list) - { - _usersList = list; - Collections.sort(_usersList); - } - - public List<String> getUsernames() - { - return _usersList; - } - - public ClientNotificationListener getNotificationListener() - { - return _notificationListener; - } - - public ClientListener getClientListener() - { - return _clientListener; - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/MBeanUtility.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/MBeanUtility.java deleted file mode 100644 index 2d1883533b..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/MBeanUtility.java +++ /dev/null @@ -1,466 +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.management.ui.jmx; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import javax.management.Attribute; -import javax.management.AttributeList; -import javax.management.InstanceNotFoundException; -import javax.management.JMException; -import javax.management.MBeanAttributeInfo; -import javax.management.MBeanException; -import javax.management.MBeanInfo; -import javax.management.MBeanNotificationInfo; -import javax.management.MBeanOperationInfo; -import javax.management.MBeanServerConnection; -import javax.management.ObjectInstance; -import javax.management.ObjectName; -import javax.management.ReflectionException; - -import org.apache.qpid.management.ui.ApplicationRegistry; -import org.apache.qpid.management.ui.ManagedBean; -import org.apache.qpid.management.ui.ManagedServer; -import org.apache.qpid.management.ui.exceptions.ManagementConsoleException; -import org.apache.qpid.management.ui.model.AttributeData; -import org.apache.qpid.management.ui.model.ManagedAttributeModel; -import org.apache.qpid.management.ui.model.NotificationInfoModel; -import org.apache.qpid.management.ui.model.OperationData; -import org.apache.qpid.management.ui.model.OperationDataModel; -import org.apache.qpid.management.ui.model.ParameterData; -import org.apache.qpid.management.ui.views.ViewUtility; - -/** - * Utility class for all mbeanserver related operations. Keeps all JMX code out from view and model classes - * @author Bhupendra Bhardwaj - */ -public class MBeanUtility -{ - public static final BigInteger MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE); - public static final BigInteger MAX_INT = BigInteger.valueOf(Integer.MAX_VALUE); - /** - * Retrieves the MBeanInfo from MBeanServer and stores in the application registry - * @param mbean managed bean - * @return MBeanInfo - * @throws Exception, if server connection is null or if server throws Exception - */ - public static MBeanInfo getMBeanInfo(ManagedBean mbean) throws Exception - { - ManagedServer server = mbean.getServer(); - JMXServerRegistry serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(server); - - MBeanServerConnection mbsc = serverRegistry.getServerConnection(); - if (mbsc == null) - { - throw new ManagementConsoleException("Server connection is broken"); - } - - JMXManagedObject jmxbean = (JMXManagedObject)mbean; - MBeanInfo mbeanInfo = mbsc.getMBeanInfo(jmxbean.getObjectName()); - serverRegistry.putMBeanInfo(mbean, mbeanInfo); - - // populate the server registry with attribute and operation info - getAttributes(mbean); - getOperations(mbean); - - return mbeanInfo; - } - - /** - * executes the MBean operation - * @param mbean - * @param opData - * @return MBean operation return value - * @throws Exception if server connection is broken or if operation execution fails on the mbean server - */ - public static Object execute(ManagedBean mbean, OperationData opData) throws Exception - { - String opName = opData.getName(); - Object[] values = null; - String[] signature = null; - - List<ParameterData> params = opData.getParameters(); - if (params != null && !params.isEmpty()) - { - signature = new String[params.size()];; - values = new Object[params.size()]; - for (int i = 0; i < params.size(); i++) - { - signature[i] = params.get(i).getType(); - values[i] = params.get(i).getValue(); - } - } - - ManagedServer server = mbean.getServer(); - JMXServerRegistry serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(server); - - MBeanServerConnection mbsc = serverRegistry.getServerConnection(); - if (mbsc == null) - { - throw new ManagementConsoleException("Server connection is broken"); - // TODO - // try and get the connection again if it was disconnected - } - JMXManagedObject jmxbean = (JMXManagedObject)mbean; - return mbsc.invoke(jmxbean.getObjectName(), opName, values, signature); - } - - /** - * @see MBeanUtility#handleException(ManagedBean, Exception) - */ - public static void handleException(Exception ex) - { - handleException(null, ex); - } - - /** - * handels the exception received. Shows the exception to the user in best suitable way - * @param mbean managed bean - * @param ex Exception - */ - public static void handleException(ManagedBean mbean, Throwable ex) - { - if (mbean == null) - { - ViewUtility.popupErrorMessage("Error", "Managed Object is null \n" + ex.toString()); - printStackTrace(ex); - } - else if (ex instanceof ReflectionException) - { - ViewUtility.popupErrorMessage(mbean.getInstanceName(), "Server has thrown error \n" + ex.toString()); - printStackTrace(ex); - } - else if (ex instanceof InstanceNotFoundException) - { - ViewUtility.popupErrorMessage(mbean.getInstanceName(), "Managed Object Not Found \n" + ex.toString()); - printStackTrace(ex); - } - else if (ex instanceof MBeanException) - { - String cause = ((MBeanException)ex).getTargetException().getMessage(); - if (cause == null) - cause = ex.toString(); - ViewUtility.popupInfoMessage(mbean.getInstanceName(), cause); - } - else if (ex instanceof JMException) - { - ViewUtility.popupErrorMessage(mbean.getInstanceName(), "Management Exception occured \n" + ex.toString()); - } - else if (ex instanceof ManagementConsoleException) - { - ViewUtility.popupErrorMessage(mbean.getInstanceName(), ex.getMessage()); - } - else - { - if (ex.getCause() != null) - { - handleException(mbean, ex.getCause()); - } - else - { - String msg = ex.getMessage(); - if (msg == null) - { - msg = ex.toString(); - } - ViewUtility.popupErrorMessage(mbean.getInstanceName(), msg); - printStackTrace(ex); - } - } - - } - - /** - * Registers the notification listener with the MBeanServer - * @param mbean managed bean - * @param name notification name - * @param type notification type - * @throws Exception if server connection is broken or if listener could not be created - */ - public static void createNotificationlistener(ManagedBean mbean, String name, String type) - throws Exception - { - JMXManagedObject jmxbean = (JMXManagedObject)mbean; - JMXServerRegistry serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(mbean); - serverRegistry.addNotificationListener(mbean, name, type); - MBeanServerConnection mbsc = serverRegistry.getServerConnection(); - - if (mbsc == null) - { - throw new ManagementConsoleException("Server connection is broken"); - } - mbsc.addNotificationListener(jmxbean.getObjectName(), serverRegistry.getNotificationListener(), null, null); - } - - public static void removeNotificationListener(ManagedBean mbean, String name, String type) throws Exception - { - JMXServerRegistry serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(mbean); - serverRegistry.removeNotificationListener(mbean, name, type); - } - - /** - * Checks if the server registry contains attribute information for this mbean. If not then it queries the - * mbean server for complete mbean information, else it gets the latest value of the given attribute - * from mbean server. - * @return attribute data for the given mbean attribute - */ - public static AttributeData getAttributeData(ManagedBean mbean, String attribute) throws Exception - { - JMXServerRegistry serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(mbean); - ManagedAttributeModel attributeModel = serverRegistry.getAttributeModel(mbean); - if (attributeModel == null) - { - // If process is here, it means the mbeanInfo is not retrieved from mbean server even once for this mbean - getMBeanInfo(mbean); - } - else - { - // refresh attribute value from mbean server - refreshAttribute(mbean, attribute); - } - attributeModel = serverRegistry.getAttributeModel(mbean); - return attributeModel.getAttribute(attribute); - } - - /** - * Retrieves the latest attribute value from mbean server for the given mbean attribute - * and also sets that value in the attribute model in the server registry - * @return latest attribute value for the given mbean attribute - */ - public static Object refreshAttribute(ManagedBean mbean, String attribute) throws Exception - { - JMXServerRegistry serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(mbean); - MBeanServerConnection mbsc = serverRegistry.getServerConnection(); - - if (mbsc == null) - { - throw new ManagementConsoleException("Server connection is broken"); - } - - Object value = mbsc.getAttribute(((JMXManagedObject)mbean).getObjectName(), attribute); - // update the attribute data in server registry for this attribute - ManagedAttributeModel attributeModel = serverRegistry.getAttributeModel(mbean); - attributeModel.setAttributeValue(attribute, value); - return value; - } - - /** - * Retrieves the attribute values from MBeanSever and stores in the server registry. - * @param mbean - * @return the attribute model - * @throws Exception if attributes can not be retrieved from MBeanServer - */ - public static ManagedAttributeModel getAttributes(ManagedBean mbean) throws Exception - { - ObjectName objName = ((JMXManagedObject)mbean).getObjectName(); - String[] attributes = null; - AttributeList list = null; - - JMXServerRegistry serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(mbean); - MBeanServerConnection mbsc = serverRegistry.getServerConnection(); - MBeanAttributeInfo[] attributesInfo = null; - ManagedAttributeModel attributeModel = serverRegistry.getAttributeModel(mbean); - - if (attributeModel == null) - { - // If the process is here, then it means the attribute values are not retrieved from mbean server - // even once for this mbean. Create attribute model, retrieve values from mbean server and - // set the attribute model in server registry for this mbean - attributeModel = new ManagedAttributeModel(); - attributesInfo = serverRegistry.getMBeanInfo(mbean).getAttributes(); - attributes = new String[attributesInfo.length]; - for (int i = 0; i< attributesInfo.length ; i++) - { - attributes[i] = attributesInfo[i].getName(); - attributeModel.setAttributeDescription(attributes[i], attributesInfo[i].getDescription()); - attributeModel.setAttributeWritable(attributes[i], attributesInfo[i].isWritable()); - attributeModel.setAttributeReadable(attributes[i], attributesInfo[i].isReadable()); - } - } - else - { - attributes = attributeModel.getAttributeNames().toArray(new String[0]); - } - - if (attributes.length != 0) - { - list = mbsc.getAttributes(objName, attributes); - for (Iterator itr = list.iterator(); itr.hasNext();) - { - Attribute attrib = (Attribute)itr.next(); - attributeModel.setAttributeValue(attrib.getName(), attrib.getValue()); - } - } - - serverRegistry.setAttributeModel(mbean, attributeModel); - return attributeModel; - } - - /** - * Updates the attribute value of an MBean - * @param mbean - * @param attribute - * @param value - * @throws Exception if MBeanServer throws exception in updating the attribute value - */ - public static void updateAttribute(ManagedBean mbean, AttributeData attribute, String value) throws Exception - { - JMXManagedObject jmxbean = (JMXManagedObject)mbean; - JMXServerRegistry serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(mbean); - - MBeanServerConnection mbsc = serverRegistry.getServerConnection(); - - Object newValue = value; - if (attribute.getDataType().equals(Long.class.getName())) - { - if (MAX_LONG.compareTo(new BigInteger(value)) == -1) - { - throw new ManagementConsoleException("Entered value is too big for \"" + - ViewUtility.getDisplayText(attribute.getName()) + "\""); - } - newValue = new Long(Long.parseLong(value)); - } - else if (attribute.getDataType().equals(Integer.class.getName())) - { - if (MAX_INT.compareTo(new BigInteger(value)) == -1) - { - throw new ManagementConsoleException("Entered value is too big for " + attribute.getName()); - } - newValue = new Integer(Integer.parseInt(value)); - } - - mbsc.setAttribute(jmxbean.getObjectName(), new Attribute(attribute.getName(), newValue)); - // Update the value in the registry, to avoid refreshing from mbsc - ManagedAttributeModel attributeModel = serverRegistry.getAttributeModel(mbean); - attributeModel.setAttributeValue(attribute.getName(), newValue); - } - - /** - * populates the operation data model in server registry for given mbean - * @param mbean - * @return operation data model - */ - public static OperationDataModel getOperations(ManagedBean mbean) - { - JMXServerRegistry serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(mbean); - OperationDataModel dataModel = serverRegistry.getOperationModel(mbean); - if (dataModel == null) - { - // Create operation model and set it in server registry for this mbean - MBeanOperationInfo[] operationsInfo = serverRegistry.getMBeanInfo(mbean).getOperations(); - dataModel = new OperationDataModel(); - - for (int i = 0; i < operationsInfo.length; i++) - { - dataModel.addOperation(operationsInfo[i]); - } - - serverRegistry.setOperationModel(mbean, dataModel); - } - return dataModel; - } - - /** - * populates the notification in the server registry for given mbean - * @param mbean - * @return notification info model - */ - public static NotificationInfoModel[] getNotificationInfo(ManagedBean mbean) - { - JMXServerRegistry serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(mbean); - MBeanNotificationInfo[] info = serverRegistry.getMBeanInfo(mbean).getNotifications(); - - // Check if this mbean sends any notification - if (info == null || info.length == 0) - return null; - - // Create notification model if not already set in the server registry for this mbean - List<NotificationInfoModel> list = serverRegistry.getNotificationInfo(mbean); - if (list != null) - return list.toArray(new NotificationInfoModel[0]); - else - list = new ArrayList<NotificationInfoModel>(); - - for (int i = 0; i < info.length; i++) - { - list.add(new NotificationInfoModel(info[i].getName(), info[i].getDescription(), info[i].getNotifTypes())); - } - - // Set the notification model in the server registry for this mbean - serverRegistry.setNotificationInfo(mbean, list); - return list.toArray(new NotificationInfoModel[0]); - } - - /** - * Retrieves all the MBeans from mbean server for a given domain - * @return list of ManagedBeans - */ - public static List<ManagedBean> getManagedObjectsForDomain(ManagedServer server, String domain) throws Exception - { - List<ManagedBean> mbeans = new ArrayList<ManagedBean>(); - JMXServerRegistry serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(server); - MBeanServerConnection mbsc = serverRegistry.getServerConnection(); - ObjectName objName = new ObjectName(domain + ":*"); - Set objectInstances = mbsc.queryMBeans(objName, null); - - for (Iterator itr = objectInstances.iterator(); itr.hasNext();) - { - ObjectInstance instance = (ObjectInstance)itr.next(); - ManagedBean obj = new JMXManagedObject(instance.getObjectName()); - mbeans.add(obj); - } - - return mbeans; - } - - /** - * Returns all the domains for the given server. This method can be removed as now this RCP is specific to - * Qpid and domain is also fixed - */ - public static List<String> getAllDomains(ManagedServer server) throws Exception - { - JMXServerRegistry serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(server); - MBeanServerConnection mbsc = serverRegistry.getServerConnection(); - String[] domains = mbsc.getDomains(); - return Arrays.asList(domains); - } - - public static void printOutput(String statement) - { - if (ApplicationRegistry.debug) - { - System.out.println(statement); - } - } - - public static void printStackTrace(Throwable ex) - { - if (ApplicationRegistry.debug) - { - ex.printStackTrace(); - } - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/AttributeData.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/AttributeData.java deleted file mode 100644 index ccd4cf8df8..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/AttributeData.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.management.ui.model; - -public class AttributeData -{ - String name = ""; - String description = ""; - String dataType = ""; - Object value = ""; - boolean readable = true; - boolean writable = false; - - - public String getDataType() - { - return dataType; - } - public void setDataType(String dataType) - { - this.dataType = dataType; - } - - public String getDescription() - { - return description; - } - public void setDescription(String description) - { - this.description = description; - } - - public String getName() - { - return name; - } - public void setName(String name) - { - this.name = name; - } - - public Object getValue() - { - return value; - } - public void setValue(Object value) - { - if (value != null) - this.value = value; - } - public boolean isReadable() - { - return readable; - } - public void setReadable(boolean readable) - { - this.readable = readable; - } - public boolean isWritable() - { - return writable; - } - public void setWritable(boolean writable) - { - this.writable = writable; - } - - public boolean isNumber() - { - if ("int".equals(dataType) || "java.lang.Integer".equals(dataType) || - "long".equals(dataType) || "java.lang.Long".equals(dataType) ) - { - return true; - } - else - return false; - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/ManagedAttributeModel.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/ManagedAttributeModel.java deleted file mode 100644 index b3219f15ea..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/ManagedAttributeModel.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.management.ui.model; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public class ManagedAttributeModel -{ - HashMap<String, AttributeData> _attributeMap = new HashMap<String, AttributeData>(); - - public void setAttributeValue(String name, Object value) - { - if (value == null) - return; - - AttributeData data = null; - String dataType = value.getClass().getName(); - if (_attributeMap.containsKey(name)) - { - data = _attributeMap.get(name); - data.setValue(value); - } - else - { - data = new AttributeData(); - data.setName(name); - data.setValue(value); - _attributeMap.put(name, data); - } - data.setDataType(dataType); - } - - - public void setAttributeDescription(String name, String value) - { - if (_attributeMap.containsKey(name)) - { - _attributeMap.get(name).setDescription(value); - } - else - { - AttributeData data = new AttributeData(); - data.setName(name); - data.setDescription(value); - _attributeMap.put(name, data); - } - } - - public void setAttributeReadable(String name, boolean readable) - { - if (_attributeMap.containsKey(name)) - { - _attributeMap.get(name).setReadable(readable); - } - else - { - AttributeData data = new AttributeData(); - data.setName(name); - data.setReadable(readable); - _attributeMap.put(name, data); - } - } - - public void setAttributeWritable(String name, boolean writable) - { - if (_attributeMap.containsKey(name)) - { - _attributeMap.get(name).setWritable(writable); - } - else - { - AttributeData data = new AttributeData(); - data.setName(name); - data.setWritable(writable); - _attributeMap.put(name, data); - } - } - - public List<String> getAttributeNames() - { - return new ArrayList<String>(_attributeMap.keySet()); - } - - public AttributeData[] getAttributes() - { - return _attributeMap.values().toArray(new AttributeData[0]); - } - - public AttributeData getAttribute(String name) - { - return _attributeMap.get(name); - } - - public int getCount() - { - return _attributeMap.size(); - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/NotificationInfoModel.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/NotificationInfoModel.java deleted file mode 100644 index 6d4160889e..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/NotificationInfoModel.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.management.ui.model; - -public class NotificationInfoModel -{ - String name; - String description; - String[] types; - - public NotificationInfoModel(String name, String desc, String[] types) - { - this.name = name; - this.description = desc; - this.types = types; - } - - public String getDescription() - { - return description; - } - - public String getName() - { - return name; - } - - public String[] getTypes() - { - return types; - } - -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/NotificationObject.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/NotificationObject.java deleted file mode 100644 index 926e5f0a24..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/NotificationObject.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.management.ui.model; - -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.TimeZone; - -import javax.management.ObjectName; - -public class NotificationObject -{ - - private long _sequenceNo; - private Date _timeStamp; - private String _message; - private Object _source; - private String _type; // INFO, WARN, etc - private static final SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss dd/MM/yy z"); - - public NotificationObject(long seqNo, Date timeStamp, String message, Object source, String type) - { - this._sequenceNo = seqNo; - this._message = message; - this._source = source; - this._type = type; - this._timeStamp = timeStamp; - dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); - } - - public Object getSource() - { - return _source; - } - public void setSource(Object _source) - { - this._source = _source; - } - - public String getSourceName() - { - if (_source instanceof ObjectName) - { - return ((ObjectName)_source).getKeyProperty("name"); - } - - return null; - } - - public String getMessage() - { - return _message; - } - public void setMessage(String _message) - { - this._message = _message; - } - public long getSequenceNo() - { - return _sequenceNo; - } - public void setSequenceNo(long no) - { - _sequenceNo = no; - } - public String getTimeStamp() - { - return dateFormat.format(_timeStamp); - } - public void setTimeStamp(Date stamp) - { - _timeStamp = stamp; - } - public String getType() - { - return _type; - } - public void setType(String _type) - { - this._type = _type; - } - -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/OperationData.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/OperationData.java deleted file mode 100644 index bf3b730b3e..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/OperationData.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.management.ui.model; - -import java.util.List; - -public class OperationData -{ - private String _name; - private String _description; - private String _returnType; - private int _impact; - private List<ParameterData> _parameters; - - public OperationData(String value) - { - this._name = value; - } - - public String getName() - { - return _name; - } - - public String getDescription() - { - return _description; - } - - public void setDescription(String description) - { - this._description = description; - } - - public List<ParameterData> getParameters() - { - return _parameters; - } - - public void setParameters(List<ParameterData> parameters) - { - this._parameters = parameters; - } - - public int getImpact() - { - return _impact; - } - - public void setImpact(int impact) - { - this._impact = impact; - } - - public String getReturnType() - { - return _returnType; - } - - public void setReturnType(String returnType) - { - this._returnType = returnType; - } - - public boolean isReturnTypeBoolean() - { - return (_returnType.equals("boolean") || _returnType.equals("java.lang.Boolean")); - } - - public boolean isReturnTypeVoid() - { - return (_returnType.equals("void") || _returnType.equals("java.lang.Void")); - } - - public Object getParameterValue(String paramName) - { - if (_parameters == null) - { - return null; - } - - for (int i = 0; i < _parameters.size(); i++) - { - if (paramName.equalsIgnoreCase(_parameters.get(i).getName())) - { - return _parameters.get(i).getValue(); - } - } - - return null; - } -}
\ No newline at end of file diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/OperationDataModel.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/OperationDataModel.java deleted file mode 100644 index 96964a81ef..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/OperationDataModel.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.management.ui.model; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import javax.management.MBeanOperationInfo; -import javax.management.MBeanParameterInfo; - -public class OperationDataModel -{ - HashMap<String, OperationData> _operationMap = new HashMap<String, OperationData>(); - - public void addOperation(MBeanOperationInfo opInfo) - { - OperationData opData = new OperationData(opInfo.getName()); - opData.setDescription(opInfo.getDescription()); - opData.setImpact(opInfo.getImpact()); - opData.setReturnType(opInfo.getReturnType()); - - int parametersCount = opInfo.getSignature().length; - if (parametersCount != 0) - { - List<ParameterData> paramList = new ArrayList<ParameterData>(); - for (int i = 0; i < parametersCount; i++) - { - MBeanParameterInfo paramInfo = opInfo.getSignature()[i]; - ParameterData param = new ParameterData(paramInfo.getName(), paramInfo.getDescription(), - paramInfo.getType()); - paramList.add(param); - } - opData.setParameters(paramList); - } - - _operationMap.put(opInfo.getName(), opData); - } - - public OperationData getOperation(String name) - { - return _operationMap.get(name); - } - - public List<OperationData> getOperations() - { - return new ArrayList<OperationData>(_operationMap.values()); - } - - public int getCount() - { - return _operationMap.size(); - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/ParameterData.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/ParameterData.java deleted file mode 100644 index d12217c6eb..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/ParameterData.java +++ /dev/null @@ -1,95 +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.management.ui.model; - -/** - * Class representing an mbean operation parameter - * @author Bhupendra Bhardwaj - */ -public class ParameterData -{ - private String _name; - private String _description; - private String _type; - private Object _value; - - ParameterData(String name, String desc, String type) - { - this._name = name; - this._description = desc; - this._type = type; - setDefaultValue(); - } - - public String getDescription() - { - return _description; - } - - public String getName() - { - return _name; - } - - public String getType() - { - return _type; - } - - public Object getValue() - { - return _value; - } - - public void setValueFromString(String strValue) - { - if ("int".equals(_type)) - _value = Integer.parseInt(strValue); - else if (isBoolean()) - _value = Boolean.valueOf(strValue); - else if ("long".equals(_type)) - _value = Long.parseLong(strValue); - else - _value = strValue; - } - - public void setValue(Object value) - { - this._value = value; - } - - public boolean isBoolean() - { - return (_type.equals("boolean") || _type.equals("java.lang.Boolean")); - } - - public void setDefaultValue() - { - if (isBoolean()) - { - _value = Boolean.valueOf("false"); - } - else - { - _value = null; - } - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/sasl/CRAMMD5HashedSaslClientFactory.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/sasl/CRAMMD5HashedSaslClientFactory.java deleted file mode 100644 index 32a0c12344..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/sasl/CRAMMD5HashedSaslClientFactory.java +++ /dev/null @@ -1,60 +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.management.ui.sasl; - -import java.util.Map; - -import javax.security.auth.callback.CallbackHandler; -import javax.security.sasl.Sasl; -import javax.security.sasl.SaslClient; -import javax.security.sasl.SaslClientFactory; -import javax.security.sasl.SaslException; - -public class CRAMMD5HashedSaslClientFactory implements SaslClientFactory -{ - /** The name of this mechanism */ - public static final String MECHANISM = "CRAM-MD5-HASHED"; - - public SaslClient createSaslClient(String[] mechanisms, String authorizationId, String protocol, - String serverName, Map<String, ?> props, CallbackHandler cbh) - throws SaslException - { - for (int i = 0; i < mechanisms.length; i++) - { - if (mechanisms[i].equals(MECHANISM)) - { - if (cbh == null) - { - throw new SaslException("CallbackHandler must not be null"); - } - - String[] mechs = {"CRAM-MD5"}; - return Sasl.createSaslClient(mechs, authorizationId, protocol, serverName, props, cbh); - } - } - return null; - } - - public String[] getMechanismNames(Map props) - { - return new String[]{MECHANISM}; - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/sasl/ClientSaslFactory.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/sasl/ClientSaslFactory.java deleted file mode 100644 index ce9a273eaa..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/sasl/ClientSaslFactory.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.management.ui.sasl; - -import java.util.Map; - -import javax.security.auth.callback.CallbackHandler; -import javax.security.sasl.SaslClient; -import javax.security.sasl.SaslClientFactory; -import javax.security.sasl.SaslException; - -public class ClientSaslFactory implements SaslClientFactory -{ - public SaslClient createSaslClient(String[] mechs, String authorizationId, String protocol, - String serverName, Map props, CallbackHandler cbh) - throws SaslException - { - for (int i = 0; i < mechs.length; i++) - { - if (mechs[i].equals("PLAIN")) - { - return new PlainSaslClient(authorizationId, cbh); - } - } - return null; - } - - /** - * Simple-minded implementation that ignores props - */ - public String[] getMechanismNames(Map props) - { - return new String[]{"PLAIN"}; - } - -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/sasl/JCAProvider.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/sasl/JCAProvider.java deleted file mode 100644 index d8189f3ac3..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/sasl/JCAProvider.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.management.ui.sasl; - -import java.security.Provider; -import java.util.Map; - -import javax.security.sasl.SaslClientFactory; - -public class JCAProvider extends Provider -{ - private static final long serialVersionUID = 1L; - - /** - * Creates the security provider with a map from SASL mechanisms to implementing factories. - * - * @param providerMap The map from SASL mechanims to implementing factory classes. - */ - public JCAProvider(Map<String, Class<? extends SaslClientFactory>> providerMap) - { - super("AMQSASLProvider", 1.0, "A JCA provider that registers all " - + "AMQ SASL providers that want to be registered"); - register(providerMap); - } - - /** - * Registers client factory classes for a map of mechanism names to client factory classes. - * - * @param providerMap The map from SASL mechanims to implementing factory classes. - */ - private void register(Map<String, Class<? extends SaslClientFactory>> providerMap) - { - for (Map.Entry<String, Class<? extends SaslClientFactory>> me : providerMap.entrySet()) - { - put("SaslClientFactory." + me.getKey(), me.getValue().getName()); - } - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/sasl/PlainSaslClient.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/sasl/PlainSaslClient.java deleted file mode 100644 index 22190f29eb..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/sasl/PlainSaslClient.java +++ /dev/null @@ -1,203 +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.management.ui.sasl; - -import java.io.*; -import javax.security.auth.callback.*; -import javax.security.sasl.*; - -public class PlainSaslClient implements SaslClient -{ - - private boolean completed; - private CallbackHandler cbh; - private String authorizationID; - private String authenticationID; - private byte password[]; - private static byte SEPARATOR = 0; - - public PlainSaslClient(String authorizationID, CallbackHandler cbh) throws SaslException - { - completed = false; - this.cbh = cbh; - Object[] userInfo = getUserInfo(); - this.authorizationID = authorizationID; - this.authenticationID = (String) userInfo[0]; - this.password = (byte[]) userInfo[1]; - if (authenticationID == null || password == null) - { - throw new SaslException("PLAIN: authenticationID and password must be specified"); - } - } - - public byte[] evaluateChallenge(byte[] challenge) throws SaslException - { - if (completed) - { - throw new IllegalStateException("PLAIN: authentication already " + - "completed"); - } - completed = true; - try - { - byte authzid[] = - authorizationID == null ? null : authorizationID.getBytes("UTF8"); - byte authnid[] = authenticationID.getBytes("UTF8"); - byte response[] = - new byte[ - password.length + - authnid.length + - 2 + // SEPARATOR - (authzid != null ? authzid.length : 0) - ]; - int size = 0; - if (authzid != null) { - System.arraycopy(authzid, 0, response, 0, authzid.length); - size = authzid.length; - } - response[size++] = SEPARATOR; - System.arraycopy(authnid, 0, response, size, authnid.length); - size += authnid.length; - response[size++] = SEPARATOR; - System.arraycopy(password, 0, response, size, password.length); - clearPassword(); - return response; - } catch (UnsupportedEncodingException e) { - throw new SaslException("PLAIN: Cannot get UTF-8 encoding of ids", - e); - } - } - - public String getMechanismName() - { - return "PLAIN"; - } - - public boolean hasInitialResponse() - { - return true; - } - - public boolean isComplete() - { - return completed; - } - - public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException - { - if (completed) { - throw new IllegalStateException("PLAIN: this mechanism supports " + - "neither integrity nor privacy"); - } else { - throw new IllegalStateException("PLAIN: authentication not " + - "completed"); - } - } - - public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException - { - if (completed) - { - throw new IllegalStateException("PLAIN: this mechanism supports " + - "neither integrity nor privacy"); - } - else - { - throw new IllegalStateException("PLAIN: authentication not " + - "completed"); - } - } - - public Object getNegotiatedProperty(String propName) - { - if (completed) - { - if (propName.equals(Sasl.QOP)) - { - return "auth"; - } - else - { - return null; - } - } - else - { - throw new IllegalStateException("PLAIN: authentication not " + - "completed"); - } - } - - private void clearPassword() - { - if (password != null) - { - for (int i = 0 ; i < password.length ; i++) - { - password[i] = 0; - } - password = null; - } - } - - public void dispose() throws SaslException - { - clearPassword(); - } - - protected void finalize() - { - clearPassword(); - } - - private Object[] getUserInfo() throws SaslException - { - try - { - final String userPrompt = "PLAIN authentication id: "; - final String pwPrompt = "PLAIN password: "; - NameCallback nameCb = new NameCallback(userPrompt); - PasswordCallback passwordCb = new PasswordCallback(pwPrompt, false); - cbh.handle(new Callback[] { nameCb, passwordCb }); - String userid = nameCb.getName(); - char pwchars[] = passwordCb.getPassword(); - byte pwbytes[]; - if (pwchars != null) - { - pwbytes = (new String(pwchars)).getBytes("UTF8"); - passwordCb.clearPassword(); - } - else - { - pwbytes = null; - } - return (new Object[] { userid, pwbytes }); - } - catch (IOException e) - { - throw new SaslException("Cannot get password", e); - } - catch (UnsupportedCallbackException e) - { - throw new SaslException("Cannot get userid/password", e); - } - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/sasl/SaslProvider.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/sasl/SaslProvider.java deleted file mode 100644 index 2917de8740..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/sasl/SaslProvider.java +++ /dev/null @@ -1,35 +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.management.ui.sasl; - -import java.security.Provider; - -public class SaslProvider extends Provider -{ - private static final long serialVersionUID = -6978096016899676466L; - - public SaslProvider() - { - super("SaslClientFactory", 1.0, "SASL PLAIN CLIENT MECHANISM"); - put("SaslClientFactory.PLAIN", "ClientSaslFactory"); - } - -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/sasl/UserPasswordCallbackHandler.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/sasl/UserPasswordCallbackHandler.java deleted file mode 100644 index 1602229c85..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/sasl/UserPasswordCallbackHandler.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.management.ui.sasl; - -import java.io.*; -import javax.security.auth.callback.*; - -public class UserPasswordCallbackHandler implements CallbackHandler -{ - private String user; - private char[] pwchars; - - public UserPasswordCallbackHandler(String user, String password) - { - this.user = user; - this.pwchars = password.toCharArray(); - } - - public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException - { - for (int i = 0; i < callbacks.length; i++) - { - if (callbacks[i] instanceof NameCallback) - { - NameCallback ncb = (NameCallback) callbacks[i]; - ncb.setName(user); - } - else if (callbacks[i] instanceof PasswordCallback) - { - PasswordCallback pcb = (PasswordCallback) callbacks[i]; - pcb.setPassword(pwchars); - } - else - { - throw new UnsupportedCallbackException(callbacks[i]); - } - } - } - - private void clearPassword() - { - if (pwchars != null) - { - for (int i = 0 ; i < pwchars.length ; i++) - { - pwchars[i] = 0; - } - pwchars = null; - } - } - - protected void finalize() - { - clearPassword(); - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/sasl/UsernameHashedPasswordCallbackHandler.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/sasl/UsernameHashedPasswordCallbackHandler.java deleted file mode 100644 index f4e3d2661e..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/sasl/UsernameHashedPasswordCallbackHandler.java +++ /dev/null @@ -1,82 +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.management.ui.sasl; - -import java.io.IOException; - -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.callback.NameCallback; -import javax.security.auth.callback.PasswordCallback; -import javax.security.auth.callback.UnsupportedCallbackException; - -import org.apache.qpid.management.ui.views.ViewUtility; - -public class UsernameHashedPasswordCallbackHandler implements CallbackHandler -{ - private String user; - private char[] pwchars; - - public UsernameHashedPasswordCallbackHandler(String user, String password) throws Exception - { - this.user = user; - this.pwchars = ViewUtility.getHash(password); - } - - public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException - { - for (int i = 0; i < callbacks.length; i++) - { - if (callbacks[i] instanceof NameCallback) - { - NameCallback ncb = (NameCallback) callbacks[i]; - ncb.setName(user); - } - else if (callbacks[i] instanceof PasswordCallback) - { - PasswordCallback pcb = (PasswordCallback) callbacks[i]; - pcb.setPassword(pwchars); - } - else - { - throw new UnsupportedCallbackException(callbacks[i]); - } - } - } - - - private void clearPassword() - { - if (pwchars != null) - { - for (int i = 0 ; i < pwchars.length ; i++) - { - pwchars[i] = 0; - } - pwchars = null; - } - } - - protected void finalize() - { - clearPassword(); - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/AttributesTabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/AttributesTabControl.java deleted file mode 100644 index 3234503fb5..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/AttributesTabControl.java +++ /dev/null @@ -1,936 +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.management.ui.views; - -import static org.apache.qpid.management.ui.Constants.*; - -import org.apache.qpid.management.ui.ApplicationRegistry; -import org.apache.qpid.management.ui.ManagedBean; -import org.apache.qpid.management.ui.jmx.JMXServerRegistry; -import org.apache.qpid.management.ui.jmx.MBeanUtility; -import org.apache.qpid.management.ui.model.AttributeData; -import org.apache.qpid.management.ui.model.ManagedAttributeModel; -import org.eclipse.jface.viewers.IColorProvider; -import org.eclipse.jface.viewers.IFontProvider; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.IStructuredContentProvider; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.ITableLabelProvider; -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.jface.viewers.TableViewer; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.jface.viewers.ViewerSorter; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.DisposeEvent; -import org.eclipse.swt.events.DisposeListener; -import org.eclipse.swt.events.KeyEvent; -import org.eclipse.swt.events.KeyListener; -import org.eclipse.swt.events.MouseEvent; -import org.eclipse.swt.events.MouseListener; -import org.eclipse.swt.events.MouseMoveListener; -import org.eclipse.swt.events.MouseTrackListener; -import org.eclipse.swt.events.PaintEvent; -import org.eclipse.swt.events.PaintListener; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.Font; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.graphics.Rectangle; -import org.eclipse.swt.layout.FillLayout; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Canvas; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Event; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Listener; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.widgets.TabFolder; -import org.eclipse.swt.widgets.Table; -import org.eclipse.swt.widgets.TableColumn; -import org.eclipse.swt.widgets.TableItem; -import org.eclipse.swt.widgets.Text; -import org.eclipse.ui.forms.widgets.Form; -import org.eclipse.ui.forms.widgets.FormToolkit; - - -/** - * Creates controller composite for the attribute's tab. - * @author Bhupendra Bhardwaj - */ -public class AttributesTabControl extends TabControl -{ - private FormToolkit _toolkit; - private Form _form; - private Table _table = null; - private TableViewer _tableViewer = null; - private static final int[] tableWidths = new int[] {300, 300}; - - private Composite _tableComposite = null; - private Composite _buttonsComposite = null; - - private DisposeListener tableDisposeListener = new DisposeListenerImpl(); - final Image image; - private Button _detailsButton = null; - private Button _editButton = null; - private Button _graphButton = null; - private Button _refreshButton = null; - private boolean disableEditing = false; - - private static final String MAX_VALUE = "MaxValue"; - private static final String GRAPH_VALUES = "GraphValues"; - private int GRAPH_WIDTH = 700; - private int GRAPH_HEIGHT = 450; - private int GRAPH_ITEM_GAP = 100; - private int startX = 80; - private int startY = 60; - - public AttributesTabControl(TabFolder tabFolder) - { - super(tabFolder); - _toolkit = new FormToolkit(_tabFolder.getDisplay()); - _form = _toolkit.createForm(_tabFolder); - GridLayout gridLayout = new GridLayout(2, false); - gridLayout.marginWidth = 0; - gridLayout.marginHeight = 0; - _form.getBody().setLayout(gridLayout); - _tableComposite = _toolkit.createComposite(_form.getBody()); - _tableComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - _tableComposite.setLayout(new GridLayout()); - _buttonsComposite = _toolkit.createComposite(_form.getBody()); - _buttonsComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true)); - _buttonsComposite.setLayout(new GridLayout()); - - image = Display.getCurrent().getSystemImage(SWT.ICON_INFORMATION); - createWidgets(); - } - - /** - * @see TabControl#getControl() - */ - public Control getControl() - { - return _form; - } - - /** - * Creates required widgets for Attribute's tab - */ - protected void createWidgets() - { - createTable(); - createTableViewer(); - createButtons(); - addTableListeners(); - } - - /** - * Creates table for listing the MBean attributes - */ - private void createTable() - { - _table = _toolkit.createTable(_tableComposite, SWT.FULL_SELECTION); - GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true); - _table.setLayoutData(gridData); - - for (int i = 0; i < ATTRIBUTE_TABLE_TITLES.length; ++i) - { - final TableColumn column = new TableColumn(_table, SWT.NONE); - column.setText(ATTRIBUTE_TABLE_TITLES[i]); - column.setWidth(tableWidths[i]); - column.setResizable(false); - } - - _table.setLinesVisible (true); - _table.setHeaderVisible (true); - } - - /** - * Creates tableviewer for the attribute's table - */ - private void createTableViewer() - { - _tableViewer = new TableViewer(_table); - _tableViewer.setUseHashlookup(true); - _tableViewer.setColumnProperties(ATTRIBUTE_TABLE_TITLES); - _tableViewer.setContentProvider(new ContentProviderImpl()); - _tableViewer.setLabelProvider(new LabelProviderImpl()); - _tableViewer.setSorter(new ViewerSorterImpl()); - } - - private void createButtons() - { - addDetailsButton(); - addEditButton(); - addGraphButton(); - addRefreshButton(); - } - - private void addDetailsButton() - { - // Create and configure the button for attribute details - _detailsButton = _toolkit.createButton(_buttonsComposite, BUTTON_DETAILS, SWT.PUSH | SWT.CENTER); - _detailsButton.setFont(ApplicationRegistry.getFont(FONT_BUTTON)); - GridData gridData = new GridData(SWT.CENTER, SWT.TOP, false, false); - gridData.widthHint = 80; - _detailsButton.setLayoutData(gridData); - _detailsButton.addSelectionListener(new SelectionAdapter() - { - public void widgetSelected(SelectionEvent e) - { - disableEditing = true; - int index = _table.getSelectionIndex(); - TableItem item = _table.getItem(index); - createDetailsPopup((AttributeData)item.getData()); - disableEditing = false; - setFocus(); - } - }); - } - - /** - * Creates the button for editing attributes. - */ - private void addEditButton() - { - // Create and configure the button for editing attribute - _editButton = _toolkit.createButton(_buttonsComposite, BUTTON_EDIT_ATTRIBUTE, SWT.PUSH | SWT.CENTER); - _editButton.setFont(ApplicationRegistry.getFont(FONT_BUTTON)); - GridData gridData = new GridData(SWT.CENTER, SWT.TOP, false, false); - gridData.widthHint = 80; - _editButton.setLayoutData(gridData); - _editButton.addSelectionListener(new SelectionAdapter() - { - public void widgetSelected(SelectionEvent e) - { - int index = _table.getSelectionIndex(); - TableItem item = _table.getItem(index); - createDetailsPopup((AttributeData)item.getData()); - setFocus(); - } - }); - } - - /** - * Creates the button for viewing Graphs - */ - private void addGraphButton() - { - _graphButton = _toolkit.createButton(_buttonsComposite, BUTTON_GRAPH, SWT.PUSH | SWT.CENTER); - _graphButton.setFont(ApplicationRegistry.getFont(FONT_BUTTON)); - GridData gridData = new GridData(SWT.CENTER, SWT.TOP, false, false); - gridData.widthHint = 80; - _graphButton.setLayoutData(gridData); - _graphButton.addSelectionListener(new SelectionAdapter() - { - public void widgetSelected(SelectionEvent event) - { - int selectionIndex = _table.getSelectionIndex(); - AttributeData data = (AttributeData)_table.getItem(selectionIndex).getData(); - createGraph(data); - setFocus(); - } - }); - } - - /** - * Creates the "Refresh" button - */ - private void addRefreshButton() - { - _refreshButton = _toolkit.createButton(_buttonsComposite, BUTTON_REFRESH, SWT.PUSH | SWT.CENTER); - - _refreshButton.setFont(ApplicationRegistry.getFont(FONT_BUTTON)); - GridData gridData = new GridData(SWT.CENTER, SWT.TOP, false, false); - gridData.widthHint = 80; - _refreshButton.setLayoutData(gridData); - _refreshButton.addSelectionListener(new SelectionAdapter() - { - public void widgetSelected(SelectionEvent e) - { - try - { - // refresh the attributes list - refresh(_mbean); - } - catch (Exception ex) - { - MBeanUtility.handleException(_mbean, ex); - } - - } - }); - } - - private void addTableListeners() - { - _tableViewer.addSelectionChangedListener(new ISelectionChangedListener(){ - public void selectionChanged(SelectionChangedEvent evt) - { - IStructuredSelection ss = (IStructuredSelection)evt.getSelection(); - checkForEnablingButtons((AttributeData)ss.getFirstElement()); - } - }); - - MouseListenerImpl listener = new MouseListenerImpl(); - _tableViewer.getTable().addMouseTrackListener(listener); - _tableViewer.getTable().addMouseMoveListener(listener); - _tableViewer.getTable().addMouseListener(listener); - - _table.addDisposeListener(tableDisposeListener); - - // _table is equal to _tableViewer.getControl() - _table.addListener(SWT.MeasureItem, new Listener() { - public void handleEvent(Event event) - { - event.height = event.gc.getFontMetrics().getHeight() * 3/2; - } - }); - } - - /** - * Listeners implementation class for showing table tooltip - * @author Bhupendra Bhardwaj - */ - private class MouseListenerImpl implements MouseTrackListener, MouseMoveListener, KeyListener, MouseListener - { - Shell tooltipShell = null; - Label tooltipLabel = null; - public void mouseHover(MouseEvent event) - { - TableItem item = _table.getItem (new Point (event.x, event.y)); - - if (item != null) - { - AttributeData data = (AttributeData)item.getData(); - if (tooltipShell != null && !tooltipShell.isDisposed ()) tooltipShell.dispose (); - tooltipShell = new Shell(_table.getShell(), SWT.ON_TOP | SWT.NO_FOCUS | SWT.TOOL); - tooltipShell.setBackground(event.display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); - FillLayout layout = new FillLayout(); - layout.marginWidth = 2; - tooltipShell.setLayout(layout); - tooltipLabel = new Label(tooltipShell, SWT.NONE); - tooltipLabel.setForeground(event.display.getSystemColor(SWT.COLOR_INFO_FOREGROUND)); - tooltipLabel.setBackground(event.display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); - tooltipLabel.setText(data.getDescription()); - tooltipLabel.setData("_TABLEITEM", item); - tooltipLabel.addListener(SWT.MouseExit, tooltipLabelListener); - tooltipLabel.addListener(SWT.MouseDown, tooltipLabelListener); - Point size = tooltipShell.computeSize(SWT.DEFAULT, SWT.DEFAULT); - Rectangle rect = item.getBounds(0); - Point pt = _table.toDisplay(rect.x, rect.y); - tooltipShell.setBounds(pt.x, pt.y, size.x, size.y); - tooltipShell.setVisible(true); - } - } - public void mouseEnter(MouseEvent e) - { - } - public void mouseExit(MouseEvent e) - { - } - - // MouseMoveListener implementation - public void mouseMove(MouseEvent event) - { - if (tooltipShell == null) - return; - - tooltipShell.dispose(); - tooltipShell = null; - tooltipLabel = null; - } - - // KeyListener implementation - public void keyPressed(KeyEvent e) - { - if (tooltipShell == null) - return; - - tooltipShell.dispose(); - tooltipShell = null; - tooltipLabel = null; - } - public void keyReleased(KeyEvent e) - { - - } - - // MouseListener implementation - public void mouseDoubleClick(MouseEvent event) - { - if (tooltipShell != null) - { - tooltipShell.dispose(); - tooltipShell = null; - tooltipLabel = null; - } - Table table = (Table)event.getSource(); - int selectionIndex = table.getSelectionIndex(); - AttributeData data = (AttributeData)table.getItem(selectionIndex).getData(); - createDetailsPopup(data); - } - public void mouseDown(MouseEvent e) - { - if (tooltipShell != null) - { - tooltipShell.dispose(); - tooltipShell = null; - tooltipLabel = null; - } - } - public void mouseUp(MouseEvent e) - { - - } - } // end of MouseListenerImpl - - /** - * Creates pop-up window for showing attribute details - * @param data - Selectes attribute - */ - public void createDetailsPopup(AttributeData data) - { - int width = 500; - int height = 250; - if (!isSimpleType(data.getValue())) - { - width = 650; - height = 450; - } - - Display display = Display.getCurrent(); - Shell shell = ViewUtility.createPopupShell(ATTRIBUTE, width, height); - createDetailsPopupContents(shell, data); - - shell.open(); - while (!shell.isDisposed()) - { - if (!display.readAndDispatch()) - { - display.sleep(); - } - } - shell.dispose(); - } - - /** - * Listener class for table tooltip label - */ - final Listener tooltipLabelListener = new Listener () - { - public void handleEvent (Event event) - { - Label label = (Label)event.widget; - Shell shell = label.getShell(); - switch (event.type) - { - case SWT.MouseDown: - Event e = new Event(); - e.item = (TableItem)label.getData ("_TABLEITEM"); - _table.setSelection(new TableItem[] {(TableItem)e.item}); - shell.dispose(); - _table.setFocus(); - break; - case SWT.MouseExit: - shell.dispose(); - break; - } - } - }; - - - /** - * Create the contents for the attribute details window pop-up - * @param shell - The shell that will be filled with details. - * @param attribute - Selected attribute - */ - private void createDetailsPopupContents(Composite shell, AttributeData attribute) - { - GridLayout layout = new GridLayout(2, false); - layout.horizontalSpacing = 10; - layout.verticalSpacing = 10; - layout.marginHeight = 20; - layout.marginWidth = 20; - - Composite parent = _toolkit.createComposite(shell, SWT.NONE); - parent.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - parent.setLayout(layout); - - // Name - Label label = _toolkit.createLabel(parent, ATTRIBUTE_TABLE_TITLES[0], SWT.NONE); - GridData layoutData = new GridData(SWT.TRAIL, SWT.TOP, false, false); - label.setLayoutData(layoutData); - int textStyle = SWT.BEGINNING | SWT.BORDER |SWT.READ_ONLY; - Text value = _toolkit.createText(parent, ViewUtility.getDisplayText(attribute.getName()), textStyle); - value.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); - - - // Description - label = _toolkit.createLabel(parent, DESCRIPTION, SWT.NONE); - label.setLayoutData(new GridData(SWT.TRAIL, SWT.TOP, false, false)); - value = _toolkit.createText(parent, attribute.getDescription(), textStyle); - value.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); - - // value - label = _toolkit.createLabel(parent, ATTRIBUTE_TABLE_TITLES[1], SWT.NONE); - label.setLayoutData(new GridData(SWT.TRAIL, SWT.TOP, false, false)); - - if (!attribute.isReadable()) - { - value = _toolkit.createText(parent, "", textStyle); - value.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); - } - else - { - if (!isSimpleType(attribute.getValue())) - { - Composite composite = new Composite(parent, SWT.BORDER); - composite.setLayout(new GridLayout()); - composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); - ViewUtility.populateCompositeWithData(_toolkit, composite, attribute.getValue()); - } - else - { - if (attribute.isWritable()) - { - value = _toolkit.createText(parent, "", SWT.BEGINNING | SWT.BORDER); - value.addVerifyListener(new NumberVerifyListener()); - - // set data to access in the listener - parent.setData(attribute); - } - else - { - value = _toolkit.createText(parent, "", textStyle); - } - - value.setText(attribute.getValue().toString()); - value.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); - } - } - - - // Update button - Button updateButton = addUpdateButton(parent); - updateButton.setData(value); - if (!attribute.isWritable()) - { - updateButton.setVisible(false); - } - - if (disableEditing) - { - value.setEditable(false); - updateButton.setVisible(false); - } - } - - /** - * Create the button for updating attributes. This should be enabled for writable attribute - */ - private Button addUpdateButton(Composite parent) - { - final Button updateButton = new Button(parent, SWT.PUSH | SWT.CENTER); - // set the data to access in the listener - parent.setData(BUTTON_UPDATE, updateButton); - - updateButton.setText(BUTTON_UPDATE); - GridData gridData = new GridData (SWT.CENTER, SWT.BOTTOM, true, true, 2, 1); - gridData.widthHint = 100; - updateButton.setLayoutData(gridData); - updateButton.addSelectionListener(new SelectionAdapter() - { - public void widgetSelected(SelectionEvent event) - { - try - { - Button button = (Button)event.widget; - Text text = (Text)button.getData(); - AttributeData data = (AttributeData)button.getParent().getData(); - MBeanUtility.updateAttribute(_mbean, data, text.getText()); - button.getShell().close(); - refresh(); - } - catch (Exception ex) - { - MBeanUtility.handleException(_mbean, ex); - } - } - }); - - return updateButton; - } - - // Refresh from the server registry - public void refresh() - { - JMXServerRegistry serverRegistry = (JMXServerRegistry)ApplicationRegistry.getServerRegistry(_mbean); - ManagedAttributeModel attributesList = serverRegistry.getAttributeModel(_mbean); - _tableViewer.setInput(attributesList); - } - - /** - * Refreshes the attribute tab by querying the mbean server for latest values - */ - @Override - public void refresh(ManagedBean mbean) - { - _mbean = mbean; - if (_mbean == null) - { - _tableViewer.setInput(null); - return; - } - ManagedAttributeModel attributesList = null; - try - { - attributesList = MBeanUtility.getAttributes(mbean); - } - catch(Exception ex) - { - MBeanUtility.handleException(_mbean, ex); - } - _tableViewer.setInput(attributesList); - checkForEnablingButtons(getSelectionAttribute()); - - _form.layout(true); - _form.getBody().layout(true, true); - } - - /** - * @see TabControl#setFocus() - */ - public void setFocus() - { - _table.setFocus(); - } - - /** - * Checks which buttons are to be enabled or disabled. The graph button will be enabled only - * for readable number attributes. Editing is enabled for writeable attribtues. - * @param attribute - */ - private void checkForEnablingButtons(AttributeData attribute) - { - if (attribute == null) - { - _detailsButton.setEnabled(false); - _editButton.setEnabled(false); - _graphButton.setEnabled(false); - _refreshButton.setEnabled(false); - return; - } - - _detailsButton.setEnabled(true); - _refreshButton.setEnabled(true); - if (attribute.isWritable()) - { - _editButton.setEnabled(true); - _graphButton.setEnabled(false); - } - else - { - _editButton.setEnabled(false); - // Currently only Queues are having attributes, which are suitable for a graph - if (attribute.isNumber() && _mbean.isQueue()) - { - _graphButton.setEnabled(true); - } - else - { - _graphButton.setEnabled(false); - } - } - } - - /** - * Creates graph in a pop-up window for given attribute. - * @param data - */ - private void createGraph(final AttributeData data) - { - Display display = Display.getCurrent(); - Shell shell = new Shell(display, SWT.BORDER | SWT.CLOSE | SWT.MIN | SWT.MAX); - shell.setText(_mbean.getName()); - int x = display.getBounds().width; - int y = display.getBounds().height; - shell.setBounds(x/4, y/4, GRAPH_WIDTH, GRAPH_HEIGHT); - shell.setLayout(new FillLayout()); - - final Canvas canvas = new Canvas(shell, SWT.NONE); - long currentValue = Long.parseLong(data.getValue().toString()); - long mValue = getGraphMaxValue(currentValue); - canvas.setData(MAX_VALUE, mValue); - canvas.setData(GRAPH_VALUES, new long[] {0,0,0,0,0,currentValue}); - - canvas.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); - canvas.addPaintListener(new PaintListener() - { - public void paintControl(PaintEvent event) - { - Canvas canvas = (Canvas)event.widget; - int maxX = canvas.getSize().x; - int maxY = canvas.getSize().y; - event.gc.fillRectangle(canvas.getBounds()); - event.gc.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK)); - event.gc.setLineWidth(4); - - Object canvasData = canvas.getData(MAX_VALUE); - String str = canvasData.toString(); - long maxValue = Long.parseLong(str); - // Set the graph dimensions - event.gc.drawText("0", startX - 40, maxY - startY - 10); - event.gc.drawText("" + maxValue/2, startX - 40, maxY/2); - event.gc.drawText("" + maxValue, startX - 40, startY); - - // horizontal line - event.gc.drawLine(startX, maxY - startY, maxX - 60, maxY - startY); - // vertical line - event.gc.drawLine(startX, maxY - startY, startX, startY); - // set graph text - event.gc.drawText(data.getName(), startX - 40, startY - 40); - event.gc.drawText("25 sec", startX, maxY - startY + 10); - event.gc.drawText("20 sec", startX + GRAPH_ITEM_GAP, maxY - startY + 10); - event.gc.drawText("15 sec", startX + GRAPH_ITEM_GAP * 2, maxY - startY + 10); - event.gc.drawText("10 sec", startX + GRAPH_ITEM_GAP * 3, maxY - startY + 10); - event.gc.drawText(" 5 sec", startX + GRAPH_ITEM_GAP * 4, maxY - startY + 10); - event.gc.drawText(" 0 sec", startX + GRAPH_ITEM_GAP * 5, maxY - startY + 10); - - // plot the graph now for values - event.gc.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLUE)); - canvasData = canvas.getData(GRAPH_VALUES); - long[] graphValues = (long[]) canvasData; - for (int i = 0; i < graphValues.length; i++) - { - int x = startX + i * GRAPH_ITEM_GAP; - int yTotalLength = (maxY - 2 * startY); - float ratio = ((float)graphValues[i]/(float)maxValue); - int itemlength = (int)(yTotalLength * ratio); - int y = maxY - startY - itemlength; - event.gc.drawLine(x, maxY- startY, x, y); - event.gc.drawText(String.valueOf(graphValues[i]), x, y - 20); - } - } - }); - - shell.open(); - - // Set up the timer for the animation - Runnable runnable = new Runnable() - { - public void run() - { - try - { - animate(canvas, data); - Display.getCurrent().timerExec(TIMER_INTERVAL, this); - } - catch(Exception ex) - { - MBeanUtility.handleException(ex); - } - } - }; - - // Launch the timer - display.timerExec(TIMER_INTERVAL, runnable); - - while (!shell.isDisposed()) - { - if (!display.readAndDispatch()) - { - display.sleep(); - } - } - - // Kill the timer - display.timerExec(-1, runnable); - shell.dispose(); - } - - /** - * @return selected attribute in the table - */ - public AttributeData getSelectionAttribute() - { - int index = _table.getSelectionIndex(); - if (index == -1) - return null; - - return (AttributeData)_table.getItem(index).getData(); - } - - /** - * checks for newer values of selected attribute to update the graph - * @param canvas - * @param data - * @throws Exception - */ - private void animate(Canvas canvas, AttributeData data) throws Exception - { - String attribute = data.getName(); - Object valueObj = MBeanUtility.refreshAttribute(_mbean, attribute); - int value = Integer.parseInt(String.valueOf(valueObj)); - Object canvasData = canvas.getData(GRAPH_VALUES); - long[] graphValues = (long[]) canvasData; - - for (int i = 0; i < graphValues.length -1; i++) - { - graphValues[i] = graphValues[i + 1]; - } - graphValues[graphValues.length - 1] = value; - - canvasData = canvas.getData(MAX_VALUE); - long maxValue = Long.parseLong(String.valueOf(canvasData)); - if (maxValue < value) - { - maxValue = getGraphMaxValue(value); - canvas.setData(MAX_VALUE, maxValue); - } - - canvas.redraw(); - } - - /** - * @param maxAttributeValue - * @return dynamically calculated value for y-axis on the graph - */ - private long getGraphMaxValue(long maxAttributeValue) - { - long maxGraphValue = 100; - long temp = maxAttributeValue * 3/2; - if (temp > maxGraphValue) - { - long modulus = temp % 100; - maxGraphValue = temp + ( 100 - modulus); - } - - return maxGraphValue; - } - - /** - * Content Provider class for the table viewer - * @author Bhupendra Bhardwaj - */ - private class ContentProviderImpl implements IStructuredContentProvider - { - - public void inputChanged(Viewer v, Object oldInput, Object newInput) - { - - } - - public void dispose() - { - - } - - public Object[] getElements(Object parent) - { - return ((ManagedAttributeModel)parent).getAttributes(); - } - } - - /** - * Label Provider class for the table viewer - * @author Bhupendra Bhardwaj - */ - private class LabelProviderImpl extends LabelProvider implements ITableLabelProvider, - IFontProvider, - IColorProvider - { - AttributeData attribute = null; - public String getColumnText(Object element, int columnIndex) - { - String result = ""; - attribute = (AttributeData) element; - - switch (columnIndex) - { - case 0 : // attribute name column - result = ViewUtility.getDisplayText(attribute.getName()); - break; - case 1 : // attribute value column - if (attribute.getValue() != null) - result = String.valueOf(attribute.getValue()); - break; - default : - result = ""; - } - - return result; - } - - public Image getColumnImage(Object element, int columnIndex) - { - return null; - } - - public Font getFont(Object element) - { - return ApplicationRegistry.getFont(FONT_TABLE_CELL); - } - - public Color getForeground(Object element) - { - attribute = (AttributeData) element; - if (attribute.isWritable()) - return Display.getCurrent().getSystemColor(SWT.COLOR_DARK_BLUE); - else - return Display.getCurrent().getSystemColor(SWT.COLOR_BLACK); - } - public Color getBackground(Object element) - { - return _form.getBackground(); - } - } - - private class DisposeListenerImpl implements DisposeListener - { - public void widgetDisposed(DisposeEvent e) - { - - } - } - - /** - * Sorter class for the table viewer. It sorts the table for according to attribute name. - * @author Bhupendra Bhardwaj - * - */ - private class ViewerSorterImpl extends ViewerSorter - { - public int compare(Viewer viewer, Object o1, Object o2) - { - AttributeData attribtue1 = (AttributeData)o1; - AttributeData attribtue2 = (AttributeData)o2; - - return collator.compare(attribtue1.getName(), attribtue2.getName()); - } - } -}
\ No newline at end of file diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/ConnectionTypeTabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/ConnectionTypeTabControl.java deleted file mode 100644 index d891a45210..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/ConnectionTypeTabControl.java +++ /dev/null @@ -1,59 +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.management.ui.views; - -import org.apache.qpid.management.ui.ApplicationRegistry; -import org.apache.qpid.management.ui.Constants; -import org.apache.qpid.management.ui.ManagedBean; -import org.apache.qpid.management.ui.ServerRegistry; -import org.eclipse.swt.widgets.TabFolder; - -/** - * Controller class, which takes care of displaying appropriate information and widgets for Connections. - * This allows user to select Connections and add those to the navigation view - */ -public class ConnectionTypeTabControl extends MBeanTypeTabControl -{ - - public ConnectionTypeTabControl(TabFolder tabFolder) - { - super(tabFolder, Constants.CONNECTION); - createWidgets(); - } - - protected void createWidgets() - { - createHeaderComposite(getFormComposite()); - createButtonsComposite(getFormComposite()); - createListComposite(getFormComposite()); - } - - protected void populateList() throws Exception - { - // map should be cleared before populating it with new values - getMBeansMap().clear(); - - ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(MBeanView.getServer()); - java.util.List<ManagedBean> list = serverRegistry.getConnections(MBeanView.getVirtualHost()); - getListWidget().setItems(getItems(list)); - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/ExchangeTypeTabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/ExchangeTypeTabControl.java deleted file mode 100644 index ee55b251ee..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/ExchangeTypeTabControl.java +++ /dev/null @@ -1,60 +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.management.ui.views; - -import org.apache.qpid.management.ui.ApplicationRegistry; -import org.apache.qpid.management.ui.Constants; -import org.apache.qpid.management.ui.ManagedBean; -import org.apache.qpid.management.ui.ServerRegistry; -import org.eclipse.swt.widgets.TabFolder; - -/** - * Controller class, which takes care of displaying appropriate information and widgets for Exchanges. - * This allows user to select Exchanges and add those to the navigation view - * @author Bhupendra Bhardwaj - */ -public class ExchangeTypeTabControl extends MBeanTypeTabControl -{ - - public ExchangeTypeTabControl(TabFolder tabFolder) - { - super(tabFolder, Constants.EXCHANGE); - createWidgets(); - } - - protected void createWidgets() - { - createHeaderComposite(getFormComposite()); - createButtonsComposite(getFormComposite()); - createListComposite(getFormComposite()); - } - - protected void populateList() throws Exception - { - // map should be cleared before populating it with new values - getMBeansMap().clear(); - - ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(MBeanView.getServer()); - java.util.List<ManagedBean> list = serverRegistry.getExchanges(MBeanView.getVirtualHost()); - getListWidget().setItems(getItems(list)); - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/INotificationViewer.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/INotificationViewer.java deleted file mode 100644 index bc560b6064..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/INotificationViewer.java +++ /dev/null @@ -1,32 +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.management.ui.views; - -import java.util.List; - -import org.apache.qpid.management.ui.model.NotificationObject; - -public interface INotificationViewer -{ - public void addNotification(NotificationObject notification); - - public void addNotification(List<NotificationObject> notificationList); -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/MBeanTypeTabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/MBeanTypeTabControl.java deleted file mode 100644 index 24dfb519fd..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/MBeanTypeTabControl.java +++ /dev/null @@ -1,336 +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.management.ui.views; - -import static org.apache.qpid.management.ui.Constants.BUTTON_REFRESH; -import static org.apache.qpid.management.ui.Constants.FONT_BOLD; -import static org.apache.qpid.management.ui.Constants.FONT_ITALIC; -import static org.apache.qpid.management.ui.Constants.FONT_NORMAL; - -import java.util.Collections; -import java.util.HashMap; - -import org.apache.qpid.management.ui.ApplicationRegistry; -import org.apache.qpid.management.ui.ManagedBean; -import org.apache.qpid.management.ui.jmx.MBeanUtility; -import org.apache.qpid.management.ui.model.AttributeData; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.List; -import org.eclipse.swt.widgets.TabFolder; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.forms.widgets.Form; -import org.eclipse.ui.forms.widgets.FormToolkit; - -/** - * Abstract class to be extended by the Controller classes for different MBean types (Connection, Queue, Exchange) - */ -public abstract class MBeanTypeTabControl -{ - private FormToolkit _toolkit = null; - private Form _form = null; - private TabFolder _tabFolder = null; - private Composite _composite = null; - private Composite _headerComposite = null; - private Composite _listComposite = null; - private Label _labelName = null; - private Label _labelDesc = null; - private Label _labelList = null; - - private org.eclipse.swt.widgets.List _list = null; - private Button _refreshButton = null; - private Button _addButton = null; - - private String _type = null; - - // maps an mbean name with the mbean object. Required to get mbean object when an mbean - // is to be added to the navigation view. - private HashMap<String, ManagedBean> _objectsMap = new HashMap<String, ManagedBean>(); - private Sorter _sorterByName = new Sorter(); - - public MBeanTypeTabControl(TabFolder tabFolder, String type) - { - _type = type; - _tabFolder = tabFolder; - _toolkit = new FormToolkit(_tabFolder.getDisplay()); - _form = _toolkit.createForm(_tabFolder); - createFormComposite(); - } - - public FormToolkit getToolkit() - { - return _toolkit; - } - - public Control getControl() - { - return _form; - } - - public String getType() - { - return _type; - } - - protected List getListWidget() - { - return _list; - } - - protected HashMap<String, ManagedBean> getMBeansMap() - { - return _objectsMap; - } - - public Sorter getMBeanNameSorter() - { - return _sorterByName; - } - - public Button getAddButton() - { - return _addButton; - } - - public Button getRefreshButton() - { - return _refreshButton; - } - - /** - * Creates the main Composite, which will contain all other Composites and Widgets - */ - protected void createFormComposite() - { - _form.getBody().setLayout(new GridLayout()); - _composite = _toolkit.createComposite(_form.getBody(), SWT.NONE); - _composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - GridLayout layout = new GridLayout(); - layout.verticalSpacing = 10; - layout.horizontalSpacing = 0; - _composite.setLayout(layout); - } - - protected Composite getFormComposite() - { - return _composite; - } - - /** - * Creates the header composite, which has MBean type name and description - * @param parentComposite - */ - protected void createHeaderComposite(Composite parentComposite) - { - _headerComposite = _toolkit.createComposite(parentComposite); - _headerComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); - GridLayout layout = new GridLayout(); - layout.verticalSpacing = 10; - layout.horizontalSpacing = 0; - _headerComposite.setLayout(layout); - - _labelName = _toolkit.createLabel(_headerComposite, "Type:", SWT.NONE); - GridData gridData = new GridData(SWT.CENTER, SWT.TOP, true, false); - _labelName.setLayoutData(gridData); - _labelName.setFont(ApplicationRegistry.getFont(FONT_BOLD)); - - _labelDesc = _toolkit.createLabel(_headerComposite, " ", SWT.NONE); - _labelDesc.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, true, false)); - _labelDesc.setFont(ApplicationRegistry.getFont(FONT_ITALIC)); - - _headerComposite.layout(); - } - - /** - * Creates Composite, which contains the common buttons - Add and Refresh. - * @param parentComposite - */ - protected void createButtonsComposite(Composite parentComposite) - { - Composite composite = _toolkit.createComposite(parentComposite); - composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); - GridLayout layout = new GridLayout(2, true); - layout.verticalSpacing = 10; - layout.horizontalSpacing = 20; - composite.setLayout(layout); - - createAddButton(composite); - createRefreshButton(composite); - } - - /** - * Creates the Add button, which adds the selected item to the navigation view - * @param parentComposite - */ - protected void createAddButton(Composite parentComposite) - { - Button _addButton = _toolkit.createButton(parentComposite, "<- Add to Navigation", SWT.PUSH); - GridData gridData = new GridData(SWT.CENTER, SWT.CENTER, false, false); - _addButton.setLayoutData(gridData); - _addButton.addSelectionListener(new SelectionAdapter(){ - public void widgetSelected(SelectionEvent e) - { - if (_list.getSelectionCount() == 0) - return; - - String[] selectedItems = _list.getSelection(); - for (int i = 0; i < selectedItems.length; i++) - { - String name = selectedItems[i]; - // pass the ManagedBean to the navigation view to be added - ManagedBean mbean = _objectsMap.get(name); - IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); - NavigationView view = (NavigationView)window.getActivePage().findView(NavigationView.ID); - try - { - view.addManagedBean(mbean); - } - catch (Exception ex) - { - MBeanUtility.handleException(mbean, ex); - } - } - } - }); - } - - /** - * Creates the Refresh button, which gets syncs the items with the broker server - * @param parentComposite - */ - protected void createRefreshButton(Composite parentComposite) - { - Button _refreshButton = _toolkit.createButton(parentComposite, BUTTON_REFRESH, SWT.PUSH); - GridData gridData = new GridData(SWT.CENTER, SWT.CENTER, false, false); - gridData.widthHint = 120; - _refreshButton.setLayoutData(gridData); - _refreshButton.addSelectionListener(new SelectionAdapter(){ - public void widgetSelected(SelectionEvent e) - { - try - { - // refresh the list from the broker server - populateList(); - } - catch (Exception ex) - { - MBeanUtility.handleException(ex); - } - } - }); - } - - /** - * Creates the Composite, which contains the items ( Connections, Exchanges or Queues) - * @param parentComposite - */ - protected void createListComposite(Composite parentComposite) - { - // Composite to contain the item list - _listComposite = _toolkit.createComposite(parentComposite); - GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true); - _listComposite.setLayoutData(gridData); - GridLayout layout = new GridLayout(); - layout.verticalSpacing = 0; - _listComposite.setLayout(layout); - - // Label for item name - _labelList = _toolkit.createLabel(_listComposite, " ", SWT.CENTER); - gridData = new GridData(SWT.CENTER, SWT.TOP, true, false, 1, 1); - _labelList.setLayoutData(gridData); - _labelList.setFont(ApplicationRegistry.getFont(FONT_NORMAL)); - - _list = new List(_listComposite, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); - gridData = new GridData(SWT.FILL, SWT.FILL, true, true,1, 1); - _list.setLayoutData(gridData); - - } - - /** - * This is called from MBean View to refresh the tab contents - * @throws Exception - */ - public void refresh() throws Exception - { - setLabelValues(); - populateList(); - layout(); - } - - protected void setLabelValues() - { - _labelName.setText("Type : " + _type); - _labelDesc.setText("Select the " + _type + "(s) to add in the Navigation View"); - _labelList.setText("-- List of " + _type + "s --"); - } - - protected abstract void populateList() throws Exception; - - public void layout() - { - _form.layout(true); - _form.getBody().layout(true, true); - } - - // sets the map with appropriate mbean and name - protected String[] getItems(java.util.List<ManagedBean> list) - { - if (list == null) - return new String[0]; - - Collections.sort(list, _sorterByName); - String[] items = new String[list.size()]; - int i = 0; - for (ManagedBean mbean : list) - { - items[i++] = mbean.getName(); - _objectsMap.put(mbean.getName(), mbean); - } - return items; - } - - protected class ComparatorImpl implements java.util.Comparator<AttributeData> - { - public int compare(AttributeData data1, AttributeData data2) - { - Integer int1 = Integer.parseInt(data1.getValue().toString()); - Integer int2 = Integer.parseInt(data2.getValue().toString()); - return int1.compareTo(int2) * -1; - } - } - - protected class Sorter implements java.util.Comparator<ManagedBean> - { - public int compare(ManagedBean mbean1, ManagedBean mbean2) - { - return mbean1.getName().compareTo(mbean2.getName()); - } - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/MBeanView.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/MBeanView.java deleted file mode 100644 index 344c3c4e7f..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/MBeanView.java +++ /dev/null @@ -1,545 +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.management.ui.views; - -import java.util.HashMap; - -import static org.apache.qpid.management.ui.Constants.*; -import org.apache.qpid.management.ui.ApplicationRegistry; -import org.apache.qpid.management.ui.ManagedBean; -import org.apache.qpid.management.ui.ManagedServer; -import org.apache.qpid.management.ui.ServerRegistry; -import org.apache.qpid.management.ui.exceptions.InfoRequiredException; -import org.apache.qpid.management.ui.jmx.MBeanUtility; -import org.apache.qpid.management.ui.model.AttributeData; -import org.apache.qpid.management.ui.model.OperationData; -import org.apache.qpid.management.ui.model.OperationDataModel; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.swt.SWT; -import org.eclipse.swt.layout.FormAttachment; -import org.eclipse.swt.layout.FormData; -import org.eclipse.swt.layout.FormLayout; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Event; -import org.eclipse.swt.widgets.Listener; -import org.eclipse.swt.widgets.TabFolder; -import org.eclipse.swt.widgets.TabItem; -import org.eclipse.ui.ISelectionListener; -import org.eclipse.ui.IWorkbenchPart; -import org.eclipse.ui.forms.widgets.Form; -import org.eclipse.ui.forms.widgets.FormToolkit; -import org.eclipse.ui.part.ViewPart; - -/** - * MBean View create appropriate view based on the user selection on the Navigation View. - * Create TabFolder for all MBeans and displays the attribtues and method tabs. - * @author Bhupendra Bhardwaj - * - */ -public class MBeanView extends ViewPart -{ - public static final String ID = "org.apache.qpid.management.ui.mbeanView"; - private static final String CONTROLLER = "CONTROLLER"; - - private FormToolkit _toolkit = null; - private Form _form = null; - private String _formText = APPLICATION_NAME; - private static ManagedServer _server = null; - private TreeObject _selectedNode = null; - private ManagedBean _mbean = null; - private static String _virtualHostName = null; - // This map contains a TabFolder for each kind of MBean. - // TabFolder is mapped with mbeantype(Connection, Queue and Exchange) - private HashMap<String, TabFolder> tabFolderMap = new HashMap<String, TabFolder>(); - private ISelectionListener selectionListener = new SelectionListenerImpl(); - - // TabFolder to list all the mbeans for a given mbeantype(eg Connection, Queue, Exchange) - private TabFolder typeTabFolder = null; - - private TabFolder notificationTabFolder = null; - /* - * Listener for the selection events in the navigation view - */ - private class SelectionListenerImpl implements ISelectionListener - { - public void selectionChanged(IWorkbenchPart part, ISelection sel) - { - if (!(sel instanceof IStructuredSelection)) - return; - - IStructuredSelection ss = (IStructuredSelection) sel; - _selectedNode = (TreeObject)ss.getFirstElement(); - - - // mbean should be set to null. A selection done on the navigation view can be either an mbean or - // an mbeantype. For mbeantype selection(eg Connection, Queue, Exchange) _mbean will remain null. - _mbean = null; - setInvisible(); - - // If a selected node(mbean) gets unregistered from mbean server, mbeanview should - // make the tabfolber for that mbean invisible - if (_selectedNode == null) - return; - - setServer(); - refreshMBeanView(); - setFormTitle(); - } - } - - private void setFormTitle() - { - if (_mbean != null) - { - _formText = _mbean.getType(); - if ((_mbean.getVirtualHostName() != null) && (!DEFAULT_VH.equals(_mbean.getVirtualHostName())) ) - { - _formText = _formText.replaceFirst(VIRTUAL_HOST, _mbean.getVirtualHostName()); - if (_mbean.getName() != null && _mbean.getName().length() != 0) - { - _formText = _formText + ": " + _mbean.getName(); - } - } - } - else if ((_selectedNode.getVirtualHost() != null) && (!DEFAULT_VH.equals(_selectedNode.getVirtualHost()))) - { - _formText = _selectedNode.getVirtualHost(); - } - else - { - _formText = APPLICATION_NAME; - } - _form.setText(_formText); - } - - public void refreshMBeanView() - { - try - { - if (NODE_TYPE_SERVER.equals(_selectedNode.getType()) || - NODE_TYPE_DOMAIN.equals(_selectedNode.getType()) ) - { - return; - } - else if (NODE_TYPE_TYPEINSTANCE.equals(_selectedNode.getType())) - { - // An virtual host instance is selected - refreshTypeTabFolder(typeTabFolder.getItem(0)); - } - else if (NODE_TYPE_MBEANTYPE.equals(_selectedNode.getType())) - { - refreshTypeTabFolder(_selectedNode.getName()); - } - else if (NOTIFICATIONS.equals(_selectedNode.getType())) - { - refreshNotificationPage(); - } - else if (MBEAN.equals(_selectedNode.getType())) - { - _mbean = (ManagedBean)_selectedNode.getManagedObject(); - showSelectedMBean(); - } - - _form.layout(true); - _form.getBody().layout(true, true); - } - catch(Exception ex) - { - MBeanUtility.handleException(_mbean, ex); - } - } - - /** - * Sets the managedServer based on the selection in the navigation view - * At any given time MBeanView will be displaying information for an mbean of mbeantype - * for a specifiv managed server. This server information will be used by the tab controllers - * to get server registry. - */ - private void setServer() - { - if (NODE_TYPE_SERVER.equals(_selectedNode.getType()) || - NODE_TYPE_DOMAIN.equals(_selectedNode.getType()) ) - { - _server = (ManagedServer)_selectedNode.getManagedObject(); - _virtualHostName = null; - } - else - { - TreeObject parent = _selectedNode.getParent(); - while (parent != null && !parent.getType().equals(NODE_TYPE_SERVER)) - { - parent = parent.getParent(); - } - - if (parent != null && parent.getType().equals(NODE_TYPE_SERVER)) - _server = (ManagedServer)parent.getManagedObject(); - - _virtualHostName = _selectedNode.getVirtualHost(); - } - } - - public static ManagedServer getServer() - { - return _server; - } - - public static String getVirtualHost() - { - return _virtualHostName; - } - - private void showSelectedMBean() throws Exception - { - try - { - MBeanUtility.getMBeanInfo(_mbean); - } - catch(Exception ex) - { - MBeanUtility.handleException(_mbean, ex); - return; - } - - TabFolder tabFolder = tabFolderMap.get(_mbean.getType()); - /* - * This solution can be used if there are many versions of Qpid running. Otherwise - * there is no need to create a tabFolder everytime a bean is selected. - if (tabFolder != null && !tabFolder.isDisposed()) - { - tabFolder.dispose(); - } - tabFolder = createTabFolder(); - */ - if (tabFolder == null) - { - tabFolder = createMBeanTabFolder(); - } - - int tabIndex = 0; - if (NOTIFICATIONS.equals(_selectedNode.getType())) - { - tabIndex = tabFolder.getItemCount() -1; - } - - TabItem tab = tabFolder.getItem(tabIndex); - // If folder is being set as visible after tab refresh, then the tab - // doesn't have the focus. - tabFolder.setSelection(tabIndex); - refreshTab(tab); - setVisible(tabFolder); - } - - public void createPartControl(Composite parent) - { - // Create the Form - _toolkit = new FormToolkit(parent.getDisplay()); - _form = _toolkit.createForm(parent); - _form.getBody().setLayout(new FormLayout()); - _form.setText(APPLICATION_NAME); - - // Add selection listener for selection events in the Navigation view - getSite().getPage().addSelectionListener(NavigationView.ID, selectionListener); - - // Add mbeantype TabFolder. This will list all the mbeans under a mbeantype (eg Queue, Exchange). - // Using this list mbeans will be added in the navigation view - createMBeanTypeTabFolder(); - - createNotificationsTabFolder(); - } - - private TabFolder createMBeanTabFolder() - { - TabFolder tabFolder = new TabFolder(_form.getBody(), SWT.NONE); - FormData layoutData = new FormData(); - layoutData.left = new FormAttachment(0); - layoutData.top = new FormAttachment(0); - layoutData.right = new FormAttachment(100); - layoutData.bottom = new FormAttachment(100); - tabFolder.setLayoutData(layoutData); - tabFolder.setVisible(false); - - createAttributesTab(tabFolder); - createOperationTabs(tabFolder); - createNotificationsTab(tabFolder); - - tabFolder.addListener(SWT.Selection, new Listener() - { - public void handleEvent(Event evt) - { - TabItem tab = (TabItem)evt.item; - refreshTab(tab); - } - }); - - tabFolderMap.put(_mbean.getType(), tabFolder); - return tabFolder; - } - - private void refreshTab(TabItem tab) - { - // We can avoid refreshing the attributes tab because it's control - // already contains the required values. But it is added for now and - // will remove if there is any performance issue or any other issue. - // The operations control should be refreshed because there is only one - // controller for all operations tab. - // The Notifications control needs to refresh with latest set of notifications - - if (tab == null) - return; - - TabControl controller = (TabControl)tab.getData(CONTROLLER); - controller.refresh(_mbean); - } - - public void setFocus() - { - //_form.setFocus(); - } - - public void dispose() - { - _toolkit.dispose(); - super.dispose(); - } - - private void createAttributesTab(TabFolder tabFolder) - { - ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(_mbean); - if (serverRegistry.getAttributeModel(_mbean).getCount() == 0) - { - return; - } - - TabItem tab = new TabItem(tabFolder, SWT.NONE); - tab.setText(ATTRIBUTES); - AttributesTabControl controller = new AttributesTabControl(tabFolder); - tab.setControl(controller.getControl()); - tab.setData(CONTROLLER, controller); - } - - private void createOperationTabs(TabFolder tabFolder) - { - ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(_mbean); - int operationsCount = serverRegistry.getOperationModel(_mbean).getCount(); - if (operationsCount == 0) - { - return; - } - - OperationDataModel operationModel = serverRegistry.getOperationModel(_mbean); - for (OperationData operationData : operationModel.getOperations()) - { - TabItem operationTab = new TabItem(tabFolder, SWT.NONE); - operationTab.setText(ViewUtility.getDisplayText(operationData.getName())); - operationTab.setData(operationData); - OperationTabControl control = new OperationTabControl(tabFolder, operationData); - operationTab.setData(CONTROLLER, control); - operationTab.setControl(control.getControl()); - } - } - - private void createNotificationsTab(TabFolder tabFolder) - { - NotificationsTabControl controller = new NotificationsTabControl(tabFolder); - - TabItem tab = new TabItem(tabFolder, SWT.NONE); - tab.setText(NOTIFICATIONS); - tab.setData(CONTROLLER, controller); - tab.setControl(controller.getControl()); - } - - /** - * For the EditAttribtue Action. Invoking this from action is same as clicking - * "EditAttribute" button from Attribute tab. - */ - public void editAttribute() throws Exception - { - if (_mbean == null) - throw new InfoRequiredException("Please select the managed object and then attribute to be edited"); - - String name = (_mbean.getName() != null) ? _mbean.getName() : _mbean.getType(); - ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(_mbean); - if (serverRegistry.getAttributeModel(_mbean).getCount() == 0) - { - throw new InfoRequiredException("There are no attributes to be edited for " + name); - } - - TabFolder tabFolder = tabFolderMap.get(_mbean.getType()); - int index = tabFolder.getSelectionIndex(); - if (index != 0) - { - tabFolder.setSelection(0); - throw new InfoRequiredException("Please select the attribute to be edited"); - } - - TabItem tab = tabFolder.getItem(0); - AttributesTabControl tabControl = (AttributesTabControl)tab.getData(CONTROLLER); - AttributeData attribute = tabControl.getSelectionAttribute(); - if (attribute == null) - throw new InfoRequiredException("Please select the attribute to be edited"); - - tabControl.createDetailsPopup(attribute); - } - - /** - * Creates TabFolder and tabs for each mbeantype (eg Connection, Queue, Exchange) - */ - private void createMBeanTypeTabFolder() - { - typeTabFolder = new TabFolder(_form.getBody(), SWT.NONE); - FormData layoutData = new FormData(); - layoutData.left = new FormAttachment(0); - layoutData.top = new FormAttachment(0); - layoutData.right = new FormAttachment(100); - layoutData.bottom = new FormAttachment(100); - typeTabFolder.setLayoutData(layoutData); - typeTabFolder.setVisible(false); - - TabItem tab = new TabItem(typeTabFolder, SWT.NONE); - tab.setText(CONNECTION); - MBeanTypeTabControl controller = new ConnectionTypeTabControl(typeTabFolder); - tab.setData(CONTROLLER, controller); - tab.setControl(controller.getControl()); - - tab = new TabItem(typeTabFolder, SWT.NONE); - tab.setText(EXCHANGE); - controller = new ExchangeTypeTabControl(typeTabFolder); - tab.setData(CONTROLLER, controller); - tab.setControl(controller.getControl()); - - tab = new TabItem(typeTabFolder, SWT.NONE); - tab.setText(QUEUE); - controller = new QueueTypeTabControl(typeTabFolder); - tab.setData(CONTROLLER, controller); - tab.setControl(controller.getControl()); - - typeTabFolder.addListener(SWT.Selection, new Listener() - { - public void handleEvent(Event evt) - { - TabItem tab = (TabItem)evt.item; - try - { - refreshTypeTabFolder(tab); - } - catch (Exception ex) - { - MBeanUtility.handleException(ex); - } - } - }); - } - - private void createNotificationsTabFolder() - { - notificationTabFolder = new TabFolder(_form.getBody(), SWT.NONE); - FormData layoutData = new FormData(); - layoutData.left = new FormAttachment(0); - layoutData.top = new FormAttachment(0); - layoutData.right = new FormAttachment(100); - layoutData.bottom = new FormAttachment(100); - notificationTabFolder.setLayoutData(layoutData); - notificationTabFolder.setVisible(false); - - VHNotificationsTabControl controller = new VHNotificationsTabControl(notificationTabFolder); - TabItem tab = new TabItem(notificationTabFolder, SWT.NONE); - tab.setText(NOTIFICATIONS); - tab.setData(CONTROLLER, controller); - tab.setControl(controller.getControl()); - } - - private void refreshNotificationPage() - { - TabItem tab = notificationTabFolder.getItem(0); - VHNotificationsTabControl controller = (VHNotificationsTabControl)tab.getData(CONTROLLER); - controller.refresh(); - notificationTabFolder.setVisible(true); - } - - /** - * Refreshes the Selected mbeantype tab. The control lists all the available mbeans - * for an mbeantype(eg Queue, Exchange etc) - * @param tab - * @throws Exception - */ - private void refreshTypeTabFolder(TabItem tab) throws Exception - { - if (tab == null) - { - return; - } - typeTabFolder.setSelection(tab); - MBeanTypeTabControl controller = (MBeanTypeTabControl)tab.getData(CONTROLLER); - controller.refresh(); - typeTabFolder.setVisible(true); - } - - private void refreshTypeTabFolder(String type) throws Exception - { - if (CONNECTION.equals(type)) - { - refreshTypeTabFolder(typeTabFolder.getItem(0)); - } - else if (EXCHANGE.equals(type)) - { - refreshTypeTabFolder(typeTabFolder.getItem(1)); - } - else if (QUEUE.equals(type)) - { - refreshTypeTabFolder(typeTabFolder.getItem(2)); - } - } - - /** - * hides other folders and makes the given one visible. - * @param tabFolder - */ - private void setVisible(TabFolder tabFolder) - { - for (TabFolder folder : tabFolderMap.values()) - { - if (folder == tabFolder) - folder.setVisible(true); - else - folder.setVisible(false); - } - } - - private void setInvisible() - { - for (TabFolder folder : tabFolderMap.values()) - { - folder.setVisible(false); - } - - if (typeTabFolder != null) - { - typeTabFolder.setVisible(false); - } - - if (notificationTabFolder != null) - { - notificationTabFolder.setVisible(false); - } - } - -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NavigationView.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NavigationView.java deleted file mode 100644 index 1da13a9b56..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NavigationView.java +++ /dev/null @@ -1,1253 +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.management.ui.views; - -import static org.apache.qpid.management.ui.Constants.*; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import org.apache.qpid.management.ui.ApplicationRegistry; -import org.apache.qpid.management.ui.ManagedBean; -import org.apache.qpid.management.ui.ManagedServer; -import org.apache.qpid.management.ui.ServerRegistry; -import org.apache.qpid.management.ui.exceptions.InfoRequiredException; -import org.apache.qpid.management.ui.jmx.JMXServerRegistry; -import org.apache.qpid.management.ui.jmx.MBeanUtility; -import org.eclipse.jface.preference.PreferenceStore; -import org.eclipse.jface.viewers.DoubleClickEvent; -import org.eclipse.jface.viewers.IDoubleClickListener; -import org.eclipse.jface.viewers.IFontProvider; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.ITreeContentProvider; -import org.eclipse.jface.viewers.ITreeViewerListener; -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.jface.viewers.TreeExpansionEvent; -import org.eclipse.jface.viewers.TreeViewer; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.jface.viewers.ViewerSorter; -import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.Font; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Event; -import org.eclipse.swt.widgets.Listener; -import org.eclipse.swt.widgets.Menu; -import org.eclipse.swt.widgets.MenuItem; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.widgets.Tree; -import org.eclipse.swt.widgets.TreeItem; -import org.eclipse.ui.part.ViewPart; - -/** - * Navigation View for navigating the managed servers and managed beans on - * those servers - * @author Bhupendra Bhardwaj - */ -public class NavigationView extends ViewPart -{ - public static final String ID = "org.apache.qpid.management.ui.navigationView"; - public static final String INI_FILENAME = System.getProperty("user.home") + File.separator + "qpidManagementConsole.ini"; - - private static final String INI_SERVERS = "Servers"; - private static final String INI_QUEUES = QUEUE + "s"; - private static final String INI_CONNECTIONS = CONNECTION + "s"; - private static final String INI_EXCHANGES = EXCHANGE + "s"; - - private TreeViewer _treeViewer = null; - private TreeObject _rootNode = null; - private TreeObject _serversRootNode = null; - - private PreferenceStore _preferences; - // Map of connected servers - private HashMap<ManagedServer, TreeObject> _managedServerMap = new HashMap<ManagedServer, TreeObject>(); - - private void createTreeViewer(Composite parent) - { - _treeViewer = new TreeViewer(parent); - _treeViewer.setContentProvider(new ContentProviderImpl()); - _treeViewer.setLabelProvider(new LabelProviderImpl()); - _treeViewer.setSorter(new ViewerSorterImpl()); - - // layout the tree viewer below the label field, to cover the area - GridData layoutData = new GridData(); - layoutData = new GridData(); - layoutData.grabExcessHorizontalSpace = true; - layoutData.grabExcessVerticalSpace = true; - layoutData.horizontalAlignment = GridData.FILL; - layoutData.verticalAlignment = GridData.FILL; - _treeViewer.getControl().setLayoutData(layoutData); - _treeViewer.setUseHashlookup(true); - - createListeners(); - } - - /** - * Creates listeners for the JFace treeviewer - */ - private void createListeners() - { - _treeViewer.addDoubleClickListener(new IDoubleClickListener() - { - public void doubleClick(DoubleClickEvent event) - { - IStructuredSelection ss = (IStructuredSelection) event.getSelection(); - if ((ss == null) || (ss.getFirstElement() == null)) - { - return; - } - - boolean state = _treeViewer.getExpandedState(ss.getFirstElement()); - _treeViewer.setExpandedState(ss.getFirstElement(), !state); - } - }); - - _treeViewer.addTreeListener(new ITreeViewerListener() - { - public void treeExpanded(TreeExpansionEvent event) - { - _treeViewer.setExpandedState(event.getElement(), true); - // Following will cause the selection event to be sent, so commented - // _treeViewer.setSelection(new StructuredSelection(event.getElement())); - _treeViewer.refresh(); - } - - public void treeCollapsed(TreeExpansionEvent event) - { - _treeViewer.setExpandedState(event.getElement(), false); - _treeViewer.refresh(); - } - }); - - // This listener is for popup menu, which pops up if a queue,exchange or connection is selected - // with right click. - _treeViewer.getTree().addListener(SWT.MenuDetect, new Listener() - { - Display display = getSite().getShell().getDisplay(); - final Shell shell = new Shell(display); - - public void handleEvent(Event event) - { - Tree widget = (Tree) event.widget; - TreeItem[] items = widget.getSelection(); - if (items == null) - { - return; - } - - // Get the selected node - final TreeObject selectedNode = (TreeObject) items[0].getData(); - final TreeObject parentNode = selectedNode.getParent(); - - // This popup is only for mbeans and only connection,exchange and queue types - if ((parentNode == null) || !MBEAN.equals(selectedNode.getType()) - || !(CONNECTION.equals(parentNode.getName()) || QUEUE.equals(parentNode.getName()) - || EXCHANGE.equals(parentNode.getName()))) - { - return; - } - - Menu menu = new Menu(shell, SWT.POP_UP); - MenuItem item = new MenuItem(menu, SWT.PUSH); - // Add the action item, which will remove the node from the tree if selected - item.setText(ACTION_REMOVE_MBEANNODE); - item.addListener(SWT.Selection, new Listener() - { - public void handleEvent(Event e) - { - removeManagedObject(parentNode, (ManagedBean) selectedNode.getManagedObject()); - _treeViewer.refresh(); - // set the selection to the parent node - _treeViewer.setSelection(new StructuredSelection(parentNode)); - } - }); - menu.setLocation(event.x, event.y); - menu.setVisible(true); - while (!menu.isDisposed() && menu.isVisible()) - { - if (!display.readAndDispatch()) - { - display.sleep(); - } - } - - menu.dispose(); - } - }); - } - - /** - * Creates Qpid Server connection using JMX RMI protocol - * @param server - * @throws Exception - */ - private void createRMIServerConnection(ManagedServer server) throws Exception - { - // Currently Qpid Management Console only supports JMX MBeanServer - ServerRegistry serverRegistry = new JMXServerRegistry(server); - ApplicationRegistry.addServer(server, serverRegistry); - } - - /** - * Adds a new server node in the navigation view if server connection is successful. - * @param transportProtocol - * @param host - * @param port - * @param domain - * @throws Exception - */ - public void addNewServer(String transportProtocol, String host, int port, String domain, String user, String pwd) - throws Exception - { - String serverAddress = host + ":" + port; - String url = null; - ManagedServer managedServer = new ManagedServer(host, port, domain, user, pwd); - - if ("RMI".equals(transportProtocol)) - { - url = managedServer.getUrl(); - List<TreeObject> list = _serversRootNode.getChildren(); - for (TreeObject node : list) - { - ManagedServer nodeServer = (ManagedServer)node.getManagedObject(); - if (url.equals(nodeServer.getUrl())) - { - // Server is already in the list of added servers, so now connect it. - // Set the server node as selected and then connect it. - _treeViewer.setSelection(new StructuredSelection(node)); - reconnect(user, pwd); - - return; - } - } - - // The server is not in the list of already added servers, so now connect and add it. - managedServer.setName(serverAddress); - createRMIServerConnection(managedServer); - } - else - { - throw new InfoRequiredException(transportProtocol + " transport is not supported"); - } - - // Server connection is successful. Now add the server in the tree - TreeObject serverNode = new TreeObject(serverAddress, NODE_TYPE_SERVER); - serverNode.setManagedObject(managedServer); - _serversRootNode.addChild(serverNode); - - // Add server in the connected server map - _managedServerMap.put(managedServer, serverNode); - - // populate the server tree - try - { - populateServer(serverNode); - } - catch (SecurityException ex) - { - disconnect(managedServer); - throw ex; - } - - // Add the Queue/Exchanges/Connections from config file into the navigation tree - addConfiguredItems(managedServer); - - _treeViewer.refresh(); - - // save server address in file - addServerInConfigFile(serverAddress); - } - - /** - * Create the config file, if it doesn't already exist. - * Exits the application if the file could not be created. - */ - private void createConfigFile() - { - File file = new File(INI_FILENAME); - try - { - if (!file.exists()) - { - file.createNewFile(); - } - } - catch (IOException ex) - { - System.out.println("Could not write to the file " + INI_FILENAME); - System.out.println(ex); - System.exit(1); - } - } - - /** - * Server addresses are stored in a file. When user launches the application again, the - * server addresses are picked up from the file and shown in the navigfation view. This method - * adds the server address in a file, when a new server is added in the navigation view. - * @param serverAddress - */ - private void addServerInConfigFile(String serverAddress) - { - // Check if the address already exists - List<String> list = getServerListFromFile(); - if ((list != null) && list.contains(serverAddress)) - { - return; - } - - // Get the existing server list and add to that - String servers = _preferences.getString(INI_SERVERS); - String value = (servers.length() != 0) ? (servers + "," + serverAddress) : serverAddress; - _preferences.putValue(INI_SERVERS, value); - try - { - _preferences.save(); - } - catch (IOException ex) - { - System.err.println("Could not add " + serverAddress + " in " + INI_SERVERS + " (" + INI_FILENAME + ")"); - System.out.println(ex); - } - } - - /** - * Adds the item (Queue/Exchange/Connection) to the config file - * @param server - * @param virtualhost - * @param type - (Queue or Exchange or Connection) - * @param name - item name - */ - private void addItemInConfigFile(TreeObject node) - { - ManagedBean mbean = (ManagedBean) node.getManagedObject(); - String server = mbean.getServer().getName(); - String virtualhost = mbean.getVirtualHostName(); - String type = node.getParent().getName() + "s"; - String name = node.getName(); - String itemKey = server + "." + virtualhost + "." + type; - - // Check if the item already exists in the config file - List<String> list = getConfiguredItemsFromFile(itemKey); - if ((list != null) && list.contains(name)) - { - return; - } - - // Add this item to the existing list of items - String items = _preferences.getString(itemKey); - String value = (items.length() != 0) ? (items + "," + name) : name; - _preferences.putValue(itemKey, value); - try - { - _preferences.save(); - } - catch (IOException ex) - { - System.err.println("Could not add " + name + " in " + itemKey + " (" + INI_FILENAME + ")"); - System.out.println(ex); - } - } - - private void removeItemFromConfigFile(TreeObject node) - { - ManagedBean mbean = (ManagedBean) node.getManagedObject(); - String server = mbean.getServer().getName(); - String vHost = mbean.getVirtualHostName(); - String type = node.getParent().getName() + "s"; - String itemKey = server + "." + vHost + "." + type; - - List<String> list = getConfiguredItemsFromFile(itemKey); - if (list.contains(node.getName())) - { - list.remove(node.getName()); - String value = ""; - for (String item : list) - { - value += item + ","; - } - - value = (value.lastIndexOf(",") != -1) ? value.substring(0, value.lastIndexOf(",")) : value; - - _preferences.putValue(itemKey, value); - try - { - _preferences.save(); - } - catch (IOException ex) - { - System.err.println("Error in updating the config file " + INI_FILENAME); - System.out.println(ex); - } - } - } - - /** - * Queries the qpid server for MBeans and populates the navigation view with all MBeans for - * the given server node. - * @param serverNode - */ - private void populateServer(TreeObject serverNode) throws Exception - { - ManagedServer server = (ManagedServer) serverNode.getManagedObject(); - String domain = server.getDomain(); - if (!domain.equals(ALL)) - { - TreeObject domainNode = new TreeObject(domain, NODE_TYPE_DOMAIN); - domainNode.setParent(serverNode); - - populateDomain(domainNode); - } - else - { - List<TreeObject> domainList = new ArrayList<TreeObject>(); - List<String> domains = MBeanUtility.getAllDomains(server); - - for (String domainName : domains) - { - TreeObject domainNode = new TreeObject(domainName, NODE_TYPE_DOMAIN); - domainNode.setParent(serverNode); - - domainList.add(domainNode); - populateDomain(domainNode); - } - } - } - - /** - * Queries the Qpid Server and populates the given domain node with all MBeans undser that domain. - * @param domain - * @throws IOException - * @throws Exception - */ - @SuppressWarnings("unchecked") - private void populateDomain(TreeObject domain) throws IOException, Exception - { - ManagedServer server = (ManagedServer) domain.getParent().getManagedObject(); - - // Now populate the mbenas under those types - List<ManagedBean> mbeans = MBeanUtility.getManagedObjectsForDomain(server, domain.getName()); - for (ManagedBean mbean : mbeans) - { - mbean.setServer(server); - ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(server); - serverRegistry.addManagedObject(mbean); - - // Add all mbeans other than Connections, Exchanges and Queues. Because these will be added - // manually by selecting from MBeanView - if (!(mbean.isConnection() || mbean.isExchange() || mbean.isQueue())) - { - addManagedBean(domain, mbean); - } - } - // To make it work with the broker without virtual host implementation. - // This will add the default nodes to the domain node - for (TreeObject child : domain.getChildren()) - { - if (!child.getName().startsWith(VIRTUAL_HOST)) - { - addDefaultNodes(domain); - } - - break; - } - } - - /** - * Add these three types - Connection, Exchange, Queue - * By adding these, these will always be available, even if there are no mbeans under thse types - * This is required because, the mbeans will be added from mbeanview, by selecting from the list - * @param parent Node - */ - private void addDefaultNodes(TreeObject parent) - { - TreeObject typeChild = new TreeObject(CONNECTION, NODE_TYPE_MBEANTYPE); - typeChild.setParent(parent); - typeChild.setVirtualHost(parent.getVirtualHost()); - typeChild = new TreeObject(EXCHANGE, NODE_TYPE_MBEANTYPE); - typeChild.setParent(parent); - typeChild.setVirtualHost(parent.getVirtualHost()); - typeChild = new TreeObject(QUEUE, NODE_TYPE_MBEANTYPE); - typeChild.setParent(parent); - typeChild.setVirtualHost(parent.getVirtualHost()); - - // Add common notification node for virtual host - TreeObject notificationNode = new TreeObject(NOTIFICATIONS, NOTIFICATIONS); - notificationNode.setParent(parent); - notificationNode.setVirtualHost(parent.getVirtualHost()); - } - - /** - * Checks if a particular mbeantype is already there in the navigation view for a domain. - * This is used while populating domain with mbeans. - * @param parent - * @param typeName - * @return Node if given mbeantype already exists, otherwise null - */ - private TreeObject getMBeanTypeNode(TreeObject parent, String typeName) - { - List<TreeObject> childNodes = parent.getChildren(); - for (TreeObject child : childNodes) - { - if ((NODE_TYPE_MBEANTYPE.equals(child.getType()) || NODE_TYPE_TYPEINSTANCE.equals(child.getType())) - && typeName.equals(child.getName())) - { - return child; - } - } - - return null; - } - - private boolean doesMBeanNodeAlreadyExist(TreeObject typeNode, String mbeanName) - { - List<TreeObject> childNodes = typeNode.getChildren(); - for (TreeObject child : childNodes) - { - if (MBEAN.equals(child.getType()) && mbeanName.equals(child.getName())) - { - return true; - } - } - - return false; - } - - /** - * Adds the given MBean to the given domain node. Creates Notification node for the MBean. - * sample ObjectNames - - * org.apache.qpid:type=VirtualHost.VirtualHostManager,VirtualHost=localhost - * org.apache.qpid:type=VirtualHost.Queue,VirtualHost=test,name=ping_1 - * @param domain - * @param mbean - * @throws Exception - */ - private void addManagedBean(TreeObject domain, ManagedBean mbean) // throws Exception - { - String name = mbean.getName(); - // Split the mbean type into array of Strings, to create hierarchy - // eg. type=VirtualHost.VirtualHostManager,VirtualHost=localhost will be: - // localhost->VirtualHostManager - // eg. type=org.apache.qpid:type=VirtualHost.Queue,VirtualHost=test,name=ping will be: - // test->Queue->ping - String[] types = mbean.getType().split("\\."); - TreeObject typeNode = null; - TreeObject parentNode = domain; - - // Run this loop till all nodes(hierarchy) for this mbean are created. This loop only creates - // all the required parent nodes for the mbean - for (int i = 0; i < types.length; i++) - { - String type = types[i]; - String valueOftype = mbean.getProperty(type); - // If value is not null, then there will be a parent node for this mbean - // eg. for type=VirtualHost the value is "test" - typeNode = getMBeanTypeNode(parentNode, type); - - // create the type node if not already created - if (typeNode == null) - { - // If the ObjectName doesn't have name property, that means there will be only one instance - // of this mbean for given "type". So there will be no type node created for this mbean. - if ((name == null) && (i == (types.length - 1))) - { - break; - } - - // create a node for "type" - typeNode = createTypeNode(parentNode, type); - if (!type.equals(VIRTUAL_HOST)) - { - typeNode.setVirtualHost(mbean.getVirtualHostName()); - } - } - - // now type node create becomes the parent node for next node in hierarchy - parentNode = typeNode; - - /* - * Now create instances node for this type if value exists. - */ - if (valueOftype == null) - { - // No instance node will be created when value is null (eg type=Queue) - break; - } - - // For different virtual hosts, the nodes with given value will be created. - // eg type=VirtualHost, value=test - typeNode = getMBeanTypeNode(parentNode, valueOftype); - if (typeNode == null) - { - typeNode = createTypeInstanceNode(parentNode, valueOftype); - typeNode.setVirtualHost(mbean.getVirtualHostName()); - - // Create default nodes for VHost instances - if (type.equals(VIRTUAL_HOST)) - { - addDefaultNodes(typeNode); - } - } - - parentNode = typeNode; - } - - if (typeNode == null) - { - typeNode = parentNode; - } - - // Check if an MBean is already added - if (doesMBeanNodeAlreadyExist(typeNode, name)) - { - return; - } - - // Add the mbean node now - TreeObject mbeanNode = new TreeObject(mbean); - mbeanNode.setParent(typeNode); - - // Add the mbean to the config file - if (mbean.isQueue() || mbean.isExchange() || mbean.isConnection()) - { - addItemInConfigFile(mbeanNode); - } - - // Add notification node - // TODO: show this only if the mbean sends any notification - //TreeObject notificationNode = new TreeObject(NOTIFICATION, NOTIFICATION); - //notificationNode.setParent(mbeanNode); - } - - private TreeObject createTypeNode(TreeObject parent, String name) - { - TreeObject typeNode = new TreeObject(name, NODE_TYPE_MBEANTYPE); - typeNode.setParent(parent); - - return typeNode; - } - - private TreeObject createTypeInstanceNode(TreeObject parent, String name) - { - TreeObject typeNode = new TreeObject(name, NODE_TYPE_TYPEINSTANCE); - typeNode.setParent(parent); - - return typeNode; - } - - /** - * Removes all the child nodes of the given parent node. Used when closing a server. - * @param parent - */ - private void removeManagedObject(TreeObject parent) - { - List<TreeObject> list = parent.getChildren(); - for (TreeObject child : list) - { - removeManagedObject(child); - } - - list.clear(); - } - - /** - * Removes the mbean from the tree - * @param parent - * @param mbean - */ - private void removeManagedObject(TreeObject parent, ManagedBean mbean) - { - List<TreeObject> list = parent.getChildren(); - TreeObject objectToRemove = null; - for (TreeObject child : list) - { - if (MBEAN.equals(child.getType())) - { - String name = (mbean.getName() != null) ? mbean.getName() : mbean.getType(); - if (child.getName().equals(name)) - { - objectToRemove = child; - - break; - } - } - else - { - removeManagedObject(child, mbean); - } - } - - if (objectToRemove != null) - { - list.remove(objectToRemove); - removeItemFromConfigFile(objectToRemove); - } - - } - - /** - * Closes the Qpid server connection - */ - public void disconnect() throws Exception - { - TreeObject selectedNode = getSelectedServerNode(); - ManagedServer managedServer = (ManagedServer) selectedNode.getManagedObject(); - disconnect(managedServer); - } - - private void disconnect(ManagedServer managedServer) throws Exception - { - if (!_managedServerMap.containsKey(managedServer)) - { - return; - } - - // Close server connection - ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(managedServer); - if (serverRegistry == null) // server connection is already closed - { - return; - } - - serverRegistry.closeServerConnection(); - // Add server to the closed server list and the worker thread will remove the server from required places. - ApplicationRegistry.serverConnectionClosed(managedServer); - } - - /** - * Connects the selected server node - * @throws Exception - */ - public void reconnect(String user, String password) throws Exception - { - TreeObject selectedNode = getSelectedServerNode(); - ManagedServer managedServer = (ManagedServer) selectedNode.getManagedObject(); - if (_managedServerMap.containsKey(managedServer)) - { - throw new InfoRequiredException("Server " + managedServer.getName() + " is already connected"); - } - - managedServer.setUser(user); - managedServer.setPassword(password); - createRMIServerConnection(managedServer); - - // put the server in the managed server map - _managedServerMap.put(managedServer, selectedNode); - - try - { - // populate the server tree now - populateServer(selectedNode); - } - catch (SecurityException ex) - { - disconnect(managedServer); - throw ex; - } - - - // Add the Queue/Exchanges/Connections from config file into the navigation tree - addConfiguredItems(managedServer); - - _treeViewer.refresh(); - } - - /** - * Adds the items(queues/exchanges/connectins) from config file to the server tree - * @param server - */ - private void addConfiguredItems(ManagedServer server) - { - ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(server); - List<String> list = serverRegistry.getVirtualHosts(); - for (String virtualHost : list) - { - // Add Queues - String itemKey = server.getName() + "." + virtualHost + "." + INI_QUEUES; - List<String> items = getConfiguredItemsFromFile(itemKey); - List<ManagedBean> mbeans = serverRegistry.getQueues(virtualHost); - addConfiguredItems(items, mbeans); - - // Add Exchanges - itemKey = server.getName() + "." + virtualHost + "." + INI_EXCHANGES; - items = getConfiguredItemsFromFile(itemKey); - mbeans = serverRegistry.getExchanges(virtualHost); - addConfiguredItems(items, mbeans); - - // Add Connections - itemKey = server.getName() + "." + virtualHost + "." + INI_CONNECTIONS; - items = getConfiguredItemsFromFile(itemKey); - mbeans = serverRegistry.getConnections(virtualHost); - addConfiguredItems(items, mbeans); - } - } - - /** - * Gets the mbeans corresponding to the items and adds those to the navigation tree - * @param items - * @param mbeans - */ - private void addConfiguredItems(List<String> items, List<ManagedBean> mbeans) - { - if ((items == null) || (items.isEmpty() | (mbeans == null)) || mbeans.isEmpty()) - { - return; - } - - for (String item : items) - { - for (ManagedBean mbean : mbeans) - { - if (item.equals(mbean.getName())) - { - addManagedBean(mbean); - - break; - } - } - } - } - - /** - * Closes the Qpid server connection if not already closed and removes the server node from the navigation view and - * also from the ini file stored in the system. - * @throws Exception - */ - public void removeServer() throws Exception - { - disconnect(); - - // Remove from the Tree - String serverNodeName = getSelectedServerNode().getName(); - List<TreeObject> list = _serversRootNode.getChildren(); - TreeObject objectToRemove = null; - for (TreeObject child : list) - { - if (child.getName().equals(serverNodeName)) - { - objectToRemove = child; - - break; - } - } - - if (objectToRemove != null) - { - list.remove(objectToRemove); - } - - _treeViewer.refresh(); - - // Remove from the ini file - removeServerFromConfigFile(serverNodeName); - } - - private void removeServerFromConfigFile(String serverNodeName) - { - List<String> serversList = getServerListFromFile(); - serversList.remove(serverNodeName); - - String value = ""; - for (String item : serversList) - { - value += item + ","; - } - - value = (value.lastIndexOf(",") != -1) ? value.substring(0, value.lastIndexOf(",")) : value; - - _preferences.putValue(INI_SERVERS, value); - - try - { - _preferences.save(); - } - catch (IOException ex) - { - System.err.println("Error in updating the config file " + INI_FILENAME); - System.out.println(ex); - } - } - - /** - * @return the server addresses from the ini file - * @throws Exception - */ - private List<String> getServerListFromFile() - { - return getConfiguredItemsFromFile(INI_SERVERS); - } - - /** - * Returns the list of items from the config file. - * sample ini file: - * Servers=localhost:8999,127.0.0.1:8999 - * localhost.virtualhost1.Queues=queue1,queue2 - * localhost.virtualhost1.Exchanges=exchange1,exchange2 - * localhost.virtualhost2.Connections=conn1 - * @param key - * @return - */ - private List<String> getConfiguredItemsFromFile(String key) - { - List<String> list = new ArrayList<String>(); - String items = _preferences.getString(key); - if (items.length() != 0) - { - String[] array = items.split(","); - for (String item : array) - { - list.add(item); - } - } - - return list; - } - - public TreeObject getSelectedServerNode() throws Exception - { - IStructuredSelection ss = (IStructuredSelection) _treeViewer.getSelection(); - TreeObject selectedNode = (TreeObject) ss.getFirstElement(); - if (ss.isEmpty() || (selectedNode == null) || (!selectedNode.getType().equals(NODE_TYPE_SERVER))) - { - throw new InfoRequiredException("Please select the server"); - } - - return selectedNode; - } - - /** - * This is a callback that will allow us to create the viewer and initialize - * it. - */ - public void createPartControl(Composite parent) - { - Composite composite = new Composite(parent, SWT.NONE); - GridLayout gridLayout = new GridLayout(); - gridLayout.marginHeight = 2; - gridLayout.marginWidth = 2; - gridLayout.horizontalSpacing = 0; - gridLayout.verticalSpacing = 2; - composite.setLayout(gridLayout); - - createTreeViewer(composite); - _rootNode = new TreeObject("ROOT", "ROOT"); - _serversRootNode = new TreeObject(NAVIGATION_ROOT, "ROOT"); - _serversRootNode.setParent(_rootNode); - - _treeViewer.setInput(_rootNode); - // set viewer as selection event provider for MBeanView - getSite().setSelectionProvider(_treeViewer); - - // Start worker thread to refresh tree for added or removed objects - (new Thread(new Worker())).start(); - - createConfigFile(); - _preferences = new PreferenceStore(INI_FILENAME); - - try - { - _preferences.load(); - } - catch (IOException ex) - { - System.out.println(ex); - } - - // load the list of servers already added from file - List<String> serversList = getServerListFromFile(); - if (serversList != null) - { - for (String serverAddress : serversList) - { - String[] server = serverAddress.split(":"); - ManagedServer managedServer = new ManagedServer(server[0], Integer.parseInt(server[1]), "org.apache.qpid"); - TreeObject serverNode = new TreeObject(serverAddress, NODE_TYPE_SERVER); - serverNode.setManagedObject(managedServer); - _serversRootNode.addChild(serverNode); - } - } - - _treeViewer.refresh(); - - } - - /** - * Passing the focus request to the viewer's control. - */ - public void setFocus() - { } - - public void refresh() - { - _treeViewer.refresh(); - } - - /** - * Content provider class for the tree viewer - */ - private class ContentProviderImpl implements ITreeContentProvider - { - public Object[] getElements(Object parent) - { - return getChildren(parent); - } - - public Object[] getChildren(final Object parentElement) - { - final TreeObject node = (TreeObject) parentElement; - - return node.getChildren().toArray(new TreeObject[0]); - } - - public Object getParent(final Object element) - { - final TreeObject node = (TreeObject) element; - - return node.getParent(); - } - - public boolean hasChildren(final Object element) - { - final TreeObject node = (TreeObject) element; - - return !node.getChildren().isEmpty(); - } - - public void inputChanged(final Viewer viewer, final Object oldInput, final Object newInput) - { - // Do nothing - } - - public void dispose() - { - // Do nothing - } - } - - /** - * Label provider class for the tree viewer - */ - private class LabelProviderImpl extends LabelProvider implements IFontProvider - { - public Image getImage(Object element) - { - TreeObject node = (TreeObject) element; - if (node.getType().equals(NOTIFICATIONS)) - { - return ApplicationRegistry.getImage(NOTIFICATION_IMAGE); - } - else if (!node.getType().equals(MBEAN)) - { - if (_treeViewer.getExpandedState(node)) - { - return ApplicationRegistry.getImage(OPEN_FOLDER_IMAGE); - } - else - { - return ApplicationRegistry.getImage(CLOSED_FOLDER_IMAGE); - } - - } - else - { - return ApplicationRegistry.getImage(MBEAN_IMAGE); - } - } - - public String getText(Object element) - { - TreeObject node = (TreeObject) element; - if (node.getType().equals(NODE_TYPE_MBEANTYPE)) - { - return node.getName() + "s"; - } - else - { - return node.getName(); - } - } - - public Font getFont(Object element) - { - TreeObject node = (TreeObject) element; - if (node.getType().equals(NODE_TYPE_SERVER)) - { - if (node.getChildren().isEmpty()) - { - return ApplicationRegistry.getFont(FONT_NORMAL); - } - else - { - return ApplicationRegistry.getFont(FONT_BOLD); - } - } - - return ApplicationRegistry.getFont(FONT_NORMAL); - } - } // End of LabelProviderImpl - - private class ViewerSorterImpl extends ViewerSorter - { - public int category(Object element) - { - TreeObject node = (TreeObject) element; - if (node.getType().equals(MBEAN)) - { - return 1; - } - if (node.getType().equals(NOTIFICATIONS)) - { - return 2; - } - return 3; - } - } - - /** - * Worker thread, which keeps looking for new ManagedObjects to be added and - * unregistered objects to be removed from the tree. - * @author Bhupendra Bhardwaj - */ - private class Worker implements Runnable - { - public void run() - { - while (true) - { - if (!_managedServerMap.isEmpty()) - { - refreshRemovedObjects(); - refreshClosedServerConnections(); - } - - try - { - Thread.sleep(3000); - } - catch (Exception ex) - { } - - } // end of while loop - } // end of run method. - } // end of Worker class - - /** - * Adds the mbean to the navigation tree - * @param mbean - * @throws Exception - */ - public void addManagedBean(ManagedBean mbean) // throws Exception - { - TreeObject treeServerObject = _managedServerMap.get(mbean.getServer()); - List<TreeObject> domains = treeServerObject.getChildren(); - TreeObject domain = null; - for (TreeObject child : domains) - { - if (child.getName().equals(mbean.getDomain())) - { - domain = child; - - break; - } - } - - addManagedBean(domain, mbean); - _treeViewer.refresh(); - } - - private void refreshRemovedObjects() - { - for (ManagedServer server : _managedServerMap.keySet()) - { - final ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(server); - if (serverRegistry == null) // server connection is closed - { - continue; - } - - final List<ManagedBean> removalList = serverRegistry.getObjectsToBeRemoved(); - if (removalList != null) - { - Display display = getSite().getShell().getDisplay(); - display.syncExec(new Runnable() - { - public void run() - { - for (ManagedBean mbean : removalList) - { - TreeObject treeServerObject = _managedServerMap.get(mbean.getServer()); - List<TreeObject> domains = treeServerObject.getChildren(); - TreeObject domain = null; - for (TreeObject child : domains) - { - if (child.getName().equals(mbean.getDomain())) - { - domain = child; - - break; - } - } - - removeManagedObject(domain, mbean); - // serverRegistry.removeManagedObject(mbean); - } - - _treeViewer.refresh(); - } - }); - } - } - } - - /** - * Gets the list of closed server connection from the ApplicationRegistry and then removes - * the closed server nodes from the navigation view - */ - private void refreshClosedServerConnections() - { - final List<ManagedServer> closedServers = ApplicationRegistry.getClosedServers(); - if (closedServers != null) - { - Display display = getSite().getShell().getDisplay(); - display.syncExec(new Runnable() - { - public void run() - { - for (ManagedServer server : closedServers) - { - removeManagedObject(_managedServerMap.get(server)); - _managedServerMap.remove(server); - ApplicationRegistry.removeServer(server); - } - - _treeViewer.refresh(); - } - }); - } - } - -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NotificationsTabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NotificationsTabControl.java deleted file mode 100644 index 6894080859..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NotificationsTabControl.java +++ /dev/null @@ -1,427 +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.management.ui.views; - -import static org.apache.qpid.management.ui.Constants.BUTTON_CLEAR; -import static org.apache.qpid.management.ui.Constants.BUTTON_REFRESH; -import static org.apache.qpid.management.ui.Constants.DESCRIPTION; -import static org.apache.qpid.management.ui.Constants.FONT_BOLD; -import static org.apache.qpid.management.ui.Constants.FONT_BUTTON; -import static org.apache.qpid.management.ui.Constants.FONT_ITALIC; -import static org.apache.qpid.management.ui.Constants.SUBSCRIBE_BUTTON; -import static org.apache.qpid.management.ui.Constants.UNSUBSCRIBE_BUTTON; - -import java.util.List; - -import org.apache.qpid.management.ui.ApplicationRegistry; -import org.apache.qpid.management.ui.ManagedBean; -import org.apache.qpid.management.ui.ServerRegistry; -import org.apache.qpid.management.ui.jmx.MBeanUtility; -import org.apache.qpid.management.ui.model.NotificationInfoModel; -import org.apache.qpid.management.ui.model.NotificationObject; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.layout.FormAttachment; -import org.eclipse.swt.layout.FormData; -import org.eclipse.swt.layout.FormLayout; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Combo; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.TabFolder; - -/** - * Creates control composite for Notifications tab - * @author Bhupendra Bhardwaj - */ -public class NotificationsTabControl extends VHNotificationsTabControl -{ - private static final String SELECT_NOTIFICATIONNAME = "Select Notification"; - private static final String SELECT_NOTIFICATIONTYPE = "Select Type"; - private SelectionListener selectionListener; - private SelectionListener comboListener; - - private Combo notificationNameCombo = null; - private Combo typesCombo = null; - private Label descriptionLabel = null; - private Button _subscribeButton = null; - private Button _unsubscribeButton = null; - - public NotificationsTabControl(TabFolder tabFolder) - { - super(tabFolder); - } - - protected void createWidgets() - { - selectionListener = new SelectionListenerImpl(); - comboListener = new ComboSelectionListener(); - createNotificationInfoComposite(); - //addFilterComposite(); - addButtons(); - createTableViewer(); - } - - /** - * Creates composite and populates for displaying Notification Information (name, type, description) - * and creates buttons for subscribing or unsubscribing for notifications - */ - private void createNotificationInfoComposite() - { - Composite composite = _toolkit.createComposite(_form.getBody(), SWT.NONE); - composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); - composite.setLayout(new FormLayout()); - - Label label = _toolkit.createLabel(composite, "Select the notification to subscribe or unsubscribe"); - label.setFont(ApplicationRegistry.getFont(FONT_BOLD)); - FormData formData = new FormData(); - formData.top = new FormAttachment(0, 10); - formData.left = new FormAttachment(0, 10); - label.setLayoutData(formData); - - notificationNameCombo = new Combo(composite, SWT.READ_ONLY | SWT.DROP_DOWN); - formData = new FormData(); - formData.top = new FormAttachment(label, 10); - formData.left = new FormAttachment(0, 10); - formData.right = new FormAttachment(40); - notificationNameCombo.setLayoutData(formData); - notificationNameCombo.addSelectionListener(comboListener); - - typesCombo = new Combo(composite, SWT.READ_ONLY | SWT.DROP_DOWN); - formData = new FormData(); - formData.top = new FormAttachment(label, 10); - formData.left = new FormAttachment(notificationNameCombo, 5); - formData.right = new FormAttachment(65); - typesCombo.setLayoutData(formData); - typesCombo.addSelectionListener(comboListener); - - _subscribeButton = new Button(composite, SWT.PUSH | SWT.CENTER); - _subscribeButton.setFont(ApplicationRegistry.getFont(FONT_BUTTON)); - _subscribeButton.setText(SUBSCRIBE_BUTTON); - formData = new FormData(); - formData.top = new FormAttachment(label, 10); - formData.left = new FormAttachment(65, 10); - formData.width = 80; - _subscribeButton.setLayoutData(formData); - _subscribeButton.addSelectionListener(selectionListener); - - _unsubscribeButton = new Button(composite, SWT.PUSH | SWT.CENTER); - _unsubscribeButton.setFont(ApplicationRegistry.getFont(FONT_BUTTON)); - _unsubscribeButton.setText(UNSUBSCRIBE_BUTTON); - formData = new FormData(); - formData.top = new FormAttachment(label, 10); - formData.left = new FormAttachment(_subscribeButton, 10); - formData.width = 80; - _unsubscribeButton.setLayoutData(formData); - _unsubscribeButton.addSelectionListener(selectionListener); - - Label fixedLabel = _toolkit.createLabel(composite, ""); - formData = new FormData(); - formData.top = new FormAttachment(notificationNameCombo, 5); - formData.left = new FormAttachment(0, 10); - fixedLabel.setLayoutData(formData); - fixedLabel.setText(DESCRIPTION + " : "); - fixedLabel.setFont(ApplicationRegistry.getFont(FONT_BOLD)); - - descriptionLabel = _toolkit.createLabel(composite, ""); - formData = new FormData(); - formData.top = new FormAttachment(notificationNameCombo, 5); - formData.left = new FormAttachment(fixedLabel, 10); - formData.right = new FormAttachment(100); - descriptionLabel.setLayoutData(formData); - descriptionLabel.setText(" "); - descriptionLabel.setFont(ApplicationRegistry.getFont(FONT_ITALIC)); - } - - /** - * Creates clear buttin and refresh button - */ - protected void addButtons() - { - Composite composite = _toolkit.createComposite(_form.getBody(), SWT.NONE); - composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); - composite.setLayout(new GridLayout(2, true)); - - // Add Clear Button - _clearButton = _toolkit.createButton(composite, BUTTON_CLEAR, SWT.PUSH | SWT.CENTER); - _clearButton.setFont(ApplicationRegistry.getFont(FONT_BUTTON)); - GridData gridData = new GridData(SWT.LEAD, SWT.TOP, true, false); - gridData.widthHint = 80; - _clearButton.setLayoutData(gridData); - _clearButton.addSelectionListener(new SelectionAdapter() - { - public void widgetSelected(SelectionEvent e) - { - if (_mbean == null) - return; - - IStructuredSelection ss = (IStructuredSelection)_tableViewer.getSelection(); - ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(_mbean); - serverRegistry.clearNotifications(_mbean, ss.toList()); - refresh(); - } - }); - - // Add Refresh Button - _refreshButton = _toolkit.createButton(composite, BUTTON_REFRESH, SWT.PUSH | SWT.CENTER); - _refreshButton.setFont(ApplicationRegistry.getFont(FONT_BUTTON)); - gridData = new GridData(SWT.TRAIL, SWT.TOP, true, false); - gridData.widthHint = 80; - _refreshButton.setLayoutData(gridData); - _refreshButton.addSelectionListener(new SelectionAdapter() - { - public void widgetSelected(SelectionEvent e) - { - if (_mbean == null) - return; - - refresh(); - } - }); - } - - @Override - public void refresh(ManagedBean mbean) - { - _mbean = mbean; - _notifications = null; - _table.deselectAll(); - _tableViewer.getTable().clearAll(); - - if (_mbean == null) - { - _tableViewer.getTable().clearAll(); - _subscribeButton.setEnabled(false); - _unsubscribeButton.setEnabled(false); - return; - } - - if (!doesMBeanSendsNotification()) - { - Control[] children = _form.getBody().getChildren(); - for (int i = 0; i < children.length; i++) - { - children[i].setVisible(false); - } - - String name = (_mbean.getName() != null) ? _mbean.getName() : _mbean.getType(); - _form.setText(name + " does not send any notification"); - return; - } - - Control[] children = _form.getBody().getChildren(); - for (int i = 0; i < children.length; i++) - { - children[i].setVisible(true); - } - - populateNotificationInfo(); - workerRunning = true; - _form.layout(true); - _form.getBody().layout(true, true); - } - - public void refresh() - { - _notifications = null; - _table.deselectAll(); - _tableViewer.getTable().clearAll(); - } - - /** - * Fills the notification information widgets for selected mbean - */ - private void populateNotificationInfo() - { - notificationNameCombo.removeAll(); - NotificationInfoModel[] items = MBeanUtility.getNotificationInfo(_mbean); - if (items.length > 1) - { - notificationNameCombo.add(SELECT_NOTIFICATIONNAME); - } - - for (int i = 0; i < items.length; i++) - { - notificationNameCombo.add(items[i].getName()); - notificationNameCombo.setData(items[i].getName(), items[i]); - } - notificationNameCombo.select(0); - - typesCombo.removeAll(); - typesCombo.add("Select Type", 0); - typesCombo.select(0); - typesCombo.setEnabled(false); - - populateNotificationType(notificationNameCombo.getItem(0)); - checkForEnablingButtons(); - } - - /** - * Checks and the enabing/disabling of buttons - */ - private void checkForEnablingButtons() - { - int nameIndex = notificationNameCombo.getSelectionIndex(); - int itemCount = notificationNameCombo.getItems().length; - if ((itemCount > 1) && (nameIndex == 0)) - { - _subscribeButton.setEnabled(false); - _unsubscribeButton.setEnabled(false); - descriptionLabel.setText(""); - return; - } - - int typeIndex = typesCombo.getSelectionIndex(); - itemCount = typesCombo.getItems().length; - if ((itemCount > 1) && (typeIndex == 0)) - { - _subscribeButton.setEnabled(false); - _unsubscribeButton.setEnabled(false); - return; - } - - String type = typesCombo.getItem(typeIndex); - String name = notificationNameCombo.getItem(nameIndex); - ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(_mbean); - - if (serverRegistry.hasSubscribedForNotifications(_mbean, name, type)) - { - _subscribeButton.setEnabled(false); - _unsubscribeButton.setEnabled(true); - } - else - { - _subscribeButton.setEnabled(true); - _unsubscribeButton.setEnabled(false); - } - } - - private boolean doesMBeanSendsNotification() - { - NotificationInfoModel[] items = MBeanUtility.getNotificationInfo(_mbean); - if (items == null || items.length == 0) - return false; - else - return true; - } - - /** - * Selection listener for subscribing or unsubscribing the notifications - */ - private class SelectionListenerImpl extends SelectionAdapter - { - public void widgetSelected(SelectionEvent e) - { - if (_mbean == null) - return; - - Button source = (Button)e.getSource(); - String type = typesCombo.getItem(typesCombo.getSelectionIndex()); - String name = notificationNameCombo.getItem(notificationNameCombo.getSelectionIndex()); - if (source == _unsubscribeButton) - { - try - { - MBeanUtility.removeNotificationListener(_mbean, name, type); - } - catch(Exception ex) - { - MBeanUtility.handleException(ex); - } - } - else if (source == _subscribeButton) - { - try - { - MBeanUtility.createNotificationlistener(_mbean, name, type); - } - catch(Exception ex) - { - MBeanUtility.handleException(ex); - } - } - checkForEnablingButtons(); - } - } - - /** - * Selection listener class for the Notification Name. The notification type and description will be - * displayed accordingly - */ - private class ComboSelectionListener extends SelectionAdapter - { - public void widgetSelected(SelectionEvent e) - { - if (_mbean == null) - return; - - Combo combo = (Combo)e.getSource(); - if (combo == notificationNameCombo) - { - String selectedItem = combo.getItem(combo.getSelectionIndex()); - populateNotificationType(selectedItem); - } - checkForEnablingButtons(); - } - } - - private void populateNotificationType(String notificationName) - { - NotificationInfoModel data = (NotificationInfoModel)notificationNameCombo.getData(notificationName); - if (data == null) - { - descriptionLabel.setText(""); - typesCombo.select(0); - typesCombo.setEnabled(false); - return; - } - descriptionLabel.setText(data.getDescription()); - typesCombo.removeAll(); - typesCombo.setItems(data.getTypes()); - if (typesCombo.getItemCount() > 1) - { - typesCombo.add(SELECT_NOTIFICATIONTYPE, 0); - } - typesCombo.select(0); - typesCombo.setEnabled(true); - } - - /** - * Updates the table with new notifications received from mbean server for the selected mbean - */ - protected void updateTableViewer() - { - ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(_mbean); - List<NotificationObject> newList = serverRegistry.getNotifications(_mbean); - if (newList == null) - return; - - _notifications = newList; - _tableViewer.setInput(_notifications); - _tableViewer.refresh(); - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NumberVerifyListener.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NumberVerifyListener.java deleted file mode 100644 index 1774209dae..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NumberVerifyListener.java +++ /dev/null @@ -1,46 +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.management.ui.views; - -import org.eclipse.swt.events.VerifyEvent; -import org.eclipse.swt.events.VerifyListener; - -/** - * Implementation of VeryfyListener for numeric values - * @author Bhupendra Bhardwaj - */ -public class NumberVerifyListener implements VerifyListener -{ - public void verifyText(VerifyEvent event) - { - String string = event.text; - char [] chars = new char [string.length ()]; - string.getChars (0, chars.length, chars, 0); - for (int i=0; i<chars.length; i++) - { - if (!('0' <= chars [i] && chars [i] <= '9')) - { - event.doit = false; - return; - } - } - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/OperationTabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/OperationTabControl.java deleted file mode 100644 index 12f38f1c74..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/OperationTabControl.java +++ /dev/null @@ -1,898 +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.management.ui.views; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map.Entry; - -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.TabularDataSupport; - -import static org.apache.qpid.management.ui.Constants.*; - -import org.apache.qpid.management.ui.ApplicationRegistry; -import org.apache.qpid.management.ui.ManagedBean; -import org.apache.qpid.management.ui.jmx.MBeanUtility; -import org.apache.qpid.management.ui.model.OperationData; -import org.apache.qpid.management.ui.model.ParameterData; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.ScrolledComposite; -import org.eclipse.swt.events.KeyAdapter; -import org.eclipse.swt.events.KeyEvent; -import org.eclipse.swt.events.KeyListener; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.events.VerifyEvent; -import org.eclipse.swt.events.VerifyListener; -import org.eclipse.swt.layout.FormAttachment; -import org.eclipse.swt.layout.FormData; -import org.eclipse.swt.layout.FormLayout; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Combo; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.widgets.TabFolder; -import org.eclipse.swt.widgets.Text; -import org.eclipse.ui.forms.widgets.Form; -import org.eclipse.ui.forms.widgets.FormToolkit; - -/** - * Control class for the MBean operations tab. It creates the required widgets - * for the selected MBean. - * @author Bhupendra Bhardwaj - */ -public class OperationTabControl extends TabControl -{ - private static final int heightForAParameter = 30; - private static final int labelWidth = 30; - private static final int valueWidth = labelWidth + 25; - - private FormToolkit _toolkit; - private Form _form; - private OperationData _opData; - - private SelectionListener operationExecutionListener = new OperationExecutionListener(); - private SelectionListener refreshListener = new RefreshListener(); - private SelectionListener parameterSelectionListener = new ParameterSelectionListener(); - private SelectionListener booleanSelectionListener = new BooleanSelectionListener(); - private VerifyListener verifyListener = new VerifyListenerImpl(); - private KeyListener keyListener = new KeyListenerImpl(); - private KeyListener headerBindingListener = new HeaderBindingKeyListener(); - - private Composite _headerComposite = null; - private Composite _paramsComposite = null; - private Composite _resultsComposite = null; - private Button _executionButton = null; - - // for customized method in header exchange - private HashMap<Text, Text> headerBindingHashMap = null; - private String _virtualHostName = null; - - public OperationTabControl(TabFolder tabFolder, OperationData opData) - { - super(tabFolder); - _toolkit = new FormToolkit(_tabFolder.getDisplay()); - _form = _toolkit.createForm(_tabFolder); - _form.getBody().setLayout(new GridLayout()); - _opData = opData; - createComposites(); - setHeader(); - } - - /** - * Form area is devided in four parts: - * Header composite - displays operaiton information - * Patameters composite - displays parameters if there - * Button - operation execution button - * Results composite - displays results for operations, which have - * no parameters but have some return value - */ - private void createComposites() - { - // - _headerComposite = _toolkit.createComposite(_form.getBody(), SWT.NONE); - _headerComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); - - List<ParameterData> params = _opData.getParameters(); - if (params != null && !params.isEmpty()) - { - _paramsComposite = _toolkit.createComposite(_form.getBody(), SWT.NONE); - _paramsComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); - } - _executionButton = _toolkit.createButton(_form.getBody(), BUTTON_EXECUTE, SWT.PUSH | SWT.CENTER); - _executionButton.setFont(ApplicationRegistry.getFont(FONT_BUTTON)); - GridData layoutData = new GridData(SWT.CENTER, SWT.TOP, true, false); - layoutData.verticalIndent = 20; - _executionButton.setLayoutData(layoutData); - - _resultsComposite = _toolkit.createComposite(_form.getBody(), SWT.NONE); - layoutData = new GridData(SWT.FILL, SWT.FILL, true, true); - layoutData.verticalIndent = 20; - _resultsComposite.setLayoutData(layoutData); - _resultsComposite.setLayout(new GridLayout()); - } - - /** - * @see TabControl#getControl() - */ - public Control getControl() - { - return _form; - } - - @Override - public void refresh(ManagedBean mbean) - { - _mbean = mbean; - _virtualHostName = _mbean.getVirtualHostName(); - - // Setting the form to be invisible. Just in case the mbean server connection - // is done and it takes time in getting the response, then the ui should be blank - // instead of having half the widgets displayed. - _form.setVisible(false); - - ViewUtility.disposeChildren(_paramsComposite); - createParameterWidgets(); - - // Set button text and add appropriate listener to button. - // If there are no parameters and it is info operation, then operation gets executed - // and result is displayed - List<ParameterData> params = _opData.getParameters(); - if (params != null && !params.isEmpty()) - { - setButton(BUTTON_EXECUTE); - } - else if (_opData.getImpact() == OPERATION_IMPACT_ACTION) - { - setButton(BUTTON_EXECUTE); - } - else if (_opData.getImpact() == OPERATION_IMPACT_INFO) - { - setButton(BUTTON_REFRESH); - executeAndShowResults(); - } - - _form.setVisible(true); - layout(); - } - - public void layout() - { - _form.layout(true); - _form.getBody().layout(true, true); - } - - /** - * populates the header composite, containing the operation name and description. - */ - private void setHeader() - { - _form.setText(ViewUtility.getDisplayText(_opData.getName())); - _headerComposite.setLayout(new GridLayout(2, false)); - //operation description - Label label = _toolkit.createLabel(_headerComposite, DESCRIPTION + " : "); - label.setFont(ApplicationRegistry.getFont(FONT_BOLD)); - label.setLayoutData(new GridData(SWT.LEAD, SWT.TOP, false, false)); - - label = _toolkit.createLabel(_headerComposite, _opData.getDescription()); - label.setFont(ApplicationRegistry.getFont(FONT_NORMAL)); - label.setLayoutData(new GridData(SWT.LEAD, SWT.TOP, true, false)); - - _headerComposite.layout(); - } - - /** - * Creates the widgets for operation parameters if there are any - */ - private void createParameterWidgets() - { - List<ParameterData> params = _opData.getParameters(); - if (params == null || params.isEmpty()) - { - return; - } - - // Customised parameter widgets - if (_mbean.isExchange() && - EXCHANGE_TYPE_VALUES[2].equals(_mbean.getProperty(EXCHANGE_TYPE)) && - _opData.getName().equalsIgnoreCase(OPERATION_CREATE_BINDING)) - { - customCreateNewBinding(); - return; - } - // end of Customised parameter widgets - - _paramsComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); - _paramsComposite.setLayout(new FormLayout()); - int parameterPositionOffset = 0; - for (ParameterData param : params) - { - boolean valueInCombo = false; - Label label = _toolkit.createLabel(_paramsComposite, ViewUtility.getDisplayText(param.getName())); - FormData formData = new FormData(); - if (params.indexOf(param) == 0) - { - parameterPositionOffset = 0; - } - else - { - parameterPositionOffset += heightForAParameter; - } - formData.top = new FormAttachment(0, parameterPositionOffset + 2); - formData.right = new FormAttachment(labelWidth); - label.setLayoutData(formData); - label.setToolTipText(param.getDescription()); - - formData = new FormData(); - formData.top = new FormAttachment(0, parameterPositionOffset); - formData.left = new FormAttachment(label, 5); - formData.right = new FormAttachment(valueWidth); - // this will contain the list of items, if the list is to be made available to choose from - // e.g. the list of exchanges - String[] items = null; - if (param.getName().equals(QUEUE)) - { - List<String> qList = ApplicationRegistry.getServerRegistry(_mbean).getQueueNames(_virtualHostName); - // Customization for AMQQueueMBean method OPERATION_MOVE_MESSAGES - if (_opData.getName().equals(OPERATION_MOVE_MESSAGES)) - { - qList.remove(_mbean.getName()); - } - // End of Customization - items = qList.toArray(new String[0]); - } - else if (param.getName().equals(EXCHANGE)) - { - items = ApplicationRegistry.getServerRegistry(_mbean).getExchangeNames(_virtualHostName); - } - else if (param.getName().equals(EXCHANGE_TYPE)) - { - items = EXCHANGE_TYPE_VALUES; - } - else if (isUserListParameter(param)) - { - List<String> list = ApplicationRegistry.getServerRegistry(_mbean).getUsernames(); - if (list != null && !list.isEmpty()) - { - items = list.toArray(new String[0]); - } - } - - if (items != null) - { - org.eclipse.swt.widgets.List _list = new org.eclipse.swt.widgets.List(_paramsComposite, SWT.BORDER | SWT.V_SCROLL); - int listSize = _form.getClientArea().height * 2 / 3; - int itemsHeight = items.length * (_list.getItemHeight() + 2); - // Set a min height for the list widget (set it to min 4 items) - if (items.length < 4) - { - itemsHeight = 4 * (_list.getItemHeight() + 2); - } - - listSize = (listSize > itemsHeight) ? itemsHeight : listSize; - parameterPositionOffset = parameterPositionOffset + listSize; - formData.bottom = new FormAttachment(0, parameterPositionOffset); - _list.setLayoutData(formData); - _list.setData(param); - _list.setItems(items); - _list.addSelectionListener(parameterSelectionListener); - valueInCombo = true; - } - else if (param.isBoolean()) - { - Button booleanButton = _toolkit.createButton(_paramsComposite, "", SWT.CHECK); - booleanButton.setLayoutData(formData); - booleanButton.setData(param); - booleanButton.addSelectionListener(booleanSelectionListener); - valueInCombo = true; - } - else - { - int style = SWT.NONE; - if (PASSWORD.equalsIgnoreCase(param.getName())) - { - style = SWT.PASSWORD; - } - Text text = _toolkit.createText(_paramsComposite, "", style); - formData = new FormData(); - formData.top = new FormAttachment(0, parameterPositionOffset); - formData.left = new FormAttachment(label, 5); - formData.right = new FormAttachment(valueWidth); - text.setLayoutData(formData); - // Listener to assign value to the parameter - text.addKeyListener(keyListener); - // Listener to verify if the entered key is valid - text.addVerifyListener(verifyListener); - text.setData(param); - } - - // display the parameter data type next to the text field - if (valueInCombo) - { - label = _toolkit.createLabel(_paramsComposite, ""); - } - else if (PASSWORD.equalsIgnoreCase(param.getName())) - { - label = _toolkit.createLabel(_paramsComposite, "(String)"); - } - else - { - String str = param.getType(); - - if (param.getType().lastIndexOf(".") != -1) - str = param.getType().substring(1 + param.getType().lastIndexOf(".")); - - label = _toolkit.createLabel(_paramsComposite, "(" + str + ")"); - } - formData = new FormData(); - formData.top = new FormAttachment(0, parameterPositionOffset); - formData.left = new FormAttachment(valueWidth, 5); - label.setLayoutData(formData); - } - } - - private boolean isUserListParameter(ParameterData param) - { - if (_mbean.isAdmin() && param.getName().equals(OPERATION_PARAM_USERNAME) - && !_opData.getName().equals(OPERATION_CREATEUSER)) - { - return true; - } - - return false; - } - - /** - * Creates customized dispaly for a method "CreateNewBinding" for Headers exchange - * - */ - private void customCreateNewBinding() - { - headerBindingHashMap = new HashMap<Text, Text>(); - - _paramsComposite.setLayout(new GridLayout()); - _paramsComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true)); - final ScrolledComposite scrolledComposite = new ScrolledComposite(_paramsComposite, SWT.BORDER | SWT.V_SCROLL); - scrolledComposite.setExpandHorizontal(true); - scrolledComposite.setExpandVertical(true); - GridData layoutData = new GridData(SWT.FILL, SWT.TOP, true, true); - scrolledComposite.setLayoutData(layoutData); - scrolledComposite.setLayout(new GridLayout()); - - final Composite composite = _toolkit.createComposite(scrolledComposite, SWT.NONE); - scrolledComposite.setContent(composite); - layoutData = new GridData(SWT.FILL, SWT.FILL, true, true); - layoutData.verticalIndent = 20; - composite.setLayoutData(layoutData); - composite.setLayout(new FormLayout()); - - List<ParameterData> params = _opData.getParameters(); - ParameterData param = params.get(0); - // Queue selection widget - Label label = _toolkit.createLabel(composite, ViewUtility.getDisplayText(param.getName())); - FormData formData = new FormData(); - formData.top = new FormAttachment(0, 2); - formData.right = new FormAttachment(labelWidth); - label.setLayoutData(formData); - label.setToolTipText(param.getDescription()); - - formData = new FormData(); - formData.top = new FormAttachment(0); - formData.left = new FormAttachment(label, 5); - formData.right = new FormAttachment(valueWidth); - - Combo combo = new Combo(composite, SWT.READ_ONLY | SWT.DROP_DOWN); - List<String> qList = ApplicationRegistry.getServerRegistry(_mbean).getQueueNames(_virtualHostName); - combo.setItems(qList.toArray(new String[0])); - combo.add("Select Queue", 0); - combo.select(0); - combo.setLayoutData(formData); - combo.setData(param); - combo.addSelectionListener(parameterSelectionListener); - - // Binding creation widgets - createARowForCreatingHeadersBinding(composite, 1); - createARowForCreatingHeadersBinding(composite, 2); - createARowForCreatingHeadersBinding(composite, 3); - createARowForCreatingHeadersBinding(composite, 4); - createARowForCreatingHeadersBinding(composite, 5); - createARowForCreatingHeadersBinding(composite, 6); - createARowForCreatingHeadersBinding(composite, 7); - createARowForCreatingHeadersBinding(composite, 8); - - final Button addMoreButton = _toolkit.createButton(composite, "Add More", SWT.PUSH); - formData = new FormData(); - formData.top = new FormAttachment(0, heightForAParameter); - formData.left = new FormAttachment(70, 5); - addMoreButton.setLayoutData(formData); - addMoreButton.setData("rowCount", 8); - addMoreButton.addSelectionListener(new SelectionAdapter() - { - public void widgetSelected(SelectionEvent e) - { - int count = Integer.parseInt(addMoreButton.getData("rowCount").toString()); - createARowForCreatingHeadersBinding(composite, ++count); - addMoreButton.setData("rowCount", count); - scrolledComposite.setMinSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT)); - composite.layout(); - _form.layout(); - } - }); - - scrolledComposite.setMinSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT)); - composite.layout(); - } - - /** - * Adds a row for adding a binding for Headers Exchange. Used by the method, which creates the customized - * layout and widgest for Header's exchange method createNewBinding. - * @param parent composite - * @param rowCount - row number - */ - private void createARowForCreatingHeadersBinding(Composite parent, int rowCount) - { - Label key = _toolkit.createLabel(parent, "Name"); - FormData formData = new FormData(); - formData.top = new FormAttachment(0, rowCount * heightForAParameter + 2); - formData.right = new FormAttachment(15); - key.setLayoutData(formData); - - Text keyText = _toolkit.createText(parent, "", SWT.NONE); - formData = new FormData(); - formData.top = new FormAttachment(0, rowCount * heightForAParameter); - formData.left = new FormAttachment(key, 5); - formData.right = new FormAttachment(40); - keyText.setLayoutData(formData); - keyText.addKeyListener(headerBindingListener); - - Label value = _toolkit.createLabel(parent, "Value"); - formData = new FormData(); - formData.top = new FormAttachment(0, rowCount * heightForAParameter + 2); - formData.right = new FormAttachment(45); - value.setLayoutData(formData); - - Text valueText = _toolkit.createText(parent, "", SWT.NONE); - formData = new FormData(); - formData.top = new FormAttachment(0, rowCount * heightForAParameter); - formData.left = new FormAttachment(value, 5); - formData.right = new FormAttachment(70); - valueText.setLayoutData(formData); - valueText.addKeyListener(headerBindingListener); - - // Add these to the map, to retrieve the values while setting the parameter value - headerBindingHashMap.put(keyText, valueText); - } - - /** - * Sets text and listener for the operation execution button - * @param text - */ - private void setButton(String text) - { - _executionButton.setText(text); - _executionButton.removeSelectionListener(refreshListener); - _executionButton.removeSelectionListener(operationExecutionListener); - - if (BUTTON_EXECUTE.equals(text)) - { - _executionButton.addSelectionListener(operationExecutionListener); - } - else - { - _executionButton.addSelectionListener(refreshListener); - } - } - - /** - * displays the operation result in a pop-up window - * @param result - */ - private void populateResults(Object result) - { - Display display = Display.getCurrent(); - int width = 610; - int height = 400; - Shell shell = ViewUtility.createPopupShell(RESULT, width, height); - shell.setImage(ApplicationRegistry.getImage(CONSOLE_IMAGE)); - ViewUtility.populateCompositeWithData(_toolkit, shell, result); - - shell.open(); - while (!shell.isDisposed()) { - if (!display.readAndDispatch()) { - display.sleep(); - } - } - shell.dispose(); - } - - /** - * Clears the parameter values of the operation - */ - private void clearParameters() - { - List<ParameterData> params = _opData.getParameters(); - if (params != null && !params.isEmpty()) - { - for (ParameterData param : params) - { - param.setDefaultValue(); - } - } - } - - /** - * Clears the values entered by the user from parameter value widgets - * @param control - */ - private void clearParameterValues(Composite control) - { - if (control == null || (control.isDisposed())) - return; - - Control[] controls = control.getChildren(); - if (controls == null || controls.length == 0) - return; - - for (int i = 0; i < controls.length; i++) - { - if (controls[i] instanceof Combo) - ((Combo)controls[i]).select(0); - if (controls[i] instanceof org.eclipse.swt.widgets.List) - ((org.eclipse.swt.widgets.List)controls[i]).deselectAll(); - else if (controls[i] instanceof Text) - ((Text)controls[i]).setText(""); - else if (controls[i] instanceof Button) - ((Button)controls[i]).setSelection(false); - else if (controls[i] instanceof Composite) - clearParameterValues((Composite)controls[i]); - } - } - - /** - * Listener class for operation execution events - */ - private class OperationExecutionListener extends SelectionAdapter - { - public void widgetSelected(SelectionEvent e) - { - List<ParameterData> params = _opData.getParameters(); - if (params != null && !params.isEmpty()) - { - for (ParameterData param : params) - { - if (param.getValue() == null || param.getValue().toString().length() == 0) - { - // Customized check, because for this parameter null is allowed - if (param.getName().equals(ATTRIBUTE_QUEUE_OWNER) && - _opData.getName().equals(OPERATION_CREATE_QUEUE)) - { - continue; - } - // End of custom code - - ViewUtility.popupInfoMessage(_form.getText(), "Please select the " + ViewUtility.getDisplayText(param.getName())); - return; - } - - // customized for passwords - String securityMechanism = ApplicationRegistry.getSecurityMechanism(); - if ((MECH_CRAMMD5.equals(securityMechanism)) && PASSWORD.equalsIgnoreCase(param.getName())) - { - try - { - param.setValue(ViewUtility.getMD5HashedCharArray(param.getValue())); - } - catch (Exception ex) - { - MBeanUtility.handleException(_mbean, ex); - return; - } - } - // end of customization - } - } - - if (_opData.getImpact() == OPERATION_IMPACT_ACTION) - { - String bean = _mbean.getName() == null ? _mbean.getType() : _mbean.getName(); - int response = ViewUtility.popupConfirmationMessage(bean, "Do you want to " + _form.getText()+ " ?"); - if (response == SWT.YES) - { - executeAndShowResults(); - } - } - else - { - executeAndShowResults(); - } - - if (_mbean.isAdmin() && _opData.getName().equals(OPERATION_DELETEUSER)) - { - refresh(_mbean); - } - else - { - clearParameters(); - clearParameterValues(_paramsComposite); - } - } - } - - // Listener for the "Refresh" execution button - private class RefreshListener extends SelectionAdapter - { - public void widgetSelected(SelectionEvent e) - { - executeAndShowResults(); - } - } - - /** - * Executres the operation, gets the result from server and displays to the user - */ - private void executeAndShowResults() - { - Object result = null; - try - { - result = MBeanUtility.execute(_mbean, _opData); - } - catch(Exception ex) - { - MBeanUtility.handleException(_mbean, ex); - return; - } - - // Custom code for Admin mbean operation - /* These custome codes here are to make the GUI look more user friendly. - * Here we are adding the users to a list, which will be used to list username to be selected on - * pages like "delete user", "set password" instead of typing the username - */ - if (_mbean.isAdmin()) - { - if (_opData.getName().equals(OPERATION_VIEWUSERS)) - { - ApplicationRegistry.getServerRegistry(_mbean).setUserList(extractUserList(result)); - } - else if (_opData.getName().equals(OPERATION_DELETEUSER)) - { - List<String> list = ApplicationRegistry.getServerRegistry(_mbean).getUsernames(); - Object userName = _opData.getParameterValue(OPERATION_PARAM_USERNAME); - if ((list != null) && !list.isEmpty() && (userName != null)) - { - list.remove(userName); - ApplicationRegistry.getServerRegistry(_mbean).setUserList(list); - } - } - else if (_opData.getName().equals(OPERATION_CREATEUSER)) - { - List<String> list = ApplicationRegistry.getServerRegistry(_mbean).getUsernames(); - Object userName = _opData.getParameterValue(OPERATION_PARAM_USERNAME); - if ((list != null) && !list.isEmpty() && (userName != null)) - { - list.add(userName.toString()); - ApplicationRegistry.getServerRegistry(_mbean).setUserList(list); - } - } - } - // end of custom code - - // Some mbeans have only "type" and no "name". - String title = _mbean.getType(); - if (_mbean.getName() != null && _mbean.getName().length() != 0) - { - title = _mbean.getName(); - } - - if (_opData.isReturnTypeVoid()) - { - ViewUtility.popupInfoMessage(title, OPERATION_SUCCESSFUL); - } - else if (_opData.isReturnTypeBoolean()) - { - boolean success = Boolean.parseBoolean(result.toString()); - String message = success ? OPERATION_SUCCESSFUL : OPERATION_UNSUCCESSFUL; - ViewUtility.popupInfoMessage(title, message); - } - else if (_opData.getParameters() != null && !_opData.getParameters().isEmpty()) - { - populateResults(result); - } - else - { - ViewUtility.disposeChildren(_resultsComposite); - ViewUtility.populateCompositeWithData(_toolkit, _resultsComposite, result); - _resultsComposite.layout(); - _form.layout(); - } - - } - - private List<String> extractUserList(Object result) - { - if (!(result instanceof TabularDataSupport)) - { - return null; - } - - TabularDataSupport tabularData = (TabularDataSupport)result; - Collection<Object> records = tabularData.values(); - List<String> list = new ArrayList<String>(); - for (Object o : records) - { - CompositeData data = (CompositeData) o; - if (data.containsKey(USERNAME)) - { - list.add(data.get(USERNAME).toString()); - } - } - - return list; - } - - /** - * Listener class for the operation parameters widget - */ - private class ParameterSelectionListener extends SelectionAdapter - { - public void widgetSelected(SelectionEvent e) - { - ParameterData parameter = (ParameterData)e.widget.getData(); - parameter.setValue(null); - if (e.widget instanceof Combo) - { - Combo combo = (Combo)e.widget; - if (combo.getSelectionIndex() > 0) - { - String item = combo.getItem(combo.getSelectionIndex()); - parameter.setValueFromString(item); - } - } - else if (e.widget instanceof org.eclipse.swt.widgets.List) - { - org.eclipse.swt.widgets.List list = (org.eclipse.swt.widgets.List)e.widget; - String[] selectedItems = list.getSelection(); - if (selectedItems.length > 0) - { - parameter.setValueFromString(selectedItems[0]); - } - } - } - } - - /** - * Listener class for boolean parameter widgets - */ - private class BooleanSelectionListener extends SelectionAdapter - { - public void widgetSelected(SelectionEvent e) - { - ParameterData parameter = (ParameterData)(e.widget.getData()); - if (e.widget instanceof Button) - { - Button button = (Button)e.widget; - parameter.setValue(button.getSelection()); - } - else if (e.widget instanceof Combo) - { - Combo combo = (Combo)e.widget; - String item = combo.getItem(combo.getSelectionIndex()); - parameter.setValueFromString(item); - } - } - } - - /** - * Listener class for the operation parameter value widget (Text field) - */ - private class KeyListenerImpl extends KeyAdapter - { - public void keyReleased(KeyEvent e) - { - if (!(e.widget instanceof Text)) - return; - - Text text = (Text)e.widget; - // Get the parameters widget and assign the text to the parameter - String strValue = text.getText(); - ParameterData parameter = (ParameterData)text.getData(); - try - { - parameter.setValueFromString(strValue); - } - catch(Exception ex) - { - // Exception occured in setting parameter value. - // ignore it. The value will not be assigned to the parameter - } - } - } - - /** - * Listener class for HeaderExchange's new binding widgets. Used when the new bindings are - * being created for Header's Exchange - */ - private class HeaderBindingKeyListener extends KeyAdapter - { - public void keyReleased(KeyEvent e) - { - ParameterData param = _opData.getParameters().get(1); - StringBuffer paramValue = new StringBuffer(); - for (Entry<Text, Text> entry : headerBindingHashMap.entrySet()) - { - - Text nameText = entry.getKey(); - String name = nameText.getText(); - Text valueText = entry.getValue(); - String value = valueText.getText(); - if ((name != null) && (name.length() != 0) && (value != null) && (value.length() != 0)) - { - if (paramValue.length() != 0) - { - paramValue.append(","); - } - paramValue.append(name + "=" + value); - } - } - - param.setValue(paramValue.toString()); - } - } - - /** - * Listener class for verifying the user input with parameter type - */ - private class VerifyListenerImpl implements VerifyListener - { - public void verifyText(VerifyEvent event) - { - ParameterData parameter = (ParameterData)event.widget.getData(); - String text = event.text; - char [] chars = new char [text.length ()]; - text.getChars(0, chars.length, chars, 0); - String type = parameter.getType(); - if (type.equals("int") || type.equals("java.lang.Integer") || - type.equals("long") || type.equals("java.lang.Long")) - { - for (int i=0; i<chars.length; i++) - { - if (!('0' <= chars [i] && chars [i] <= '9')) - { - event.doit = false; - return; - } - } - - } - } - } - -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/QueueTypeTabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/QueueTypeTabControl.java deleted file mode 100644 index 31a0bc857b..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/QueueTypeTabControl.java +++ /dev/null @@ -1,296 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.management.ui.views; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; - -import org.apache.qpid.management.ui.ApplicationRegistry; -import org.apache.qpid.management.ui.Constants; -import org.apache.qpid.management.ui.ManagedBean; -import org.apache.qpid.management.ui.ServerRegistry; -import org.apache.qpid.management.ui.jmx.MBeanUtility; -import org.apache.qpid.management.ui.model.AttributeData; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Group; -import org.eclipse.swt.widgets.TabFolder; - -/** - * Controller class, which takes care of displaying appropriate information and widgets for Queues. - * This allows user to select Queues and add those to the navigation view - */ -public class QueueTypeTabControl extends MBeanTypeTabControl -{ - private boolean _showTempQueues = false; - private Button _sortBySizeButton = null; - private Button _sortByConsumercountButton = null; - private Button _sortByNameButton = null; - private Button _showTempQueuesButton = null; - - private ComparatorImpl _sorterByAttribute = new ComparatorImpl(); - - // Map required for sorting queues based on attribute values - private Map<AttributeData, ManagedBean> _queueDepthMap = new LinkedHashMap<AttributeData, ManagedBean>(); - // Map used for sorting Queues based on consumer count - private Map<AttributeData, ManagedBean> _queueConsumerCountMap = new LinkedHashMap<AttributeData, ManagedBean>(); - - - public QueueTypeTabControl(TabFolder tabFolder) - { - super(tabFolder, Constants.QUEUE); - createWidgets(); - } - - protected void createWidgets() - { - createHeaderComposite(getFormComposite()); - createButtonsComposite(getFormComposite()); - createListComposite(); - } - - @Override - public void refresh() throws Exception - { - setLabelValues(); - selectDefaultSortingButton(); - populateList(); - layout(); - } - - /** - * populates the map with mbean name and the mbean object. - * @throws Exception - */ - protected void populateList() throws Exception - { - // map should be cleared before populating it with new values - getMBeansMap().clear(); - _queueDepthMap.clear(); - _queueConsumerCountMap.clear(); - - ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(MBeanView.getServer()); - String[] items = null; - java.util.List<ManagedBean> list = null; - - // populate the map and list with appropriate mbeans - list = serverRegistry.getQueues(MBeanView.getVirtualHost()); - items = getQueueItems(list); - // sort the refreshed list in the selected order - if (_sortBySizeButton.getSelection()) - { - sortQueuesByQueueDepth(); - } - else if (_sortByConsumercountButton.getSelection()) - { - sortQueuesByConsumerCount(); - } - else - { - getListWidget().setItems(items); - } - } - - private void selectDefaultSortingButton() - { - _sortByNameButton.setSelection(true); - _sortBySizeButton.setSelection(false); - _sortByConsumercountButton.setSelection(false); - - _showTempQueues = false; - _showTempQueuesButton.setSelection(_showTempQueues); - } - - protected void createListComposite() - { - // Composite to contain the item list - Composite composite = getToolkit().createComposite(getFormComposite()); - GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true); - composite.setLayoutData(gridData); - GridLayout layout = new GridLayout(2, true); - layout.verticalSpacing = 0; - composite.setLayout(layout); - - createListComposite(composite); - - // Composite to contain buttons like - Sort by size - Composite _sortingComposite = getToolkit().createComposite(composite); - gridData = new GridData(SWT.FILL, SWT.FILL, true, true); - _sortingComposite.setLayoutData(gridData); - GridLayout gridLayout = new GridLayout(); - gridLayout.verticalSpacing = 20; - _sortingComposite.setLayout(gridLayout); - - Group sortingGroup = new Group(_sortingComposite, SWT.SHADOW_NONE); - sortingGroup.setBackground(_sortingComposite.getBackground()); - sortingGroup.setText(" Sort List By "); - sortingGroup.setFont(ApplicationRegistry.getFont(Constants.FONT_BOLD)); - gridData = new GridData(SWT.CENTER, SWT.TOP, true, false); - sortingGroup.setLayoutData(gridData); - sortingGroup.setLayout(new GridLayout()); - - _sortByNameButton = getToolkit().createButton(sortingGroup, Constants.QUEUE_SORT_BY_NAME, SWT.RADIO); - gridData = new GridData(SWT.LEAD, SWT.CENTER, true, false); - _sortByNameButton.setLayoutData(gridData); - _sortByNameButton.addSelectionListener(new SelectionAdapter(){ - public void widgetSelected(SelectionEvent e) - { - try - { - // sort the stored list of items - java.util.List<String> list = new ArrayList<String>(getMBeansMap().keySet()); - Collections.sort(list); - getListWidget().setItems(list.toArray(new String[0])); - } - catch (Exception ex) - { - MBeanUtility.handleException(ex); - } - } - }); - - _sortBySizeButton = getToolkit().createButton(sortingGroup, Constants.QUEUE_SORT_BY_DEPTH, SWT.RADIO); - gridData = new GridData(SWT.LEAD, SWT.CENTER, true, false); - _sortBySizeButton.setLayoutData(gridData); - _sortBySizeButton.addSelectionListener(new SelectionAdapter(){ - public void widgetSelected(SelectionEvent e) - { - try - { - // sort the stored list of items - sortQueuesByQueueDepth(); - } - catch (Exception ex) - { - MBeanUtility.handleException(ex); - } - } - }); - - _sortByConsumercountButton = getToolkit().createButton(sortingGroup, Constants.QUEUE_SORT_BY_CONSUMERCOUNT, SWT.RADIO); - gridData = new GridData(SWT.LEAD, SWT.CENTER, true, false); - _sortByConsumercountButton.setLayoutData(gridData); - _sortByConsumercountButton.addSelectionListener(new SelectionAdapter(){ - public void widgetSelected(SelectionEvent e) - { - try - { - sortQueuesByConsumerCount(); - } - catch (Exception ex) - { - MBeanUtility.handleException(ex); - } - } - }); - - _showTempQueuesButton = getToolkit().createButton(_sortingComposite, Constants.QUEUE_SHOW_TEMP_QUEUES, SWT.CHECK); - _showTempQueuesButton.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, true, false)); - _showTempQueuesButton.addSelectionListener(new SelectionAdapter(){ - public void widgetSelected(SelectionEvent e) - { - Button button = (Button)e.widget; - _showTempQueues = button.getSelection(); - try - { - populateList(); - } - catch (Exception ex) - { - MBeanUtility.handleException(ex); - } - } - }); - } - - - private String[] getQueueItems(java.util.List<ManagedBean> list) throws Exception - { - if (list == null) - return new String[0]; - - // Sort the list. It will keep the mbeans in sorted order in the _queueMap, which is required for - // sorting the queue according to size etc - Collections.sort(list, getMBeanNameSorter()); - java.util.List<String> items = new ArrayList<String>();; - int i = 0; - for (ManagedBean mbean : list) - { - if ((!_showTempQueues && mbean.isTempQueue())) - { - continue; - } - AttributeData data = MBeanUtility.getAttributeData(mbean, Constants.ATTRIBUTE_QUEUE_DEPTH); - String value = mbean.getName() + " (" + data.getValue().toString() + " KB)"; - items.add(value); - //items[i] = mbean.getName() + " (" + value + " KB)"; - getMBeansMap().put(value, mbean); - _queueDepthMap.put(data, mbean); - data = MBeanUtility.getAttributeData(mbean, Constants.ATTRIBUTE_QUEUE_CONSUMERCOUNT); - _queueConsumerCountMap.put(data, mbean); - i++; - } - - return items.toArray(new String[0]); - } - - - private void sortQueuesByQueueDepth() - { - // Queues are already in the alphabetically sorted order in _queueMap, now sort for queueDepth - java.util.List<AttributeData> list = new ArrayList<AttributeData>(_queueDepthMap.keySet()); - Collections.sort(list, _sorterByAttribute); - - String[] items = new String[list.size()]; - int i = 0; - for (AttributeData data : list) - { - ManagedBean mbean = _queueDepthMap.get(data); - String value = data.getValue().toString(); - items[i++] = mbean.getName() + " (" + value + " KB)"; - } - getListWidget().setItems(items); - } - - private void sortQueuesByConsumerCount() - { - java.util.List<AttributeData> list = new ArrayList<AttributeData>(_queueConsumerCountMap.keySet()); - Collections.sort(list, _sorterByAttribute); - - String[] items = new String[list.size()]; - int i = 0; - for (AttributeData data : list) - { - ManagedBean mbean = _queueConsumerCountMap.get(data); - String value = data.getValue().toString(); - items[i++] = mbean.getName() + " (" + value + " )"; - } - getListWidget().setItems(items); - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/TabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/TabControl.java deleted file mode 100644 index c13c92066c..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/TabControl.java +++ /dev/null @@ -1,102 +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.management.ui.views; - -import java.util.ArrayList; - -import org.apache.qpid.management.ui.ManagedBean; -import org.apache.qpid.management.ui.model.OperationData; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.TabFolder; - -/** - * Abstract class for all the control classes of tabs. - * @author Bhupendra Bhardwaj - */ -public abstract class TabControl -{ - protected ManagedBean _mbean = null; - protected TabFolder _tabFolder = null; - - private static java.util.List<String> simpleTypes = new ArrayList<String>(); - - static - { - simpleTypes.add("java.math.BigDecimal"); - simpleTypes.add("java.math.BigInteger"); - simpleTypes.add("java.lang.Boolean"); - simpleTypes.add("java.lang.Byte"); - simpleTypes.add("java.lang.Character"); - simpleTypes.add("java.util.Date"); - simpleTypes.add("java.lang.Double"); - simpleTypes.add("java.lang.Float"); - simpleTypes.add("java.lang.Integer"); - simpleTypes.add("java.lang.Long"); - simpleTypes.add("javax.management.ObjectName"); - simpleTypes.add("java.lang.Short"); - simpleTypes.add("java.lang.String"); - simpleTypes.add("boolean"); - } - - public TabControl(TabFolder tabFolder) - { - _tabFolder = tabFolder; - } - - /** - * @return controller composite for the tab - */ - public Control getControl() - { - return null; - } - - public void refresh(ManagedBean mbean) - { - if (mbean == null) - { - refresh(); - } - } - - public void refresh() - { - - } - - public void refresh(ManagedBean mbean, OperationData opData) - { - - } - - /** - * Sets focus on a widget - */ - public void setFocus() - { - - } - - public boolean isSimpleType(Object data) - { - return simpleTypes.contains(data.getClass().getName()); - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/TreeObject.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/TreeObject.java deleted file mode 100644 index 9545ed9876..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/TreeObject.java +++ /dev/null @@ -1,126 +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.management.ui.views; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.qpid.management.ui.Constants; -import org.apache.qpid.management.ui.ManagedBean; -import org.apache.qpid.management.ui.ManagedObject; - -public class TreeObject -{ - private String _name; - private String _type; - private String _virtualHost; - private TreeObject _parent; - private List<TreeObject> _children = new ArrayList<TreeObject>(); - private ManagedObject _object; - - public TreeObject(String name, String type) - { - this._name = name; - this._type = type; - } - - public TreeObject(ManagedObject obj) - { - _name = obj.getName(); - if (_name == null && (obj instanceof ManagedBean)) - { - String[] types = ((ManagedBean)obj).getType().split("\\."); - _name = types[types.length - 1]; - } - this._type = Constants.MBEAN; - this._object = obj; - } - - public void addChild(TreeObject child) - { - _children.add(child); - } - - public void addChildren(List<TreeObject> subList) - { - _children.addAll(subList); - } - - public List<TreeObject> getChildren() - { - return _children; - } - - public void setChildren(List<TreeObject> children) - { - this._children = children; - } - - public void setName(String value) - { - _name = value; - } - - public String getName() - { - return _name; - } - public String getType() - { - return _type; - } - - public String getVirtualHost() - { - // To make it work with the broker with no virtual host implementation - return _virtualHost == null ? Constants.DEFAULT_VH : _virtualHost; - } - - public void setVirtualHost(String vHost) - { - _virtualHost = vHost; - } - - public ManagedObject getManagedObject() - { - return _object; - } - - public void setManagedObject(ManagedObject obj) - { - this._object = obj; - } - - public TreeObject getParent() - { - return _parent; - } - - public void setParent(TreeObject parent) - { - this._parent = parent; - - if (parent != null) - { - parent.addChild(this); - } - } -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/VHNotificationsTabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/VHNotificationsTabControl.java deleted file mode 100644 index be25707bd3..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/VHNotificationsTabControl.java +++ /dev/null @@ -1,483 +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.management.ui.views; - -import static org.apache.qpid.management.ui.Constants.BUTTON_CLEAR; -import static org.apache.qpid.management.ui.Constants.BUTTON_REFRESH; -import static org.apache.qpid.management.ui.Constants.CONSOLE_IMAGE; -import static org.apache.qpid.management.ui.Constants.FONT_BUTTON; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.qpid.management.ui.ApplicationRegistry; -import org.apache.qpid.management.ui.ServerRegistry; -import org.apache.qpid.management.ui.model.NotificationObject; -import org.eclipse.jface.viewers.DoubleClickEvent; -import org.eclipse.jface.viewers.IDoubleClickListener; -import org.eclipse.jface.viewers.ILabelProviderListener; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.IStructuredContentProvider; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.ITableLabelProvider; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.jface.viewers.TableViewer; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.widgets.TabFolder; -import org.eclipse.swt.widgets.Table; -import org.eclipse.swt.widgets.TableColumn; -import org.eclipse.swt.widgets.Text; -import org.eclipse.ui.forms.widgets.Form; -import org.eclipse.ui.forms.widgets.FormToolkit; - -public class VHNotificationsTabControl extends TabControl -{ - protected FormToolkit _toolkit; - protected Form _form; - protected Table _table = null; - protected TableViewer _tableViewer = null; - - protected Thread worker = null; - - protected List<NotificationObject> _notifications = null; - - private static final String COLUMN_OBJ = "Object Name"; - private static final String COLUMN_SEQ = "Sequence No"; - private static final String COLUMN_TIME = "TimeStamp"; - private static final String COLUMN_TYPE = "Type"; - private static final String COLUMN_MSG = "Notification Message"; - protected static final String[] _tableTitles = new String [] { - COLUMN_OBJ, - COLUMN_SEQ, - COLUMN_TIME, - COLUMN_TYPE, - COLUMN_MSG - }; - - protected Button _clearButton = null; - protected Button _refreshButton = null; - - public VHNotificationsTabControl(TabFolder tabFolder) - { - super(tabFolder); - _toolkit = new FormToolkit(_tabFolder.getDisplay()); - _form = _toolkit.createForm(_tabFolder); - GridLayout gridLayout = new GridLayout(); - gridLayout.marginWidth = 0; - gridLayout.marginHeight = 0; - _form.getBody().setLayout(gridLayout); - - worker = new Thread(new Worker()); - worker.start(); - } - - protected void createWidgets() - { - addButtons(); - createTableViewer(); - } - - /** - * @see TabControl#getControl() - */ - public Control getControl() - { - if (_table == null) - { - createWidgets(); - } - return _form; - } - - /** - * Creates clear buttin and refresh button - */ - protected void addButtons() - { - Composite composite = _toolkit.createComposite(_form.getBody(), SWT.NONE); - composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); - composite.setLayout(new GridLayout(2, true)); - - // Add Clear Button - _clearButton = _toolkit.createButton(composite, BUTTON_CLEAR, SWT.PUSH | SWT.CENTER); - _clearButton.setFont(ApplicationRegistry.getFont(FONT_BUTTON)); - GridData gridData = new GridData(SWT.LEAD, SWT.TOP, true, false); - gridData.widthHint = 80; - _clearButton.setLayoutData(gridData); - _clearButton.addSelectionListener(new SelectionAdapter() - { - public void widgetSelected(SelectionEvent e) - { - //TODO : Get selected rows and clear those - IStructuredSelection ss = (IStructuredSelection)_tableViewer.getSelection(); - ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(MBeanView.getServer()); - serverRegistry.clearNotifications(null, ss.toList()); - refresh(); - } - }); - - // Add Refresh Button - _refreshButton = _toolkit.createButton(composite, BUTTON_REFRESH, SWT.PUSH | SWT.CENTER); - _refreshButton.setFont(ApplicationRegistry.getFont(FONT_BUTTON)); - gridData = new GridData(SWT.TRAIL, SWT.TOP, true, false); - gridData.widthHint = 80; - _refreshButton.setLayoutData(gridData); - _refreshButton.addSelectionListener(new SelectionAdapter() - { - public void widgetSelected(SelectionEvent e) - { - refresh(); - } - }); - } - - /** - * Creates table to display notifications - */ - private void createTable() - { - _table = _toolkit.createTable(_form.getBody(), SWT.MULTI | SWT.FULL_SELECTION); - _table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - - TableColumn column = new TableColumn(_table, SWT.NONE); - column.setText(_tableTitles[0]); - column.setWidth(100); - - column = new TableColumn(_table, SWT.NONE); - column.setText(_tableTitles[1]); - column.setWidth(100); - - column = new TableColumn(_table, SWT.NONE); - column.setText(_tableTitles[2]); - column.setWidth(130); - - column = new TableColumn(_table, SWT.NONE); - column.setText(_tableTitles[3]); - column.setWidth(100); - - column = new TableColumn(_table, SWT.NONE); - column.setText(_tableTitles[4]); - column.setWidth(500); - - _table.setHeaderVisible(true); - _table.setLinesVisible(true); - } - - /** - * Creates JFace viewer for the notifications table - */ - protected void createTableViewer() - { - createTable(); - _tableViewer = new TableViewer(_table); - //_tableViewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - _tableViewer.setUseHashlookup(true); - _tableViewer.setContentProvider(new ContentProviderImpl()); - _tableViewer.setLabelProvider(new LabelProviderImpl()); - _tableViewer.setColumnProperties(_tableTitles); - /* - CellEditor[] cellEditors = new CellEditor[_tableTitles.length]; - TextCellEditor textEditor = new TextCellEditor(table); - cellEditors[0] = textEditor; - textEditor = new TextCellEditor(table); - cellEditors[1] = textEditor; - textEditor = new TextCellEditor(table); - cellEditors[2] = textEditor; - textEditor = new TextCellEditor(table); - cellEditors[3] = textEditor; - - // Assign the cell editors to the viewer - _tableViewer.setCellEditors(cellEditors); - _tableViewer.setCellModifier(new TableCellModifier()); - */ - - addTableListeners(); - - //_tableViewer.addSelectionChangedListener(new ); - - //_notificationDetails = new Composite(_tabControl, SWT.BORDER); - //_notificationDetails.setLayoutData(new GridData(GridData.FILL_BOTH)); - - //_tabControl.layout(); - //viewerComposite.layout(); - } - - /** - * Adds listeners to the viewer for displaying notification details - */ - protected void addTableListeners() - { - _tableViewer.addDoubleClickListener(new IDoubleClickListener() - { - Display display = null; - Shell shell = null; - public void doubleClick(DoubleClickEvent event) - { - display = Display.getCurrent(); - shell = new Shell(display, SWT.BORDER | SWT.CLOSE | SWT.MIN | SWT.MAX | SWT.RESIZE); - shell.setText("Notification"); - shell.setImage(ApplicationRegistry.getImage(CONSOLE_IMAGE)); - - int x = display.getBounds().width; - int y = display.getBounds().height; - shell.setBounds(x/4, y/4, x/2, y/3); - StructuredSelection selection = (StructuredSelection)event.getSelection(); - createPopupContents((NotificationObject)selection.getFirstElement()); - shell.open(); - while (!shell.isDisposed()) { - if (!display.readAndDispatch()) { - display.sleep(); - } - } - - //If you create it, you dispose it. - shell.dispose(); - } - - private void createPopupContents(NotificationObject obj) - { - shell.setLayout(new GridLayout()); - - Composite parent = _toolkit.createComposite(shell, SWT.NONE); - parent.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - GridLayout layout = new GridLayout(4, true); - parent.setLayout(layout); - - // Object name record - Label key = _toolkit.createLabel(parent, COLUMN_OBJ, SWT.TRAIL); - GridData layoutData = new GridData(SWT.TRAIL, SWT.TOP, false, false,1,1); - key.setLayoutData(layoutData); - Text value = _toolkit.createText(parent, obj.getSourceName(), SWT.BEGINNING | SWT.BORDER |SWT.READ_ONLY); - value.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false,3,1)); - - // Sequence no record - key = _toolkit.createLabel(parent, COLUMN_SEQ, SWT.TRAIL); - layoutData = new GridData(SWT.TRAIL, SWT.TOP, false, false,1,1); - key.setLayoutData(layoutData); - value = _toolkit.createText(parent, ""+obj.getSequenceNo(), SWT.BEGINNING | SWT.BORDER |SWT.READ_ONLY); - value.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false,3,1)); - - // Time row - key = _toolkit.createLabel(parent, COLUMN_TIME, SWT.TRAIL); - key.setLayoutData(new GridData(SWT.TRAIL, SWT.TOP, true, false,1,1)); - value = _toolkit.createText(parent, obj.getTimeStamp(), SWT.BEGINNING | SWT.BORDER | SWT.READ_ONLY); - value.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false,3,1)); - - key = _toolkit.createLabel(parent, COLUMN_TYPE, SWT.TRAIL); - key.setLayoutData(new GridData(SWT.TRAIL, SWT.TOP, true, false,1,1)); - value = _toolkit.createText(parent, obj.getType(), SWT.BEGINNING | SWT.BORDER | SWT.READ_ONLY); - value.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false,3,1)); - - key = _toolkit.createLabel(parent, COLUMN_MSG, SWT.TRAIL); - key.setLayoutData(new GridData(SWT.TRAIL, SWT.TOP, true, false,1,1)); - value = _toolkit.createText(parent, obj.getMessage(), SWT.MULTI | SWT.WRAP| SWT.BORDER | SWT.V_SCROLL | SWT.READ_ONLY); - GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1); - gridData.heightHint = 100; - value.setLayoutData(gridData); - } - }); - } - - public void refresh() - { - _notifications = null; - _table.deselectAll(); - _tableViewer.getTable().clearAll(); - - Control[] children = _form.getBody().getChildren(); - for (int i = 0; i < children.length; i++) - { - children[i].setVisible(true); - } - - workerRunning = true; - _form.layout(true); - _form.getBody().layout(true, true); - } - - /** - * Content provider class for the table viewer - */ - protected class ContentProviderImpl implements IStructuredContentProvider, INotificationViewer - { - public void inputChanged(Viewer v, Object oldInput, Object newInput) - { - - } - public void dispose() - { - - } - public Object[] getElements(Object parent) - { - return _notifications.toArray(new NotificationObject[0]); - } - public void addNotification(NotificationObject notification) - { - _tableViewer.add(notification); - } - - public void addNotification(List<NotificationObject> notificationList) - { - _tableViewer.add(notificationList.toArray(new NotificationObject[0])); - } - } - - /** - * Label provider for the table viewer - */ - protected class LabelProviderImpl implements ITableLabelProvider - { - List<ILabelProviderListener> listeners = new ArrayList<ILabelProviderListener>(); - public void addListener(ILabelProviderListener listener) - { - listeners.add(listener); - } - - public void dispose(){ - - } - - public Image getColumnImage(Object element, int columnIndex) - { - return null; - } - - public String getColumnText(Object element, int columnIndex) - { - String result = null; - NotificationObject t = (NotificationObject)element; - switch(columnIndex) - { - case 0 : - result = t.getSourceName(); - break; - case 1 : - result = String.valueOf(t.getSequenceNo()); - break; - case 2 : - result = String.valueOf(t.getTimeStamp()); - break; - case 3 : - result = t.getType(); - break; - case 4 : - result = t.getMessage(); - break; - default : - result = ""; - } - - return result; - } - - public boolean isLabelProperty(Object element, String property) - { - return false; - } - - public void removeListener(ILabelProviderListener listener) - { - listeners.remove(listener); - } - } // end of LabelProviderImpl - - protected boolean workerRunning = false; - protected void setWorkerRunning(boolean running) - { - workerRunning = running; - } - - /** - * Worker class which keeps looking if there are new notifications coming from server for the selected mbean - */ - private class Worker implements Runnable - { - public void run() - { - Display display = _tabFolder.getDisplay(); - while(true) - { - if (!workerRunning || display == null) - { - sleep(); - continue; - } - - display.syncExec(new Runnable() - { - public void run() - { - if (_form == null || _form.isDisposed()) - return; - setWorkerRunning(_form.isVisible()); - if (!workerRunning) return; - - updateTableViewer(); - } - }); - - sleep(); - } - } - - private void sleep() - { - try - { - Thread.sleep(2000); - } - catch(Exception ex) - { - - } - } - } - - /** - * Updates the table with new notifications received from mbean server for all mbeans - */ - protected void updateTableViewer() - { - ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(MBeanView.getServer()); - List<NotificationObject> newList = serverRegistry.getNotifications(null); - if (newList == null) - return; - - _notifications = newList; - _tableViewer.setInput(_notifications); - _tableViewer.refresh(); - } - -} diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/ViewUtility.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/ViewUtility.java deleted file mode 100644 index 4a441d3ae5..0000000000 --- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/ViewUtility.java +++ /dev/null @@ -1,979 +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.management.ui.views; - -import org.apache.commons.codec.binary.Hex; -import org.apache.qpid.management.ui.ApplicationWorkbenchAdvisor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.jface.dialogs.ErrorDialog; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.ControlAdapter; -import org.eclipse.swt.events.ControlEvent; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.graphics.Font; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.MessageBox; -import org.eclipse.swt.widgets.ScrollBar; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.widgets.Text; -import org.eclipse.ui.forms.widgets.FormToolkit; - -import javax.management.openmbean.ArrayType; -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.CompositeDataSupport; -import javax.management.openmbean.CompositeType; -import javax.management.openmbean.OpenType; -import javax.management.openmbean.TabularDataSupport; -import javax.management.openmbean.TabularType; -import java.io.UnsupportedEncodingException; -import java.nio.charset.Charset; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.Map; -import java.util.Set; - - -/** - * Utility Class for displaying OpenMbean data types by creating required SWT widgets - * @author Bhupendra Bhardwaj - */ -public class ViewUtility -{ - public static final String OP_NAME = "operation_name"; - public static final String OP_PARAMS = "parameters"; - public static final String PARAMS_TEXT = "text"; - - public static final String FIRST = "First"; - public static final String LAST = "Last"; - public static final String NEXT = "Next"; - public static final String PREV = "Previous"; - public static final String INDEX = "Index"; - - private static final Comparator tabularDataComparator = new TabularDataComparator(); - - private static List<String> SUPPORTED_ARRAY_DATATYPES = new ArrayList<String>(); - private static final int DEFAULT_CONTENT_SIZE = 198; - - static - { - SUPPORTED_ARRAY_DATATYPES.add("java.lang.String"); - SUPPORTED_ARRAY_DATATYPES.add("java.lang.Boolean"); - SUPPORTED_ARRAY_DATATYPES.add("java.lang.Character"); - SUPPORTED_ARRAY_DATATYPES.add("java.lang.Integer"); - SUPPORTED_ARRAY_DATATYPES.add("java.lang.Long"); - SUPPORTED_ARRAY_DATATYPES.add("java.lang.Double"); - SUPPORTED_ARRAY_DATATYPES.add("java.util.Date"); - } - - /** - * Populates the composite with given openmbean data type (TabularType or CompositeType) - * @param toolkit - * @param parent composite - * @param data open mbean data type(either composite type or tabular data type) - */ - public static void populateCompositeWithData(FormToolkit toolkit, Composite parent, Object data) - { - if (data instanceof TabularDataSupport) - { - ViewUtility.createTabularDataHolder(toolkit, parent, (TabularDataSupport) data); - } - else if (data instanceof CompositeDataSupport) - { - ViewUtility.populateCompositeWithCompositeData(toolkit, parent, (CompositeDataSupport) data); - } - } - - @SuppressWarnings("unchecked") - private static void createTabularDataHolder(FormToolkit toolkit, Composite parent, TabularDataSupport tabularData) - { - Composite composite = toolkit.createComposite(parent, SWT.BORDER); - GridLayout layout = new GridLayout(4, true); - layout.horizontalSpacing = 0; - layout.marginWidth = 0; - layout.marginHeight = 10; - layout.verticalSpacing = 10; - composite.setLayout(layout); - composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - - Set entrySet = tabularData.entrySet(); - ArrayList<Map.Entry> list = new ArrayList<Map.Entry>(entrySet); - if (list.size() == 0) - { - Text text = toolkit.createText(composite, " No records ", SWT.CENTER | SWT.SINGLE | SWT.READ_ONLY); - GridData layoutData = new GridData(SWT.FILL, SWT.FILL, true, true, 4, 1); - text.setLayoutData(layoutData); - return; - } - - Collections.sort(list, tabularDataComparator); - - // Attach the tabular record to be retrieved and shown later when record is traversed - // using first/next/previous/last buttons - composite.setData(list); - - // Create button and the composite for CompositeData - Composite compositeDataHolder = createCompositeDataHolder(toolkit, composite, - tabularData.getTabularType().getRowType()); - - // display the first record - CompositeData data = (CompositeData) (list.get(0)).getValue(); - composite.setData(INDEX, 0); - populateCompositeWithCompositeData(toolkit, compositeDataHolder, data); - enableOrDisableTraversalButtons(composite); - } - - private static void enableOrDisableTraversalButtons(Composite composite) - { - int index = (Integer) composite.getData(INDEX); - int size = ((List) composite.getData()).size(); - - ((Button) composite.getData(FIRST)).setEnabled(true); - ((Button) composite.getData(PREV)).setEnabled(true); - ((Button) composite.getData(NEXT)).setEnabled(true); - ((Button) composite.getData(LAST)).setEnabled(true); - - if (index == 0) - { - ((Button) composite.getData(FIRST)).setEnabled(false); - ((Button) composite.getData(PREV)).setEnabled(false); - } - if (index == size - 1) - { - ((Button) composite.getData(NEXT)).setEnabled(false); - ((Button) composite.getData(LAST)).setEnabled(false); - } - } - - /** - * Sets up the given composite for holding a CompositeData. Create traversal buttons, label etc and - * creates a child Composite, which should be populated with the CompositeData - * @param toolkit - * @param dataHolder - * @param compositeType - * @return - */ - private static Composite createCompositeDataHolder(final FormToolkit toolkit, final Composite dataHolder, CompositeType compositeType) - { - String desc = compositeType.getDescription(); - Label description = toolkit.createLabel(dataHolder, desc, SWT.CENTER); - description.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, true, false, 4, 1)); - // TODO nameLabel.setFont(font); - description.setText(desc); - - // Add traversal buttons - final Button firstRecordButton = toolkit.createButton(dataHolder, FIRST, SWT.PUSH); - GridData layoutData = new GridData(GridData.HORIZONTAL_ALIGN_END); - layoutData.widthHint = 80; - firstRecordButton.setLayoutData(layoutData); - - final Button nextRecordButton = toolkit.createButton(dataHolder, NEXT, SWT.PUSH); - layoutData = new GridData(GridData.HORIZONTAL_ALIGN_END); - layoutData.widthHint = 80; - nextRecordButton.setLayoutData(layoutData); - - final Button previousRecordButton = toolkit.createButton(dataHolder, PREV, SWT.PUSH); - layoutData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - layoutData.widthHint = 80; - previousRecordButton.setLayoutData(layoutData); - - final Button lastRecordButton = toolkit.createButton(dataHolder, LAST, SWT.PUSH); - layoutData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - layoutData.widthHint = 80; - lastRecordButton.setLayoutData(layoutData); - - // Now create the composite, which will hold the CompositeData - final Composite composite = toolkit.createComposite(dataHolder, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.horizontalSpacing = layout.verticalSpacing = 0; - layout.marginHeight = layout.marginWidth = 0; - composite.setLayout(layout); - composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 4, 1)); - - // Add button references. These references will be used when buttons - // are to enabled or disabled based of record index. e.g. for first record - // First and Previous buttons will be disabled. - dataHolder.setData(FIRST, firstRecordButton); - dataHolder.setData(NEXT, nextRecordButton); - dataHolder.setData(PREV, previousRecordButton); - dataHolder.setData(LAST, lastRecordButton); - - // Listener for the traversal buttons. When a button is clicked the respective - // CompositeData will be populated in the composite - SelectionListener listener = new SelectionAdapter() - { - public void widgetSelected(SelectionEvent e) - { - if (!(e.widget instanceof Button)) - { - return; - } - - Button traverseButton = (Button) e.widget; - // Get the CompositeData respective to the button selected - CompositeData data = getCompositeData(dataHolder, traverseButton.getText()); - populateCompositeWithCompositeData(toolkit, composite, data); - enableOrDisableTraversalButtons(dataHolder); - } - }; - - firstRecordButton.addSelectionListener(listener); - nextRecordButton.addSelectionListener(listener); - previousRecordButton.addSelectionListener(listener); - lastRecordButton.addSelectionListener(listener); - - return composite; - } - - /** - * The CompositeData is set as data with the Composite and using the index, this method will - * return the corresponding CompositeData - * @param compositeHolder - * @param dataIndex - * @return the CompositeData respective to the index - */ - private static CompositeData getCompositeData(Composite compositeHolder, String dataIndex) - { - List objectData = (List) compositeHolder.getData(); - if (objectData == null || objectData.isEmpty()) - { - // TODO - } - - // Get the index of record to be shown. - int index = 0; - if (compositeHolder.getData(INDEX) != null) - { - index = (Integer) compositeHolder.getData(INDEX); - } - - if (FIRST.equals(dataIndex)) - { - index = 0; - } - else if (NEXT.equals(dataIndex)) - { - index = index + 1; - } - else if (PREV.equals(dataIndex)) - { - index = (index != 0) ? (index = index - 1) : index; - } - else if (LAST.equals(dataIndex)) - { - index = objectData.size() - 1; - } - - // Set the index being shown. - compositeHolder.setData(INDEX, index); - - return (CompositeData) ((Map.Entry) objectData.get(index)).getValue(); - } - - /** - * Populates the given composite with the CompositeData. Creates required widgets to hold the data types - * @param toolkit - * @param parent - * @param data CompositeData - */ - @SuppressWarnings("unchecked") - private static void populateCompositeWithCompositeData(FormToolkit toolkit, Composite parent, CompositeData data) - { - Control[] oldControls = parent.getChildren(); - for (int i = 0; i < oldControls.length; i++) - { - oldControls[i].dispose(); - } - - Composite compositeHolder = toolkit.createComposite(parent, SWT.NONE); - GridLayout layout = new GridLayout(4, false); - layout.horizontalSpacing = 10; - compositeHolder.setLayout(layout); - compositeHolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - - // ItemNames in composite data - List<String> itemNames = new ArrayList<String>(data.getCompositeType().keySet()); - - for (String itemName : itemNames) - { - OpenType itemType = data.getCompositeType().getType(itemName); - Label keyLabel = toolkit.createLabel(compositeHolder, itemName, SWT.TRAIL); - GridData layoutData = new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1); - layoutData.minimumWidth = 70; - keyLabel.setLayoutData(layoutData); - - if (itemType.isArray()) - { - OpenType type = ((ArrayType) itemType).getElementOpenType(); - // If Byte array and mimetype is text, convert to text string - if (type.getClassName().equals(Byte.class.getName())) - { - String mimeType = null; - String encoding = null; - if (data.containsKey("MimeType")) - { - mimeType = (String) data.get("MimeType"); - } - if (data.containsKey("Encoding")) - { - encoding = (String) data.get("Encoding"); - } - - if (encoding == null || encoding.length() == 0) - { - encoding = Charset.defaultCharset().name(); - } - - if ("text/plain".equals(mimeType)) - { - convertByteArray(toolkit, compositeHolder, data, itemName, encoding); - } - else - { - handleBinaryMessageContent(toolkit, compositeHolder, data, itemName, encoding); - } - } - // If array of any other supported type, show as a list of String array - else if (SUPPORTED_ARRAY_DATATYPES.contains(type.getClassName())) - { - convertArrayItemForDisplay(compositeHolder, data, itemName); - } - else - { - setNotSupportedDataType(toolkit, compositeHolder); - } - } - else if (itemType instanceof TabularType) - { - Composite composite = toolkit.createComposite(compositeHolder, SWT.NONE); - composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 3, 1)); - layout = new GridLayout(); - layout.marginHeight = 0; - layout.marginWidth = 0; - composite.setLayout(layout); - createTabularDataHolder(toolkit, composite, (TabularDataSupport) data.get(itemName)); - } - else - { - Text valueText = toolkit.createText(compositeHolder, String.valueOf(data.get(itemName)), SWT.READ_ONLY | SWT.BORDER); - valueText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 3, 1)); - } - } - - // layout the composite after creating new widgets. - parent.layout(); - } //end of method - - - private static void convertByteArray(FormToolkit toolkit, Composite compositeHolder, CompositeData data, String itemName, String encoding) - { - Byte[] arrayItems = (Byte[]) data.get(itemName); - byte[] byteArray = new byte[arrayItems.length]; - - for (int i = 0; i < arrayItems.length; i++) - { - byteArray[i] = arrayItems[i]; - } - try - { - String textMessage = new String(byteArray, encoding); - - Text valueText = toolkit.createText(compositeHolder, textMessage, SWT.READ_ONLY | SWT.BORDER | - SWT.MULTI | SWT.WRAP | SWT.V_SCROLL); - GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1); - gridData.heightHint = 300; - valueText.setLayoutData(gridData); - } - catch (Exception ex) - { - ex.printStackTrace(); - } - } - - static Button _firstButton, _nextButton, _previousButton, _lastButton; - static Text _hexNumTextToEnd, _hexNumTextToStart; - - /** - * Creates widgets for object messages and populates the content in hexadecimal format. - * @param toolkit - * @param compositeHolder - * @param data - * @param itemName - * @param encoding - */ - private static void handleBinaryMessageContent(FormToolkit toolkit, Composite compositeHolder, CompositeData data, String itemName, String encoding) - { - final String thisEncoding = encoding; - final Byte[] arrayItems = (Byte[]) data.get(itemName); - final byte[] byteArray = new byte[arrayItems.length]; - - for (int i = 0; i < arrayItems.length; i++) - { - byteArray[i] = arrayItems[i]; - } - - try - { - //create a new composite to contain the widgets required to display object messages. - final Composite localComposite = toolkit.createComposite(compositeHolder, SWT.NONE); - localComposite.setData("currentBytePos", 0); - localComposite.setData("startingBytePos", 0); - GridLayout layout = new GridLayout(2, true); - layout.marginWidth = 0; - layout.marginHeight = 0; - localComposite.setLayout(layout); - localComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1)); - - int startContentSize = DEFAULT_CONTENT_SIZE; // This will fill the 18 rows of the standard size - - if (byteArray.length < DEFAULT_CONTENT_SIZE) - { - startContentSize = byteArray.length; - } - - //create a text to display the hexadecimal views of object messages, it takes more space than ascii view as a hex uses 2 chars - //and 1 space, while ascii only uses 1 char and 1 space. - final Text hexText = toolkit.createText(localComposite, - new String(displayByteFormat(localComposite, byteArray, startContentSize * 2, thisEncoding, "<<", true)), - SWT.READ_ONLY | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL | SWT.BORDER); - GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); - gridData.widthHint = 144; //set to 222 if not using any fonts - gridData.heightHint = 200; - hexText.setLayoutData(gridData); - - final Text asciiText = toolkit.createText(localComposite, - new String(displayByteFormat(localComposite, byteArray, startContentSize * 2, thisEncoding, "<<", false)), - SWT.READ_ONLY | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL | SWT.BORDER); - - - gridData = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); - gridData.widthHint = 52;//set to 98 if not using any fonts - gridData.heightHint = 200; - asciiText.setLayoutData(gridData); - - //use a monospaced font for a better layout - Font font = new Font(compositeHolder.getDisplay(), "Courier", 10, SWT.NORMAL); - hexText.setFont(font); - asciiText.setFont(font); - - final ScrollBar hexScrollBar = hexText.getVerticalBar(); - final ScrollBar asciiScrollBar = asciiText.getVerticalBar(); - - //create a sub composite to contain all the buttons - final Composite buttonComposite = toolkit.createComposite(localComposite, SWT.NONE); - layout = new GridLayout(7, false); - layout.marginWidth = 0; - buttonComposite.setLayout(layout); - buttonComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 2, 1)); - - _firstButton = toolkit.createButton(buttonComposite, "<<", SWT.PUSH); - GridData layoutData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - layoutData.widthHint = 40; - _firstButton.setLayoutData(layoutData); - _firstButton.setToolTipText("See the first n bytes"); - - _previousButton = toolkit.createButton(buttonComposite, "<", SWT.PUSH); - layoutData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - layoutData.widthHint = 40; - _previousButton.setLayoutData(layoutData); - _previousButton.setToolTipText("See the previous n bytes"); - _previousButton.setEnabled(false); - - _hexNumTextToStart = toolkit.createText(buttonComposite, "0"); - layoutData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - layoutData.widthHint = 40; - _hexNumTextToStart.setLayoutData(layoutData); - _hexNumTextToStart.setEditable(false); - - final Text hexNumText = toolkit.createText(buttonComposite, "" + startContentSize); - layoutData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - layoutData.widthHint = 40; - hexNumText.setLayoutData(layoutData); - - _hexNumTextToEnd = toolkit.createText(buttonComposite, "" + (byteArray.length - startContentSize)); - layoutData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - layoutData.widthHint = 40; - _hexNumTextToEnd.setLayoutData(layoutData); - _hexNumTextToEnd.setEditable(false); - - _nextButton = toolkit.createButton(buttonComposite, ">", SWT.PUSH); - layoutData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - layoutData.widthHint = 40; - _nextButton.setLayoutData(layoutData); - _nextButton.setToolTipText("See the next n bytes"); - _nextButton.setEnabled(true); - - _lastButton = toolkit.createButton(buttonComposite, ">>", SWT.PUSH); - layoutData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - layoutData.widthHint = 40; - _lastButton.setToolTipText("See the last n bytes"); - _lastButton.setLayoutData(layoutData); - - SelectionListener listener = new SelectionAdapter() - { - public void widgetSelected(SelectionEvent e) - { - if (e.widget instanceof Button) - { - String numOfBytes = hexNumText.getText(); - try - { - int n = Integer.parseInt(numOfBytes); - - //Reset range display if user requests a large value - if (n > byteArray.length) - { - n = (byteArray.length > DEFAULT_CONTENT_SIZE) ? DEFAULT_CONTENT_SIZE : byteArray.length; - hexNumText.setText("" + n); - } - - //rest if the user requests 0 - if (n < 1) - { - n = DEFAULT_CONTENT_SIZE; - hexNumText.setText("" + n); - } - - Button button = (Button) e.widget; - hexText.setText(displayByteFormat(localComposite, byteArray, n * 2, thisEncoding, - button.getText(), true)); - asciiText.setText(displayByteFormat(localComposite, byteArray, n * 2, thisEncoding, - button.getText(), false)); - } - catch (NumberFormatException exp) - { - popupErrorMessage("Error", - "Please input the number of bytes you wish to look at"); - } - } - if (e.widget instanceof ScrollBar) - { - //synchronize the movements of the two scrollbars - ScrollBar sb = (ScrollBar) e.widget; - if (sb.getParent().equals(hexText)) - { - asciiScrollBar.setIncrement(sb.getIncrement()); - asciiScrollBar.setSelection(sb.getSelection()); - asciiText.setTopIndex(hexText.getTopIndex()); - } - else if (sb.getParent().equals(asciiText)) - { - hexScrollBar.setSelection(sb.getSelection()); - hexScrollBar.setIncrement(sb.getIncrement()); - hexText.setTopIndex(asciiText.getTopIndex()); - } - } - } - }; - localComposite.addControlListener(new ControlAdapter() - { - public void controlResized(ControlEvent e) - { - //if the control is resized, set different parameters to make a single line displays the same contents. - if (((GridLayout) localComposite.getLayout()).makeColumnsEqualWidth) - { - ((GridLayout) localComposite.getLayout()).makeColumnsEqualWidth = false; - ((GridLayout) localComposite.getLayout()).numColumns = 2; - ((GridData) hexText.getLayoutData()).horizontalSpan = 1; - ((GridData) hexText.getLayoutData()).widthHint = 144; - ((GridData) asciiText.getLayoutData()).horizontalSpan = 1; - ((GridData) asciiText.getLayoutData()).widthHint = 52; - ((GridData) buttonComposite.getLayoutData()).horizontalSpan = 2; - } - else - { - ((GridLayout) localComposite.getLayout()).makeColumnsEqualWidth = true; - ((GridLayout) localComposite.getLayout()).numColumns = 42; //set to 47 if not using any fonts - ((GridData) hexText.getLayoutData()).horizontalSpan = 25; // set to 30 if not using any fonts - ((GridData) asciiText.getLayoutData()).horizontalSpan = 17; // set to 17 if not using any fonts - ((GridData) buttonComposite.getLayoutData()).horizontalSpan = 42; - } - } - }); - - _firstButton.addSelectionListener(listener); - _previousButton.addSelectionListener(listener); - _nextButton.addSelectionListener(listener); - _lastButton.addSelectionListener(listener); - hexScrollBar.addSelectionListener(listener); - asciiScrollBar.addSelectionListener(listener); - //f.dispose(); - } - catch (Exception ex) - { - ex.printStackTrace(); - } - } - - /** - * Format object messages to have a hexadecimal view and a ascii view. - * @param numOfBytes - * @param encoding - * @return - */ - private static String displayByteFormat(Composite localComposite, byte[] byteArray, int numOfBytes, String encoding, String direction, boolean isHex) - { - final Hex hexeconder = new Hex(); - final byte[] encoded = hexeconder.encode(byteArray); - - int hexLength = byteArray.length * 2; - StringBuilder sb = new StringBuilder(); - int currentBytePos = (Integer) localComposite.getData("currentBytePos"); - int startingBytePos = (Integer) localComposite.getData("startingBytePos"); - - int strLength = 0; - int offset = 0; - String encStr; - if (isHex) - { - if (direction.equals("<<")) - { - strLength = (numOfBytes > hexLength) ? hexLength : numOfBytes; - offset = 0; - } - else if (direction.equals("<")) - { - strLength = (startingBytePos - numOfBytes < 0) ? startingBytePos - : numOfBytes; - offset = (startingBytePos - numOfBytes < 0) ? 0 - : startingBytePos - numOfBytes; - } - else if (direction.equals(">")) - { - strLength = (numOfBytes > (hexLength - currentBytePos)) ? hexLength - - currentBytePos - : numOfBytes; - offset = currentBytePos; - - } - else if (direction.equals(">>")) - { - strLength = (numOfBytes > hexLength) ? hexLength : numOfBytes; - offset = (hexLength - numOfBytes > 0) ? hexLength - numOfBytes - : 0; - } - else - { - strLength = hexLength; - offset = 0; - } - localComposite.setData("strLength", strLength); - localComposite.setData("currentBytePos", offset + strLength); - localComposite.setData("startingBytePos", offset); - - if (_lastButton != null && !_lastButton.isDisposed()) - { - //Set button state - _previousButton.setEnabled(offset != 0); - _nextButton.setEnabled(offset + strLength != hexLength); - - //set the text fields - _hexNumTextToStart.setText("" + offset / 2); - _hexNumTextToEnd.setText("" + (hexLength - (offset + strLength)) / 2); - } - } - - try - { - if (isHex) - { - encStr = new String(encoded, offset, strLength, encoding); - for (int c = 0; c < strLength; c++) - { - - sb.append(encStr.charAt(c)); - if (c % 2 == 1) - { - sb.append(" "); - } - - } - return sb.toString().toUpperCase(); - } - else - { - strLength = (Integer) localComposite.getData("strLength"); - sb = new StringBuilder(); - encStr = new String(byteArray, startingBytePos / 2, strLength / 2, encoding); - for (int c = 0; c < encStr.length(); c++) - { - char ch = encStr.charAt(c); - if (ch > 31 && ch < 127) - { - sb.append(ch); - } - else - { - sb.append("?"); - } - - sb.append(" "); - } - } - } - catch (UnsupportedEncodingException e) - { - e.printStackTrace(); - } - return sb.toString(); - } - - public static int popupInfoMessage(String title, String message) - { - MessageBox messageBox = new MessageBox(Display.getCurrent().getActiveShell(), SWT.ICON_INFORMATION | SWT.OK); - messageBox.setMessage(message); - messageBox.setText(title); - int response = messageBox.open(); - - return response; - } - - public static int popupErrorMessage(String title, String message) - { - MessageBox messageBox = new MessageBox(Display.getCurrent().getActiveShell(), SWT.ICON_ERROR | SWT.OK); - messageBox.setMessage(message); - messageBox.setText(title); - int response = messageBox.open(); - - return response; - } - - public static int popupConfirmationMessage(String title, String message) - { - MessageBox messageBox = new MessageBox(Display.getCurrent().getActiveShell(), - SWT.ICON_QUESTION | SWT.YES | SWT.NO | SWT.CANCEL); - messageBox.setMessage(message); - messageBox.setText(title); - int response = messageBox.open(); - - return response; - } - - public static void popupError(String title, String message, Throwable ex) - { - IStatus status = new Status(IStatus.ERROR, ApplicationWorkbenchAdvisor.PERSPECTIVE_ID, - IStatus.ERROR, ex.toString(), ex); - ErrorDialog.openError(Display.getCurrent().getActiveShell(), title, message, status); - - } - - public static void popupError(String errorMsg) - { - Display display = Display.getCurrent(); - Shell shell = new Shell(display, SWT.BORDER | SWT.CLOSE | SWT.MIN | SWT.MAX); - shell.setText("Attribute"); - shell.setLayout(new GridLayout()); - int x = display.getBounds().width; - int y = display.getBounds().height; - int width = 500; - int height = 250; - shell.setBounds(x / 4, y / 4, width, height); - - Label label = new Label(shell, SWT.NONE); - label.setText(errorMsg); - label.setLayoutData(new GridData(SWT.TRAIL, SWT.TOP, false, false)); - - shell.open(); - while (!shell.isDisposed()) - { - if (!display.readAndDispatch()) - { - display.sleep(); - } - } - shell.dispose(); - } - - public static Shell createPopupShell(String title, int width, int height) - { - Display display = Display.getCurrent(); - Shell shell = new Shell(display, SWT.BORDER | SWT.CLOSE | SWT.MIN | SWT.MAX); - shell.setText(title); - shell.setLayout(new GridLayout()); - int x = display.getBounds().width; - int y = display.getBounds().height; - shell.setBounds(x / 4, y / 4, width, height); - - return shell; - } - - /** - * Creates a List widget for displaying array of strings - * @param compositeHolder - * @param data - containing the array item value - * @param itemName - item name - */ - private static void convertArrayItemForDisplay(Composite compositeHolder, CompositeData data, String itemName) - { - Object[] arrayItems = (Object[]) data.get(itemName); - String[] items = new String[arrayItems.length]; - for (int i = 0; i < arrayItems.length; i++) - { - items[i] = String.valueOf(arrayItems[i]); - } - org.eclipse.swt.widgets.List list = new org.eclipse.swt.widgets.List(compositeHolder, - SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.READ_ONLY); - list.setItems(items); - //list.setBackground(compositeHolder.getBackground()); - list.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1)); - } - - private static void setNotSupportedDataType(FormToolkit toolkit, Composite compositeHolder) - { - Text valueText = toolkit.createText(compositeHolder, "--- Content can not be displayed ---", SWT.READ_ONLY); - valueText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 3, 1)); - } - - /** - * Converts the input string to displayable format by converting some character case or inserting space - * @param input - * @return formatted string - */ - public static String getDisplayText(String input) - { - StringBuffer result = new StringBuffer(input); - if (Character.isLowerCase(result.charAt(0))) - { - result.setCharAt(0, Character.toUpperCase(result.charAt(0))); - } - for (int i = 1; i < input.length(); i++) - { - if (Character.isUpperCase(result.charAt(i)) && !Character.isWhitespace(result.charAt(i - 1)) - && Character.isLowerCase(result.charAt(i - 1))) - { - result.insert(i, " "); - i++; - } - else if (Character.isLowerCase(result.charAt(i)) && Character.isWhitespace(result.charAt(i - 1))) - { - result.setCharAt(i, Character.toUpperCase(result.charAt(i))); - } - - } - - return result.toString(); - } - - /** - * Disposes the children of given Composite if not null and not already disposed - * @param parent composite - */ - public static void disposeChildren(Composite parent) - { - if (parent == null || parent.isDisposed()) - { - return; - } - - Control[] oldControls = parent.getChildren(); - for (int i = 0; i < oldControls.length; i++) - { - oldControls[i].dispose(); - } - } - - public static char[] getMD5HashedCharArray(Object text) throws NoSuchAlgorithmException, UnsupportedEncodingException - { - byte[] data = ((String) text).getBytes("utf-8"); - - MessageDigest md = MessageDigest.getInstance("MD5"); - - for (byte b : data) - { - md.update(b); - } - - byte[] digest = md.digest(); - - char[] byteArray = new char[digest.length]; - int index = 0; - for (byte b : digest) - { - byteArray[index++] = (char) b; - } - return byteArray; - } - - public static char[] getHash(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException - { - byte[] data = text.getBytes("utf-8"); - - MessageDigest md = MessageDigest.getInstance("MD5"); - - for (byte b : data) - { - md.update(b); - } - - byte[] digest = md.digest(); - - char[] hash = new char[digest.length]; - - int index = 0; - for (byte b : digest) - { - hash[index++] = (char) b; - } - - return hash; - } - - private static class TabularDataComparator implements java.util.Comparator<Map.Entry> - { - public int compare(Map.Entry data1, Map.Entry data2) - { - if (data1.getKey() instanceof List) - { - Object obj1 = ((List) data1.getKey()).get(0); - Object obj2 = ((List) data2.getKey()).get(0); - String str1 = obj1.toString(); - String str2 = obj2.toString(); - if (obj1 instanceof String) - { - return str1.compareTo(str2); - } - - try - { - return Long.valueOf(str1).compareTo(Long.valueOf(str2)); - } - catch (Exception ex) - { - return -1; - } - } - - return -1; - } - } -} diff --git a/java/management/eclipse-plugin/src/main/resources/.eclipseproduct b/java/management/eclipse-plugin/src/main/resources/.eclipseproduct deleted file mode 100644 index 28ee27ca17..0000000000 --- a/java/management/eclipse-plugin/src/main/resources/.eclipseproduct +++ /dev/null @@ -1,23 +0,0 @@ -#Eclipse Product File
-#Fri Nov 03 14:47:54 GMT 2006
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-version=1.0-incubating-M2-SNAPSHOT
-name=Qpid Management Console
-id=org.apache.qpid.manager.gui.product
diff --git a/java/management/eclipse-plugin/src/main/resources/eclipse.exe b/java/management/eclipse-plugin/src/main/resources/eclipse.exe Binary files differdeleted file mode 100644 index 7826d1ed80..0000000000 --- a/java/management/eclipse-plugin/src/main/resources/eclipse.exe +++ /dev/null diff --git a/java/management/eclipse-plugin/src/main/resources/eclipse.ini b/java/management/eclipse-plugin/src/main/resources/eclipse.ini deleted file mode 100644 index 6a4ecb5b5d..0000000000 --- a/java/management/eclipse-plugin/src/main/resources/eclipse.ini +++ /dev/null @@ -1,4 +0,0 @@ --vmargs
--Xms40m
--Xmx256m
--Declipse.consoleLog=true
diff --git a/java/management/eclipse-plugin/src/main/resources/license.eclipse.txt b/java/management/eclipse-plugin/src/main/resources/license.eclipse.txt deleted file mode 100644 index da433e89f9..0000000000 --- a/java/management/eclipse-plugin/src/main/resources/license.eclipse.txt +++ /dev/null @@ -1,88 +0,0 @@ -Eclipse Public License - v 1.0 - -THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. - -1. DEFINITIONS - -"Contribution" means: - -a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and -b) in the case of each subsequent Contributor: - -i) changes to the Program, and - -ii) additions to the Program; - -where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program. - -"Contributor" means any person or entity that distributes the Program. - -"Licensed Patents " mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. - -"Program" means the Contributions distributed in accordance with this Agreement. - -"Recipient" means anyone who receives the Program under this Agreement, including all Contributors. - -2. GRANT OF RIGHTS - -a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form. - -b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder. - -c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program. - -d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement. - -3. REQUIREMENTS - -A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that: - -a) it complies with the terms and conditions of this Agreement; and - -b) its license agreement: - -i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose; - -ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits; - -iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and - -iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange. - -When the Program is made available in source code form: - -a) it must be made available under this Agreement; and - -b) a copy of this Agreement must be included with each copy of the Program. - -Contributors may not remove or alter any copyright notices contained within the Program. - -Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution. - -4. COMMERCIAL DISTRIBUTION - -Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense. - -For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages. - -5. NO WARRANTY - -EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. - -6. DISCLAIMER OF LIABILITY - -EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -7. GENERAL - -If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. - -If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed. - -All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive. - -Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. - -This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation. - - diff --git a/java/management/eclipse-plugin/src/main/resources/org.apache.commons.codec/org.apache.commons.codec_1.3.0.jar b/java/management/eclipse-plugin/src/main/resources/org.apache.commons.codec/org.apache.commons.codec_1.3.0.jar Binary files differdeleted file mode 100644 index ae60ce21b7..0000000000 --- a/java/management/eclipse-plugin/src/main/resources/org.apache.commons.codec/org.apache.commons.codec_1.3.0.jar +++ /dev/null diff --git a/java/management/eclipse-plugin/src/main/resources/sasl/MANIFEST.MF b/java/management/eclipse-plugin/src/main/resources/sasl/MANIFEST.MF deleted file mode 100644 index d18b1a073d..0000000000 --- a/java/management/eclipse-plugin/src/main/resources/sasl/MANIFEST.MF +++ /dev/null @@ -1,8 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: jmx sasl Plug-in -Bundle-SymbolicName: jmxremote.sasl -Bundle-Version: 1.0.1 -Bundle-ClassPath: . -Bundle-Vendor: -Bundle-Localization: plugin diff --git a/java/management/eclipse-plugin/src/main/resources/startup.jar b/java/management/eclipse-plugin/src/main/resources/startup.jar Binary files differdeleted file mode 100644 index 2f26eceece..0000000000 --- a/java/management/eclipse-plugin/src/main/resources/startup.jar +++ /dev/null diff --git a/java/management/eclipse-plugin/src/main/resources/unix/configuration/config.ini b/java/management/eclipse-plugin/src/main/resources/unix/configuration/config.ini deleted file mode 100644 index b5186ef073..0000000000 --- a/java/management/eclipse-plugin/src/main/resources/unix/configuration/config.ini +++ /dev/null @@ -1,27 +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.
-###############################################################################
-
-#Product Runtime Configuration File
-
-osgi.splashPath=platform:/base/plugins/org.apache.qpid.management.ui
-eclipse.product=org.apache.qpid.management.ui.product
-eclipse.application=org.apache.qpid.management.ui.application
-osgi.bundles=org.eclipse.equinox.common@2:start,org.eclipse.core.runtime@start,com.ibm.icu,org.apache.qpid.management.ui,org.eclipse.core.commands,org.eclipse.core.contenttype,org.eclipse.core.expressions,org.eclipse.core.jobs,org.eclipse.core.runtime.compatibility.auth,org.eclipse.core.runtime.compatibility.registry,org.eclipse.equinox.preferences,org.eclipse.equinox.registry,org.eclipse.help,org.eclipse.jface,org.eclipse.swt,org.eclipse.swt.motif.linux.x86,org.eclipse.swt.gtk.linux.x86_64,org.eclipse.swt.gtk.linux.x86,org.eclipse.swt.gtk.linux.ppc,org.eclipse.swt.motif.hpux.PA_RISC,org.eclipse.swt.gtk.solaris.sparc,org.eclipse.swt.motif.solaris.sparc,org.eclipse.swt.carbon.macocx,org.eclipse.ui,org.eclipse.ui.forms,org.eclipse.ui.workbench,org.apache.commons.codec
-osgi.bundles.defaultStartLevel=4
-eof=eof
diff --git a/java/management/eclipse-plugin/src/main/resources/win32/configuration/config.ini b/java/management/eclipse-plugin/src/main/resources/win32/configuration/config.ini deleted file mode 100644 index e287f0f4a9..0000000000 --- a/java/management/eclipse-plugin/src/main/resources/win32/configuration/config.ini +++ /dev/null @@ -1,26 +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.
-###############################################################################
-
-#Product Runtime Configuration File
-
-osgi.splashPath=platform:/base/plugins/org.apache.qpid.management.ui
-eclipse.product=org.apache.qpid.management.ui.product
-eclipse.application=org.apache.qpid.management.ui.application
-osgi.bundles=org.eclipse.equinox.common@2:start,org.eclipse.core.runtime@start,com.ibm.icu,org.apache.qpid.management.ui,org.eclipse.core.commands,org.eclipse.core.contenttype,org.eclipse.core.expressions,org.eclipse.core.jobs,org.eclipse.core.runtime.compatibility.auth,org.eclipse.core.runtime.compatibility.registry,org.eclipse.equinox.preferences,org.eclipse.equinox.registry,org.eclipse.help,org.eclipse.jface,org.eclipse.swt,org.eclipse.swt.win32.win32.x86,org.eclipse.ui,org.eclipse.ui.forms,jmxremote.sasl,org.eclipse.ui.workbench,org.apache.commons.codec
-osgi.bundles.defaultStartLevel=4
diff --git a/java/management/eclipse-plugin/src/test/java/org/apache/qpid/management/ui/ManagementConsoleTest.java b/java/management/eclipse-plugin/src/test/java/org/apache/qpid/management/ui/ManagementConsoleTest.java deleted file mode 100644 index 64a5843953..0000000000 --- a/java/management/eclipse-plugin/src/test/java/org/apache/qpid/management/ui/ManagementConsoleTest.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.management.ui; - -import junit.framework.TestCase; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.exchange.DestNameExchange; -import org.apache.qpid.server.management.AMQManagedObject; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.AMQQueueMBean; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.registry.IApplicationRegistry; -import org.apache.qpid.server.virtualhost.VirtualHost; - -import javax.management.MBeanFeatureInfo; -import javax.management.MBeanInfo; -import java.util.ArrayList; -import java.util.List; - - -/** - * Test class to test if any change in the broker JMX code is affesting the management console - * There are some hardcoding of management feature names and parameter names to create a customized - * look in the console. - */ -public class ManagementConsoleTest extends TestCase -{ - private VirtualHost _virtualHost; - - @Override - protected void setUp() throws Exception - { - super.setUp(); - IApplicationRegistry applicationRegistry = ApplicationRegistry.getInstance(); - _virtualHost = applicationRegistry.getVirtualHostRegistry().getVirtualHost("test"); - } - - /** - * Test for AMQQueueMBean attribute and operation names, which are used in the management console - * @throws Exception - */ - public void testAMQQueueMBeanInfo() throws Exception - { - // If this test fails due to changes in the broker code, - // then the constants in the Constants.java shoule be updated accordingly - AMQQueue queue = new AMQQueue(new AMQShortString("testQueueForManagement"), false, null, false, _virtualHost); - AMQManagedObject mbean = new AMQQueueMBean(queue); - MBeanInfo mbeanInfo = mbean.getMBeanInfo(); - - List<String> operationNames = getNamesList(mbeanInfo.getOperations()); - assertTrue(operationNames.contains(Constants.OPERATION_MOVE_MESSAGES)); - - List<String> attributesList = getNamesList(mbeanInfo.getAttributes()); - assertTrue(attributesList.contains(Constants.ATTRIBUTE_QUEUE_CONSUMERCOUNT)); - assertTrue(attributesList.contains(Constants.ATTRIBUTE_QUEUE_DEPTH)); - } - - /** - * Test for Exchange MBean attribute and operation names, which are used in the management console - * @throws Exception - */ - public void testExchangeMBeanInfo() throws Exception - { - // If this test fails due to changes in the broker code, - // then the constants in the Constants.java shoule be updated accordingly - DestNameExchange exchange = new DestNameExchange(); - exchange.initialise(_virtualHost, ExchangeDefaults.DIRECT_EXCHANGE_NAME, false, true); - AMQManagedObject mbean = (AMQManagedObject)exchange.getManagedObject(); - MBeanInfo mbeanInfo = mbean.getMBeanInfo(); - - // Check for the Exchange Type property in the ObjectName - assertNotNull(mbean.getObjectName().getKeyProperty(Constants.EXCHANGE_TYPE)); - - // Check for operation names - List<String> operationNames = getNamesList(mbeanInfo.getOperations()); - assertTrue(operationNames.contains(Constants.OPERATION_CREATE_BINDING)); - } - - /** - * Test for VirtualHostManagerMBean features used in Management console for customizing the GUI - * @throws Exception - */ - public void testVirtualHostManagerMBeanInfo() throws Exception - { - AMQManagedObject mbean = (AMQManagedObject)_virtualHost.getManagedObject(); - assertTrue(mbean.getType().equals(Constants.VIRTUAL_HOST)); - } - - private List<String> getNamesList(MBeanFeatureInfo[] features) - { - List<String> names = new ArrayList<String>(); - for (MBeanFeatureInfo feature : features) - { - names.add(feature.getName()); - } - - return names; - } -} diff --git a/java/perftests/RunningPerformanceTests.txt b/java/perftests/RunningPerformanceTests.txt deleted file mode 100644 index 54291483bf..0000000000 --- a/java/perftests/RunningPerformanceTests.txt +++ /dev/null @@ -1,141 +0,0 @@ -The Performance Tests -------------------------- - -Building the Tests (Only develoeprs need to know how to do this). ------------------------------------------------------------------ - -The performance tests are compiled as part of the Maven build by default, but the performance test scripts are not. There is also an additional step to perform, that generates a convenient Jar file containing all of the test dependencies, to simplify invoking Java with a very long command line. The steps to build the performance test suite are: - - 1. Cd to the /java/perftests directory. - 2. Execute: mvn uk.co.thebadgerset:junit-toolkit-maven-plugin:tkscriptgen (this generates the scripts). - 3. Execute: mvn assembly:assembly - -The assembly:assembly step generates a Jar with all the dependecies in it in a file name ending with -all-test-deps.jar, which contains the client code and all its dependencies, plus JUnit and the toolkit test runners. The generated scripts expect to find the jar in the current directory. You can Cd to the /target directory and run the scripts from there. The assembly:assembly step also outputs some archives that contain all the scripts and required Jar for convenient shipping of the test suite. Unpack this anywhere you like and run the tests from there. - -Running the Tests ------------------ - -All the performance tests are run through shell scripts, that have been configured with parameters set up in the pom.xml file. You can override any of these parameters on the command line. It is also possible to pass parameters through the script to the JVM that is running the test. For example to change the heap size you might do: - -./Ping-Once.sh -java:Xmx1024M - -The tests have all been set up to accept a single integer 'size' parameter, passed to the JUnit TestCase for the test, through the JUnit Toolkit asymptotic test case extension. The 'size' parameter is always interpreted in the performance tests as standing for the number of messages to send per test method invocation. Therefore, in the results of the test the throughput of messages is equal to the number of test method invocations times the 'size' divided by the time taken. - -** TODO: Change this, use seconds not millis. - -Test timing results are output to .csv files, which can easily be imported into a spreadsheet for graphing and analysis. The timings in this file are always given in milliseconds, which may be a bit confusing and should really be changed to seconds. - -The JUnit Toolkit provides a framework for controlling how long tests are run for, how many are run at once and what the 'size' parameter is, which is general enough to handle a wide variety of performance tests. Here is the documentation from the TKTestRunner class that explains what its command line parameters are: - - ... - * TKTestRunner extends {@link junit.textui.TestRunner} with the ability to run tests multiple times, to execute a test - * simultaneously using many threads, to put a delay between test runs and adds support for tests that take integer - * parameters that can be 'stepped' through on multiple test runs. These features can be accessed by using this class - * as an entry point and passing command line arguments to specify which features to use: - * - * <pre> - * -w ms The number of milliseconds between invocations of test cases. - * -c pattern The number of tests to run concurrently. - * -r num The number of times to repeat each test. - * -d duration The length of time to run the tests for. - * -t name The name of the test case to execute. - * -s pattern The size parameter to run tests with. - * -o dir The name of the directory to output test timings to. - * -v Verbose mode. - * </pre> - * - * <p/>The pattern arguments are of the form [lowest(, ...)(, highest)](,sample=s)(,exp), where round brackets - * enclose optional values. Using this pattern form it is possible to specify a single value, a range of values divided - * into s samples, a range of values divided into s samples but distributed exponentially, or a fixed set of samples. - * - * <p/>The duration arguments are of the form dD(:hH)(:mM)(:sS), where round brackets enclose optional values. - * - * <p/>Here are some examples: - * - * <p/><table> - * <tr><td><pre> -c [10,20,30,40,50] </pre><td> Runs the test with 10,20,...,50 threads. - * <tr><td><pre> -s [1,100],samples=10 </pre> - * <td> Runs the test with ten different size parameters evenly spaced between 1 and 100. - * <tr><td><pre> -s [1,1000000],samples=10,exp </pre> - * <td> Runs the test with ten different size parameters exponentially spaced between 1 and 1000000. - * <tr><td><pre> -r 10 </pre><td> Runs each test ten times. - * <tr><td><pre> -d 10H </pre><td> Runs the test repeatedly for 10 hours. - * <tr><td><pre> -d 1M, -r 10 </pre> - * <td> Runs the test repeatedly for 1 minute but only takes a timing sample every 10 test runs. - * <tr><td><pre> -r 10, -c [1, 5, 10, 50], -s [100, 1000, 10000] </pre> - * <td> Runs 12 test cycles (4 concurrency samples * 3 size sample), with 10 repeats each. In total the test - * will be run 199 times (3 + 15 + 30 + 150) - * </table> - ... - -The specific performance test cases for QPid are implemented as extensions to JUnit TestCase (asymptotic test cases), and also accept a large number of different parameters to control the characteristics of the test. The are passed into the test scripts as name=value pairs. Here is the documentation from the PingPongProducer class that explains what the available parameters and default values are: - - ... - * <p/>This ping tool accepts a vast number of configuration options, all of which are passed in to the constructor. It - * can ping topics or queues; ping multiple destinations; do persistent pings; send messages of any size; do pings within - * transactions; control the number of pings to send in each transaction; limit its sending rate; and perform failover - * testing. A complete list of accepted parameters, default values and comments on their usage is provided here: - * - * <p/><table><caption>Parameters</caption> - * <tr><th> Parameter <th> Default <th> Comments - * <tr><td> messageSize <td> 0 <td> Message size in bytes. Not including any headers. - * <tr><td> destinationName <td> ping <td> The root name to use to generate destination names to ping. - * <tr><td> persistent <td> false <td> Determines whether peristent delivery is used. - * <tr><td> transacted <td> false <td> Determines whether messages are sent/received in transactions. - * <tr><td> broker <td> tcp://localhost:5672 <td> Determines the broker to connect to. - * <tr><td> virtualHost <td> test <td> Determines the virtual host to send all ping over. - * <tr><td> rate <td> 0 <td> The maximum rate (in hertz) to send messages at. 0 means no limit. - * <tr><td> verbose <td> false <td> The verbose flag for debugging. Prints to console on every message. - * <tr><td> pubsub <td> false <td> Whether to ping topics or queues. Uses p2p by default. - * <tr><td> failAfterCommit <td> false <td> Whether to prompt user to kill broker after a commit batch. - * <tr><td> failBeforeCommit <td> false <td> Whether to prompt user to kill broker before a commit batch. - * <tr><td> failAfterSend <td> false <td> Whether to prompt user to kill broker after a send. - * <tr><td> failBeforeSend <td> false <td> Whether to prompt user to kill broker before a send. - * <tr><td> failOnce <td> true <td> Whether to prompt for failover only once. - * <tr><td> username <td> guest <td> The username to access the broker with. - * <tr><td> password <td> guest <td> The password to access the broker with. - * <tr><td> selector <td> null <td> Not used. Defines a message selector to filter pings with. - * <tr><td> destinationCount <td> 1 <td> The number of receivers listening to the pings. - * <tr><td> timeout <td> 30000 <td> In milliseconds. The timeout to stop waiting for replies. - * <tr><td> commitBatchSize <td> 1 <td> The number of messages per transaction in transactional mode. - * <tr><td> uniqueDests <td> true <td> Whether each receiver only listens to one ping destination or all. - * <tr><td> durableDests <td> false <td> Whether or not durable destinations are used. - * <tr><td> ackMode <td> AUTO_ACK <td> The message acknowledgement mode. Possible values are: - * 0 - SESSION_TRANSACTED - * 1 - AUTO_ACKNOWLEDGE - * 2 - CLIENT_ACKNOWLEDGE - * 3 - DUPS_OK_ACKNOWLEDGE - * 257 - NO_ACKNOWLEDGE - * 258 - PRE_ACKNOWLEDGE - * <tr><td> maxPending <td> 0 <td> The maximum size in bytes, of messages sent but not yet received. - * Limits the volume of messages currently buffered on the client - * or broker. Can help scale test clients by limiting amount of buffered - * data to avoid out of memory errors. - * </table> - ... - -The most common test case to run is implemented in the class PingAsyncTestPerf, which sends and recieves messages simultaneously. This class uses a PingPongProdicer to do its sending and receiving, and wraps it in a suitable way to make it callable through the extended JUnit test runner. This class also accpets another parameter "batchSize" with a default of "1000". This tells the test how many messages to send before stopping sending and waiting for them all to come back. The actual value entered does not matter too much, but typically values larger than 1000 are used to ensure that there is a reasonable opportunity for simultaneous sending and receiving, and less than 10000 to ensure that each test method invocation does not go on for too long. - -The test script parameters can all be seen in the pom.xml file. A three letter code is used on the test scripts, first letter P or T for persistent or transient, second letter Q or T for queue (p2p) or topic (pub/sub), third letter R for reliability tests, C for client scaling tests, M for message size tests.Typically tests run and sample their results for 10 minutes, to get a reasonable measurement of a broker running under a steady load. The tests as configured do not measure 'burst' performance. - -The reliability/burn in tests, test the broker running at slightly below its maximum throughput for a period of 24 hours. Their purpose is to check that the broker remains stable under load for a reasonable duration, in order to provide some confidence in the long-term stability of its process. These tests are intended to be run as a two step process. The first two tests run for 10 minutes and are used to asses the broker throughput for the test. The output from these tests are to be fed into the rate limiter for the second set of tests, so that the broker may be set up to run at slightly below its maximum throughput for the 24 hour duration. It is suggested that 90% of the rate achieved by the first two tests should be used for this. - -The client scaling tests are split into two sub-sections. The first section tests the performance of increasing numbers of client connections, each sending at a fixed rate. The purpose of this is to determine the brokers saturation load, and to evaluate how its performance degrades uder higher loads. The second section varies the fan-out or fan-in ratio of the number of sending clients to receving clients. This is primarily intended to test the pubsub messaging model, but the tests are also run in p2p mode (with each message being received by one consumer), for completeness and to provide a comparison with the pubsub performance. - -The message size scaling tests, examine the brokers performance with different message payload sizes. The purpose of these tests is to evaluate where the broker process switches from being an io-bound to a cpu-bound process (if at all). The expected model is that the amount of CPU processing the broker has to carry out depends largely on the number of messages, and not on their size, because it carries out de-framing and routing for each message header but just copies payloads in-place or in a tight instruction loop. Therefore large message should be io-bound and a constant data rate through the broker should be seen for messages larger than the io/cpu threshold. Small messages require more processing so a constant message rate should be seen for message smaller than the io/cpu threshold. If the broker implementation is extremely efficient the threshold may dissapear altogether and the broker will be purely io-bound. -The final variation, which is applied to all tests, is to run a transactional and non-transactional version of each. Messages are always batched into transactions of 100 messages each. - -Running the entire test suite can take some time, in particular their are about 4 24 hour burn-in tests. There are also 8 30 minute client scaling ramp up tests. If you want to run the test for a short time, to skim test that they work on your environment a command line like the following is usefull: - -> find . -name '*.sh' -exec {} -d10S \; - -If you want to run just a sub-set of the tests, you can use variations of the above command line. For example, to run just the message size tests using persistent p2p messaging do: - -> find . -name 'PPM-*.sh' -exec {} \; - -and so on. - -Interpreting the Results ------------------------- - -TODO: Explain what the results are expected to show and how to look for it. What should be graphed to get a visualization of the broker performance. How to turn the measurements into a description of the performance 'envelope'.
\ No newline at end of file diff --git a/java/perftests/build.xml b/java/perftests/build.xml deleted file mode 100644 index 670351886d..0000000000 --- a/java/perftests/build.xml +++ /dev/null @@ -1,28 +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. - - - --> -<project name="Performance Tests" default="build"> - - <property name="module.depends" value="systests client broker common"/> - <property name="module.dist" value="false"/> - - <import file="../module.xml"/> - -</project> diff --git a/java/perftests/dist-zip.xml b/java/perftests/dist-zip.xml deleted file mode 100644 index 0039bfb157..0000000000 --- a/java/perftests/dist-zip.xml +++ /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.
--->
-<!-- This is an assembly descriptor that produces a zip containing all the test scripts and
- the all dependencies jar. -->
-<assembly>
- <id>perftests</id>
- <formats>
- <format>zip</format>
- <format>tar.gz</format>
- </formats>
- <includeBaseDirectory>false</includeBaseDirectory>
- <fileSets>
- <fileSet>
- <directory>target</directory>
- <outputDirectory>PerformanceTests</outputDirectory>
- <includes>
- <include>qpid-perftests-${qpid.version}-all-test-deps.jar</include>
- <include>*.sh</include>
- </includes>
- </fileSet>
- <fileSet>
- <directory>etc/scripts</directory>
- <outputDirectory>PerformanceTests</outputDirectory>
- <includes>
- <include>*.sh</include>
- </includes>
- </fileSet>
- </fileSets>
-</assembly>
diff --git a/java/perftests/distribution/pom.xml b/java/perftests/distribution/pom.xml deleted file mode 100644 index 7de50d5a6e..0000000000 --- a/java/perftests/distribution/pom.xml +++ /dev/null @@ -1,133 +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. - --> -<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> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-perftests-distribution</artifactId> - <packaging>jar</packaging> - <version>1.0-incubating-M3-SNAPSHOT</version> - <name>Qpid Performance Tests Distribution</name> - <url>http://cwiki.apache.org/confluence/display/qpid</url> - - <parent> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid</artifactId> - <version>1.0-incubating-M3-SNAPSHOT</version> - </parent> - - <properties> - <topDirectoryLocation>..</topDirectoryLocation> - <java.source.version>1.5</java.source.version> - <qpid.version>${pom.version}</qpid.version> - <qpid.targetDir>${project.build.directory}</qpid.targetDir> - </properties> - - <dependencies> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-perftests</artifactId> - <type>jar</type> - <version>${pom.version}</version> - </dependency> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-perftests</artifactId> - <type>test-jar</type> - <version>${pom.version}</version> - </dependency> - <dependency> - <groupId>uk.co.thebadgerset</groupId> - <artifactId>junit-toolkit</artifactId> - <version>0.6-SNAPSHOT</version> - <scope>runtime</scope> - </dependency> - <dependency> - <groupId>uk.co.thebadgerset</groupId> - <artifactId>junit-toolkit-maven-plugin</artifactId> - <version>0.6-SNAPSHOT</version> - <scope>runtime</scope> - </dependency> - </dependencies> - - <build> - <pluginManagement> - <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-compiler-plugin</artifactId> - <configuration> - <source>${java.source.version}</source> - <target>${java.source.version}</target> - </configuration> - </plugin> - - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-assembly-plugin</artifactId> - <version>${assembly.version}</version> - <configuration> - <descriptors> - <descriptor>src/main/assembly/performance.xml</descriptor> - </descriptors> - <finalName>qpid-${pom.version}</finalName> - <outputDirectory>${qpid.targetDir}</outputDirectory> - <tarLongFileMode>gnu</tarLongFileMode> - </configuration> - </plugin> - - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-jar-plugin</artifactId> - <configuration> - <finalName>qpid-performance</finalName> - <archive> - <manifest> - <addClasspath>true</addClasspath> - </manifest> - </archive> - </configuration> - </plugin> - </plugins> - </pluginManagement> - - <plugins> - <plugin> - <artifactId>maven-assembly-plugin</artifactId> - <executions> - <execution> - <id>distribution-package</id> - <phase>package</phase> - <goals> - <goal>single</goal> - </goals> - <configuration> - <descriptors> - <descriptor>src/main/assembly/performance.xml</descriptor> - </descriptors> - </configuration> - </execution> - </executions> - </plugin> - </plugins> - - </build> - -</project> diff --git a/java/perftests/distribution/src/main/assembly/performance.xml b/java/perftests/distribution/src/main/assembly/performance.xml deleted file mode 100644 index a564261a24..0000000000 --- a/java/perftests/distribution/src/main/assembly/performance.xml +++ /dev/null @@ -1,103 +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. ---> -<assembly> - <id>performance-test-java</id> - <includeBaseDirectory>false</includeBaseDirectory> - <formats> - <format>tar.gz</format> - <format>zip</format> - </formats> - - <fileSets> - <!-- Apache Licensing --> - <fileSet> - <directory>../../resources</directory> - <outputDirectory>qpid-${qpid.version}</outputDirectory> - <includes> - <include>DISCLAIMER</include> - <include>LICENSE.txt</include> - <include>NOTICE.txt</include> - <include>README.txt</include> - </includes> - </fileSet> - - <fileSet> - <directory>../../release-docs</directory> - <outputDirectory>qpid-${qpid.version}/docs</outputDirectory> - <includes> - <include>RELEASE_NOTES.txt</include> - </includes> - </fileSet> - - <!-- Performance txt files--> - <fileSet> - <directory>..</directory> - <outputDirectory>qpid-${qpid.version}</outputDirectory> - <includes> - <include>*.txt</include> - </includes> - </fileSet> - - <!-- Execution Scripts --> - <fileSet> - <directory>../bin</directory> - <outputDirectory>qpid-${qpid.version}/bin</outputDirectory> - <includes> - <include>*</include> - </includes> - <fileMode>777</fileMode> - </fileSet> - - <!-- Provide Source in easy access location --> - <fileSet> - <directory>../src/main</directory> - <outputDirectory>qpid-${qpid.version}/src</outputDirectory> - <includes> - <include>**/*.java</include> - <include>**/*.log4j</include> - </includes> - </fileSet> - <fileSet> - <directory>../src/test</directory> - <outputDirectory>qpid-${qpid.version}/src</outputDirectory> - <includes> - <include>**/*.java</include> - </includes> - </fileSet> - - <!-- Metadata Jar --> - <fileSet> - <directory>target</directory> - <outputDirectory>qpid-${qpid.version}/lib</outputDirectory> - <includes> - <include>qpid-performance.jar</include> - </includes> - </fileSet> - </fileSets> - <dependencySets> - <dependencySet> - <outputDirectory>qpid-${qpid.version}/lib</outputDirectory> - <unpack>false</unpack> - <excludes> - <exclude>org.apache.qpid:qpid-perftests-distribution</exclude> - </excludes> - </dependencySet> - </dependencySets> -</assembly> diff --git a/java/perftests/etc/jndi/activemq.properties b/java/perftests/etc/jndi/activemq.properties deleted file mode 100644 index 0616bee2e0..0000000000 --- a/java/perftests/etc/jndi/activemq.properties +++ /dev/null @@ -1,3 +0,0 @@ -java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory
-java.naming.provider.url= tcp://localhost:61616
-
diff --git a/java/perftests/etc/jndi/perftests.properties b/java/perftests/etc/jndi/perftests.properties deleted file mode 100644 index 6cc16203e9..0000000000 --- a/java/perftests/etc/jndi/perftests.properties +++ /dev/null @@ -1,2 +0,0 @@ -java.naming.factory.initial = org.apache.qpid.jndi.PropertiesFileInitialContextFactory
-connectionfactory.local = amqp://guest:guest@clientid/test?brokerlist='tcp://localhost:5672'
diff --git a/java/perftests/etc/jndi/swiftmq.properties b/java/perftests/etc/jndi/swiftmq.properties deleted file mode 100644 index 5a3b3ea7ec..0000000000 --- a/java/perftests/etc/jndi/swiftmq.properties +++ /dev/null @@ -1,3 +0,0 @@ -java.naming.factory.initial = com.swiftmq.jndi.InitialContextFactoryImpl
-java.naming.provider.url=smqp://localhost:4001/timeout=10000
-#connectionfactory.local = amqp://guest:guest@clientid/test?brokerlist='tcp://localhost:5672'
diff --git a/java/perftests/etc/scripts/CTQ-Qpid-1.sh b/java/perftests/etc/scripts/CTQ-Qpid-1.sh deleted file mode 100755 index 057dec5c63..0000000000 --- a/java/perftests/etc/scripts/CTQ-Qpid-1.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/bash -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - -./PQ-Qpid-1.sh $@ & ./PQ-Qpid-1-P.sh $@ diff --git a/java/perftests/etc/scripts/CTQ-Qpid-2.sh b/java/perftests/etc/scripts/CTQ-Qpid-2.sh deleted file mode 100755 index 08057cbf44..0000000000 --- a/java/perftests/etc/scripts/CTQ-Qpid-2.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/bash -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - -./PQ-Qpid-2.sh $@ & ./PQ-Qpid-2-P.sh $@ diff --git a/java/perftests/etc/scripts/CTQ-Qpid-3.sh b/java/perftests/etc/scripts/CTQ-Qpid-3.sh deleted file mode 100755 index 0bb7e25197..0000000000 --- a/java/perftests/etc/scripts/CTQ-Qpid-3.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/bash -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - -./PQ-Qpid-3.sh $@ & ./PQ-Qpid-3-P.sh $@ diff --git a/java/perftests/etc/scripts/CTQ-Qpid-4.sh b/java/perftests/etc/scripts/CTQ-Qpid-4.sh deleted file mode 100755 index 278e44d12b..0000000000 --- a/java/perftests/etc/scripts/CTQ-Qpid-4.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/bash -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - -./PQ-Qpid-4.sh $@ & ./PQ-Qpid-4-P.sh $@ diff --git a/java/perftests/etc/scripts/CTQ-Qpid-5.sh b/java/perftests/etc/scripts/CTQ-Qpid-5.sh deleted file mode 100755 index 5dee0176b2..0000000000 --- a/java/perftests/etc/scripts/CTQ-Qpid-5.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/bash -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - -./PQ-Qpid-5.sh $@ & ./PQ-Qpid-5-P.sh $@ diff --git a/java/perftests/etc/scripts/CTQ-Qpid-6.sh b/java/perftests/etc/scripts/CTQ-Qpid-6.sh deleted file mode 100755 index b9996da77d..0000000000 --- a/java/perftests/etc/scripts/CTQ-Qpid-6.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/bash -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - -./PQ-Qpid-6.sh $@ & ./PQ-Qpid-6-P.sh $@ diff --git a/java/perftests/etc/scripts/PT-Qpid-13.sh b/java/perftests/etc/scripts/PT-Qpid-13.sh deleted file mode 100755 index c2c6d6fd81..0000000000 --- a/java/perftests/etc/scripts/PT-Qpid-13.sh +++ /dev/null @@ -1,42 +0,0 @@ -#!/bin/bash -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - -# Parse arguements taking all - prefixed args as JAVA_OPTS -for arg in "$@"; do - if [[ $arg == -java:* ]]; then - JAVA_OPTS="${JAVA_OPTS}-`echo $arg|cut -d ':' -f 2` " - else - ARGS="${ARGS}$arg " - fi -done - -echo "Starting 6 parallel tests" -java -Xms256m -Dlog4j.configuration=perftests.log4j -Xmx3072m -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn ${JAVA_OPTS} -cp qpid-perftests-1.0-incubating-M2-SNAPSHOT-all-test-deps.jar uk.co.thebadgerset.junit.extensions.TKTestRunner -n PT-Qpid-13.1 -s [250] -c[200] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true messageSize=256 destinationName=newd1 uniqueDests=true batchSize=250 transacted=true commitBatchSize=50 -o $QPID_WORK/results ${ARGS} & - -java -Xms256m -Dlog4j.configuration=perftests.log4j -Xmx3072m -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn ${JAVA_OPTS} -cp qpid-perftests-1.0-incubating-M2-SNAPSHOT-all-test-deps.jar uk.co.thebadgerset.junit.extensions.TKTestRunner -n PT-Qpid-13.2 -s [250] -c[200] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true messageSize=256 destinationName=newd2 uniqueDests=true batchSize=250 transacted=true commitBatchSize=50 -o $QPID_WORK/results ${ARGS} & - -java -Xms256m -Dlog4j.configuration=perftests.log4j -Xmx3072m -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn ${JAVA_OPTS} -cp qpid-perftests-1.0-incubating-M2-SNAPSHOT-all-test-deps.jar uk.co.thebadgerset.junit.extensions.TKTestRunner -n PT-Qpid-13.3 -s [250] -c[200] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true messageSize=256 destinationName=newd3 uniqueDests=true batchSize=250 transacted=true commitBatchSize=50 -o $QPID_WORK/results ${ARGS} & - -java -Xms256m -Dlog4j.configuration=perftests.log4j -Xmx3072m -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn ${JAVA_OPTS} -cp qpid-perftests-1.0-incubating-M2-SNAPSHOT-all-test-deps.jar uk.co.thebadgerset.junit.extensions.TKTestRunner -n PT-Qpid-13.4 -s [250] -c[200] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true messageSize=256 destinatioNname=newd4 uniqueDests=true batchSize=250 transacted=true commitBatchSize=50 -o $QPID_WORK/results ${ARGS} & - -java -Xms256m -Dlog4j.configuration=perftests.log4j -Xmx3072m -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn ${JAVA_OPTS} -cp qpid-perftests-1.0-incubating-M2-SNAPSHOT-all-test-deps.jar uk.co.thebadgerset.junit.extensions.TKTestRunner -n PT-Qpid-13.5 -s [250] -c[100] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true messageSize=256 destinationName=newd5 uniqueDests=true batchSize=250 transacted=true commitBatchSize=50 -o $QPID_WORK/results ${ARGS} & - -java -Xms256m -Dlog4j.configuration=perftests.log4j -Xmx3072m -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn ${JAVA_OPTS} -cp qpid-perftests-1.0-incubating-M2-SNAPSHOT-all-test-deps.jar uk.co.thebadgerset.junit.extensions.TKTestRunner -n PT-Qpid-13.6 -s [250] -c[100] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true messageSize=256 destinationName=newd6 uniqueDests=true batchSize=250 transacted=true commitBatchSize=50 -o $QPID_WORK/results ${ARGS} - diff --git a/java/perftests/etc/scripts/PT-Qpid-14.sh b/java/perftests/etc/scripts/PT-Qpid-14.sh deleted file mode 100755 index f0adaa1c30..0000000000 --- a/java/perftests/etc/scripts/PT-Qpid-14.sh +++ /dev/null @@ -1,41 +0,0 @@ -#!/bin/bash -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - -# Parse arguements taking all - prefixed args as JAVA_OPTS -for arg in "$@"; do - if [[ $arg == -java:* ]]; then - JAVA_OPTS="${JAVA_OPTS}-`echo $arg|cut -d ':' -f 2` " - else - ARGS="${ARGS}$arg " - fi -done -echo "Starting 6 parallel tests" - -java -Xms256m -Dlog4j.configuration=perftests.log4j -Xmx3072m -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn ${JAVA_OPTS} -cp qpid-perftests-1.0-incubating-M2-SNAPSHOT-all-test-deps.jar uk.co.thebadgerset.junit.extensions.TKTestRunner -n PT-Qpid-14 -s [250] -c[200] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true messageSize=256 destinationName=ping1 batchSize=250 -o $QPID_WORK/results ${ARGS} & - -java -Xms256m -Dlog4j.configuration=perftests.log4j -Xmx3072m -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn ${JAVA_OPTS} -cp qpid-perftests-1.0-incubating-M2-SNAPSHOT-all-test-deps.jar uk.co.thebadgerset.junit.extensions.TKTestRunner -n PT-Qpid-14 -s [250] -c[200] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true messageSize=256 destinationName=ping2 batchSize=250 -o $QPID_WORK/results ${ARGS} & - -java -Xms256m -Dlog4j.configuration=perftests.log4j -Xmx3072m -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn ${JAVA_OPTS} -cp qpid-perftests-1.0-incubating-M2-SNAPSHOT-all-test-deps.jar uk.co.thebadgerset.junit.extensions.TKTestRunner -n PT-Qpid-14 -s [250] -c[200] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true messageSize=256 destinationName=ping3 batchSize=250 -o $QPID_WORK/results ${ARGS} & - -java -Xms256m -Dlog4j.configuration=perftests.log4j -Xmx3072m -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn ${JAVA_OPTS} -cp qpid-perftests-1.0-incubating-M2-SNAPSHOT-all-test-deps.jar uk.co.thebadgerset.junit.extensions.TKTestRunner -n PT-Qpid-14 -s [250] -c[200] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true messageSize=256destinationname=ping4 batchSize=250 -o $QPID_WORK/results ${ARGS} & - -java -Xms256m -Dlog4j.configuration=perftests.log4j -Xmx3072m -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn ${JAVA_OPTS} -cp qpid-perftests-1.0-incubating-M2-SNAPSHOT-all-test-deps.jar uk.co.thebadgerset.junit.extensions.TKTestRunner -n PT-Qpid-14 -s [250] -c[100] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true messageSize=256 destinationName=ping5 batchSize=250 -o $QPID_WORK/results ${ARGS} & - -java -Xms256m -Dlog4j.configuration=perftests.log4j -Xmx3072m -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn ${JAVA_OPTS} -cp qpid-perftests-1.0-incubating-M2-SNAPSHOT-all-test-deps.jar uk.co.thebadgerset.junit.extensions.TKTestRunner -n PT-Qpid-14 -s [250] -c[100] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true messageSize=256 destinationName=ping6 batchSize=250 -o $QPID_WORK/results ${ARGS} diff --git a/java/perftests/etc/scripts/Test-ActiveMQ.sh b/java/perftests/etc/scripts/Test-ActiveMQ.sh deleted file mode 100644 index 099259de3d..0000000000 --- a/java/perftests/etc/scripts/Test-ActiveMQ.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/bash
-
-# Parse arguements taking all - prefixed args as JAVA_OPTS
-for arg in "$@"; do
- if [[ $arg == -java:* ]]; then
- JAVA_OPTS="${JAVA_OPTS}-`echo $arg|cut -d ':' -f 2` "
- else
- ARGS="${ARGS}$arg "
- fi
-done
-
-java -Xms256m -Dlog4j.configuration=perftests.log4j -Xmx1024m -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn ${JAVA_OPTS} -cp "qpid-perftests-1.0-incubating-M2.1-SNAPSHOT.jar;activemq-jars/apache-activemq-4.1.1.jar" uk.co.thebadgerset.junit.extensions.TKTestRunner -n Test-ActiveMQ -s[1] -r 1 -t testAsyncPingOk -o . org.apache.qpid.ping.PingAsyncTestPerf properties=activemq.properties factoryName=ConnectionFactory ${ARGS}
-
-# queueNamePostfix=@router1 overrideClientId=true
\ No newline at end of file diff --git a/java/perftests/etc/scripts/Test-SwiftMQ.sh b/java/perftests/etc/scripts/Test-SwiftMQ.sh deleted file mode 100644 index e9ee85aca7..0000000000 --- a/java/perftests/etc/scripts/Test-SwiftMQ.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/bash
-
-# Parse arguements taking all - prefixed args as JAVA_OPTS
-for arg in "$@"; do
- if [[ $arg == -java:* ]]; then
- JAVA_OPTS="${JAVA_OPTS}-`echo $arg|cut -d ':' -f 2` "
- else
- ARGS="${ARGS}$arg "
- fi
-done
-
-java -Xms256m -Dlog4j.configuration=perftests.log4j -Xmx1024m -Dbadger.level=warn -Damqj.test.logging.level=info -Damqj.logging.level=warn ${JAVA_OPTS} -cp "qpid-perftests-1.0-incubating-M2.1-SNAPSHOT.jar;swiftmqjars/swiftmq.jar" uk.co.thebadgerset.junit.extensions.TKTestRunner -n Test-SwiftMQ -s[1] -r 1 -t testAsyncPingOk -o . org.apache.qpid.ping.PingAsyncTestPerf properties=swiftmq.properties factoryName=ConnectionFactory queueNamePostfix=@router1 overrideClientId=true ${ARGS}
\ No newline at end of file diff --git a/java/perftests/etc/scripts/run_consumer.sh b/java/perftests/etc/scripts/run_consumer.sh deleted file mode 100755 index 26585ff930..0000000000 --- a/java/perftests/etc/scripts/run_consumer.sh +++ /dev/null @@ -1,2 +0,0 @@ -java -Xms256m -Xmx1024m -Ddestinations="test" -Dduration=15M -DlogFrequency=1000 -DlogFilePath="/home/rajith/qpid" -Dmax_prefetch=1000 -Djava.naming.provider.url="/home/rajith/tests.properties" -Djava.naming.factory.initial=org.apache.qpid.jndi.PropertiesFileInitialContextFactory -Djms_timeout=2000 -cp qpid-perftests-1.0-incubating-M2-SNAPSHOT.jar org.apache.qpid.client.perf.MessageConsumerTest - diff --git a/java/perftests/etc/scripts/run_producer.sh b/java/perftests/etc/scripts/run_producer.sh deleted file mode 100755 index f27c1f7469..0000000000 --- a/java/perftests/etc/scripts/run_producer.sh +++ /dev/null @@ -1,2 +0,0 @@ -java -Xms256m -Xmx1024m -Ddestinations="test" -Dduration=15M -DlogFrequency=1000 -DlogFilePath="/home/rajith/qpid" -Dmessage_size_before_sync=25000 -Dmessage_size_before_flush=10000 -Djava.naming.provider.url="/home/rajith/tests.properties" -Djava.naming.factory.initial=org.apache.qpid.jndi.PropertiesFileInitialContextFactory -cp qpid-perftests-1.0-incubating-M2-SNAPSHOT.jar org.apache.qpid.client.perf.MessageProducerTest - diff --git a/java/perftests/etc/scripts/sendAndWaitClient.sh b/java/perftests/etc/scripts/sendAndWaitClient.sh deleted file mode 100755 index af4b788658..0000000000 --- a/java/perftests/etc/scripts/sendAndWaitClient.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/bin/bash -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# -# - -$JAVA_HOME/bin/java -Dlog4j.configuration=backup-log4j.xml -cp qpid-perftests-1.0-incubating-M2-SNAPSHOT-all-test-deps.jar org.apache.qpid.ping.PingSendOnlyClient messageSize=512 diff --git a/java/perftests/jar-with-dependencies.xml b/java/perftests/jar-with-dependencies.xml deleted file mode 100644 index c1e3717ddf..0000000000 --- a/java/perftests/jar-with-dependencies.xml +++ /dev/null @@ -1,91 +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 is an assembly descriptor that produces a distribution that contains all the
- dependencies, with a manifest only jar that references them, required to run the
- tests of a maven project.
--->
-<assembly>
- <id>all-test-deps</id>
- <formats>
- <format>tar.gz</format>
- <format>zip</format>
- </formats>
- <includeBaseDirectory>false</includeBaseDirectory>
- <dependencySets>
- <dependencySet>
- <outputDirectory>/</outputDirectory>
- <unpack>false</unpack>
- <scope>test</scope>
- </dependencySet>
- </dependencySets>
- <fileSets>
- <fileSet>
- <directory>target/classes</directory>
- <outputDirectory></outputDirectory>
- </fileSet>
- <fileSet>
- <directory>target/test-classes</directory>
- <outputDirectory></outputDirectory>
- </fileSet>
-
- <!-- Include all the test scripts, both generated and hand-written. -->
- <fileSet>
- <directory>target</directory>
- <outputDirectory></outputDirectory>
- <includes>
- <include>*.sh</include>
- </includes>
- </fileSet>
- <fileSet>
- <directory>etc/scripts</directory>
- <outputDirectory></outputDirectory>
- <includes>
- <include>*.sh</include>
- </includes>
- </fileSet>
-
- <!-- Include all jndi configurations needed to run the tests. -->
- <fileSet>
- <directory>etc/jndi</directory>
- <outputDirectory></outputDirectory>
- <includes>
- <include>*.properties</include>
- </includes>
- </fileSet>
-
- <!-- Include the build artifact. -->
- <fileSet>
- <directory>target</directory>
- <outputDirectory></outputDirectory>
- <includes>
- <include>qpid-perftests-1.0-incubating-M3-SNAPSHOT.jar</include>
- </includes>
- </fileSet>
-
- <!-- Include the manifest with classpath jar. -->
- <fileSet>
- <directory>target</directory>
- <outputDirectory></outputDirectory>
- <includes>
- <include>qpid-perftests-${qpid.version}.jar</include>
- </includes>
- </fileSet>
-
- </fileSets>
-</assembly>
diff --git a/java/perftests/pom.xml b/java/perftests/pom.xml deleted file mode 100644 index 2e13f1fae6..0000000000 --- a/java/perftests/pom.xml +++ /dev/null @@ -1,714 +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. ---> -<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> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-perftests</artifactId> - <packaging>jar</packaging> - <version>1.0-incubating-M3-SNAPSHOT</version> - <name>Qpid Performance Tests</name> - <url>http://cwiki.apache.org/confluence/display/qpid</url> - - <parent> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid</artifactId> - <version>1.0-incubating-M3-SNAPSHOT</version> - <relativePath>../pom.xml</relativePath> - </parent> - - <properties> - <topDirectoryLocation>..</topDirectoryLocation> - <log4j.perftests>perftests.log4j</log4j.perftests> - </properties> - - <!-- Temporary local maven repo, whilst JUnit Toolkit is still reaching stable version to add to central maven repository. --> - <repositories> - <repository> - <id>junit-toolkit.snapshots</id> - <name>JUnit Toolkit SNAPSHOT Repository</name> - <url>http://junit-toolkit.svn.sourceforge.net/svnroot/junit-toolkit/snapshots/</url> - <snapshots> - <enabled>true</enabled> - </snapshots> - </repository> - </repositories> - - <!-- Temporary local maven repo, whilst JUnit Toolkit is still reaching stable version to add to central maven repository. --> - <pluginRepositories> - <pluginRepository> - <id>junit-toolkit-plugin.snapshots</id> - <name>JUnit Toolkit SNAPSHOT Repository</name> - <url>http://junit-toolkit.svn.sourceforge.net/svnroot/junit-toolkit/snapshots/</url> - <snapshots> - <enabled>true</enabled> - </snapshots> - </pluginRepository> - </pluginRepositories> - - <dependencies> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-client</artifactId> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-systests</artifactId> - </dependency> - - <dependency> - <groupId>log4j</groupId> - <artifactId>log4j</artifactId> - </dependency> - - <dependency> - <groupId>uk.co.thebadgerset</groupId> - <artifactId>junit-toolkit</artifactId> - </dependency> - - <!-- Test dependencies. --> - <dependency> - <groupId>junit</groupId> - <artifactId>junit</artifactId> - <scope>compile</scope> - </dependency> - - <dependency> - <groupId>org.slf4j</groupId> - <artifactId>slf4j-log4j12</artifactId> - <version>1.4.0</version> - </dependency> - - </dependencies> - - <build> - <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-antrun-plugin</artifactId> - </plugin> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-surefire-plugin</artifactId> - </plugin> - - <!-- The JUnit Toolkit maven2 plugin is in the process of being added to the maven repository. - - Configures the toolkit test runner for performance testing. These can be run from within maven, or by using the generated - scripts. - - To run from within maven: - - mvn uk.co.thebadgerset:junit-toolkit-maven-plugin:tktest - - To run from the command line (after doing assembly:assembly goal): - - java -cp target/test_jar-jar-with-dependencies.jar uk.co.thebadgerset.junit.extensions.TKTestRunner -s 1 -r 100000 - -o target org.apache.qpid.requestreply.PingPongTestPerf - - To generate the scripts do: - - mvn uk.co.thebadgerset:junit-toolkit-maven-plugin:tkscriptgen - - Then to run the scripts, in the target directory do (after doing assembly:assembly goal): - - ./script_name.sh - - These scripts can find everything in the 'all test dependencies' jar created by the assembly:assembly goal. - --> - <plugin> - <groupId>uk.co.thebadgerset</groupId> - <artifactId>junit-toolkit-maven-plugin</artifactId> - - <configuration> - <scriptOutDirectory>target</scriptOutDirectory> - <testJar>${project.build.finalName}.jar</testJar> - <systemproperties> - <property> - <name>-Xms</name> - <value>256m</value> - </property> - <property> - <name>-Xmx</name> - <value>1024m</value> - </property> - <property> - <name>log4j.configuration</name> - <value>${log4j.perftests}</value> - </property> - <property> - <name>amqj.logging.level</name> - <value>warn</value> - </property> - <property><!-- Turn off most logging messages from the junit-toolkit test tool itself. --> - <name>badger.level</name> - <value>warn</value> - </property> - <property> - <name>amqj.test.logging.level</name> - <value>info</value> - </property> - </systemproperties> - - <commands> - <!-- Single pings. These can be scaled up by overriding the parameters when calling the test script. --> - <Ping-Once>-n Ping-Once -s[1] -r 1 -t testPingOk -o . org.apache.qpid.ping.PingTestPerf</Ping-Once> - <Ping-Once-Async>-n Ping-Once-Async -s[1] -r 1 -t testAsyncPingOk -o . org.apache.qpid.ping.PingAsyncTestPerf</Ping-Once-Async> - <Ping-Latency>-n Ping-Latency -s[1000] -d10S -t testPingLatency -o . org.apache.qpid.ping.PingLatencyTestPerf rate=100 batchSize=100</Ping-Latency> - - <!-- More example Tests. These are examples to exercise all the features of the test harness. Can scale up with option overrides. --> - <Ping-Tx>-n Ping-Tx -s[100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf transacted=true</Ping-Tx> - <Ping-Size>-n Ping-Size -s[100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf messageSize=512</Ping-Size> - <Ping-Concurrent>-n Ping-Concurrent -s[100] -c [4] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf</Ping-Concurrent> - <Ping-Many-Queues>-n Ping-Many-Queues -s[100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf destinationCount=4</Ping-Many-Queues> - <Ping-Duration>-n Ping-Duration -s[100] -d10S -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf</Ping-Duration> - <Ping-Rate>-n Ping-Rate -s[100] -d10S -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf rate=500</Ping-Rate> - <Ping-PubSub>-n Ping-PubSub -s[100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true</Ping-PubSub> - <Ping-Many-Topics>-n Ping-Many-Topics -s[100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true destinationCount=4</Ping-Many-Topics> - <Ping-Persistent>-n Ping-Persistent -s[100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true</Ping-Persistent> - <Ping-Batch-Logging>-n Ping-Batch-Logging -s[100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf batchSize=10</Ping-Batch-Logging> - <Ping-Failover-Before-Send>-n Ping-Failover-Before-Send -s[100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf commitBatchSize=10 failBeforeSend=true</Ping-Failover-Before-Send> - <Ping-Failover-After-Send>-n Ping-Failover-After-Send -s[100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf commitBatchSize=10 failAfterSend=true</Ping-Failover-After-Send> - <Ping-Failover-Before-Commit>-n Ping-Failover-Before-Commit -s[100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf commitBatchSize=10 failBeforeCommit=true</Ping-Failover-Before-Commit> - <Ping-Failover-After-Commit>-n Ping-Failover-After-Commit -s[100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf commitBatchSize=10 failAfterCommit=true</Ping-Failover-After-Commit> - - <!-- - ***** If editing below, please use a non line wrapping mode and keep in columns, makes it easier to check for consistent - ***** parameter setting accross all of the tests. - --> - - <!-- - Reliability tests. The longer these tests can be run, the better. - Tests 01 and 02 run for a short time. Use these to get an idea of the expected throughput. - Tests 03 to 08 test all ack modes, transient/persistent, p2p/pubsub. There are 24 tests in total running for 1 hour each. - This can be shortened or lengthened for the desired burn-in test time. - --> - <TQR-Qpid-01>-n TQR-Qpid-01 -d1M -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </TQR-Qpid-01> - <TQR-Qpid-02>-n TQR-Qpid-02 -d1M -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </TQR-Qpid-02> - <TTR-Qpid-01>-n TTR-Qpid-01 -d1M -s[100] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=8 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </TTR-Qpid-01> - <TTR-Qpid-02>-n TTR-Qpid-02 -d1M -s[100] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </TTR-Qpid-02> - <PQR-Qpid-01>-n PQR-Qpid-01 -d1M -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </PQR-Qpid-01> - <PQR-Qpid-02>-n PQR-Qpid-02 -d1M -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </PQR-Qpid-02> - <PTR-Qpid-01>-n PTR-Qpid-01 -d1M -s[100] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=8 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </PTR-Qpid-01> - <PTR-Qpid-02>-n PTR-Qpid-02 -d1M -s[100] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </PTR-Qpid-02> - - <TQR-Qpid-03-TX>-n TQR-Qpid-03 -d1H -s[10000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </TQR-Qpid-03-TX> - <TQR-Qpid-04-AUTOACK>-n TQR-Qpid-04 -d1H -s[10000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </TQR-Qpid-04-AUTOACK> - <TQR-Qpid-05-CLIENTACK>-n TQR-Qpid-05 -d1H -s[10000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=2 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </TQR-Qpid-05-CLIENTACK> - <TQR-Qpid-06-DUPSOKACK>-n TQR-Qpid-06 -d1H -s[10000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=3 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </TQR-Qpid-06-DUPSOKACK> - <TQR-Qpid-07-NOACK>-n TQR-Qpid-07 -d1H -s[10000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=257 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </TQR-Qpid-07-NOACK> - <TQR-Qpid-08-PREACK>-n TQR-Qpid-08 -d1H -s[10000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=258 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </TQR-Qpid-08-PREACK> - - <TTR-Qpid-03-TX>-n TTR-Qpid-03 -d1H -s[1000] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=8 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </TTR-Qpid-03-TX> - <TTR-Qpid-04-AUTOACK>-n TTR-Qpid-04 -d1H -s[1000] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </TTR-Qpid-04-AUTOACK> - <TTR-Qpid-05-CLIENTACK>-n TTR-Qpid-05 -d1H -s[1000] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=2 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </TTR-Qpid-05-CLIENTACK> - <TTR-Qpid-06-DUPSOKACK>-n TTR-Qpid-06 -d1H -s[1000] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=3 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </TTR-Qpid-06-DUPSOKACK> - <TTR-Qpid-07-NOACK>-n TTR-Qpid-07 -d1H -s[1000] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=257 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </TTR-Qpid-07-NOACK> - <TTR-Qpid-08-PREACK>-n TTR-Qpid-08 -d1H -s[1000] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=258 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </TTR-Qpid-08-PREACK> - - <PQR-Qpid-03-TX>-n PQR-Qpid-03 -d1H -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </PQR-Qpid-03-TX> - <PQR-Qpid-04-AUTOACK>-n PQR-Qpid-04 -d1H -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </PQR-Qpid-04-AUTOACK> - <PQR-Qpid-05-CLIENTACK>-n PQR-Qpid-05 -d1H -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=2 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </PQR-Qpid-05-CLIENTACK> - <PQR-Qpid-06-DUPSOKACK>-n PQR-Qpid-06 -d1H -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=3 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </PQR-Qpid-06-DUPSOKACK> - <PQR-Qpid-07-NOACK>-n PQR-Qpid-07 -d1H -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=257 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </PQR-Qpid-07-NOACK> - <PQR-Qpid-08-PREACK>-n PQR-Qpid-08 -d1H -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=258 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </PQR-Qpid-08-PREACK> - - <PTR-Qpid-03-TX>-n PTR-Qpid-03 -d1H -s[100] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=8 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </PTR-Qpid-03-TX> - <PTR-Qpid-04-AUTOACK>-n PTR-Qpid-04 -d1H -s[100] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </PTR-Qpid-04-AUTOACK> - <PTR-Qpid-05-CLIENTACK>-n PTR-Qpid-05 -d1H -s[100] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=2 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </PTR-Qpid-05-CLIENTACK> - <PTR-Qpid-06-DUPSOKACK>-n PTR-Qpid-06 -d1H -s[100] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=3 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </PTR-Qpid-06-DUPSOKACK> - <PTR-Qpid-07-NOACK>-n PTR-Qpid-07 -d1H -s[100] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=257 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </PTR-Qpid-07-NOACK> - <PTR-Qpid-08-PREACK>-n PTR-Qpid-08 -d1H -s[100] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=258 commitBatchSize=10 batchSize=100000 messageSize=256 destinationCount=1 rate=0 maxPending=500000 </PTR-Qpid-08-PREACK> - - <!-- Performance Tests. --> - - <!-- Transient, P2P Tests --> - <TQCT-Qpid-01>-n TQCT-Qpid-01 -d1M -s[1000] -c[1,30],samples=30 -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=2000 maxPending=2000000 </TQCT-Qpid-01> - <TQCT-Qpid-02>-n TQCT-Qpid-02 -d1M -s[1000] -c[1,30],samples=30 -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=2000 maxPending=2000000 </TQCT-Qpid-02> - <TQCL-Qpid-01>-n TQCL-Qpid-01 -d1M -s[1000] -c[1,30],samples=30 -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=2000 maxPending=2000000 </TQCL-Qpid-01> - <TQCL-Qpid-02>-n TQCL-Qpid-02 -d1M -s[1000] -c[1,30],samples=30 -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=2000 maxPending=2000000 </TQCL-Qpid-02> - - <!-- <TQC-Qpid-05>-n TQC-Qpid-05 -d10M -s[10] -c[100] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=10 rate=0 maxPending=100000 </TQC-Qpid-05> --> - <!-- <TQC-Qpid-06>-n TQC-Qpid-06 -d10M -s[10] -c[100] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=10 rate=0 maxPending=100000 </TQC-Qpid-06> --> - - <TQM-Qpid-01-512b>-n TQM-Qpid-01-512b -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </TQM-Qpid-01-512b> - <TQM-Qpid-02-512b>-n TQM-Qpid-02-512b -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </TQM-Qpid-02-512b> - <TQM-Qpid-01-1K>-n TQM-Qpid-01-1K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=1024 destinationCount=1 rate=0 maxPending=2000000 </TQM-Qpid-01-1K> - <TQM-Qpid-02-1K>-n TQM-Qpid-02-1K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=1024 destinationCount=1 rate=0 maxPending=2000000 </TQM-Qpid-02-1K> - <TQM-Qpid-01-5K>-n TQM-Qpid-01-5K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=5120 destinationCount=1 rate=0 maxPending=2000000 </TQM-Qpid-01-5K> - <TQM-Qpid-02-5K>-n TQM-Qpid-02-5K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=5120 destinationCount=1 rate=0 maxPending=2000000 </TQM-Qpid-02-5K> - <TQM-Qpid-01-10K>-n TQM-Qpid-01-10K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=10240 destinationCount=1 rate=0 maxPending=2000000 </TQM-Qpid-01-10K> - <TQM-Qpid-02-10K>-n TQM-Qpid-02-10K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=10240 destinationCount=1 rate=0 maxPending=2000000 </TQM-Qpid-02-10K> - <TQM-Qpid-01-50K>-n TQM-Qpid-01-50K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=51200 destinationCount=1 rate=0 maxPending=100000000</TQM-Qpid-01-50K> - <TQM-Qpid-02-50K>-n TQM-Qpid-02-50K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=51200 destinationCount=1 rate=0 maxPending=100000000</TQM-Qpid-02-50K> - <TQM-Qpid-01-100K>-n TQM-Qpid-01-100K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=102400 destinationCount=1 rate=0 maxPending=100000000</TQM-Qpid-01-100K> - <TQM-Qpid-02-100K>-n TQM-Qpid-02-100K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=102400 destinationCount=1 rate=0 maxPending=100000000</TQM-Qpid-02-100K> - <TQM-Qpid-01-500K>-n TQM-Qpid-01-500K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=512000 destinationCount=1 rate=0 maxPending=100000000</TQM-Qpid-01-500K> - <TQM-Qpid-02-500K>-n TQM-Qpid-02-500K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=512000 destinationCount=1 rate=0 maxPending=100000000</TQM-Qpid-02-500K> - <TQM-Qpid-01-1M>-n TQM-Qpid-01-1M -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=1048576 destinationCount=1 rate=0 maxPending=100000000</TQM-Qpid-01-1M> - <TQM-Qpid-02-1M>-n TQM-Qpid-02-1M -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=1048576 destinationCount=1 rate=0 maxPending=100000000</TQM-Qpid-02-1M> - - <!-- Transient, Pub/Sub Tests --> - <TTCT-Qpid-01>-n TTCT-Qpid-01 -d1M -s[10] -c[1,30],samples=30 -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=40 maxPending=2000000 </TTCT-Qpid-01> - <TTCT-Qpid-02>-n TTCT-Qpid-02 -d1M -s[10] -c[1,30],samples=30 -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=40 maxPending=2000000 </TTCT-Qpid-02> - <TTCL-Qpid-01>-n TTCL-Qpid-01 -d1M -s[10] -c[1,30],samples=30 -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=40 maxPending=2000000 </TTCL-Qpid-01> - <TTCL-Qpid-02>-n TTCL-Qpid-02 -d1M -s[10] -c[1,30],samples=30 -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=40 maxPending=2000000 </TTCL-Qpid-02> - - <!-- <TTC-Qpid-05>-n TTC-Qpid-05 -d10M -s[10] -c[100] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=10 rate=0 maxPending=100000 </TTC-Qpid-05> --> - <!-- <TTC-Qpid-06>-n TTC-Qpid-06 -d10M -s[10] -c[100] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=10 rate=0 maxPending=100000 </TTC-Qpid-06> --> - - <TTM-Qpid-01-512b>-n TTM-Qpid-01-512b -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </TTM-Qpid-01-512b> - <TTM-Qpid-02-512b>-n TTM-Qpid-02-512b -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </TTM-Qpid-02-512b> - <TTM-Qpid-01-1K>-n TTM-Qpid-01-1K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=1024 destinationCount=1 rate=0 maxPending=2000000 </TTM-Qpid-01-1K> - <TTM-Qpid-02-1K>-n TTM-Qpid-02-1K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=1024 destinationCount=1 rate=0 maxPending=2000000 </TTM-Qpid-02-1K> - <TTM-Qpid-01-5K>-n TTM-Qpid-01-5K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=5120 destinationCount=1 rate=0 maxPending=2000000 </TTM-Qpid-01-5K> - <TTM-Qpid-02-5K>-n TTM-Qpid-02-5K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=5120 destinationCount=1 rate=0 maxPending=2000000 </TTM-Qpid-02-5K> - <TTM-Qpid-01-10K>-n TTM-Qpid-01-10K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=10240 destinationCount=1 rate=0 maxPending=2000000 </TTM-Qpid-01-10K> - <TTM-Qpid-02-10K>-n TTM-Qpid-02-10K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=10240 destinationCount=1 rate=0 maxPending=2000000 </TTM-Qpid-02-10K> - <TTM-Qpid-01-50K>-n TTM-Qpid-01-50K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=51200 destinationCount=1 rate=0 maxPending=20000000</TTM-Qpid-01-50K> - <TTM-Qpid-02-50K>-n TTM-Qpid-02-50K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=51200 destinationCount=1 rate=0 maxPending=20000000</TTM-Qpid-02-50K> - <TTM-Qpid-01-100K>-n TTM-Qpid-01-100K -d10M -s[40] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=102400 destinationCount=1 rate=0 maxPending=20000000</TTM-Qpid-01-100K> - <TTM-Qpid-02-100K>-n TTM-Qpid-02-100K -d10M -s[40] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=102400 destinationCount=1 rate=0 maxPending=20000000</TTM-Qpid-02-100K> - <TTM-Qpid-01-500K>-n TTM-Qpid-01-500K -d10M -s[8] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=512000 destinationCount=1 rate=0 maxPending=20000000</TTM-Qpid-01-500K> - <TTM-Qpid-02-500K>-n TTM-Qpid-02-500K -d10M -s[8] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=512000 destinationCount=1 rate=0 maxPending=20000000</TTM-Qpid-02-500K> - <TTM-Qpid-01-1M>-n TTM-Qpid-01-1M -d10M -s[4] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=1048576 destinationCount=1 rate=0 maxPending=20000000</TTM-Qpid-01-1M> - <TTM-Qpid-02-1M>-n TTM-Qpid-02-1M -d10M -s[4] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=1048476 destinationCount=1 rate=0 maxPending=20000000</TTM-Qpid-02-1M> - - <!-- Persistent, P2P Tests --> - <PQCT-Qpid-01>-n PQCT-Qpid-01 -d1M -s[1000] -c[1,30],samples=30 -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=600 maxPending=2000000 </PQCT-Qpid-01> - <PQCT-Qpid-02>-n PQCT-Qpid-02 -d1M -s[1000] -c[1,30],samples=30 -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=100 maxPending=2000000 </PQCT-Qpid-02> - <PQCL-Qpid-01>-n PQCL-Qpid-01 -d1M -s[1000] -c[1,30],samples=30 -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=600 maxPending=2000000 </PQCL-Qpid-01> - <PQCL-Qpid-02>-n PQCL-Qpid-02 -d1M -s[1000] -c[1,30],samples=30 -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=100 maxPending=2000000 </PQCL-Qpid-02> - - <!-- <PQC-Qpid-05>-n PQC-Qpid-05 -d10M -s[10] -c[100] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=10 rate=0 maxPending=100000 </PQC-Qpid-05> --> - <!-- <PQC-Qpid-06>-n PQC-Qpid-06 -d10M -s[10] -c[100] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=10 rate=0 maxPending=100000 </PQC-Qpid-06> --> - - <PQM-Qpid-01-512b>-n PQM-Qpid-01-512b -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </PQM-Qpid-01-512b> - <PQM-Qpid-02-512b>-n PQM-Qpid-02-512b -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </PQM-Qpid-02-512b> - <PQM-Qpid-01-1K>-n PQM-Qpid-01-1K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=1024 destinationCount=1 rate=0 maxPending=2000000 </PQM-Qpid-01-1K> - <PQM-Qpid-02-1K>-n PQM-Qpid-02-1K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=1024 destinationCount=1 rate=0 maxPending=2000000 </PQM-Qpid-02-1K> - <PQM-Qpid-01-5K>-n PQM-Qpid-01-5K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=5120 destinationCount=1 rate=0 maxPending=2000000 </PQM-Qpid-01-5K> - <PQM-Qpid-02-5K>-n PQM-Qpid-02-5K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=5120 destinationCount=1 rate=0 maxPending=2000000 </PQM-Qpid-02-5K> - <PQM-Qpid-01-10K>-n PQM-Qpid-01-10K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=10240 destinationCount=1 rate=0 maxPending=2000000 </PQM-Qpid-01-10K> - <PQM-Qpid-02-10K>-n PQM-Qpid-02-10K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=10240 destinationCount=1 rate=0 maxPending=2000000 </PQM-Qpid-02-10K> - <PQM-Qpid-01-50K>-n PQM-Qpid-01-50K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=51200 destinationCount=1 rate=0 maxPending=20000000</PQM-Qpid-01-50K> - <PQM-Qpid-02-50K>-n PQM-Qpid-02-50K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=51200 destinationCount=1 rate=0 maxPending=20000000</PQM-Qpid-02-50K> - <PQM-Qpid-01-100K>-n PQM-Qpid-01-100K -d10M -s[40] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=102400 destinationCount=1 rate=0 maxPending=20000000</PQM-Qpid-01-100K> - <PQM-Qpid-02-100K>-n PQM-Qpid-02-100K -d10M -s[40] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=102400 destinationCount=1 rate=0 maxPending=20000000</PQM-Qpid-02-100K> - <PQM-Qpid-01-500K>-n PQM-Qpid-01-500K -d10M -s[8] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=512000 destinationCount=1 rate=0 maxPending=20000000</PQM-Qpid-01-500K> - <PQM-Qpid-02-500K>-n PQM-Qpid-02-500K -d10M -s[8] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=512000 destinationCount=1 rate=0 maxPending=20000000</PQM-Qpid-02-500K> - <PQM-Qpid-01-1M>-n PQM-Qpid-01-1M -d10M -s[4] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=1048576 destinationCount=1 rate=0 maxPending=20000000</PQM-Qpid-01-1M> - <PQM-Qpid-02-1M>-n PQM-Qpid-02-1M -d10M -s[4] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=1048576 destinationCount=1 rate=0 maxPending=20000000</PQM-Qpid-02-1M> - - <!-- Persistent, Pub/Sub Tests --> - <PTCT-Qpid-01>-n PTCT-Qpid-01 -d1M -s[1] -c[1,30],samples=30 -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=1 maxPending=2000000 </PTCT-Qpid-01> - <PTCT-Qpid-02>-n PTCT-Qpid-02 -d1M -s[1] -c[1,30],samples=30 -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=1 maxPending=2000000 </PTCT-Qpid-02> - <PTCL-Qpid-01>-n PTCL-Qpid-01 -d1M -s[1] -c[1,30],samples=30 -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=1 maxPending=2000000 </PTCL-Qpid-01> - <PTCL-Qpid-02>-n PTCL-Qpid-02 -d1M -s[1] -c[1,30],samples=30 -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=1 rate=1 maxPending=2000000 </PTCL-Qpid-02> - - <!-- <PTC-Qpid-05>-n PTC-Qpid-05 -d10M -s[10] -c[100] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=10 rate=0 maxPending=100000 </PTC-Qpid-05> --> - <!-- <PTC-Qpid-06>-n PTC-Qpid-06 -d10M -s[10] -c[100] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=256 destinationCount=10 rate=0 maxPending=100000 </PTC-Qpid-06> --> - - <PTM-Qpid-01-512b>-n PTM-Qpid-01-512b -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </PTM-Qpid-01-512b> - <PTM-Qpid-02-512b>-n PTM-Qpid-02-512b -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </PTM-Qpid-02-512b> - <PTM-Qpid-01-1K>-n PTM-Qpid-01-1K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=1024 destinationCount=1 rate=0 maxPending=2000000 </PTM-Qpid-01-1K> - <PTM-Qpid-02-1K>-n PTM-Qpid-02-1K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=1024 destinationCount=1 rate=0 maxPending=2000000 </PTM-Qpid-02-1K> - <PTM-Qpid-01-5K>-n PTM-Qpid-01-5K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=5120 destinationCount=1 rate=0 maxPending=2000000 </PTM-Qpid-01-5K> - <PTM-Qpid-02-5K>-n PTM-Qpid-02-5K -d10M -s[1000] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=5120 destinationCount=1 rate=0 maxPending=2000000 </PTM-Qpid-02-5K> - <PTM-Qpid-01-10K>-n PTM-Qpid-01-10K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=10240 destinationCount=1 rate=0 maxPending=2000000 </PTM-Qpid-01-10K> - <PTM-Qpid-02-10K>-n PTM-Qpid-02-10K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=10240 destinationCount=1 rate=0 maxPending=2000000 </PTM-Qpid-02-10K> - <PTM-Qpid-01-50K>-n PTM-Qpid-01-50K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=51200 destinationCount=1 rate=0 maxPending=20000000</PTM-Qpid-01-50K> - <PTM-Qpid-02-50K>-n PTM-Qpid-02-50K -d10M -s[100] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=51200 destinationCount=1 rate=0 maxPending=20000000</PTM-Qpid-02-50K> - <PTM-Qpid-01-100K>-n PTM-Qpid-01-100K -d10M -s[40] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=102400 destinationCount=1 rate=0 maxPending=20000000</PTM-Qpid-01-100K> - <PTM-Qpid-02-100K>-n PTM-Qpid-02-100K -d10M -s[40] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=102400 destinationCount=1 rate=0 maxPending=20000000</PTM-Qpid-02-100K> - <PTM-Qpid-01-500K>-n PTM-Qpid-01-500K -d10M -s[8] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=512000 destinationCount=1 rate=0 maxPending=20000000</PTM-Qpid-01-500K> - <PTM-Qpid-02-500K>-n PTM-Qpid-02-500K -d10M -s[8] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=512000 destinationCount=1 rate=0 maxPending=20000000</PTM-Qpid-02-500K> - <PTM-Qpid-01-1M>-n PTM-Qpid-01-1M -d10M -s[4] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=10 batchSize=1000 messageSize=1048576 destinationCount=1 rate=0 maxPending=20000000</PTM-Qpid-01-1M> - <PTM-Qpid-02-1M>-n PTM-Qpid-02-1M -d10M -s[4] -c[8] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=10 batchSize=1000 messageSize=1048476 destinationCount=1 rate=0 maxPending=20000000</PTM-Qpid-02-1M> - - <!-- Benchmarking tests. --> - <!-- Throughput. --> - <TQBT-TX-Qpid-01>-n TQBT-TX-Qpid-01 -d10M -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TQBT-TX-Qpid-01> - <TQBT-AA-Qpid-01>-n TQBT-AA-Qpid-01 -d10M -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TQBT-AA-Qpid-01> - <TQBT-NA-Qpid-01>-n TQBT-NA-Qpid-01 -d10M -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TQBT-NA-Qpid-01> - <TTBT-TX-Qpid-01>-n TTBT-TX-Qpid-01 -d10M -s[1000] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=8 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TTBT-TX-Qpid-01> - <TTBT-AA-Qpid-01>-n TTBT-AA-Qpid-01 -d10M -s[1000] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TTBT-AA-Qpid-01> - <TTBT-NA-Qpid-01>-n TTBT-NA-Qpid-01 -d10M -s[1000] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TTBT-NA-Qpid-01> - - <PQBT-TX-Qpid-01>-n PQBT-TX-Qpid-01 -d10M -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=true consAckMode=0 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </PQBT-TX-Qpid-01> - <PQBT-AA-Qpid-01>-n PQBT-AA-Qpid-01 -d10M -s[1000] -c[16] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </PQBT-AA-Qpid-01> - <PTBT-TX-Qpid-01>-n PTBT-TX-Qpid-01 -d10M -s[1000] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=8 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </PTBT-TX-Qpid-01> - <PTBT-AA-Qpid-01>-n PTBT-AA-Qpid-01 -d10M -s[1000] -c[2] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=8 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </PTBT-AA-Qpid-01> - - <!-- Job Queueing. 1:10 --> - <TQBL-AA-Qpid-02-01>-n TQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=1000 maxPending=2000000 </TQBL-AA-Qpid-02-01> - <TQBL-AA-Qpid-02-02>-n TQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=2000 maxPending=2000000 </TQBL-AA-Qpid-02-02> - <TQBL-AA-Qpid-02-03>-n TQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=3000 maxPending=2000000 </TQBL-AA-Qpid-02-03> - <TQBL-AA-Qpid-02-04>-n TQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=4000 maxPending=2000000 </TQBL-AA-Qpid-02-04> - <TQBL-AA-Qpid-02-05>-n TQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=5000 maxPending=2000000 </TQBL-AA-Qpid-02-05> - <TQBL-AA-Qpid-02-06>-n TQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=6000 maxPending=2000000 </TQBL-AA-Qpid-02-06> - <TQBL-AA-Qpid-02-07>-n TQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=7000 maxPending=2000000 </TQBL-AA-Qpid-02-07> - <TQBL-AA-Qpid-02-08>-n TQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=8000 maxPending=2000000 </TQBL-AA-Qpid-02-08> - <TQBL-AA-Qpid-02-09>-n TQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=9000 maxPending=2000000 </TQBL-AA-Qpid-02-09> - <TQBL-AA-Qpid-02-10>-n TQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=10000 maxPending=2000000 </TQBL-AA-Qpid-02-10> - - <PQBL-AA-Qpid-02-01>-n PQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=100 maxPending=2000000 </PQBL-AA-Qpid-02-01> - <PQBL-AA-Qpid-02-02>-n PQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=200 maxPending=2000000 </PQBL-AA-Qpid-02-02> - <PQBL-AA-Qpid-02-03>-n PQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=300 maxPending=2000000 </PQBL-AA-Qpid-02-03> - <PQBL-AA-Qpid-02-04>-n PQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=400 maxPending=2000000 </PQBL-AA-Qpid-02-04> - <PQBL-AA-Qpid-02-05>-n PQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=500 maxPending=2000000 </PQBL-AA-Qpid-02-05> - <PQBL-AA-Qpid-02-06>-n PQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=600 maxPending=2000000 </PQBL-AA-Qpid-02-06> - <PQBL-AA-Qpid-02-07>-n PQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=700 maxPending=2000000 </PQBL-AA-Qpid-02-07> - <PQBL-AA-Qpid-02-08>-n PQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=800 maxPending=2000000 </PQBL-AA-Qpid-02-08> - <PQBL-AA-Qpid-02-09>-n PQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=900 maxPending=2000000 </PQBL-AA-Qpid-02-09> - <PQBL-AA-Qpid-02-10>-n PQBL-AA-Qpid-02 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=10 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=5120 destinationCount=1 rate=1000 maxPending=2000000 </PQBL-AA-Qpid-02-10> - - <!-- Broadcast of small sized time critical messages. Lowish rates. Transient/Persistent. 1:100, auto ack. --> - <TTBL-AA-Qpid-03-01>-n TTBL-AA-Qpid-03 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=200 maxPending=2000000 </TTBL-AA-Qpid-03-01> - <TTBL-AA-Qpid-03-02>-n TTBL-AA-Qpid-03 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=400 maxPending=2000000 </TTBL-AA-Qpid-03-02> - <TTBL-AA-Qpid-03-03>-n TTBL-AA-Qpid-03 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=600 maxPending=2000000 </TTBL-AA-Qpid-03-03> - <TTBL-AA-Qpid-03-04>-n TTBL-AA-Qpid-03 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=800 maxPending=2000000 </TTBL-AA-Qpid-03-04> - <TTBL-AA-Qpid-03-05>-n TTBL-AA-Qpid-03 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=1000 maxPending=2000000 </TTBL-AA-Qpid-03-05> - <TTBL-AA-Qpid-03-06>-n TTBL-AA-Qpid-03 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=1200 maxPending=2000000 </TTBL-AA-Qpid-03-06> - <TTBL-AA-Qpid-03-07>-n TTBL-AA-Qpid-03 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=1400 maxPending=2000000 </TTBL-AA-Qpid-03-07> - <TTBL-AA-Qpid-03-08>-n TTBL-AA-Qpid-03 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=1600 maxPending=2000000 </TTBL-AA-Qpid-03-08> - <TTBL-AA-Qpid-03-09>-n TTBL-AA-Qpid-03 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=1800 maxPending=2000000 </TTBL-AA-Qpid-03-09> - <TTBL-AA-Qpid-03-10>-n TTBL-AA-Qpid-03 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=2000 maxPending=2000000 </TTBL-AA-Qpid-03-10> - - <PTBL-AA-Qpid-03-01>-n PTBL-AA-Qpid-03 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=256 destinationCount=1 rate=10 maxPending=2000000 </PTBL-AA-Qpid-03-01> - <PTBL-AA-Qpid-03-02>-n PTBL-AA-Qpid-03 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=256 destinationCount=1 rate=20 maxPending=2000000 </PTBL-AA-Qpid-03-02> - <PTBL-AA-Qpid-03-03>-n PTBL-AA-Qpid-03 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=256 destinationCount=1 rate=30 maxPending=2000000 </PTBL-AA-Qpid-03-03> - <PTBL-AA-Qpid-03-04>-n PTBL-AA-Qpid-03 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=256 destinationCount=1 rate=40 maxPending=2000000 </PTBL-AA-Qpid-03-04> - <PTBL-AA-Qpid-03-05>-n PTBL-AA-Qpid-03 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=256 destinationCount=1 rate=50 maxPending=2000000 </PTBL-AA-Qpid-03-05> - <PTBL-AA-Qpid-03-06>-n PTBL-AA-Qpid-03 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=256 destinationCount=1 rate=60 maxPending=2000000 </PTBL-AA-Qpid-03-06> - <PTBL-AA-Qpid-03-07>-n PTBL-AA-Qpid-03 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=256 destinationCount=1 rate=70 maxPending=2000000 </PTBL-AA-Qpid-03-07> - <PTBL-AA-Qpid-03-08>-n PTBL-AA-Qpid-03 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=256 destinationCount=1 rate=80 maxPending=2000000 </PTBL-AA-Qpid-03-08> - <PTBL-AA-Qpid-03-09>-n PTBL-AA-Qpid-03 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=256 destinationCount=1 rate=90 maxPending=2000000 </PTBL-AA-Qpid-03-09> - <PTBL-AA-Qpid-03-10>-n PTBL-AA-Qpid-03 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=256 destinationCount=1 rate=100 maxPending=2000000 </PTBL-AA-Qpid-03-10> - - <!-- Broadcast of medium sized time critical messages. Lowish rates. Transient/Persistent. 1:100, auto ack. --> - <TTBL-AA-Qpid-04-01>-n TTBL-AA-Qpid-04 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=100 maxPending=2000000 </TTBL-AA-Qpid-04-01> - <TTBL-AA-Qpid-04-02>-n TTBL-AA-Qpid-04 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=200 maxPending=2000000 </TTBL-AA-Qpid-04-02> - <TTBL-AA-Qpid-04-03>-n TTBL-AA-Qpid-04 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=300 maxPending=2000000 </TTBL-AA-Qpid-04-03> - <TTBL-AA-Qpid-04-04>-n TTBL-AA-Qpid-04 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=400 maxPending=2000000 </TTBL-AA-Qpid-04-04> - <TTBL-AA-Qpid-04-05>-n TTBL-AA-Qpid-04 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=500 maxPending=2000000 </TTBL-AA-Qpid-04-05> - <TTBL-AA-Qpid-04-06>-n TTBL-AA-Qpid-04 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=600 maxPending=2000000 </TTBL-AA-Qpid-04-06> - <TTBL-AA-Qpid-04-07>-n TTBL-AA-Qpid-04 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=700 maxPending=2000000 </TTBL-AA-Qpid-04-07> - <TTBL-AA-Qpid-04-08>-n TTBL-AA-Qpid-04 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=800 maxPending=2000000 </TTBL-AA-Qpid-04-08> - <TTBL-AA-Qpid-04-09>-n TTBL-AA-Qpid-04 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=900 maxPending=2000000 </TTBL-AA-Qpid-04-09> - <TTBL-AA-Qpid-04-10>-n TTBL-AA-Qpid-04 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=1000 maxPending=2000000 </TTBL-AA-Qpid-04-10> - - <PTBL-AA-Qpid-04-01>-n PTBL-AA-Qpid-04 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=5120 destinationCount=1 rate=10 maxPending=2000000 </PTBL-AA-Qpid-04-01> - <PTBL-AA-Qpid-04-02>-n PTBL-AA-Qpid-04 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=5120 destinationCount=1 rate=20 maxPending=2000000 </PTBL-AA-Qpid-04-02> - <PTBL-AA-Qpid-04-03>-n PTBL-AA-Qpid-04 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=5120 destinationCount=1 rate=30 maxPending=2000000 </PTBL-AA-Qpid-04-03> - <PTBL-AA-Qpid-04-04>-n PTBL-AA-Qpid-04 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=5120 destinationCount=1 rate=40 maxPending=2000000 </PTBL-AA-Qpid-04-04> - <PTBL-AA-Qpid-04-05>-n PTBL-AA-Qpid-04 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=5120 destinationCount=1 rate=50 maxPending=2000000 </PTBL-AA-Qpid-04-05> - <PTBL-AA-Qpid-04-06>-n PTBL-AA-Qpid-04 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=5120 destinationCount=1 rate=60 maxPending=2000000 </PTBL-AA-Qpid-04-06> - <PTBL-AA-Qpid-04-07>-n PTBL-AA-Qpid-04 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=5120 destinationCount=1 rate=70 maxPending=2000000 </PTBL-AA-Qpid-04-07> - <PTBL-AA-Qpid-04-08>-n PTBL-AA-Qpid-04 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=5120 destinationCount=1 rate=80 maxPending=2000000 </PTBL-AA-Qpid-04-08> - <PTBL-AA-Qpid-04-09>-n PTBL-AA-Qpid-04 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=5120 destinationCount=1 rate=90 maxPending=2000000 </PTBL-AA-Qpid-04-09> - <PTBL-AA-Qpid-04-10>-n PTBL-AA-Qpid-04 -d1M -s[100] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=101 messageSize=5120 destinationCount=1 rate=100 maxPending=2000000 </PTBL-AA-Qpid-04-10> - - <!-- Low-latency broadcast of time sensitive events. Transient, no_ack. --> - <TTBL-NA-Qpid-05-01>-n TTBL-NA-Qpid-05 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=400 maxPending=2000000 </TTBL-NA-Qpid-05-01> - <TTBL-NA-Qpid-05-02>-n TTBL-NA-Qpid-05 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=800 maxPending=2000000 </TTBL-NA-Qpid-05-02> - <TTBL-NA-Qpid-05-03>-n TTBL-NA-Qpid-05 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=1200 maxPending=2000000 </TTBL-NA-Qpid-05-03> - <TTBL-NA-Qpid-05-04>-n TTBL-NA-Qpid-05 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=1600 maxPending=2000000 </TTBL-NA-Qpid-05-04> - <TTBL-NA-Qpid-05-05>-n TTBL-NA-Qpid-05 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=2000 maxPending=2000000 </TTBL-NA-Qpid-05-05> - <TTBL-NA-Qpid-05-06>-n TTBL-NA-Qpid-05 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=2400 maxPending=2000000 </TTBL-NA-Qpid-05-06> - <TTBL-NA-Qpid-05-07>-n TTBL-NA-Qpid-05 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=2800 maxPending=2000000 </TTBL-NA-Qpid-05-07> - <TTBL-NA-Qpid-05-08>-n TTBL-NA-Qpid-05 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=3200 maxPending=2000000 </TTBL-NA-Qpid-05-08> - <TTBL-NA-Qpid-05-09>-n TTBL-NA-Qpid-05 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=3600 maxPending=2000000 </TTBL-NA-Qpid-05-09> - <TTBL-NA-Qpid-05-10>-n TTBL-NA-Qpid-05 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=256 destinationCount=1 rate=4000 maxPending=2000000 </TTBL-NA-Qpid-05-10> - - <!-- Low-latency broadcast of medium sized time sensitive events. Transient, no_ack. --> - <TTBL-NA-Qpid-06-01>-n TTBL-NA-Qpid-06 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=100 maxPending=2000000 </TTBL-NA-Qpid-06-01> - <TTBL-NA-Qpid-06-02>-n TTBL-NA-Qpid-06 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=200 maxPending=2000000 </TTBL-NA-Qpid-06-02> - <TTBL-NA-Qpid-06-03>-n TTBL-NA-Qpid-06 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=300 maxPending=2000000 </TTBL-NA-Qpid-06-03> - <TTBL-NA-Qpid-06-04>-n TTBL-NA-Qpid-06 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=400 maxPending=2000000 </TTBL-NA-Qpid-06-04> - <TTBL-NA-Qpid-06-05>-n TTBL-NA-Qpid-06 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=500 maxPending=2000000 </TTBL-NA-Qpid-06-05> - <TTBL-NA-Qpid-06-06>-n TTBL-NA-Qpid-06 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=600 maxPending=2000000 </TTBL-NA-Qpid-06-06> - <TTBL-NA-Qpid-06-07>-n TTBL-NA-Qpid-06 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=700 maxPending=2000000 </TTBL-NA-Qpid-06-07> - <TTBL-NA-Qpid-06-08>-n TTBL-NA-Qpid-06 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=800 maxPending=2000000 </TTBL-NA-Qpid-06-08> - <TTBL-NA-Qpid-06-09>-n TTBL-NA-Qpid-06 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=900 maxPending=2000000 </TTBL-NA-Qpid-06-09> - <TTBL-NA-Qpid-06-10>-n TTBL-NA-Qpid-06 -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=true uniqueDests=false numConsumers=50 transacted=false consTransacted=false consAckMode=257 commitBatchSize=1 batchSize=1001 messageSize=5120 destinationCount=1 rate=1000 maxPending=2000000 </TTBL-NA-Qpid-06-10> - - <!-- Benchmarking Tests for P2P. --> - <!-- - Bench mark 1. P2P messaging from 1:1 to 1:32, shared queue, load balancing scenario. - Non-tx, and 1 msg per tx. - Persistent and non-persistent. - No rate limiting. - Message size 256 bytes. - --> - <!-- - <TQBT-Qpid-01-1C> -n TQBT-Qpid-01-1C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-01-1C> - <TQBT-Qpid-01-2C> -n TQBT-Qpid-01-2C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=2 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-01-2C> - <TQBT-Qpid-01-4C> -n TQBT-Qpid-01-4C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=4 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-01-4C> - <TQBT-Qpid-01-8C> -n TQBT-Qpid-01-8C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=8 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-01-8C> - <TQBT-Qpid-01-16C>-n TQBT-Qpid-01-16C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=16 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-01-16C> - <TQBT-Qpid-01-32C>-n TQBT-Qpid-01-32C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=32 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-01-32C> - - <TQBT-Qpid-02-1C> -n TQBT-Qpid-02-1C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-02-1C> - <TQBT-Qpid-02-2C> -n TQBT-Qpid-02-2C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=2 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-02-2C> - <TQBT-Qpid-02-4C> -n TQBT-Qpid-02-4C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=4 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-02-4C> - <TQBT-Qpid-02-8C> -n TQBT-Qpid-02-8C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=8 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-02-8C> - <TQBT-Qpid-02-16C>-n TQBT-Qpid-02-16C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=16 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-02-16C> - <TQBT-Qpid-02-32C>-n TQBT-Qpid-02-32C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=32 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-02-32C> - - <PQBT-Qpid-01-1C> -n PQBT-Qpid-01-1C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-01-1C> - <PQBT-Qpid-01-2C> -n PQBT-Qpid-01-2C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=2 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-01-2C> - <PQBT-Qpid-01-4C> -n PQBT-Qpid-01-4C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=4 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-01-4C> - <PQBT-Qpid-01-8C> -n PQBT-Qpid-01-8C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=8 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-01-8C> - <PQBT-Qpid-01-16C>-n PQBT-Qpid-01-16C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=16 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-01-16C> - <PQBT-Qpid-01-32C>-n PQBT-Qpid-01-32C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=32 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-01-32C> - - <PQBT-Qpid-02-1C> -n PQBT-Qpid-02-1C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-02-1C> - <PQBT-Qpid-02-2C> -n PQBT-Qpid-02-2C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=2 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-02-2C> - <PQBT-Qpid-02-4C> -n PQBT-Qpid-02-4C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=4 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-02-4C> - <PQBT-Qpid-02-8C> -n PQBT-Qpid-02-8C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=8 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-02-8C> - <PQBT-Qpid-02-16C>-n PQBT-Qpid-02-16C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=16 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-02-16C> - <PQBT-Qpid-02-32C>-n PQBT-Qpid-02-32C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=32 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-02-32C> - - <TQBL-Qpid-01-1C> -n TQBL-Qpid-01-1C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-01-1C> - <TQBL-Qpid-01-2C> -n TQBL-Qpid-01-2C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=2 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-01-2C> - <TQBL-Qpid-01-4C> -n TQBL-Qpid-01-4C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=4 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-01-4C> - <TQBL-Qpid-01-8C> -n TQBL-Qpid-01-8C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=8 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-01-8C> - <TQBL-Qpid-01-16C>-n TQBL-Qpid-01-16C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=16 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-01-16C> - <TQBL-Qpid-01-32C>-n TQBL-Qpid-01-32C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=32 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-01-32C> - - <TQBL-Qpid-02-1C> -n TQBL-Qpid-02-1C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-02-1C> - <TQBL-Qpid-02-2C> -n TQBL-Qpid-02-2C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=2 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-02-2C> - <TQBL-Qpid-02-4C> -n TQBL-Qpid-02-4C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=4 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-02-4C> - <TQBL-Qpid-02-8C> -n TQBL-Qpid-02-8C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=8 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-02-8C> - <TQBL-Qpid-02-16C>-n TQBL-Qpid-02-16C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=16 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-02-16C> - <TQBL-Qpid-02-32C>-n TQBL-Qpid-02-32C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=32 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-02-32C> - - <PQBL-Qpid-01-1C> -n PQBL-Qpid-01-1C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-01-1C> - <PQBL-Qpid-01-2C> -n PQBL-Qpid-01-2C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=2 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-01-2C> - <PQBL-Qpid-01-4C> -n PQBL-Qpid-01-4C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=4 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-01-4C> - <PQBL-Qpid-01-8C> -n PQBL-Qpid-01-8C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=8 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-01-8C> - <PQBL-Qpid-01-16C>-n PQBL-Qpid-01-16C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=16 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-01-16C> - <PQBL-Qpid-01-32C>-n PQBL-Qpid-01-32C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=32 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-01-32C> - - <PQBL-Qpid-02-1C> -n PQBL-Qpid-02-1C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-02-1C> - <PQBL-Qpid-02-2C> -n PQBL-Qpid-02-2C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=2 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-02-2C> - <PQBL-Qpid-02-4C> -n PQBL-Qpid-02-4C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=4 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-02-4C> - <PQBL-Qpid-02-8C> -n PQBL-Qpid-02-8C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=8 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-02-8C> - <PQBL-Qpid-02-16C>-n PQBL-Qpid-02-16C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=16 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-02-16C> - <PQBL-Qpid-02-32C>-n PQBL-Qpid-02-32C -d1M -s[1000] -c[1] -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=32 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=1000 messageSize=256 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-02-32C> - --> - - <!-- - Bench mark 2. P2P messaging 1:1, scaled up from 1 to 32 times. Queues not shared, just one to one throughput. - Non-tx, and 1 msg per tx. - Persistent and non-persistent. - No rate limiting. - Message size from 128 bytes to 1 Meg. - --> - <!-- - <TQBT-Qpid-03-128b>-n TQBT-Qpid-03-128b -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-03-128b> - <TQBT-Qpid-03-256b>-n TQBT-Qpid-03-256b -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-03-256b> - <TQBT-Qpid-03-512b>-n TQBT-Qpid-03-512b -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-03-512b> - <TQBT-Qpid-03-1K>-n TQBT-Qpid-03-1K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=1024 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-03-1K> - <TQBT-Qpid-03-5K>-n TQBT-Qpid-03-5K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=5120 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-03-5K> - <TQBT-Qpid-03-10K>-n TQBT-Qpid-03-10K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=10240 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-03-10K> - <TQBT-Qpid-03-50K>-n TQBT-Qpid-03-50K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=51200 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-03-50K> - <TQBT-Qpid-03-100K>-n TQBT-Qpid-03-100K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=102400 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-03-100K> - <TQBT-Qpid-03-500K>-n TQBT-Qpid-03-500K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512000 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-03-500K> - <TQBT-Qpid-03-1M>-n TQBT-Qpid-03-1M -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=1048576 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-03-1M> - - <TQBT-Qpid-04-128b>-n TQBT-Qpid-04-128b -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-04-128b> - <TQBT-Qpid-04-256b>-n TQBT-Qpid-04-256b -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-04-256b> - <TQBT-Qpid-04-512b>-n TQBT-Qpid-04-512b -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-04-512b> - <TQBT-Qpid-04-1K>-n TQBT-Qpid-04-1K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=1024 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-04-1K> - <TQBT-Qpid-04-5K>-n TQBT-Qpid-04-5K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=5120 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-04-5K> - <TQBT-Qpid-04-10K>-n TQBT-Qpid-04-10K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=10240 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-04-10K> - <TQBT-Qpid-04-50K>-n TQBT-Qpid-04-50K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=51200 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-04-50K> - <TQBT-Qpid-04-100K>-n TQBT-Qpid-04-100K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=102400 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-04-100K> - <TQBT-Qpid-04-500K>-n TQBT-Qpid-04-500K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512000 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-04-500K> - <TQBT-Qpid-04-1M>-n TQBT-Qpid-04-1M -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=1048576 destinationCount=1 rate=0 maxPending=2000000 </TQBT-Qpid-04-1M> - - <PQBT-Qpid-03-128b>-n PQBT-Qpid-03-128b -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-03-128b> - <PQBT-Qpid-03-256b>-n PQBT-Qpid-03-256b -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-03-256b> - <PQBT-Qpid-03-512b>-n PQBT-Qpid-03-512b -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-03-512b> - <PQBT-Qpid-03-1K>-n PQBT-Qpid-03-1K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=1024 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-03-1K> - <PQBT-Qpid-03-5K>-n PQBT-Qpid-03-5K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=5120 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-03-5K> - <PQBT-Qpid-03-10K>-n PQBT-Qpid-03-10K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=10240 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-03-10K> - <PQBT-Qpid-03-50K>-n PQBT-Qpid-03-50K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=51200 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-03-50K> - <PQBT-Qpid-03-100K>-n PQBT-Qpid-03-100K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=102400 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-03-100K> - <PQBT-Qpid-03-500K>-n PQBT-Qpid-03-500K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512000 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-03-500K> - <PQBT-Qpid-03-1M>-n PQBT-Qpid-03-1M -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=1048576 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-03-1M> - - <PQBT-Qpid-04-128b>-n PQBT-Qpid-04-128b -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-04-128b> - <PQBT-Qpid-04-256b>-n PQBT-Qpid-04-256b -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-04-256b> - <PQBT-Qpid-04-512b>-n PQBT-Qpid-04-512b -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-04-512b> - <PQBT-Qpid-04-1K>-n PQBT-Qpid-04-1K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=1024 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-04-1K> - <PQBT-Qpid-04-5K>-n PQBT-Qpid-04-5K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=5120 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-04-5K> - <PQBT-Qpid-04-10K>-n PQBT-Qpid-04-10K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=10240 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-04-10K> - <PQBT-Qpid-04-50K>-n PQBT-Qpid-04-50K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=51200 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-04-50K> - <PQBT-Qpid-04-100K>-n PQBT-Qpid-04-100K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=102400 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-04-100K> - <PQBT-Qpid-04-500K>-n PQBT-Qpid-04-500K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512000 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-04-500K> - <PQBT-Qpid-04-1M>-n PQBT-Qpid-04-1M -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=1048576 destinationCount=1 rate=0 maxPending=2000000 </PQBT-Qpid-04-1M> - - <TQBL-Qpid-03-128b>-n TQBL-Qpid-03-128b -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-03-128b> - <TQBL-Qpid-03-256b>-n TQBL-Qpid-03-256b -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-03-256b> - <TQBL-Qpid-03-512b>-n TQBL-Qpid-03-512b -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-03-512b> - <TQBL-Qpid-03-1K>-n TQBL-Qpid-03-1K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=1024 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-03-1K> - <TQBL-Qpid-03-5K>-n TQBL-Qpid-03-5K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=5120 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-03-5K> - <TQBL-Qpid-03-10K>-n TQBL-Qpid-03-10K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=10240 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-03-10K> - <TQBL-Qpid-03-50K>-n TQBL-Qpid-03-50K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=51200 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-03-50K> - <TQBL-Qpid-03-100K>-n TQBL-Qpid-03-100K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=102400 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-03-100K> - <TQBL-Qpid-03-500K>-n TQBL-Qpid-03-500K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512000 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-03-500K> - <TQBL-Qpid-03-1M>-n TQBL-Qpid-03-1M -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=1048576 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-03-1M> - - <TQBL-Qpid-04-128b>-n TQBL-Qpid-04-128b -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-04-128b> - <TQBL-Qpid-04-256b>-n TQBL-Qpid-04-256b -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-04-256b> - <TQBL-Qpid-04-512b>-n TQBL-Qpid-04-512b -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-04-512b> - <TQBL-Qpid-04-1K>-n TQBL-Qpid-04-1K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=1024 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-04-1K> - <TQBL-Qpid-04-5K>-n TQBL-Qpid-04-5K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=5120 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-04-5K> - <TQBL-Qpid-04-10K>-n TQBL-Qpid-04-10K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=10240 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-04-10K> - <TQBL-Qpid-04-50K>-n TQBL-Qpid-04-50K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=51200 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-04-50K> - <TQBL-Qpid-04-100K>-n TQBL-Qpid-04-100K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=102400 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-04-100K> - <TQBL-Qpid-04-500K>-n TQBL-Qpid-04-500K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512000 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-04-500K> - <TQBL-Qpid-04-1M>-n TQBL-Qpid-04-1M -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=false pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=1048576 destinationCount=1 rate=0 maxPending=2000000 </TQBL-Qpid-04-1M> - - <PQBL-Qpid-03-128b>-n PQBL-Qpid-03-128b -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-03-128b> - <PQBL-Qpid-03-256b>-n PQBL-Qpid-03-256b -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-03-256b> - <PQBL-Qpid-03-512b>-n PQBL-Qpid-03-512b -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-03-512b> - <PQBL-Qpid-03-1K>-n PQBL-Qpid-03-1K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=1024 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-03-1K> - <PQBL-Qpid-03-5K>-n PQBL-Qpid-03-5K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=5120 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-03-5K> - <PQBL-Qpid-03-10K>-n PQBL-Qpid-03-10K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=10240 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-03-10K> - <PQBL-Qpid-03-50K>-n PQBL-Qpid-03-50K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=51200 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-03-50K> - <PQBL-Qpid-03-100K>-n PQBL-Qpid-03-100K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=102400 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-03-100K> - <PQBL-Qpid-03-500K>-n PQBL-Qpid-03-500K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512000 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-03-500K> - <PQBL-Qpid-03-1M>-n PQBL-Qpid-03-1M -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=true consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=1048576 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-03-1M> - - <PQBL-Qpid-04-128b>-n PQBL-Qpid-04-128b -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-04-128b> - <PQBL-Qpid-04-256b>-n PQBL-Qpid-04-256b -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-04-256b> - <PQBL-Qpid-04-512b>-n PQBL-Qpid-04-512b -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-04-512b> - <PQBL-Qpid-04-1K>-n PQBL-Qpid-04-1K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=1024 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-04-1K> - <PQBL-Qpid-04-5K>-n PQBL-Qpid-04-5K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=5120 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-04-5K> - <PQBL-Qpid-04-10K>-n PQBL-Qpid-04-10K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=10240 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-04-10K> - <PQBL-Qpid-04-50K>-n PQBL-Qpid-04-50K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=51200 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-04-50K> - <PQBL-Qpid-04-100K>-n PQBL-Qpid-04-100K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=102400 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-04-100K> - <PQBL-Qpid-04-500K>-n PQBL-Qpid-04-500K -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=512000 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-04-500K> - <PQBL-Qpid-04-1M>-n PQBL-Qpid-04-1M -d1M -s[100] -c[1,32],samples=6,exp -o $QPID_WORK/results -t testPingLatency org.apache.qpid.ping.PingLatencyTestPerf persistent=true pubsub=false uniqueDests=true numConsumers=1 transacted=false consTransacted=false consAckMode=1 commitBatchSize=1 batchSize=100 messageSize=1048576 destinationCount=1 rate=0 maxPending=2000000 </PQBL-Qpid-04-1M> - --> - - <!-- Failover Tests. --> - <FT-Qpid-01>-n FT-Qpid-01 -s[2500] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf messageSize=256 batchSize=10000 transacted=true broker="tcp://127.0.0.1:5001;tcp://127.0.0.1:5002" failBeforeSend=true -o $QPID_WORK/results</FT-Qpid-01> - <FT-Qpid-02>-n FT-Qpid-02 -s[2500] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf messageSize=256 batchSize=10000 transacted=true broker="tcp://127.0.0.1:5001;tcp://127.0.0.1:5002" failAfterSend=true -o $QPID_WORK/results</FT-Qpid-02> - <FT-Qpid-03>-n FT-Qpid-03 -s[2500] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf messageSize=256 batchSize=1000 transacted=true broker="tcp://127.0.0.1:5001;tcp://127.0.0.1:5002" failAfterCommit=true -o $QPID_WORK/results</FT-Qpid-03> - <FT-Qpid-04>-n FT-Qpid-04 -s[2500] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf messageSize=256 batchSize=1000 broker="tcp://127.0.0.1:5001;tcp://127.0.0.1:5002" transacted=false failBeforeSend=true -o $QPID_WORK/results</FT-Qpid-04> - <FT-Qpid-05>-n FT-Qpid-05 -s[2500] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf messageSize=256 batchSize=1000 broker="tcp://127.0.0.1:5001;tcp://127.0.0.1:5002" transacted=false failAfterSend=true -o $QPID_WORK/results</FT-Qpid-05> - <FT-Qpid-01-P>-n FT-Qpid-01-P -s[2500] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true messageSize=256 batchSize=1000 transacted=true broker="tcp://127.0.0.1:5001;tcp://127.0.0.1:5002" failBeforeSend=true -o $QPID_WORK/results</FT-Qpid-01-P> - <FT-Qpid-02-P>-n FT-Qpid-02-P -s[2500] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true messageSize=256 batchSize=1000 transacted=true broker="tcp://127.0.0.1:5001;tcp://127.0.0.1:5002" failAfterSend=true -o $QPID_WORK/results</FT-Qpid-02-P> - <FT-Qpid-03-P>-n FT-Qpid-03-P -s[2500] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true messageSize=256 batchSize=1000 transacted=true broker="tcp://127.0.0.1:5001;tcp://127.0.0.1:5002" failAfterCommit=true -o $QPID_WORK/results</FT-Qpid-03-P> - <FT-Qpid-04-P>-n FT-Qpid-04-P -s[250] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true messageSize=256 batchSize=1000 broker="tcp://127.0.0.1:5001;tcp://127.0.0.1:5002" transacted=false failBeforeSend=true -o $QPID_WORK/results</FT-Qpid-04-P> - <FT-Qpid-05-P>-n FT-Qpid-05-P -s[250] -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true messageSize=256 batchSize=1000 broker="tcp://127.0.0.1:5001;tcp://127.0.0.1:5002" transacted=false failAfterSend=true -o $QPID_WORK/results</FT-Qpid-05-P> - - </commands> - </configuration> - - <executions> - <execution> - <phase>test</phase> - </execution> - </executions> - </plugin> - - <!-- Bundles all the dependencies, fully expanded into a single jar, required to run the tests. - Also builds all thescripts and this jar into distributable .zip and .tar.gz files. - - Usefull when bundling system, integration or performance tests into a convenient - package to hand over to testers. To use it run: - - java -cp target/your_app_name-all-test-deps.jar path.to.your.Class - - or often: - - java -cp target/your_app_name-all-test-deps.jar junit.framework.textui.TestRunner path.to.your.test.Class - - or other JUnit test runner invocations. - --> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-assembly-plugin</artifactId> - <version>2.2-SNAPSHOT</version> - <configuration> - <descriptors> - <descriptor>jar-with-dependencies.xml</descriptor> - <!--<descriptor>dist-zip.xml</descriptor>--> - </descriptors> - <outputDirectory>target</outputDirectory> - <workDirectory>target/assembly/work</workDirectory> - </configuration> - </plugin> - - <!-- Build a manifest only jar with all the required jars for the broker in its classpath. --> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-jar-plugin</artifactId> - <executions> - <execution> - <id>test_jar</id> - <configuration> - <archive> - <manifest> - <addClasspath>true</addClasspath> - </manifest> - </archive> - </configuration> - <goals> - <goal>jar</goal> - </goals> - </execution> - </executions> - </plugin> - - </plugins> - - <resources> - <!-- Include source files in built jar --> - <resource> - <targetPath>src/</targetPath> - <filtering>false</filtering> - <directory>src/main/java</directory> - <includes> - <include>**/*.java</include> - </includes> - </resource> - <!-- Include a log4j configuration in the jar at the root level (don't name this log4j.properties though as won't be able to override it). --> - <resource> - <targetPath>/</targetPath> - <filtering>false</filtering> - <directory>src/main/java</directory> - <includes> - <include>perftests.log4j</include> - </includes> - </resource> - </resources> - </build> - -</project> diff --git a/java/perftests/src/main/java/org/apache/qpid/client/latency/MessageConsumer.java b/java/perftests/src/main/java/org/apache/qpid/client/latency/MessageConsumer.java deleted file mode 100644 index 80f965eae5..0000000000 --- a/java/perftests/src/main/java/org/apache/qpid/client/latency/MessageConsumer.java +++ /dev/null @@ -1,129 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.client.latency; - -import org.apache.qpid.client.AMQConnection; -import org.apache.qpid.client.AMQQueue; -import org.apache.qpid.client.AMQTopic; -import org.apache.qpid.client.perf.Options; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.requestreply.InitialContextHelper; - -import javax.jms.*; -import javax.naming.Context; - -/** - * - * - */ -public class MessageConsumer extends Options implements MessageListener -{ - private javax.jms.MessageProducer _producer; - private AMQConnection _connection; - private final Object _lock = new Object(); - private Session _session; - private int _receivedMessages = 0; - private long _timeFirstMessage; - private long _timeLastMessage; - private void init() - { - this.parseOptions(); - try - { - Context context = InitialContextHelper.getInitialContext(""); - ConnectionFactory factory = (ConnectionFactory) context.lookup("local"); - _connection = (AMQConnection) factory.createConnection("guest","guest"); - _session = _connection.createSession(_transacted, Session.AUTO_ACKNOWLEDGE); - Destination dest = Boolean.getBoolean("useQueue")? (Destination) context.lookup("testQueue") : - (Destination) context.lookup("testTopic"); - Destination syncQueue = (Destination) context.lookup("syncQueue"); - _producer = _session.createProducer(syncQueue); - // this should speedup the message producer - _producer.setDisableMessageTimestamp(true); - javax.jms.MessageConsumer consumer = _session.createConsumer(dest); - consumer.setMessageListener(this); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - - private void run() - { - try - { - synchronized(_lock) - { - _connection.start(); - try - { - _lock.wait(); - } - catch (InterruptedException e) - { - e.printStackTrace(); - } - } - // send sync message; - _producer.send(_session.createMessage()); - System.out.println("Time to receive " + _logFrequency + " messages is: " + (_timeLastMessage - _timeFirstMessage) ); - double rate = _logFrequency / ((_timeLastMessage - _timeFirstMessage) *1.0) *1000 ; - System.out.println("The rate is " + rate + " msg/s" ); - double latency = ((_timeLastMessage - _timeFirstMessage) *1.0) / _logFrequency; - System.out.println("The latency is " + latency + " milli secs" ); - _connection.close(); - } - catch (JMSException e) - { - e.printStackTrace(); - } - } - - public void onMessage(Message message) - { - if( _receivedMessages == 0) - { - _timeFirstMessage = System.currentTimeMillis(); - } - _receivedMessages++; - if( _receivedMessages == _logFrequency) - { - _timeLastMessage = System.currentTimeMillis(); - synchronized(_lock) - { - _lock.notify(); - } - } - } - - public static void main(String[] args) - { - try - { - MessageConsumer test = new MessageConsumer(); - test.init(); - test.run(); - } - catch(Exception e) - { - e.printStackTrace(); - } - } - -}
\ No newline at end of file diff --git a/java/perftests/src/main/java/org/apache/qpid/client/latency/MessageProducer.java b/java/perftests/src/main/java/org/apache/qpid/client/latency/MessageProducer.java deleted file mode 100644 index c084a55bcc..0000000000 --- a/java/perftests/src/main/java/org/apache/qpid/client/latency/MessageProducer.java +++ /dev/null @@ -1,116 +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.client.latency; - -import org.apache.qpid.client.AMQConnection; -import org.apache.qpid.client.message.TestMessageFactory; -import org.apache.qpid.client.perf.Options; -import org.apache.qpid.requestreply.InitialContextHelper; -import org.apache.qpidity.transport.network.nio.NioSender; - -import javax.jms.*; -import javax.naming.Context; - -/** - * - * - */ -public class MessageProducer extends Options -{ - private BytesMessage _payload; - private javax.jms.MessageProducer _producer; - private javax.jms.MessageConsumer _consumer; - private AMQConnection _connection; - private void init() - { - this.parseOptions(); - try - { - Context context = InitialContextHelper.getInitialContext(""); - ConnectionFactory factory = (ConnectionFactory) context.lookup("local"); - _connection = (AMQConnection) factory.createConnection("guest","guest"); - Destination dest = Boolean.getBoolean("useQueue")? (Destination) context.lookup("testQueue") : - (Destination) context.lookup("testTopic"); - Destination syncQueue = (Destination) context.lookup("syncQueue"); - _connection.start(); - Session session = _connection.createSession(_transacted, Session.AUTO_ACKNOWLEDGE); - _payload = TestMessageFactory.newBytesMessage(session, _messageSize); - _producer = session.createProducer(dest); - _consumer = session.createConsumer(syncQueue); - // this should speedup the message producer - _producer.setDisableMessageTimestamp(true); - System.out.println("Init end" ); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - - private void run() - { - try - { - System.out.println("Sending " + _logFrequency + " messages"); - - // NioSender.setStartBatching(); - long startTime = System.currentTimeMillis(); - for(int i =0; i < _logFrequency; i++ ) - { - _producer.send(_payload, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, 0); - } - long endProducing = System.currentTimeMillis(); - double throughput = (_logFrequency * 1000.0) / (endProducing - startTime); - System.out.println("The producer throughput is: " + throughput + " msg/s"); - - // startTime = System.currentTimeMillis(); - // NioSender.purge(); - // endProducing = System.currentTimeMillis(); - // throughput = (_logFrequency * 1000.0) / (endProducing - startTime); - // System.out.println("The NIO throughput is: " + throughput + " msg/s"); - - - // now wait for the sync message - _consumer.receive(); - // this is done - long endTime = System.currentTimeMillis(); - System.out.println("Time to send and receive " + _logFrequency + " messages is: " + (endTime - startTime) ); - double latency = ( (endTime - startTime) * 1.0) /_logFrequency; - System.out.println("The latency is " + latency + " milli secs" ); - _connection.close(); - } - catch (JMSException e) - { - e.printStackTrace(); - } - } - - public static void main(String[] args) - { - try - { - MessageProducer test = new MessageProducer(); - test.init(); - test.run(); - } - catch(Exception e) - { - e.printStackTrace(); - } - } -} diff --git a/java/perftests/src/main/java/org/apache/qpid/client/message/TestMessageFactory.java b/java/perftests/src/main/java/org/apache/qpid/client/message/TestMessageFactory.java deleted file mode 100644 index 4d038db0a8..0000000000 --- a/java/perftests/src/main/java/org/apache/qpid/client/message/TestMessageFactory.java +++ /dev/null @@ -1,109 +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.client.message; - -import javax.jms.JMSException; -import javax.jms.Session; -import javax.jms.ObjectMessage; -import javax.jms.StreamMessage; -import javax.jms.BytesMessage; -import javax.jms.TextMessage; -import javax.jms.DeliveryMode; -import javax.jms.Destination; - -public class TestMessageFactory -{ - private static final String MESSAGE_DATA_BYTES = "-message payload-message paylaod-message payload-message paylaod"; - - public static TextMessage newTextMessage(Session session, int size) throws JMSException - { - return session.createTextMessage(createMessagePayload(size)); - } - - public static BytesMessage newBytesMessage(Session session, int size) throws JMSException - { - BytesMessage message = session.createBytesMessage(); - message.writeUTF(createMessagePayload(size)); - return message; - } - - public static StreamMessage newStreamMessage(Session session, int size) throws JMSException - { - StreamMessage message = session.createStreamMessage(); - message.writeString(createMessagePayload(size)); - return message; - } - - public static ObjectMessage newObjectMessage(Session session, int size) throws JMSException - { - if (size == 0) - { - return session.createObjectMessage(); - } - else - { - return session.createObjectMessage(createMessagePayload(size)); - } - } - - /** - * Creates an ObjectMessage with given size and sets the JMS properties - * (JMSReplyTo and DeliveryMode) - * @param session - * @param replyDestination - * @param size - * @param persistent - * @return the new ObjectMessage - * @throws JMSException - */ - public static ObjectMessage newObjectMessage(Session session, Destination replyDestination, int size, boolean persistent) throws JMSException - { - ObjectMessage msg = newObjectMessage(session, size); - - // Set the messages persistent delivery flag. - msg.setJMSDeliveryMode(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT); - - // Ensure that the temporary reply queue is set as the reply to destination for the message. - if (replyDestination != null) - { - msg.setJMSReplyTo(replyDestination); - } - - return msg; - } - - public static String createMessagePayload(int size) - { - StringBuffer buf = new StringBuffer(size); - int count = 0; - while (count <= (size - MESSAGE_DATA_BYTES.length())) - { - buf.append(MESSAGE_DATA_BYTES); - count += MESSAGE_DATA_BYTES.length(); - } - if (count < size) - { - buf.append(MESSAGE_DATA_BYTES, 0, size - count); - } - - return buf.toString(); - } -} diff --git a/java/perftests/src/main/java/org/apache/qpid/client/perf/ConnectionUtility.java b/java/perftests/src/main/java/org/apache/qpid/client/perf/ConnectionUtility.java deleted file mode 100644 index 133ef5f854..0000000000 --- a/java/perftests/src/main/java/org/apache/qpid/client/perf/ConnectionUtility.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.apache.qpid.client.perf; - -import javax.naming.InitialContext; - -import org.apache.qpid.client.AMQConnection; -import org.apache.qpid.client.AMQConnectionFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ConnectionUtility -{ - private static final Logger _logger = LoggerFactory.getLogger(ConnectionUtility.class); - - private InitialContext _initialContext; - private AMQConnectionFactory _connectionFactory; - - private static ConnectionUtility _instance = new ConnectionUtility(); - - public static ConnectionUtility getInstance() - { - return _instance; - } - - private InitialContext getInitialContext() throws Exception - { - _logger.info("get InitialContext"); - if (_initialContext == null) - { - _initialContext = new InitialContext(); - } - return _initialContext; - } - - private AMQConnectionFactory getConnectionFactory() throws Exception - { - _logger.info("get ConnectionFactory"); - if (_connectionFactory == null) - { - _connectionFactory = (AMQConnectionFactory) getInitialContext().lookup("local"); - } - return _connectionFactory; - } - - public AMQConnection getConnection() throws Exception - { - _logger.info("get Connection"); - return (AMQConnection)getConnectionFactory().createConnection(); - } - -} diff --git a/java/perftests/src/main/java/org/apache/qpid/client/perf/MessageConsumerTest.java b/java/perftests/src/main/java/org/apache/qpid/client/perf/MessageConsumerTest.java deleted file mode 100644 index 1124e070a1..0000000000 --- a/java/perftests/src/main/java/org/apache/qpid/client/perf/MessageConsumerTest.java +++ /dev/null @@ -1,171 +0,0 @@ -package org.apache.qpid.client.perf; - -import java.io.FileWriter; -import java.io.IOException; -import java.sql.Date; -import java.text.SimpleDateFormat; - -import javax.jms.Destination; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.Session; - -import org.apache.qpid.client.AMQConnection; -import org.apache.qpid.client.AMQQueue; -import org.apache.qpid.client.AMQTopic; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class MessageConsumerTest extends Options implements MessageListener -{ - private static final Logger _logger = LoggerFactory.getLogger(MessageConsumerTest.class); - private SimpleDateFormat df = new SimpleDateFormat("h:mm a"); - - String _logFileName; - long _startTime; - long _intervalStartTime; - long _totalMsgCount; - long _intervalCount; - - private AMQConnection _connection; - private Session _session; - - public void init() throws Exception - { - this.parseOptions(); - _logFileName = _logFilePath + "/MessageConsumerTest_" + System.currentTimeMillis(); - _connection = ConnectionUtility.getInstance().getConnection(); - _connection.start(); - Destination dest = Boolean.getBoolean("useQueue")? new AMQQueue(_connection,_destination) : new AMQTopic(_connection,_destination); - _session = _connection.createSession(_transacted, Session.AUTO_ACKNOWLEDGE); - MessageConsumer _consumer = _session.createConsumer(dest); - _consumer.setMessageListener(this); - _startTime = System.currentTimeMillis(); - if(Boolean.getBoolean("collect_stats")) - { - printHeading(); - runReaper(); - } - } - - public void onMessage(Message message) - { - try - { - /* long msgId = Integer.parseInt(message.getJMSMessageID()); - if (_verifyOrder && _totalMsgCount+1 != msgId) - { - _logger.error("Error : Message received out of order in JMSSyncConsumer:" + _id + " message id was " + msgId + " expected: " + _currentMsgCount+1); - }*/ - _totalMsgCount ++; - _intervalCount++; - if(_intervalCount >= _logFrequency) - { - _intervalCount = 0; - if (Boolean.getBoolean("collect_stats")) - { - runReaper(); - } - if (System.currentTimeMillis() - _startTime >= _expiry) - { - printSummary(); - _session.close(); - _connection.stop(); - } - } - } - catch(Exception e) - { - e.printStackTrace(); - } - } - - public void runReaper() - { - try - { - FileWriter _memoryLog = new FileWriter(_logFileName + ".csv",true); - StringBuffer buf = new StringBuffer(); - Date d = new Date(System.currentTimeMillis()); - long currentTime = d.getTime(); - long intervalTime = currentTime - _intervalStartTime; - long totalTime = currentTime - _startTime; - buf.append(df.format(d)).append(","); - buf.append(d.getTime()).append(","); - buf.append(" total Msg Count: ").append(_totalMsgCount).append(","); - if(totalTime > 0 ) - buf.append(" rate: ").append(_totalMsgCount * 1000 / totalTime); - buf.append(","); - buf.append(" interval Count: ").append(_intervalCount).append(","); - if(intervalTime > 0 ) - buf.append(" interval rate: ").append(_intervalCount * 1000 / intervalTime).append(","); - buf.append(Runtime.getRuntime().totalMemory() -Runtime.getRuntime().freeMemory()).append("\n"); - buf.append("\n"); - _memoryLog.write(buf.toString()); - _memoryLog.close(); - System.out.println(buf); - _intervalStartTime = d.getTime(); - } - catch (Exception e) - { - _logger.error("Error printing info to the log file", e); - } - } - - private void printHeading() - { - try - { - FileWriter _memoryLog = new FileWriter(_logFileName + ".csv",true); - String s = "Date/Time,Time (ms),total msg count,total rate (msg/sec),memory"; - _memoryLog.write(s); - _memoryLog.close(); - } - catch (IOException e) - { - e.printStackTrace(); - } - } - - private void printSummary() - { - try - { - - long current = System.currentTimeMillis(); - double time = current - _startTime; - double ratio = _totalMsgCount*1000/time; - FileWriter _summaryLog = new FileWriter(_logFileName + "_Summary",true); - - StringBuffer buf = new StringBuffer("MessageProducerTest \n Test started at : "); - buf.append(df.format(new Date(_startTime))).append("\n Test finished at : "); - Date d = new Date(current); - buf.append(df.format(d)).append("\n Total Time taken (ms):"); - buf.append(time).append("\n Total messages sent:"); - buf.append(_totalMsgCount).append("\n producer rate:"); - buf.append(ratio).append("\n"); - _summaryLog.write(buf.toString()); - System.out.println("---------- Test Ended -------------"); - _summaryLog.close(); - } - catch(Exception e) - { - e.printStackTrace(); - } - } - - public static void main(String[] args) - { - try - { - MessageConsumerTest test = new MessageConsumerTest(); - test.init(); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - -} diff --git a/java/perftests/src/main/java/org/apache/qpid/client/perf/MessageProducerTest.java b/java/perftests/src/main/java/org/apache/qpid/client/perf/MessageProducerTest.java deleted file mode 100644 index 4398b28131..0000000000 --- a/java/perftests/src/main/java/org/apache/qpid/client/perf/MessageProducerTest.java +++ /dev/null @@ -1,182 +0,0 @@ -package org.apache.qpid.client.perf; - -import java.io.FileWriter; -import java.io.IOException; -import java.sql.Date; -import java.text.SimpleDateFormat; - -import javax.jms.BytesMessage; -import javax.jms.Destination; -import javax.jms.MessageProducer; -import javax.jms.Session; - -import org.apache.qpid.client.AMQConnection; -import org.apache.qpid.client.AMQQueue; -import org.apache.qpid.client.AMQTopic; -import org.apache.qpid.client.message.TestMessageFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class MessageProducerTest extends Options -{ - private static final Logger _logger = LoggerFactory.getLogger(MessageProducerTest.class); - private SimpleDateFormat df = new SimpleDateFormat("h:mm a"); - - String _logFileName; - long _startTime; - long _intervalStartTime; - long _totalMsgCount; - long _intervalCount; - - private AMQConnection _connection; - private Session _session; - private BytesMessage _payload; - private MessageProducer _producer; - - public void init() throws Exception - { - this.parseOptions(); - _logFileName = _logFilePath + "/MessageProducerTest_" + System.currentTimeMillis(); - _connection = ConnectionUtility.getInstance().getConnection(); - _connection.start(); - Destination dest = Boolean.getBoolean("useQueue")? new AMQQueue(_connection,_destination) : new AMQTopic(_connection,_destination); - _session = _connection.createSession(_transacted, Session.AUTO_ACKNOWLEDGE); - _payload = TestMessageFactory.newBytesMessage(_session, _messageSize); - _producer = _session.createProducer(dest); - // this should speedup the message producer - _producer.setDisableMessageTimestamp(true); - } - - public void run() - { - _startTime = System.currentTimeMillis(); - boolean run = true; - if(Boolean.getBoolean("collect_stats")) - { - printHeading(); - runReaper(); - } - - try - { - while (run) - { - _payload.setJMSMessageID(String.valueOf(_totalMsgCount+1)); - _producer.send(_payload); - _totalMsgCount ++; - _intervalCount ++; - - // check every x messages to see if times up - if(_intervalCount >= _logFrequency) - { - if (Boolean.getBoolean("collect_stats")) - { - runReaper(); - _intervalCount = 0; - } - if (System.currentTimeMillis() - _startTime >= _expiry) - { - // time to stop the test. - _session.close(); - _connection.stop(); - run = false; - } - } - } - } - catch (Exception e) - { - _logger.error("The timer thread exited", e); - } - printSummary(); - } - - public void runReaper() - { - try - { - FileWriter _memoryLog = new FileWriter(_logFileName + ".csv",true); - StringBuffer buf = new StringBuffer(); - Date d = new Date(System.currentTimeMillis()); - long currentTime = d.getTime(); - long intervalTime = currentTime - _intervalStartTime; - long totalTime = currentTime - _startTime; - buf.append(df.format(d)).append(","); - buf.append(d.getTime()).append(","); - buf.append(" total Msg Count: ").append(_totalMsgCount).append(","); - if(totalTime > 0 ) - buf.append(" rate: ").append(_totalMsgCount * 1000 / totalTime); - buf.append(","); - buf.append(" interval Count: ").append(_intervalCount).append(","); - if(intervalTime > 0 ) - buf.append(" interval rate: ").append(_intervalCount * 1000 / intervalTime).append(","); - buf.append(Runtime.getRuntime().totalMemory() -Runtime.getRuntime().freeMemory()).append("\n"); - buf.append("\n"); - _memoryLog.write(buf.toString()); - _memoryLog.close(); - System.out.println(buf); - _intervalStartTime = d.getTime(); - } - catch (Exception e) - { - _logger.error("Error printing info to the log file", e); - } - } - - private void printHeading() - { - try - { - FileWriter _memoryLog = new FileWriter(_logFileName + ".csv",true); - String s = "Date/Time,Time (ms),total msg count,total rate (msg/sec),memory"; - _memoryLog.write(s); - _memoryLog.close(); - } - catch (IOException e) - { - e.printStackTrace(); - } - } - - private void printSummary() - { - try - { - - long current = System.currentTimeMillis(); - double time = current - _startTime; - double ratio = _totalMsgCount*1000/time; - FileWriter _summaryLog = new FileWriter(_logFileName + "_Summary",true); - - StringBuffer buf = new StringBuffer("MessageProducerTest \n Test started at : "); - buf.append(df.format(new Date(_startTime))).append("\n Test finished at : "); - Date d = new Date(current); - buf.append(df.format(d)).append("\n Total Time taken (ms):"); - buf.append(time).append("\n Total messages sent:"); - buf.append(_totalMsgCount).append("\n producer rate:"); - buf.append(ratio).append("\n"); - _summaryLog.write(buf.toString()); - System.out.println("---------- Test Ended -------------"); - _summaryLog.close(); - } - catch(Exception e) - { - e.printStackTrace(); - } - } - - public static void main(String[] args) - { - try - { - MessageProducerTest test = new MessageProducerTest(); - test.init(); - test.run(); - } - catch(Exception e) - { - e.printStackTrace(); - } - } - -} diff --git a/java/perftests/src/main/java/org/apache/qpid/client/perf/Options.java b/java/perftests/src/main/java/org/apache/qpid/client/perf/Options.java deleted file mode 100644 index c0f51738db..0000000000 --- a/java/perftests/src/main/java/org/apache/qpid/client/perf/Options.java +++ /dev/null @@ -1,105 +0,0 @@ -package org.apache.qpid.client.perf; - -public class Options -{ - public int _messageSize; - public boolean _transacted; - public boolean _synchronous; - public String _destination; - public long _expiry; - public long _logFrequency; - public String _logFilePath; - - /** - * System props - * -DmessageSize - * -DuseQueue - * -Dtransacted - * -Ddestinations - * -DlogFilePath - * -Duration=1H,30M,10S - * -DlogDuration=10 in mins - */ - public void parseOptions() - { - _messageSize = Integer.parseInt(System.getProperty("messageSize","100")); - _transacted = false; - _destination = System.getProperty("destination", "foo"); - _logFrequency = Long.parseLong(System.getProperty("logFrequency","10000")); - _logFilePath = System.getProperty("logFilePath"); - _expiry = getExpiry(); - - System.out.println("============= Test Data ==================="); - System.out.println("Destination : " + _destination); - System.out.println("Collect stats : " + Boolean.getBoolean("collect_stats")); - System.out.println("Log Frequency in msgs : " + _logFrequency); - System.out.println("Log file path : " + _logFilePath); - System.out.println("Test Duration : " + printTestDuration()); - System.out.println("============= /Test Data ==================="); - } - - private String printTestDuration() - { - StringBuffer buf = new StringBuffer(); - long temp = _expiry; - int hours = (int)temp/(60*60*1000); - temp = temp -hours*60*60*1000; - - int mins = (int)(temp)/(60*1000); - temp = temp -mins*60*1000; - - int secs = (int)temp/1000; - - if (hours > 0) - { - buf.append(hours).append(" hours "); - } - if (mins > 0) - { - buf.append(mins).append(" mins "); - } - if (secs > 0) - { - buf.append(secs).append(" secs"); - } - - return buf.toString(); - } - - private long getExpiry() - { - // default is 30 mins - long time = 0; - String s = System.getProperty("duration"); - if(s != null) - { - String[] temp = s.split(","); - for (String st:temp) - { - if(st.indexOf("H")>0) - { - int hour = Integer.parseInt(st.substring(0,st.indexOf("H"))); - time = time + hour * 60 * 60 * 1000; - } - else if(st.indexOf("M")>0) - { - int min = Integer.parseInt(st.substring(0,st.indexOf("M"))); - time = time + min * 60 * 1000; - } - else if(st.indexOf("S")>0) - { - int sec = Integer.parseInt(st.substring(0,st.indexOf("S"))); - time = time + sec * 1000; - } - - } - } - if (time == 0) - { - time = 30 * 60 * 1000; - } - - return time; - } - -} diff --git a/java/perftests/src/main/java/org/apache/qpid/client/topic/Client.java b/java/perftests/src/main/java/org/apache/qpid/client/topic/Client.java deleted file mode 100644 index 4a726c19ea..0000000000 --- a/java/perftests/src/main/java/org/apache/qpid/client/topic/Client.java +++ /dev/null @@ -1,210 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.client.topic; - -import org.apache.qpid.client.message.TestMessageFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.jms.*; -import java.util.Properties; -import java.util.Random; -import java.util.List; -import java.util.ArrayList; -import java.io.FileWriter; - -public class Client -{ - /** - * This class logger - */ - private static final Logger _logger=LoggerFactory.getLogger(Client.class); - - private long _messagesProduced=0; - private final Object _lock=new Object(); - private Message _message; - private List<Runner> _runners=new ArrayList<Runner>(); - - - /** - * Run the message consumer example. - * - * @param args Command line arguments. - */ - public static void main(String[] args) - { - Client syncConsumer=new Client(); - int firstArg=120; - if (args.length > 0) - { - try - { - firstArg=Integer.parseInt(args[0]); - } - catch (NumberFormatException e) - { - _logger.warn("Argument must be an integer, running for 2 minutes"); - } - } - syncConsumer.runClient(firstArg); - } - - - void runClient(long duration) - { - try - { - // Load JNDI properties - Properties properties=new Properties(); - properties.load(this.getClass().getResourceAsStream("topic.properties")); - - String logFilePath = System.getProperty("logFilePath", "./"); - FileWriter file = new FileWriter(logFilePath + "client-" + System.currentTimeMillis() + ".cvs",true); - - //Create the initial context - Context ctx=new InitialContext(properties); - - // Lookup the connection factory - ConnectionFactory conFac=(ConnectionFactory) ctx.lookup("qpidConnectionfactory"); - // create the connection - Connection connection=conFac.createConnection(); - - connection.setExceptionListener(new ExceptionListener() - { - public void onException(JMSException jmse) - { - // The connection may have broken invoke reconnect code if available. - // The connection may have broken invoke reconnect code if available. - System.err.println("Received an exception through the ExceptionListener"); - System.exit(0); - } - }); - - // Now the messageConsumer is set up we can start the connection - connection.start(); - - // Create a session on the connection - // This session is a default choice of non-transacted and uses the auto acknowledge feature of a session. - Session session=connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - Queue queueCompleted = session.createQueue("completed"); - Queue queueStarted = session.createQueue("started"); - MessageProducer prod = session.createProducer(queueCompleted); - MessageConsumer cons = session.createConsumer(queueStarted); - cons.receive(); - _logger.info("Starting producing messages"); - - _message=TestMessageFactory.newBytesMessage(session, 1024); - - Random random=new Random(); - long testDuration=0; - long totalMessagesProduced; - long messagesProducedLastInterval=0; - long intervalThroughput; - long totalThroughput; - long numProducers=1; - String info; - startNewProducer(session, random); - while (testDuration < duration) - { - // every 5 second creates a thread an print the throughput - synchronized (_lock) - { - _lock.wait(5000); - totalMessagesProduced=_messagesProduced; - } - testDuration=testDuration + 5; - intervalThroughput=(totalMessagesProduced - messagesProducedLastInterval) / 5; - totalThroughput=totalMessagesProduced / testDuration; - messagesProducedLastInterval=totalMessagesProduced; - info = "Number of producers " + numProducers + " | This interval throughput = " + - intervalThroughput + " | Total throughput = " + totalThroughput; - _logger.info(info); - file.write(info + "\n"); - startNewProducer(session, random); - numProducers++; - } - file.close(); - // stop all the producers - for (Runner runner : _runners) - { - runner.stop(); - } - _logger.info("Stopping server"); - prod.send(session.createTextMessage("stop")); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - - private void startNewProducer(Session session, Random random) - throws JMSException - { - // select a random topic - int topicNumber=random.nextInt(50); - _logger.info("creating producer for topic: topic- " + topicNumber); - Topic topic=session.createTopic("topic-" + topicNumber); - MessageProducer prod=session.createProducer(topic); - Runner runner=new Runner(prod); - _runners.add(runner); - Thread thread=new Thread(runner); - thread.setDaemon(true); - thread.start(); - } - - private class Runner implements Runnable - { - MessageProducer _prod; - boolean _produce=true; - private Runner(MessageProducer prod) - { - _prod=prod; - } - - public void run() - { - while (_produce) - { - try - { - _prod.send(_message, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, - Message.DEFAULT_TIME_TO_LIVE); - synchronized (_lock) - { - _messagesProduced++; - } - } - catch (Exception e) - { - e.printStackTrace(); - _produce=false; - } - } - } - - public void stop() - { - _produce=false; - } - } - -} diff --git a/java/perftests/src/main/java/org/apache/qpid/client/topic/Server.java b/java/perftests/src/main/java/org/apache/qpid/client/topic/Server.java deleted file mode 100644 index 883a7465a1..0000000000 --- a/java/perftests/src/main/java/org/apache/qpid/client/topic/Server.java +++ /dev/null @@ -1,171 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.qpid.client.topic; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.naming.Context; -import javax.naming.InitialContext; - -import javax.jms.*; -import java.util.Properties; -import java.io.FileWriter; - - -public class Server -{ - /** - * This class logger - */ - private static final Logger _logger=LoggerFactory.getLogger(Server.class); - - - private final Object _lock=new Object(); - private long _numMessages=0; - public FileWriter _file; - public boolean _running=true; - - public static void main(String[] args) - { - (new Server()).runServer(); - } - - void runServer() - { - try - { - // Load JNDI properties - Properties properties=new Properties(); - properties.load(this.getClass().getResourceAsStream("topic.properties")); - - String logFilePath=System.getProperty("logFilePath", "./"); - _file=new FileWriter(logFilePath + "server-" + System.currentTimeMillis() + ".cvs", true); - - //Create the initial context - Context ctx=new InitialContext(properties); - - // Lookup the connection factory - ConnectionFactory conFac=(ConnectionFactory) ctx.lookup("qpidConnectionfactory"); - // create the connection - Connection connection=conFac.createConnection(); - - connection.setExceptionListener(new ExceptionListener() - { - public void onException(JMSException jmse) - { - // The connection may have broken invoke reconnect code if available. - // The connection may have broken invoke reconnect code if available. - _logger.warn("Received an exception through the ExceptionListener"); - System.exit(0); - } - }); - - // Create a session on the connection - // This session is a default choice of non-transacted and uses the auto acknowledge feature of a session. - // Session session=connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - for (int i=0; i < 50; i++) - { - Session session=connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Topic topic=session.createTopic("topic-" + i); - TopicSubscriber dursub=session.createDurableSubscriber(topic, "durable-" + i); - dursub.setMessageListener(new MyListener()); - } - - // Now the messageConsumer is set up we can start the connection - connection.start(); - _logger.info("Ready to consume messages"); - // listen for the termination message - Session session=connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queueCompleted=session.createQueue("completed"); - Queue queueStarted=session.createQueue("started"); - MessageProducer prod=session.createProducer(queueStarted); - - Thread logger=new Thread(new MyLogger()); - logger.setDaemon(true); - logger.start(); - - prod.send(session.createTextMessage("start")); - long startTime=System.currentTimeMillis(); - MessageConsumer cons=session.createConsumer(queueCompleted); - cons.receive(); - - _running=false; - - long endTime=System.currentTimeMillis(); - session.close(); - _logger.info("Received " + _numMessages); - _file.write("Received " + _numMessages + "\n"); - _logger.info("Throughput " + _numMessages / (endTime - startTime) * 1000 + "msg/s"); - _file.write("Throughput " + _numMessages / (endTime - startTime) * 1000 + "msg/s"); - _file.close(); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - - private class MyListener implements MessageListener - { - public void onMessage(Message message) - { - synchronized (_lock) - { - _numMessages++; - /*if(_numMessages % 1000 == 0) - { - _logger.info("received: " + _numMessages); - } */ - } - } - } - - private class MyLogger implements Runnable - { - public void run() - { - long endTime=0; - while (_running) - { - synchronized (_lock) - { - try - { - _lock.wait(5000); - if (_running) - { - endTime=endTime + 5; - String s="Throughput " + _numMessages / endTime + " msg/s"; - _logger.info(s); - _file.write(s + "\n"); - } - - } - catch (Exception e) - { - e.printStackTrace(); - } - - } - } - } - } -} diff --git a/java/perftests/src/main/java/org/apache/qpid/client/topic/topic.properties b/java/perftests/src/main/java/org/apache/qpid/client/topic/topic.properties deleted file mode 100644 index cff5275e36..0000000000 --- a/java/perftests/src/main/java/org/apache/qpid/client/topic/topic.properties +++ /dev/null @@ -1,24 +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. -# -java.naming.factory.initial = org.apache.qpid.jndi.PropertiesFileInitialContextFactory - -connectionfactory.qpidConnectionfactory = amqp://guest:guest@clientid/test?brokerlist='tcp://localhost:5672' - -# A 0.10 connection factory -#connectionfactory.qpidConnectionfactory = qpid:password=pass;username=name@tcp:localhost:5672 diff --git a/java/perftests/src/main/java/org/apache/qpid/ping/PingAsyncTestPerf.java b/java/perftests/src/main/java/org/apache/qpid/ping/PingAsyncTestPerf.java deleted file mode 100644 index 06081e6ebf..0000000000 --- a/java/perftests/src/main/java/org/apache/qpid/ping/PingAsyncTestPerf.java +++ /dev/null @@ -1,292 +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.ping; - -import junit.framework.Test; -import junit.framework.TestSuite; - -import org.apache.log4j.Logger; - -import org.apache.qpid.requestreply.PingPongProducer; - -import uk.co.thebadgerset.junit.extensions.TimingController; -import uk.co.thebadgerset.junit.extensions.TimingControllerAware; - -import javax.jms.JMSException; -import javax.jms.Message; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.atomic.AtomicLong; - -/** - * PingAsyncTestPerf is a performance test that outputs multiple timings from its test method, using the timing controller - * interface supplied by the test runner from a seperate listener thread. It differs from the {@link PingTestPerf} test - * that it extends because it can output timings as replies are received, rather than waiting until all expected replies - * are received. This is less 'blocky' than the tests in {@link PingTestPerf}, and provides a truer simulation of sending - * and recieving clients working asynchronously. - * - * <p/><table id="crc"><caption>CRC Card</caption> - * <tr><td> Responsibilities <th> Collaborations - * <tr><td> Send many ping messages and output timings asynchronously on batches received. - * </table> - */ -public class PingAsyncTestPerf extends PingTestPerf implements TimingControllerAware -{ - private static Logger _logger = Logger.getLogger(PingAsyncTestPerf.class); - - /** Holds the name of the property to get the test results logging batch size. */ - public static final String TEST_RESULTS_BATCH_SIZE_PROPNAME = "batchSize"; - - /** Holds the default test results logging batch size. */ - public static final int TEST_RESULTS_BATCH_SIZE_DEFAULT = 1000; - - /** Used to hold the timing controller passed from the test runner. */ - private TimingController _timingController; - - /** Used to generate unique correlation ids for each test run. */ - private AtomicLong corellationIdGenerator = new AtomicLong(); - - /** Holds test specifics by correlation id. This consists of the expected number of messages and the timing controler. */ - private Map<String, PerCorrelationId> perCorrelationIds = - Collections.synchronizedMap(new HashMap<String, PerCorrelationId>()); - - /** Holds the batched results listener, that does logging on batch boundaries. */ - private BatchedResultsListener batchedResultsListener = null; - - /** - * Creates a new asynchronous ping performance test with the specified name. - * - * @param name The test name. - */ - public PingAsyncTestPerf(String name) - { - super(name); - - // Sets up the test parameters with defaults. - testParameters.setPropertyIfNull(TEST_RESULTS_BATCH_SIZE_PROPNAME, - Integer.toString(TEST_RESULTS_BATCH_SIZE_DEFAULT)); - } - - /** - * Compile all the tests into a test suite. - * @return The test suite to run. Should only contain testAsyncPingOk method. - */ - public static Test suite() - { - // Build a new test suite - TestSuite suite = new TestSuite("Ping Performance Tests"); - - // Run performance tests in read committed mode. - suite.addTest(new PingAsyncTestPerf("testAsyncPingOk")); - - return suite; - } - - /** - * Accepts a timing controller from the test runner. - * - * @param timingController The timing controller to register mutliple timings with. - */ - public void setTimingController(TimingController timingController) - { - _timingController = timingController; - } - - /** - * Gets the timing controller passed in by the test runner. - * - * @return The timing controller passed in by the test runner. - */ - public TimingController getTimingController() - { - return _timingController; - } - - /** - * Sends the specified number of pings, asynchronously outputs timings on every batch boundary, and waits until - * all replies have been received or a time out occurs before exiting this method. - * - * @param numPings The number of pings to send. - * @throws Exception pass all errors out to the test harness - */ - public void testAsyncPingOk(int numPings) throws Exception - { - // _logger.debug("public void testAsyncPingOk(int numPings): called"); - - // Ensure that at least one ping was requeusted. - if (numPings == 0) - { - _logger.error("Number of pings requested was zero."); - fail("Number of pings requested was zero."); - } - - // Get the per thread test setup to run the test through. - PerThreadSetup perThreadSetup = threadSetup.get(); - PingClient pingClient = perThreadSetup._pingClient; - - // Advance the correlation id of messages to send, to make it unique for this run. - perThreadSetup._correlationId = Long.toString(corellationIdGenerator.incrementAndGet()); - // String messageCorrelationId = perThreadSetup._correlationId; - // _logger.debug("messageCorrelationId = " + messageCorrelationId); - - // Initialize the count and timing controller for the new correlation id. - PerCorrelationId perCorrelationId = new PerCorrelationId(); - TimingController tc = getTimingController().getControllerForCurrentThread(); - perCorrelationId._tc = tc; - perCorrelationId._expectedCount = pingClient.getExpectedNumPings(numPings); - perCorrelationIds.put(perThreadSetup._correlationId, perCorrelationId); - - // Send the requested number of messages, and wait until they have all been received. - long timeout = Long.parseLong(testParameters.getProperty(PingPongProducer.TIMEOUT_PROPNAME)); - int numReplies = pingClient.pingAndWaitForReply(null, numPings, timeout, perThreadSetup._correlationId); - - // Check that all the replies were received and log a fail if they were not. - if (numReplies < perCorrelationId._expectedCount) - { - perCorrelationId._tc.completeTest(false, numPings - perCorrelationId._expectedCount); - } - - // Remove the expected count and timing controller for the message correlation id, to ensure they are cleaned up. - perCorrelationIds.remove(perThreadSetup._correlationId); - } - - /** - * Performs test fixture creation on a per thread basis. This will only be called once for each test thread. - */ - public void threadSetUp() - { - _logger.debug("public void threadSetUp(): called"); - - try - { - // Call the set up method in the super class. This creates a PingClient pinger. - super.threadSetUp(); - - // Create the chained message listener, only if it has not already been created. This is set up with the - // batch size property, to tell it what batch size to output results on. A synchronized block is used to - // ensure that only one thread creates this. - synchronized (this) - { - if (batchedResultsListener == null) - { - int batchSize = Integer.parseInt(testParameters.getProperty(TEST_RESULTS_BATCH_SIZE_PROPNAME)); - batchedResultsListener = new BatchedResultsListener(batchSize); - } - } - - // Get the set up that the super class created. - PerThreadSetup perThreadSetup = threadSetup.get(); - - // Register the chained message listener on the pinger to do its asynchronous test timings from. - perThreadSetup._pingClient.setChainedMessageListener(batchedResultsListener); - } - catch (Exception e) - { - _logger.warn("There was an exception during per thread setup.", e); - } - } - - /** - * BatchedResultsListener is a {@link PingPongProducer.ChainedMessageListener} that can be attached to the - * pinger, in order to receive notifications about every message received and the number remaining to be - * received. Whenever the number remaining crosses a batch size boundary this results listener outputs - * a test timing for the actual number of messages received in the current batch. - */ - private class BatchedResultsListener implements PingPongProducer.ChainedMessageListener - { - /** The test results logging batch size. */ - int _batchSize; - - /** - * Creates a results listener on the specified batch size. - * - * @param batchSize The batch size to use. - */ - public BatchedResultsListener(int batchSize) - { - _batchSize = batchSize; - } - - /** - * This callback method is called from all of the pingers that this test creates. It uses the correlation id - * from the message to identify the timing controller for the test thread that was responsible for sending those - * messages. - * - * @param message The message. - * @param remainingCount The count of messages remaining to be received with a particular correlation id. - * - * @throws JMSException Any underlying JMSException is allowed to fall through. - */ - public void onMessage(Message message, int remainingCount, long latency) throws JMSException - { - // Check if a batch boundary has been crossed. - if ((remainingCount % _batchSize) == 0) - { - // Extract the correlation id from the message. - String correlationId = message.getJMSCorrelationID(); - - /*_logger.debug("public void onMessage(Message message, int remainingCount = " + remainingCount - + "): called on batch boundary for message id: " + correlationId + " with thread id: " - + Thread.currentThread().getId());*/ - - // Get the details for the correlation id and check that they are not null. They can become null - // if a test times out. - PerCorrelationId perCorrelationId = perCorrelationIds.get(correlationId); - if (perCorrelationId != null) - { - // Get the timing controller and expected count for this correlation id. - TimingController tc = perCorrelationId._tc; - int expected = perCorrelationId._expectedCount; - - // Calculate how many messages were actually received in the last batch. This will be the batch size - // except where the number expected is not a multiple of the batch size and this is the first remaining - // count to cross a batch size boundary, in which case it will be the number expected modulo the batch - // size. - int receivedInBatch = ((expected - remainingCount) < _batchSize) ? (expected % _batchSize) : _batchSize; - - // Register a test result for the correlation id. - try - { - tc.completeTest(true, receivedInBatch); - } - catch (InterruptedException e) - { - // Ignore this. It means the test runner wants to stop as soon as possible. - _logger.warn("Got InterruptedException.", e); - } - } - // Else ignore, test timed out. Should log a fail here? - } - } - } - - /** - * Holds state specific to each correlation id, needed to output test results. This consists of the count of - * the total expected number of messages, and the timing controller for the thread sending those message ids. - */ - private static class PerCorrelationId - { - public int _expectedCount; - public TimingController _tc; - } -} diff --git a/java/perftests/src/main/java/org/apache/qpid/ping/PingClient.java b/java/perftests/src/main/java/org/apache/qpid/ping/PingClient.java deleted file mode 100644 index b9632eee4c..0000000000 --- a/java/perftests/src/main/java/org/apache/qpid/ping/PingClient.java +++ /dev/null @@ -1,107 +0,0 @@ -/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.ping;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.requestreply.PingPongProducer;
-
-import javax.jms.Destination;
-
-import java.util.List;
-import java.util.Properties;
-
-/**
- * PingClient is a {@link PingPongProducer} that does not need a {@link org.apache.qpid.requestreply.PingPongBouncer}
- * to send replies to its pings. It simply listens to its own ping destinations, rather than seperate reply queues.
- * It is an all in one ping client, that produces and consumes its own pings.
- *
- * <p/>The constructor increments a count of the number of ping clients created. It is assumed that where many
- * are created they will all be run in parallel and be active in sending and consuming pings at the same time.
- * If the unique destinations flag is not set and a pub/sub ping cycle is being run, this means that they will all hear
- * pings sent by each other. The expected number of pings received will therefore be multiplied up by the number of
- * active ping clients. The {@link #getConsumersPerDestination()} method is used to supply this multiplier under these
- * conditions.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Create a ping producer that listens to its own pings <td> {@link PingPongProducer}
- * <tr><td> Count the number of ping producers and produce multiplier for scaling up messages expected over topic pings.
- * </table>
- */
-public class PingClient extends PingPongProducer
-{
- /** Used for debugging. */
- private final Logger log = Logger.getLogger(PingClient.class);
-
- /** Used to count the number of ping clients created. */
- private static int _pingClientCount;
-
- /**
- * Creates a ping producer with the specified parameters, of which there are many. See the class level comments
- * for {@link PingPongProducer} for details. This constructor creates a connection to the broker and creates
- * producer and consumer sessions on it, to send and recieve its pings and replies on.
- *
- * @param overrides Properties containing any desired overrides to the defaults.
- *
- * @throws Exception Any exceptions are allowed to fall through.
- */
- public PingClient(Properties overrides) throws Exception
- {
- super(overrides);
-
- _pingClientCount++;
- }
-
- /**
- * Returns the ping destinations themselves as the reply destinations for this pinger to listen to. This has the
- * effect of making this pinger listen to its own pings.
- *
- * @return The ping destinations.
- */
- public List<Destination> getReplyDestinations()
- {
- return _pingDestinations;
- }
-
- /**
- * Supplies the multiplier for the number of ping clients that will hear each ping when doing pub/sub pinging.
- *
- * @return The scaling up of the number of expected pub/sub pings.
- */
- public int getConsumersPerDestination()
- {
- log.debug("public int getConsumersPerDestination(): called");
-
- if (_isUnique)
- {
- log.debug(_noOfConsumers + " consumer per destination.");
-
- return _noOfConsumers;
- }
- else
- {
- log.debug((_pingClientCount * _noOfConsumers) + " consumers per destination.");
-
- return _pingClientCount * _noOfConsumers;
- }
- }
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/ping/PingDurableClient.java b/java/perftests/src/main/java/org/apache/qpid/ping/PingDurableClient.java deleted file mode 100644 index 2750790354..0000000000 --- a/java/perftests/src/main/java/org/apache/qpid/ping/PingDurableClient.java +++ /dev/null @@ -1,451 +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.ping;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.requestreply.PingPongProducer;
-import org.apache.qpid.util.CommandLineParser;
-
-import uk.co.thebadgerset.junit.extensions.util.MathUtils;
-import uk.co.thebadgerset.junit.extensions.util.ParsedProperties;
-
-import javax.jms.*;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.util.List;
-import java.util.Properties;
-import java.util.concurrent.atomic.AtomicInteger;
-
-/**
- * PingDurableClient is a variation of the {@link PingPongProducer} ping tool. Instead of sending its pings and
- * receiving replies to them at the same time, this tool sends pings until it is signalled by some 'event' to stop
- * sending. It then waits for another signal before it re-opens a fresh connection and attempts to receive all of the
- * pings that it has succesfully sent. It is intended to be an interactive test that lets a user experiment with
- * failure conditions when using durable messaging.
- *
- * <p/>The events that can stop it from sending are input from the user on the console, failure of its connection to
- * the broker, completion of sending a specified number of messages, or expiry of a specified duration. In all cases
- * it will do its best to clean up and close the connection before opening a fresh connection to receive the pings
- * with.
- *
- * <p/>The event to re-connect and attempt to recieve the pings is input from the user on the console.
- *
- * <p/>This ping client inherits the configuration properties of its parent class ({@link PingPongProducer}) and
- * additionally accepts the following parameters:
- *
- * <p/><table><caption>Parameters</caption>
- * <tr><th> Parameter <th> Default <th> Comments
- * <tr><td> numMessages <td> 100 <td> The total number of messages to send.
- * <tr><td> numMessagesToAction <td> -1 <td> The number of messages to send before taking a custom 'action'.
- * <tr><td> duration <td> 30S <td> The length of time to ping for. (Format dDhHmMsS, for d days, h hours,
- * m minutes and s seconds).
- * </table>
- *
- * <p/>This ping client also overrides some of the defaults of its parent class, to provide a reasonable set up
- * when no parameters are specified.
- *
- * <p/><table><caption>Parameters</caption>
- * <tr><th> Parameter <th> Default <th> Comments
- * <tr><td> uniqueDests <td> false <td> Prevents destination names being timestamped.
- * <tr><td> transacted <td> true <td> Only makes sense to test with transactions.
- * <tr><td> persistent <td> true <td> Only makes sense to test persistent.
- * <tr><td> durableDests <td> true <td> Should use durable queues with persistent messages.
- * <tr><td> commitBatchSize <td> 10
- * <tr><td> rate <td> 20 <td> Total default test time is 5 seconds.
- * </table>
- *
- * <p/>When a number of messages or duration is specified, this ping client will ping until the first of those limits
- * is reached. Reaching the limit will be interpreted as the first signal to stop sending, and the ping client will
- * wait for the second signal before receiving its pings.
- *
- * <p/>This class provides a mechanism for extensions to add arbitrary actions, after a particular number of messages
- * have been sent. When the number of messages equal the value set in the 'numMessagesToAction' property is method,
- * the {@link #takeAction} method is called. By default this does nothing, but extensions of this class can provide
- * custom behaviour with alternative implementations of this method (for example taking a backup).
- *
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Send and receive pings.
- * <tr><td> Accept user input to signal stop sending.
- * <tr><td> Accept user input to signal start receiving.
- * <tr><td> Provide feedback on pings sent versus pings received.
- * <tr><td> Provide extension point for arbitrary action on a particular message count.
- * </table>
- */
-public class PingDurableClient extends PingPongProducer implements ExceptionListener
-{
- private static final Logger log = Logger.getLogger(PingDurableClient.class);
-
- public static final String NUM_MESSAGES_PROPNAME = "numMessages";
- public static final String NUM_MESSAGES_DEFAULT = "100";
- public static final String DURATION_PROPNAME = "duration";
- public static final String DURATION_DEFAULT = "30S";
- public static final String NUM_MESSAGES_TO_ACTION_PROPNAME = "numMessagesToAction";
- public static final String NUM_MESSAGES_TO_ACTION_DEFAULT = "-1";
-
- /** The maximum length of time to wait whilst receiving pings before assuming that no more are coming. */
- private static final long TIME_OUT = 3000;
-
- static
- {
- defaults.setProperty(NUM_MESSAGES_PROPNAME, NUM_MESSAGES_DEFAULT);
- defaults.setProperty(DURATION_PROPNAME, DURATION_DEFAULT);
- defaults.setProperty(UNIQUE_DESTS_PROPNAME, "false");
- defaults.setProperty(TRANSACTED_PROPNAME, "true");
- defaults.setProperty(PERSISTENT_MODE_PROPNAME, "true");
- defaults.setProperty(TX_BATCH_SIZE_PROPNAME, "10");
- defaults.setProperty(RATE_PROPNAME, "20");
- defaults.setProperty(NUM_MESSAGES_TO_ACTION_PROPNAME, NUM_MESSAGES_TO_ACTION_DEFAULT);
- }
-
- /** Specifies the number of pings to send, if larger than 0. 0 means send until told to stop. */
- private int numMessages;
-
- /** Holds the number of messages to send before taking triggering the action. */
- private int numMessagesToAction;
-
- /** Sepcifies how long to ping for, if larger than 0. 0 means send until told to stop. */
- private long duration;
-
- /** Used to indciate that this application should terminate. Set by the shutdown hook. */
- private boolean terminate = false;
-
- /**
- * @throws Exception Any exceptions are allowed to fall through.
- */
- public PingDurableClient(Properties overrides) throws Exception
- {
- super(overrides);
- log.debug("public PingDurableClient(Properties overrides = " + overrides + "): called");
-
- // Extract the additional configuration parameters.
- ParsedProperties properties = new ParsedProperties(defaults);
- properties.putAll(overrides);
-
- numMessages = properties.getPropertyAsInteger(NUM_MESSAGES_PROPNAME);
- String durationSpec = properties.getProperty(DURATION_PROPNAME);
- numMessagesToAction = properties.getPropertyAsInteger(NUM_MESSAGES_TO_ACTION_PROPNAME);
-
- if (durationSpec != null)
- {
- duration = MathUtils.parseDuration(durationSpec) * 1000000;
- }
- }
-
- /**
- * Starts the ping/wait/receive process.
- *
- * @param args The command line arguments.
- */
- public static void main(String[] args)
- {
- try
- {
- // Create a ping producer overriding its defaults with all options passed on the command line.
- Properties options =
- CommandLineParser.processCommandLine(args, new CommandLineParser(new String[][] {}), System.getProperties());
- PingDurableClient pingProducer = new PingDurableClient(options);
-
- // Create a shutdown hook to terminate the ping-pong producer.
- Runtime.getRuntime().addShutdownHook(pingProducer.getShutdownHook());
-
- // Ensure that the ping pong producer is registered to listen for exceptions on the connection too.
- // pingProducer.getConnection().setExceptionListener(pingProducer);
-
- // Run the test procedure.
- int sent = pingProducer.send();
- pingProducer.closeConnection();
- pingProducer.waitForUser("Press return to begin receiving the pings.");
- pingProducer.receive(sent);
-
- System.exit(0);
- }
- catch (Exception e)
- {
- System.err.println(e.getMessage());
- log.error("Top level handler caught execption.", e);
- System.exit(1);
- }
- }
-
- /**
- * Performs the main test procedure implemented by this ping client. See the class level comment for details.
- */
- protected int send() throws Exception
- {
- log.debug("public void sendWaitReceive(): called");
-
- log.debug("duration = " + duration);
- log.debug("numMessages = " + numMessages);
-
- if (duration > 0)
- {
- System.out.println("Sending for up to " + (duration / 1000000000f) + " seconds.");
- }
-
- if (_rate > 0)
- {
- System.out.println("Sending at " + _rate + " messages per second.");
- }
-
- if (numMessages > 0)
- {
- System.out.println("Sending up to " + numMessages + " messages.");
- }
-
- // Establish the connection and the message producer.
- establishConnection(true, false);
- _connection.start();
-
- Message message = getTestMessage(getReplyDestinations().get(0), _messageSize, _persistent);
-
- // Send pings until a terminating condition is received.
- boolean endCondition = false;
- int messagesSent = 0;
- int messagesCommitted = 0;
- int messagesNotCommitted = 0;
- long start = System.nanoTime();
-
- // Clear console in.
- clearConsole();
-
- while (!endCondition)
- {
- boolean committed = false;
-
- try
- {
- committed = sendMessage(messagesSent, message) && _transacted;
-
- messagesSent++;
- messagesNotCommitted++;
-
- // Keep count of the number of messsages currently committed and pending commit.
- if (committed)
- {
- log.debug("Adding " + messagesNotCommitted + " messages to the committed count.");
- messagesCommitted += messagesNotCommitted;
- messagesNotCommitted = 0;
-
- System.out.println("Commited: " + messagesCommitted);
- }
- }
- catch (JMSException e)
- {
- log.debug("Got JMSException whilst sending.");
- _publish = false;
- }
-
- // Perform the arbitrary action if the number of messages sent has reached the right number.
- if (messagesSent == numMessagesToAction)
- {
- System.out.println("At action point, Messages sent = " + messagesSent + ", Messages Committed = "
- + messagesCommitted + ", Messages not Committed = " + messagesNotCommitted);
- takeAction();
- }
-
- // Determine if the end condition has been met, based on the number of messages, time passed, errors on
- // the connection or user input.
- long now = System.nanoTime();
-
- if ((duration != 0) && ((now - start) > duration))
- {
- System.out.println("Send halted because duration expired.");
- endCondition = true;
- }
- else if ((numMessages != 0) && (messagesSent >= numMessages))
- {
- System.out.println("Send halted because # messages completed.");
- endCondition = true;
- }
- else if (System.in.available() > 0)
- {
- System.out.println("Send halted by user input.");
- endCondition = true;
-
- clearConsole();
- }
- else if (!_publish)
- {
- System.out.println("Send halted by error on the connection.");
- endCondition = true;
- }
- }
-
- log.debug("messagesSent = " + messagesSent);
- log.debug("messagesCommitted = " + messagesCommitted);
- log.debug("messagesNotCommitted = " + messagesNotCommitted);
-
- System.out.println("Messages sent: " + messagesSent + ", Messages Committed = " + messagesCommitted
- + ", Messages not Committed = " + messagesNotCommitted);
-
- return messagesSent;
- }
-
- protected void closeConnection()
- {
- // Clean up the connection.
- try
- {
- close();
- }
- catch (JMSException e)
- {
- log.debug("There was an error whilst closing the connection: " + e, e);
- System.out.println("There was an error whilst closing the connection.");
-
- // Ignore as did best could manage to clean up.
- }
- }
-
- protected void receive(int messagesSent) throws Exception
- {
- // Re-establish the connection and the message consumer.
- _queueJVMSequenceID = new AtomicInteger();
- _queueSharedID = new AtomicInteger();
-
- establishConnection(false, true);
- _consumer[0].setMessageListener(null);
- _consumerConnection[0].start();
-
- // Try to receive all of the pings that were successfully sent.
- int messagesReceived = 0;
- boolean endCondition = false;
-
- while (!endCondition)
- {
- // Message received = _consumer.receiveNoWait();
- Message received = _consumer[0].receive(TIME_OUT);
- log.debug("received = " + received);
-
- if (received != null)
- {
- messagesReceived++;
- }
-
- // Determine if the end condition has been met, based on the number of messages and time passed since last
- // receiving a message.
- if (received == null)
- {
- System.out.println("Timed out.");
- endCondition = true;
- }
- else if (messagesReceived >= messagesSent)
- {
- System.out.println("Got all messages.");
- endCondition = true;
- }
- }
-
- // Ensure messages received are committed.
- if (_consTransacted)
- {
- try
- {
- _consumerSession[0].commit();
- System.out.println("Committed for all messages received.");
- }
- catch (JMSException e)
- {
- log.debug("Error during commit: " + e, e);
- System.out.println("Error during commit.");
- try
- {
- _consumerSession[0].rollback();
- System.out.println("Rolled back on all messages received.");
- }
- catch (JMSException e2)
- {
- log.debug("Error during rollback: " + e, e);
- System.out.println("Error on roll back of all messages received.");
- }
-
- }
- }
-
- log.debug("messagesReceived = " + messagesReceived);
-
- System.out.println("Messages received: " + messagesReceived);
-
- // Clean up the connection.
- close();
- }
-
- /**
- * Clears any pending input from the console.
- */
- private void clearConsole()
- {
- try
- {
- BufferedReader bis = new BufferedReader(new InputStreamReader(System.in));
-
- // System.in.skip(System.in.available());
- while (bis.ready())
- {
- bis.readLine();
- }
- }
- catch (IOException e)
- { }
- }
-
- /**
- * Returns the ping destinations themselves as the reply destinations for this pinger to listen to. This has the
- * effect of making this pinger listen to its own pings.
- *
- * @return The ping destinations.
- */
- public List<Destination> getReplyDestinations()
- {
- return _pingDestinations;
- }
-
- /**
- * Gets a shutdown hook that will cleanly shut this down when it is running the ping loop. This can be registered with
- * the runtime system as a shutdown hook. This shutdown hook sets an additional terminate flag, compared with the
- * shutdown hook in {@link PingPongProducer}, because the publish flag is used to indicate that sending or receiving
- * message should stop, not that the application should termiante.
- *
- * @return A shutdown hook for the ping loop.
- */
- public Thread getShutdownHook()
- {
- return new Thread(new Runnable()
- {
- public void run()
- {
- stop();
- terminate = true;
- }
- });
- }
-
- /**
- * Performs an aribtrary action once the 'numMesagesToAction' count is reached on sending messages. This default
- * implementation does nothing.
- */
- public void takeAction()
- { }
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/ping/PingLatencyTestPerf.java b/java/perftests/src/main/java/org/apache/qpid/ping/PingLatencyTestPerf.java deleted file mode 100644 index 55414664da..0000000000 --- a/java/perftests/src/main/java/org/apache/qpid/ping/PingLatencyTestPerf.java +++ /dev/null @@ -1,314 +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.ping; - -import junit.framework.Test; -import junit.framework.TestSuite; - -import org.apache.log4j.Logger; - -import org.apache.qpid.client.AMQSession; -import org.apache.qpid.client.message.AMQMessage; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.requestreply.PingPongProducer; - -import uk.co.thebadgerset.junit.extensions.TimingController; -import uk.co.thebadgerset.junit.extensions.TimingControllerAware; -import uk.co.thebadgerset.junit.extensions.util.ParsedProperties; - -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.ObjectMessage; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.atomic.AtomicLong; - -/** - * PingLatencyTestPerf is a performance test that outputs multiple timings from its test method, using the timing - * controller interface supplied by the test runner from a seperate listener thread. It outputs round trip timings for - * individual ping messages rather than for how long a complete batch of messages took to process. It also differs from - * the {@link PingTestPerf} test that it extends because it can output timings as replies are received, rather than - * waiting until all expected replies are received. - * - * <p/>This test does not output timings for every single ping message, as when running at high volume, writing the test - * log for a vast number of messages would slow the testing down. Instead samples ping latency occasionally. The - * frequency of ping sampling is set using the {@link #TEST_RESULTS_BATCH_SIZE_PROPNAME} property, to override the - * default of every {@link #DEFAULT_TEST_RESULTS_BATCH_SIZE}. - * - * <p/>The size parameter logged for each individual ping is set to the size of the batch of messages that the - * individual timed ping was taken from, rather than 1 for a single message. This is so that the total throughput - * (messages / time) can be calculated in order to examine the relationship between throughput and latency. - * - * <p/><table id="crc"><caption>CRC Card</caption> <tr><td> Responsibilities <th> Collaborations <tr><td> Send many ping - * messages and output timings for sampled individual pings. </table> - */ -public class PingLatencyTestPerf extends PingTestPerf implements TimingControllerAware -{ - private static Logger _logger = Logger.getLogger(PingLatencyTestPerf.class); - - /** Holds the name of the property to get the test results logging batch size. */ - public static final String TEST_RESULTS_BATCH_SIZE_PROPNAME = "batchSize"; - - /** Holds the default test results logging batch size. */ - public static final int DEFAULT_TEST_RESULTS_BATCH_SIZE = 1000; - - /** Used to hold the timing controller passed from the test runner. */ - private TimingController _timingController; - - /** Used to generate unique correlation ids for each test run. */ - private AtomicLong corellationIdGenerator = new AtomicLong(); - - /** - * Holds test specifics by correlation id. This consists of the expected number of messages and the timing - * controler. - */ - private Map<String, PerCorrelationId> perCorrelationIds = - Collections.synchronizedMap(new HashMap<String, PerCorrelationId>()); - - /** Holds the batched results listener, that does logging on batch boundaries. */ - private BatchedResultsListener batchedResultsListener = null; - - /** - * Creates a new asynchronous ping performance test with the specified name. - * - * @param name The test name. - */ - public PingLatencyTestPerf(String name) - { - super(name); - - // Sets up the test parameters with defaults. - ParsedProperties.setSysPropertyIfNull(TEST_RESULTS_BATCH_SIZE_PROPNAME, - Integer.toString(DEFAULT_TEST_RESULTS_BATCH_SIZE)); - } - - /** Compile all the tests into a test suite. */ - public static Test suite() - { - // Build a new test suite - TestSuite suite = new TestSuite("Ping Latency Tests"); - - // Run performance tests in read committed mode. - suite.addTest(new PingLatencyTestPerf("testPingLatency")); - - return suite; - } - - /** - * Accepts a timing controller from the test runner. - * - * @param timingController The timing controller to register mutliple timings with. - */ - public void setTimingController(TimingController timingController) - { - _timingController = timingController; - } - - /** - * Gets the timing controller passed in by the test runner. - * - * @return The timing controller passed in by the test runner. - */ - public TimingController getTimingController() - { - return _timingController; - } - - /** - * Sends the specified number of pings, asynchronously outputs timings on every batch boundary, and waits until all - * replies have been received or a time out occurs before exiting this method. - * - * @param numPings The number of pings to send. - */ - public void testPingLatency(int numPings) throws Exception - { - _logger.debug("public void testPingLatency(int numPings): called"); - - // Ensure that at least one ping was requeusted. - if (numPings == 0) - { - _logger.error("Number of pings requested was zero."); - } - - // Get the per thread test setup to run the test through. - PerThreadSetup perThreadSetup = threadSetup.get(); - PingClient pingClient = perThreadSetup._pingClient; - - // Advance the correlation id of messages to send, to make it unique for this run. - String messageCorrelationId = Long.toString(corellationIdGenerator.incrementAndGet()); - _logger.debug("messageCorrelationId = " + messageCorrelationId); - - // Initialize the count and timing controller for the new correlation id. - PerCorrelationId perCorrelationId = new PerCorrelationId(); - TimingController tc = getTimingController().getControllerForCurrentThread(); - perCorrelationId._tc = tc; - perCorrelationId._expectedCount = numPings; - perCorrelationIds.put(messageCorrelationId, perCorrelationId); - - // Attach the chained message listener to the ping producer to listen asynchronously for the replies to these - // messages. - pingClient.setChainedMessageListener(batchedResultsListener); - - // Generate a sample message of the specified size. - Message msg = - pingClient.getTestMessage(perThreadSetup._pingClient.getReplyDestinations().get(0), - testParameters.getPropertyAsInteger(PingPongProducer.MESSAGE_SIZE_PROPNAME), - testParameters.getPropertyAsBoolean(PingPongProducer.PERSISTENT_MODE_PROPNAME)); - - // Send the requested number of messages, and wait until they have all been received. - long timeout = Long.parseLong(testParameters.getProperty(PingPongProducer.TIMEOUT_PROPNAME)); - int numReplies = pingClient.pingAndWaitForReply(msg, numPings, timeout, null); - - // Check that all the replies were received and log a fail if they were not. - if (numReplies < numPings) - { - tc.completeTest(false, 0); - } - - // Remove the chained message listener from the ping producer. - pingClient.removeChainedMessageListener(); - - // Remove the expected count and timing controller for the message correlation id, to ensure they are cleaned up. - perCorrelationIds.remove(messageCorrelationId); - } - - /** Performs test fixture creation on a per thread basis. This will only be called once for each test thread. */ - public void threadSetUp() - { - _logger.debug("public void threadSetUp(): called"); - - try - { - // Call the set up method in the super class. This creates a PingClient pinger. - super.threadSetUp(); - - // Create the chained message listener, only if it has not already been created. This is set up with the - // batch size property, to tell it what batch size to output results on. A synchronized block is used to - // ensure that only one thread creates this. - synchronized (this) - { - if (batchedResultsListener == null) - { - int batchSize = Integer.parseInt(testParameters.getProperty(TEST_RESULTS_BATCH_SIZE_PROPNAME)); - batchedResultsListener = new BatchedResultsListener(batchSize); - } - } - - // Get the set up that the super class created. - PerThreadSetup perThreadSetup = threadSetup.get(); - - // Register the chained message listener on the pinger to do its asynchronous test timings from. - perThreadSetup._pingClient.setChainedMessageListener(batchedResultsListener); - } - catch (Exception e) - { - _logger.warn("There was an exception during per thread setup.", e); - } - } - - /** - * BatchedResultsListener is a {@link org.apache.qpid.requestreply.PingPongProducer.ChainedMessageListener} that can - * be attached to the pinger, in order to receive notifications about every message received and the number - * remaining to be received. Whenever the number remaining crosses a batch size boundary this results listener - * outputs a test timing for the actual number of messages received in the current batch. - */ - private class BatchedResultsListener implements PingPongProducer.ChainedMessageListener - { - /** The test results logging batch size. */ - int _batchSize; - private boolean _strictAMQP; - - /** - * Creates a results listener on the specified batch size. - * - * @param batchSize The batch size to use. - */ - public BatchedResultsListener(int batchSize) - { - _batchSize = batchSize; - _strictAMQP = - Boolean.parseBoolean(System.getProperties().getProperty(AMQSession.STRICT_AMQP, - AMQSession.STRICT_AMQP_DEFAULT)); - } - - /** - * This callback method is called from all of the pingers that this test creates. It uses the correlation id - * from the message to identify the timing controller for the test thread that was responsible for sending those - * messages. - * - * @param message The message. - * @param remainingCount The count of messages remaining to be received with a particular correlation id. - * - * @throws javax.jms.JMSException Any underlying JMSException is allowed to fall through. - */ - public void onMessage(Message message, int remainingCount, long latency) throws JMSException - { - _logger.debug("public void onMessage(Message message, int remainingCount = " + remainingCount + "): called"); - - // Check if a batch boundary has been crossed. - if ((remainingCount % _batchSize) == 0) - { - // Extract the correlation id from the message. - String correlationId = message.getJMSCorrelationID(); - - // Get the details for the correlation id and check that they are not null. They can become null - // if a test times out. - PerCorrelationId perCorrelationId = perCorrelationIds.get(correlationId); - if (perCorrelationId != null) - { - // Get the timing controller and expected count for this correlation id. - TimingController tc = perCorrelationId._tc; - int expected = perCorrelationId._expectedCount; - - // Calculate how many messages were actually received in the last batch. This will be the batch size - // except where the number expected is not a multiple of the batch size and this is the first remaining - // count to cross a batch size boundary, in which case it will be the number expected modulo the batch - // size. - int receivedInBatch = ((expected - remainingCount) < _batchSize) ? (expected % _batchSize) : _batchSize; - - // Register a test result for the correlation id. - try - { - tc.completeTest(true, receivedInBatch, latency); - } - catch (InterruptedException e) - { - // Ignore this. It means the test runner wants to stop as soon as possible. - _logger.warn("Got InterruptedException.", e); - } - } - // Else ignore, test timed out. Should log a fail here? - } - } - } - - /** - * Holds state specific to each correlation id, needed to output test results. This consists of the count of the - * total expected number of messages, and the timing controller for the thread sending those message ids. - */ - private static class PerCorrelationId - { - public int _expectedCount; - public TimingController _tc; - } -} diff --git a/java/perftests/src/main/java/org/apache/qpid/ping/PingSendOnlyClient.java b/java/perftests/src/main/java/org/apache/qpid/ping/PingSendOnlyClient.java deleted file mode 100644 index 150f7c0d52..0000000000 --- a/java/perftests/src/main/java/org/apache/qpid/ping/PingSendOnlyClient.java +++ /dev/null @@ -1,92 +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.ping;
-
-import java.util.Properties;
-
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.Message;
-
-import org.apache.log4j.Logger;
-
-import org.apache.qpid.client.message.TestMessageFactory;
-import org.apache.qpid.util.CommandLineParser;
-
-/**
- * <p><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * </table>
- */
-public class PingSendOnlyClient extends PingDurableClient
-{
- private static final Logger log = Logger.getLogger(PingSendOnlyClient.class);
-
- public PingSendOnlyClient(Properties overrides) throws Exception
- {
- super(overrides);
- }
-
- /**
- * Starts the ping/wait/receive process.
- *
- * @param args The command line arguments.
- */
- public static void main(String[] args)
- {
- try
- {
- // Create a ping producer overriding its defaults with all options passed on the command line.
- Properties options = CommandLineParser.processCommandLine(args, new CommandLineParser(new String[][] {}), System.getProperties());
- PingSendOnlyClient pingProducer = new PingSendOnlyClient(options);
-
- // Create a shutdown hook to terminate the ping-pong producer.
- Runtime.getRuntime().addShutdownHook(pingProducer.getShutdownHook());
-
- // Ensure that the ping pong producer is registered to listen for exceptions on the connection too.
- // pingProducer.getConnection().setExceptionListener(pingProducer);
-
- // Run the test procedure.
- int sent = pingProducer.send();
- pingProducer.waitForUser("Press return to close connection and quit.");
- pingProducer.closeConnection();
-
- System.exit(0);
- }
- catch (Exception e)
- {
- System.err.println(e.getMessage());
- log.error("Top level handler caught execption.", e);
- System.exit(1);
- }
- }
-
- public Message getTestMessage(Destination replyQueue, int messageSize, boolean persistent) throws JMSException
- {
- Message msg = TestMessageFactory.newTextMessage(_producerSession, messageSize);
-
- // Timestamp the message in nanoseconds.
- msg.setLongProperty(MESSAGE_TIMESTAMP_PROPNAME, System.nanoTime());
-
- return msg;
- }
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/ping/PingTestPerf.java b/java/perftests/src/main/java/org/apache/qpid/ping/PingTestPerf.java deleted file mode 100644 index 375007584b..0000000000 --- a/java/perftests/src/main/java/org/apache/qpid/ping/PingTestPerf.java +++ /dev/null @@ -1,196 +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.ping; - -import junit.framework.Assert; -import junit.framework.Test; -import junit.framework.TestSuite; - -import org.apache.log4j.Logger; - -import org.apache.qpid.requestreply.PingPongProducer; - -import uk.co.thebadgerset.junit.extensions.AsymptoticTestCase; -import uk.co.thebadgerset.junit.extensions.TestThreadAware; -import uk.co.thebadgerset.junit.extensions.util.ParsedProperties; -import uk.co.thebadgerset.junit.extensions.util.TestContextProperties; - -import javax.jms.*; - -/** - * PingTestPerf is a ping test, that has been written with the intention of being scaled up to run many times - * simultaneously to simluate many clients/producers/connections. - * - * <p/>A single run of the test using the default JUnit test runner will result in the sending and timing of a single - * full round trip ping. This test may be scaled up using a suitable JUnit test runner. - * - * <p/>The setup/teardown cycle establishes a connection to a broker and sets up a queue to send ping messages to and a - * temporary queue for replies. This setup is only established once for all the test repeats/threads that may be run, - * except if the connection is lost in which case an attempt to re-establish the setup is made. - * - * <p/>The test cycle is: Connects to a queue, creates a temporary queue, creates messages containing a property that - * is the name of the temporary queue, fires off a message on the original queue and waits for a response on the - * temporary queue. - * - * <p/>Configurable test properties: message size, transacted or not, persistent or not. Broker connection details. - * - * <p><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * </table> - */ -public class PingTestPerf extends AsymptoticTestCase implements TestThreadAware -{ - private static Logger _logger = Logger.getLogger(PingTestPerf.class); - - /** Thread local to hold the per-thread test setup fields. */ - ThreadLocal<PerThreadSetup> threadSetup = new ThreadLocal<PerThreadSetup>(); - - /** Holds a property reader to extract the test parameters from. */ - protected ParsedProperties testParameters = - TestContextProperties.getInstance(PingPongProducer.defaults /*System.getProperties()*/); - - public PingTestPerf(String name) - { - super(name); - - _logger.debug("testParameters = " + testParameters); - } - - /** - * Compile all the tests into a test suite. - * @return The test method testPingOk. - */ - public static Test suite() - { - // Build a new test suite - TestSuite suite = new TestSuite("Ping Performance Tests"); - - // Run performance tests in read committed mode. - suite.addTest(new PingTestPerf("testPingOk")); - - return suite; - } - - public void testPingOk(int numPings) throws Exception - { - if (numPings == 0) - { - Assert.fail("Number of pings requested was zero."); - } - - // Get the per thread test setup to run the test through. - PerThreadSetup perThreadSetup = threadSetup.get(); - - if (perThreadSetup == null) - { - Assert.fail("Could not get per thread test setup, it was null."); - } - - // Generate a sample message. This message is already time stamped and has its reply-to destination set. - Message msg = - perThreadSetup._pingClient.getTestMessage(perThreadSetup._pingClient.getReplyDestinations().get(0), - testParameters.getPropertyAsInteger(PingPongProducer.MESSAGE_SIZE_PROPNAME), - testParameters.getPropertyAsBoolean(PingPongProducer.PERSISTENT_MODE_PROPNAME)); - - // start the test - long timeout = Long.parseLong(testParameters.getProperty(PingPongProducer.TIMEOUT_PROPNAME)); - int numReplies = perThreadSetup._pingClient.pingAndWaitForReply(msg, numPings, timeout, null); - - // Fail the test if the timeout was exceeded. - if (numReplies != perThreadSetup._pingClient.getExpectedNumPings(numPings)) - { - Assert.fail("The ping timed out after " + timeout + " ms. Messages Sent = " + numPings + ", MessagesReceived = " - + numReplies); - } - } - - /** - * Performs test fixture creation on a per thread basis. This will only be called once for each test thread. - */ - public void threadSetUp() - { - _logger.debug("public void threadSetUp(): called"); - - try - { - PerThreadSetup perThreadSetup = new PerThreadSetup(); - - // This is synchronized because there is a race condition, which causes one connection to sleep if - // all threads try to create connection concurrently. - synchronized (this) - { - // Establish a client to ping a Destination and listen the reply back from same Destination - perThreadSetup._pingClient = new PingClient(testParameters); - perThreadSetup._pingClient.establishConnection(true, true); - } - // Start the client connection - perThreadSetup._pingClient.start(); - - // Attach the per-thread set to the thread. - threadSetup.set(perThreadSetup); - } - catch (Exception e) - { - _logger.warn("There was an exception during per thread setup.", e); - } - } - - /** - * Performs test fixture clean - */ - public void threadTearDown() - { - _logger.debug("public void threadTearDown(): called"); - - try - { - // Get the per thread test fixture. - PerThreadSetup perThreadSetup = threadSetup.get(); - - // Close the pingers so that it cleans up its connection cleanly. - synchronized (this) - { - if ((perThreadSetup != null) && (perThreadSetup._pingClient != null)) - { - perThreadSetup._pingClient.close(); - } - } - } - catch (JMSException e) - { - _logger.warn("There was an exception during per thread tear down."); - } - finally - { - // Ensure the per thread fixture is reclaimed. - threadSetup.remove(); - } - } - - protected static class PerThreadSetup - { - /** - * Holds the test ping client. - */ - protected PingClient _pingClient; - protected String _correlationId; - } -} diff --git a/java/perftests/src/main/java/org/apache/qpid/requestreply/InitialContextHelper.java b/java/perftests/src/main/java/org/apache/qpid/requestreply/InitialContextHelper.java deleted file mode 100644 index b684fd6b9b..0000000000 --- a/java/perftests/src/main/java/org/apache/qpid/requestreply/InitialContextHelper.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.requestreply; - -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.naming.NamingException; -import java.util.Properties; -import java.io.InputStream; -import java.io.IOException; - -/** - * - * - */ -public class InitialContextHelper -{ - - public static Context getInitialContext(String propertyFile) throws IOException, NamingException - { - if ((propertyFile == null) || (propertyFile.length() == 0)) - { - propertyFile = "/perftests.properties"; - } - - Properties fileProperties = new Properties(); - ClassLoader cl = Thread.currentThread().getContextClassLoader(); - // NB: Need to change path to reflect package if moving classes around ! - InputStream is = cl.getResourceAsStream(propertyFile); - if( is != null ) - { - fileProperties.load(is); - return new InitialContext(fileProperties); - } - else - { - return new InitialContext(); - } - } -} diff --git a/java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongBouncer.java b/java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongBouncer.java deleted file mode 100644 index 8bcbdbd369..0000000000 --- a/java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongBouncer.java +++ /dev/null @@ -1,392 +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.requestreply; - -import java.io.IOException; -import java.net.InetAddress; -import java.text.SimpleDateFormat; -import java.util.Date; - -import javax.jms.*; -import javax.naming.Context; - -import org.apache.log4j.Logger; - -/** - * PingPongBouncer is a message listener the bounces back messages to their reply to destination. This is used to return - * ping messages generated by {@link org.apache.qpid.requestreply.PingPongProducer} but could be used for other purposes - * too. - * <p/> - * <p/>The correlation id from the received message is extracted, and placed into the reply as the correlation id. Messages - * are bounced back to their reply-to destination. The original sender of the message has the option to use either a unique - * temporary queue or the correlation id to correlate the original message to the reply. - * <p/> - * <p/>There is a verbose mode flag which causes information about each ping to be output to the console - * (info level logging, so usually console). This can be helpfull to check the bounce backs are happening but should - * be disabled for real timing tests as writing to the console will slow things down. - * <p/> - * <p><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Bounce back messages to their reply to destination. - * <tr><td> Provide command line invocation to start the bounce back on a configurable broker url. - * </table> - * - * @todo Replace the command line parsing with a neater tool. - * @todo Make verbose accept a number of messages, only prints to console every X messages. - */ -public class PingPongBouncer implements MessageListener -{ - private static final Logger _logger = Logger.getLogger(PingPongBouncer.class); - - /** - * The default prefetch size for the message consumer. - */ - private static final int PREFETCH = 1; - - /** - * The default no local flag for the message consumer. - */ - private static final boolean NO_LOCAL = true; - - private static final String DEFAULT_DESTINATION_NAME = "ping"; - - /** - * The default exclusive flag for the message consumer. - */ - private static final boolean EXCLUSIVE = false; - - /** - * A convenient formatter to use when time stamping output. - */ - protected static final SimpleDateFormat timestampFormatter = new SimpleDateFormat("hh:mm:ss:SS"); - - /** - * Used to indicate that the reply generator should log timing info to the console (logger info level). - */ - private boolean _verbose = false; - - /** - * Determines whether this bounce back client bounces back messages persistently. - */ - private boolean _persistent = false; - - private Destination _consumerDestination; - - /** - * Keeps track of the response destination of the previous message for the last reply to producer cache. - */ - private Destination _lastResponseDest; - - /** - * The producer for sending replies with. - */ - private MessageProducer _replyProducer; - - /** - * The consumer controlSession. - */ - private Session _consumerSession; - - /** - * The producer controlSession. - */ - private Session _producerSession; - - /** - * Holds the connection to the broker. - */ - private Connection _connection; - - /** - * Flag used to indicate if this is a point to point or pub/sub ping client. - */ - private boolean _isPubSub = false; - - /** - * This flag is used to indicate that the user should be prompted to kill a broker, in order to test - * failover, immediately before committing a transaction. - */ - protected boolean _failBeforeCommit = false; - - /** - * This flag is used to indicate that the user should be prompted to a kill a broker, in order to test - * failover, immediate after committing a transaction. - */ - protected boolean _failAfterCommit = false; - - /** - * Creates a PingPongBouncer on the specified producer and consumer sessions. - * - * @param fileProperties The path to the file properties - * @param factoryName The factory name - * @param username The broker username. - * @param password The broker password. - * @param destinationName The name of the queue to receive pings on - * (or root of the queue name where many queues are generated). - * @param persistent A flag to indicate that persistent message should be used. - * @param transacted A flag to indicate that pings should be sent within transactions. - * @param selector A message selector to filter received pings with. - * @param verbose A flag to indicate that message timings should be sent to the console. - * @throws Exception All underlying exceptions allowed to fall through. This is only test code... - */ - public PingPongBouncer(String fileProperties, String factoryName, String username, String password, - String destinationName, boolean persistent, boolean transacted, - String selector, boolean verbose, boolean pubsub) throws Exception - { - // Create a client id to uniquely identify this client. - InetAddress address = InetAddress.getLocalHost(); - String clientId = address.getHostName() + System.currentTimeMillis(); - _verbose = verbose; - _persistent = persistent; - setPubSub(pubsub); - // Connect to the broker. - Context context = InitialContextHelper.getInitialContext(fileProperties); - ConnectionFactory factory = (ConnectionFactory) context.lookup(factoryName); - setConnection(factory.createConnection(username, password)); - - // Create a controlSession to listen for messages on and one to send replies on, transactional depending on the - // command line option. - _consumerSession = (Session) getConnection().createSession(transacted, Session.AUTO_ACKNOWLEDGE); - _producerSession = (Session) getConnection().createSession(transacted, Session.AUTO_ACKNOWLEDGE); - - // Create the queue to listen for message on. - createConsumerDestination(destinationName); - MessageConsumer consumer = _consumerSession.createConsumer(_consumerDestination, selector, NO_LOCAL); - - // Create a producer for the replies, without a default destination. - _replyProducer = _producerSession.createProducer(null); - _replyProducer.setDisableMessageTimestamp(true); - _replyProducer.setDeliveryMode(_persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT); - - // Set this up to listen for messages on the queue. - consumer.setMessageListener(this); - } - - private static void usage() - { - System.err.println( - "Usage: PingPongBouncer \n" + "-host : broker host\n" + "-port : broker port\n" + "-destinationname : queue/topic name\n" + "-transacted : (true/false). Default is false\n" + "-persistent : (true/false). Default is false\n" + "-pubsub : (true/false). Default is false\n" + "-selector : selector string\n"); - } - - /** - * This is a callback method that is notified of all messages for which this has been registered as a message - * listener on a message consumer. It sends a reply (pong) to all messages it receieves on the reply to - * destination of the message. - * - * @param message The message that triggered this callback. - */ - public void onMessage(Message message) - { - try - { - String messageCorrelationId = message.getJMSCorrelationID(); - if (_verbose) - { - _logger.info(timestampFormatter - .format(new Date()) + ": Got ping with correlation id, " + messageCorrelationId); - } - - // Get the reply to destination from the message and check it is set. - Destination responseDest = message.getJMSReplyTo(); - - if (responseDest == null) - { - _logger.debug("Cannot send reply because reply-to destination is null."); - - return; - } - - // Spew out some timing information if verbose mode is on. - if (_verbose) - { - Long timestamp = message.getLongProperty("timestamp"); - - if (timestamp != null) - { - long diff = System.currentTimeMillis() - timestamp; - _logger.info("Time to bounce point: " + diff); - } - } - - // Correlate the reply to the original. - message.setJMSCorrelationID(messageCorrelationId); - - // Send the receieved message as the pong reply. - _replyProducer.send(responseDest, message); - - if (_verbose) - { - _logger.info(timestampFormatter - .format(new Date()) + ": Sent reply with correlation id, " + messageCorrelationId); - } - - // Commit the transaction if running in transactional mode. - commitTx(_producerSession); - } - catch (JMSException e) - { - _logger.debug("There was a JMSException: " + e.getMessage(), e); - } - } - - /** - * Gets the underlying connection that this ping client is running on. - * - * @return The underlying connection that this ping client is running on. - */ - public Connection getConnection() - { - return _connection; - } - - /** - * Sets the connection that this ping client is using. - * - * @param connection The ping connection. - */ - public void setConnection(Connection connection) - { - this._connection = connection; - } - - /** - * Sets or clears the pub/sub flag to indiciate whether this client is pinging a queue or a topic. - * - * @param pubsub <tt>true</tt> if this client is pinging a topic, <tt>false</tt> if it is pinging a queue. - */ - public void setPubSub(boolean pubsub) - { - _isPubSub = pubsub; - } - - /** - * Checks whether this client is a p2p or pub/sub ping client. - * - * @return <tt>true</tt> if this client is pinging a topic, <tt>false</tt> if it is pinging a queue. - */ - public boolean isPubSub() - { - return _isPubSub; - } - - /** - * Convenience method to commit the transaction on the specified controlSession. If the controlSession to commit on is not - * a transactional controlSession, this method does nothing. - * <p/> - * <p/>If the {@link #_failBeforeCommit} flag is set, this will prompt the user to kill the broker before the - * commit is applied. If the {@link #_failAfterCommit} flag is set, this will prompt the user to kill the broker - * after the commit is applied. - * - * @throws javax.jms.JMSException If the commit fails and then the rollback fails. - */ - protected void commitTx(Session session) throws JMSException - { - if (session.getTransacted()) - { - try - { - if (_failBeforeCommit) - { - _logger.trace("Failing Before Commit"); - doFailover(); - } - - session.commit(); - - if (_failAfterCommit) - { - _logger.trace("Failing After Commit"); - doFailover(); - } - - _logger.trace("Session Commited."); - } - catch (JMSException e) - { - _logger.trace("JMSException on commit:" + e.getMessage(), e); - - try - { - session.rollback(); - _logger.debug("Message rolled back."); - } - catch (JMSException jmse) - { - _logger.trace("JMSE on rollback:" + jmse.getMessage(), jmse); - - // Both commit and rollback failed. Throw the rollback exception. - throw jmse; - } - } - } - } - - /** - * Prompts the user to terminate the named broker, in order to test failover functionality. This method will block - * until the user supplied some input on the terminal. - * - * @param broker The name of the broker to terminate. - */ - protected void doFailover(String broker) - { - System.out.println("Kill Broker " + broker + " now."); - try - { - System.in.read(); - } - catch (IOException e) - { - } - - System.out.println("Continuing."); - } - - /** - * Prompts the user to terminate the broker, in order to test failover functionality. This method will block - * until the user supplied some input on the terminal. - */ - protected void doFailover() - { - System.out.println("Kill Broker now."); - try - { - System.in.read(); - } - catch (IOException e) - { - } - - System.out.println("Continuing."); - - } - - private void createConsumerDestination(String name) throws JMSException - { - if (isPubSub()) - { - _consumerDestination = _consumerSession.createTopic(name); - } - else - { - _consumerDestination = _consumerSession.createQueue(name); - } - } -} diff --git a/java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongProducer.java b/java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongProducer.java deleted file mode 100644 index da6d6eb7d0..0000000000 --- a/java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongProducer.java +++ /dev/null @@ -1,1717 +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.requestreply;
-
-import org.apache.log4j.Logger;
-import org.apache.log4j.NDC;
-
-import org.apache.qpid.test.framework.TestUtils;
-
-import uk.co.thebadgerset.junit.extensions.BatchedThrottle;
-import uk.co.thebadgerset.junit.extensions.Throttle;
-import uk.co.thebadgerset.junit.extensions.util.CommandLineParser;
-import uk.co.thebadgerset.junit.extensions.util.ParsedProperties;
-
-import javax.jms.*;
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-
-import java.io.*;
-import java.net.InetAddress;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.*;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.SynchronousQueue;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.atomic.AtomicLong;
-
-/**
- * PingPongProducer is a client that sends test messages, and waits for replies to these messages. The replies may
- * either be generated by another client (see {@link PingPongBouncer}, or an extension of it may be used that listens
- * to its own messages and does not send replies (see {@link org.apache.qpid.ping.PingClient}). The intention of ping
- * pong producer is that it is a swiss-army knife test client that makes almost every aspect of its behaviour
- * configurable.
- *
- * <p/>The pings are sent with a reply-to field set to a single temporary queue, which is the same for all pings. This
- * means that this class has to do some work to correlate pings with pongs; it expectes the original message correlation
- * id in the ping to be bounced back in the reply correlation id.
- *
- * <p/>This ping tool accepts a vast number of configuration options, all of which are passed in to the constructor. It
- * can ping topics or queues; ping multiple destinations; do persistent pings; send messages of any size; do pings within
- * transactions; control the number of pings to send in each transaction; limit its sending rate; and perform failover
- * testing. A complete list of accepted parameters, default values and comments on their usage is provided here:
- *
- * <p/><table><caption>Parameters</caption>
- * <tr><th> Parameter <th> Default <th> Comments
- * <tr><td> messageSize <td> 0 <td> Message size in bytes. Not including any headers.
- * <tr><td> destinationName <td> ping <td> The root name to use to generate destination names to ping.
- * <tr><td> persistent <td> false <td> Determines whether peristent delivery is used.
- * <tr><td> transacted <td> false <td> Determines whether messages are sent/received in transactions.
- * <tr><td> broker <td> tcp://localhost:5672 <td> Determines the broker to connect to.
- * <tr><td> virtualHost <td> test <td> Determines the virtual host to send all ping over.
- * <tr><td> rate <td> 0 <td> The maximum rate (in hertz) to send messages at. 0 means no limit.
- * <tr><td> verbose <td> false <td> The verbose flag for debugging. Prints to console on every message.
- * <tr><td> pubsub <td> false <td> Whether to ping topics or queues. Uses p2p by default.
- * <tr><td> failAfterCommit <td> false <td> Whether to prompt user to kill broker after a commit batch.
- * <tr><td> failBeforeCommit <td> false <td> Whether to prompt user to kill broker before a commit batch.
- * <tr><td> failAfterSend <td> false <td> Whether to prompt user to kill broker after a send.
- * <tr><td> failBeforeSend <td> false <td> Whether to prompt user to kill broker before a send.
- * <tr><td> failOnce <td> true <td> Whether to prompt for failover only once.
- * <tr><td> username <td> guest <td> The username to access the broker with.
- * <tr><td> password <td> guest <td> The password to access the broker with.
- * <tr><td> selector <td> null <td> Not used. Defines a message selector to filter pings with.
- * <tr><td> destinationCount <td> 1 <td> The number of destinations to send pings to.
- * <tr><td> numConsumers <td> 1 <td> The number of consumers on each destination.
- * <tr><td> timeout <td> 30000 <td> In milliseconds. The timeout to stop waiting for replies.
- * <tr><td> commitBatchSize <td> 1 <td> The number of messages per transaction in transactional mode.
- * <tr><td> uniqueDests <td> true <td> Whether each receivers only listens to one ping destination or all.
- * <tr><td> durableDests <td> false <td> Whether or not durable destinations are used.
- * <tr><td> ackMode <td> AUTO_ACK <td> The message acknowledgement mode. Possible values are:
- * 0 - SESSION_TRANSACTED
- * 1 - AUTO_ACKNOWLEDGE
- * 2 - CLIENT_ACKNOWLEDGE
- * 3 - DUPS_OK_ACKNOWLEDGE
- * 257 - NO_ACKNOWLEDGE
- * 258 - PRE_ACKNOWLEDGE
- * <tr><td> consTransacted <td> false <td> Whether or not consumers use transactions. Defaults to the same value
- * as the 'transacted' option if not seperately defined.
- * <tr><td> consAckMode <td> AUTO_ACK <td> The message acknowledgement mode for consumers. Defaults to the same
- * value as 'ackMode' if not seperately defined.
- * <tr><td> maxPending <td> 0 <td> The maximum size in bytes, of messages sent but not yet received.
- * Limits the volume of messages currently buffered on the client
- * or broker. Can help scale test clients by limiting amount of buffered
- * data to avoid out of memory errors.
- * </table>
- *
- * <p/>This implements the Runnable interface with a run method that implements an infinite ping loop. The ping loop
- * does all its work through helper methods, so that code wishing to run a ping-pong cycle is not forced to do so by
- * starting a new thread. The command line invocation does take advantage of this ping loop. A shutdown hook is also
- * registered to terminate the ping-pong loop cleanly.
- *
- * <p/><table id="crc"><caption>CRC Card</caption>
- * <tr><th> Responsibilities <th> Collaborations
- * <tr><td> Provide a ping and wait for all responses cycle.
- * <tr><td> Provide command line invocation to loop the ping cycle on a configurable broker url.
- * </table>
- *
- * @todo Use read/write lock in the onmessage, not for reading writing but to make use of a shared and exlcusive lock pair.
- * Obtain read lock on all messages, before decrementing the message count. At the end of the on message method add a
- * block that obtains the write lock for the very last message, releases any waiting producer. Means that the last
- * message waits until all other messages have been handled before releasing producers but allows messages to be
- * processed concurrently, unlike the current synchronized block.
- */
-public class PingPongProducer implements Runnable, ExceptionListener
-{
- /** Used for debugging. */
- private static final Logger log = Logger.getLogger(PingPongProducer.class);
-
- /** Holds the name of the property to determine whether of not client id is overridden at connection time. */
- public static final String OVERRIDE_CLIENT_ID_PROPNAME = "overrideClientId";
-
- /** Holds the default value of the override client id flag. */
- public static final String OVERRIDE_CLIENT_ID_DEAFULT = "false";
-
- /** Holds the name of the property to define the JNDI factory name with. */
- public static final String FACTORY_NAME_PROPNAME = "factoryName";
-
- /** Holds the default JNDI name of the connection factory. */
- public static final String FACTORY_NAME_DEAFULT = "local";
-
- /** Holds the name of the property to set the JNDI initial context properties with. */
- public static final String FILE_PROPERTIES_PROPNAME = "properties";
-
- /** Holds the default file name of the JNDI initial context properties. */
- public static final String FILE_PROPERTIES_DEAFULT = "perftests.properties";
-
- /** Holds the name of the property to get the test message size from. */
- public static final String MESSAGE_SIZE_PROPNAME = "messageSize";
-
- /** Used to set up a default message size. */
- public static final int MESSAGE_SIZE_DEAFULT = 0;
-
- /** Holds the name of the property to get the ping queue name from. */
- public static final String PING_QUEUE_NAME_PROPNAME = "destinationName";
-
- /** Holds the name of the default destination to send pings on. */
- public static final String PING_QUEUE_NAME_DEFAULT = "ping";
-
- /** Holds the name of the property to get the queue name postfix from. */
- public static final String QUEUE_NAME_POSTFIX_PROPNAME = "queueNamePostfix";
-
- /** Holds the default queue name postfix value. */
- public static final String QUEUE_NAME_POSTFIX_DEFAULT = "";
-
- /** Holds the name of the property to get the test delivery mode from. */
- public static final String PERSISTENT_MODE_PROPNAME = "persistent";
-
- /** Holds the message delivery mode to use for the test. */
- public static final boolean PERSISTENT_MODE_DEFAULT = false;
-
- /** Holds the name of the property to get the test transactional mode from. */
- public static final String TRANSACTED_PROPNAME = "transacted";
-
- /** Holds the transactional mode to use for the test. */
- public static final boolean TRANSACTED_DEFAULT = false;
-
- /** Holds the name of the property to get the test consumer transacted mode from. */
- public static final String CONSUMER_TRANSACTED_PROPNAME = "consTransacted";
-
- /** Holds the consumer transactional mode default setting. */
- public static final boolean CONSUMER_TRANSACTED_DEFAULT = false;
-
- /** Holds the name of the property to get the test broker url from. */
- public static final String BROKER_PROPNAME = "broker";
-
- /** Holds the default broker url for the test. */
- public static final String BROKER_DEFAULT = "tcp://localhost:5672";
-
- /** Holds the name of the property to get the test broker virtual path. */
- public static final String VIRTUAL_HOST_PROPNAME = "virtualHost";
-
- /** Holds the default virtual path for the test. */
- public static final String VIRTUAL_HOST_DEFAULT = "";
-
- /** Holds the name of the property to get the message rate from. */
- public static final String RATE_PROPNAME = "rate";
-
- /** Defines the default rate (in pings per second) to send pings at. 0 means as fast as possible, no restriction. */
- public static final int RATE_DEFAULT = 0;
-
- /** Holds the name of the property to get the verbose mode proeprty from. */
- public static final String VERBOSE_PROPNAME = "verbose";
-
- /** Holds the default verbose mode. */
- public static final boolean VERBOSE_DEFAULT = false;
-
- /** Holds the name of the property to get the p2p or pub/sub messaging mode from. */
- public static final String PUBSUB_PROPNAME = "pubsub";
-
- /** Holds the pub/sub mode default, true means ping a topic, false means ping a queue. */
- public static final boolean PUBSUB_DEFAULT = false;
-
- /** Holds the name of the property to get the fail after commit flag from. */
- public static final String FAIL_AFTER_COMMIT_PROPNAME = "failAfterCommit";
-
- /** Holds the default failover after commit test flag. */
- public static final boolean FAIL_AFTER_COMMIT_DEFAULT = false;
-
- /** Holds the name of the proeprty to get the fail before commit flag from. */
- public static final String FAIL_BEFORE_COMMIT_PROPNAME = "failBeforeCommit";
-
- /** Holds the default failover before commit test flag. */
- public static final boolean FAIL_BEFORE_COMMIT_DEFAULT = false;
-
- /** Holds the name of the proeprty to get the fail after send flag from. */
- public static final String FAIL_AFTER_SEND_PROPNAME = "failAfterSend";
-
- /** Holds the default failover after send test flag. */
- public static final boolean FAIL_AFTER_SEND_DEFAULT = false;
-
- /** Holds the name of the property to get the fail before send flag from. */
- public static final String FAIL_BEFORE_SEND_PROPNAME = "failBeforeSend";
-
- /** Holds the default failover before send test flag. */
- public static final boolean FAIL_BEFORE_SEND_DEFAULT = false;
-
- /** Holds the name of the property to get the fail once flag from. */
- public static final String FAIL_ONCE_PROPNAME = "failOnce";
-
- /** The default failover once flag, true means only do one failover, false means failover on every commit cycle. */
- public static final boolean FAIL_ONCE_DEFAULT = true;
-
- /** Holds the name of the property to get the broker access username from. */
- public static final String USERNAME_PROPNAME = "username";
-
- /** Holds the default broker log on username. */
- public static final String USERNAME_DEFAULT = "guest";
-
- /** Holds the name of the property to get the broker access password from. */
- public static final String PASSWORD_PROPNAME = "password";
-
- /** Holds the default broker log on password. */
- public static final String PASSWORD_DEFAULT = "guest";
-
- /** Holds the name of the proeprty to get the. */
- public static final String SELECTOR_PROPNAME = "selector";
-
- /** Holds the default message selector. */
- public static final String SELECTOR_DEFAULT = "";
-
- /** Holds the name of the property to get the destination count from. */
- public static final String DESTINATION_COUNT_PROPNAME = "destinationCount";
-
- /** Defines the default number of destinations to ping. */
- public static final int DESTINATION_COUNT_DEFAULT = 1;
-
- /** Holds the name of the property to get the number of consumers per destination from. */
- public static final String NUM_CONSUMERS_PROPNAME = "numConsumers";
-
- /** Defines the default number consumers per destination. */
- public static final int NUM_CONSUMERS_DEFAULT = 1;
-
- /** Holds the name of the property to get the waiting timeout for response messages. */
- public static final String TIMEOUT_PROPNAME = "timeout";
-
- /** Default time to wait before assuming that a ping has timed out. */
- public static final long TIMEOUT_DEFAULT = 30000;
-
- /** Holds the name of the property to get the commit batch size from. */
- public static final String TX_BATCH_SIZE_PROPNAME = "commitBatchSize";
-
- /** Defines the default number of pings to send in each transaction when running transactionally. */
- public static final int TX_BATCH_SIZE_DEFAULT = 1;
-
- /** Holds the name of the property to get the unique destinations flag from. */
- public static final String UNIQUE_DESTS_PROPNAME = "uniqueDests";
-
- /** Defines the default value for the unique destinations property. */
- public static final boolean UNIQUE_DESTS_DEFAULT = true;
-
- /** Holds the name of the property to get the durable destinations flag from. */
- public static final String DURABLE_DESTS_PROPNAME = "durableDests";
-
- /** Defines the default value of the durable destinations flag. */
- public static final boolean DURABLE_DESTS_DEFAULT = false;
-
- /** Holds the name of the proeprty to get the message acknowledgement mode from. */
- public static final String ACK_MODE_PROPNAME = "ackMode";
-
- /** Defines the default message acknowledgement mode. */
- public static final int ACK_MODE_DEFAULT = Session.AUTO_ACKNOWLEDGE;
-
- /** Holds the name of the property to get the consumers message acknowledgement mode from. */
- public static final String CONSUMER_ACK_MODE_PROPNAME = "consAckMode";
-
- /** Defines the default consumers message acknowledgement mode. */
- public static final int CONSUMER_ACK_MODE_DEFAULT = Session.AUTO_ACKNOWLEDGE;
-
- /** Holds the name of the property to get the maximum pending message size setting from. */
- public static final String MAX_PENDING_PROPNAME = "maxPending";
-
- /** Defines the default value for the maximum pending message size setting. 0 means no limit. */
- public static final int MAX_PENDING_DEFAULT = 0;
-
- /** Defines the default prefetch size to use when consuming messages. */
- public static final int PREFETCH_DEFAULT = 100;
-
- /** Defines the default value of the no local flag to use when consuming messages. */
- public static final boolean NO_LOCAL_DEFAULT = false;
-
- /** Defines the default value of the exclusive flag to use when consuming messages. */
- public static final boolean EXCLUSIVE_DEFAULT = false;
-
- /** Holds the name of the property to store nanosecond timestamps in ping messages with. */
- public static final String MESSAGE_TIMESTAMP_PROPNAME = "timestamp";
-
- /** Holds the default configuration properties. */
- public static ParsedProperties defaults = new ParsedProperties();
-
- static
- {
- defaults.setPropertyIfNull(OVERRIDE_CLIENT_ID_PROPNAME, OVERRIDE_CLIENT_ID_DEAFULT);
- defaults.setPropertyIfNull(FILE_PROPERTIES_PROPNAME, FILE_PROPERTIES_DEAFULT);
- defaults.setPropertyIfNull(FACTORY_NAME_PROPNAME, FACTORY_NAME_DEAFULT);
- defaults.setPropertyIfNull(BROKER_PROPNAME, BROKER_DEFAULT);
- defaults.setPropertyIfNull(USERNAME_PROPNAME, USERNAME_DEFAULT);
- defaults.setPropertyIfNull(PASSWORD_PROPNAME, PASSWORD_DEFAULT);
- defaults.setPropertyIfNull(VIRTUAL_HOST_PROPNAME, VIRTUAL_HOST_DEFAULT);
- defaults.setPropertyIfNull(PING_QUEUE_NAME_PROPNAME, PING_QUEUE_NAME_DEFAULT);
- defaults.setPropertyIfNull(QUEUE_NAME_POSTFIX_PROPNAME, QUEUE_NAME_POSTFIX_DEFAULT);
- defaults.setPropertyIfNull(SELECTOR_PROPNAME, SELECTOR_DEFAULT);
- defaults.setPropertyIfNull(TRANSACTED_PROPNAME, TRANSACTED_DEFAULT);
- defaults.setPropertyIfNull(CONSUMER_TRANSACTED_PROPNAME, CONSUMER_TRANSACTED_DEFAULT);
- defaults.setPropertyIfNull(PERSISTENT_MODE_PROPNAME, PERSISTENT_MODE_DEFAULT);
- defaults.setPropertyIfNull(ACK_MODE_PROPNAME, ACK_MODE_DEFAULT);
- defaults.setPropertyIfNull(CONSUMER_ACK_MODE_PROPNAME, CONSUMER_ACK_MODE_DEFAULT);
- defaults.setPropertyIfNull(MESSAGE_SIZE_PROPNAME, MESSAGE_SIZE_DEAFULT);
- defaults.setPropertyIfNull(VERBOSE_PROPNAME, VERBOSE_DEFAULT);
- defaults.setPropertyIfNull(PUBSUB_PROPNAME, PUBSUB_DEFAULT);
- defaults.setPropertyIfNull(UNIQUE_DESTS_PROPNAME, UNIQUE_DESTS_DEFAULT);
- defaults.setPropertyIfNull(DURABLE_DESTS_PROPNAME, DURABLE_DESTS_DEFAULT);
- defaults.setPropertyIfNull(FAIL_BEFORE_COMMIT_PROPNAME, FAIL_BEFORE_COMMIT_DEFAULT);
- defaults.setPropertyIfNull(FAIL_AFTER_COMMIT_PROPNAME, FAIL_AFTER_COMMIT_DEFAULT);
- defaults.setPropertyIfNull(FAIL_BEFORE_SEND_PROPNAME, FAIL_BEFORE_SEND_DEFAULT);
- defaults.setPropertyIfNull(FAIL_AFTER_SEND_PROPNAME, FAIL_AFTER_SEND_DEFAULT);
- defaults.setPropertyIfNull(FAIL_ONCE_PROPNAME, FAIL_ONCE_DEFAULT);
- defaults.setPropertyIfNull(TX_BATCH_SIZE_PROPNAME, TX_BATCH_SIZE_DEFAULT);
- defaults.setPropertyIfNull(DESTINATION_COUNT_PROPNAME, DESTINATION_COUNT_DEFAULT);
- defaults.setPropertyIfNull(NUM_CONSUMERS_PROPNAME, NUM_CONSUMERS_DEFAULT);
- defaults.setPropertyIfNull(RATE_PROPNAME, RATE_DEFAULT);
- defaults.setPropertyIfNull(TIMEOUT_PROPNAME, TIMEOUT_DEFAULT);
- defaults.setPropertyIfNull(MAX_PENDING_PROPNAME, MAX_PENDING_DEFAULT);
- }
-
- /** Allows setting of client ID on the connection, rather than through the connection URL. */
- protected boolean _overrideClientId;
-
- /** Holds the JNDI name of the JMS connection factory. */
- protected String _factoryName;
-
- /** Holds the name of the properties file to configure JNDI with. */
- protected String _fileProperties;
-
- /** Holds the broker url. */
- protected String _brokerDetails;
-
- /** Holds the username to access the broker with. */
- protected String _username;
-
- /** Holds the password to access the broker with. */
- protected String _password;
-
- /** Holds the virtual host on the broker to run the tests through. */
- protected String _virtualpath;
-
- /** Holds the root name from which to generate test destination names. */
- protected String _destinationName;
-
- /** Holds the default queue name postfix value. */
- protected String _queueNamePostfix;
-
- /** Holds the message selector to filter the pings with. */
- protected String _selector;
-
- /** Holds the producers transactional mode flag. */
- protected boolean _transacted;
-
- /** Holds the consumers transactional mode flag. */
- protected boolean _consTransacted;
-
- /** Determines whether this producer sends persistent messages. */
- protected boolean _persistent;
-
- /** Holds the acknowledgement mode used for the producers. */
- protected int _ackMode;
-
- /** Holds the acknowledgement mode setting for the consumers. */
- protected int _consAckMode;
-
- /** Determines what size of messages this producer sends. */
- protected int _messageSize;
-
- /** Used to indicate that the ping loop should print out whenever it pings. */
- protected boolean _verbose;
-
- /** Flag used to indicate if this is a point to point or pub/sub ping client. */
- protected boolean _isPubSub;
-
- /** Flag used to indicate if the destinations should be unique client. */
- protected boolean _isUnique;
-
- /** Flag used to indicate that durable destination should be used. */
- protected boolean _isDurable;
-
- /** Flag used to indicate that the user should be prompted to terminate a broker, to test failover before a commit. */
- protected boolean _failBeforeCommit;
-
- /** Flag used to indicate that the user should be prompted to terminate a broker, to test failover after a commit. */
- protected boolean _failAfterCommit;
-
- /** Flag used to indicate that the user should be prompted to terminate a broker, to test failover before a send. */
- protected boolean _failBeforeSend;
-
- /** Flag used to indicate that the user should be prompted to terminate a broker, to test failover after a send. */
- protected boolean _failAfterSend;
-
- /** Flag used to indicate that failover prompting should only be done on the first commit, not on every commit. */
- protected boolean _failOnce;
-
- /** Holds the number of sends that should be performed in every transaction when using transactions. */
- protected int _txBatchSize;
-
- /** Holds the number of destinations to ping. */
- protected int _noOfDestinations;
-
- /** Holds the number of consumers per destination. */
- protected int _noOfConsumers;
-
- /** Holds the maximum send rate in herz. */
- protected int _rate;
-
- /**
- * Holds the size of the maximum amount of pending data that the client should buffer, sending is suspended
- * if this limit is breached.
- */
- protected int _maxPendingSize;
-
- /** A source for providing sequential unique correlation ids. These will be unique within the same JVM. */
- private static AtomicLong _correlationIdGenerator = new AtomicLong(0L);
-
- /** A source for providing sequential unqiue ids for instances of this class to be identifed with. */
- private static AtomicInteger _instanceIdGenerator = new AtomicInteger(0);
-
- /** Holds this instances unique id. */
- private int instanceId;
-
- /**
- * Holds a map from message ids to latches on which threads wait for replies. This map is shared accross multiple
- * ping producers on the same JVM.
- */
- private static Map<String, PerCorrelationId> perCorrelationIds =
- Collections.synchronizedMap(new HashMap<String, PerCorrelationId>());
-
- /** A convenient formatter to use when time stamping output. */
- protected static final DateFormat timestampFormatter = new SimpleDateFormat("hh:mm:ss:SS");
-
- /** Holds the connection for the message producer. */
- protected Connection _connection;
-
- /** Holds the consumer connections. */
- protected Connection[] _consumerConnection;
-
- /** Holds the controlSession on which ping replies are received. */
- protected Session[] _consumerSession;
-
- /** Holds the producer controlSession, needed to create ping messages. */
- protected Session _producerSession;
-
- /** Holds the destination where the response messages will arrive. */
- protected Destination _replyDestination;
-
- /** Holds the set of destinations that this ping producer pings. */
- protected List<Destination> _pingDestinations;
-
- /** Used to restrict the sending rate to a specified limit. */
- protected Throttle _rateLimiter;
-
- /** Holds a message listener that this message listener chains all its messages to. */
- protected ChainedMessageListener _chainedMessageListener = null;
-
- /**
- * This id generator is used to generate ids to append to the queue name to ensure that queues can be unique when
- * creating multiple ping producers in the same JVM.
- */
- protected static AtomicInteger _queueJVMSequenceID = new AtomicInteger();
-
- /**
- * This id generator is used to generates ids that are only unique within this pinger. Creating multiple pingers
- * on the same JVM using this id generator will allow them to ping on the same queues.
- */
- protected AtomicInteger _queueSharedID = new AtomicInteger();
-
- /** Used to tell the ping loop when to terminate, it only runs while this is true. */
- protected boolean _publish = true;
-
- /** Holds the message producer to send the pings through. */
- protected MessageProducer _producer;
-
- /** Holds the message consumer to receive the ping replies through. */
- protected MessageConsumer[] _consumer;
-
- /** The prompt to display when asking the user to kill the broker for failover testing. */
- private static final String KILL_BROKER_PROMPT = "Kill broker now, then press Return.";
-
- /** Holds the name for this test client to be identified to the broker with. */
- private String _clientID;
-
- /** Keeps count of the total messages sent purely for debugging purposes. */
- private static AtomicInteger numSent = new AtomicInteger();
-
- /**
- * Holds a monitor which is used to synchronize sender and receivers threads, where the sender has elected
- * to wait until the number of unreceived message is reduced before continuing to send. This monitor is a
- * fair SynchronousQueue becuase that provides fair scheduling, to ensure that all producer threads get an
- * equal chance to produce messages.
- */
- static final SynchronousQueue _sendPauseMonitor = new SynchronousQueue(true);
-
- /** Keeps a count of the number of message currently sent but not received. */
- static AtomicInteger _unreceived = new AtomicInteger(0);
-
- /**
- * Creates a ping producer with the specified parameters, of which there are many. See the class level comments
- * for details. This constructor creates a connection to the broker and creates producer and consumer sessions on
- * it, to send and recieve its pings and replies on.
- *
- * @param overrides Properties containing any desired overrides to the defaults.
- *
- * @throws Exception Any exceptions are allowed to fall through.
- */
- public PingPongProducer(Properties overrides) throws Exception
- {
- // log.debug("public PingPongProducer(Properties overrides = " + overrides + "): called");
- instanceId = _instanceIdGenerator.getAndIncrement();
-
- // Create a set of parsed properties from the defaults overriden by the passed in values.
- ParsedProperties properties = new ParsedProperties(defaults);
- properties.putAll(overrides);
-
- // Extract the configuration properties to set the pinger up with.
- _overrideClientId = properties.getPropertyAsBoolean(OVERRIDE_CLIENT_ID_PROPNAME);
- _factoryName = properties.getProperty(FACTORY_NAME_PROPNAME);
- _fileProperties = properties.getProperty(FILE_PROPERTIES_PROPNAME);
- _brokerDetails = properties.getProperty(BROKER_PROPNAME);
- _username = properties.getProperty(USERNAME_PROPNAME);
- _password = properties.getProperty(PASSWORD_PROPNAME);
- _virtualpath = properties.getProperty(VIRTUAL_HOST_PROPNAME);
- _destinationName = properties.getProperty(PING_QUEUE_NAME_PROPNAME);
- _queueNamePostfix = properties.getProperty(QUEUE_NAME_POSTFIX_PROPNAME);
- _selector = properties.getProperty(SELECTOR_PROPNAME);
- _transacted = properties.getPropertyAsBoolean(TRANSACTED_PROPNAME);
- _consTransacted = properties.getPropertyAsBoolean(CONSUMER_TRANSACTED_PROPNAME);
- _persistent = properties.getPropertyAsBoolean(PERSISTENT_MODE_PROPNAME);
- _messageSize = properties.getPropertyAsInteger(MESSAGE_SIZE_PROPNAME);
- _verbose = properties.getPropertyAsBoolean(VERBOSE_PROPNAME);
- _failAfterCommit = properties.getPropertyAsBoolean(FAIL_AFTER_COMMIT_PROPNAME);
- _failBeforeCommit = properties.getPropertyAsBoolean(FAIL_BEFORE_COMMIT_PROPNAME);
- _failAfterSend = properties.getPropertyAsBoolean(FAIL_AFTER_SEND_PROPNAME);
- _failBeforeSend = properties.getPropertyAsBoolean(FAIL_BEFORE_SEND_PROPNAME);
- _failOnce = properties.getPropertyAsBoolean(FAIL_ONCE_PROPNAME);
- _txBatchSize = properties.getPropertyAsInteger(TX_BATCH_SIZE_PROPNAME);
- _noOfDestinations = properties.getPropertyAsInteger(DESTINATION_COUNT_PROPNAME);
- _noOfConsumers = properties.getPropertyAsInteger(NUM_CONSUMERS_PROPNAME);
- _rate = properties.getPropertyAsInteger(RATE_PROPNAME);
- _isPubSub = properties.getPropertyAsBoolean(PUBSUB_PROPNAME);
- _isUnique = properties.getPropertyAsBoolean(UNIQUE_DESTS_PROPNAME);
- _isDurable = properties.getPropertyAsBoolean(DURABLE_DESTS_PROPNAME);
- _ackMode = _transacted ? 0 : properties.getPropertyAsInteger(ACK_MODE_PROPNAME);
- _consAckMode = _consTransacted ? 0 : properties.getPropertyAsInteger(CONSUMER_ACK_MODE_PROPNAME);
- _maxPendingSize = properties.getPropertyAsInteger(MAX_PENDING_PROPNAME);
-
- // Check that one or more destinations were specified.
- if (_noOfDestinations < 1)
- {
- throw new IllegalArgumentException("There must be at least one destination.");
- }
-
- // Set up a throttle to control the send rate, if a rate > 0 is specified.
- if (_rate > 0)
- {
- _rateLimiter = new BatchedThrottle();
- _rateLimiter.setRate(_rate);
- }
-
- // Create the connection and message producers/consumers.
- // establishConnection(true, true);
- }
-
- /**
- * Establishes a connection to the broker and creates message consumers and producers based on the parameters
- * that this ping client was created with.
- *
- * @param producer Flag to indicate whether or not the producer should be set up.
- * @param consumer Flag to indicate whether or not the consumers should be set up.
- *
- * @throws Exception Any exceptions are allowed to fall through.
- */
- public void establishConnection(boolean producer, boolean consumer) throws Exception
- {
- // log.debug("public void establishConnection(): called");
-
- // Generate a unique identifying name for this client, based on it ip address and the current time.
- InetAddress address = InetAddress.getLocalHost();
- // _clientID = address.getHostName() + System.currentTimeMillis();
- _clientID = "perftest_" + instanceId;
-
- // Create a connection to the broker.
- createConnection(_clientID);
-
- // Create transactional or non-transactional sessions, based on the command line arguments.
- _producerSession = _connection.createSession(_transacted, _ackMode);
-
- _consumerSession = new Session[_noOfConsumers];
-
- for (int i = 0; i < _noOfConsumers; i++)
- {
- _consumerSession[i] = _consumerConnection[i].createSession(_consTransacted, _consAckMode);
- }
-
- // Create the destinations to send pings to and receive replies from.
- _replyDestination = _consumerSession[0].createTemporaryQueue();
- createPingDestinations(_noOfDestinations, _selector, _destinationName, _isUnique, _isDurable);
-
- // Create the message producer only if instructed to.
- if (producer)
- {
- createProducer();
- }
-
- // Create the message consumer only if instructed to.
- if (consumer)
- {
- createReplyConsumers(getReplyDestinations(), _selector);
- }
- }
-
- /**
- * Establishes a connection to the broker, based on the configuration parameters that this ping client was
- * created with.
- *
- * @param clientID The clients identifier.
- *
- * @throws JMSException Underlying exceptions allowed to fall through.
- * @throws NamingException Underlying exceptions allowed to fall through.
- * @throws IOException Underlying exceptions allowed to fall through.
- */
- protected void createConnection(String clientID) throws JMSException, NamingException, IOException
- {
- // _log.debug("protected void createConnection(String clientID = " + clientID + "): called");
-
- // _log.debug("Creating a connection for the message producer.");
-
-
- Context context = InitialContextHelper.getInitialContext(_fileProperties);
- ConnectionFactory factory = (ConnectionFactory) context.lookup(_factoryName);
- _connection = factory.createConnection(_username, _password);
-
- if (_overrideClientId)
- {
- _connection.setClientID(clientID);
- }
-
- // _log.debug("Creating " + _noOfConsumers + " connections for the consumers.");
-
- _consumerConnection = new Connection[_noOfConsumers];
-
- for (int i = 0; i < _noOfConsumers; i++)
- {
- _consumerConnection[i] = factory.createConnection(_username, _password);
- // _consumerConnection[i].setClientID(clientID);
- }
- }
-
- /**
- * Starts a ping-pong loop running from the command line. The bounce back client {@link PingPongBouncer} also needs
- * to be started to bounce the pings back again.
- *
- * @param args The command line arguments.
- */
- public static void main(String[] args)
- {
- try
- {
- Properties options =
- CommandLineParser.processCommandLine(args, new CommandLineParser(new String[][] {}), System.getProperties());
-
- // Create a ping producer overriding its defaults with all options passed on the command line.
- PingPongProducer pingProducer = new PingPongProducer(options);
- pingProducer.establishConnection(true, true);
-
- // Start the ping producers dispatch thread running.
- pingProducer._connection.start();
-
- // Create a shutdown hook to terminate the ping-pong producer.
- Runtime.getRuntime().addShutdownHook(pingProducer.getShutdownHook());
-
- // Ensure that the ping pong producer is registered to listen for exceptions on the connection too.
- pingProducer._connection.setExceptionListener(pingProducer);
-
- // Create the ping loop thread and run it until it is terminated by the shutdown hook or exception.
- Thread pingThread = new Thread(pingProducer);
- pingThread.run();
- pingThread.join();
- }
- catch (Exception e)
- {
- System.err.println(e.getMessage());
- log.error("Top level handler caught execption.", e);
- System.exit(1);
- }
- }
-
- /**
- * Convenience method for a short pause.
- *
- * @param sleepTime The time in milliseconds to pause for.
- */
- public static void pause(long sleepTime)
- {
- if (sleepTime > 0)
- {
- try
- {
- Thread.sleep(sleepTime);
- }
- catch (InterruptedException ie)
- { }
- }
- }
-
- /**
- * Gets all the reply destinations (to listen for replies on). In this case this will just be the single reply to
- * destination of this pinger.
- *
- * @return The single reply to destination of this pinger, wrapped in a list.
- */
- public List<Destination> getReplyDestinations()
- {
- // log.debug("public List<Destination> getReplyDestinations(): called");
-
- List<Destination> replyDestinations = new ArrayList<Destination>();
- replyDestinations.add(_replyDestination);
-
- // log.debug("replyDestinations = " + replyDestinations);
-
- return replyDestinations;
- }
-
- /**
- * Creates the producer to send the pings on. This is created without a default destination. Its persistent delivery
- * flag is set accoring the ping producer creation options.
- *
- * @throws JMSException Any JMSExceptions are allowed to fall through.
- */
- public void createProducer() throws JMSException
- {
- // log.debug("public void createProducer(): called");
-
- _producer = (MessageProducer) _producerSession.createProducer(null);
- _producer.setDeliveryMode(_persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT);
-
- // log.debug("Created producer for " + (_persistent ? "persistent" : "non-persistent") + " messages.");
- }
-
- /**
- * Creates consumers for the specified number of destinations. The destinations themselves are also created by this
- * method.
- *
- * @param noOfDestinations The number of destinations to create consumers for.
- * @param selector The message selector to filter the consumers with.
- * @param rootName The root of the name, or actual name if only one is being created.
- * @param unique <tt>true</tt> to make the destinations unique to this pinger, <tt>false</tt> to share the
- * numbering with all pingers on the same JVM.
- * @param durable If the destinations are durable topics.
- *
- * @throws JMSException Any JMSExceptions are allowed to fall through.
- */
- public void createPingDestinations(int noOfDestinations, String selector, String rootName, boolean unique,
- boolean durable) throws JMSException
- {
- /*log.debug("public void createPingDestinations(int noOfDestinations = " + noOfDestinations + ", String selector = "
- + selector + ", String rootName = " + rootName + ", boolean unique = " + unique + ", boolean durable = "
- + durable + "): called");*/
-
- _pingDestinations = new ArrayList<Destination>();
-
- // Create the desired number of ping destinations and consumers for them.
- // log.debug("Creating " + noOfDestinations + " destinations to ping.");
-
- for (int i = 0; i < noOfDestinations; i++)
- {
- Destination destination;
- String id;
-
- // Generate an id, unique within this pinger or to the whole JVM depending on the unique flag.
- if (unique)
- {
- // log.debug("Creating unique destinations.");
- id = "_" + _queueJVMSequenceID.incrementAndGet() + "_" + _connection.getClientID();
- }
- else
- {
- // log.debug("Creating shared destinations.");
- id = "_" + _queueSharedID.incrementAndGet();
- }
-
- // Check if this is a pub/sub pinger, in which case create topics.
- if (_isPubSub)
- {
- destination = _producerSession.createTopic(rootName + id);
- // log.debug("Created non-durable topic " + destination);
-
- if (durable)
- {
- _producerSession.createDurableSubscriber((Topic) destination, _connection.getClientID());
- }
- }
- // Otherwise this is a p2p pinger, in which case create queues.
- else
- {
- destination = _producerSession.createQueue(rootName + id + _queueNamePostfix);
- // log.debug("Created queue " + destination);
- }
-
- // Keep the destination.
- _pingDestinations.add(destination);
- }
- }
-
- /**
- * Creates consumers for the specified destinations and registers this pinger to listen to their messages.
- *
- * @param destinations The destinations to listen to.
- * @param selector A selector to filter the messages with.
- *
- * @throws javax.jms.JMSException Any JMSExceptions are allowed to fall through.
- */
- public void createReplyConsumers(Collection<Destination> destinations, String selector) throws JMSException
- {
- /*log.debug("public void createReplyConsumers(Collection<Destination> destinations = " + destinations
- + ", String selector = " + selector + "): called");*/
-
- log.debug("There are " + destinations.size() + " destinations.");
- log.debug("Creating " + _noOfConsumers + " consumers on each destination.");
- log.debug("Total number of consumers is: " + (destinations.size() * _noOfConsumers));
-
- for (Destination destination : destinations)
- {
- _consumer = new MessageConsumer[_noOfConsumers];
-
- for (int i = 0; i < _noOfConsumers; i++)
- {
- // Create a consumer for the destination and set this pinger to listen to its messages.
- _consumer[i] = _consumerSession[i].createConsumer(destination, selector, NO_LOCAL_DEFAULT);
-
- final int consumerNo = i;
-
- _consumer[i].setMessageListener(new MessageListener()
- {
- public void onMessage(Message message)
- {
- onMessageWithConsumerNo(message, consumerNo);
- }
- });
-
- log.debug("Set consumer " + i + " to listen to replies sent to destination: " + destination);
- }
- }
- }
-
- /**
- * Stores the received message in the replies map, then resets the boolean latch that a thread waiting for a
- * correlating reply may be waiting on. This is only done if the reply has a correlation id that is expected in the
- * replies map.
- *
- * @param message The received message.
- * @param consumerNo The consumer number within this test pinger instance.
- */
- public void onMessageWithConsumerNo(Message message, int consumerNo)
- {
- // log.debug("public void onMessageWithConsumerNo(Message message, int consumerNo = " + consumerNo + "): called");
- try
- {
- long now = System.nanoTime();
- long timestamp = getTimestamp(message);
- long pingTime = now - timestamp;
-
- // NDC.push("id" + instanceId + "/cons" + consumerNo);
-
- // Extract the messages correlation id.
- String correlationID = message.getJMSCorrelationID();
- // log.debug("correlationID = " + correlationID);
-
- // int num = message.getIntProperty("MSG_NUM");
- // log.info("Message " + num + " received.");
-
- boolean isRedelivered = message.getJMSRedelivered();
- // log.debug("isRedelivered = " + isRedelivered);
-
- if (!isRedelivered)
- {
- // Countdown on the traffic light if there is one for the matching correlation id.
- PerCorrelationId perCorrelationId = perCorrelationIds.get(correlationID);
-
- if (perCorrelationId != null)
- {
- CountDownLatch trafficLight = perCorrelationId.trafficLight;
-
- // Restart the timeout timer on every message.
- perCorrelationId.timeOutStart = System.nanoTime();
-
- // log.debug("Reply was expected, decrementing the latch for the id, " + correlationID);
-
- // Release waiting senders if there are some and using maxPending limit.
- if ((_maxPendingSize > 0))
- {
- // Decrement the count of sent but not yet received messages.
- int unreceived = _unreceived.decrementAndGet();
- int unreceivedSize =
- (unreceived * ((_messageSize == 0) ? 1 : _messageSize))
- / (_isPubSub ? getConsumersPerDestination() : 1);
-
- // log.debug("unreceived = " + unreceived);
- // log.debug("unreceivedSize = " + unreceivedSize);
-
- // synchronized (_sendPauseMonitor)
- // {
- if (unreceivedSize < _maxPendingSize)
- {
- _sendPauseMonitor.poll();
- }
- // }
- }
-
- // Decrement the countdown latch. Before this point, it is possible that two threads might enter this
- // method simultanesouly with the same correlation id. Decrementing the latch in a synchronized block
- // ensures that each thread will get a unique value for the remaining messages.
- long trueCount;
- long remainingCount;
-
- synchronized (trafficLight)
- {
- trafficLight.countDown();
-
- trueCount = trafficLight.getCount();
- remainingCount = trueCount - 1;
-
- // NDC.push("/rem" + remainingCount);
-
- // log.debug("remainingCount = " + remainingCount);
- // log.debug("trueCount = " + trueCount);
-
- // Commit on transaction batch size boundaries. At this point in time the waiting producer
- // remains blocked, even on the last message.
- // Commit count is divided by noOfConsumers in p2p mode, so that each consumer only commits on
- // each batch boundary. For pub/sub each consumer gets every message so no division is done.
- // When running in client ack mode, an ack is done instead of a commit, on the commit batch
- // size boundaries.
- long commitCount = _isPubSub ? remainingCount : (remainingCount / _noOfConsumers);
- // log.debug("commitCount = " + commitCount);
-
- if ((commitCount % _txBatchSize) == 0)
- {
- if (_consAckMode == 2)
- {
- // log.debug("Doing client ack for consumer " + consumerNo + ".");
- message.acknowledge();
- }
- else
- {
- // log.debug("Trying commit for consumer " + consumerNo + ".");
- commitTx(_consumerSession[consumerNo]);
- // log.info("Tx committed on consumer " + consumerNo);
- }
- }
-
- // Forward the message and remaining count to any interested chained message listener.
- if (_chainedMessageListener != null)
- {
- _chainedMessageListener.onMessage(message, (int) remainingCount, pingTime);
- }
-
- // Check if this is the last message, in which case release any waiting producers. This is done
- // after the transaction has been committed and any listeners notified.
- if (trueCount == 1)
- {
- trafficLight.countDown();
- }
- }
- }
- else
- {
- log.warn("Got unexpected message with correlationId: " + correlationID);
- }
- }
- else
- {
- log.warn("Got redelivered message, ignoring.");
- }
- }
- catch (JMSException e)
- {
- log.warn("There was a JMSException: " + e.getMessage(), e);
- }
- finally
- {
- // log.debug("public void onMessageWithConsumerNo(Message message, int consumerNo): ending");
- // NDC.clear();
- }
- }
-
- /**
- * Sends the specified number of ping message and then waits for all correlating replies. If the wait times out
- * before a reply arrives, then a null reply is returned from this method. This method allows the caller to specify
- * the correlation id.
- *
- * @param message The message to send. If this is null, one is generated.
- * @param numPings The number of ping messages to send.
- * @param timeout The timeout in milliseconds.
- * @param messageCorrelationId The message correlation id. If this is null, one is generated.
- *
- * @return The number of replies received. This may be less than the number sent if the timeout terminated the wait
- * for all prematurely.
- *
- * @throws JMSException All underlying JMSExceptions are allowed to fall through.
- * @throws InterruptedException When interrupted by a timeout
- */
- public int pingAndWaitForReply(Message message, int numPings, long timeout, String messageCorrelationId)
- throws JMSException, InterruptedException
- {
- /*log.debug("public int pingAndWaitForReply(Message message, int numPings = " + numPings + ", long timeout = "
- + timeout + ", String messageCorrelationId = " + messageCorrelationId + "): called");*/
-
- // Generate a unique correlation id to put on the messages before sending them, if one was not specified.
- if (messageCorrelationId == null)
- {
- messageCorrelationId = Long.toString(_correlationIdGenerator.incrementAndGet());
- }
-
- try
- {
- // NDC.push("prod");
-
- // Create a count down latch to count the number of replies with. This is created before the messages are
- // sent so that the replies cannot be received before the count down is created.
- // One is added to this, so that the last reply becomes a special case. The special case is that the
- // chained message listener must be called before this sender can be unblocked, but that decrementing the
- // countdown needs to be done before the chained listener can be called.
- PerCorrelationId perCorrelationId = new PerCorrelationId();
-
- perCorrelationId.trafficLight = new CountDownLatch(getExpectedNumPings(numPings) + 1);
- perCorrelationIds.put(messageCorrelationId, perCorrelationId);
-
- // Set up the current time as the start time for pinging on the correlation id. This is used to determine
- // timeouts.
- perCorrelationId.timeOutStart = System.nanoTime();
-
- // Send the specifed number of messages.
- pingNoWaitForReply(message, numPings, messageCorrelationId);
-
- boolean timedOut;
- boolean allMessagesReceived;
- int numReplies;
-
- do
- {
- // Block the current thread until replies to all the messages are received, or it times out.
- perCorrelationId.trafficLight.await(timeout, TimeUnit.MILLISECONDS);
-
- // Work out how many replies were receieved.
- numReplies = getExpectedNumPings(numPings) - (int) perCorrelationId.trafficLight.getCount();
-
- allMessagesReceived = numReplies == getExpectedNumPings(numPings);
-
- // log.debug("numReplies = " + numReplies);
- // log.debug("allMessagesReceived = " + allMessagesReceived);
-
- // Recheck the timeout condition.
- long now = System.nanoTime();
- long lastMessageReceievedAt = perCorrelationId.timeOutStart;
- timedOut = (now - lastMessageReceievedAt) > (timeout * 1000000);
-
- // log.debug("now = " + now);
- // log.debug("lastMessageReceievedAt = " + lastMessageReceievedAt);
- }
- while (!timedOut && !allMessagesReceived);
-
- if ((numReplies < getExpectedNumPings(numPings)) && _verbose)
- {
- log.info("Timed out (" + timeout + " ms) before all replies received on id, " + messageCorrelationId);
- }
- else if (_verbose)
- {
- log.info("Got all replies on id, " + messageCorrelationId);
- }
-
- // commitTx(_consumerSession);
-
- // log.debug("public int pingAndWaitForReply(Message message, int numPings, long timeout): ending");
-
- return numReplies;
- }
- // Ensure that the message countdown latch is always removed from the reply map. The reply map is long lived,
- // so will be a memory leak if this is not done.
- finally
- {
- // NDC.pop();
- perCorrelationIds.remove(messageCorrelationId);
- }
- }
-
- /**
- * Sends the specified number of ping messages and does not wait for correlating replies.
- *
- * @param message The message to send.
- * @param numPings The number of pings to send.
- * @param messageCorrelationId A correlation id to place on all messages sent.
- *
- * @throws JMSException All underlying JMSExceptions are allowed to fall through.
- */
- public void pingNoWaitForReply(Message message, int numPings, String messageCorrelationId) throws JMSException
- {
- /*log.debug("public void pingNoWaitForReply(Message message, int numPings = " + numPings
- + ", String messageCorrelationId = " + messageCorrelationId + "): called");*/
-
- if (message == null)
- {
- message = getTestMessage(getReplyDestinations().get(0), _messageSize, _persistent);
- }
-
- message.setJMSCorrelationID(messageCorrelationId);
-
- // Set up a committed flag to detect uncommitted messages at the end of the send loop. This may occurr if the
- // transaction batch size is not a factor of the number of pings. In which case an extra commit at the end is
- // needed.
- boolean committed = false;
-
- // Send all of the ping messages.
- for (int i = 0; i < numPings; i++)
- {
- // Re-timestamp the message.
- // message.setLongProperty(MESSAGE_TIMESTAMP_PROPNAME, System.nanoTime());
-
- // Send the message, passing in the message count.
- committed = sendMessage(i, message);
-
- // Spew out per message timings on every message sonly in verbose mode.
- /*if (_verbose)
- {
- log.info(timestampFormatter.format(new Date()) + ": Pinged at with correlation id, " + messageCorrelationId);
- }*/
- }
-
- // Call commit if the send loop finished before reaching a batch size boundary so there may still be uncommitted messages.
- if (!committed)
- {
- commitTx(_producerSession);
- }
- }
-
- /**
- * Sends the sepcified message, applies rate limiting and possibly commits the current transaction. The count of
- * messages sent so far must be specified and is used to round robin the ping destinations (where there are more
- * than one), and to determine if the transaction batch size has been reached and the sent messages should be
- * committed.
- *
- * @param i The count of messages sent so far in a loop of multiple calls to this send method.
- * @param message The message to send.
- *
- * @return <tt>true</tt> if the messages were committed, <tt>false</tt> otherwise.
- *
- * @throws JMSException All underlyiung JMSExceptions are allowed to fall through.
- */
- protected boolean sendMessage(int i, Message message) throws JMSException
- {
- try
- {
- NDC.push("id" + instanceId + "/prod");
-
- // log.debug("protected boolean sendMessage(int i = " + i + ", Message message): called");
- // log.debug("_txBatchSize = " + _txBatchSize);
-
- // Round robin the destinations as the messages are sent.
- Destination destination = _pingDestinations.get(i % _pingDestinations.size());
-
- // Prompt the user to kill the broker when doing failover testing.
- _failBeforeSend = waitForUserToPromptOnFailure(_failBeforeSend);
-
- // Get the test setup for the correlation id.
- String correlationID = message.getJMSCorrelationID();
- PerCorrelationId perCorrelationId = perCorrelationIds.get(correlationID);
-
- // If necessary, wait until the max pending message size comes within its limit.
- if (_maxPendingSize > 0)
- {
- synchronized (_sendPauseMonitor)
- {
- // Used to keep track of the number of times that send has to wait.
- int numWaits = 0;
-
- // The maximum number of waits before the test gives up and fails. This has been chosen to correspond with
- // the test timeout.
- int waitLimit = (int) (TIMEOUT_DEFAULT / 10000);
-
- while (true)
- {
- // Get the size estimate of sent but not yet received messages.
- int unreceived = _unreceived.get();
- int unreceivedSize =
- (unreceived * ((_messageSize == 0) ? 1 : _messageSize))
- / (_isPubSub ? getConsumersPerDestination() : 1);
-
- // log.debug("unreceived = " + unreceived);
- // log.debug("unreceivedSize = " + unreceivedSize);
- // log.debug("_maxPendingSize = " + _maxPendingSize);
-
- if (unreceivedSize > _maxPendingSize)
- {
- // log.debug("unreceived size estimate over limit = " + unreceivedSize);
-
- // Fail the test if the send has had to wait more than the maximum allowed number of times.
- if (numWaits > waitLimit)
- {
- String errorMessage =
- "Send has had to wait for the unreceivedSize (" + unreceivedSize
- + ") to come below the maxPendingSize (" + _maxPendingSize + ") more that " + waitLimit
- + " times.";
- log.warn(errorMessage);
- throw new RuntimeException(errorMessage);
- }
-
- // Wait on the send pause barrier for the limit to be re-established.
- try
- {
- long start = System.nanoTime();
- // _sendPauseMonitor.wait(10000);
- _sendPauseMonitor.offer(new Object(), 10000, TimeUnit.MILLISECONDS);
- long end = System.nanoTime();
-
- // Count the wait only if it was for > 99% of the requested wait time.
- if (((float) (end - start) / (float) (10000 * 1000000L)) > 0.99)
- {
- numWaits++;
- }
- }
- catch (InterruptedException e)
- {
- // Restore the interrupted status
- Thread.currentThread().interrupt();
- throw new RuntimeException(e);
- }
- }
- else
- {
- break;
- }
- }
- }
- }
-
- // Send the message either to its round robin destination, or its default destination.
- // int num = numSent.incrementAndGet();
- // message.setIntProperty("MSG_NUM", num);
- setTimestamp(message);
-
- if (destination == null)
- {
- _producer.send(message);
- }
- else
- {
- _producer.send(destination, message);
- }
-
- // Increase the unreceived size, this may actually happen after the message is received.
- // The unreceived size is incremented by the number of consumers that will get a copy of the message,
- // in pub/sub mode.
- if (_maxPendingSize > 0)
- {
- int newUnreceivedCount = _unreceived.addAndGet(_isPubSub ? getConsumersPerDestination() : 1);
- // log.debug("newUnreceivedCount = " + newUnreceivedCount);
- }
-
- // Apply message rate throttling if a rate limit has been set up.
- if (_rateLimiter != null)
- {
- _rateLimiter.throttle();
- }
-
- // Call commit every time the commit batch size is reached.
- boolean committed = false;
-
- // Commit on every transaction batch size boundary. Here i + 1 is the count of actual messages sent.
- if (((i + 1) % _txBatchSize) == 0)
- {
- // log.debug("Trying commit on producer session.");
- committed = commitTx(_producerSession);
- }
-
- return committed;
- }
- finally
- {
- NDC.clear();
- }
- }
-
- /**
- * If the specified fail flag is set, this method waits for the user to cause a failure and then indicate to the
- * test that the failure has occurred, before the method returns.
- *
- * @param failFlag The fail flag to test.
- *
- * @return The new value for the fail flag. If the {@link #_failOnce} flag is set, then each fail flag is only
- * used once, then reset.
- */
- private boolean waitForUserToPromptOnFailure(boolean failFlag)
- {
- if (failFlag)
- {
- if (_failOnce)
- {
- failFlag = false;
- }
-
- // log.debug("Failing Before Send");
- waitForUser(KILL_BROKER_PROMPT);
- }
-
- return failFlag;
- }
-
- /**
- * Implements a single iteration of the ping loop. This sends the number of pings specified by the transaction batch
- * size property, and waits for replies to all of them. Any errors cause the publish flag to be cleared, which will
- * terminate the pinger.
- */
- public void pingLoop()
- {
- try
- {
- // Generate a sample message and time stamp it.
- Message msg = getTestMessage(_replyDestination, _messageSize, _persistent);
- // setTimestamp(msg);
-
- // Send the message and wait for a reply.
- pingAndWaitForReply(msg, TX_BATCH_SIZE_DEFAULT, TIMEOUT_DEFAULT, null);
- }
- catch (JMSException e)
- {
- _publish = false;
- // log.debug("There was a JMSException: " + e.getMessage(), e);
- }
- catch (InterruptedException e)
- {
- _publish = false;
- // log.debug("There was an interruption: " + e.getMessage(), e);
- }
- }
-
- /**
- * Sets a chained message listener. The message listener on this pinger, chains all its messages to the one set
- * here.
- *
- * @param messageListener The chained message listener.
- */
- public void setChainedMessageListener(ChainedMessageListener messageListener)
- {
- _chainedMessageListener = messageListener;
- }
-
- /** Removes any chained message listeners from this pinger. */
- public void removeChainedMessageListener()
- {
- _chainedMessageListener = null;
- }
-
- /**
- * Generates a test message of the specified size, with the specified reply-to destination and persistence flag.
- *
- * @param replyQueue The reply-to destination for the message.
- * @param messageSize The desired size of the message in bytes.
- * @param persistent <tt>true</tt> if the message should use persistent delivery, <tt>false</tt> otherwise.
- *
- * @return A freshly generated test message.
- *
- * @throws javax.jms.JMSException All underlying JMSException are allowed to fall through.
- */
- public Message getTestMessage(Destination replyQueue, int messageSize, boolean persistent) throws JMSException
- {
- // return TestMessageFactory.newObjectMessage(_producerSession, replyQueue, messageSize, persistent);
- return TestUtils.createTestMessageOfSize(_producerSession, messageSize);
- }
-
- /**
- * Sets the current time in nanoseconds as the timestamp on the message.
- *
- * @param msg The message to timestamp.
- *
- * @throws JMSException Any JMSExceptions are allowed to fall through.
- */
- protected void setTimestamp(Message msg) throws JMSException
- {
- /*if (((AMQSession)_producerSession).isStrictAMQP())
- {
- ((AMQMessage)msg).setTimestampProperty(new AMQShortString(MESSAGE_TIMESTAMP_PROPNAME), System.nanoTime());
- }
- else
- {*/
- msg.setLongProperty(MESSAGE_TIMESTAMP_PROPNAME, System.nanoTime());
- // }
- }
-
- /**
- * Extracts the nanosecond timestamp from a message.
- *
- * @param msg The message to extract the time stamp from.
- *
- * @return The timestamp in nanos.
- *
- * @throws JMSException Any JMSExceptions are allowed to fall through.
- */
- protected long getTimestamp(Message msg) throws JMSException
- {
- /*if (((AMQSession)_producerSession).isStrictAMQP())
- {
- Long value = ((AMQMessage)msg).getTimestampProperty(new AMQShortString(MESSAGE_TIMESTAMP_PROPNAME));
-
- return (value == null) ? 0L : value;
- }
- else
- {*/
- return msg.getLongProperty(PingPongProducer.MESSAGE_TIMESTAMP_PROPNAME);
- // }
- }
-
- /**
- * Stops the ping loop by clearing the publish flag. The current loop will complete when it notices that this flag
- * has been cleared.
- */
- public void stop()
- {
- _publish = false;
- }
-
- /**
- * Starts the producer and consumer connections.
- *
- * @throws JMSException Any JMSExceptions are allowed to fall through.
- */
- public void start() throws JMSException
- {
- // log.debug("public void start(): called");
-
- _connection.start();
- // log.debug("Producer started.");
-
- for (int i = 0; i < _noOfConsumers; i++)
- {
- _consumerConnection[i].start();
- // log.debug("Consumer " + i + " started.");
- }
- }
-
- /** Implements a ping loop that repeatedly pings until the publish flag becomes false. */
- public void run()
- {
- // Keep running until the publish flag is cleared.
- while (_publish)
- {
- pingLoop();
- }
- }
-
- /**
- * Callback method, implementing ExceptionListener. This should be registered to listen for exceptions on the
- * connection, this clears the publish flag which in turn will halt the ping loop.
- *
- * @param e The exception that triggered this callback method.
- */
- public void onException(JMSException e)
- {
- // log.debug("public void onException(JMSException e = " + e + "): called", e);
- _publish = false;
- }
-
- /**
- * Gets a shutdown hook that will cleanly shut this down when it is running the ping loop. This can be registered
- * with the runtime system as a shutdown hook.
- *
- * @return A shutdown hook for the ping loop.
- */
- public Thread getShutdownHook()
- {
- return new Thread(new Runnable()
- {
- public void run()
- {
- stop();
- }
- });
- }
-
- /**
- * Closes all of the producer and consumer connections.
- *
- * @throws JMSException All JMSException are allowed to fall through.
- */
- public void close() throws JMSException
- {
- // log.debug("public void close(): called");
-
- try
- {
- if (_connection != null)
- {
- // log.debug("Before close producer connection.");
- _connection.close();
- // log.debug("Closed producer connection.");
- }
-
- for (int i = 0; i < _noOfConsumers; i++)
- {
- if (_consumerConnection[i] != null)
- {
- // log.debug("Before close consumer connection " + i + ".");
- _consumerConnection[i].close();
- // log.debug("Closed consumer connection " + i + ".");
- }
- }
- }
- finally
- {
- _connection = null;
- _producerSession = null;
- _consumerSession = null;
- _consumerConnection = null;
- _producer = null;
- _consumer = null;
- _pingDestinations = null;
- _replyDestination = null;
- }
- }
-
- /**
- * Convenience method to commit the transaction on the specified controlSession. If the controlSession to commit on is not a
- * transactional controlSession, this method does nothing (unless the failover after send flag is set).
- *
- * <p/>If the {@link #_failAfterSend} flag is set, this will prompt the user to kill the broker before the commit is
- * applied. This flag applies whether the pinger is transactional or not.
- *
- * <p/>If the {@link #_failBeforeCommit} flag is set, this will prompt the user to kill the broker before the commit
- * is applied. If the {@link #_failAfterCommit} flag is set, this will prompt the user to kill the broker after the
- * commit is applied. These flags will only apply if using a transactional pinger.
- *
- * @param session The controlSession to commit
- *
- * @return <tt>true</tt> if the controlSession was committed, <tt>false</tt> if it was not.
- *
- * @throws javax.jms.JMSException If the commit fails and then the rollback fails.
- *
- * @todo Consider moving the fail after send logic into the send method. It is confusing to have it in this commit
- * method, because commits only apply to transactional pingers, but fail after send applied to transactional and
- * non-transactional alike.
- */
- protected boolean commitTx(Session session) throws JMSException
- {
- // log.debug("protected void commitTx(Session session): called");
-
- boolean committed = false;
-
- _failAfterSend = waitForUserToPromptOnFailure(_failAfterSend);
-
- if (session.getTransacted())
- {
- // log.debug("Session is transacted.");
-
- try
- {
- _failBeforeCommit = waitForUserToPromptOnFailure(_failBeforeCommit);
-
- long start = System.nanoTime();
- session.commit();
- committed = true;
- // log.debug("Time taken to commit :" + ((System.nanoTime() - start) / 1000000f) + " ms");
-
- _failAfterCommit = waitForUserToPromptOnFailure(_failAfterCommit);
-
- // log.debug("Session Commited.");
- }
- catch (JMSException e)
- {
- // log.debug("JMSException on commit:" + e.getMessage(), e);
-
- try
- {
- session.rollback();
- // log.debug("Message rolled back.");
- }
- catch (JMSException jmse)
- {
- // log.debug("JMSE on rollback:" + jmse.getMessage(), jmse);
-
- // Both commit and rollback failed. Throw the rollback exception.
- throw jmse;
- }
- }
- }
-
- return committed;
- }
-
- /**
- * Outputs a prompt to the console and waits for the user to press return.
- *
- * @param prompt The prompt to display on the console.
- */
- public void waitForUser(String prompt)
- {
- System.out.println(prompt);
-
- try
- {
- System.in.read();
- }
- catch (IOException e)
- {
- // Ignored.
- }
-
- System.out.println("Continuing.");
- }
-
- /**
- * Gets the number of consumers that are listening to each destination in the test.
- *
- * @return int The number of consumers subscribing to each topic.
- */
- public int getConsumersPerDestination()
- {
- return _noOfConsumers;
- }
-
- /**
- * Calculates how many pings are expected to be received for the given number sent.
- *
- * @param numpings The number of pings that will be sent.
- *
- * @return The number that should be received, for the test to pass.
- */
- public int getExpectedNumPings(int numpings)
- {
- // log.debug("public int getExpectedNumPings(int numpings = " + numpings + "): called");
-
- // log.debug("Each ping will be received by " + (_isPubSub ? getConsumersPerDestination() : 1) + " consumers.");
-
- return numpings * (_isPubSub ? getConsumersPerDestination() : 1);
- }
-
- /**
- * Defines a chained message listener interface that can be attached to this pinger. Whenever this pinger's {@link
- * PingPongProducer#onMessageWithConsumerNo} method is called, the chained listener set through the {@link
- * PingPongProducer#setChainedMessageListener} method is passed the message, and the remaining expected count of
- * messages with that correlation id.
- *
- * <p/>Provided only one pinger is producing messages with that correlation id, the chained listener will always be
- * given unique message counts. It will always be called while the producer waiting for all messages to arrive is
- * still blocked.
- */
- public static interface ChainedMessageListener
- {
- /**
- * Notifies interested listeners about message arrival and important test stats, the number of messages
- * remaining in the test, and the messages send timestamp.
- *
- * @param message The newly arrived message.
- * @param remainingCount The number of messages left to complete the test.
- * @param latency The nanosecond latency of the message.
- *
- * @throws JMSException Any JMS exceptions is allowed to fall through.
- */
- public void onMessage(Message message, int remainingCount, long latency) throws JMSException;
- }
-
- /**
- * Holds information on each correlation id. The countdown latch, the current timeout timer... More stuff to be
- * added to this: read/write lock to make onMessage more concurrent as described in class header comment.
- */
- protected static class PerCorrelationId
- {
- /** Holds a countdown on number of expected messages. */
- CountDownLatch trafficLight;
-
- /** Holds the last timestamp that the timeout was reset to. */
- Long timeOutStart;
- }
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongTestPerf.java b/java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongTestPerf.java deleted file mode 100644 index 780589768f..0000000000 --- a/java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongTestPerf.java +++ /dev/null @@ -1,251 +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.requestreply; - -import junit.framework.Assert; -import junit.framework.Test; -import junit.framework.TestSuite; - -import org.apache.log4j.Logger; - -import uk.co.thebadgerset.junit.extensions.AsymptoticTestCase; -import uk.co.thebadgerset.junit.extensions.util.ParsedProperties; -import uk.co.thebadgerset.junit.extensions.util.TestContextProperties; - -import javax.jms.*; - -/** - * PingPongTestPerf is a full round trip ping test, that has been written with the intention of being scaled up to run - * many times simultaneously to simluate many clients/producer/connections. A full round trip ping sends a message from - * a producer to a conumer, then the consumer replies to the message on a temporary queue. - * - * <p/>A single run of the test using the default JUnit test runner will result in the sending and timing of the number - * of pings specified by the test size and time how long it takes for all of these to complete. This test may be scaled - * up using a suitable JUnit test runner. See {@link uk.co.thebadgerset.junit.extensions.TKTestRunner} for more - * information on how to do this. - * - * <p/>The setup/teardown cycle establishes a connection to a broker and sets up a queue to send ping messages to and a - * temporary queue for replies. This setup is only established once for all the test repeats, but each test threads - * gets its own connection/producer/consumer, this is only re-established if the connection is lost. - * - * <p/>The test cycle is: Connects to a queue, creates a temporary queue, creates messages containing a property that - * is the name of the temporary queue, fires off many messages on the original queue and waits for them all to come - * back on the temporary queue. - * - * <p/>Configurable test properties: message size, transacted or not, persistent or not. Broker connection details. - * - * <p><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * </table> - */ -public class PingPongTestPerf extends AsymptoticTestCase -{ - private static Logger _logger = Logger.getLogger(PingPongTestPerf.class); - - /** Thread local to hold the per-thread test setup fields. */ - ThreadLocal<PerThreadSetup> threadSetup = new ThreadLocal<PerThreadSetup>(); - - // Set up a property reader to extract the test parameters from. Once ContextualProperties is available in - // the project dependencies, use it to get property overrides for configurable tests and to notify the test runner - // of the test parameters to log with the results. It also providers some basic type parsing convenience methods. - // private Properties testParameters = System.getProperties(); - private ParsedProperties testParameters = - TestContextProperties.getInstance(PingPongProducer.defaults /*System.getProperties()*/); - - public PingPongTestPerf(String name) - { - super(name); - - _logger.debug(testParameters); - - // Sets up the test parameters with defaults. - /*testParameters.setPropertyIfNull(PingPongProducer.TX_BATCH_SIZE_PROPNAME, - Integer.toString(PingPongProducer.TX_BATCH_SIZE_DEFAULT)); - testParameters.setPropertyIfNull(PingPongProducer.MESSAGE_SIZE_PROPNAME, - Integer.toString(PingPongProducer.MESSAGE_SIZE_DEAFULT)); - testParameters.setPropertyIfNull(PingPongProducer.PING_QUEUE_NAME_PROPNAME, - PingPongProducer.PING_QUEUE_NAME_DEFAULT); - testParameters.setPropertyIfNull(PingPongProducer.PERSISTENT_MODE_PROPNAME, - Boolean.toString(PingPongProducer.PERSISTENT_MODE_DEFAULT)); - testParameters.setPropertyIfNull(PingPongProducer.TRANSACTED_PROPNAME, - Boolean.toString(PingPongProducer.TRANSACTED_DEFAULT)); - testParameters.setPropertyIfNull(PingPongProducer.BROKER_PROPNAME, PingPongProducer.BROKER_DEFAULT); - testParameters.setPropertyIfNull(PingPongProducer.USERNAME_PROPNAME, PingPongProducer.USERNAME_DEFAULT); - testParameters.setPropertyIfNull(PingPongProducer.PASSWORD_PROPNAME, PingPongProducer.PASSWORD_DEFAULT); - testParameters.setPropertyIfNull(PingPongProducer.VIRTUAL_HOST_PROPNAME, PingPongProducer.VIRTUAL_HOST_DEFAULT); - testParameters.setPropertyIfNull(PingPongProducer.VERBOSE_PROPNAME, - Boolean.toString(PingPongProducer.VERBOSE_DEFAULT)); - testParameters.setPropertyIfNull(PingPongProducer.RATE_PROPNAME, Integer.toString(PingPongProducer.RATE_DEFAULT)); - testParameters.setPropertyIfNull(PingPongProducer.PUBSUB_PROPNAME, - Boolean.toString(PingPongProducer.PUBSUB_DEFAULT)); - testParameters.setPropertyIfNull(PingPongProducer.TX_BATCH_SIZE_PROPNAME, - Integer.toString(PingPongProducer.TX_BATCH_SIZE_DEFAULT)); - testParameters.setPropertyIfNull(PingPongProducer.TIMEOUT_PROPNAME, Long.toString(PingPongProducer.TIMEOUT_DEFAULT)); - testParameters.setPropertyIfNull(PingPongProducer.DESTINATION_COUNT_PROPNAME, - Integer.toString(PingPongProducer.DESTINATION_COUNT_DEFAULT)); - testParameters.setPropertyIfNull(PingPongProducer.FAIL_AFTER_COMMIT_PROPNAME, - PingPongProducer.FAIL_AFTER_COMMIT_DEFAULT); - testParameters.setPropertyIfNull(PingPongProducer.FAIL_BEFORE_COMMIT_PROPNAME, - PingPongProducer.FAIL_BEFORE_COMMIT_DEFAULT); - testParameters.setPropertyIfNull(PingPongProducer.FAIL_AFTER_SEND_PROPNAME, - PingPongProducer.FAIL_AFTER_SEND_DEFAULT); - testParameters.setPropertyIfNull(PingPongProducer.FAIL_BEFORE_SEND_PROPNAME, - PingPongProducer.FAIL_BEFORE_SEND_DEFAULT); - testParameters.setPropertyIfNull(PingPongProducer.FAIL_ONCE_PROPNAME, PingPongProducer.FAIL_ONCE_DEFAULT); - testParameters.setPropertyIfNull(PingPongProducer.UNIQUE_DESTS_PROPNAME, - Boolean.toString(PingPongProducer.UNIQUE_DESTS_DEFAULT)); - testParameters.setPropertyIfNull(PingPongProducer.ACK_MODE_PROPNAME, - Integer.toString(PingPongProducer.ACK_MODE_DEFAULT)); - testParameters.setPropertyIfNull(PingPongProducer.PAUSE_AFTER_BATCH_PROPNAME, - PingPongProducer.PAUSE_AFTER_BATCH_DEFAULT);*/ - } - - /** - * Compile all the tests into a test suite. - */ - public static Test suite() - { - // Build a new test suite - TestSuite suite = new TestSuite("Ping-Pong Performance Tests"); - - // Run performance tests in read committed mode. - suite.addTest(new PingPongTestPerf("testPingPongOk")); - - return suite; - } - - private static void setSystemPropertyIfNull(String propName, String propValue) - { - if (System.getProperty(propName) == null) - { - System.setProperty(propName, propValue); - } - } - - public void testPingPongOk(int numPings) throws Exception - { - // Get the per thread test setup to run the test through. - PerThreadSetup perThreadSetup = threadSetup.get(); - - // Generate a sample message. This message is already time stamped and has its reply-to destination set. - Message msg = - perThreadSetup._testPingProducer.getTestMessage(perThreadSetup._testPingProducer.getReplyDestinations().get(0), - testParameters.getPropertyAsInteger(PingPongProducer.MESSAGE_SIZE_PROPNAME), - testParameters.getPropertyAsBoolean(PingPongProducer.PERSISTENT_MODE_PROPNAME)); - - // Send the message and wait for a reply. - int numReplies = - perThreadSetup._testPingProducer.pingAndWaitForReply(msg, numPings, PingPongProducer.TIMEOUT_DEFAULT, null); - - // Fail the test if the timeout was exceeded. - if (numReplies != numPings) - { - Assert.fail("The ping timed out, got " + numReplies + " out of " + numPings); - } - } - - /** - * Performs test fixture creation on a per thread basis. This will only be called once for each test thread. - */ - public void threadSetUp() - { - try - { - PerThreadSetup perThreadSetup = new PerThreadSetup(); - - // Extract the test set up paramaeters. - String fileProperties = testParameters.getProperty(PingPongProducer.FILE_PROPERTIES_PROPNAME); - String factoryName = testParameters.getProperty(PingPongProducer.FACTORY_NAME_PROPNAME); - String username = testParameters.getProperty(PingPongProducer.USERNAME_PROPNAME); - String password = testParameters.getProperty(PingPongProducer.PASSWORD_PROPNAME); - String destinationName = testParameters.getProperty(PingPongProducer.PING_QUEUE_NAME_PROPNAME); - boolean persistent = testParameters.getPropertyAsBoolean(PingPongProducer.PERSISTENT_MODE_PROPNAME); - boolean transacted = testParameters.getPropertyAsBoolean(PingPongProducer.TRANSACTED_PROPNAME); - String selector = testParameters.getProperty(PingPongProducer.SELECTOR_PROPNAME); - boolean verbose = testParameters.getPropertyAsBoolean(PingPongProducer.VERBOSE_PROPNAME); - boolean pubsub = testParameters.getPropertyAsBoolean(PingPongProducer.PUBSUB_PROPNAME); - - synchronized (this) - { - // Establish a bounce back client on the ping queue to bounce back the pings. - perThreadSetup._testPingBouncer = - new PingPongBouncer(fileProperties, factoryName, username, password, destinationName, persistent, - transacted, selector, verbose, pubsub); - - // Start the connections for client and producer running. - perThreadSetup._testPingBouncer.getConnection().start(); - - // Establish a ping-pong client on the ping queue to send the pings and receive replies with. - perThreadSetup._testPingProducer = new PingPongProducer(testParameters); - perThreadSetup._testPingProducer.establishConnection(true, true); - perThreadSetup._testPingProducer.start(); - } - - // Attach the per-thread set to the thread. - threadSetup.set(perThreadSetup); - } - catch (Exception e) - { - _logger.warn("There was an exception during per thread setup.", e); - } - } - - /** - * Performs test fixture clean - */ - public void threadTearDown() - { - _logger.debug("public void threadTearDown(): called"); - - try - { - // Get the per thread test fixture. - PerThreadSetup perThreadSetup = threadSetup.get(); - - // Close the pingers so that it cleans up its connection cleanly. - synchronized (this) - { - perThreadSetup._testPingProducer.close(); - // perThreadSetup._testPingBouncer.close(); - } - - // Ensure the per thread fixture is reclaimed. - threadSetup.remove(); - } - catch (JMSException e) - { - _logger.warn("There was an exception during per thread tear down."); - } - } - - protected static class PerThreadSetup - { - /** - * Holds the test ping-pong producer. - */ - private PingPongProducer _testPingProducer; - - /** - * Holds the test ping client. - */ - private PingPongBouncer _testPingBouncer; - } -} diff --git a/java/perftests/src/main/java/perftests.log4j b/java/perftests/src/main/java/perftests.log4j deleted file mode 100644 index badb617432..0000000000 --- a/java/perftests/src/main/java/perftests.log4j +++ /dev/null @@ -1,51 +0,0 @@ -#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-log4j.rootLogger=${root.logging.level}
-
-
-log4j.logger.org.apache.qpid=${amqj.logging.level}, console
-log4j.additivity.org.apache.qpid=false
-
-log4j.logger.org.apache.qpidity=${amqj.logging.level}, console
-log4j.additivity.org.apache.qpidity=false
-
-log4j.logger.org.apache.mina=ERROR, console
-log4j.additivity.org.apache.mina=false
-
-log4j.logger.org.apache.qpid.requestreply=${amqj.test.logging.level}
-log4j.logger.org.apache.qpid.pingpong=${amqj.test.logging.level}
-log4j.logger.org.apache.qpid.ping=${amqj.test.logging.level}
-log4j.logger.org.apache.qpid.topic=${amqj.test.logging.level}
-
-
-log4j.logger.uk.co.thebadgerset.junit.extensions=${badger.level}, console
-log4j.additivity.uk.co.thebadgerset.junit.extensions=false
-
-log4j.appender.console=org.apache.log4j.ConsoleAppender
-log4j.appender.console.Threshold=all
-log4j.appender.console.layout=org.apache.log4j.PatternLayout
-
-log4j.appender.console.layout.ConversionPattern=%t %d %p [%c{4}] %m%n
-#log4j.appender.console.layout.ConversionPattern=%t %p [%c] %m%n
-
-log4j.appender.fileApp=org.apache.log4j.FileAppender
-log4j.appender.fileApp.file=${log.dir}/perftests.volumetest.log
-log4j.appender.fileApp.Threshold=info
-log4j.appender.fileApp.append=false
-log4j.appender.fileApp.layout=org.apache.log4j.PatternLayout
diff --git a/java/perftests/src/main/java/perftests.properties b/java/perftests/src/main/java/perftests.properties deleted file mode 100644 index d97d0d3906..0000000000 --- a/java/perftests/src/main/java/perftests.properties +++ /dev/null @@ -1,46 +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.
-
-
-java.naming.factory.initial = org.apache.qpid.jndi.PropertiesFileInitialContextFactory
-
-# use the following property to configure the default connector
-#java.naming.provider.url - ignored.
-
-# register some connection factories
-# connectionfactory.[jndiname] = [ConnectionURL]
-#connectionfactory.local = amqp://guest:guest@clientid/test?brokerlist='tcp://192.168.1.10:5672'
-connectionfactory.local = amqp://guest:guest@clientid/test?brokerlist='tcp://localhost:5672'
-
-# A 0.10 connection factory
-##connectionfactory.local = qpid:password=pass;username=name@tcp:192.168.1.10:5672
-
-# register some queues in JNDI using the form
-# queue.[jndiName] = [physicalName]
-#queue.MyQueue = example.MyQueue
-queue.syncQueue = syncQueue
-queue.testQueue = testQueue
-
-# register some topics in JNDI using the form
-# topic.[jndiName] = [physicalName]
-#topic.ibmStocks = stocks.nyse.ibm
-topic.testTopic = testTopic
-
-# Register an AMQP destination in JNDI
-# NOTE: Qpid currently only supports direct,topics and headers
-# destination.[jniName] = [BindingURL]
-destination.direct = direct://amq.direct//directQueue
|