diff options
| author | Alex Rudyy <orudyy@apache.org> | 2015-04-15 09:47:28 +0000 |
|---|---|---|
| committer | Alex Rudyy <orudyy@apache.org> | 2015-04-15 09:47:28 +0000 |
| commit | 0a0baee45ebcff44635907d457c4ff6810b09c87 (patch) | |
| tree | 8bfb0f9eddbc23cff88af69be80ab3ce7d47011c /qpid/java/client | |
| parent | 54aa3d7070da16ce55c28ccad3f7d0871479e461 (diff) | |
| download | qpid-python-0a0baee45ebcff44635907d457c4ff6810b09c87.tar.gz | |
QPID-6481: Move java source tree to top level
git-svn-id: https://svn.apache.org/repos/asf/qpid/trunk@1673693 13f79535-47bb-0310-9956-ffa450edef68
Diffstat (limited to 'qpid/java/client')
248 files changed, 0 insertions, 49306 deletions
diff --git a/qpid/java/client/README.txt b/qpid/java/client/README.txt deleted file mode 100644 index a8c7da32c5..0000000000 --- a/qpid/java/client/README.txt +++ /dev/null @@ -1,49 +0,0 @@ -Documentation -============= - -You can access documentation for the client via our website at: -http://qpid.apache.org/documentation - -and via our wiki at: -http://cwiki.apache.org/confluence/display/qpid/Qpid+Java+Documentation - -The client uses the Java Message Service (JMS) 1.1 API, information on which is -widely available using your favoured search engine. - - -Running the Examples: -===================== - -1. From the client Binary distribution: - -From the <installation path>/qpid-client-<version> directory, there are examples -provided in source form in the example/src sub-directory. These are also -provided in binary form in the example/lib directory in order that they can be -run more easily. - -E.g, in order to run the Hello example, you would add the client+example library -files to the java classpath and launch the example like follows: - -java -cp "lib/qpid-all.jar:example/lib/qpid-client-example-<version>.jar" \ - org.apache.qpid.example.Hello - -NOTE: The client uses the SL4FJ API for its logging. You must supply a logging -implementation of your choice (eg Log4J) and its associated SLF4J binding, by -also adding them to the Java classpath as well as the client libraries -themselves. Failure to do so will result in a warning being output and use of -NoOp logging by the client. - -More information on using SLF4J is available at http://www.slf4j.org/manual.html -which details some of the supported logging implementations and their -associated SLF4 bindings as available in the SLF4J distribution. - - - -2. From the Source distribution / repository: - -Run 'ant build' in the parent directory from where this file is stored, ie: -<installation path>/qpid/java - -This will build the various Java modules, leaving binary .jar files output in: -<installation path>/qpid/java/build/lib - diff --git a/qpid/java/client/example/README.txt b/qpid/java/client/example/README.txt deleted file mode 100644 index 36e4351a51..0000000000 --- a/qpid/java/client/example/README.txt +++ /dev/null @@ -1,17 +0,0 @@ -=========================== -Running the client examples -=========================== - -Use maven to build the module, and additionally copy the dependencies -alongside their output: - - mvn clean package dependency:copy-dependencies -DincludeScope=runtime -DskipTests - -Now you can run the examples using commands of the format: - - java -cp "target/classes/:target/dependency/*" org.apache.qpid.example.Hello - - -NOTE: The earlier build command will cause Maven to resolve the client artifact -dependencies against its local and remote repositories. If you wish to use a -locally-built client, ensure to install it in your local maven repo first. diff --git a/qpid/java/client/example/pom.xml b/qpid/java/client/example/pom.xml deleted file mode 100644 index 8015f94624..0000000000 --- a/qpid/java/client/example/pom.xml +++ /dev/null @@ -1,66 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. ---> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> - <modelVersion>4.0.0</modelVersion> - - <parent> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-java-build</artifactId> - <version>0.32-SNAPSHOT</version> - <relativePath>../../pom.xml</relativePath> - </parent> - - <artifactId>qpid-client-examples</artifactId> - <name>Qpid AMQP 0-x JMS Client Examples</name> - <description>JMS client examples.</description> - - <dependencies> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-client</artifactId> - <version>${project.version}</version> - </dependency> - - <dependency> - <groupId>org.apache.geronimo.specs</groupId> - <artifactId>geronimo-jms_1.1_spec</artifactId> - <version>${geronimo-jms-1-1-version}</version> - </dependency> - - <dependency> - <groupId>org.slf4j</groupId> - <artifactId>slf4j-api</artifactId> - <version>${slf4j-version}</version> - </dependency> - </dependencies> - - <build> - <resources> - <resource> - <directory>src/main/resources</directory> - </resource> - <resource> - <directory>src/main/java</directory> - <excludes> - <exclude>**/*.java</exclude> - </excludes> - </resource> - </resources> - </build> - -</project> diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/Drain.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/Drain.java deleted file mode 100644 index f0eb83ad24..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/Drain.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.example; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.Session; - -import org.apache.qpid.client.AMQAnyDestination; - -public class Drain extends OptionParser -{ - - static final Option FOREVER = new Option("f", - "forever", - "ignore timeout and wait forever", - null, - null, - Boolean.class); - - static final Option COUNT = new Option ("c", - "count", - "read c messages, then exit", - "COUNT", - "0", - Integer.class); - - - static - { - addOption(BROKER); - addOption(HELP); - addOption(TIMEOUT); - addOption(FOREVER); - addOption(COUNT); - addOption(CON_OPTIONS); - addOption(BROKER_OPTIONS); - } - - public Drain(String[] args, String usage, String desc) throws Exception - { - super(args, usage, desc); - - Connection con = createConnection(); - con.start(); - Session ssn = con.createSession(false,Session.AUTO_ACKNOWLEDGE); - Destination dest = new AMQAnyDestination(getAddress()); - MessageConsumer consumer = ssn.createConsumer(dest); - Message msg; - - long timeout = -1; - int count = 0; - int i = 0; - - if (containsOp(TIMEOUT)) { timeout = Integer.parseInt(getOp(TIMEOUT))*1000; } - if (containsOp(FOREVER)) { timeout = 0; } - if (containsOp(COUNT)) { count = Integer.parseInt(getOp(COUNT)); } - - while ((msg = consumer.receive(timeout)) != null) - { - System.out.println("\n------------- Msg -------------"); - System.out.println(msg); - System.out.println("-------------------------------\n"); - - if (count > 0) { - if (++i == count) { - break; - } - } - } - consumer.close(); - ssn.close(); - con.close(); - } - - public static void main(String[] args) throws Exception - { - String u = "Usage: drain [OPTIONS] 'ADDRESS'"; - String d = "Drains messages from the specified address."; - - new Drain(args,u,d); - } -} diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/Hello.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/Hello.java deleted file mode 100644 index 109a72bcbf..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/Hello.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.example; - -import java.io.InputStream; -import java.util.Properties; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.Destination; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.naming.Context; -import javax.naming.InitialContext; - - -public class Hello -{ - - public Hello() - { - } - - public static void main(String[] args) - { - Hello hello = new Hello(); - hello.runTest(); - } - - private void runTest() - { - try (InputStream resourceAsStream = this.getClass().getResourceAsStream("hello.properties")) - { - Properties properties = new Properties(); - properties.load(resourceAsStream); - Context context = new InitialContext(properties); - - ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup("qpidConnectionfactory"); - Connection connection = connectionFactory.createConnection(); - connection.start(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = (Destination) context.lookup("topicExchange"); - - MessageProducer messageProducer = session.createProducer(destination); - MessageConsumer messageConsumer = session.createConsumer(destination); - - TextMessage message = session.createTextMessage("Hello world!"); - messageProducer.send(message); - - message = (TextMessage)messageConsumer.receive(); - System.out.println(message.getText()); - - connection.close(); - context.close(); - } - catch (Exception exp) - { - exp.printStackTrace(); - } - } -} diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/ListReceiver.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/ListReceiver.java deleted file mode 100644 index b12cfab9de..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/ListReceiver.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.example; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.MapMessage; -import javax.jms.StreamMessage; -import javax.jms.MessageConsumer; -import javax.jms.Session; -import javax.jms.MessageEOFException; - -import org.apache.qpid.client.AMQAnyDestination; -import org.apache.qpid.client.AMQConnection; - -import org.apache.qpid.jms.ListMessage; - -import java.util.Enumeration; -import java.util.Iterator; - -public class ListReceiver { - - public static void main(String[] args) throws Exception - { - if (args.length != 1) { - System.out.println("Usage: java org.apache.qpid.example.ListReceiver <-l | -m | -s>"); - System.out.println("where:"); - System.out.println("\t-l\tAccept ListMessage and print it"); - System.out.println("\t-m\tAccept ListMessage as a MapMessage"); - System.out.println("\t-s\tAccept ListMessage as a StreamMessage"); - return; - } - - Connection connection = - new AMQConnection("amqp://guest:guest@test/?brokerlist='tcp://localhost:5672'"); - - connection.start(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination queue = new AMQAnyDestination("ADDR:message_queue; {create: always}"); - MessageConsumer consumer = session.createConsumer(queue); - - if (args[0].equals("-l")) { - System.out.println("Receiving as ListMessage"); - ListMessage m = (ListMessage)consumer.receive(); - System.out.println(m); - System.out.println("=========================================="); - System.out.println("Printing list contents:"); - Iterator i = m.iterator(); - while(i.hasNext()) - System.out.println(i.next()); - } - else if (args[0].equals("-m")) { - System.out.println("Receiving as MapMessage"); - MapMessage m = (MapMessage)consumer.receive(); - System.out.println(m); - System.out.println("=========================================="); - System.out.println("Printing map contents:"); - Enumeration keys = m.getMapNames(); - while(keys.hasMoreElements()) { - String key = (String)keys.nextElement(); - System.out.println(key + " => " + m.getObject(key)); - } - } - else if (args[0].equals("-s")) { - System.out.println("Receiving as StreamMessage"); - StreamMessage m = (StreamMessage)consumer.receive(); - System.out.println(m); - System.out.println("=========================================="); - System.out.println("Printing stream contents:"); - try { - while(true) - System.out.println(m.readObject()); - } - catch (MessageEOFException e) { - // DONE - } - } - - connection.close(); - } -} diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/ListSender.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/ListSender.java deleted file mode 100644 index fe2c1ec472..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/ListSender.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.example; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.Message; -import javax.jms.MessageProducer; -import javax.jms.Session; - -import org.apache.qpid.client.AMQAnyDestination; -import org.apache.qpid.client.AMQConnection; - -import org.apache.qpid.jms.ListMessage; - - -public class ListSender { - - public static void main(String[] args) throws Exception - { - Connection connection = - new AMQConnection("amqp://guest:guest@test/?brokerlist='tcp://localhost:5672'"); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination queue = new AMQAnyDestination("ADDR:message_queue; {create: always}"); - MessageProducer producer = session.createProducer(queue); - - ListMessage m = ((org.apache.qpid.jms.Session)session).createListMessage(); - m.setIntProperty("Id", 987654321); - m.setStringProperty("name", "Widget"); - m.setDoubleProperty("price", 0.99); - - List<String> colors = new ArrayList<String>(); - colors.add("red"); - colors.add("green"); - colors.add("white"); - m.add(colors); - - Map<String,Double> dimensions = new HashMap<String,Double>(); - dimensions.put("length",10.2); - dimensions.put("width",5.1); - dimensions.put("depth",2.0); - m.add(dimensions); - - List<List<Integer>> parts = new ArrayList<List<Integer>>(); - parts.add(Arrays.asList(new Integer[] {1,2,5})); - parts.add(Arrays.asList(new Integer[] {8,2,5})); - m.add(parts); - - Map<String,Object> specs = new HashMap<String,Object>(); - specs.put("colours", colors); - specs.put("dimensions", dimensions); - specs.put("parts", parts); - m.add(specs); - - producer.send((Message)m); - System.out.println("Sent: " + m); - connection.close(); - } - -} diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/MapReceiver.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/MapReceiver.java deleted file mode 100644 index 89db04f8d3..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/MapReceiver.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.example; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.MapMessage; -import javax.jms.MessageConsumer; -import javax.jms.Session; - -import org.apache.qpid.client.AMQAnyDestination; -import org.apache.qpid.client.AMQConnection; - - -public class MapReceiver { - - public static void main(String[] args) throws Exception - { - Connection connection = - new AMQConnection("amqp://guest:guest@test/?brokerlist='tcp://localhost:5672'"); - - connection.start(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination queue = new AMQAnyDestination("ADDR:message_queue; {create: always}"); - MessageConsumer consumer = session.createConsumer(queue); - - MapMessage m = (MapMessage)consumer.receive(); - System.out.println(m); - connection.close(); - } - -}
\ No newline at end of file diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/MapSender.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/MapSender.java deleted file mode 100644 index 0ce9383add..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/MapSender.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.example; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.MapMessage; -import javax.jms.MessageProducer; -import javax.jms.Session; - -import org.apache.qpid.client.AMQAnyDestination; -import org.apache.qpid.client.AMQConnection; - - -public class MapSender { - - public static void main(String[] args) throws Exception - { - Connection connection = - new AMQConnection("amqp://guest:guest@test/?brokerlist='tcp://localhost:5672'"); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination queue = new AMQAnyDestination("ADDR:message_queue; {create: always}"); - MessageProducer producer = session.createProducer(queue); - - MapMessage m = session.createMapMessage(); - m.setIntProperty("Id", 987654321); - m.setStringProperty("name", "Widget"); - m.setDoubleProperty("price", 0.99); - - List<String> colors = new ArrayList<String>(); - colors.add("red"); - colors.add("green"); - colors.add("white"); - m.setObject("colours", colors); - - Map<String,Double> dimensions = new HashMap<String,Double>(); - dimensions.put("length",10.2); - dimensions.put("width",5.1); - dimensions.put("depth",2.0); - m.setObject("dimensions",dimensions); - - List<List<Integer>> parts = new ArrayList<List<Integer>>(); - parts.add(Arrays.asList(new Integer[] {1,2,5})); - parts.add(Arrays.asList(new Integer[] {8,2,5})); - m.setObject("parts", parts); - - Map<String,Object> specs = new HashMap<String,Object>(); - specs.put("colours", colors); - specs.put("dimensions", dimensions); - specs.put("parts", parts); - m.setObject("specs",specs); - - producer.send(m); - connection.close(); - } - -}
\ No newline at end of file diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/OptionParser.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/OptionParser.java deleted file mode 100644 index 9360be4106..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/OptionParser.java +++ /dev/null @@ -1,351 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.example; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.jms.Connection; - -import org.apache.qpid.client.AMQConnection; - -public class OptionParser -{ - static final Option BROKER = new Option("b", - "broker", - "connect to specified broker", - "USER:PASS@HOST:PORT", - "guest:guest@localhost:5672", - String.class); - - static final Option HELP = new Option("h", - "help", - "show this help message and exit", - null, - null, - Boolean.class); - - static final Option TIMEOUT = new Option("t", - "timeout", - "timeout in seconds to wait before exiting", - "TIMEOUT", - "0", - Integer.class); - - static final Option CON_OPTIONS = new Option(null, - "con-option", - "JMS Connection URL options. Ex sync_ack=true sync_publish=all ", - "NAME=VALUE", - null, - String.class); - - - static final Option BROKER_OPTIONS = new Option(null, - "broker-option", - "JMS Broker URL options. Ex ssl=true sasl_mechs=GSSAPI ", - "NAME=VALUE", - null, - String.class); - - - private Map<String,Object> optMap = new HashMap<String,Object>(); - private static final List<Option> optDefs = new ArrayList<Option>(); - - private static final String CLIENTID = "test"; - - private String usage; - private String desc; - private String address; - - public OptionParser(String[] args, String usage, String desc) - { - this.usage = usage; - this.desc = desc; - - if (args.length == 0 || - (args.length == 1 && (args[0].equals("-h") || args[0].equals("--help")))) - { - printHelp(); - } - - address = args[args.length -1]; - String[] ops = new String[args.length -1]; - System.arraycopy(args, 0, ops, 0, ops.length); - parseOpts(ops); - - System.out.println(optMap); - - if (isHelp()) - { - printHelp(); - } - } - - public boolean isHelp() - { - return optMap.containsKey("h") || optMap.containsKey("help"); - } - - public void printHelp() - { - System.out.println(String.format("%s\n",usage)); - System.out.println(String.format("%s\n",desc)); - System.out.println(String.format("%s\n","Options:")); - - for (Option op : optDefs) - { - String valueLabel = op.getValueLabel() != null ? "=" + op.getValueLabel() : ""; - String shortForm = op.getShortForm() != null ? "-" + op.getShortForm() + valueLabel : ""; - String longForm = op.getLongForm() != null ? "--" + op.getLongForm() + valueLabel : ""; - String desc = op.getDesc(); - String defaultValue = op.getDefaultValue() != null ? - " (default " + op.getDefaultValue() + ")" : ""; - - if (!shortForm.equals("")) - { - longForm = shortForm + ", " + longForm; - } - System.out.println( - String.format("%-54s%s%s", longForm,desc,defaultValue)); - } - - System.exit(0); - } - - private void parseOpts(String[] args) - { - String prevOpt = null; - for(String op: args) - { - // covers both -h and --help formats - if (op.startsWith("-")) - { - String key = op.substring(op.startsWith("--")? 2:1 , - (op.indexOf('=') > 0) ? - op.indexOf('='): - op.length()); - - boolean match = false; - for (Option option: optDefs) - { - - if ((op.startsWith("-") && option.getShortForm() != null && option.getShortForm().equals(key)) || - (op.startsWith("--") && option.getLongForm() != null && option.getLongForm().equals(key)) ) - { - match = true; - break; - } - } - - if (!match) - { - System.out.println(op + " is not a valid option"); - System.exit(0); - } - - if (op.indexOf('=') > 0) - { - String val = extractValue(op.substring(op.indexOf('=')+1)); - if (optMap.containsKey(key)) - { - optMap.put(key, optMap.get(key) + "," + val); - } - else - { - optMap.put(key, val); - } - } - else - { - if (! optMap.containsKey(key)){ optMap.put(key, ""); } - prevOpt = key; - } - } - else if (prevOpt != null) // this is to catch broker localhost:5672 instead broker=localhost:5672 - { - String val = extractValue(op); - if (optMap.containsKey(prevOpt) && !optMap.get(prevOpt).toString().equals("")) - { - optMap.put(prevOpt, optMap.get(prevOpt) + "," + val); - } - else - { - optMap.put(prevOpt, val); - } - prevOpt = null; - } - else - { - System.out.println(optMap); - throw new IllegalArgumentException(op + " is not a valid option"); - } - } - } - - private String extractValue(String op) - { - if (op.startsWith("'")) - { - if (!op.endsWith("'")) - { - throw new IllegalArgumentException(" The option " + op + " needs to be inside quotes"); - } - - return op.substring(1,op.length() -1); - } - else - { - return op; - } - } - - protected boolean containsOp(Option op) - { - return optMap.containsKey(op.getShortForm()) || optMap.containsKey(op.getLongForm()); - } - - protected String getOp(Option op) - { - if (optMap.containsKey(op.getShortForm())) - { - return (String)optMap.get(op.getShortForm()); - } - else if (optMap.containsKey(op.getLongForm())) - { - return (String)optMap.get(op.getLongForm()); - } - else - { - return op.getDefaultValue(); - } - } - - protected Connection createConnection() throws Exception - { - StringBuffer buf; - buf = new StringBuffer(); - buf.append("amqp://"); - String userPass = "guest:guest"; - String broker = "localhost:5672"; - if(containsOp(BROKER)) - { - try - { - String b = getOp(BROKER); - userPass = b.substring(0,b.indexOf('@')); - broker = b.substring(b.indexOf('@')+1); - } - catch (StringIndexOutOfBoundsException e) - { - Exception ex = new Exception("Error parsing broker string " + getOp(BROKER)); - ex.initCause(e); - throw ex; - } - - } - - if(containsOp(BROKER_OPTIONS)) - { - String bOps = getOp(BROKER_OPTIONS); - bOps = bOps.replaceAll(",", "'&"); - bOps = bOps.replaceAll("=", "='"); - broker = broker + "?" + bOps + "'"; - } - buf.append(userPass); - buf.append("@"); - buf.append(CLIENTID); - buf.append("/?brokerlist='tcp://"); - buf.append(broker).append("'"); - if(containsOp(CON_OPTIONS)) - { - String bOps = getOp(CON_OPTIONS); - bOps = bOps.replaceAll(",", "'&"); - bOps = bOps.replaceAll("=", "='"); - buf.append("&").append(bOps).append("'"); - } - - Connection con = new AMQConnection(buf.toString()); - return con; - } - - public static void addOption(Option opt) - { - optDefs.add(opt); - } - - protected String getAddress() - { - return address; - } - - static class Option - { - private final String shortForm; - private final String longForm; - private final String desc; - private final String valueLabel; - private final String defaultValue; - private final Class type; - - public Option(String shortForm, String longForm, String desc, - String valueLabel, String defaultValue, Class type) - { - this.shortForm = shortForm; - this.longForm = longForm; - this.defaultValue = defaultValue; - this.type = type; - this.desc = desc; - this.valueLabel = valueLabel; - } - - public String getShortForm() - { - return shortForm; - } - - public String getLongForm() - { - return longForm; - } - - public String getDefaultValue() - { - return defaultValue; - } - - public Class getType() - { - return type; - } - - public String getDesc() - { - return desc; - } - - public String getValueLabel() - { - return valueLabel; - } - } -} diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/Spout.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/Spout.java deleted file mode 100644 index 09e813f8c1..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/Spout.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.example; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.MapMessage; -import javax.jms.Message; -import javax.jms.MessageProducer; -import javax.jms.Session; - -import org.apache.qpid.client.AMQAnyDestination; - -public class Spout extends OptionParser -{ - - static final Option COUNT = new Option("c", - "count", - "stop after count messages have been sent, zero disables", - "COUNT", - "1", - Integer.class); - - static final Option ID = new Option("i", - "id", - "use the supplied id instead of generating one", - null, - null, - Boolean.class); - - static final Option CONTENT = new Option(null, - "content", - "specify textual content", - "TEXT", - null, - Boolean.class); - - static final Option MSG_PROPERTY = new Option("P", - "property", - "specify message property", - "NAME=VALUE", - null, - Boolean.class); - - static final Option MAP_ENTRY = new Option("M", - "map", - "specify entry for map content", - "KEY=VALUE", - null, - Boolean.class); - - static - { - addOption(BROKER); - addOption(HELP); - addOption(TIMEOUT); - addOption(COUNT); - addOption(MSG_PROPERTY); - addOption(MAP_ENTRY); - addOption(CONTENT); - addOption(CON_OPTIONS); - addOption(BROKER_OPTIONS); - } - - public Spout(String[] args, String usage, String desc) throws Exception - { - super(args, usage, desc); - - Connection con = createConnection(); - con.start(); - Session ssn = con.createSession(false,Session.AUTO_ACKNOWLEDGE); - Destination dest = new AMQAnyDestination(getAddress()); - MessageProducer producer = ssn.createProducer(dest); - - int count = Integer.parseInt(getOp(COUNT)); - - for (int i=0; i < count; i++) - { - Message msg = createMessage(ssn); - producer.send(msg); - System.out.println("\n------------- Msg -------------"); - System.out.println(msg); - System.out.println("-------------------------------\n"); - } - producer.close(); - ssn.close(); - con.close(); - } - - private Message createMessage(Session ssn) throws Exception - { - if (containsOp(MAP_ENTRY)) - { - MapMessage msg = ssn.createMapMessage(); - for (String pair: getOp(MAP_ENTRY).split(",")) - { - msg.setString(pair.substring(0, pair.indexOf('=')), - pair.substring(pair.indexOf('=') + 1)); - } - setProperties(msg); - return msg; - } - else - { - Message msg = - ssn.createTextMessage(containsOp(CONTENT) ? getOp(CONTENT) : ""); - setProperties(msg); - return msg; - } - } - - private void setProperties(Message m) throws Exception - { - if(containsOp(MSG_PROPERTY)) - { - for (String pair: getOp(MSG_PROPERTY).split(",")) - { - m.setStringProperty(pair.substring(0, pair.indexOf('=')), - pair.substring(pair.indexOf('=') + 1)); - } - } - } - - public static void main(String[] args) throws Exception - { - String u = "Usage: spout [OPTIONS] 'ADDRESS'"; - String d = "Send messages to the specified address."; - - new Spout(args,u,d); - } -} diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/hello.properties b/qpid/java/client/example/src/main/java/org/apache/qpid/example/hello.properties deleted file mode 100644 index fdfbd418f8..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/hello.properties +++ /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. -# -java.naming.factory.initial = org.apache.qpid.jndi.PropertiesFileInitialContextFactory - -# register some connection factories -# connectionfactory.[jndiname] = [ConnectionURL] -connectionfactory.qpidConnectionfactory = amqp://guest:guest@clientid/?brokerlist='tcp://localhost:5672' - -# Register an AMQP destination in JNDI -# destination.[jniName] = [Address Format] -destination.topicExchange = amq.topic diff --git a/qpid/java/client/pom.xml b/qpid/java/client/pom.xml deleted file mode 100644 index e491151a8f..0000000000 --- a/qpid/java/client/pom.xml +++ /dev/null @@ -1,126 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. ---> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> - <modelVersion>4.0.0</modelVersion> - - <parent> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-java-build</artifactId> - <version>0.32-SNAPSHOT</version> - </parent> - - <artifactId>qpid-client</artifactId> - <name>Qpid AMQP 0-x JMS Client</name> - <description>JMS client supporting AMQP 0-8, 0-9, 0-9-1 and 0-10.</description> - - <properties> - <dependency-change-verification>true</dependency-change-verification> - </properties> - - <dependencies> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-common</artifactId> - <version>${project.version}</version> - </dependency> - - <dependency> - <groupId>org.apache.geronimo.specs</groupId> - <artifactId>geronimo-jms_1.1_spec</artifactId> - <version>${geronimo-jms-1-1-version}</version> - <scope>provided</scope> - </dependency> - - <dependency> - <groupId>org.slf4j</groupId> - <artifactId>slf4j-api</artifactId> - <version>${slf4j-version}</version> - </dependency> - - <!-- test dependencies --> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-test-utils</artifactId> - <version>${project.version}</version> - <scope>test</scope> - </dependency> - - <dependency> - <groupId>log4j</groupId> - <artifactId>log4j</artifactId> - <version>${log4j-version}</version> - <scope>test</scope> - </dependency> - - <dependency> - <groupId>org.slf4j</groupId> - <artifactId>slf4j-log4j12</artifactId> - <version>${slf4j-version}</version> - <scope>test</scope> - </dependency> - </dependencies> - - <build> - <resources> - <resource> - <directory>src/main/resources</directory> - </resource> - <resource> - <directory>src/main/java</directory> - <excludes> - <exclude>**/*.java/</exclude> - </excludes> - </resource> - </resources> - - <testResources> - <testResource> - <directory>${basedir}/src/test/java</directory> - <excludes> - <exclude>**/*.java/</exclude> - </excludes> - </testResource> - <testResource> - <directory>${basedir}/src/test/resources</directory> - </testResource> - </testResources> - - <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-assembly-plugin</artifactId> - <!--version specified in parent pluginManagement --> - <configuration> - <descriptors> - <descriptor>src/main/assembly/qpid-client-bin.xml</descriptor> - </descriptors> - </configuration> - <executions> - <execution> - <id>make-assembly</id> - <phase>package</phase> - <goals> - <goal>single</goal> - </goals> - </execution> - </executions> - </plugin> - </plugins> - </build> - -</project> diff --git a/qpid/java/client/src/main/assembly/LICENSE b/qpid/java/client/src/main/assembly/LICENSE deleted file mode 100644 index 19995e9050..0000000000 --- a/qpid/java/client/src/main/assembly/LICENSE +++ /dev/null @@ -1,234 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) 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. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. - - - -############################################### -# Third Party Dependency Licensing Information: -############################################### - -This product bundles the SLF4J API, which is distributed under -the MIT licence: - -Copyright (c) 2004-2013 QOS.ch -All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - diff --git a/qpid/java/client/src/main/assembly/NOTICE b/qpid/java/client/src/main/assembly/NOTICE deleted file mode 100644 index 4952a853c6..0000000000 --- a/qpid/java/client/src/main/assembly/NOTICE +++ /dev/null @@ -1,10 +0,0 @@ -Qpid AMQP 0-x JMS Client -Copyright 2006-2014 The Apache Software Foundation - -This product includes software developed at -The Apache Software Foundation (http://www.apache.org/). - -############################################### - -Apache Geronimo JMS 1.1 Spec -Copyright 2003-2008 The Apache Software Foundation
\ No newline at end of file diff --git a/qpid/java/client/src/main/assembly/README.txt b/qpid/java/client/src/main/assembly/README.txt deleted file mode 100644 index eec46a52f0..0000000000 --- a/qpid/java/client/src/main/assembly/README.txt +++ /dev/null @@ -1,3 +0,0 @@ -Documentation for the Qpid components can be accessed on our website at: - -http://qpid.apache.org/documentation.html diff --git a/qpid/java/client/src/main/assembly/dependency-verification/DEPENDENCIES_REFERENCE b/qpid/java/client/src/main/assembly/dependency-verification/DEPENDENCIES_REFERENCE deleted file mode 100644 index 2ed83f3e48..0000000000 --- a/qpid/java/client/src/main/assembly/dependency-verification/DEPENDENCIES_REFERENCE +++ /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. -# - -#// ------------------------------------------------------------------ -# TRIMMED 3RD PARTY DEPENDENCY INFORMATION FOR MODIFICATION CHECKS -#// ------------------------------------------------------------------ - - - -From: 'QOS.ch' (http://www.qos.ch) - - SLF4J API Module (http://www.slf4j.org) org.slf4j:slf4j-api:jar:1.6.4 - License: MIT License (http://www.opensource.org/licenses/mit-license.php) - -From: 'The Apache Software Foundation' (http://www.apache.org/) - - Qpid Common (http://qpid.apache.org/qpid-java-build/management/qpid-common) org.apache.qpid:qpid-common:jar - License: The Apache Software License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.txt) - - - - diff --git a/qpid/java/client/src/main/assembly/qpid-client-bin.xml b/qpid/java/client/src/main/assembly/qpid-client-bin.xml deleted file mode 100644 index afdc6b8dfb..0000000000 --- a/qpid/java/client/src/main/assembly/qpid-client-bin.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. - ---> -<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd"> - <id>bin</id> - <formats> - <format>tar.gz</format> - </formats> - <baseDirectory>qpid-client/${project.version}</baseDirectory> - <fileSets> - <fileSet> - <directory>${basedir}/src/main/assembly/</directory> - <outputDirectory>/</outputDirectory> - <includes> - <include>README.txt</include> - <include>NOTICE</include> - <include>LICENSE</include> - </includes> - <fileMode>0644</fileMode> - <directoryMode>0755</directoryMode> - </fileSet> - <fileSet> - <directory>${basedir}/example</directory> - <outputDirectory>example</outputDirectory> - <includes> - <include>src/**</include> - <include>pom.xml</include> - <include>README.txt</include> - </includes> - <fileMode>0644</fileMode> - <directoryMode>0755</directoryMode> - </fileSet> - </fileSets> - <dependencySets> - <dependencySet> - <outputDirectory>/lib</outputDirectory> - <useProjectArtifact>true</useProjectArtifact> - </dependencySet> - <dependencySet> - <outputDirectory>/lib</outputDirectory> - <useProjectArtifact>false</useProjectArtifact> - <scope>provided</scope> - <includes> - <include>org.apache.geronimo.specs:geronimo-jms_1.1_spec</include> - </includes> - </dependencySet> - </dependencySets> -</assembly> - diff --git a/qpid/java/client/src/main/java/client.bnd b/qpid/java/client/src/main/java/client.bnd deleted file mode 100755 index 997f1e2d42..0000000000 --- a/qpid/java/client/src/main/java/client.bnd +++ /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. -# - -ver: 0.31.0 - -Bundle-SymbolicName: qpid-client -Bundle-Version: ${ver} -Export-Package: *;version=${ver} -Bundle-RequiredExecutionEnvironment: J2SE-1.5 -DynamicImport-Package: * - diff --git a/qpid/java/client/src/main/java/client.log4j b/qpid/java/client/src/main/java/client.log4j deleted file mode 100644 index 19cc946118..0000000000 --- a/qpid/java/client/src/main/java/client.log4j +++ /dev/null @@ -1,33 +0,0 @@ -#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-log4j.rootLogger=${root.logging.level}
-
-
-#log4j.logger.org.apache.qpid=${amqj.logging.level}, console
-#log4j.additivity.org.apache.qpid=false
-
-log4j.logger.org.apache.qpid=ERROR, console
-log4j.additivity.org.apache.qpid=false
-
-#log4j.logger.org.apache.qpid.client.message.AbstractBytesTypedMessage=DEBUG, console
-
-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
diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQAnyDestination.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQAnyDestination.java deleted file mode 100644 index 57f8343874..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQAnyDestination.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.client; - -import java.net.URISyntaxException; - -import javax.jms.JMSException; -import javax.jms.Queue; -import javax.jms.Topic; - -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.messaging.Address; -import org.apache.qpid.url.BindingURL; - -/** - * In order to support JMS 1.0 the Qpid implementation maps the - * direct exchange to JMS Queue and topic exchange to JMS Topic. - * - * The JMS 1.1 spec provides a javax.Destination as an abstraction - * to represent any type of destination. - * The abstract class AMQDestination has most of the functionality - * to support any destination defined in AMQP 0-10 spec. - */ -public class AMQAnyDestination extends AMQDestination implements Queue, Topic -{ - private static final long serialVersionUID = 2853054849716163231L; - - public AMQAnyDestination() - { - super(); - } - - public AMQAnyDestination(BindingURL binding) - { - super(binding); - } - - public AMQAnyDestination(String str) throws URISyntaxException - { - super(str); - } - - public AMQAnyDestination(Address addr) - { - super(addr); - } - - public AMQAnyDestination(AMQShortString exchangeName,AMQShortString exchangeClass, - AMQShortString routingKey,boolean isExclusive, - boolean isAutoDelete, AMQShortString queueName, - boolean isDurable, AMQShortString[] bindingKeys) - { - super(exchangeName, exchangeClass, routingKey, isExclusive, isAutoDelete, queueName, isDurable, bindingKeys); - } - - @Override - public boolean isNameRequired() - { - return getAMQQueueName() == null; - } - - public String getTopicName() throws JMSException - { - if (getRoutingKey() != null) - { - return getRoutingKey().asString(); - } - else if (getSubject() != null) - { - return getSubject(); - } - else - { - return null; - } - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQAuthenticationException.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQAuthenticationException.java deleted file mode 100644 index 67885777f0..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQAuthenticationException.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.client; - -import org.apache.qpid.AMQException; -import org.apache.qpid.protocol.AMQConstant; - -/** - * AMQAuthenticationException represents all failures to authenticate access to a broker. - * <p> - * TODO Will this alwyas have the same status code, NOT_ALLOWED 530? Might set this up to always use that code. - */ -public class AMQAuthenticationException extends AMQException -{ - public AMQAuthenticationException(AMQConstant error, String msg, Throwable cause) - { - super(error, msg, cause); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQBrokerDetails.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQBrokerDetails.java deleted file mode 100644 index 9d9278b74d..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQBrokerDetails.java +++ /dev/null @@ -1,507 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; - -import java.io.Serializable; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.HashMap; -import java.util.Map; - -import org.apache.qpid.configuration.ClientProperties; -import org.apache.qpid.jms.BrokerDetails; -import org.apache.qpid.transport.ConnectionSettings; -import org.apache.qpid.url.URLHelper; -import org.apache.qpid.url.URLSyntaxException; - -public class AMQBrokerDetails implements BrokerDetails, Serializable -{ - private static final long serialVersionUID = 8450786374975932890L; - - private String _host; - private int _port; - private String _transport; - - private Map<String, String> _options = new HashMap<String, String>(); - - public AMQBrokerDetails(BrokerDetails details) - { - _host = details.getHost(); - _port = details.getPort(); - _transport = details.getTransport(); - _options = new HashMap<>(details.getProperties()); - } - - public AMQBrokerDetails(){} - - public AMQBrokerDetails(String url) throws URLSyntaxException - { - - // URL should be of format tcp://host:port?option='value',option='value' - try - { - URI connection = new URI(url); - - String transport = connection.getScheme(); - - // Handles some defaults to minimise changes to existing broker URLS e.g. localhost - if (transport != null) - { - //todo this list of valid transports should be enumerated somewhere - if (!(transport.equalsIgnoreCase(BrokerDetails.TCP))) - { - if (transport.equalsIgnoreCase("localhost")) - { - connection = new URI(DEFAULT_TRANSPORT + "://" + url); - transport = connection.getScheme(); - } - else - { - if (url.charAt(transport.length()) == ':' && url.charAt(transport.length() + 1) != '/') - { - //Then most likely we have a host:port value - connection = new URI(DEFAULT_TRANSPORT + "://" + url); - transport = connection.getScheme(); - } - else - { - throw URLHelper.parseError(0, transport.length(), "Unknown transport", url); - } - } - } - else if (url.indexOf("//") == -1) - { - throw new URLSyntaxException(url, "Missing '//' after the transport In broker URL",transport.length()+1,1); - } - } - else - { - //Default the transport - connection = new URI(DEFAULT_TRANSPORT + "://" + url); - transport = connection.getScheme(); - } - - if (transport == null) - { - throw URLHelper.parseError(-1, "Unknown transport in broker URL:'" - + url + "' Format: " + URL_FORMAT_EXAMPLE, ""); - } - - setTransport(transport); - - String host = connection.getHost(); - - // Fix for Java 1.5 - if (host == null) - { - host = ""; - - String auth = connection.getAuthority(); - if (auth != null) - { - // contains both host & port myhost:5672 - if (auth.contains(":")) - { - host = auth.substring(0,auth.indexOf(":")); - } - else - { - host = auth; - } - } - - } - - setHost(host); - - int port = connection.getPort(); - - if (port == -1) - { - // Fix for when there is port data but it is not automatically parseable by getPort(). - String auth = connection.getAuthority(); - - if (auth != null && auth.contains(":")) - { - int start = auth.indexOf(":") + 1; - int end = start; - boolean looking = true; - boolean found = false; - // Throw an URL exception if the port number is not specified - if (start == auth.length()) - { - throw URLHelper.parseError(connection.toString().indexOf(auth) + end - 1, - connection.toString().indexOf(auth) + end, "Port number must be specified", - connection.toString()); - } - //Walk the authority looking for a port value. - while (looking) - { - try - { - end++; - Integer.parseInt(auth.substring(start, end)); - - if (end >= auth.length()) - { - looking = false; - found = true; - } - } - catch (NumberFormatException nfe) - { - looking = false; - } - - } - if (found) - { - setPort(Integer.parseInt(auth.substring(start, end))); - } - else - { - throw URLHelper.parseError(connection.toString().indexOf(connection.getAuthority()) + end - 1, - "Illegal character in port number", connection.toString()); - } - - } - else - { - setPort(DEFAULT_PORT); - } - } - else - { - setPort(port); - } - - String queryString = connection.getQuery(); - - URLHelper.parseOptions(_options, queryString); - - //Fragment is #string (not used) - } - catch (URISyntaxException uris) - { - if (uris instanceof URLSyntaxException) - { - throw(URLSyntaxException) uris; - } - - throw URLHelper.parseError(uris.getIndex(), uris.getReason(), uris.getInput()); - } - } - - public AMQBrokerDetails(String host, int port) - { - _host = host; - _port = port; - } - - public String getHost() - { - return _host; - } - - public void setHost(String _host) - { - this._host = _host; - } - - public int getPort() - { - return _port; - } - - public void setPort(int _port) - { - this._port = _port; - } - - public String getTransport() - { - return _transport; - } - - public void setTransport(String _transport) - { - this._transport = _transport; - } - - - public String getProperty(String key) - { - return _options.get(key); - } - - public void setProperty(String key, String value) - { - _options.put(key, value); - } - - private int lookupConnectTimeout() - { - if (_options.containsKey(OPTIONS_CONNECT_TIMEOUT)) - { - try - { - return Integer.parseInt(_options.get(OPTIONS_CONNECT_TIMEOUT)); - } - catch (NumberFormatException nfe) - { - //Do nothing as we will use the default below. - } - } - - return BrokerDetails.DEFAULT_CONNECT_TIMEOUT; - } - - public boolean getBooleanProperty(String propName) - { - return getBooleanProperty(propName, false); - } - - public boolean getBooleanProperty(String propName, boolean defaultValue) - { - if (_options.containsKey(propName)) - { - if (_options.get(propName).equalsIgnoreCase("false")) - { - return false; - } - else if (_options.get(propName).equalsIgnoreCase("true")) - { - return true; - } - else - { - return defaultValue; - } - } - else - { - return defaultValue; - } - } - - private int getIntegerProperty(String key) - { - String stringValue = getProperty(key); - try - { - return Integer.parseInt(stringValue); - } - catch (NumberFormatException e) - { - throw new IllegalArgumentException("Cannot parse key " + key + " with value '" + stringValue + "' as integer.", e); - } - } - - public String toString() - { - StringBuffer sb = new StringBuffer(); - - sb.append(_transport); - sb.append("://"); - sb.append(_host); - sb.append(':'); - sb.append(_port); - - sb.append(printOptionsURL()); - - return sb.toString(); - } - - public boolean equals(Object o) - { - if (!(o instanceof BrokerDetails)) - { - return false; - } - - BrokerDetails bd = (BrokerDetails) o; - - return _host.toLowerCase().equals(bd.getHost() == null ? null : bd.getHost().toLowerCase()) && - (_port == bd.getPort()) && - _transport.toLowerCase().equals(bd.getTransport() == null ? null : bd.getTransport().toLowerCase()); - //TODO do we need to compare all the options as well? - } - - @Override - public int hashCode() - { - int result = _host != null ? _host.toLowerCase().hashCode() : 0; - result = 31 * result + _port; - result = 31 * result + (_transport != null ? _transport.toLowerCase().hashCode() : 0); - return result; - } - - private String printOptionsURL() - { - StringBuffer optionsURL = new StringBuffer(); - - optionsURL.append('?'); - - if (!(_options.isEmpty())) - { - - for (String key : _options.keySet()) - { - optionsURL.append(key); - - optionsURL.append("='"); - - if (OPTIONS_TRUST_STORE_PASSWORD.equals(key) || OPTIONS_KEY_STORE_PASSWORD.equals(key)) - { - optionsURL.append("********"); - } - else - { - optionsURL.append(_options.get(key)); - } - - optionsURL.append("'"); - - optionsURL.append(URLHelper.DEFAULT_OPTION_SEPERATOR); - } - } - - //removeKey the extra DEFAULT_OPTION_SEPERATOR or the '?' if there are no options - optionsURL.deleteCharAt(optionsURL.length() - 1); - - return optionsURL.toString(); - } - - public static String checkTransport(String broker) - { - if ((!broker.contains("://"))) - { - return "tcp://" + broker; - } - else - { - return broker; - } - } - - public Map<String, String> getProperties() - { - return _options; - } - - public void setProperties(Map<String, String> props) - { - _options = props; - } - - public ConnectionSettings buildConnectionSettings() - { - ConnectionSettings conSettings = new ConnectionSettings(); - - conSettings.setHost(getHost()); - conSettings.setPort(getPort()); - - // ------------ sasl options --------------- - if (getProperty(BrokerDetails.OPTIONS_SASL_MECHS) != null) - { - conSettings.setSaslMechs( - getProperty(BrokerDetails.OPTIONS_SASL_MECHS)); - } - - // Sun SASL Kerberos client uses the - // protocol + servername as the service key. - - if (getProperty(BrokerDetails.OPTIONS_SASL_PROTOCOL_NAME) != null) - { - conSettings.setSaslProtocol( - getProperty(BrokerDetails.OPTIONS_SASL_PROTOCOL_NAME)); - } - - - if (getProperty(BrokerDetails.OPTIONS_SASL_SERVER_NAME) != null) - { - conSettings.setSaslServerName( - getProperty(BrokerDetails.OPTIONS_SASL_SERVER_NAME)); - } - - conSettings.setUseSASLEncryption( - getBooleanProperty(BrokerDetails.OPTIONS_SASL_ENCRYPTION)); - - // ------------- ssl options --------------------- - conSettings.setUseSSL(getBooleanProperty(BrokerDetails.OPTIONS_SSL)); - - if (getProperty(BrokerDetails.OPTIONS_TRUST_STORE) != null) - { - conSettings.setTrustStorePath( - getProperty(BrokerDetails.OPTIONS_TRUST_STORE)); - } - - if (getProperty(BrokerDetails.OPTIONS_TRUST_STORE_PASSWORD) != null) - { - conSettings.setTrustStorePassword( - getProperty(BrokerDetails.OPTIONS_TRUST_STORE_PASSWORD)); - } - - if (getProperty(BrokerDetails.OPTIONS_KEY_STORE) != null) - { - conSettings.setKeyStorePath( - getProperty(BrokerDetails.OPTIONS_KEY_STORE)); - } - - if (getProperty(BrokerDetails.OPTIONS_KEY_STORE_PASSWORD) != null) - { - conSettings.setKeyStorePassword( - getProperty(BrokerDetails.OPTIONS_KEY_STORE_PASSWORD)); - } - - if (getProperty(BrokerDetails.OPTIONS_SSL_CERT_ALIAS) != null) - { - conSettings.setCertAlias( - getProperty(BrokerDetails.OPTIONS_SSL_CERT_ALIAS)); - } - // ---------------------------- - - boolean defaultSSLVerifyHostName = Boolean.parseBoolean( - System.getProperty(ClientProperties.CONNECTION_OPTION_SSL_VERIFY_HOST_NAME, - String.valueOf(ClientProperties.DEFAULT_CONNECTION_OPTION_SSL_VERIFY_HOST_NAME))); - conSettings.setVerifyHostname(getBooleanProperty(BrokerDetails.OPTIONS_SSL_VERIFY_HOSTNAME, defaultSSLVerifyHostName )); - - if (getProperty(BrokerDetails.OPTIONS_TCP_NO_DELAY) != null) - { - conSettings.setTcpNodelay( - getBooleanProperty(BrokerDetails.OPTIONS_TCP_NO_DELAY,true)); - } - - conSettings.setConnectTimeout(lookupConnectTimeout()); - - if (getProperty(BrokerDetails.OPTIONS_HEARTBEAT) != null) - { - conSettings.setHeartbeatInterval(getIntegerProperty(BrokerDetails.OPTIONS_HEARTBEAT)); - } - else if (getProperty(BrokerDetails.OPTIONS_IDLE_TIMEOUT) != null) - { - conSettings.setHeartbeatInterval(getIntegerProperty(BrokerDetails.OPTIONS_IDLE_TIMEOUT) / 1000); - } - - return conSettings; - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQConnection.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQConnection.java deleted file mode 100644 index 717ebcc86f..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQConnection.java +++ /dev/null @@ -1,1694 +0,0 @@ -/* -* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; - -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.net.ConnectException; -import java.net.SocketAddress; -import java.net.UnknownHostException; -import java.nio.channels.UnresolvedAddressException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.atomic.AtomicLong; - -import javax.jms.ConnectionConsumer; -import javax.jms.ConnectionMetaData; -import javax.jms.Destination; -import javax.jms.ExceptionListener; -import javax.jms.IllegalStateException; -import javax.jms.JMSException; -import javax.jms.Queue; -import javax.jms.QueueConnection; -import javax.jms.QueueSession; -import javax.jms.ServerSessionPool; -import javax.jms.Topic; -import javax.jms.TopicConnection; -import javax.jms.TopicSession; -import javax.naming.NamingException; -import javax.naming.Reference; -import javax.naming.Referenceable; -import javax.naming.StringRefAddr; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQConnectionFailureException; -import org.apache.qpid.AMQDisconnectedException; -import org.apache.qpid.AMQException; -import org.apache.qpid.AMQProtocolException; -import org.apache.qpid.AMQUnresolvedAddressException; -import org.apache.qpid.client.failover.ConnectionRedirectException; -import org.apache.qpid.client.failover.FailoverException; -import org.apache.qpid.client.failover.FailoverProtectedOperation; -import org.apache.qpid.client.protocol.AMQProtocolHandler; -import org.apache.qpid.client.security.CallbackHandlerRegistry; -import org.apache.qpid.client.state.AMQStateManager; -import org.apache.qpid.common.QpidProperties; -import org.apache.qpid.configuration.ClientProperties; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.ProtocolVersion; -import org.apache.qpid.jms.BrokerDetails; -import org.apache.qpid.jms.Connection; -import org.apache.qpid.jms.ConnectionListener; -import org.apache.qpid.jms.ConnectionURL; -import org.apache.qpid.jms.FailoverPolicy; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.url.URLSyntaxException; - -public class AMQConnection extends Closeable implements Connection, QueueConnection, TopicConnection, Referenceable -{ - private static final Logger _logger = LoggerFactory.getLogger(AMQConnection.class); - private static final AtomicLong CONN_NUMBER_GENERATOR = new AtomicLong(); - - private static final long DEFAULT_CLOSE_TIMEOUT = Long.getLong(ClientProperties.QPID_CLOSE_TIMEOUT, - ClientProperties.DEFAULT_CLOSE_TIMEOUT); - - private final long _connectionNumber = CONN_NUMBER_GENERATOR.incrementAndGet(); - - /** - * This is the "root" mutex that must be held when doing anything that could be impacted by failover. This must be - * held by any child objects of this connection such as the session, producers and consumers. - */ - private final Object _failoverMutex = new Object(); - - private final Object _sessionCreationLock = new Object(); - - /** - * A channel is roughly analogous to a session. The server can negotiate the maximum number of channels per session - * and we must prevent the client from opening too many. - */ - private long _maximumChannelCount; - - /** The maximum size of frame supported by the server */ - private long _maximumFrameSize; - - /** - * The protocol handler dispatches protocol events for this connection. For example, when the connection is dropped - * the handler deals with this. It also deals with the initial dispatch of any protocol frames to their appropriate - * handler. - */ - private AMQProtocolHandler _protocolHandler; - - /** Maps from session id (Integer) to AMQSession instance */ - private final ChannelToSessionMap _sessions = new ChannelToSessionMap(); - - private final String _clientName; - - /** The user name to use for authentication */ - private String _username; - - /** The password to use for authentication */ - private String _password; - - /** The virtual path to connect to on the AMQ server */ - private String _virtualHost; - - /** The exception listener for this connection object. */ - private volatile ExceptionListener _exceptionListener; - - private ConnectionListener _connectionListener; - - private final ConnectionURL _connectionURL; - - /** - * Whether this connection is started, i.e. whether messages are flowing to consumers. It has no meaning for message - * publication. - */ - private volatile boolean _started; - - /** Policy dictating how to failover */ - private FailoverPolicy _failoverPolicy; - - /* - * _Connected should be refactored with a suitable wait object. - */ - private boolean _connected; - - /* - * The connection meta data - */ - private QpidConnectionMetaData _connectionMetaData; - - private AMQShortString _defaultTopicExchangeName = AMQShortString.valueOf(ExchangeDefaults.TOPIC_EXCHANGE_NAME); - private AMQShortString _defaultQueueExchangeName = AMQShortString.valueOf(ExchangeDefaults.DIRECT_EXCHANGE_NAME); - private AMQShortString _temporaryTopicExchangeName = AMQShortString.valueOf(ExchangeDefaults.TOPIC_EXCHANGE_NAME); - private AMQShortString _temporaryQueueExchangeName = AMQShortString.valueOf(ExchangeDefaults.DIRECT_EXCHANGE_NAME); - - /** - * Thread Pool for executing connection level processes such as reporting asynchronous exceptions - * and for 0-8..0-91 returning bounced messages. - */ - private final ExecutorService _taskPool = Executors.newSingleThreadExecutor(new ThreadFactory() - { - @Override - public Thread newThread(final Runnable r) - { - Thread thread = new Thread(r, "Connection_" + AMQConnection.this._connectionNumber + "_task"); - if (!thread.isDaemon()) - { - thread.setDaemon(true); - } - - return thread; - } - }); - - private AMQConnectionDelegate _delegate; - - // this connection maximum number of prefetched messages - private int _maxPrefetch; - - //Indicates whether persistent messages are synchronized - private boolean _syncPersistence; - - //Indicates whether we need to sync on every message ack - private boolean _syncAck; - - //Indicates the sync publish options (persistent|all) - //By default it's async publish - private String _syncPublish = ""; - - // Indicates whether to use the old map message format or the - // new amqp-0-10 encoded format. - private boolean _useLegacyMapMessageFormat; - - // Indicates whether to use the old stream message format or the - // new amqp-0-10 list encoded format. - private boolean _useLegacyStreamMessageFormat; - - // When sending to a Queue destination for the first time, check that the queue is bound - private final boolean _validateQueueOnSend; - - //used to track the last failover time for - //Address resolution purposes - private volatile long _lastFailoverTime = 0; - - private boolean _compressMessages; - private int _messageCompressionThresholdSize; - - static - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Qpid version : " + QpidProperties.getVersionString()); - } - - // The registering of any additional SASL mechanisms with the Java Security API requires - // SecurityManager permissions. In execution environments such as web containers, - // this may require adjustments to the Java security.policy. - CallbackHandlerRegistry registry = CallbackHandlerRegistry.getInstance(); - if (_logger.isDebugEnabled()) - { - _logger.debug("Loaded mechanisms " + registry.getMechanisms()); - } - } - /** - * @param broker brokerdetails - * @param username username - * @param password password - * @param clientName clientid - * @param virtualHost virtualhost - * - * @throws AMQException - * @throws URLSyntaxException - */ - public AMQConnection(String broker, String username, String password, String clientName, String virtualHost) - throws AMQException, URLSyntaxException - { - this(new AMQConnectionURL( - ConnectionURL.AMQ_PROTOCOL + "://" + username + ":" + password + "@" - + ((clientName == null) ? "" : clientName) + "/" + virtualHost + "?brokerlist='" - + AMQBrokerDetails.checkTransport(broker) + "'")); - } - - public AMQConnection(String host, int port, String username, String password, String clientName, String virtualHost) - throws AMQException, URLSyntaxException - { - this(new AMQConnectionURL( - ConnectionURL.AMQ_PROTOCOL + "://" + username + ":" + password + "@" - + ((clientName == null) ? "" : clientName) + virtualHost + "?brokerlist='tcp://" + host + ":" + port + "'")); - } - - public AMQConnection(String connection) throws AMQException, URLSyntaxException - { - this(new AMQConnectionURL(connection)); - } - - /** - * TODO Some horrible stuff going on here with setting exceptions to be non-null to detect if an exception - * was thrown during the connection! Intention not clear. Use a flag anyway, not exceptions... Will fix soon. - */ - public AMQConnection(ConnectionURL connectionURL) throws AMQException - { - if (connectionURL == null) - { - throw new IllegalArgumentException("Connection must be specified"); - } - - if (_logger.isDebugEnabled()) - { - _logger.debug("Connection(" + _connectionNumber + "):" + connectionURL); - } - - // set this connection maxPrefetch - if (connectionURL.getOption(ConnectionURL.OPTIONS_MAXPREFETCH) != null) - { - _maxPrefetch = Integer.parseInt(connectionURL.getOption(ConnectionURL.OPTIONS_MAXPREFETCH)); - } - else - { - // use the default value set for all connections - _maxPrefetch = Integer.parseInt(System.getProperties().getProperty(ClientProperties.MAX_PREFETCH_PROP_NAME, - ClientProperties.MAX_PREFETCH_DEFAULT)); - } - - if (connectionURL.getOption(ConnectionURL.OPTIONS_SYNC_PERSISTENCE) != null) - { - _syncPersistence = - Boolean.parseBoolean(connectionURL.getOption(ConnectionURL.OPTIONS_SYNC_PERSISTENCE)); - _logger.warn("sync_persistence is a deprecated property, " + - "please use sync_publish={persistent|all} instead"); - } - else - { - // use the default value set for all connections - _syncPersistence = Boolean.getBoolean(ClientProperties.SYNC_PERSISTENT_PROP_NAME); - if (_syncPersistence) - { - _logger.warn("sync_persistence is a deprecated property, " + - "please use sync_publish={persistent|all} instead"); - } - } - - if (connectionURL.getOption(ConnectionURL.OPTIONS_SYNC_ACK) != null) - { - _syncAck = Boolean.parseBoolean(connectionURL.getOption(ConnectionURL.OPTIONS_SYNC_ACK)); - } - else - { - // use the default value set for all connections - _syncAck = Boolean.getBoolean(ClientProperties.SYNC_ACK_PROP_NAME); - } - - if (connectionURL.getOption(ConnectionURL.OPTIONS_SYNC_PUBLISH) != null) - { - _syncPublish = connectionURL.getOption(ConnectionURL.OPTIONS_SYNC_PUBLISH); - } - else - { - // use the default value set for all connections - _syncPublish = System.getProperty((ClientProperties.SYNC_PUBLISH_PROP_NAME),_syncPublish); - } - - if (connectionURL.getOption(ConnectionURL.OPTIONS_USE_LEGACY_MAP_MESSAGE_FORMAT) != null) - { - _useLegacyMapMessageFormat = Boolean.parseBoolean( - connectionURL.getOption(ConnectionURL.OPTIONS_USE_LEGACY_MAP_MESSAGE_FORMAT)); - } - else - { - // use the default value set for all connections - _useLegacyMapMessageFormat = Boolean.getBoolean(ClientProperties.USE_LEGACY_MAP_MESSAGE_FORMAT); - } - - if (connectionURL.getOption(ConnectionURL.OPTIONS_USE_LEGACY_STREAM_MESSAGE_FORMAT) != null) - { - _useLegacyStreamMessageFormat = Boolean.parseBoolean( - connectionURL.getOption(ConnectionURL.OPTIONS_USE_LEGACY_STREAM_MESSAGE_FORMAT)); - } - else - { - // use the default value set for all connections - _useLegacyStreamMessageFormat = System.getProperty(ClientProperties.USE_LEGACY_STREAM_MESSAGE_FORMAT) == null ? - true : Boolean.getBoolean(ClientProperties.USE_LEGACY_STREAM_MESSAGE_FORMAT); - } - - if(connectionURL.getOption(ConnectionURL.OPTIONS_VERIFY_QUEUE_ON_SEND) != null) - { - _validateQueueOnSend = Boolean.parseBoolean( - connectionURL.getOption(ConnectionURL.OPTIONS_VERIFY_QUEUE_ON_SEND)); - } - else - { - _validateQueueOnSend = - Boolean.parseBoolean(System.getProperty(ClientProperties.VERIFY_QUEUE_ON_SEND, "false")); - } - - if(connectionURL.getOption(ConnectionURL.OPTIONS_COMPRESS_MESSAGES) != null) - { - _compressMessages = Boolean.parseBoolean(connectionURL.getOption(ConnectionURL.OPTIONS_COMPRESS_MESSAGES)); - } - else - { - _compressMessages = - Boolean.parseBoolean(System.getProperty(ClientProperties.CONNECTION_OPTION_COMPRESS_MESSAGES, - String.valueOf(ClientProperties.DEFAULT_CONNECTION_OPTION_COMPRESS_MESSAGES))); - } - - - if(connectionURL.getOption(ConnectionURL.OPTIONS_MESSAGES_COMPRESSION_THRESHOLD_SIZE) != null) - { - _messageCompressionThresholdSize = Integer.valueOf(connectionURL.getOption(ConnectionURL.OPTIONS_MESSAGES_COMPRESSION_THRESHOLD_SIZE)); - } - else - { - _messageCompressionThresholdSize = Integer.getInteger(ClientProperties.CONNECTION_OPTION_MESSAGE_COMPRESSION_THRESHOLD_SIZE, - ClientProperties.DEFAULT_MESSAGE_COMPRESSION_THRESHOLD_SIZE); - } - if(_messageCompressionThresholdSize <= 0) - { - _messageCompressionThresholdSize = Integer.MAX_VALUE; - } - - String amqpVersion = System.getProperty((ClientProperties.AMQP_VERSION), "0-10"); - if (_logger.isDebugEnabled()) - { - _logger.debug("AMQP version " + amqpVersion); - } - - _failoverPolicy = new FailoverPolicy(connectionURL, this); - BrokerDetails brokerDetails = _failoverPolicy.getCurrentBrokerDetails(); - if ("0-8".equals(amqpVersion)) - { - _delegate = new AMQConnectionDelegate_8_0(this); - } - else if ("0-9".equals(amqpVersion)) - { - _delegate = new AMQConnectionDelegate_0_9(this); - } - else if ("0-91".equals(amqpVersion) || "0-9-1".equals(amqpVersion)) - { - _delegate = new AMQConnectionDelegate_9_1(this); - } - else - { - _delegate = new AMQConnectionDelegate_0_10(this); - } - - _connectionURL = connectionURL; - - _clientName = connectionURL.getClientName(); - _username = connectionURL.getUsername(); - _password = connectionURL.getPassword(); - - setVirtualHost(connectionURL.getVirtualHost()); - - if (connectionURL.getDefaultQueueExchangeName() != null) - { - _defaultQueueExchangeName = connectionURL.getDefaultQueueExchangeName(); - } - - if (connectionURL.getDefaultTopicExchangeName() != null) - { - _defaultTopicExchangeName = connectionURL.getDefaultTopicExchangeName(); - } - - if (connectionURL.getTemporaryQueueExchangeName() != null) - { - _temporaryQueueExchangeName = connectionURL.getTemporaryQueueExchangeName(); - } - - if (connectionURL.getTemporaryTopicExchangeName() != null) - { - _temporaryTopicExchangeName = connectionURL.getTemporaryTopicExchangeName(); - } - - _protocolHandler = new AMQProtocolHandler(this); - - if (_logger.isDebugEnabled()) - { - _logger.debug("Connecting with ProtocolHandler Version:"+_protocolHandler.getProtocolVersion()); - } - - // We are not currently connected - setConnected(false); - - boolean retryAllowed = true; - Exception connectionException = null; - while (!isConnected() && retryAllowed && brokerDetails != null) - { - ProtocolVersion pe = null; - try - { - pe = makeBrokerConnection(brokerDetails); - } - catch (Exception e) - { - if (_logger.isInfoEnabled()) - { - _logger.info("Unable to connect to broker at " + - _failoverPolicy.getCurrentBrokerDetails(), - e); - } - connectionException = e; - } - - if (pe != null) - { - // reset the delegate to the version returned by the - // broker - initDelegate(pe); - } - else if (!isConnected()) - { - if(connectionException instanceof ConnectionRedirectException) - { - ConnectionRedirectException redirect = (ConnectionRedirectException) connectionException; - retryAllowed = true; - brokerDetails = new AMQBrokerDetails(brokerDetails); - brokerDetails.setHost(redirect.getHost()); - brokerDetails.setPort(redirect.getPort()); - _protocolHandler.setStateManager(new AMQStateManager(_protocolHandler.getProtocolSession())); - - } - else - { - retryAllowed = _failoverPolicy.failoverAllowed(); - brokerDetails = _failoverPolicy.getNextBrokerDetails(); - _protocolHandler.setStateManager(new AMQStateManager(_protocolHandler.getProtocolSession())); - } - - } - } - verifyClientID(); - - if (_logger.isDebugEnabled()) - { - _logger.debug("Are we connected:" + isConnected()); - } - - if (!isConnected()) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Last attempted ProtocolHandler Version:"+_protocolHandler.getProtocolVersion()); - } - - String message = null; - - if (connectionException != null) - { - if (connectionException.getCause() != null) - { - message = connectionException.getCause().getMessage(); - } - else - { - message = connectionException.getMessage(); - } - } - - if (message == null) - { - message = "Unable to Connect"; - } - else if("".equals(message)) - { - message = "Unable to Connect:" + connectionException.getClass(); - } - - for (Throwable th = connectionException; th != null; th = th.getCause()) - { - if (th instanceof UnresolvedAddressException || - th instanceof UnknownHostException) - { - throw new AMQUnresolvedAddressException - (message, - _failoverPolicy.getCurrentBrokerDetails().toString(), - connectionException); - } - } - - throw new AMQConnectionFailureException(message, connectionException); - } - - if (_logger.isDebugEnabled()) - { - _logger.debug("Connected with ProtocolHandler Version:"+_protocolHandler.getProtocolVersion()); - } - - _sessions.setMaxChannelID(_delegate.getMaxChannelID()); - _sessions.setMinChannelID(_delegate.getMinChannelID()); - - _connectionMetaData = new QpidConnectionMetaData(this); - } - - private void initDelegate(ProtocolVersion pe) throws AMQProtocolException - { - try - { - String delegateClassName = String.format - ("org.apache.qpid.client.AMQConnectionDelegate_%s_%s", - pe.getMajorVersion(), pe.getMinorVersion()); - if (_logger.isDebugEnabled()) - { - _logger.debug("Looking up delegate '" + delegateClassName + "' Based on PE:" + pe); - } - Class c = Class.forName(delegateClassName); - Class partypes[] = new Class[1]; - partypes[0] = AMQConnection.class; - _delegate = (AMQConnectionDelegate) c.getConstructor(partypes).newInstance(this); - //Update our session to use this new protocol version - _protocolHandler.getProtocolSession().setProtocolVersion(_delegate.getProtocolVersion()); - - } - catch (ClassNotFoundException e) - { - throw new AMQProtocolException - (AMQConstant.UNSUPPORTED_CLIENT_PROTOCOL_ERROR, - String.format("Protocol: %s.%s is rquired by the broker but is not " + - "currently supported by this client library implementation", - pe.getMajorVersion(), pe.getMinorVersion()), - e); - } - catch (NoSuchMethodException e) - { - throw new RuntimeException("unable to locate constructor for delegate", e); - } - catch (InstantiationException e) - { - throw new RuntimeException("error instantiating delegate", e); - } - catch (IllegalAccessException e) - { - throw new RuntimeException("error accessing delegate", e); - } - catch (InvocationTargetException e) - { - throw new RuntimeException("error invoking delegate", e); - } - } - - private void setVirtualHost(String virtualHost) - { - if (virtualHost != null && virtualHost.startsWith("/")) - { - virtualHost = virtualHost.substring(1); - } - - _virtualHost = virtualHost; - } - - public boolean attemptReconnection(String host, int port, final boolean useFailoverConfigOnFailure) - { - BrokerDetails bd = new AMQBrokerDetails(_failoverPolicy.getCurrentBrokerDetails()); - bd.setHost(host); - bd.setPort(port); - - _failoverPolicy.setBroker(bd); - - try - { - makeBrokerConnection(bd); - - return true; - } - catch (Exception e) - { - if (_logger.isInfoEnabled()) - { - _logger.info("Unable to connect to broker at " + bd); - } - - return useFailoverConfigOnFailure && attemptReconnection(); - } - - } - - public boolean attemptReconnection() - { - BrokerDetails broker = null; - while (_failoverPolicy.failoverAllowed() && (broker = _failoverPolicy.getNextBrokerDetails()) != null) - { - if (attemptConnection(broker)) - { - return true; - } - } - - // connection unsuccessful - return false; - } - - private boolean attemptConnection(final BrokerDetails broker) - { - try - { - makeBrokerConnection(broker); - return true; - } - catch (Exception e) - { - if (!(e instanceof AMQException)) - { - if (_logger.isInfoEnabled()) - { - _logger.info("Unable to connect to broker at " + _failoverPolicy.getCurrentBrokerDetails(), e); - } - } - else - { - if (_logger.isInfoEnabled()) - { - _logger.info(e.getMessage() + ":Unable to connect to broker at " - + _failoverPolicy.getCurrentBrokerDetails()); - } - } - } - return false; - } - - public ProtocolVersion makeBrokerConnection(BrokerDetails brokerDetail) throws IOException, AMQException - { - resetClosedFlag(); - return _delegate.makeBrokerConnection(brokerDetail); - } - - public <T, E extends Exception> T executeRetrySupport(FailoverProtectedOperation<T,E> operation) throws E - { - return _delegate.executeRetrySupport(operation); - } - - /** - * Get the details of the currently active broker - * - * @return null if no broker is active (i.e. no successful connection has been made, or the BrokerDetail instance - * otherwise - */ - public BrokerDetails getActiveBrokerDetails() - { - return _failoverPolicy.getCurrentBrokerDetails(); - } - - public boolean failoverAllowed() - { - if (!isConnected()) - { - return false; - } - else - { - return _failoverPolicy.failoverAllowed(); - } - } - - public org.apache.qpid.jms.Session createSession(final boolean transacted, final int acknowledgeMode) throws JMSException - { - return createSession(transacted, acknowledgeMode, _maxPrefetch); - } - - public org.apache.qpid.jms.Session createSession(final boolean transacted, final int acknowledgeMode, final int prefetch) - throws JMSException - { - return createSession(transacted, acknowledgeMode, prefetch, prefetch); - } - - public org.apache.qpid.jms.Session createSession(final boolean transacted, final int acknowledgeMode, - final int prefetchHigh, final int prefetchLow) throws JMSException - { - synchronized (_sessionCreationLock) - { - checkNotClosed(); - return _delegate.createSession(transacted, acknowledgeMode, prefetchHigh, prefetchLow); - } - } - - public void setFailoverPolicy(FailoverPolicy policy) - { - _failoverPolicy = policy; - } - - public FailoverPolicy getFailoverPolicy() - { - return _failoverPolicy; - } - - /** - * Returns an AMQQueueSessionAdaptor which wraps an AMQSession and throws IllegalStateExceptions where specified in - * the JMS spec - * - * @param transacted - * @param acknowledgeMode - * - * @return QueueSession - * - * @throws JMSException - */ - public QueueSession createQueueSession(boolean transacted, int acknowledgeMode) throws JMSException - { - return new AMQQueueSessionAdaptor(createSession(transacted, acknowledgeMode)); - } - - /** - * Returns an AMQTopicSessionAdapter which wraps an AMQSession and throws IllegalStateExceptions where specified in - * the JMS spec - * - * @param transacted - * @param acknowledgeMode - * - * @return TopicSession - * - * @throws JMSException - */ - public TopicSession createTopicSession(boolean transacted, int acknowledgeMode) throws JMSException - { - return new AMQTopicSessionAdaptor(createSession(transacted, acknowledgeMode)); - } - - public boolean channelLimitReached() - { - return _sessions.size() >= _maximumChannelCount; - } - - public String getClientID() throws JMSException - { - checkNotClosed(); - - return _clientName; - } - - public void setClientID(String clientID) throws JMSException - { - checkNotClosed(); - // in AMQP it is not possible to change the client ID. If one is not specified - // upon connection construction, an id is generated automatically. Therefore - // we can always throw an exception. - if (!Boolean.getBoolean(ClientProperties.IGNORE_SET_CLIENTID_PROP_NAME)) - { - throw new IllegalStateException("Client name cannot be changed after being set"); - } - else - { - _logger.info("Operation setClientID is ignored using ID: " + getClientID()); - } - } - - public ConnectionMetaData getMetaData() throws JMSException - { - checkNotClosed(); - - return _connectionMetaData; - - } - - protected final ExceptionListener getExceptionListenerNoCheck() - { - return _exceptionListener; - } - - public ExceptionListener getExceptionListener() throws JMSException - { - checkNotClosed(); - return getExceptionListenerNoCheck(); - } - - public void setExceptionListener(ExceptionListener listener) throws JMSException - { - checkNotClosed(); - - _exceptionListener = listener; - } - - /** - * Start the connection, i.e. start flowing messages. Note that this method must be called only from a single thread - * and is not thread safe (which is legal according to the JMS specification). - * - * @throws JMSException - */ - public void start() throws JMSException - { - checkNotClosed(); - if (!_started) - { - _started = true; - final Iterator it = _sessions.values().iterator(); - while (it.hasNext()) - { - final AMQSession s = (AMQSession) (it.next()); - try - { - s.start(); - } - catch (AMQException e) - { - throw new JMSAMQException(e); - } - } - - } - } - - public void stop() throws JMSException - { - checkNotClosed(); - if (_started) - { - for (Iterator i = _sessions.values().iterator(); i.hasNext();) - { - try - { - ((AMQSession) i.next()).stop(); - } - catch (AMQException e) - { - throw new JMSAMQException(e); - } - } - - _started = false; - } - } - - public void close() throws JMSException - { - close(DEFAULT_CLOSE_TIMEOUT); - } - - public void close(long timeout) throws JMSException - { - boolean closed; - - synchronized (_sessionCreationLock) - { - closed = setClosed(); - } - - if (!closed) - { - List<AMQSession> sessions = new ArrayList<>(_sessions.values()); - - setClosing(true); - try - { - doClose(sessions, timeout); - } - finally - { - setClosing(false); - } - } - } - - private void doClose(List<AMQSession> sessions, long timeout) throws JMSException - { - if (!sessions.isEmpty()) - { - AMQSession session = sessions.remove(0); - synchronized (session.getMessageDeliveryLock()) - { - doClose(sessions, timeout); - } - } - else - { - synchronized (getFailoverMutex()) - { - try - { - try - { - closeAllSessions(null, timeout); - } - finally - { - shutdownTaskPool(); - } - } - catch (JMSException e) - { - _logger.error("Error closing connection", e); - JMSException jmse = new JMSException("Error closing connection: " + e); - jmse.setLinkedException(e); - jmse.initCause(e); - throw jmse; - } - finally - { - try - { - _delegate.closeConnection(timeout); - } - catch (Exception e) - { - _logger.warn("Error closing underlying protocol connection", e); - } - } - } - } - } - - private void shutdownTaskPool() - { - _taskPool.shutdown(); - } - - /** - * Marks all sessions and their children as closed without sending any protocol messages. Useful when you need to - * mark objects "visible" in userland as closed after failover or other significant event that impacts the - * connection. <p/> The caller must hold the failover mutex before calling this method. - */ - private void markAllSessionsClosed() - { - final LinkedList sessionCopy = new LinkedList(_sessions.values()); - final Iterator it = sessionCopy.iterator(); - while (it.hasNext()) - { - final AMQSession session = (AMQSession) it.next(); - - session.markClosed(); - } - - _sessions.clear(); - } - - /** - * Close all the sessions, either due to normal connection closure or due to an error occurring. - * - * @param cause if not null, the error that is causing this shutdown <p/> The caller must hold the failover mutex - * before calling this method. - */ - private void closeAllSessions(Throwable cause, long timeout) throws JMSException - { - final LinkedList sessionCopy = new LinkedList(_sessions.values()); - final Iterator it = sessionCopy.iterator(); - JMSException sessionException = null; - while (it.hasNext()) - { - final AMQSession session = (AMQSession) it.next(); - if (cause != null) - { - session.closed(cause); - } - else - { - try - { - session.close(timeout); - } - catch (JMSException e) - { - _logger.error("Error closing session: " + e); - sessionException = e; - } - } - } - - _sessions.clear(); - if (sessionException != null) - { - throw sessionException; - } - } - - public ConnectionConsumer createConnectionConsumer(Destination destination, String messageSelector, - ServerSessionPool sessionPool, int maxMessages) throws JMSException - { - checkNotClosed(); - - throw new JmsNotImplementedException(); - - } - - public ConnectionConsumer createConnectionConsumer(Queue queue, String messageSelector, ServerSessionPool sessionPool, - int maxMessages) throws JMSException - { - checkNotClosed(); - - throw new JmsNotImplementedException(); - } - - public ConnectionConsumer createConnectionConsumer(Topic topic, String messageSelector, ServerSessionPool sessionPool, - int maxMessages) throws JMSException - { - checkNotClosed(); - - throw new JmsNotImplementedException(); - } - - public ConnectionConsumer createDurableConnectionConsumer(Topic topic, String subscriptionName, String messageSelector, - ServerSessionPool sessionPool, int maxMessages) throws JMSException - { - checkNotClosed(); - - throw new JmsNotImplementedException(); - } - - public long getMaximumChannelCount() throws JMSException - { - checkNotClosed(); - - return _maximumChannelCount; - } - - public void setConnectionListener(ConnectionListener listener) - { - _connectionListener = listener; - } - - public ConnectionListener getConnectionListener() - { - return _connectionListener; - } - - public void setMaximumChannelCount(long maximumChannelCount) - { - _maximumChannelCount = maximumChannelCount; - } - - public void setMaximumFrameSize(long frameMax) - { - _maximumFrameSize = frameMax; - } - - public long getMaximumFrameSize() - { - return _maximumFrameSize; - } - - public ChannelToSessionMap getSessions() - { - return _sessions; - } - - public String getUsername() - { - return _username; - } - - public void setUsername(String id) - { - _username = id; - } - - public String getPassword() - { - return _password; - } - - public String getVirtualHost() - { - return _virtualHost; - } - - public final AMQProtocolHandler getProtocolHandler() - { - return _protocolHandler; - } - - public final boolean started() - { - return _started; - } - - public final boolean isConnected() - { - return _connected; - } - - protected final void setConnected(boolean connected) - { - _connected = connected; - } - - public void bytesSent(long writtenBytes) - { - if (_connectionListener != null) - { - _connectionListener.bytesSent(writtenBytes); - } - } - - public void bytesReceived(long receivedBytes) - { - if (_connectionListener != null) - { - _connectionListener.bytesReceived(receivedBytes); - } - } - - /** - * Fire the preFailover event to the registered connection listener (if any) - * - * @param redirect true if this is the result of a redirect request rather than a connection error - * - * @return true if no listener or listener does not veto change - */ - public boolean firePreFailover(boolean redirect) - { - _lastFailoverTime = System.currentTimeMillis(); - boolean proceed = true; - if (_connectionListener != null) - { - proceed = _connectionListener.preFailover(redirect); - } - - return proceed; - } - - /** - * Fire the preResubscribe event to the registered connection listener (if any). If the listener vetoes - * resubscription then all the sessions are closed. - * - * @return true if no listener or listener does not veto resubscription. - * - * @throws JMSException - */ - public boolean firePreResubscribe() throws JMSException - { - if (_connectionListener != null) - { - boolean resubscribe = _connectionListener.preResubscribe(); - if (!resubscribe) - { - markAllSessionsClosed(); - } - - return resubscribe; - } - else - { - return true; - } - } - - /** Fires a failover complete event to the registered connection listener (if any). */ - public void fireFailoverComplete() - { - if (_connectionListener != null) - { - _connectionListener.failoverComplete(); - } - } - - /** - * In order to protect the consistency of the connection and its child sessions, consumers and producers, the - * "failover mutex" must be held when doing any operations that could be corrupted during failover. - * - * @return a mutex. Guaranteed never to change for the lifetime of this connection even if failover occurs. - */ - public final Object getFailoverMutex() - { - return _failoverMutex; - } - - public void resubscribeSessions() throws JMSException, AMQException, FailoverException - { - _delegate.resubscribeSessions(); - } - - /** - * If failover is taking place this will block until it has completed. If failover is not taking place it will - * return immediately. - * - * @throws InterruptedException - */ - public void blockUntilNotFailingOver() throws InterruptedException - { - _protocolHandler.blockUntilNotFailingOver(); - } - - /** - * Invoked by the AMQProtocolSession when a protocol session exception has occurred. This method sends the exception - * to a JMS exception listener, if configured, and propagates the exception to sessions, which in turn will - * propagate to consumers. This allows synchronous consumers to have exceptions thrown to them. - * - * @param cause the exception - */ - public void exceptionReceived(Throwable cause) - { - - if (_logger.isDebugEnabled()) - { - _logger.debug("exceptionReceived done by:" + Thread.currentThread().getName(), cause); - } - - final JMSException je; - if (cause instanceof JMSException) - { - je = (JMSException) cause; - } - else - { - AMQConstant code = null; - - if (cause instanceof AMQException) - { - code = ((AMQException) cause).getErrorCode(); - } - - if (code != null) - { - je = new JMSException("Exception thrown against " + toString() + ": " + cause, Integer.toString(code.getCode())); - } - else - { - //Should never get here as all AMQEs are required to have an ErrorCode! - // Other than AMQDisconnectedEx! - - if (cause instanceof AMQDisconnectedException) - { - Exception last = _protocolHandler.getStateManager().getLastException(); - if (last != null) - { - _logger.info("StateManager had an exception for us to use a cause of our Disconnected Exception"); - cause = last; - } - } - je = new JMSException("Exception thrown against " + toString() + ": " + cause); - } - - if (cause instanceof Exception) - { - je.setLinkedException((Exception) cause); - } - - je.initCause(cause); - } - - boolean closer = false; - - // in the case of an IOException, MINA has closed the protocol session so we set _closed to true - // so that any generic client code that tries to close the connection will not mess up this error - // handling sequence - if (cause instanceof IOException || cause instanceof AMQDisconnectedException) - { - // If we have an IOE/AMQDisconnect there is no connection to close on. - setClosing(false); - closer = !setClosed(); - - _protocolHandler.getProtocolSession().notifyError(je); - } - - try - { - // decide if we are going to close the session - if (hardError(cause)) - { - closer = (!setClosed()) || closer; - { - _logger.info("Closing AMQConnection due to :" + cause); - } - } - else - { - _logger.info("Not a hard-error connection not closing: " + cause); - } - - - // if we are closing the connection, close sessions first - if (closer) - { - // get the failover mutex before trying to close - synchronized (getFailoverMutex()) - { - try - { - closeAllSessions(cause, -1); - } - catch (JMSException e) - { - _logger.error("Error closing all sessions: " + e, e); - } - } - } - } - finally - { - deliverJMSExceptionToExceptionListenerOrLog(je, cause); - } - } - - private void deliverJMSExceptionToExceptionListenerOrLog(final JMSException je, final Throwable cause) - { - final ExceptionListener exceptionListener = getExceptionListenerNoCheck(); - if (exceptionListener != null) - { - performConnectionTask(new Runnable() - { - @Override - public void run() - { - // deliver the exception if there is a listener - try - { - exceptionListener.onException(je); - } - catch (RuntimeException e) - { - _logger.error("Exception occurred in ExceptionListener", e); - } - } - }); - } - else - { - _logger.error("Throwable Received but no listener set: " + cause); - } - - - } - - private boolean hardError(Throwable cause) - { - if (cause instanceof AMQException) - { - return ((AMQException) cause).isHardError(); - } - - return true; - } - - void registerSession(int channelId, AMQSession session) - { - _sessions.put(channelId, session); - } - - public void deregisterSession(int channelId) - { - _sessions.remove(channelId); - } - - public String toString() - { - StringBuffer buf = new StringBuffer("AMQConnection:\n"); - if (_failoverPolicy.getCurrentBrokerDetails() == null) - { - buf.append("No active broker connection"); - } - else - { - BrokerDetails bd = _failoverPolicy.getCurrentBrokerDetails(); - buf.append("Host: ").append(String.valueOf(bd.getHost())); - buf.append("\nPort: ").append(String.valueOf(bd.getPort())); - } - - buf.append("\nVirtual Host: ").append(String.valueOf(_virtualHost)); - buf.append("\nClient ID: ").append(String.valueOf(_clientName)); - buf.append("\nActive session count: ").append((_sessions == null) ? 0 : _sessions.size()); - - return buf.toString(); - } - - /** - * Returns connection url. - * @return connection url - */ - public ConnectionURL getConnectionURL() - { - return _connectionURL; - } - - /** - * Returns stringified connection url. This url is suitable only for display - * as {@link AMQConnectionURL#toString()} converts any password to asterisks. - * @return connection url - */ - public String toURL() - { - return _connectionURL.toString(); - } - - public Reference getReference() throws NamingException - { - return new Reference(AMQConnection.class.getName(), new StringRefAddr(AMQConnection.class.getName(), toURL()), - AMQConnectionFactory.class.getName(), null); // factory location - } - - public AMQShortString getDefaultTopicExchangeName() - { - return _defaultTopicExchangeName; - } - - public void setDefaultTopicExchangeName(AMQShortString defaultTopicExchangeName) - { - _defaultTopicExchangeName = defaultTopicExchangeName; - } - - public AMQShortString getDefaultQueueExchangeName() - { - return _defaultQueueExchangeName; - } - - public void setDefaultQueueExchangeName(AMQShortString defaultQueueExchangeName) - { - _defaultQueueExchangeName = defaultQueueExchangeName; - } - - public AMQShortString getTemporaryTopicExchangeName() - { - return _temporaryTopicExchangeName; - } - - public AMQShortString getTemporaryQueueExchangeName() - { - return _temporaryQueueExchangeName; - } - - public void setTemporaryTopicExchangeName(AMQShortString temporaryTopicExchangeName) - { - _temporaryTopicExchangeName = temporaryTopicExchangeName; - } - - public void setTemporaryQueueExchangeName(AMQShortString temporaryQueueExchangeName) - { - _temporaryQueueExchangeName = temporaryQueueExchangeName; - } - - public void performConnectionTask(Runnable task) - { - try - { - _taskPool.execute(task); - } - catch (RejectedExecutionException e) - { - if(!(isClosed() || isClosing())) - { - throw e; - } - } - } - - public AMQSession getSession(int channelId) - { - return _sessions.get(channelId); - } - - public ProtocolVersion getProtocolVersion() - { - return _delegate.getProtocolVersion(); - } - - public String getBrokerUUID() - { - if(getProtocolVersion().equals(ProtocolVersion.v0_10)) - { - return ((AMQConnectionDelegate_0_10)_delegate).getUUID(); - } - else - { - return null; - } - } - - /** - * Tests whether the Broker has advertised support for the named feature. - * - * @param featureName - * - * @return true if the feature is supported, or false otherwise. - */ - boolean isSupportedServerFeature(final String featureName) - { - return _delegate.isSupportedServerFeature(featureName); - } - - public boolean isFailingOver() - { - return (_protocolHandler.getFailoverLatch() != null); - } - - /** - * Get the maximum number of messages that this connection can pre-fetch. - * - * @return The maximum number of messages that this connection can pre-fetch. - */ - public long getMaxPrefetch() - { - return _maxPrefetch; - } - - /** - * Indicates whether persistent messages are synchronized - * - * @return true if persistent messages are synchronized false otherwise - */ - public boolean getSyncPersistence() - { - return _syncPersistence; - } - - /** - * Indicates whether we need to sync on every message ack - */ - public boolean getSyncAck() - { - return _syncAck; - } - - public String getSyncPublish() - { - return _syncPublish; - } - - public boolean isMessageCompressionDesired() - { - return _compressMessages; - } - - public int getNextChannelID() - { - return _sessions.getNextChannelId(); - } - - public boolean isUseLegacyMapMessageFormat() - { - return _useLegacyMapMessageFormat; - } - - public boolean isUseLegacyStreamMessageFormat() - { - return _useLegacyStreamMessageFormat; - } - - private void verifyClientID() throws AMQException - { - if (Boolean.getBoolean(ClientProperties.QPID_VERIFY_CLIENT_ID)) - { - try - { - if (!_delegate.verifyClientID()) - { - throw new AMQException(AMQConstant.ALREADY_EXISTS,"ClientID must be unique"); - } - } - catch(JMSException e) - { - throw new AMQException(e.getMessage(),e); - } - } - } - - public long getLastFailoverTime() - { - return _lastFailoverTime; - } - - protected AMQConnectionDelegate getDelegate() - { - return _delegate; - } - - public Long getConnectionNumber() - { - return _connectionNumber; - } - - protected void logConnected(SocketAddress localAddress, SocketAddress remoteAddress) - { - if(_logger.isInfoEnabled()) - { - _logger.info("Connection " + _connectionNumber + " now connected from " - + localAddress + " to " + remoteAddress); - } - } - - void setHeartbeatListener(HeartbeatListener listener) - { - _delegate.setHeartbeatListener(listener); - } - - public boolean validateQueueOnSend() - { - return _validateQueueOnSend; - } - - @Override - protected boolean setClosed() - { - return super.setClosed(); - } - - public int getMessageCompressionThresholdSize() - { - return _messageCompressionThresholdSize; - } - - void doWithAllLocks(Runnable r) - { - doWithAllLocks(r, _sessions.values()); - - } - - private void doWithAllLocks(final Runnable r, final List<AMQSession> sessions) - { - if (!sessions.isEmpty()) - { - AMQSession session = sessions.remove(0); - - final Object dispatcherLock = session.getDispatcherLock(); - if (dispatcherLock != null) - { - synchronized (dispatcherLock) - { - synchronized (session.getMessageDeliveryLock()) - { - doWithAllLocks(r, sessions); - } - } - } - else - { - synchronized (session.getMessageDeliveryLock()) - { - doWithAllLocks(r, sessions); - } - } - } - else - { - synchronized (getFailoverMutex()) - { - r.run(); - } - } - } - - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate.java deleted file mode 100644 index c359fbcc84..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.client; - -import java.io.IOException; - -import javax.jms.JMSException; -import javax.jms.XASession; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.failover.FailoverException; -import org.apache.qpid.client.failover.FailoverProtectedOperation; -import org.apache.qpid.framing.ProtocolVersion; -import org.apache.qpid.jms.BrokerDetails; -import org.apache.qpid.jms.Session; - -public interface AMQConnectionDelegate -{ - ProtocolVersion makeBrokerConnection(BrokerDetails brokerDetail) throws IOException, AMQException; - - Session createSession(final boolean transacted, final int acknowledgeMode, - final int prefetchHigh, final int prefetchLow) throws JMSException; - - /** - * Create an XASession with default prefetch values of: - * High = MaxPrefetch - * Low = MaxPrefetch / 2 - * @return XASession - * @throws JMSException thrown if there is a problem creating the session. - */ - XASession createXASession() throws JMSException; - - XASession createXASession(int prefetchHigh, int prefetchLow) throws JMSException; - - XASession createXASession(int ackMode) throws JMSException; - - void resubscribeSessions() throws JMSException, AMQException, FailoverException; - - void closeConnection(long timeout) throws JMSException, AMQException; - - <T, E extends Exception> T executeRetrySupport(FailoverProtectedOperation<T,E> operation) throws E; - - int getMaxChannelID(); - - int getMinChannelID(); - - ProtocolVersion getProtocolVersion(); - - boolean verifyClientID() throws JMSException, AMQException; - - /** - * Tests whether the server has advertised support for the specified feature - * via the qpid.features server connection property. By convention the feature name - * with begin <code>qpid.</code> followed by one or more words separated by minus signs - * e.g. qpid.jms-selector. - * - * @param featureName name of feature. - * - * @return true if the feature is supported by the server - */ - boolean isSupportedServerFeature(final String featureName); - - void setHeartbeatListener(HeartbeatListener listener); - - boolean supportsIsBound(); - - boolean isMessageCompressionSupported(); -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_0_10.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_0_10.java deleted file mode 100644 index 2c10c585fc..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_0_10.java +++ /dev/null @@ -1,633 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.atomic.AtomicBoolean; - -import javax.jms.ExceptionListener; -import javax.jms.JMSException; -import javax.jms.XASession; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.failover.FailoverException; -import org.apache.qpid.client.failover.FailoverProtectedOperation; -import org.apache.qpid.client.transport.ClientConnectionDelegate; -import org.apache.qpid.common.ServerPropertyNames; -import org.apache.qpid.framing.ProtocolVersion; -import org.apache.qpid.jms.BrokerDetails; -import org.apache.qpid.jms.ChannelLimitReachedException; -import org.apache.qpid.jms.ConnectionURL; -import org.apache.qpid.jms.Session; -import org.apache.qpid.properties.ConnectionStartProperties; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.transport.Connection; -import org.apache.qpid.transport.ConnectionClose; -import org.apache.qpid.transport.ConnectionCloseCode; -import org.apache.qpid.transport.ConnectionException; -import org.apache.qpid.transport.ConnectionListener; -import org.apache.qpid.transport.ConnectionSettings; -import org.apache.qpid.transport.ProtocolVersionException; -import org.apache.qpid.transport.SessionDetachCode; -import org.apache.qpid.transport.SessionException; -import org.apache.qpid.transport.TransportException; - -public class AMQConnectionDelegate_0_10 implements AMQConnectionDelegate, ConnectionListener -{ - private static final int DEFAULT_PORT = 5672; - - /** - * This class logger. - */ - private static final Logger _logger = LoggerFactory.getLogger(AMQConnectionDelegate_0_10.class); - - /** - * The AMQ Connection. - */ - private final AMQConnection _conn; - - /** - * The QpidConeection instance that is mapped with this JMS connection. - */ - private org.apache.qpid.transport.Connection _qpidConnection; - private ConnectionException exception = null; - - //--- constructor - public AMQConnectionDelegate_0_10(AMQConnection conn) - { - _conn = conn; - _qpidConnection = new Connection(); - _qpidConnection.addConnectionListener(this); - } - - /** - * create a Session and start it if required. - */ - - public Session createSession(boolean transacted, int acknowledgeMode, int prefetchHigh, int prefetchLow) - throws JMSException - { - return createSession(transacted,acknowledgeMode,prefetchHigh,prefetchLow,null); - } - - public Session createSession(boolean transacted, int acknowledgeMode, int prefetchHigh, int prefetchLow, String name) - throws JMSException - { - _conn.checkNotClosed(); - - if (_conn.channelLimitReached()) - { - throw new ChannelLimitReachedException(_conn.getMaximumChannelCount()); - } - - int channelId = _conn.getNextChannelID(); - AMQSession session; - try - { - session = new AMQSession_0_10(_qpidConnection, _conn, channelId, transacted, acknowledgeMode, prefetchHigh, - prefetchLow,name); - _conn.registerSession(channelId, session); - if (_conn.started()) - { - session.start(); - } - } - catch (Exception e) - { - _logger.error("exception creating session:", e); - throw new JMSAMQException("cannot create session", e); - } - return session; - } - - /** - * Create an XASession with default prefetch values of: - * High = MaxPrefetch - * Low = MaxPrefetch / 2 - * @return XASession - * @throws JMSException - */ - public XASession createXASession() throws JMSException - { - return createXASession((int) _conn.getMaxPrefetch(), (int) _conn.getMaxPrefetch() / 2); - } - - /** - * create an XA Session and start it if required. - */ - public XASession createXASession(int prefetchHigh, int prefetchLow) throws JMSException - { - _conn.checkNotClosed(); - - if (_conn.channelLimitReached()) - { - throw new ChannelLimitReachedException(_conn.getMaximumChannelCount()); - } - - int channelId = _conn.getNextChannelID(); - XASessionImpl session; - try - { - session = new XASessionImpl(_qpidConnection, _conn, channelId, prefetchHigh, prefetchLow); - _conn.registerSession(channelId, session); - if (_conn.started()) - { - session.start(); - } - } - catch (Exception e) - { - throw new JMSAMQException("cannot create session", e); - } - return session; - } - - public XASession createXASession(int ackMode) - throws JMSException - { - - _conn.checkNotClosed(); - - if (_conn.channelLimitReached()) - { - throw new ChannelLimitReachedException(_conn.getMaximumChannelCount()); - } - - int channelId = _conn.getNextChannelID(); - XASessionImpl session; - try - { - session = new XASessionImpl(_qpidConnection, _conn, channelId, ackMode, (int)_conn.getMaxPrefetch(), (int)_conn.getMaxPrefetch() / 2); - _conn.registerSession(channelId, session); - if (_conn.started()) - { - session.start(); - } - } - catch (Exception e) - { - throw new JMSAMQException("cannot create session", e); - } - return session; - } - - /** - * Make a connection with the broker - * - * @param brokerDetail The detail of the broker to connect to. - * @throws IOException - * @throws AMQException - */ - public ProtocolVersion makeBrokerConnection(BrokerDetails brokerDetail) throws IOException, AMQException - { - try - { - if (_logger.isDebugEnabled()) - { - _logger.debug("connecting to host: " + brokerDetail.getHost() - + " port: " + brokerDetail.getPort() + " vhost: " - + _conn.getVirtualHost() + " username: " - + _conn.getUsername() + " password: " - + "********"); - } - - ConnectionSettings conSettings = retrieveConnectionSettings(brokerDetail); - - _qpidConnection.setConnectionDelegate(new ClientConnectionDelegate(conSettings, _conn.getConnectionURL())); - _qpidConnection.connect(conSettings); - - _conn.setConnected(true); - _conn.setUsername(_qpidConnection.getUserID()); - _conn.setMaximumChannelCount(_qpidConnection.getChannelMax()); - _conn.getFailoverPolicy().attainedConnection(); - _conn.logConnected(_qpidConnection.getLocalAddress(), _qpidConnection.getRemoteAddress()); - } - catch (ProtocolVersionException pe) - { - return new ProtocolVersion(pe.getMajor(), pe.getMinor()); - } - catch (ConnectionException ce) - { - AMQConstant code = AMQConstant.REPLY_SUCCESS; - if (ce.getClose() != null && ce.getClose().getReplyCode() != null) - { - code = AMQConstant.getConstant(ce.getClose().getReplyCode().getValue()); - } - String msg = "Cannot connect to broker ("+brokerDetail+"): " + ce.getMessage(); - throw new AMQException(code, msg, ce); - } - - return null; - } - - public void failoverPrep() - { - List<AMQSession> sessions = new ArrayList<AMQSession>(_conn.getSessions().values()); - for (AMQSession s : sessions) - { - ((AMQSession_0_10)s).failoverPrep(); - } - } - - public void resubscribeSessions() throws JMSException, AMQException, FailoverException - { - _logger.info("Resuming connection"); - getQpidConnection().resume(); - List<AMQSession> sessions = new ArrayList<AMQSession>(_conn.getSessions().values()); - _logger.info(String.format("Resubscribing sessions = %s sessions.size=%d", sessions, sessions.size())); - for (AMQSession s : sessions) - { - s.resubscribe(); - } - } - - public void closeConnection(long timeout) throws JMSException, AMQException - { - try - { - _qpidConnection.close(); - } - catch (TransportException e) - { - throw new AMQException(e.getMessage(), e); - } - } - - public void opened(Connection conn) {} - - public void exception(Connection conn, ConnectionException exc) - { - if (exception != null) - { - _logger.error("previous exception", exception); - } - - exception = exc; - } - - public void closed(Connection conn) - { - final ConnectionException exc = exception; - exception = null; - - if (exc == null) - { - return; - } - - final ConnectionClose close = exc.getClose(); - if (close == null || close.getReplyCode() == ConnectionCloseCode.CONNECTION_FORCED) - { - _conn.getProtocolHandler().setFailoverLatch(new CountDownLatch(1)); - - _qpidConnection.notifyFailoverRequired(); - - final AtomicBoolean failoverDone = new AtomicBoolean(); - - _conn.doWithAllLocks(new Runnable() - { - @Override - public void run() - { - try - { - boolean preFailover = _conn.firePreFailover(false); - if (preFailover) - { - boolean reconnected; - if(exc instanceof RedirectConnectionException) - { - RedirectConnectionException redirect = (RedirectConnectionException)exc; - reconnected = attemptRedirection(redirect.getHost(), redirect.getKnownHosts()); - } - else - { - reconnected = _conn.attemptReconnection(); - } - if(reconnected) - { - failoverPrep(); - _conn.resubscribeSessions(); - _conn.fireFailoverComplete(); - failoverDone.set(true); - } - } - } - catch (Exception e) - { - _logger.error("error during failover", e); - } - finally - { - _conn.getProtocolHandler().getFailoverLatch().countDown(); - _conn.getProtocolHandler().setFailoverLatch(null); - } - - } - }); - - - if (failoverDone.get()) - { - return; - } - - } - - - _conn.setClosed(); - - final ExceptionListener listener = _conn.getExceptionListenerNoCheck(); - if (listener == null) - { - _logger.error("connection exception: " + conn, exc); - } - else - { - _conn.performConnectionTask(new Runnable() - { - @Override - public void run() - { - String code = null; - if (close != null) - { - code = close.getReplyCode().toString(); - } - - JMSException ex = new JMSException(exc.getMessage(), code); - ex.setLinkedException(exc); - ex.initCause(exc); - listener.onException(ex); - } - }); - - } - } - - @Override - public boolean redirect(final String host, final List<Object> knownHosts) - { - exception = new RedirectConnectionException(host,knownHosts); - - return false; - } - - private boolean attemptRedirection(String host, List<Object> knownHosts) - { - - boolean redirected = host != null && attemptRedirection(host); - if(knownHosts != null) - { - for(Object knownHost : knownHosts) - { - redirected = attemptRedirection(String.valueOf(knownHost)); - if(redirected) - { - break; - } - } - } - return redirected; - } - - private boolean attemptRedirection(String host) - { - int portIndex = host.indexOf(':'); - - int port; - if (portIndex == -1) - { - port = DEFAULT_PORT; - } - else - { - try - { - port = Integer.parseInt(host.substring(portIndex + 1)); - } - catch(NumberFormatException e) - { - _logger.info("Unable to redirect to " + host + " - does not look like a valid address"); - return false; - } - host = host.substring(0, portIndex); - - } - return _conn.attemptReconnection(host,port,false); - } - - public <T, E extends Exception> T executeRetrySupport(FailoverProtectedOperation<T,E> operation) throws E - { - if (_conn.isFailingOver()) - { - try - { - _conn.blockUntilNotFailingOver(); - } - catch (InterruptedException e) - { - //ignore - } - } - - try - { - return operation.execute(); - } - catch (FailoverException e) - { - throw new RuntimeException(e); - } - } - - public int getMaxChannelID() - { - //For a negotiated channelMax N, there are channels 0 to N-1 available. - return _qpidConnection.getChannelMax() - 1; - } - - public int getMinChannelID() - { - return Connection.MIN_USABLE_CHANNEL_NUM; - } - - public ProtocolVersion getProtocolVersion() - { - return ProtocolVersion.v0_10; - } - - public String getUUID() - { - return (String)_qpidConnection.getServerProperties().get(ServerPropertyNames.FEDERATION_TAG); - } - - /* - * @see org.apache.qpid.client.AMQConnectionDelegate#isSupportedServerFeature(java.lang.String) - */ - public boolean isSupportedServerFeature(final String featureName) - { - if (featureName == null) - { - throw new IllegalArgumentException("featureName cannot be null"); - } - final Map<String, Object> serverProperties = _qpidConnection.getServerProperties(); - boolean featureSupported = false; - if (serverProperties != null && serverProperties.containsKey(ServerPropertyNames.QPID_FEATURES)) - { - final Object supportServerFeatures = serverProperties.get(ServerPropertyNames.QPID_FEATURES); - featureSupported = supportServerFeatures instanceof List && ((List<String>)supportServerFeatures).contains(featureName); - } - - if (_logger.isDebugEnabled()) - { - _logger.debug("Server support for feature '" + featureName + "' : " + featureSupported); - } - - return featureSupported; - } - - @Override - public void setHeartbeatListener(HeartbeatListener listener) - { - ((ClientConnectionDelegate)(_qpidConnection.getConnectionDelegate())).setHeartbeatListener(listener); - } - - private ConnectionSettings retrieveConnectionSettings(BrokerDetails brokerDetail) - { - ConnectionSettings conSettings = brokerDetail.buildConnectionSettings(); - - conSettings.setVhost(_conn.getVirtualHost()); - conSettings.setUsername(_conn.getUsername()); - conSettings.setPassword(_conn.getPassword()); - - // Pass client name from connection URL - Map<String, Object> clientProps = new HashMap<String, Object>(); - try - { - clientProps.put(ConnectionStartProperties.CLIENT_ID_0_10, _conn.getClientID()); - if(_conn.isMessageCompressionDesired()) - { - clientProps.put(ConnectionStartProperties.QPID_MESSAGE_COMPRESSION_SUPPORTED, Boolean.TRUE.toString()); - } - conSettings.setClientProperties(clientProps); - } - catch (JMSException e) - { - // Ignore - } - - //Check connection-level ssl override setting - String connectionSslOption = _conn.getConnectionURL().getOption(ConnectionURL.OPTIONS_SSL); - if(connectionSslOption != null) - { - boolean connUseSsl = Boolean.parseBoolean(connectionSslOption); - boolean brokerlistUseSsl = conSettings.isUseSSL(); - - if( connUseSsl != brokerlistUseSsl) - { - conSettings.setUseSSL(connUseSsl); - - if (_logger.isDebugEnabled()) - { - _logger.debug("Applied connection ssl option override, setting UseSsl to: " + connUseSsl ); - } - } - } - - return conSettings; - } - protected org.apache.qpid.transport.Connection getQpidConnection() - { - return _qpidConnection; - } - - public boolean verifyClientID() throws JMSException, AMQException - { - int prefetch = (int)_conn.getMaxPrefetch(); - AMQSession_0_10 ssn = (AMQSession_0_10)createSession(false, 1,prefetch,prefetch,_conn.getClientID()); - org.apache.qpid.transport.Session ssn_0_10 = ssn.getQpidSession(); - try - { - ssn_0_10.awaitOpen(); - } - catch(SessionException se) - { - //if due to non unique client id for user return false, otherwise wrap and re-throw. - if (ssn_0_10.getDetachCode() != null && - ssn_0_10.getDetachCode() == SessionDetachCode.SESSION_BUSY) - { - return false; - } - else - { - throw new AMQException(AMQConstant.INTERNAL_ERROR, "Unexpected SessionException thrown while awaiting session opening", se); - } - } - return true; - } - - @Override - public boolean supportsIsBound() - { - //0-10 supports the isBound method - return true; - } - - @Override - public boolean isMessageCompressionSupported() - { - return _qpidConnection.isMessageCompressionSupported(); - } - - private class RedirectConnectionException extends ConnectionException - { - private final String _host; - private final List<Object> _knownHosts; - - public RedirectConnectionException(final String host, - final List<Object> knownHosts) - { - super("Connection redirected to " + host + " alternates " + knownHosts); - _host = host; - _knownHosts = knownHosts; - } - - public String getHost() - { - return _host; - } - - public List<Object> getKnownHosts() - { - return _knownHosts; - } - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_0_9.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_0_9.java deleted file mode 100755 index 70ecedfd8b..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_0_9.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.client; - -import org.apache.qpid.framing.ProtocolVersion; - - -public class AMQConnectionDelegate_0_9 extends AMQConnectionDelegate_8_0 -{ - - public AMQConnectionDelegate_0_9(AMQConnection conn) - { - super(conn); - } - - @Override - public ProtocolVersion getProtocolVersion() - { - return ProtocolVersion.v0_9; - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_8_0.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_8_0.java deleted file mode 100644 index 8176358733..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_8_0.java +++ /dev/null @@ -1,579 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.client; - -import java.net.ConnectException; -import java.nio.ByteBuffer; -import java.nio.channels.UnresolvedAddressException; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.Iterator; -import java.util.Set; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import javax.jms.JMSException; -import javax.jms.XASession; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.failover.FailoverException; -import org.apache.qpid.client.failover.FailoverProtectedOperation; -import org.apache.qpid.client.failover.FailoverRetrySupport; -import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.apache.qpid.client.state.AMQState; -import org.apache.qpid.client.state.StateWaiter; -import org.apache.qpid.common.ServerPropertyNames; -import org.apache.qpid.configuration.ClientProperties; -import org.apache.qpid.framing.ChannelOpenBody; -import org.apache.qpid.framing.ChannelOpenOkBody; -import org.apache.qpid.framing.ConfirmSelectBody; -import org.apache.qpid.framing.ConfirmSelectOkBody; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.ProtocolVersion; -import org.apache.qpid.framing.TxSelectBody; -import org.apache.qpid.framing.TxSelectOkBody; -import org.apache.qpid.jms.BrokerDetails; -import org.apache.qpid.jms.ChannelLimitReachedException; -import org.apache.qpid.jms.ConnectionURL; -import org.apache.qpid.jms.Session; -import org.apache.qpid.properties.ConnectionStartProperties; -import org.apache.qpid.transport.ByteBufferReceiver; -import org.apache.qpid.transport.ConnectionSettings; -import org.apache.qpid.transport.network.NetworkConnection; -import org.apache.qpid.transport.network.OutgoingNetworkTransport; -import org.apache.qpid.transport.network.Transport; -import org.apache.qpid.transport.network.security.SecurityLayer; -import org.apache.qpid.transport.network.security.SecurityLayerFactory; - -public class AMQConnectionDelegate_8_0 implements AMQConnectionDelegate -{ - private static final Logger _logger = LoggerFactory.getLogger(AMQConnectionDelegate_8_0.class); - private final AMQConnection _conn; - private final long _timeout = Long.getLong(ClientProperties.QPID_SYNC_OP_TIMEOUT, - Long.getLong(ClientProperties.AMQJ_DEFAULT_SYNCWRITE_TIMEOUT, - ClientProperties.DEFAULT_SYNC_OPERATION_TIMEOUT)); - private boolean _messageCompressionSupported; - private boolean _addrSyntaxSupported; - private boolean _confirmedPublishSupported; - private boolean _confirmedPublishNonTransactionalSupported; - - public void closeConnection(long timeout) throws JMSException, AMQException - { - _conn.getProtocolHandler().closeConnection(timeout); - } - - public AMQConnectionDelegate_8_0(AMQConnection conn) - { - _conn = conn; - _addrSyntaxSupported = - Boolean.parseBoolean(System.getProperty(ClientProperties.ADDR_SYNTAX_SUPPORTED_IN_0_8, - String.valueOf(ClientProperties.DEFAULT_ADDR_SYNTAX_0_8_SUPPORT))); - } - - protected boolean checkException(Throwable thrown) - { - Throwable cause = thrown.getCause(); - - if (cause == null) - { - cause = thrown; - } - - return ((cause instanceof ConnectException) || (cause instanceof UnresolvedAddressException)); - } - - public boolean isConfirmedPublishSupported() - { - return _confirmedPublishSupported; - } - - public ProtocolVersion makeBrokerConnection(BrokerDetails brokerDetail) throws AMQException - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Connecting to broker:" + brokerDetail); - } - final Set<AMQState> openOrClosedStates = - EnumSet.of(AMQState.CONNECTION_OPEN, AMQState.CONNECTION_CLOSED); - - ConnectionSettings settings = brokerDetail.buildConnectionSettings(); - settings.setProtocol(brokerDetail.getTransport()); - - //Check connection-level ssl override setting - String connectionSslOption = _conn.getConnectionURL().getOption(ConnectionURL.OPTIONS_SSL); - if(connectionSslOption != null) - { - boolean connUseSsl = Boolean.parseBoolean(connectionSslOption); - boolean brokerlistUseSsl = settings.isUseSSL(); - - if( connUseSsl != brokerlistUseSsl) - { - settings.setUseSSL(connUseSsl); - - if (_logger.isDebugEnabled()) - { - _logger.debug("Applied connection ssl option override, setting UseSsl to: " + connUseSsl ); - } - } - } - - SecurityLayer securityLayer = SecurityLayerFactory.newInstance(settings); - - OutgoingNetworkTransport transport = Transport.getOutgoingTransportInstance(getProtocolVersion()); - - ReceiverClosedWaiter monitoringReceiver = new ReceiverClosedWaiter(securityLayer.receiver(_conn.getProtocolHandler())); - - NetworkConnection network = transport.connect(settings, monitoringReceiver, - _conn.getProtocolHandler()); - - try - { - _conn.getProtocolHandler().setNetworkConnection(network, securityLayer.sender(network.getSender())); - - StateWaiter waiter = _conn.getProtocolHandler().createWaiter(openOrClosedStates); - _conn.getProtocolHandler().init(settings); - - // this blocks until the connection has been set up or when an error - // has prevented the connection being set up - - AMQState state = waiter.await(); - - if (state == AMQState.CONNECTION_OPEN) - { - _conn.getFailoverPolicy().attainedConnection(); - _conn.setConnected(true); - _conn.logConnected(network.getLocalAddress(), network.getRemoteAddress()); - _messageCompressionSupported = checkMessageCompressionSupported(); - _confirmedPublishSupported = checkConfirmedPublishSupported(); - _confirmedPublishNonTransactionalSupported = checkConfirmedPublishNonTransactionalSupported(); - return null; - } - else - { - return _conn.getProtocolHandler().getSuggestedProtocolVersion(); - } - } - catch(AMQException | RuntimeException e) - { - network.close(); - throw e; - } - finally - { - // await the receiver to finish its execution (and so the IO threads too) - if (!_conn.isConnected()) - { - boolean closedWithinTimeout = monitoringReceiver.awaitClose(_timeout); - if (!closedWithinTimeout) - { - _logger.warn("Timed-out waiting for receiver for connection to " - + brokerDetail + " to be closed."); - } - } - } - - } - - // RabbitMQ supports confirmed publishing, but only on non transactional sessions - private boolean checkConfirmedPublishNonTransactionalSupported() - { - FieldTable serverProperties = _conn.getProtocolHandler().getProtocolSession().getConnectionStartServerProperties(); - if( serverProperties != null - && serverProperties.containsKey("capabilities") - && serverProperties.get("capabilities") instanceof FieldTable) - { - FieldTable capabilities = serverProperties.getFieldTable("capabilities"); - if(capabilities.containsKey("publisher_confirms") - && capabilities.get("publisher_confirms") instanceof Boolean - && capabilities.getBoolean("publisher_confirms")) - { - return true; - } - else - { - return false; - } - } - else - { - return false; - } - } - - public org.apache.qpid.jms.Session createSession(final boolean transacted, final int acknowledgeMode, final int prefetch) - throws JMSException - { - return createSession(transacted, acknowledgeMode, prefetch, prefetch); - } - - - public XASession createXASession(int prefetchHigh, int prefetchLow) throws JMSException - { - throw new UnsupportedOperationException("0_8 version does not provide XA support"); - } - - public XASession createXASession(int ackMode) throws JMSException - { - throw new UnsupportedOperationException("0_8 version does not provide XA support"); - } - public org.apache.qpid.jms.Session createSession(final boolean transacted, final int acknowledgeMode, - final int prefetchHigh, final int prefetchLow) throws JMSException - { - _conn.checkNotClosed(); - - if (_conn.channelLimitReached()) - { - throw new ChannelLimitReachedException(_conn.getMaximumChannelCount()); - } - - return new FailoverRetrySupport<Session, JMSException>( - new FailoverProtectedOperation<Session, JMSException>() - { - public Session execute() throws JMSException, FailoverException - { - int channelId = _conn.getNextChannelID(); - - if (_logger.isDebugEnabled()) - { - _logger.debug("Write channel open frame for channel id " + channelId); - } - - // We must create the session and register it before actually sending the frame to the server to - // open it, so that there is no window where we could receive data on the channel and not be set - // up to handle it appropriately. - AMQSession_0_8 session = - new AMQSession_0_8(_conn, channelId, transacted, acknowledgeMode, prefetchHigh, - prefetchLow); - _conn.registerSession(channelId, session); - - boolean success = false; - try - { - createChannelOverWire(channelId, transacted); - session.setPrefetchLimits(prefetchHigh, 0); - success = true; - } - catch (AMQException e) - { - JMSException jmse = new JMSException("Error creating session: " + e); - jmse.setLinkedException(e); - jmse.initCause(e); - throw jmse; - } - finally - { - if (!success) - { - _conn.deregisterSession(channelId); - } - } - - if (_conn.started()) - { - try - { - session.start(); - } - catch (AMQException e) - { - throw new JMSAMQException(e); - } - } - - return session; - } - }, _conn).execute(); - } - - /** - * Create an XASession with default prefetch values of: - * High = MaxPrefetch - * Low = MaxPrefetch / 2 - * @return XASession - * @throws JMSException thrown if there is a problem creating the session. - */ - public XASession createXASession() throws JMSException - { - return createXASession((int) _conn.getMaxPrefetch(), (int) _conn.getMaxPrefetch() / 2); - } - - private void createChannelOverWire(int channelId, boolean transacted) - throws AMQException, FailoverException - { - ChannelOpenBody channelOpenBody = _conn.getProtocolHandler().getMethodRegistry().createChannelOpenBody(null); - _conn.getProtocolHandler().syncWrite(channelOpenBody.generateFrame(channelId), ChannelOpenOkBody.class); - - if (transacted) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Issuing TxSelect for " + channelId); - } - TxSelectBody body = _conn.getProtocolHandler().getMethodRegistry().createTxSelectBody(); - - - _conn.getProtocolHandler().syncWrite(body.generateFrame(channelId), TxSelectOkBody.class); - } - boolean useConfirms = (_confirmedPublishSupported || (!transacted && _confirmedPublishNonTransactionalSupported)) - && "all".equals(_conn.getSyncPublish()); - if(useConfirms) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Issuing ConfirmSelect for " + channelId); - } - ConfirmSelectBody body = new ConfirmSelectBody(false); - - _conn.getProtocolHandler().syncWrite(body.generateFrame(channelId), ConfirmSelectOkBody.class); - } - } - - /** - * For all sessions, and for all consumers in those sessions, resubscribe. This is called during failover handling. - * The caller must hold the failover mutex before calling this method. - */ - public void resubscribeSessions() throws JMSException, AMQException, FailoverException - { - ArrayList sessions = new ArrayList(_conn.getSessions().values()); - _logger.info(MessageFormat.format("Resubscribing sessions = {0} sessions.size={1}", sessions, sessions.size())); // FIXME: removeKey? - for (Iterator it = sessions.iterator(); it.hasNext();) - { - AMQSession_0_8 s = (AMQSession_0_8) it.next(); - - // reset the flow control flag - // on opening channel, broker sends flow blocked if virtual host is blocked - // if virtual host is not blocked, then broker does not send flow command - // that's why we need to reset the flow control flag - s.setFlowControl(true); - reopenChannel(s.getChannelId(), s.getDefaultPrefetchHigh(), s.getDefaultPrefetchLow(), s.isTransacted()); - s.setPrefetchLimits(s.getDefaultPrefetchHigh(), 0); - s.resubscribe(); - } - } - - private void reopenChannel(int channelId, int prefetchHigh, int prefetchLow, boolean transacted) - throws AMQException, FailoverException - { - try - { - createChannelOverWire(channelId, transacted); - } - catch (AMQException e) - { - _conn.deregisterSession(channelId); - throw new AMQException(null, "Error reopening channel " + channelId + " after failover: " + e, e); - } - } - - public <T, E extends Exception> T executeRetrySupport(FailoverProtectedOperation<T,E> operation) throws E - { - while (true) - { - try - { - _conn.blockUntilNotFailingOver(); - } - catch (InterruptedException e) - { - _logger.debug("Interrupted: " + e, e); - - return null; - } - - synchronized (_conn.getFailoverMutex()) - { - try - { - return operation.execute(); - } - catch (FailoverException e) - { - _logger.debug("Failover exception caught during operation: " + e, e); - } - catch (IllegalStateException e) - { - if (!(e.getMessage().startsWith("Fail-over interrupted no-op failover support"))) - { - throw e; - } - } - } - } - } - - public int getMaxChannelID() - { - ConnectionTuneParameters params = _conn.getProtocolHandler().getProtocolSession().getConnectionTuneParameters(); - - return params == null ? AMQProtocolSession.MAX_CHANNEL_MAX : params.getChannelMax(); - } - - public int getMinChannelID() - { - return AMQProtocolSession.MIN_USABLE_CHANNEL_NUM; - } - - public ProtocolVersion getProtocolVersion() - { - return ProtocolVersion.v8_0; - } - - public boolean verifyClientID() throws JMSException - { - return true; - } - - /* - * @see org.apache.qpid.client.AMQConnectionDelegate#isSupportedServerFeature(java.lang.String) - */ - public boolean isSupportedServerFeature(String featureName) - { - // The Qpid Java Broker 0-8..0-9-1 does not advertise features by the qpid.features property, so for now - // we just hardcode JMS selectors as supported. - return ServerPropertyNames.FEATURE_QPID_JMS_SELECTOR.equals(featureName); - } - - @Override - public void setHeartbeatListener(HeartbeatListener listener) - { - _conn.getProtocolHandler().setHeartbeatListener(listener); - } - - @Override - public boolean supportsIsBound() - { - //Rough check whether the 'isBound' AMQP extension method is supported, by trying to determine if we are connected to Qpid. - //As older versions of the Qpid broker did not send properties, the value will be assumed true if no server properties - //are found, or the 'product' entry isn't present, and will only be false if it is present but doesn't match expectation. - boolean connectedToQpid = true; - - FieldTable serverProperties = _conn.getProtocolHandler().getProtocolSession().getConnectionStartServerProperties(); - if(serverProperties != null) - { - if(serverProperties.containsKey(ConnectionStartProperties.PRODUCT)) - { - //String.valueof to ensure it is non-null, then lowercase it - String product = String.valueOf(serverProperties.getString(ConnectionStartProperties.PRODUCT)).toLowerCase(); - - //value is "unknown" when the naming properties file hasn't been found, e.g in IDE. - connectedToQpid = product.contains("qpid") || product.equals("unknown"); - } - } - - if(_logger.isDebugEnabled()) - { - _logger.debug("supportsIsBound: " + connectedToQpid); - } - - return connectedToQpid; - } - - private boolean checkMessageCompressionSupported() - { - FieldTable serverProperties = _conn.getProtocolHandler().getProtocolSession().getConnectionStartServerProperties(); - return serverProperties != null - && Boolean.parseBoolean(serverProperties.getString(ConnectionStartProperties.QPID_MESSAGE_COMPRESSION_SUPPORTED)); - - } - - private boolean checkConfirmedPublishSupported() - { - FieldTable serverProperties = _conn.getProtocolHandler().getProtocolSession().getConnectionStartServerProperties(); - return serverProperties != null - && Boolean.parseBoolean(serverProperties.getString(ConnectionStartProperties.QPID_CONFIRMED_PUBLISH_SUPPORTED)); - - } - - public boolean isMessageCompressionSupported() - { - return _messageCompressionSupported; - } - - public boolean isAddrSyntaxSupported() - { - return _addrSyntaxSupported; - } - - public boolean isConfirmedPublishNonTransactionalSupported() - { - return _confirmedPublishNonTransactionalSupported; - } - - - private static class ReceiverClosedWaiter implements ByteBufferReceiver - { - private final CountDownLatch _closedWatcher; - private final ByteBufferReceiver _receiver; - - public ReceiverClosedWaiter(ByteBufferReceiver receiver) - { - _receiver = receiver; - _closedWatcher = new CountDownLatch(1); - } - - @Override - public void received(ByteBuffer msg) - { - _receiver.received(msg); - } - - @Override - public void exception(Throwable t) - { - _receiver.exception(t); - } - - @Override - public void closed() - { - try - { - _receiver.closed(); - } - finally - { - _closedWatcher.countDown(); - } - } - - public boolean awaitClose(long timeout) - { - try - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Waiting " + timeout + "ms for receiver to be closed"); - } - - return _closedWatcher.await(timeout, TimeUnit.MILLISECONDS); - } - catch (InterruptedException e) - { - Thread.currentThread().interrupt(); - return _closedWatcher.getCount() == 0; - } - } - }; -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_9_1.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_9_1.java deleted file mode 100755 index 442dd7b286..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_9_1.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.client; - -import org.apache.qpid.framing.ProtocolVersion; - - -public class AMQConnectionDelegate_9_1 extends AMQConnectionDelegate_8_0 -{ - - public AMQConnectionDelegate_9_1(AMQConnection conn) - { - super(conn); - } - - @Override - public ProtocolVersion getProtocolVersion() - { - return ProtocolVersion.v0_91; - } -}
\ No newline at end of file diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQConnectionFactory.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQConnectionFactory.java deleted file mode 100644 index e9580eff7e..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQConnectionFactory.java +++ /dev/null @@ -1,456 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.client; - -import org.apache.qpid.jms.ConnectionURL; -import org.apache.qpid.url.AMQBindingURL; -import org.apache.qpid.url.URLSyntaxException; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.JMSException; -import javax.jms.QueueConnection; -import javax.jms.QueueConnectionFactory; -import javax.jms.TopicConnection; -import javax.jms.TopicConnectionFactory; -import javax.jms.XAConnection; -import javax.jms.XAConnectionFactory; -import javax.jms.XAQueueConnection; -import javax.jms.XAQueueConnectionFactory; -import javax.jms.XATopicConnection; -import javax.jms.XATopicConnectionFactory; -import javax.naming.Context; -import javax.naming.Name; -import javax.naming.NamingException; -import javax.naming.RefAddr; -import javax.naming.Reference; -import javax.naming.Referenceable; -import javax.naming.StringRefAddr; -import javax.naming.spi.ObjectFactory; - -import java.io.Serializable; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.Hashtable; -import java.util.UUID; - - -public class AMQConnectionFactory implements ConnectionFactory, QueueConnectionFactory, TopicConnectionFactory, - ObjectFactory, Referenceable, XATopicConnectionFactory, - XAQueueConnectionFactory, XAConnectionFactory, Serializable -{ - protected static final String NO_URL_CONFIGURED = "The connection factory wasn't created with a proper URL, the connection details are empty"; - - - private ConnectionURL _connectionDetails; - - // The default constructor is necessary to allow AMQConnectionFactory to be deserialised from JNDI - public AMQConnectionFactory() - { - } - - public AMQConnectionFactory(final String url) throws URLSyntaxException - { - if (url == null) - { - throw new IllegalArgumentException("url cannot be null"); - } - - _connectionDetails = new AMQConnectionURL(url); - } - - public AMQConnectionFactory(ConnectionURL url) - { - if (url == null) - { - throw new IllegalArgumentException("url cannot be null"); - } - - _connectionDetails = url; - } - - /** - * @return the virtualPath of the connection details. - */ - public final String getVirtualPath() - { - return _connectionDetails.getVirtualHost(); - } - - public static String getUniqueClientID() - { - try - { - InetAddress addr = InetAddress.getLocalHost(); - return addr.getHostName() + System.currentTimeMillis(); - } - catch (UnknownHostException e) - { - return "UnknownHost" + UUID.randomUUID(); - } - } - - public Connection createConnection() throws JMSException - { - if(_connectionDetails == null) - { - throw new JMSException(NO_URL_CONFIGURED); - } - - try - { - if (_connectionDetails.getClientName() == null || _connectionDetails.getClientName().equals("")) - { - _connectionDetails.setClientName(getUniqueClientID()); - } - return new AMQConnection(_connectionDetails); - } - catch (Exception e) - { - JMSException jmse = new JMSException("Error creating connection: " + e.getMessage()); - jmse.setLinkedException(e); - jmse.initCause(e); - throw jmse; - } - } - - public Connection createConnection(String userName, String password) throws JMSException - { - return createConnection(userName, password, null); - } - - public Connection createConnection(String userName, String password, String id) throws JMSException - { - if (_connectionDetails != null) - { - try - { - ConnectionURL connectionDetails = new AMQConnectionURL(_connectionDetails.getURL()); - connectionDetails.setUsername(userName); - connectionDetails.setPassword(password); - - if (id != null && !id.equals("")) - { - connectionDetails.setClientName(id); - } - else if (connectionDetails.getClientName() == null || connectionDetails.getClientName().equals("")) - { - connectionDetails.setClientName(getUniqueClientID()); - } - return new AMQConnection(connectionDetails); - } - catch (Exception e) - { - JMSException jmse = new JMSException("Error creating connection: " + e.getMessage()); - jmse.setLinkedException(e); - jmse.initCause(e); - throw jmse; - } - } - else - { - throw new JMSException(NO_URL_CONFIGURED); - } - } - - public QueueConnection createQueueConnection() throws JMSException - { - return (QueueConnection) createConnection(); - } - - public QueueConnection createQueueConnection(String username, String password) throws JMSException - { - return (QueueConnection) createConnection(username, password); - } - - public TopicConnection createTopicConnection() throws JMSException - { - return (TopicConnection) createConnection(); - } - - public TopicConnection createTopicConnection(String username, String password) throws JMSException - { - return (TopicConnection) createConnection(username, password); - } - - - public ConnectionURL getConnectionURL() - { - return _connectionDetails; - } - - public String getConnectionURLString() - { - return _connectionDetails.toString(); - } - - //setter necessary to use instances created with the default constructor (which we can't remove) - public final void setConnectionURLString(String url) throws URLSyntaxException - { - _connectionDetails = new AMQConnectionURL(url); - } - - /** - * JNDI interface to create objects from References. - * - * @param obj The Reference from JNDI - * @param name - * @param ctx - * @param env - * - * @return AMQConnection,AMQTopic,AMQQueue, or AMQConnectionFactory. - * - * @throws Exception - */ - public Object getObjectInstance(Object obj, Name name, Context ctx, Hashtable env) throws Exception - { - if (obj instanceof Reference) - { - Reference ref = (Reference) obj; - - if (ref.getClassName().equals(AMQConnection.class.getName())) - { - RefAddr addr = ref.get(AMQConnection.class.getName()); - - if (addr != null) - { - return new AMQConnection((String) addr.getContent()); - } - } - - if (ref.getClassName().equals(AMQQueue.class.getName())) - { - RefAddr addr = ref.get(AMQQueue.class.getName()); - - if (addr != null) - { - return new AMQQueue(new AMQBindingURL((String) addr.getContent())); - } - } - - if (ref.getClassName().equals(AMQTopic.class.getName())) - { - RefAddr addr = ref.get(AMQTopic.class.getName()); - - if (addr != null) - { - return new AMQTopic(new AMQBindingURL((String) addr.getContent())); - } - } - - if (ref.getClassName().equals(AMQConnectionFactory.class.getName())) - { - RefAddr addr = ref.get(AMQConnectionFactory.class.getName()); - - if (addr != null) - { - return new AMQConnectionFactory((String) addr.getContent()); - } - } - - } - return null; - } - - - public Reference getReference() throws NamingException - { - return new Reference( - AMQConnectionFactory.class.getName(), - new StringRefAddr(AMQConnectionFactory.class.getName(), _connectionDetails.getURL()), - AMQConnectionFactory.class.getName(), null); // factory location - } - - // --------------------------------------------------------------------------------------------------- - // the following methods are provided for XA compatibility - // Those methods are only supported by 0_10 and above - // --------------------------------------------------------------------------------------------------- - - /** - * Creates a XAConnection with the default user identity. - * <p> The XAConnection is created in stopped mode. No messages - * will be delivered until the <code>Connection.start</code> method - * is explicitly called. - * - * @return A newly created XAConnection - * @throws JMSException If creating the XAConnection fails due to some internal error. - * @throws javax.jms.JMSSecurityException If client authentication fails due to an invalid user name or password. - */ - public XAConnection createXAConnection() throws JMSException - { - try - { - return new XAConnectionImpl(_connectionDetails); - } - catch (Exception e) - { - JMSException jmse = new JMSException("Error creating connection: " + e.getMessage()); - jmse.setLinkedException(e); - jmse.initCause(e); - throw jmse; - } - } - - /** - * Creates a XAConnection with the specified user identity. - * <p> The XAConnection is created in stopped mode. No messages - * will be delivered until the <code>Connection.start</code> method - * is explicitly called. - * - * @param username the caller's user name - * @param password the caller's password - * @return A newly created XAConnection. - * @throws JMSException If creating the XAConnection fails due to some internal error. - * @throws javax.jms.JMSSecurityException If client authentication fails due to an invalid user name or password. - */ - public XAConnection createXAConnection(String username, String password) throws JMSException - { - if (_connectionDetails != null) - { - try - { - ConnectionURL connectionDetails = new AMQConnectionURL(_connectionDetails.toString()); - connectionDetails.setUsername(username); - connectionDetails.setPassword(password); - - if (connectionDetails.getClientName() == null || connectionDetails.getClientName().equals("")) - { - connectionDetails.setClientName(getUniqueClientID()); - } - return new XAConnectionImpl(connectionDetails); - } - catch (Exception e) - { - JMSException jmse = new JMSException("Error creating XA Connection: " + e.getMessage()); - jmse.setLinkedException(e); - jmse.initCause(e); - throw jmse; - } - } - else - { - throw new JMSException(NO_URL_CONFIGURED); - } - } - - - /** - * Creates a XATopicConnection with the default user identity. - * <p> The XATopicConnection is created in stopped mode. No messages - * will be delivered until the <code>Connection.start</code> method - * is explicitly called. - * - * @return A newly created XATopicConnection - * @throws JMSException If creating the XATopicConnection fails due to some internal error. - * @throws javax.jms.JMSSecurityException If client authentication fails due to an invalid user name or password. - */ - public XATopicConnection createXATopicConnection() throws JMSException - { - return (XATopicConnection) createXAConnection(); - } - - /** - * Creates a XATopicConnection with the specified user identity. - * <p> The XATopicConnection is created in stopped mode. No messages - * will be delivered until the <code>Connection.start</code> method - * is explicitly called. - * - * @param username the caller's user name - * @param password the caller's password - * @return A newly created XATopicConnection. - * @throws JMSException If creating the XATopicConnection fails due to some internal error. - * @throws javax.jms.JMSSecurityException If client authentication fails due to an invalid user name or password. - */ - public XATopicConnection createXATopicConnection(String username, String password) throws JMSException - { - return (XATopicConnection) createXAConnection(username, password); - } - - /** - * Creates a XAQueueConnection with the default user identity. - * <p> The XAQueueConnection is created in stopped mode. No messages - * will be delivered until the <code>Connection.start</code> method - * is explicitly called. - * - * @return A newly created XAQueueConnection - * @throws JMSException If creating the XAQueueConnection fails due to some internal error. - * @throws javax.jms.JMSSecurityException If client authentication fails due to an invalid user name or password. - */ - public XAQueueConnection createXAQueueConnection() throws JMSException - { - return (XAQueueConnection) createXAConnection(); - } - - /** - * Creates a XAQueueConnection with the specified user identity. - * <p> The XAQueueConnection is created in stopped mode. No messages - * will be delivered until the <code>Connection.start</code> method - * is explicitly called. - * - * @param username the caller's user name - * @param password the caller's password - * @return A newly created XAQueueConnection. - * @throws JMSException If creating the XAQueueConnection fails due to some internal error. - * @throws javax.jms.JMSSecurityException If client authentication fails due to an invalid user name or password. - */ - public XAQueueConnection createXAQueueConnection(String username, String password) throws JMSException - { - return (XAQueueConnection) createXAConnection(username, password); - } - - @Override - public boolean equals(final Object o) - { - if (this == o) - { - return true; - } - if (o == null || getClass() != o.getClass()) - { - return false; - } - - final AMQConnectionFactory that = (AMQConnectionFactory) o; - - if (_connectionDetails != null - ? !_connectionDetails.equals(that._connectionDetails) - : that._connectionDetails != null) - { - return false; - } - - return true; - } - - @Override - public int hashCode() - { - return _connectionDetails != null ? _connectionDetails.hashCode() : 0; - } - - @Override - public String toString() - { - return "AMQConnectionFactory{" + - "_connectionDetails=" + _connectionDetails + - '}'; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQConnectionURL.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQConnectionURL.java deleted file mode 100644 index 2e256b1f57..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQConnectionURL.java +++ /dev/null @@ -1,389 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.client; - -import org.apache.qpid.client.url.URLParser; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.jms.BrokerDetails; -import org.apache.qpid.jms.ConnectionURL; -import org.apache.qpid.url.URLHelper; -import org.apache.qpid.url.URLSyntaxException; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -public class AMQConnectionURL implements ConnectionURL, Serializable -{ - private static final long serialVersionUID = -5102704772070465832L; - - private String _url; - private String _failoverMethod; - private Map<String, String> _failoverOptions; - private Map<String, String> _options; - private List<BrokerDetails> _brokers; - private String _clientName; - private String _username; - private String _password; - private String _virtualHost; - private String _defaultQueueExchangeName; - private String _defaultTopicExchangeName; - private String _temporaryTopicExchangeName; - private String _temporaryQueueExchangeName; - - public AMQConnectionURL(String fullURL) throws URLSyntaxException - { - if (fullURL == null) - { - throw new IllegalArgumentException("URL cannot be null"); - } - _url = fullURL; - _options = new HashMap<String, String>(); - _brokers = new LinkedList<BrokerDetails>(); - _failoverOptions = new HashMap<String, String>(); - new URLParser(this); - } - - public String getURL() - { - return _url; - } - - public Map<String,String> getOptions() - { - return _options; - } - - public String getFailoverMethod() - { - return _failoverMethod; - } - - public void setFailoverMethod(String failoverMethod) - { - _failoverMethod = failoverMethod; - } - - public Map<String,String> getFailoverOptions() - { - return _failoverOptions; - } - - public String getFailoverOption(String key) - { - return _failoverOptions.get(key); - } - - public void setFailoverOption(String key, String value) - { - _failoverOptions.put(key, value); - } - - public int getBrokerCount() - { - return _brokers.size(); - } - - public BrokerDetails getBrokerDetails(int index) - { - if (index < _brokers.size()) - { - return _brokers.get(index); - } - else - { - return null; - } - } - - public void addBrokerDetails(BrokerDetails broker) - { - if (!(_brokers.contains(broker))) - { - _brokers.add(broker); - } - } - - public void setBrokerDetails(List<BrokerDetails> brokers) - { - _brokers = brokers; - } - - public List<BrokerDetails> getAllBrokerDetails() - { - return _brokers; - } - - public String getClientName() - { - return _clientName; - } - - public void setClientName(String clientName) - { - _clientName = clientName; - } - - public String getUsername() - { - return _username; - } - - public void setUsername(String username) - { - _username = username; - } - - public String getPassword() - { - return _password; - } - - public void setPassword(String password) - { - _password = password; - } - - public String getVirtualHost() - { - return _virtualHost; - } - - public void setVirtualHost(String virtuaHost) - { - _virtualHost = virtuaHost; - } - - public String getOption(String key) - { - return _options.get(key); - } - - public void setOption(String key, String value) - { - _options.put(key, value); - } - - public AMQShortString getDefaultQueueExchangeName() - { - return _defaultQueueExchangeName == null ? null : new AMQShortString(_defaultQueueExchangeName); - } - - public void setDefaultQueueExchangeName(AMQShortString defaultQueueExchangeName) - { - _defaultQueueExchangeName = defaultQueueExchangeName == null ? null : defaultQueueExchangeName.asString(); - } - - public AMQShortString getDefaultTopicExchangeName() - { - return _defaultTopicExchangeName == null ? null : new AMQShortString(_defaultTopicExchangeName); - } - - public void setDefaultTopicExchangeName(AMQShortString defaultTopicExchangeName) - { - _defaultTopicExchangeName = defaultTopicExchangeName == null ? null : defaultTopicExchangeName.asString(); - } - - public AMQShortString getTemporaryQueueExchangeName() - { - return _temporaryQueueExchangeName == null ? null : new AMQShortString(_temporaryQueueExchangeName); - } - - public void setTemporaryQueueExchangeName(AMQShortString temporaryQueueExchangeName) - { - _temporaryQueueExchangeName = temporaryQueueExchangeName == null ? null : temporaryQueueExchangeName.asString(); - } - - public AMQShortString getTemporaryTopicExchangeName() - { - return _temporaryTopicExchangeName == null ? null : new AMQShortString(_temporaryTopicExchangeName); - } - - public void setTemporaryTopicExchangeName(AMQShortString temporaryTopicExchangeName) - { - _temporaryTopicExchangeName = temporaryTopicExchangeName == null ? null : temporaryTopicExchangeName.asString() ; - } - - @Override - public boolean equals(final Object o) - { - if (this == o) - { - return true; - } - if (o == null || getClass() != o.getClass()) - { - return false; - } - - final AMQConnectionURL that = (AMQConnectionURL) o; - - if (_brokers != null ? !_brokers.equals(that._brokers) : that._brokers != null) - { - return false; - } - if (_clientName != null ? !_clientName.equals(that._clientName) : that._clientName != null) - { - return false; - } - if (_defaultQueueExchangeName != null - ? !_defaultQueueExchangeName.equals(that._defaultQueueExchangeName) - : that._defaultQueueExchangeName != null) - { - return false; - } - if (_defaultTopicExchangeName != null - ? !_defaultTopicExchangeName.equals(that._defaultTopicExchangeName) - : that._defaultTopicExchangeName != null) - { - return false; - } - if (_failoverMethod != null ? !_failoverMethod.equals(that._failoverMethod) : that._failoverMethod != null) - { - return false; - } - if (_failoverOptions != null ? !_failoverOptions.equals(that._failoverOptions) : that._failoverOptions != null) - { - return false; - } - if (_options != null ? !_options.equals(that._options) : that._options != null) - { - return false; - } - if (_password != null ? !_password.equals(that._password) : that._password != null) - { - return false; - } - if (_temporaryQueueExchangeName != null - ? !_temporaryQueueExchangeName.equals(that._temporaryQueueExchangeName) - : that._temporaryQueueExchangeName != null) - { - return false; - } - if (_temporaryTopicExchangeName != null - ? !_temporaryTopicExchangeName.equals(that._temporaryTopicExchangeName) - : that._temporaryTopicExchangeName != null) - { - return false; - } - if (_url != null ? !_url.equals(that._url) : that._url != null) - { - return false; - } - if (_username != null ? !_username.equals(that._username) : that._username != null) - { - return false; - } - if (_virtualHost != null ? !_virtualHost.equals(that._virtualHost) : that._virtualHost != null) - { - return false; - } - - return true; - } - - @Override - public int hashCode() - { - int result = _url != null ? _url.hashCode() : 0; - result = 31 * result + (_failoverMethod != null ? _failoverMethod.hashCode() : 0); - result = 31 * result + (_failoverOptions != null ? _failoverOptions.hashCode() : 0); - result = 31 * result + (_options != null ? _options.hashCode() : 0); - result = 31 * result + (_brokers != null ? _brokers.hashCode() : 0); - result = 31 * result + (_clientName != null ? _clientName.hashCode() : 0); - result = 31 * result + (_username != null ? _username.hashCode() : 0); - result = 31 * result + (_password != null ? _password.hashCode() : 0); - result = 31 * result + (_virtualHost != null ? _virtualHost.hashCode() : 0); - result = 31 * result + (_defaultQueueExchangeName != null ? _defaultQueueExchangeName.hashCode() : 0); - result = 31 * result + (_defaultTopicExchangeName != null ? _defaultTopicExchangeName.hashCode() : 0); - result = 31 * result + (_temporaryTopicExchangeName != null ? _temporaryTopicExchangeName.hashCode() : 0); - result = 31 * result + (_temporaryQueueExchangeName != null ? _temporaryQueueExchangeName.hashCode() : 0); - return result; - } - - @Override - public String toString() - { - StringBuilder sb = new StringBuilder(); - - sb.append(AMQ_PROTOCOL); - sb.append("://"); - - if (_username != null) - { - sb.append(_username); - - if (_password != null) - { - sb.append(':'); - sb.append("********"); - } - - sb.append('@'); - } - - sb.append(_clientName); - - sb.append(_virtualHost); - - sb.append(optionsToString()); - - return sb.toString(); - } - - private String optionsToString() - { - StringBuffer sb = new StringBuffer("?"); - - if (!_options.isEmpty()) - { - for (Map.Entry<String, String> option : _options.entrySet()) - { - sb.append(option.getKey()).append("='").append(option.getValue()).append("'"); - sb.append(URLHelper.DEFAULT_OPTION_SEPERATOR); - } - } - - sb.append(OPTIONS_BROKERLIST).append("='"); - for (BrokerDetails service : _brokers) - { - sb.append(service.toString()); - sb.append(URLHelper.BROKER_SEPARATOR); - } - - sb.deleteCharAt(sb.length() - 1); - sb.append("'"); - - if (_failoverMethod != null) - { - sb.append(URLHelper.DEFAULT_OPTION_SEPERATOR); - sb.append(OPTIONS_FAILOVER); - sb.append("='"); - sb.append(_failoverMethod); - sb.append(URLHelper.printOptions(_failoverOptions)); - sb.append("'"); - } - - return sb.toString(); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQDestination.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQDestination.java deleted file mode 100644 index 2eeea4c967..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQDestination.java +++ /dev/null @@ -1,1078 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; - -import java.io.Externalizable; -import java.io.IOException; -import java.io.ObjectInput; -import java.io.ObjectOutput; -import java.net.URISyntaxException; -import java.util.Map; -import java.util.concurrent.atomic.AtomicLong; - -import javax.jms.Destination; -import javax.naming.NamingException; -import javax.naming.Reference; -import javax.naming.Referenceable; -import javax.naming.StringRefAddr; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.client.messaging.address.AddressHelper; -import org.apache.qpid.client.messaging.address.Link; -import org.apache.qpid.client.messaging.address.Node; -import org.apache.qpid.configuration.ClientProperties; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.messaging.Address; -import org.apache.qpid.url.AMQBindingURL; -import org.apache.qpid.url.BindingURL; -import org.apache.qpid.url.URLHelper; - - -public abstract class AMQDestination implements Destination, Referenceable, Externalizable -{ - private static final Logger _logger = LoggerFactory.getLogger(AMQDestination.class); - private static final long serialVersionUID = -3716263015355017537L; - - private AMQShortString _exchangeName; - - private AMQShortString _exchangeClass; - - private boolean _exchangeAutoDelete; - - private boolean _exchangeDurable; - - private boolean _exchangeInternal; - - private boolean _isDurable; - - private boolean _isExclusive; - - private boolean _isAutoDelete; - - private boolean _browseOnly; - - private AtomicLong _addressResolved = new AtomicLong(0); - - private AMQShortString _queueName; - - private AMQShortString _routingKey; - - private AMQShortString[] _bindingKeys; - - private String _url; - private AMQShortString _urlAsShortString; - - private boolean _checkedForQueueBinding; - - private boolean _exchangeExistsChecked; - - private RejectBehaviour _rejectBehaviour; - - private Map<String,Object> _consumerArguments; - - public static final int QUEUE_TYPE = 1; - public static final int TOPIC_TYPE = 2; - public static final int UNKNOWN_TYPE = 3; - - protected void setExclusive(boolean exclusive) - { - _isExclusive = exclusive; - } - - protected AddressHelper getAddrHelper() - { - return _addrHelper; - } - - protected void setAddrHelper(AddressHelper addrHelper) - { - _addrHelper = addrHelper; - } - - protected String getName() - { - return _name; - } - - protected void setName(String name) - { - _name = name; - } - - public boolean neverDeclare() - { - return false; - } - - // ----- Fields required to support new address syntax ------- - - public enum DestSyntax { - BURL,ADDR; - - public static DestSyntax getSyntaxType(String s) - { - if (("BURL").equals(s)) - { - return BURL; - } - else if (("ADDR").equals(s)) - { - return ADDR; - } - else - { - throw new IllegalArgumentException("Invalid Destination Syntax Type" + - " should be one of {BURL|ADDR}"); - } - } - } - - public enum AddressOption { - ALWAYS, NEVER, SENDER, RECEIVER; - - public static AddressOption getOption(String str) - { - if ("always".equals(str)) - { - return ALWAYS; - } - else if ("never".equals(str)) - { - return NEVER; - } - else if ("sender".equals(str)) - { - return SENDER; - } - else if ("receiver".equals(str)) - { - return RECEIVER; - } - else - { - throw new IllegalArgumentException(str + " is not an allowed value"); - } - } - } - - private final static DestSyntax defaultDestSyntax; - - private DestSyntax _destSyntax = DestSyntax.ADDR; - - private AddressHelper _addrHelper; - private Address _address; - private int _addressType = AMQDestination.UNKNOWN_TYPE; - private String _name; - private String _subject; - private AddressOption _create = AddressOption.NEVER; - private AddressOption _assert = AddressOption.NEVER; - private AddressOption _delete = AddressOption.NEVER; - - private Node _node; - private Link _link; - - - // ----- / Fields required to support new address syntax ------- - - static - { - defaultDestSyntax = DestSyntax.getSyntaxType( - System.getProperty(ClientProperties.DEST_SYNTAX, - DestSyntax.ADDR.toString())); - - - } - - public static DestSyntax getDefaultDestSyntax() - { - return defaultDestSyntax; - } - - protected AMQDestination() - { - } - - protected AMQDestination(Address address) - { - this._address = address; - getInfoFromAddress(); - _destSyntax = DestSyntax.ADDR; - _logger.debug("Based on " + address + " the selected destination syntax is " + _destSyntax); - } - - public static DestSyntax getDestType(String str) - { - if (str.startsWith("BURL:") || - (!str.startsWith("ADDR:") && defaultDestSyntax == DestSyntax.BURL)) - { - return DestSyntax.BURL; - } - else - { - return DestSyntax.ADDR; - } - } - - public static String stripSyntaxPrefix(String str) - { - if (str.startsWith("BURL:") || str.startsWith("ADDR:")) - { - return str.substring(5,str.length()); - } - else - { - return str; - } - } - - protected AMQDestination(String str) throws URISyntaxException - { - parseDestinationString(str); - } - - protected void parseDestinationString(String str) throws URISyntaxException - { - _destSyntax = getDestType(str); - str = stripSyntaxPrefix(str); - if (_destSyntax == DestSyntax.BURL) - { - getInfoFromBindingURL(new AMQBindingURL(str)); - } - else - { - this._address = createAddressFromString(str); - try - { - getInfoFromAddress(); - } - catch(Exception e) - { - URISyntaxException ex = new URISyntaxException(str,"Error parsing address"); - ex.initCause(e); - throw ex; - } - } - _logger.debug("Based on " + str + " the selected destination syntax is " + _destSyntax); - } - - //retained for legacy support - protected AMQDestination(BindingURL binding) - { - getInfoFromBindingURL(binding); - _destSyntax = DestSyntax.BURL; - _logger.debug("Based on " + binding + " the selected destination syntax is " + _destSyntax); - } - - protected void getInfoFromBindingURL(BindingURL binding) - { - _exchangeName = binding.getExchangeName(); - _exchangeClass = binding.getExchangeClass(); - _exchangeDurable = Boolean.parseBoolean(binding.getOption(BindingURL.OPTION_EXCHANGE_DURABLE)); - _exchangeAutoDelete = Boolean.parseBoolean(binding.getOption(BindingURL.OPTION_EXCHANGE_AUTODELETE)); - _exchangeInternal = Boolean.parseBoolean(binding.getOption(BindingURL.OPTION_EXCHANGE_INTERNAL)); - - _isExclusive = Boolean.parseBoolean(binding.getOption(BindingURL.OPTION_EXCLUSIVE)); - _isAutoDelete = Boolean.parseBoolean(binding.getOption(BindingURL.OPTION_AUTODELETE)); - _isDurable = Boolean.parseBoolean(binding.getOption(BindingURL.OPTION_DURABLE)); - _browseOnly = Boolean.parseBoolean(binding.getOption(BindingURL.OPTION_BROWSE)); - _queueName = binding.getQueueName() == null ? null : binding.getQueueName(); - _routingKey = binding.getRoutingKey() == null ? null : binding.getRoutingKey(); - _bindingKeys = binding.getBindingKeys() == null || binding.getBindingKeys().length == 0 ? new AMQShortString[0] : binding.getBindingKeys(); - final String rejectBehaviourValue = binding.getOption(BindingURL.OPTION_REJECT_BEHAVIOUR); - _rejectBehaviour = rejectBehaviourValue == null ? null : RejectBehaviour.valueOf(rejectBehaviourValue.toUpperCase()); - _consumerArguments = binding.getConsumerOptions(); - } - - protected AMQDestination(AMQShortString exchangeName, AMQShortString exchangeClass, AMQShortString routingKey, AMQShortString queueName) - { - this(exchangeName, exchangeClass, routingKey, false, false, queueName, null); - } - - protected AMQDestination(AMQShortString exchangeName, AMQShortString exchangeClass, AMQShortString routingKey, AMQShortString queueName, AMQShortString[] bindingKeys) - { - this(exchangeName, exchangeClass, routingKey, false, false, queueName,bindingKeys); - } - - protected AMQDestination(AMQShortString exchangeName, AMQShortString exchangeClass, AMQShortString destinationName) - { - this(exchangeName, exchangeClass, destinationName, false, false, null,null); - } - - protected AMQDestination(AMQShortString exchangeName, AMQShortString exchangeClass, AMQShortString routingKey, boolean isExclusive, - boolean isAutoDelete, AMQShortString queueName) - { - this(exchangeName, exchangeClass, routingKey, isExclusive, isAutoDelete, queueName, false,null); - } - - protected AMQDestination(AMQShortString exchangeName, AMQShortString exchangeClass, AMQShortString routingKey, boolean isExclusive, - boolean isAutoDelete, AMQShortString queueName,AMQShortString[] bindingKeys) - { - this(exchangeName, exchangeClass, routingKey, isExclusive, isAutoDelete, queueName, false,bindingKeys); - } - - protected AMQDestination(AMQShortString exchangeName, AMQShortString exchangeClass, AMQShortString routingKey, boolean isExclusive, - boolean isAutoDelete, AMQShortString queueName, boolean isDurable){ - this (exchangeName, exchangeClass, routingKey, isExclusive,isAutoDelete,queueName,isDurable,null); - } - - protected AMQDestination(AMQShortString exchangeName, AMQShortString exchangeClass, AMQShortString routingKey, boolean isExclusive, - boolean isAutoDelete, AMQShortString queueName, boolean isDurable,AMQShortString[] bindingKeys) - { - this (exchangeName, exchangeClass, routingKey, isExclusive,isAutoDelete,queueName,isDurable,bindingKeys, false); - } - - protected AMQDestination(AMQShortString exchangeName, AMQShortString exchangeClass, AMQShortString routingKey, boolean isExclusive, - boolean isAutoDelete, AMQShortString queueName, boolean isDurable,AMQShortString[] bindingKeys, boolean browseOnly) - { - if ( (AMQShortString.valueOf(ExchangeDefaults.DIRECT_EXCHANGE_CLASS).equals(exchangeClass) || - AMQShortString.valueOf(ExchangeDefaults.TOPIC_EXCHANGE_CLASS).equals(exchangeClass)) - && routingKey == null) - { - throw new IllegalArgumentException("routing/binding key must not be null"); - } - if (exchangeName == null) - { - throw new IllegalArgumentException("Exchange name must not be null"); - } - if (exchangeClass == null) - { - throw new IllegalArgumentException("Exchange class must not be null"); - } - _exchangeName = exchangeName; - _exchangeClass = exchangeClass; - _routingKey = routingKey; - _isExclusive = isExclusive; - _isAutoDelete = isAutoDelete; - _queueName = queueName; - _isDurable = isDurable; - _bindingKeys = bindingKeys == null || bindingKeys.length == 0 ? new AMQShortString[0] : bindingKeys; - _destSyntax = DestSyntax.BURL; - _browseOnly = browseOnly; - _rejectBehaviour = null; - _exchangeAutoDelete = false; - _exchangeDurable = false; - _exchangeInternal = false; - - if (_logger.isDebugEnabled()) - { - _logger.debug("Based on " + toString() + " the selected destination syntax is " + _destSyntax); - } - } - - public void setDestinationString(String str) throws Exception - { - parseDestinationString(str); - } - - public String getDestinationString() - { - return toString(); - } - - public DestSyntax getDestSyntax() - { - return _destSyntax; - } - - protected void setDestSyntax(DestSyntax syntax) - { - _destSyntax = syntax; - } - - public AMQShortString getEncodedName() - { - if(_urlAsShortString == null) - { - if (_url == null) - { - toURL(); - } - _urlAsShortString = new AMQShortString(_url); - } - return _urlAsShortString; - } - - public boolean isDurable() - { - return _isDurable; - } - - public AMQShortString getExchangeName() - { - return _exchangeName; - } - - public AMQShortString getExchangeClass() - { - return _exchangeClass; - } - - public boolean isExchangeDurable() - { - return _exchangeDurable; - } - - public boolean isExchangeAutoDelete() - { - return _exchangeAutoDelete; - } - - public boolean isExchangeInternal() - { - return _exchangeInternal; - } - - public boolean isTopic() - { - return AMQShortString.valueOf(ExchangeDefaults.TOPIC_EXCHANGE_CLASS).equals(_exchangeClass); - } - - public boolean isQueue() - { - return AMQShortString.valueOf(ExchangeDefaults.DIRECT_EXCHANGE_CLASS).equals(_exchangeClass); - } - - public String getQueueName() - { - return _queueName == null ? null : _queueName.toString(); - } - - public AMQShortString getAMQQueueName() - { - return _queueName; - } - - public void setQueueName(AMQShortString queueName) - { - - _queueName = queueName; - // calculated URL now out of date - _url = null; - _urlAsShortString = null; - } - - public AMQShortString getRoutingKey() - { - return _routingKey; - } - - public AMQShortString[] getBindingKeys() - { - if (_bindingKeys != null && _bindingKeys.length > 0) - { - return _bindingKeys; - } - else - { - // catering to the common use case where the - //routingKey is the same as the bindingKey. - return new AMQShortString[]{_routingKey}; - } - } - - public boolean isExclusive() - { - return _isExclusive; - } - - public boolean isAutoDelete() - { - return _isAutoDelete; - } - - public abstract boolean isNameRequired(); - - public String toString() - { - if (_destSyntax == DestSyntax.BURL) - { - return toURL(); - } - else - { - return _address.toString(); - } - - } - - public boolean isCheckedForQueueBinding() - { - return _checkedForQueueBinding; - } - - public void setCheckedForQueueBinding(boolean checkedForQueueBinding) - { - _checkedForQueueBinding = checkedForQueueBinding; - } - - - public boolean isExchangeExistsChecked() - { - return _exchangeExistsChecked; - } - - public void setExchangeExistsChecked(final boolean exchangeExistsChecked) - { - _exchangeExistsChecked = exchangeExistsChecked; - } - - public String toURL() - { - String url = _url; - if(url == null) - { - - - StringBuffer sb = new StringBuffer(); - - sb.append(_exchangeClass); - sb.append("://"); - sb.append(_exchangeName); - - sb.append("/"+_routingKey+"/"); - - if (_queueName != null) - { - sb.append(_queueName); - } - - sb.append('?'); - - if (_routingKey != null) - { - sb.append(BindingURL.OPTION_ROUTING_KEY); - sb.append("='"); - sb.append(_routingKey).append("'"); - sb.append(URLHelper.DEFAULT_OPTION_SEPERATOR); - } - - // We can't allow both routingKey and bindingKey - if (_routingKey == null && _bindingKeys != null && _bindingKeys.length>0) - { - - for (AMQShortString bindingKey:_bindingKeys) - { - sb.append(BindingURL.OPTION_BINDING_KEY); - sb.append("='"); - sb.append(bindingKey); - sb.append("'"); - sb.append(URLHelper.DEFAULT_OPTION_SEPERATOR); - - } - } - - if (_isDurable) - { - sb.append(BindingURL.OPTION_DURABLE); - sb.append("='true'"); - sb.append(URLHelper.DEFAULT_OPTION_SEPERATOR); - } - - if (_isExclusive) - { - sb.append(BindingURL.OPTION_EXCLUSIVE); - sb.append("='true'"); - sb.append(URLHelper.DEFAULT_OPTION_SEPERATOR); - } - - if (_isAutoDelete) - { - sb.append(BindingURL.OPTION_AUTODELETE); - sb.append("='true'"); - sb.append(URLHelper.DEFAULT_OPTION_SEPERATOR); - } - - if (_rejectBehaviour != null) - { - sb.append(BindingURL.OPTION_REJECT_BEHAVIOUR); - sb.append("='" + _rejectBehaviour + "'"); - sb.append(URLHelper.DEFAULT_OPTION_SEPERATOR); - } - - if (_exchangeDurable) - { - sb.append(BindingURL.OPTION_EXCHANGE_DURABLE); - sb.append("='true'"); - sb.append(URLHelper.DEFAULT_OPTION_SEPERATOR); - } - - if (_exchangeAutoDelete) - { - sb.append(BindingURL.OPTION_EXCHANGE_AUTODELETE); - sb.append("='true'"); - sb.append(URLHelper.DEFAULT_OPTION_SEPERATOR); - } - - if (_exchangeInternal) - { - sb.append(BindingURL.OPTION_EXCHANGE_INTERNAL); - sb.append("='true'"); - sb.append(URLHelper.DEFAULT_OPTION_SEPERATOR); - } - - //removeKey the last char '?' if there is no options , ',' if there are. - sb.deleteCharAt(sb.length() - 1); - url = sb.toString(); - _url = url; - } - return url; - } - - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - if (!(o instanceof AMQDestination)) - { - return false; - } - - final AMQDestination that = (AMQDestination) o; - - if (_destSyntax != that.getDestSyntax()) - { - return false; - } - - if (_destSyntax == DestSyntax.ADDR) - { - if (_addressType != that.getAddressType()) - { - return false; - } - if (!_name.equals(that.getAddressName())) - { - return false; - } - if (_subject == null) - { - if (that.getSubject() != null) - { - return false; - } - } - else if (!_subject.equals(that.getSubject())) - { - return false; - } - } - else - { - if (!_exchangeClass.equals(that._exchangeClass)) - { - return false; - } - if (!_exchangeName.equals(that._exchangeName)) - { - return false; - } - if ((_queueName == null && that._queueName != null) || - (_queueName != null && !_queueName.equals(that._queueName))) - { - return false; - } - } - return true; - } - - public int hashCode() - { - int result; - if (_destSyntax == DestSyntax.ADDR) - { - result = 29 * _addressType + _name.hashCode(); - if (_subject != null) - { - result = 29 * result + _subject.hashCode(); - } - } - else - { - result = _exchangeName == null ? "".hashCode() : _exchangeName.hashCode(); - result = 29 * result + (_exchangeClass == null ? "".hashCode() :_exchangeClass.hashCode()); - if (_queueName != null) - { - result = 29 * result + _queueName.hashCode(); - } - } - return result; - } - - public Map<String, Object> getConsumerArguments() - { - return _consumerArguments; - } - - public Reference getReference() throws NamingException - { - return new Reference( - this.getClass().getName(), - new StringRefAddr(this.getClass().getName(), toURL()), - AMQConnectionFactory.class.getName(), - null); // factory location - } - - public static Destination createDestination(BindingURL binding) - { - AMQShortString type = binding.getExchangeClass(); - - if (type.equals(AMQShortString.valueOf(ExchangeDefaults.DIRECT_EXCHANGE_CLASS))) - { - return new AMQQueue(binding); - } - else if (type.equals(AMQShortString.valueOf(ExchangeDefaults.TOPIC_EXCHANGE_CLASS))) - { - return new AMQTopic(binding); - } - else if (type.equals(AMQShortString.valueOf(ExchangeDefaults.HEADERS_EXCHANGE_CLASS))) - { - return new AMQHeadersExchange(binding); - } - else - { - return new AMQAnyDestination(binding); - } - } - - public static Destination createDestination(String str, final boolean useNodeTypeForDestinationType) - throws URISyntaxException - { - DestSyntax syntax = getDestType(str); - str = stripSyntaxPrefix(str); - if (syntax == DestSyntax.BURL) - { - return createDestination(new AMQBindingURL(str)); - } - else - { - Address address = createAddressFromString(str); - if(useNodeTypeForDestinationType) - { - AddressHelper helper = new AddressHelper(address); - switch(helper.getNodeType()) - { - case AMQDestination.QUEUE_TYPE: - return new AMQQueue(address); - case AMQDestination.TOPIC_TYPE: - return new AMQTopic(address); - default: - return new AMQAnyDestination(address); - } - - } - else - { - return new AMQAnyDestination(address); - } - } - } - - // ----- new address syntax ----------- - - public static class Binding - { - private String exchange; - private String bindingKey; - private String queue; - private Map<String,Object> args; - - public Binding(String exchange, - String queue, - String bindingKey, - Map<String,Object> args) - { - this.exchange = exchange; - this.queue = queue; - this.bindingKey = bindingKey; - this.args = args; - } - - public String getExchange() - { - return exchange; - } - - public String getQueue() - { - return queue; - } - - public String getBindingKey() - { - return bindingKey; - } - - public Map<String, Object> getArgs() - { - return args; - } - } - - public Address getAddress() { - return _address; - } - - protected void setAddress(Address addr) { - _address = addr; - } - - public int getAddressType() - { - return _addressType; - } - - public void setAddressType(int addressType){ - _addressType = addressType; - } - - public String getAddressName() { - return _name; - } - - public void setAddressName(String name){ - _name = name; - } - - public String getSubject() { - return _subject; - } - - public void setSubject(String subject) { - _subject = subject; - } - - public AddressOption getCreate() { - return _create; - } - - public void setCreate(AddressOption option) { - _create = option; - } - - public AddressOption getAssert() { - return _assert; - } - - public void setAssert(AddressOption option) { - _assert = option; - } - - public AddressOption getDelete() { - return _delete; - } - - public void setDelete(AddressOption option) { - _delete = option; - } - - public Node getNode() - { - return _node; - } - - public void setNode(Node node) - { - _node = node; - } - - public Link getLink() - { - return _link; - } - - public void setLink(Link link) - { - _link = link; - } - - public void setExchangeName(AMQShortString name) - { - this._exchangeName = name; - } - - public void setExchangeClass(AMQShortString type) - { - this._exchangeClass = type; - } - - public void setRoutingKey(AMQShortString rk) - { - this._routingKey = rk; - } - - public boolean isAddressResolved() - { - return _addressResolved.get() > 0; - } - - public void setAddressResolved(long addressResolved) - { - _addressResolved.set(addressResolved); - } - - private static Address createAddressFromString(String str) - { - return Address.parse(str); - } - - private void getInfoFromAddress() - { - _name = _address.getName(); - _subject = _address.getSubject(); - - _addrHelper = new AddressHelper(_address); - - _create = _addrHelper.getCreate() != null ? - AddressOption.getOption(_addrHelper.getCreate()):AddressOption.NEVER; - - _assert = _addrHelper.getAssert() != null ? - AddressOption.getOption(_addrHelper.getAssert()):AddressOption.NEVER; - - _delete = _addrHelper.getDelete() != null ? - AddressOption.getOption(_addrHelper.getDelete()):AddressOption.NEVER; - - _browseOnly = _addrHelper.isBrowseOnly(); - - _addressType = _addrHelper.getNodeType(); - _node = _addrHelper.getNode(); - _link = _addrHelper.getLink(); - } - - // ----- / new address syntax ----------- - - public boolean isBrowseOnly() - { - return _browseOnly; - } - - private void setBrowseOnly(boolean b) - { - _browseOnly = b; - } - - public AMQDestination copyDestination() - { - AMQDestination dest = - new AMQAnyDestination(_exchangeName, - _exchangeClass, - _routingKey, - _isExclusive, - _isAutoDelete, - _queueName, - _isDurable, - _bindingKeys - ); - - dest.setDestSyntax(_destSyntax); - dest.setAddress(_address); - dest.setAddressName(_name); - dest.setSubject(_subject); - dest.setCreate(_create); - dest.setAssert(_assert); - dest.setDelete(_delete); - dest.setBrowseOnly(_browseOnly); - dest.setAddressType(_addressType); - dest.setNode(_node); - dest.setLink(_link); - dest.setAddressResolved(_addressResolved.get()); - return dest; - } - - protected void setAutoDelete(boolean b) - { - _isAutoDelete = b; - } - - protected void setDurable(boolean b) - { - _isDurable = b; - } - - public boolean isResolvedAfter(long time) - { - return _addressResolved.get() > time; - } - - /** - * This option is only applicable for 0-8/0-9/0-9-1 protocols connection - * <p> - * It tells the client to delegate the requeue/DLQ decision to the - * server .If this option is not specified, the messages won't be moved to - * the DLQ (or dropped) when delivery count exceeds the maximum. - * - * @return destination reject behaviour - */ - public RejectBehaviour getRejectBehaviour() - { - return _rejectBehaviour; - } - - @Override - public void writeExternal(final ObjectOutput out) throws IOException - { - out.writeObject(_destSyntax); - if (_destSyntax == DestSyntax.BURL) - { - out.writeObject(toURL()); - } - else - { - out.writeObject(_address); - } - } - - @Override - public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException - { - _destSyntax = (DestSyntax) in.readObject(); - if (_destSyntax == DestSyntax.BURL) - { - String burl = (String) in.readObject(); - final AMQBindingURL binding; - try - { - binding = new AMQBindingURL(burl); - } - catch (URISyntaxException e) - { - throw new IllegalStateException("Cannot convert url " + burl + " into a BindingURL", e); - } - getInfoFromBindingURL(binding); - } - else - { - _address = (Address) in.readObject(); - try - { - getInfoFromAddress(); - } - catch (Exception e) - { - throw new IllegalStateException("Cannot convert get info from " + _address, e); - } - } - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQHeadersExchange.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQHeadersExchange.java deleted file mode 100644 index d4bf6440b4..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQHeadersExchange.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.client; - -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.url.BindingURL; - -/** - * A destination backed by a headers exchange - */ -public class AMQHeadersExchange extends AMQDestination -{ - private static final long serialVersionUID = 2187866678283988301L; - - public AMQHeadersExchange(BindingURL binding) - { - super(binding); - } - - public AMQHeadersExchange(String name) - { - this(new AMQShortString(name)); - } - - public AMQHeadersExchange(AMQShortString queueName) - { - super(queueName, AMQShortString.valueOf(ExchangeDefaults.HEADERS_EXCHANGE_CLASS), queueName, true, true, null); - } - - public boolean isNameRequired() - { - //Not sure what the best approach is here, probably to treat this like a topic - //and allow server to generate names. As it is AMQ specific it doesn't need to - //fit the JMS API expectations so this is not as yet critical. - return getAMQQueueName() == null; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQNoConsumersException.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQNoConsumersException.java deleted file mode 100644 index c50425c1a8..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQNoConsumersException.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.client; - -import org.apache.qpid.AMQUndeliveredException; -import org.apache.qpid.protocol.AMQConstant; - -/** - * AMQNoConsumersException indicates failure to pass an immediate message to a consumer. - */ -public class AMQNoConsumersException extends AMQUndeliveredException -{ - public AMQNoConsumersException(String msg, Object bounced, Throwable cause) - { - super(AMQConstant.NO_CONSUMERS, msg, bounced, cause); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQNoRouteException.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQNoRouteException.java deleted file mode 100644 index e5f780c203..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQNoRouteException.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.client; - -import org.apache.qpid.AMQUndeliveredException; -import org.apache.qpid.protocol.AMQConstant; - -/** - * AMQNoRouteException indicates that a mandatory message could not be routed. - */ -public class AMQNoRouteException extends AMQUndeliveredException -{ - public AMQNoRouteException(String msg, Object bounced, Throwable cause) - { - super(AMQConstant.NO_ROUTE, msg, bounced, cause); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQQueue.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQQueue.java deleted file mode 100644 index 9b00883dfb..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQQueue.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.client; - -import java.net.URISyntaxException; - -import javax.jms.Queue; - -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.messaging.Address; -import org.apache.qpid.url.BindingURL; - -public class AMQQueue extends AMQDestination implements Queue -{ - private static final long serialVersionUID = -1283142598932655606L; - - public AMQQueue() - { - super(); - } - - public AMQQueue(Address address) - { - super(address); - } - - public AMQQueue(String address) throws URISyntaxException - { - super(address); - } - - /** - * Create a reference to a non temporary queue using a BindingURL object. - * Note this does not actually imply the queue exists. - * @param binding a BindingURL object - */ - public AMQQueue(BindingURL binding) - { - super(binding); - } - - /** - * Create a reference to a non temporary queue. Note this does not actually imply the queue exists. - * @param name the name of the queue - */ - public AMQQueue(AMQShortString exchangeName, String name) - { - this(exchangeName, new AMQShortString(name)); - } - - - /** - * Create a reference to a non temporary queue. Note this does not actually imply the queue exists. - * @param name the name of the queue - */ - public AMQQueue(AMQShortString exchangeName, AMQShortString name) - { - this(exchangeName, name, false); - } - - public AMQQueue(AMQShortString exchangeName, AMQShortString routingKey, AMQShortString queueName) - { - super(exchangeName, AMQShortString.valueOf(ExchangeDefaults.DIRECT_EXCHANGE_CLASS), routingKey, false, - false, queueName, false); - } - - public AMQQueue(AMQShortString exchangeName, AMQShortString routingKey, AMQShortString queueName,AMQShortString[] bindingKeys) - { - super(exchangeName, AMQShortString.valueOf(ExchangeDefaults.DIRECT_EXCHANGE_CLASS), routingKey, false, - false, queueName, false,bindingKeys); - } - - /** - * Create a reference to a non temporary queue. Note this does not actually imply the queue exists. - * @param name the name of the queue - */ - public AMQQueue(String exchangeName, String name) - { - this(new AMQShortString(exchangeName), new AMQShortString(name), false); - } - - - public AMQQueue(AMQConnection connection, String name) - { - this(connection.getDefaultQueueExchangeName(),name); - } - - public AMQQueue(AMQConnection connection, String name, boolean temporary) - { - this(connection.getDefaultQueueExchangeName(), new AMQShortString(name),temporary); - } - - - /** - * Create a queue with a specified name. - * - * @param name the destination name (used in the routing key) - * @param temporary if true the broker will generate a queue name, also if true then the queue is autodeleted - * and exclusive - */ - public AMQQueue(String exchangeName, String name, boolean temporary) - { - this(new AMQShortString(exchangeName), new AMQShortString(name),temporary); - } - - - /** - * Create a queue with a specified name. - * - * @param name the destination name (used in the routing key) - * @param temporary if true the broker will generate a queue name, also if true then the queue is autodeleted - * and exclusive - */ - public AMQQueue(AMQShortString exchangeName, AMQShortString name, boolean temporary) - { - // queue name is set to null indicating that the broker assigns a name in the case of temporary queues - // temporary queues are typically used as response queues - this(exchangeName, name, temporary?null:name, temporary, temporary, !temporary); - - } - - /** - * Create a reference to a queue. Note this does not actually imply the queue exists. - * @param exchangeName the exchange name we want to send the message to - * @param routingKey the routing key - * @param queueName the queue name - * @param exclusive true if the queue should only permit a single consumer - * @param autoDelete true if the queue should be deleted automatically when the last consumers detaches - */ - public AMQQueue(AMQShortString exchangeName, AMQShortString routingKey, AMQShortString queueName, boolean exclusive, boolean autoDelete) - { - this(exchangeName, routingKey, queueName, exclusive, autoDelete, false); - } - - public AMQQueue(AMQShortString exchangeName, AMQShortString routingKey, AMQShortString queueName, boolean exclusive, boolean autoDelete, boolean durable) - { - this(exchangeName,routingKey,queueName,exclusive,autoDelete,durable,null); - } - - public AMQQueue(AMQShortString exchangeName, AMQShortString routingKey, AMQShortString queueName, boolean exclusive, boolean autoDelete, boolean durable,AMQShortString[] bindingKeys) - { - super(exchangeName, AMQShortString.valueOf(ExchangeDefaults.DIRECT_EXCHANGE_CLASS), routingKey, exclusive, - autoDelete, queueName, durable, bindingKeys); - } - - public AMQShortString getRoutingKey() - { - if (getAMQQueueName() != null && getAMQQueueName().equals(super.getRoutingKey())) - { - return getAMQQueueName(); - } - else - { - return super.getRoutingKey(); - } - } - - public boolean isNameRequired() - { - AMQShortString queueName = getAMQQueueName(); - return queueName == null || AMQShortString.EMPTY_STRING.equals(queueName); - } - - @Override - public boolean equals(Object o) - { - return super.equals(o) && o instanceof Queue; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQQueueBrowser.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQQueueBrowser.java deleted file mode 100644 index 0c6031ea91..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQQueueBrowser.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; - -import javax.jms.InvalidDestinationException; -import javax.jms.InvalidSelectorException; -import org.apache.qpid.AMQException; -import org.apache.qpid.AMQInternalException; -import org.apache.qpid.client.filter.JMSSelectorFilter; -import org.apache.qpid.protocol.AMQConstant; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.jms.IllegalStateException; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.Queue; -import javax.jms.QueueBrowser; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.NoSuchElementException; -import java.util.concurrent.atomic.AtomicBoolean; - -public class AMQQueueBrowser implements QueueBrowser -{ - private static final Logger _logger = LoggerFactory.getLogger(AMQQueueBrowser.class); - - private AtomicBoolean _isClosed = new AtomicBoolean(); - private final AMQSession _session; - private final Queue _queue; - private final ArrayList<BasicMessageConsumer> _consumers = new ArrayList<BasicMessageConsumer>(); - private final String _messageSelector; - - AMQQueueBrowser(AMQSession session, Queue queue, String messageSelector) throws JMSException - { - _session = session; - _queue = queue; - _messageSelector = ((messageSelector == null) || (messageSelector.trim().length() == 0)) ? null : messageSelector; - - - validateQueue((AMQDestination) queue); - - if(_messageSelector != null) - { - validateSelector(_messageSelector); - } - } - - private void validateSelector(String messageSelector) throws InvalidSelectorException - { - try - { - new JMSSelectorFilter(messageSelector); - } - catch (AMQInternalException e) - { - throw new InvalidSelectorException(e.getMessage()); - } - } - - private void validateQueue(AMQDestination queue) throws JMSException - { - try - { - // Essentially just test the connection/session is still active - _session.sync(); - // TODO - should really validate queue exists, but we often rely on creating the consumer to create the queue :( - // _session.declareQueuePassive( queue ); - } - catch (AMQException e) - { - if(e.getErrorCode() == AMQConstant.NOT_FOUND) - { - throw new InvalidDestinationException(e.getMessage()); - } - else - { - final JMSException jmsException = new JMSException(e.getMessage(), String.valueOf(e.getErrorCode().getCode())); - jmsException.setLinkedException(e); - throw jmsException; - } - } - } - - public Queue getQueue() throws JMSException - { - checkState(); - - return _queue; - } - - private void checkState() throws JMSException - { - if (_isClosed.get()) - { - throw new IllegalStateException("Queue Browser"); - } - - if (_session.isClosed()) - { - throw new IllegalStateException("Session is closed"); - } - - } - - public String getMessageSelector() throws JMSException - { - - checkState(); - - return _messageSelector; - } - - public Enumeration getEnumeration() throws JMSException - { - checkState(); - if(!_session.getAMQConnection().started()) - { - throw new IllegalStateException("Cannot enumerate message on the queue while the Connection is stopped"); - } - final BasicMessageConsumer consumer = - (BasicMessageConsumer) _session.createBrowserConsumer(_queue, _messageSelector, false); - - _consumers.add(consumer); - - return new QueueBrowserEnumeration(consumer); - } - - public void close() throws JMSException - { - for (BasicMessageConsumer consumer : _consumers) - { - consumer.close(); - } - - _consumers.clear(); - } - - private class QueueBrowserEnumeration implements Enumeration - { - private Message _nextMessage; - private BasicMessageConsumer _consumer; - - public QueueBrowserEnumeration(BasicMessageConsumer consumer) throws JMSException - { - if (consumer != null) - { - _consumer = consumer; - prefetchMessage(); - } - _logger.debug("QB:created with first element:" + _nextMessage); - } - - public boolean hasMoreElements() - { - _logger.debug("QB:hasMoreElements:" + (_nextMessage != null)); - return (_nextMessage != null); - } - - public Object nextElement() - { - Message msg = _nextMessage; - if (msg == null) - { - throw new NoSuchElementException("No messages") ; - } - try - { - _logger.debug("QB:nextElement about to receive"); - prefetchMessage(); - _logger.debug("QB:nextElement received:" + _nextMessage); - } - catch (JMSException e) - { - _logger.warn("Exception caught while queue browsing", e); - _nextMessage = null; - try - { - closeConsumer() ; - } - catch (final JMSException jmse) {} // ignore - } - return msg; - } - - private void prefetchMessage() throws JMSException - { - _nextMessage = _consumer.receiveBrowse(); - if (_nextMessage == null) - { - closeConsumer() ; - } - } - - private void closeConsumer() throws JMSException - { - if (_consumer != null) - { - BasicMessageConsumer consumer = _consumer ; - _consumer = null ; - consumer.close() ; - } - } - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQQueueSessionAdaptor.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQQueueSessionAdaptor.java deleted file mode 100644 index c8cb49b53e..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQQueueSessionAdaptor.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.client; - -import javax.jms.*; -import javax.jms.IllegalStateException; - -/** - * Need this adaptor class to conform to JMS spec and throw IllegalStateException - * from createDurableSubscriber, unsubscribe, createTopic & createTemporaryTopic - */ -class AMQQueueSessionAdaptor extends AMQSessionAdapter<QueueSession> implements QueueSession -{ - /** - * Construct an adaptor with a session to wrap - * @param session - */ - protected AMQQueueSessionAdaptor(QueueSession session) - { - super(session); - } - - public QueueReceiver createReceiver(Queue queue) throws JMSException - { - return getSession().createReceiver(queue); - } - - public QueueReceiver createReceiver(Queue queue, String string) throws JMSException - { - return getSession().createReceiver(queue, string); - } - - public QueueSender createSender(Queue queue) throws JMSException - { - return getSession().createSender(queue); - } - - //The following methods cannot be called from a QueueSession as per JMS spec - - public Topic createTopic(String string) throws JMSException - { - throw new IllegalStateException("Cannot call createTopic from QueueSession"); - } - - public TopicSubscriber createDurableSubscriber(Topic topic, String string) throws JMSException - { - throw new IllegalStateException("Cannot call createDurableSubscriber from QueueSession"); - } - - public TopicSubscriber createDurableSubscriber(Topic topic, String string, String string1, boolean b) throws JMSException - { - throw new IllegalStateException("Cannot call createDurableSubscriber from QueueSession"); - } - - public TemporaryTopic createTemporaryTopic() throws JMSException - { - throw new IllegalStateException("Cannot call createTemporaryTopic from QueueSession"); - } - - public void unsubscribe(String string) throws JMSException - { - throw new IllegalStateException("Cannot call unsubscribe from QueueSession"); - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQSession.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQSession.java deleted file mode 100644 index 0ca3505053..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQSession.java +++ /dev/null @@ -1,3678 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; - -import java.io.Serializable; -import java.net.URISyntaxException; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -import javax.jms.*; -import javax.jms.IllegalStateException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQChannelClosedException; -import org.apache.qpid.AMQDisconnectedException; -import org.apache.qpid.AMQException; -import org.apache.qpid.AMQInvalidArgumentException; -import org.apache.qpid.AMQInvalidRoutingKeyException; -import org.apache.qpid.client.AMQDestination.DestSyntax; -import org.apache.qpid.client.failover.FailoverException; -import org.apache.qpid.client.failover.FailoverNoopSupport; -import org.apache.qpid.client.failover.FailoverProtectedOperation; -import org.apache.qpid.client.failover.FailoverRetrySupport; -import org.apache.qpid.client.message.AMQMessageDelegateFactory; -import org.apache.qpid.client.message.AMQPEncodedListMessage; -import org.apache.qpid.client.message.AMQPEncodedMapMessage; -import org.apache.qpid.client.message.AbstractJMSMessage; -import org.apache.qpid.client.message.CloseConsumerMessage; -import org.apache.qpid.client.message.JMSBytesMessage; -import org.apache.qpid.client.message.JMSMapMessage; -import org.apache.qpid.client.message.JMSObjectMessage; -import org.apache.qpid.client.message.JMSStreamMessage; -import org.apache.qpid.client.message.JMSTextMessage; -import org.apache.qpid.client.message.MessageFactoryRegistry; -import org.apache.qpid.client.message.UnprocessedMessage; -import org.apache.qpid.client.messaging.address.Node; -import org.apache.qpid.client.util.FlowControllingBlockingQueue; -import org.apache.qpid.common.AMQPFilterTypes; -import org.apache.qpid.configuration.ClientProperties; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.jms.ListMessage; -import org.apache.qpid.jms.Session; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.thread.Threading; -import org.apache.qpid.transport.SessionException; -import org.apache.qpid.transport.TransportException; -import org.apache.qpid.util.Strings; - -/* - * TODO Different FailoverSupport implementation are needed on the same method call, in different situations. For - * example, when failing-over and reestablishing the bindings, the bind cannot be interrupted by a second - * fail-over, if it fails with an exception, the fail-over process should also fail. When binding outside of - * the fail-over process, the retry handler could be used to automatically retry the operation once the connection - * has been reestablished. All fail-over protected operations should be placed in private methods, with - * FailoverSupport passed in by the caller to provide the correct support for the calling context. Sometimes the - * fail-over process sets a nowait flag and uses an async method call instead. - * TODO Two new objects created on every failover supported method call. Consider more efficient ways of doing this, - * after looking at worse bottlenecks first. - */ -public abstract class AMQSession<C extends BasicMessageConsumer, P extends BasicMessageProducer> extends Closeable implements Session, QueueSession, TopicSession -{ - /** Used for debugging. */ - private static final Logger _logger = LoggerFactory.getLogger(AMQSession.class); - - /** System property to enable strict AMQP compliance. */ - public static final String STRICT_AMQP = "STRICT_AMQP"; - - /** Strict AMQP default setting. */ - public static final String STRICT_AMQP_DEFAULT = "false"; - - /** System property to enable failure if strict AMQP compliance is violated. */ - public static final String STRICT_AMQP_FATAL = "STRICT_AMQP_FATAL"; - - /** Strict AMQP failure default. */ - public static final String STRICT_AMQP_FATAL_DEFAULT = "true"; - - /** System property to enable immediate message prefetching. */ - public static final String IMMEDIATE_PREFETCH = "IMMEDIATE_PREFETCH"; - - /** Immediate message prefetch default. */ - public static final String IMMEDIATE_PREFETCH_DEFAULT = "false"; - - private final boolean _declareQueues = - Boolean.parseBoolean(System.getProperty(ClientProperties.QPID_DECLARE_QUEUES_PROP_NAME, "true")); - - private final boolean _declareExchanges = - Boolean.parseBoolean(System.getProperty(ClientProperties.QPID_DECLARE_EXCHANGES_PROP_NAME, "true")); - - private final boolean _bindQueues = - Boolean.parseBoolean(System.getProperty(ClientProperties.QPID_BIND_QUEUES_PROP_NAME, "true")); - - private final boolean _useAMQPEncodedMapMessage; - - private final boolean _useAMQPEncodedStreamMessage; - - /** - * Flag indicating to start dispatcher as a daemon thread - */ - protected final boolean DAEMON_DISPATCHER_THREAD = Boolean.getBoolean(ClientProperties.DAEMON_DISPATCHER); - - /** The connection to which this session belongs. */ - private AMQConnection _connection; - - /** Used to indicate whether or not this is a transactional session. */ - private final boolean _transacted; - - /** Holds the sessions acknowledgement mode. */ - private final int _acknowledgeMode; - - /** Holds this session unique identifier, used to distinguish it from other sessions. */ - private int _channelId; - - private int _ticket; - - /** Holds the high mark for prefetched message, at which the session is suspended. */ - private int _prefetchHighMark; - - /** Holds the low mark for prefetched messages, below which the session is resumed. */ - private int _prefetchLowMark; - - /** Holds the message listener, if any, which is attached to this session. */ - private MessageListener _messageListener = null; - - /** Used to indicate that this session has been started at least once. */ - private AtomicBoolean _startedAtLeastOnce = new AtomicBoolean(false); - - private final ConcurrentMap<String, TopicSubscriberAdaptor<C>> _subscriptions = - new ConcurrentHashMap<String, TopicSubscriberAdaptor<C>>(); - - private final ConcurrentMap<C, String> _reverseSubscriptionMap = new ConcurrentHashMap<C, String>(); - - private final Lock _subscriberDetails = new ReentrantLock(true); - private final Lock _subscriberAccess = new ReentrantLock(true); - - private final FlowControllingBlockingQueue<Dispatchable> _queue; - - private final AtomicLong _highestDeliveryTag = new AtomicLong(-1); - private final AtomicLong _rollbackMark = new AtomicLong(-1); - - private ConcurrentLinkedQueue<Long> _prefetchedMessageTags = new ConcurrentLinkedQueue<Long>(); - - private ConcurrentLinkedQueue<Long> _unacknowledgedMessageTags = new ConcurrentLinkedQueue<Long>(); - - private ConcurrentLinkedQueue<Long> _deliveredMessageTags = new ConcurrentLinkedQueue<Long>(); - - private volatile Dispatcher _dispatcher; - - private volatile Thread _dispatcherThread; - - private MessageFactoryRegistry _messageFactoryRegistry; - - /** Holds all of the producers created by this session, keyed by their unique identifiers. */ - private final Map<Long, MessageProducer> _producers = new ConcurrentHashMap<Long, MessageProducer>(); - - /** - * Used as a source of unique identifiers so that the consumers can be tagged to match them to BasicConsume - * methods. - */ - private int _nextTag = 1; - - private final Map<Integer,C> _consumers = new ConcurrentHashMap<>(); - - /** - * Contains a list of consumers which have been removed but which might still have - * messages to acknowledge, eg in client ack or transacted modes - */ - private CopyOnWriteArrayList<C> _removedConsumers = new CopyOnWriteArrayList<C>(); - - /** Provides a count of consumers on destinations, in order to be able to know if a destination has consumers. */ - private ConcurrentMap<Destination, AtomicInteger> _destinationConsumerCount = - new ConcurrentHashMap<Destination, AtomicInteger>(); - - /** - * Used as a source of unique identifiers for producers within the session. - * - * <p/> Access to this id does not require to be synchronized since according to the JMS specification only one - * thread of control is allowed to create producers for any given session instance. - */ - private long _nextProducerId; - - /** - * Set when recover is called. This is to handle the case where recover() is called by application code during - * onMessage() processing to ensure that an auto ack is not sent. - */ - private volatile boolean _sessionInRecovery; - - private volatile boolean _usingDispatcherForCleanup; - - /** Used to indicates that the connection to which this session belongs, has been stopped. */ - private final AtomicBoolean _connectionStopped = new AtomicBoolean(); - - /** Used to indicate that this session has a message listener attached to it. */ - private boolean _hasMessageListeners; - - /** Used to indicate that this session has been suspended. */ - private boolean _suspended; - - /** - * Used to protect the suspension of this session, so that critical code can be executed during suspension, - * without the session being resumed by other threads. - */ - private final Object _suspensionLock = new Object(); - - private final AtomicBoolean _firstDispatcher = new AtomicBoolean(true); - - private final boolean _immediatePrefetch; - - private final boolean _strictAMQP; - - private final boolean _strictAMQPFATAL; - private final Object _messageDeliveryLock = new Object(); - - /** Session state : used to detect if commit is a) required b) allowed , i.e. does the tx span failover. */ - private boolean _dirty; - /** Has failover occured on this session with outstanding actions to commit? */ - private boolean _failedOverDirty; - - /** Holds the highest received delivery tag. */ - protected AtomicLong getHighestDeliveryTag() - { - return _highestDeliveryTag; - } - - /** Pre-fetched message tags */ - protected ConcurrentLinkedQueue<Long> getPrefetchedMessageTags() - { - return _prefetchedMessageTags; - } - - /** All the not yet acknowledged message tags */ - protected ConcurrentLinkedQueue<Long> getUnacknowledgedMessageTags() - { - return _unacknowledgedMessageTags; - } - - /** All the delivered message tags */ - protected ConcurrentLinkedQueue<Long> getDeliveredMessageTags() - { - return _deliveredMessageTags; - } - - /** Holds the dispatcher thread for this session. */ - protected Dispatcher getDispatcher() - { - return _dispatcher; - } - - protected Thread getDispatcherThread() - { - return _dispatcherThread; - } - - /** Holds the message factory factory for this session. */ - protected MessageFactoryRegistry getMessageFactoryRegistry() - { - return _messageFactoryRegistry; - } - - /** - * Consumers associated with this session - */ - protected Collection<C> getConsumers() - { - return new ArrayList(_consumers.values()); - } - - protected void setUsingDispatcherForCleanup(boolean usingDispatcherForCleanup) - { - _usingDispatcherForCleanup = usingDispatcherForCleanup; - } - - /** Used to indicate that the session should start pre-fetching messages as soon as it is started. */ - protected boolean isImmediatePrefetch() - { - return _immediatePrefetch; - } - - abstract void handleNodeDelete(final AMQDestination dest) throws AMQException; - - abstract void handleLinkDelete(final AMQDestination dest) throws AMQException; - - /** - * Creates a new session on a connection. - * - * @param con The connection on which to create the session. - * @param channelId The unique identifier for the session. - * @param transacted Indicates whether or not the session is transactional. - * @param acknowledgeMode The acknowledgement mode for the session. - * @param messageFactoryRegistry The message factory factory for the session. - * @param defaultPrefetchHighMark The maximum number of messages to prefetched before suspending the session. - * @param defaultPrefetchLowMark The number of prefetched messages at which to resume the session. - */ - protected AMQSession(AMQConnection con, int channelId, boolean transacted, int acknowledgeMode, - MessageFactoryRegistry messageFactoryRegistry, int defaultPrefetchHighMark, int defaultPrefetchLowMark) - { - _useAMQPEncodedMapMessage = con == null ? true : !con.isUseLegacyMapMessageFormat(); - _useAMQPEncodedStreamMessage = con == null ? false : !con.isUseLegacyStreamMessageFormat(); - _strictAMQP = Boolean.parseBoolean(System.getProperties().getProperty(STRICT_AMQP, STRICT_AMQP_DEFAULT)); - _strictAMQPFATAL = - Boolean.parseBoolean(System.getProperties().getProperty(STRICT_AMQP_FATAL, STRICT_AMQP_FATAL_DEFAULT)); - _immediatePrefetch = - _strictAMQP - || Boolean.parseBoolean(System.getProperties().getProperty(IMMEDIATE_PREFETCH, IMMEDIATE_PREFETCH_DEFAULT)); - - _connection = con; - _transacted = transacted; - if (transacted) - { - _acknowledgeMode = javax.jms.Session.SESSION_TRANSACTED; - } - else - { - _acknowledgeMode = acknowledgeMode; - } - - _channelId = channelId; - _messageFactoryRegistry = messageFactoryRegistry; - _prefetchHighMark = defaultPrefetchHighMark; - _prefetchLowMark = defaultPrefetchLowMark; - - if (_acknowledgeMode == NO_ACKNOWLEDGE) - { - _queue = - new FlowControllingBlockingQueue<Dispatchable>(_prefetchHighMark, _prefetchLowMark, - new FlowControllingBlockingQueue.ThresholdListener() - { - private final AtomicBoolean _suspendState = new AtomicBoolean(); - - public void aboveThreshold(int currentValue) - { - // If the session has been closed don't waste time creating a thread to do - // flow control - if (!(AMQSession.this.isClosed() || AMQSession.this.isClosing())) - { - // Only execute change if previous state - // was False - if (!_suspendState.getAndSet(true)) - { - if (_logger.isDebugEnabled()) - { - _logger.debug( - "Above threshold(" + _prefetchHighMark - + ") so suspending channel. Current value is " + currentValue); - } - try - { - Threading.getThreadFactory().createThread(new SuspenderRunner(_suspendState)).start(); - } - catch (Exception e) - { - throw new RuntimeException("Failed to create thread", e); - } - } - } - } - - public void underThreshold(int currentValue) - { - // If the session has been closed don't waste time creating a thread to do - // flow control - if (!(AMQSession.this.isClosed() || AMQSession.this.isClosing())) - { - // Only execute change if previous state - // was true - if (_suspendState.getAndSet(false)) - { - if (_logger.isDebugEnabled()) - { - - _logger.debug( - "Below threshold(" + _prefetchLowMark - + ") so unsuspending channel. Current value is " + currentValue); - } - try - { - Threading.getThreadFactory().createThread(new SuspenderRunner(_suspendState)).start(); - } - catch (Exception e) - { - throw new RuntimeException("Failed to create thread", e); - } - } - } - } - }); - } - else - { - _queue = new FlowControllingBlockingQueue<Dispatchable>(_prefetchHighMark, null); - } - - // Add creation logging to tie in with the existing close logging - if (_logger.isDebugEnabled()) - { - _logger.debug("Created session:" + this); - } - } - - /** - * Creates a new session on a connection with the default message factory factory. - * - * @param con The connection on which to create the session. - * @param channelId The unique identifier for the session. - * @param transacted Indicates whether or not the session is transactional. - * @param acknowledgeMode The acknowledgement mode for the session. - * @param defaultPrefetchHigh The maximum number of messages to prefetched before suspending the session. - * @param defaultPrefetchLow The number of prefetched messages at which to resume the session. - */ - AMQSession(AMQConnection con, int channelId, boolean transacted, int acknowledgeMode, int defaultPrefetchHigh, - int defaultPrefetchLow) - { - this(con, channelId, transacted, acknowledgeMode, MessageFactoryRegistry.newDefaultRegistry(), defaultPrefetchHigh, - defaultPrefetchLow); - } - - // ===== JMS Session methods. - - /** - * Closes the session with no timeout. - * - * @throws JMSException If the JMS provider fails to close the session due to some internal error. - */ - public void close() throws JMSException - { - close(-1); - } - - public abstract AMQException getLastException(); - - public void checkNotClosed() throws JMSException - { - try - { - super.checkNotClosed(); - } - catch (IllegalStateException ise) - { - AMQException ex = getLastException(); - if (ex != null) - { - IllegalStateException ssnClosed = new IllegalStateException( - "Session has been closed", ex.getErrorCode().toString()); - - ssnClosed.setLinkedException(ex); - ssnClosed.initCause(ex); - throw ssnClosed; - } - else - { - throw ise; - } - } - } - - public BytesMessage createBytesMessage() throws JMSException - { - checkNotClosed(); - JMSBytesMessage msg = new JMSBytesMessage(getMessageDelegateFactory()); - msg.setAMQSession(this); - return msg; - } - - /** - * Acknowledges all unacknowledged messages on the session, for all message consumers on the session. - * - * @throws IllegalStateException If the session is closed. - * @throws JMSException if there is a problem during acknowledge process. - */ - public void acknowledge() throws IllegalStateException, JMSException - { - if (isClosed()) - { - throw new IllegalStateException("Session is already closed"); - } - else if (hasFailedOverDirty()) - { - //perform an implicit recover in this scenario - recover(); - - //notify the consumer - throw new IllegalStateException("has failed over"); - } - - try - { - acknowledgeImpl(); - markClean(); - } - catch (TransportException e) - { - throw toJMSException("Exception while acknowledging message(s):" + e.getMessage(), e); - } - } - - public void setLegacyFieldsForQueueType(AMQDestination dest) - { - // legacy support - dest.setQueueName(new AMQShortString(dest.getAddressName())); - dest.setExchangeName(new AMQShortString("")); - dest.setExchangeClass(new AMQShortString("")); - dest.setRoutingKey(dest.getAMQQueueName()); - } - - public void setLegacyFieldsForTopicType(AMQDestination dest) - { - // legacy support - dest.setExchangeName(new AMQShortString(dest.getAddressName())); - Node node = dest.getNode(); - dest.setExchangeClass(node.getExchangeType() == null? - AMQShortString.valueOf(ExchangeDefaults.TOPIC_EXCHANGE_CLASS): - new AMQShortString(node.getExchangeType())); - dest.setRoutingKey(new AMQShortString(dest.getSubject())); - } - - protected void verifySubject(AMQDestination dest) throws AMQException - { - if (dest.getSubject() == null || dest.getSubject().trim().equals("")) - { - - if ("topic".equals(dest.getExchangeClass().toString())) - { - dest.setRoutingKey(new AMQShortString("#")); - dest.setSubject(dest.getRoutingKey().toString()); - } - else - { - dest.setRoutingKey(new AMQShortString("")); - dest.setSubject(""); - } - } - } - - public abstract boolean isExchangeExist(AMQDestination dest, boolean assertNode) throws AMQException; - - public abstract boolean isQueueExist(AMQDestination dest, boolean assertNode) throws AMQException; - - /** - * 1. Try to resolve the address type (queue or exchange) - * 2. if type == queue, - * 2.1 verify queue exists or create if create == true - * 2.2 If not throw exception - * - * 3. if type == exchange, - * 3.1 verify exchange exists or create if create == true - * 3.2 if not throw exception - * 3.3 if exchange exists (or created) create subscription queue. - */ - - @SuppressWarnings("deprecation") - public void resolveAddress(AMQDestination dest, - boolean isConsumer, - boolean noLocal) throws AMQException - { - if (dest.isAddressResolved() && dest.isResolvedAfter(getAMQConnection().getLastFailoverTime())) - { - return; - } - else - { - boolean assertNode = (dest.getAssert() == AMQDestination.AddressOption.ALWAYS) || - (isConsumer && dest.getAssert() == AMQDestination.AddressOption.RECEIVER) || - (!isConsumer && dest.getAssert() == AMQDestination.AddressOption.SENDER); - - boolean createNode = (dest.getCreate() == AMQDestination.AddressOption.ALWAYS) || - (isConsumer && dest.getCreate() == AMQDestination.AddressOption.RECEIVER) || - (!isConsumer && dest.getCreate() == AMQDestination.AddressOption.SENDER); - - - - int type = resolveAddressType(dest); - boolean resolved = false; - switch (type) - { - case AMQDestination.QUEUE_TYPE: - - setLegacyFieldsForQueueType(dest); - if(createNode) - { - handleQueueNodeCreation(dest,noLocal); - resolved = true; - } - else if (isQueueExist(dest,assertNode)) - { - resolved = true; - } - break; - - case AMQDestination.TOPIC_TYPE: - - setLegacyFieldsForTopicType(dest); - if(createNode) - { - verifySubject(dest); - handleExchangeNodeCreation(dest); - resolved = true; - } - else if (isExchangeExist(dest,assertNode)) - { - verifySubject(dest); - resolved = true; - } - break; - - default: - throw new AMQException( - "The name '" + dest.getAddressName() + - "' supplied in the address doesn't resolve to an exchange or a queue"); - } - if(resolved) - { - dest.setAddressResolved(System.currentTimeMillis()); - } - } - } - - public abstract int resolveAddressType(AMQDestination dest) throws AMQException; - - protected abstract void acknowledgeImpl() throws JMSException; - - /** - * Acknowledge one or many messages. - * - * @param deliveryTag The tag of the last message to be acknowledged. - * @param multiple <tt>true</tt> to acknowledge all messages up to and including the one specified by the - * delivery tag, <tt>false</tt> to just acknowledge that message. - * - * TODO Be aware of possible changes to parameter order as versions change. - */ - public abstract void acknowledgeMessage(long deliveryTag, boolean multiple); - - /** - * Binds the named queue, with the specified routing key, to the named exchange. - * <p> - * Note that this operation automatically retries in the event of fail-over. - * - * @param queueName The name of the queue to bind. - * @param routingKey The routing key to bind the queue with. - * @param arguments Additional arguments. - * @param exchangeName The exchange to bind the queue on. - * - * @throws AMQException If the queue cannot be bound for any reason. - * TODO Be aware of possible changes to parameter order as versions change. - * TODO Document the additional arguments that may be passed in the field table. Are these for headers exchanges? - */ - public void bindQueue(final AMQShortString queueName, final AMQShortString routingKey, final FieldTable arguments, - final AMQShortString exchangeName, final AMQDestination destination) throws AMQException - { - bindQueue(queueName, routingKey, arguments, exchangeName, destination, false); - } - - public void bindQueue(final AMQShortString queueName, final AMQShortString routingKey, final FieldTable arguments, - final AMQShortString exchangeName, final AMQDestination destination, - final boolean nowait) throws AMQException - { - /*new FailoverRetrySupport<Object, AMQException>(new FailoverProtectedOperation<Object, AMQException>()*/ - new FailoverNoopSupport<Object, AMQException>(new FailoverProtectedOperation<Object, AMQException>() - { - public Object execute() throws AMQException, FailoverException - { - sendQueueBind(queueName, routingKey, arguments, exchangeName, destination, nowait); - return null; - } - }, _connection).execute(); - } - - public void addBindingKey(C consumer, AMQDestination amqd, String routingKey) throws AMQException - { - if (consumer.getQueuename() != null) - { - bindQueue(consumer.getQueuename(), new AMQShortString(routingKey), new FieldTable(), amqd.getExchangeName(), amqd); - } - } - - public abstract void sendQueueBind(final AMQShortString queueName, final AMQShortString routingKey, final FieldTable arguments, - final AMQShortString exchangeName, AMQDestination destination, - final boolean nowait) throws AMQException, FailoverException; - - /** - * Closes the session. - * <p> - * Note that this operation succeeds automatically if a fail-over interrupts the synchronous request to close - * the channel. This is because the channel is marked as closed before the request to close it is made, so the - * fail-over should not re-open it. - * - * @param timeout The timeout in milliseconds to wait for the session close acknowledgement from the broker. - * - * @throws JMSException If the JMS provider fails to close the session due to some internal error. - * TODO Be aware of possible changes to parameter order as versions change. - * TODO Not certain about the logic of ignoring the failover exception, because the channel won't be - * re-opened. May need to examine this more carefully. - * TODO Note that taking the failover mutex doesn't prevent this operation being interrupted by a failover, - * because the failover process sends the failover event before acquiring the mutex itself. - */ - public void close(long timeout) throws JMSException - { - synchronized (_messageDeliveryLock) - { - // We must close down all producers and consumers in an orderly fashion. This is the only method - // that can be called from a different thread of control from the one controlling the session. - synchronized (getFailoverMutex()) - { - - close(timeout, true); - } - } - } - - private void close(long timeout, boolean sendClose) throws JMSException - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Closing session: " + this); - } - - // Ensure we only try and close an open session. - if (!setClosed()) - { - setClosing(true); - // we pass null since this is not an error case - closeProducersAndConsumers(null); - - try - { - // If the connection is open or we are in the process - // of closing the connection then send a cance - // no point otherwise as the connection will be gone - if (!_connection.isClosed() || _connection.isClosing()) - { - if (sendClose) - { - sendClose(timeout); - } - } - } - catch (AMQException e) - { - JMSException jmse = new JMSException("Error closing session: " + e); - jmse.setLinkedException(e); - jmse.initCause(e); - throw jmse; - } - // This is ignored because the channel is already marked as closed so the fail-over process will - // not re-open it. - catch (FailoverException e) - { - _logger.debug( - "Got FailoverException during channel close, ignored as channel already marked as closed."); - } - catch (TransportException e) - { - throw toJMSException("Error closing session:" + e.getMessage(), e); - } - finally - { - _connection.deregisterSession(_channelId); - } - } - } - - public abstract void sendClose(long timeout) throws AMQException, FailoverException; - - /** - * Called when the server initiates the closure of the session unilaterally. - * - * @param e the exception that caused this session to be closed. Null causes the - */ - public void closed(Throwable e) throws JMSException - { - // This method needs to be improved. Throwables only arrive here from the mina : exceptionRecived - // calls through connection.closeAllSessions which is also called by the public connection.close() - // with a null cause - // When we are closing the Session due to a protocol session error we simply create a new AMQException - // with the correct error code and text this is cleary WRONG as the instanceof check below will fail. - // We need to determin here if the connection should be - - if (e instanceof AMQDisconnectedException) - { - // Failover failed and ain't coming back. Knife the dispatcher. - stopDispatcherThread(); - - } - - //if we don't have an exception then we can perform closing operations - setClosing(e == null); - - if (!setClosed()) - { - // An AMQException has an error code and message already and will be passed in when closure occurs as a - // result of a channel close request - AMQException amqe; - if (e instanceof AMQException) - { - amqe = (AMQException) e; - } - else - { - amqe = new AMQException("Closing session forcibly", e); - } - - _connection.deregisterSession(_channelId); - closeProducersAndConsumers(amqe); - } - - } - - protected void stopDispatcherThread() - { - if (_dispatcherThread != null) - { - _dispatcherThread.interrupt(); - } - } - /** - * Commits all messages done in this transaction and releases any locks currently held. - * <p> - * If the commit fails, because the commit itself is interrupted by a fail-over between requesting that the - * commit be done, and receiving an acknowledgement that it has been done, then a JMSException will be thrown. - * The client will be unable to determine whether or not the commit actually happened on the broker in this case. - * - * @throws JMSException If the JMS provider fails to commit the transaction due to some internal error. This does - * not mean that the commit is known to have failed, merely that it is not known whether it - * failed or not. - */ - public void commit() throws JMSException - { - checkTransacted(); - - //Check that we are clean to commit. - if (_failedOverDirty) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Session " + _channelId + " was dirty whilst failing over. Rolling back."); - } - rollback(); - - throw new TransactionRolledBackException("Connection failover has occured with uncommitted transaction activity." + - "The session transaction was rolled back."); - } - - try - { - commitImpl(); - markClean(); - } - catch (AMQException e) - { - throw toJMSException("Exception during commit: " + e.getMessage() + ":" + e.getCause(), e); - } - catch (FailoverException e) - { - throw new JMSAMQException("Fail-over interrupted commit. Status of the commit is uncertain.", e); - } - catch(TransportException e) - { - throw toJMSException("Session exception occurred while trying to commit: " + e.getMessage(), e); - } - } - - protected abstract void commitImpl() throws AMQException, FailoverException, TransportException; - - - - - public void confirmConsumerCancelled(int consumerTag) - { - C consumer = _consumers.get(consumerTag); - if (consumer != null) - { - if (!consumer.isBrowseOnly()) // Normal Consumer - { - // Clean the Maps up first - // Flush any pending messages for this consumerTag - if (_dispatcher != null) - { - _logger.debug("Dispatcher is not null"); - } - else - { - _logger.debug("Dispatcher is null so created stopped dispatcher"); - startDispatcherIfNecessary(true); - } - - rejectPending(consumer); - } - else // Queue Browser - { - // Just close the consumer - // fixme the CancelOK is being processed before the arriving messages.. - // The dispatcher is still to process them so the server sent in order but the client - // has yet to receive before the close comes in - - if (consumer.isAutoClose()) - { - // There is a small window where the message is between the two queues in the dispatcher. - if (consumer.isClosed()) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Closing consumer:" + consumer.debugIdentity()); - } - - deregisterConsumer(consumer); - } - else - { - _queue.add(new CloseConsumerMessage(consumer)); - } - } - } - } - } - - private void rejectPending(C consumer) - { - // Reject messages on pre-receive queue - consumer.rollbackPendingMessages(); - - // Reject messages on pre-dispatch queue - rejectMessagesForConsumerTag(consumer.getConsumerTag()); - - // closeConsumer - consumer.markClosed(); - } - - public QueueBrowser createBrowser(Queue queue) throws JMSException - { - if (isStrictAMQP()) - { - throw new UnsupportedOperationException(); - } - - return createBrowser(queue, null); - } - - /** - * Create a queue browser if the destination is a valid queue. - */ - public QueueBrowser createBrowser(Queue queue, String messageSelector) throws JMSException - { - if (isStrictAMQP()) - { - throw new UnsupportedOperationException(); - } - - checkNotClosed(); - checkValidQueue(queue); - - return new AMQQueueBrowser(this, queue, messageSelector); - } - - protected MessageConsumer createBrowserConsumer(Destination destination, String messageSelector, boolean noLocal) - throws JMSException - { - checkValidDestination(destination); - - return createConsumerImpl(destination, _prefetchHighMark, _prefetchLowMark, noLocal, false, - messageSelector, null, true, true); - } - - public MessageConsumer createConsumer(Destination destination) throws JMSException - { - checkValidDestination(destination); - - return createConsumerImpl(destination, _prefetchHighMark, _prefetchLowMark, false, (destination instanceof Topic), null, null, - isBrowseOnlyDestination(destination), false); - } - - public MessageConsumer createConsumer(Destination destination, String messageSelector) throws JMSException - { - checkValidDestination(destination); - - return createConsumerImpl(destination, _prefetchHighMark, _prefetchLowMark, false, (destination instanceof Topic), - messageSelector, null, isBrowseOnlyDestination(destination), false); - } - - public MessageConsumer createConsumer(Destination destination, String messageSelector, boolean noLocal) - throws JMSException - { - checkValidDestination(destination); - - return createConsumerImpl(destination, _prefetchHighMark, _prefetchLowMark, noLocal, (destination instanceof Topic), - messageSelector, null, isBrowseOnlyDestination(destination), false); - } - - public MessageConsumer createConsumer(Destination destination, int prefetch, boolean noLocal, boolean exclusive, - String selector) throws JMSException - { - checkValidDestination(destination); - - return createConsumerImpl(destination, prefetch, prefetch / 2, noLocal, exclusive, selector, null, isBrowseOnlyDestination(destination), false); - } - - public MessageConsumer createConsumer(Destination destination, int prefetchHigh, int prefetchLow, boolean noLocal, - boolean exclusive, String selector) throws JMSException - { - checkValidDestination(destination); - - return createConsumerImpl(destination, prefetchHigh, prefetchLow, noLocal, exclusive, selector, null, isBrowseOnlyDestination(destination), false); - } - - public MessageConsumer createConsumer(Destination destination, int prefetchHigh, int prefetchLow, boolean noLocal, - boolean exclusive, String selector, FieldTable rawSelector) throws JMSException - { - checkValidDestination(destination); - - return createConsumerImpl(destination, prefetchHigh, prefetchLow, noLocal, exclusive, selector, rawSelector, isBrowseOnlyDestination(destination), - false); - } - - public TopicSubscriber createDurableSubscriber(Topic topic, String name) throws JMSException - { - // Delegate the work to the {@link #createDurableSubscriber(Topic, String, String, boolean)} method - return createDurableSubscriber(topic, name, null, false); - } - - public TopicSubscriber createDurableSubscriber(Topic topic, String name, String selector, boolean noLocal) - throws JMSException - { - checkNotClosed(); - Topic origTopic = checkValidTopic(topic, true); - - AMQTopic dest = AMQTopic.createDurableTopic(origTopic, name, _connection); - if (dest.getDestSyntax() == DestSyntax.ADDR && - !dest.isAddressResolved()) - { - try - { - resolveAddress(dest,false,noLocal); - if (dest.getAddressType() != AMQDestination.TOPIC_TYPE) - { - throw new JMSException("Durable subscribers can only be created for Topics"); - } - } - catch(AMQException e) - { - throw toJMSException("Error when verifying destination",e); - } - catch(TransportException e) - { - throw toJMSException("Error when verifying destination", e); - } - } - - String messageSelector = ((selector == null) || (selector.trim().length() == 0)) ? null : selector; - - _subscriberDetails.lock(); - try - { - TopicSubscriberAdaptor<C> subscriber = _subscriptions.get(name); - - // Not subscribed to this name in the current session - if (subscriber == null) - { - // After the address is resolved routing key will not be null. - AMQShortString topicName = dest.getRoutingKey(); - - if (_strictAMQP) - { - if (_strictAMQPFATAL) - { - throw new UnsupportedOperationException("JMS Durable not currently supported by AMQP."); - } - else - { - _logger.warn("Unable to determine if subscription already exists for '" + topicName - + "' for creation durableSubscriber. Requesting queue deletion regardless."); - } - - deleteQueue(dest.getAMQQueueName()); - } - else - { - Map<String,Object> args = new HashMap<String,Object>(); - - // We must always send the selector argument even if empty, so that we can tell when a selector is removed from a - // durable topic subscription that the broker arguments don't match any more. This is because it is not otherwise - // possible to determine when querying the broker whether there are no arguments or just a non-matching selector - // argument, as specifying null for the arguments when querying means they should not be checked at all - args.put(AMQPFilterTypes.JMS_SELECTOR.getValue().toString(), messageSelector == null ? "" : messageSelector); - if(noLocal) - { - args.put(AMQPFilterTypes.NO_LOCAL.getValue().toString(), true); - } - - // if the queue is bound to the exchange but NOT for this topic and selector, then the JMS spec - // says we must trash the subscription. - boolean isQueueBound = isQueueBound(dest.getExchangeName(), dest.getAMQQueueName()); - boolean isQueueBoundForTopicAndSelector = - isQueueBound(dest.getExchangeName().asString(), dest.getAMQQueueName().asString(), topicName.asString(), args); - - if (isQueueBound && !isQueueBoundForTopicAndSelector) - { - deleteQueue(dest.getAMQQueueName()); - } - else if(isQueueBound) // todo - this is a hack for 0-8/9/9-1 which cannot check if arguments on a binding match - { - try - { - bindQueue(dest.getAMQQueueName(), dest.getRoutingKey(), - FieldTable.convertToFieldTable(args), dest.getExchangeName(), dest, true); - } - catch(AMQException e) - { - throw toJMSException("Error when checking binding",e); - } - } - } - } - else - { - // Subscribed with the same topic and no current / previous or same selector - if (subscriber.getTopic().equals(topic) - && ((messageSelector == null && subscriber.getMessageSelector() == null) - || (messageSelector != null && messageSelector.equals(subscriber.getMessageSelector())))) - { - throw new IllegalStateException("Already subscribed to topic " + topic + " with subscription name " + name - + (messageSelector != null ? " and selector " + messageSelector : "")); - } - else - { - unsubscribe(name, true); - } - - } - - _subscriberAccess.lock(); - try - { - C consumer = (C) createConsumer(dest, messageSelector, noLocal); - consumer.markAsDurableSubscriber(); - subscriber = new TopicSubscriberAdaptor<C>(dest, consumer); - - // Save subscription information - _subscriptions.put(name, subscriber); - _reverseSubscriptionMap.put(subscriber.getMessageConsumer(), name); - } - finally - { - _subscriberAccess.unlock(); - } - - return subscriber; - } - catch (TransportException e) - { - throw toJMSException("Exception while creating durable subscriber:" + e.getMessage(), e); - } - finally - { - _subscriberDetails.unlock(); - } - } - - public ListMessage createListMessage() throws JMSException - { - checkNotClosed(); - AMQPEncodedListMessage msg = new AMQPEncodedListMessage(getMessageDelegateFactory()); - msg.setAMQSession(this); - return msg; - } - - public MapMessage createMapMessage() throws JMSException - { - checkNotClosed(); - if (_useAMQPEncodedMapMessage) - { - AMQPEncodedMapMessage msg = new AMQPEncodedMapMessage(getMessageDelegateFactory()); - msg.setAMQSession(this); - return msg; - } - else - { - JMSMapMessage msg = new JMSMapMessage(getMessageDelegateFactory()); - msg.setAMQSession(this); - return msg; - } - } - - public javax.jms.Message createMessage() throws JMSException - { - return createBytesMessage(); - } - - public ObjectMessage createObjectMessage() throws JMSException - { - checkNotClosed(); - JMSObjectMessage msg = new JMSObjectMessage(getMessageDelegateFactory()); - msg.setAMQSession(this); - return msg; - } - - public ObjectMessage createObjectMessage(Serializable object) throws JMSException - { - ObjectMessage msg = createObjectMessage(); - msg.setObject(object); - - return msg; - } - - public P createProducer(Destination destination) throws JMSException - { - return createProducerImpl(destination, null, null); - } - - public P createProducer(Destination destination, boolean immediate) throws JMSException - { - return createProducerImpl(destination, null, immediate); - } - - public P createProducer(Destination destination, boolean mandatory, boolean immediate) - throws JMSException - { - return createProducerImpl(destination, mandatory, immediate); - } - - public TopicPublisher createPublisher(Topic topic) throws JMSException - { - checkNotClosed(); - - return new TopicPublisherAdapter((P) createProducer(topic, false, false), topic); - } - - public Queue createQueue(String queueName) throws JMSException - { - checkNotClosed(); - try - { - if (queueName.indexOf('/') == -1 && queueName.indexOf(';') == -1) - { - DestSyntax syntax = AMQDestination.getDestType(queueName); - if (syntax == AMQDestination.DestSyntax.BURL) - { - // For testing we may want to use the prefix - return new AMQQueue(getDefaultQueueExchangeName(), - new AMQShortString(AMQDestination.stripSyntaxPrefix(queueName))); - } - else - { - AMQQueue queue = new AMQQueue(queueName); - return queue; - - } - } - else - { - return new AMQQueue(queueName); - } - } - catch (URISyntaxException urlse) - { - _logger.error("", urlse); - JMSException jmse = new JMSException(urlse.getReason()); - jmse.setLinkedException(urlse); - jmse.initCause(urlse); - throw jmse; - } - - } - - /** - * Declares the named queue. - * <p> - * Note that this operation automatically retries in the event of fail-over. - * - * @param name The name of the queue to declare. - * @param autoDelete - * @param durable Flag to indicate that the queue is durable. - * @param exclusive Flag to indicate that the queue is exclusive to this client. - * - * @throws AMQException If the queue cannot be declared for any reason. - * TODO Be aware of possible changes to parameter order as versions change. - */ - public void createQueue(final AMQShortString name, final boolean autoDelete, final boolean durable, - final boolean exclusive) throws AMQException - { - createQueue(name, autoDelete, durable, exclusive, null); - } - - /** - * Declares the named queue. - * <p> - * Note that this operation automatically retries in the event of fail-over. - * - * @param name The name of the queue to declare. - * @param autoDelete - * @param durable Flag to indicate that the queue is durable. - * @param exclusive Flag to indicate that the queue is exclusive to this client. - * @param arguments Arguments used to set special properties of the queue - * - * @throws AMQException If the queue cannot be declared for any reason. - * TODO Be aware of possible changes to parameter order as versions change. - */ - public void createQueue(final AMQShortString name, final boolean autoDelete, final boolean durable, - final boolean exclusive, final Map<String, Object> arguments) throws AMQException - { - new FailoverRetrySupport<Object, AMQException>(new FailoverProtectedOperation<Object, AMQException>() - { - public Object execute() throws AMQException, FailoverException - { - sendCreateQueue(name, autoDelete, durable, exclusive, arguments); - return null; - } - }, _connection).execute(); - } - - public abstract void sendCreateQueue(AMQShortString name, final boolean autoDelete, final boolean durable, - final boolean exclusive, final Map<String, Object> arguments) throws AMQException, FailoverException; - - /** - * Creates a QueueReceiver - * - * @param destination - * - * @return QueueReceiver - a wrapper around our MessageConsumer - * - * @throws JMSException - */ - public QueueReceiver createQueueReceiver(Destination destination) throws JMSException - { - checkValidDestination(destination); - Queue dest = validateQueue(destination); - C consumer = (C) createConsumer(dest); - consumer.setAddressType(AMQDestination.QUEUE_TYPE); - return new QueueReceiverAdaptor(dest, consumer); - } - - /** - * Creates a QueueReceiver using a message selector - * - * @param destination - * @param messageSelector - * - * @return QueueReceiver - a wrapper around our MessageConsumer - * - * @throws JMSException - */ - public QueueReceiver createQueueReceiver(Destination destination, String messageSelector) throws JMSException - { - checkValidDestination(destination); - Queue dest = validateQueue(destination); - C consumer = (C) createConsumer(dest, messageSelector); - consumer.setAddressType(AMQDestination.QUEUE_TYPE); - return new QueueReceiverAdaptor(dest, consumer); - } - - /** - * Creates a QueueReceiver wrapping a MessageConsumer - * - * @param queue - * - * @return QueueReceiver - * - * @throws JMSException - */ - public QueueReceiver createReceiver(Queue queue) throws JMSException - { - checkNotClosed(); - Queue dest = validateQueue(queue); - C consumer = (C) createConsumer(dest); - consumer.setAddressType(AMQDestination.QUEUE_TYPE); - return new QueueReceiverAdaptor(dest, consumer); - } - - /** - * Creates a QueueReceiver wrapping a MessageConsumer using a message selector - * - * @param queue - * @param messageSelector - * - * @return QueueReceiver - * - * @throws JMSException - */ - public QueueReceiver createReceiver(Queue queue, String messageSelector) throws JMSException - { - checkNotClosed(); - Queue dest = validateQueue(queue); - C consumer = (C) createConsumer(dest, messageSelector); - consumer.setAddressType(AMQDestination.QUEUE_TYPE); - return new QueueReceiverAdaptor(dest, consumer); - } - - private Queue validateQueue(Destination dest) throws InvalidDestinationException - { - if (dest instanceof AMQDestination && dest instanceof javax.jms.Queue) - { - return (Queue)dest; - } - else - { - throw new InvalidDestinationException("The destination object used is not from this provider or of type javax.jms.Queue"); - } - } - - public QueueSender createSender(Queue queue) throws JMSException - { - checkNotClosed(); - - return new QueueSenderAdapter(createProducer(queue), queue); - } - - public StreamMessage createStreamMessage() throws JMSException - { - checkNotClosed(); - if (_useAMQPEncodedStreamMessage) - { - AMQPEncodedListMessage msg = new AMQPEncodedListMessage(getMessageDelegateFactory()); - msg.setAMQSession(this); - return msg; - } - else - { - JMSStreamMessage msg = new JMSStreamMessage(getMessageDelegateFactory()); - msg.setAMQSession(this); - return msg; - } - } - - /** - * Creates a non-durable subscriber - * - * @param topic - * - * @return TopicSubscriber - a wrapper round our MessageConsumer - * - * @throws JMSException - */ - public TopicSubscriber createSubscriber(Topic topic) throws JMSException - { - checkNotClosed(); - checkValidTopic(topic); - - return new TopicSubscriberAdaptor<C>(topic, - createConsumerImpl(topic, _prefetchHighMark, _prefetchLowMark, false, true, null, null, false, false)); - } - - /** - * Creates a non-durable subscriber with a message selector - * - * @param topic - * @param messageSelector - * @param noLocal - * - * @return TopicSubscriber - a wrapper round our MessageConsumer - * - * @throws JMSException - */ - public TopicSubscriber createSubscriber(Topic topic, String messageSelector, boolean noLocal) throws JMSException - { - checkNotClosed(); - checkValidTopic(topic); - - return new TopicSubscriberAdaptor<C>(topic, - createConsumerImpl(topic, _prefetchHighMark, _prefetchLowMark, noLocal, - true, messageSelector, null, false, false)); - } - - public TemporaryQueue createTemporaryQueue() throws JMSException - { - checkNotClosed(); - try - { - AMQTemporaryQueue result = new AMQTemporaryQueue(this); - - // this is done so that we can produce to a temporary queue before we create a consumer - result.setQueueName(result.getRoutingKey()); - createQueue(result.getAMQQueueName(), result.isAutoDelete(), - result.isDurable(), result.isExclusive()); - bindQueue(result.getAMQQueueName(), result.getRoutingKey(), - new FieldTable(), result.getExchangeName(), result); - return result; - } - catch (AMQException e) - { - throw toJMSException("Cannot create temporary queue",e); - } - catch(TransportException e) - { - throw toJMSException("Cannot create temporary queue: " + e.getMessage(), e); - } - catch(Exception e) - { - throw new JMSAMQException("Cannot create temporary queue: " + e.getMessage(), e); - } - } - - public TemporaryTopic createTemporaryTopic() throws JMSException - { - checkNotClosed(); - - return new AMQTemporaryTopic(this); - } - - public TextMessage createTextMessage() throws JMSException - { - checkNotClosed(); - - JMSTextMessage msg = new JMSTextMessage(getMessageDelegateFactory()); - msg.setAMQSession(this); - return msg; - } - - protected Object getFailoverMutex() - { - return _connection.getFailoverMutex(); - } - - public TextMessage createTextMessage(String text) throws JMSException - { - - TextMessage msg = createTextMessage(); - msg.setText(text); - - return msg; - } - - public Topic createTopic(String topicName) throws JMSException - { - checkNotClosed(); - try - { - if (topicName.indexOf('/') == -1 && topicName.indexOf(';') == -1) - { - DestSyntax syntax = AMQDestination.getDestType(topicName); - // for testing we may want to use the prefix to indicate our choice. - topicName = AMQDestination.stripSyntaxPrefix(topicName); - if (syntax == AMQDestination.DestSyntax.BURL) - { - return new AMQTopic(getDefaultTopicExchangeName(), new AMQShortString(topicName)); - } - else - { - return new AMQTopic("ADDR:" + getDefaultTopicExchangeName() + "/" + topicName); - } - } - else - { - return new AMQTopic(topicName); - } - - } - catch (URISyntaxException urlse) - { - _logger.error("", urlse); - JMSException jmse = new JMSException(urlse.getReason()); - jmse.setLinkedException(urlse); - jmse.initCause(urlse); - throw jmse; - } - } - - public void declareExchange(AMQShortString name, AMQShortString type, boolean nowait) throws AMQException - { - declareExchange(name, type, nowait, false, false, false); - } - - abstract public void sync() throws AMQException; - - public int getAcknowledgeMode() - { - return _acknowledgeMode; - } - - public AMQConnection getAMQConnection() - { - return _connection; - } - - public int getChannelId() - { - return _channelId; - } - - public int getDefaultPrefetch() - { - return _prefetchHighMark; - } - - public int getDefaultPrefetchHigh() - { - return _prefetchHighMark; - } - - public int getDefaultPrefetchLow() - { - return _prefetchLowMark; - } - - public int getPrefetch() - { - return _prefetchHighMark; - } - - public AMQShortString getDefaultQueueExchangeName() - { - return _connection.getDefaultQueueExchangeName(); - } - - public AMQShortString getDefaultTopicExchangeName() - { - return _connection.getDefaultTopicExchangeName(); - } - - public MessageListener getMessageListener() throws JMSException - { - return _messageListener; - } - - public AMQShortString getTemporaryQueueExchangeName() - { - return _connection.getTemporaryQueueExchangeName(); - } - - public AMQShortString getTemporaryTopicExchangeName() - { - return _connection.getTemporaryTopicExchangeName(); - } - - public int getTicket() - { - return _ticket; - } - - /** - * Indicates whether the session is in transacted mode. - * - * @return true if the session is in transacted mode - * @throws IllegalStateException - if session is closed. - */ - public boolean getTransacted() throws JMSException - { - // Sun TCK checks that javax.jms.IllegalStateException is thrown for closed session - // nowhere else this behavior is documented - checkNotClosed(); - return _transacted; - } - - /** - * Indicates whether the session is in transacted mode. - */ - public boolean isTransacted() - { - return _transacted; - } - - public boolean hasConsumer(Destination destination) - { - AtomicInteger counter = _destinationConsumerCount.get(destination); - - return (counter != null) && (counter.get() != 0); - } - - /** Indicates that warnings should be generated on violations of the strict AMQP. */ - public boolean isStrictAMQP() - { - return _strictAMQP; - } - - public boolean isSuspended() - { - return _suspended; - } - - protected void addUnacknowledgedMessage(long id) - { - _unacknowledgedMessageTags.add(id); - } - - protected void addDeliveredMessage(long id) - { - _deliveredMessageTags.add(id); - } - - /** - * Invoked by the MINA IO thread (indirectly) when a message is received from the transport. Puts the message onto - * the queue read by the dispatcher. - * - * @param message the message that has been received - */ - public void messageReceived(UnprocessedMessage message) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Message[" + message.toString() + "] received in session"); - } - _highestDeliveryTag.set(message.getDeliveryTag()); - _queue.add(message); - } - - public void declareAndBind(AMQDestination amqd) - throws - AMQException - { - declareAndBind(amqd, new FieldTable()); - } - - - public void declareAndBind(AMQDestination amqd, FieldTable arguments) - throws - AMQException - { - declareExchange(amqd, false); - AMQShortString queueName = declareQueue(amqd, false); - bindQueue(queueName, amqd.getRoutingKey(), arguments, amqd.getExchangeName(), amqd); - } - - /** - * Stops message delivery in this session, and restarts message delivery with the oldest unacknowledged message. - * <p> - * All consumers deliver messages in a serial order. Acknowledging a received message automatically acknowledges - * all messages that have been delivered to the client. - * <p> - * Restarting a session causes it to take the following actions: - * - * <ul> - * <li>Stop message delivery.</li> - * <li>Mark all messages that might have been delivered but not acknowledged as "redelivered". - * <li>Restart the delivery sequence including all unacknowledged messages that had been previously delivered. - * Redelivered messages do not have to be delivered in exactly their original delivery order.</li> - * </ul> - * - * <p> - * If the recover operation is interrupted by a fail-over, between asking that the broker begin recovery and - * receiving acknowledgment that it has then a JMSException will be thrown. In this case it will not be possible - * for the client to determine whether the broker is going to recover the session or not. - * - * @throws JMSException If the JMS provider fails to stop and restart message delivery due to some internal error. - * Not that this does not necessarily mean that the recovery has failed, but simply that it is - * not possible to tell if it has or not. - * TODO Be aware of possible changes to parameter order as versions change. - * - * Strategy for handling recover. - * Flush any acks not yet sent. - * Stop the message flow. - * Clear the dispatch queue and the consumer queues. - * Release/Reject all messages received but not yet acknowledged. - * Start the message flow. - */ - public void recover() throws JMSException - { - // Ensure that the session is open. - checkNotClosed(); - - // Ensure that the session is not transacted. - checkNotTransacted(); - - - try - { - // flush any acks we are holding in the buffer. - flushAcknowledgments(); - - // this is only set true here, and only set false when the consumers preDeliver method is called - _sessionInRecovery = true; - - boolean isSuspended = isSuspended(); - - if (!isSuspended) - { - suspendChannel(true); - } - - // Set to true to short circuit delivery of anything currently - //in the pre-dispatch queue. - _usingDispatcherForCleanup = true; - - syncDispatchQueue(false); - - // Set to false before sending the recover as 0-8/9/9-1 will - //send messages back before the recover completes, and we - //probably shouldn't clean those! ;-) - _usingDispatcherForCleanup = false; - - if (_dispatcher != null) - { - _dispatcher.recover(); - } - - sendRecover(); - - markClean(); - - if (!isSuspended) - { - suspendChannel(false); - } - } - catch (AMQException e) - { - throw toJMSException("Recover failed: " + e.getMessage(), e); - } - catch (FailoverException e) - { - throw new JMSAMQException("Recovery was interrupted by fail-over. Recovery status is not known.", e); - } - catch(TransportException e) - { - throw toJMSException("Recover failed: " + e.getMessage(), e); - } - } - - protected abstract void sendRecover() throws AMQException, FailoverException; - - protected abstract void flushAcknowledgments(); - - public void rejectMessage(UnprocessedMessage message, boolean requeue) - { - - if (_logger.isDebugEnabled()) - { - _logger.debug("Rejecting Unacked message:" + message.getDeliveryTag()); - } - - rejectMessage(message.getDeliveryTag(), requeue); - } - - public void rejectMessage(AbstractJMSMessage message, boolean requeue) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Rejecting Abstract message:" + message.getDeliveryTag()); - } - - rejectMessage(message.getDeliveryTag(), requeue); - - } - - public abstract void rejectMessage(long deliveryTag, boolean requeue); - - /** - * Commits all messages done in this transaction and releases any locks currently held. - * <p> - * If the rollback fails, because the rollback itself is interrupted by a fail-over between requesting that the - * rollback be done, and receiving an acknowledgement that it has been done, then a JMSException will be thrown. - * The client will be unable to determine whether or not the rollback actually happened on the broker in this case. - * - * @throws JMSException If the JMS provider fails to rollback the transaction due to some internal error. This does - * not mean that the rollback is known to have failed, merely that it is not known whether it - * failed or not. - * TODO Be aware of possible changes to parameter order as versions change. - */ - public void rollback() throws JMSException - { - synchronized (_suspensionLock) - { - checkTransacted(); - - try - { - boolean isSuspended = isSuspended(); - - if (!isSuspended) - { - suspendChannel(true); - } - - setRollbackMark(); - - syncDispatchQueue(false); - - _dispatcher.rollback(); - - releaseForRollback(); - - sendRollback(); - - markClean(); - - if (!isSuspended) - { - suspendChannel(false); - } - } - catch (AMQException e) - { - throw toJMSException("Failed to rollback: " + e, e); - } - catch (FailoverException e) - { - throw new JMSAMQException("Fail-over interrupted rollback. Status of the rollback is uncertain.", e); - } - catch (TransportException e) - { - throw toJMSException("Failure to rollback:" + e.getMessage(), e); - } - } - } - - public abstract void releaseForRollback(); - - public abstract void sendRollback() throws AMQException, FailoverException; - - public void run() - { - throw new java.lang.UnsupportedOperationException(); - } - - public void setMessageListener(MessageListener listener) throws JMSException - { - } - - /** - * @see #unsubscribe(String, boolean) - */ - public void unsubscribe(String name) throws JMSException - { - try - { - unsubscribe(name, false); - } - catch (TransportException e) - { - throw toJMSException("Exception while unsubscribing:" + e.getMessage(), e); - } - } - - /** - * Unsubscribe from a subscription. - * - * @param name the name of the subscription to unsubscribe - * @param safe allows safe unsubscribe operation that will not throw an {@link InvalidDestinationException} if the - * queue is not bound, possibly due to the subscription being closed. - * @throws JMSException on - * @throws InvalidDestinationException - */ - private void unsubscribe(String name, boolean safe) throws JMSException - { - TopicSubscriberAdaptor<C> subscriber; - - _subscriberDetails.lock(); - try - { - checkNotClosed(); - subscriber = _subscriptions.get(name); - if (subscriber != null) - { - // Remove saved subscription information - _subscriptions.remove(name); - _reverseSubscriptionMap.remove(subscriber.getMessageConsumer()); - } - } - finally - { - _subscriberDetails.unlock(); - } - - if (subscriber != null) - { - subscriber.close(); - - // send a queue.delete for the subscription - deleteQueue(AMQTopic.getDurableTopicQueueName(name, _connection)); - } - else - { - if (_strictAMQP) - { - if (_strictAMQPFATAL) - { - throw new UnsupportedOperationException("JMS Durable not currently supported by AMQP."); - } - else - { - _logger.warn("Unable to determine if subscription already exists for '" + name + "' for unsubscribe." - + " Requesting queue deletion regardless."); - } - - deleteQueue(AMQTopic.getDurableTopicQueueName(name, _connection)); - } - else // Queue Browser - { - - if (isQueueBound(getDefaultTopicExchangeName(), AMQTopic.getDurableTopicQueueName(name, _connection))) - { - deleteQueue(AMQTopic.getDurableTopicQueueName(name, _connection)); - } - else if (!safe) - { - throw new InvalidDestinationException("Unknown subscription name: " + name); - } - } - } - } - - protected C createConsumerImpl(final Destination destination, final int prefetchHigh, - final int prefetchLow, final boolean noLocal, - final boolean exclusive, String selector, final FieldTable rawSelector, - final boolean noConsume, final boolean autoClose) throws JMSException - { - checkTemporaryDestination(destination); - - if(!noConsume && isBrowseOnlyDestination(destination)) - { - throw new InvalidDestinationException("The consumer being created is not 'noConsume'," + - "but a 'browseOnly' Destination has been supplied."); - } - - final String messageSelector; - - if (_strictAMQP && !((selector == null) || selector.equals(""))) - { - if (_strictAMQPFATAL) - { - throw new UnsupportedOperationException("Selectors not currently supported by AMQP."); - } - else - { - messageSelector = null; - } - } - else - { - messageSelector = selector; - } - - return new FailoverRetrySupport<C, JMSException>( - new FailoverProtectedOperation<C, JMSException>() - { - public C execute() throws JMSException, FailoverException - { - checkNotClosed(); - - AMQDestination amqd = (AMQDestination) destination; - - C consumer; - try - { - consumer = createMessageConsumer(amqd, prefetchHigh, prefetchLow, - noLocal, exclusive, messageSelector, rawSelector, noConsume, autoClose); - } - catch(TransportException e) - { - throw toJMSException("Exception while creating consumer: " + e.getMessage(), e); - } - - if (_messageListener != null) - { - consumer.setMessageListener(_messageListener); - } - - try - { - registerConsumer(consumer, false); - } - catch (AMQInvalidArgumentException ise) - { - JMSException jmse = new InvalidSelectorException(ise.getMessage()); - jmse.setLinkedException(ise); - jmse.initCause(ise); - throw jmse; - } - catch (AMQInvalidRoutingKeyException e) - { - JMSException jmse = new InvalidDestinationException("Invalid routing key:" + amqd.getRoutingKey().toString()); - jmse.setLinkedException(e); - jmse.initCause(e); - throw jmse; - } - catch (AMQException e) - { - if (e instanceof AMQChannelClosedException) - { - close(-1, false); - } - - throw toJMSException("Error registering consumer: " + e,e); - } - catch (TransportException e) - { - throw toJMSException("Exception while registering consumer:" + e.getMessage(), e); - } - return consumer; - } - }, _connection).execute(); - } - - public abstract C createMessageConsumer(final AMQDestination destination, final int prefetchHigh, - final int prefetchLow, final boolean noLocal, final boolean exclusive, String selector, final FieldTable arguments, - final boolean noConsume, final boolean autoClose) throws JMSException; - - /** - * Called by the MessageConsumer when closing, to deregister the consumer from the map from consumerTag to consumer - * instance. - * - * @param consumer the consum - */ - void deregisterConsumer(C consumer) - { - if (_consumers.remove(consumer.getConsumerTag()) != null) - { - _subscriberAccess.lock(); - try - { - String subscriptionName = _reverseSubscriptionMap.remove(consumer); - if (subscriptionName != null) - { - _subscriptions.remove(subscriptionName); - } - } - finally - { - _subscriberAccess.unlock(); - } - - Destination dest = consumer.getDestination(); - synchronized (dest) - { - // Provide additional NPE check - // This would occur if the consumer was closed before it was - // fully opened. - if (_destinationConsumerCount.get(dest) != null) - { - if (_destinationConsumerCount.get(dest).decrementAndGet() == 0) - { - _destinationConsumerCount.remove(dest); - } - } - } - - // Consumers that are closed in a transaction must be stored - // so that messages they have received can be acknowledged on commit - if (_transacted) - { - _removedConsumers.add(consumer); - } - } - } - - void deregisterProducer(long producerId) - { - _producers.remove(producerId); - } - - boolean isInRecovery() - { - return _sessionInRecovery; - } - - boolean isQueueBound(AMQShortString exchangeName, AMQShortString queueName) throws JMSException - { - return isQueueBound(exchangeName, queueName, null); - } - - /** - * Tests whether or not the specified queue is bound to the specified exchange under a particular routing key. - * <p> - * Note that this operation automatically retries in the event of fail-over. - * - * @param exchangeName The exchange name to test for binding against. - * @param queueName The queue name to check if bound. - * @param routingKey The routing key to check if the queue is bound under. - * - * @return <tt>true</tt> if the queue is bound to the exchange and routing key, <tt>false</tt> if not. - * - * @throws JMSException If the query fails for any reason. - * TODO Be aware of possible changes to parameter order as versions change. - */ - public abstract boolean isQueueBound(final AMQShortString exchangeName, final AMQShortString queueName, final AMQShortString routingKey) - throws JMSException; - - public abstract boolean isQueueBound(final AMQDestination destination) throws JMSException; - - public abstract boolean isQueueBound(String exchangeName, String queueName, String bindingKey, Map<String,Object> args) throws JMSException; - - /** - * Called to mark the session as being closed. Useful when the session needs to be made invalid, e.g. after failover - * when the client has veoted resubscription. - * <p> - * The caller of this method must already hold the failover mutex. - */ - void markClosed() - { - setClosed(); - _connection.deregisterSession(_channelId); - markClosedProducersAndConsumers(); - - } - - - void syncDispatchQueue(final boolean holdDispatchLock) - { - if (Thread.currentThread() == _dispatcherThread || holdDispatchLock) - { - while (!super.isClosed() && !_queue.isEmpty()) - { - Dispatchable disp; - try - { - disp = _queue.take(); - } - catch (InterruptedException e) - { - throw new RuntimeException(e); - } - - // Check just in case _queue becomes empty, it shouldn't but - // better than an NPE. - if (disp == null) - { - _logger.debug("_queue became empty during sync."); - break; - } - - disp.dispatch(AMQSession.this); - } - } - else - { - startDispatcherIfNecessary(); - - final CountDownLatch signal = new CountDownLatch(1); - - _queue.add(new Dispatchable() - { - public void dispatch(AMQSession ssn) - { - signal.countDown(); - } - }); - - try - { - signal.await(); - } - catch (InterruptedException e) - { - throw new RuntimeException(e); - } - } - } - - void drainDispatchQueue() - { - if (Thread.currentThread() == _dispatcherThread) - { - while (!super.isClosed() && !_queue.isEmpty()) - { - Dispatchable disp; - try - { - disp = _queue.take(); - } - catch (InterruptedException e) - { - throw new RuntimeException(e); - } - - // Check just in case _queue becomes empty, it shouldn't but - // better than an NPE. - if (disp == null) - { - _logger.debug("_queue became empty during sync."); - break; - } - - disp.dispatch(AMQSession.this); - } - } - else - { - startDispatcherIfNecessary(false); - - final CountDownLatch signal = new CountDownLatch(1); - - _queue.add(new Dispatchable() - { - public void dispatch(AMQSession ssn) - { - signal.countDown(); - } - }); - - try - { - signal.await(); - } - catch (InterruptedException e) - { - throw new RuntimeException(e); - } - } - } - - /** - * Resubscribes all producers and consumers. This is called when performing failover. - * - * @throws AMQException - */ - void resubscribe() throws AMQException - { - if (_dirty) - { - _failedOverDirty = true; - } - - _rollbackMark.set(-1); - resubscribeProducers(); - resubscribeConsumers(); - } - - void setHasMessageListeners() - { - _hasMessageListeners = true; - } - - void setInRecovery(boolean inRecovery) - { - _sessionInRecovery = inRecovery; - } - - boolean isStarted() - { - return _startedAtLeastOnce.get(); - } - - /** - * Starts the session, which ensures that it is not suspended and that its event dispatcher is running. - * - * @throws AMQException If the session cannot be started for any reason. - * TODO This should be controlled by _stopped as it pairs with the stop method fixme or check the - * FlowControlledBlockingQueue _queue to see if we have flow controlled. will result in sending Flow messages - * for each subsequent call to flow.. only need to do this if we have called stop. - */ - void start() throws AMQException - { - // Check if the session has previously been started and suspended, in which case it must be unsuspended. - if (_startedAtLeastOnce.getAndSet(true)) - { - suspendChannel(false); - } - - // If the event dispatcher is not running then start it too. - if (hasMessageListeners()) - { - startDispatcherIfNecessary(); - } - } - - void startDispatcherIfNecessary() - { - //If we are the dispatcher then we don't need to check we are started - if (Thread.currentThread() == _dispatcherThread) - { - return; - } - - // If IMMEDIATE_PREFETCH is not set then we need to start fetching - // This is final per session so will be multi-thread safe. - if (!_immediatePrefetch) - { - // We do this now if this is the first call on a started connection - if (isSuspended() && _startedAtLeastOnce.get() && _firstDispatcher.getAndSet(false)) - { - try - { - suspendChannel(false); - } - catch (AMQException e) - { - _logger.info("Unsuspending channel threw an exception:", e); - } - } - } - - startDispatcherIfNecessary(false); - } - - synchronized void startDispatcherIfNecessary(boolean initiallyStopped) - { - if (_dispatcher == null) - { - _dispatcher = new Dispatcher(); - try - { - _dispatcherThread = Threading.getThreadFactory().createThread(_dispatcher); - - } - catch(Exception e) - { - throw new Error("Error creating Dispatcher thread",e); - } - - String dispatcherThreadName = "Dispatcher-" + _channelId + "-Conn-" + _connection.getConnectionNumber(); - - _dispatcherThread.setName(dispatcherThreadName); - _dispatcherThread.setDaemon(DAEMON_DISPATCHER_THREAD); - _dispatcher.setConnectionStopped(initiallyStopped); - _dispatcherThread.start(); - if (_dispatcherLogger.isDebugEnabled()) - { - _dispatcherLogger.debug(_dispatcherThread.getName() + " created"); - } - } - else - { - _dispatcher.setConnectionStopped(initiallyStopped); - } - } - - void stop() throws AMQException - { - // Stop the server delivering messages to this session. - if (!(isClosed() || isClosing())) - { - suspendChannel(true); - } - - if (_dispatcher != null) - { - _dispatcher.setConnectionStopped(true); - } - } - - private void checkNotTransacted() throws JMSException - { - if (getTransacted()) - { - throw new IllegalStateException("Session is transacted"); - } - } - - private void checkTemporaryDestination(Destination destination) throws JMSException - { - if ((destination instanceof TemporaryDestination)) - { - _logger.debug("destination is temporary"); - final TemporaryDestination tempDest = (TemporaryDestination) destination; - if (tempDest.getSession() != this) - { - _logger.debug("destination is on different session"); - throw new JMSException("Cannot consume from a temporary destination created on another session"); - } - - if (tempDest.isDeleted()) - { - _logger.debug("destination is deleted"); - throw new JMSException("Cannot consume from a deleted destination"); - } - } - } - - protected void checkTransacted() throws JMSException - { - if (!getTransacted()) - { - throw new IllegalStateException("Session is not transacted"); - } - } - - private void checkValidDestination(Destination destination) throws InvalidDestinationException - { - if (destination == null) - { - throw new javax.jms.InvalidDestinationException("Invalid Queue"); - } - } - - private void checkValidQueue(Queue queue) throws InvalidDestinationException - { - if (queue == null) - { - throw new javax.jms.InvalidDestinationException("Invalid Queue"); - } - } - - /* - * I could have combined the last 3 methods, but this way it improves readability - */ - protected Topic checkValidTopic(Topic topic, boolean durable) throws JMSException - { - if (topic == null) - { - throw new javax.jms.InvalidDestinationException("Invalid Topic"); - } - - if ((topic instanceof TemporaryDestination) && (((TemporaryDestination) topic).getSession() != this)) - { - throw new javax.jms.InvalidDestinationException( - "Cannot create a subscription on a temporary topic created in another session"); - } - - if ((topic instanceof TemporaryDestination) && durable) - { - throw new javax.jms.InvalidDestinationException - ("Cannot create a durable subscription with a temporary topic: " + topic); - } - - if (!(topic instanceof AMQDestination)) - { - throw new javax.jms.InvalidDestinationException( - "Cannot create a subscription on topic created for another JMS Provider, class of topic provided is: " - + topic.getClass().getName()); - } - - return topic; - } - - protected Topic checkValidTopic(Topic topic) throws JMSException - { - return checkValidTopic(topic, false); - } - - /** - * Called to close message consumers cleanly. This may or may <b>not</b> be as a result of an error. - * - * @param error not null if this is a result of an error occurring at the connection level - */ - private void closeConsumers(Throwable error) throws JMSException - { - // we need to clone the list of consumers since the close() method updates the _consumers collection - // which would result in a concurrent modification exception - final ArrayList<C> clonedConsumers = new ArrayList<C>(_consumers.values()); - - final Iterator<C> it = clonedConsumers.iterator(); - while (it.hasNext()) - { - final C con = it.next(); - if (error != null) - { - con.notifyError(error); - } - else - { - con.close(false); - } - } - // at this point the _consumers map will be empty - if (_dispatcher != null) - { - _dispatcher.close(); - _dispatcher = null; - } - } - - /** - * Called to close message producers cleanly. This may or may <b>not</b> be as a result of an error. There is - * currently no way of propagating errors to message producers (this is a JMS limitation). - */ - private void closeProducers() throws JMSException - { - // we need to clone the list of producers since the close() method updates the _producers collection - // which would result in a concurrent modification exception - final ArrayList clonedProducers = new ArrayList(_producers.values()); - - final Iterator it = clonedProducers.iterator(); - while (it.hasNext()) - { - final P prod = (P) it.next(); - prod.close(); - } - // at this point the _producers map is empty - } - - /** - * Close all producers or consumers. This is called either in the error case or when closing the session normally. - * - * @param amqe the exception, may be null to indicate no error has occurred - */ - private void closeProducersAndConsumers(AMQException amqe) throws JMSException - { - JMSException jmse = null; - try - { - closeProducers(); - } - catch (JMSException e) - { - _logger.error("Error closing session: " + e, e); - jmse = e; - } - - try - { - closeConsumers(amqe); - } - catch (JMSException e) - { - _logger.error("Error closing session: " + e, e); - if (jmse == null) - { - jmse = e; - } - } - - if (jmse != null) - { - throw jmse; - } - } - - /** - * Register to consume from the queue. - * @param queueName - */ - private void consumeFromQueue(C consumer, AMQShortString queueName, boolean nowait) throws AMQException, FailoverException - { - int tagId = _nextTag++; - - consumer.setConsumerTag(tagId); - // we must register the consumer in the map before we actually start listening - _consumers.put(tagId, consumer); - - synchronized (consumer.getDestination()) - { - _destinationConsumerCount.putIfAbsent(consumer.getDestination(), new AtomicInteger()); - _destinationConsumerCount.get(consumer.getDestination()).incrementAndGet(); - } - - - try - { - sendConsume(consumer, queueName, nowait, tagId); - } - catch (AMQException e) - { - // clean-up the map in the event of an error - _consumers.remove(tagId); - throw e; - } - } - - void handleLinkCreation(AMQDestination dest) throws AMQException - { - createBindings(dest, dest.getLink().getBindings()); - } - - - void createBindings(AMQDestination dest, List<AMQDestination.Binding> bindings) throws AMQException - { - String defaultExchangeForBinding = dest.getAddressType() == AMQDestination.TOPIC_TYPE ? dest - .getAddressName() : "amq.topic"; - - String defaultQueueName = null; - if (AMQDestination.QUEUE_TYPE == dest.getAddressType()) - { - defaultQueueName = dest.getQueueName(); - } - else - { - defaultQueueName = dest.getLink().getName() != null ? dest.getLink().getName() : dest.getQueueName(); - } - - for (AMQDestination.Binding binding: bindings) - { - String queue = binding.getQueue() == null? - defaultQueueName: binding.getQueue(); - - String exchange = binding.getExchange() == null ? - defaultExchangeForBinding : - binding.getExchange(); - - if (_logger.isDebugEnabled()) - { - _logger.debug("Binding queue : " + queue + - " exchange: " + exchange + - " using binding key " + binding.getBindingKey() + - " with args " + Strings.printMap(binding.getArgs())); - } - doBind(dest, binding, queue, exchange); - } - } - - protected abstract void handleQueueNodeCreation(AMQDestination dest, boolean noLocal) throws AMQException; - - abstract void handleExchangeNodeCreation(AMQDestination dest) throws AMQException; - - abstract protected void doBind(final AMQDestination dest, final AMQDestination.Binding binding, final String queue, final String exchange) - throws AMQException; - - public abstract void sendConsume(C consumer, AMQShortString queueName, - boolean nowait, int tag) throws AMQException, FailoverException; - - private P createProducerImpl(final Destination destination, final Boolean mandatory, final Boolean immediate) - throws JMSException - { - return new FailoverRetrySupport<P, JMSException>( - new FailoverProtectedOperation<P, JMSException>() - { - public P execute() throws JMSException, FailoverException - { - checkNotClosed(); - long producerId = getNextProducerId(); - - P producer; - try - { - producer = createMessageProducer(destination, mandatory, - immediate, producerId); - } - catch (TransportException e) - { - throw toJMSException("Exception while creating producer:" + e.getMessage(), e); - } - - registerProducer(producerId, producer); - - return producer; - } - }, _connection).execute(); - } - - public abstract P createMessageProducer(final Destination destination, final Boolean mandatory, - final Boolean immediate, final long producerId) throws JMSException; - - private void declareExchange(AMQDestination amqd, boolean nowait) throws AMQException - { - declareExchange(amqd.getExchangeName(), amqd.getExchangeClass(), nowait, amqd.isExchangeDurable(), - amqd.isExchangeAutoDelete(), amqd.isExchangeInternal()); - } - - /** - * Returns the number of messages currently queued for the given destination. - * <p> - * Note that this operation automatically retries in the event of fail-over. - * - * @param amqd The destination to be checked - * - * @return the number of queued messages. - * - * @throws AMQException If the queue cannot be declared for any reason. - */ - public long getQueueDepth(final AMQDestination amqd) - throws AMQException - { - return getQueueDepth(amqd, false); - } - - /** - * Returns the number of messages currently queued by the given - * destination. Syncs session before receiving the queue depth if sync is - * set to true. - * - * @param amqd AMQ destination to get the depth value - * @param sync flag to sync session before receiving the queue depth - * @return queue depth - * @throws AMQException - */ - public long getQueueDepth(final AMQDestination amqd, final boolean sync) throws AMQException - { - return new FailoverNoopSupport<Long, AMQException>(new FailoverProtectedOperation<Long, AMQException>() - { - public Long execute() throws AMQException, FailoverException - { - try - { - return requestQueueDepth(amqd, sync); - } - catch (TransportException e) - { - throw new AMQException(AMQConstant.getConstant(getErrorCode(e)), e.getMessage(), e); - } - } - }, _connection).execute(); - } - - protected abstract Long requestQueueDepth(AMQDestination amqd, boolean sync) throws AMQException, FailoverException; - - /** - * Declares the named exchange and type of exchange. - * <p> - * Note that this operation automatically retries in the event of fail-over. - * - * @param name The name of the exchange to declare. - * @param type The type of the exchange to declare. - * @param nowait - * @param durable - * @param autoDelete - * @param internal - * @throws AMQException If the exchange cannot be declared for any reason. - * TODO Be aware of possible changes to parameter order as versions change. - */ - void declareExchange(final AMQShortString name, final AMQShortString type, - final boolean nowait, final boolean durable, - final boolean autoDelete, final boolean internal) throws AMQException - { - new FailoverNoopSupport<Object, AMQException>(new FailoverProtectedOperation<Object, AMQException>() - { - public Object execute() throws AMQException, FailoverException - { - sendExchangeDeclare(name, type, nowait, durable, autoDelete, internal); - return null; - } - }, _connection).execute(); - } - - void declareExchange(final AMQShortString name, final AMQShortString type, - final boolean nowait, final boolean durable, - final boolean autoDelete, final FieldTable arguments, - final boolean passive) throws AMQException - { - new FailoverNoopSupport<Object, AMQException>(new FailoverProtectedOperation<Object, AMQException>() - { - public Object execute() throws AMQException, FailoverException - { - sendExchangeDeclare(name, type, nowait, durable, autoDelete, arguments, passive); - return null; - } - }, _connection).execute(); - } - - protected AMQShortString preprocessAddressTopic(final C consumer, - AMQShortString queueName) throws AMQException - { - if (DestSyntax.ADDR == consumer.getDestination().getDestSyntax()) - { - if (AMQDestination.TOPIC_TYPE == consumer.getDestination().getAddressType()) - { - String selector = consumer.getMessageSelectorFilter() == null? null : consumer.getMessageSelectorFilter().getSelector(); - - createSubscriptionQueue(consumer.getDestination(), consumer.isNoLocal(), selector); - queueName = consumer.getDestination().getAMQQueueName(); - consumer.setQueuename(queueName); - } - handleLinkCreation(consumer.getDestination()); - } - return queueName; - } - - abstract void createSubscriptionQueue(AMQDestination dest, boolean noLocal, String messageSelector) throws AMQException; - - public abstract void sendExchangeDeclare(final AMQShortString name, final AMQShortString type, final boolean nowait, - boolean durable, boolean autoDelete, boolean internal) throws AMQException, FailoverException; - - - public abstract void sendExchangeDeclare(final AMQShortString name, - final AMQShortString type, - final boolean nowait, - boolean durable, - boolean autoDelete, - FieldTable arguments, - final boolean passive) throws AMQException, FailoverException; - - /** - * Declares a queue for a JMS destination. - * <p> - * Note that for queues but not topics the name is generated in the client rather than the server. This allows - * the name to be reused on failover if required. In general, the destination indicates whether it wants a name - * generated or not. - * <p> - * Note that this operation automatically retries in the event of fail-over. - * - * - * @param amqd The destination to declare as a queue. - * @return The name of the decalred queue. This is useful where the broker is generating a queue name on behalf of - * the client. - * - * - * - * @throws AMQException If the queue cannot be declared for any reason. - * TODO Verify the destiation is valid or throw an exception. - * TODO Be aware of possible changes to parameter order as versions change. - */ - protected AMQShortString declareQueue(final AMQDestination amqd, - final boolean noLocal) throws AMQException - { - return declareQueue(amqd, noLocal, false); - } - - protected AMQShortString declareQueue(final AMQDestination amqd, - final boolean noLocal, final boolean nowait) - throws AMQException - { - return declareQueue(amqd, noLocal, nowait, false); - } - - protected abstract AMQShortString declareQueue(final AMQDestination amqd, - final boolean noLocal, final boolean nowait, final boolean passive) throws AMQException; - - /** - * Undeclares the specified queue. - * <p> - * Note that this operation automatically retries in the event of fail-over. - * - * @param queueName The name of the queue to delete. - * - * @throws JMSException If the queue could not be deleted for any reason. - * TODO Be aware of possible changes to parameter order as versions change. - */ - protected void deleteQueue(final AMQShortString queueName) throws JMSException - { - try - { - new FailoverRetrySupport<Object, AMQException>(new FailoverProtectedOperation<Object, AMQException>() - { - public Object execute() throws AMQException, FailoverException - { - sendQueueDelete(queueName); - return null; - } - }, _connection).execute(); - } - catch (AMQException e) - { - throw toJMSException("The queue deletion failed: " + e.getMessage(), e); - } - } - - /** - * Undeclares the specified temporary queue/topic. - * <p> - * Note that this operation automatically retries in the event of fail-over. - * - * @param amqQueue The name of the temporary destination to delete. - * - * @throws JMSException If the queue could not be deleted for any reason. - * TODO Be aware of possible changes to parameter order as versions change. - */ - protected void deleteTemporaryDestination(final TemporaryDestination amqQueue) throws JMSException - { - deleteQueue(amqQueue.getAMQQueueName()); - } - - public abstract void sendQueueDelete(final AMQShortString queueName) throws AMQException, FailoverException; - - private long getNextProducerId() - { - return ++_nextProducerId; - } - - protected boolean hasMessageListeners() - { - return _hasMessageListeners; - } - - private void markClosedConsumers() throws JMSException - { - if (_dispatcher != null) - { - _dispatcher.close(); - _dispatcher = null; - } - // we need to clone the list of consumers since the close() method updates the _consumers collection - // which would result in a concurrent modification exception - final ArrayList<C> clonedConsumers = new ArrayList<C>(_consumers.values()); - - final Iterator<C> it = clonedConsumers.iterator(); - while (it.hasNext()) - { - final C con = it.next(); - con.markClosed(); - } - // at this point the _consumers map will be empty - } - - private void markClosedProducersAndConsumers() - { - try - { - // no need for a markClosed* method in this case since there is no protocol traffic closing a producer - closeProducers(); - } - catch (JMSException e) - { - _logger.error("Error closing session: " + e, e); - } - - try - { - markClosedConsumers(); - } - catch (JMSException e) - { - _logger.error("Error closing session: " + e, e); - } - } - - /** - * Callers must hold the failover mutex before calling this method. - * - * @param consumer - * - * @throws AMQException - */ - private void registerConsumer(C consumer, boolean nowait) throws AMQException // , FailoverException - { - AMQDestination amqd = consumer.getDestination(); - - if (amqd.getDestSyntax() == DestSyntax.ADDR) - { - resolveAddress(amqd,true,consumer.isNoLocal()); - } - else - { - if (_declareExchanges && !amqd.neverDeclare()) - { - declareExchange(amqd, nowait); - } - - if ((_declareQueues || amqd.isNameRequired()) && !amqd.neverDeclare()) - { - declareQueue(amqd, consumer.isNoLocal(), nowait); - } - if (_bindQueues && !amqd.neverDeclare()) - { - if(!isBound(amqd.getExchangeName(), amqd.getAMQQueueName(), amqd.getRoutingKey())) - { - bindQueue(amqd.getAMQQueueName(), amqd.getRoutingKey(), - amqd instanceof AMQTopic ? consumer.getArguments() : null, amqd.getExchangeName(), amqd, nowait); - } - } - - } - - AMQShortString queueName = amqd.getAMQQueueName(); - - // store the consumer queue name - consumer.setQueuename(queueName); - - // If IMMEDIATE_PREFETCH is not required then suspsend the channel to delay prefetch - if (!_immediatePrefetch) - { - // The dispatcher will be null if we have just created this session - // so suspend the channel before we register our consumer so that we don't - // start prefetching until a receive/mListener is set. - if (_dispatcher == null) - { - if (!isSuspended()) - { - try - { - suspendChannel(true); - _logger.debug( - "Prefetching delayed existing messages will not flow until requested via receive*() or setML()."); - } - catch (AMQException e) - { - _logger.info("Suspending channel threw an exception:", e); - } - } - } - } - else - { - _logger.debug("Immediately prefetching existing messages to new consumer."); - } - - try - { - consumeFromQueue(consumer, queueName, nowait); - } - catch (FailoverException e) - { - throw new AMQException(null, "Fail-over exception interrupted basic consume.", e); - } - } - - protected abstract boolean isBound(AMQShortString exchangeName, AMQShortString amqQueueName, AMQShortString routingKey) - throws AMQException; - - private void registerProducer(long producerId, MessageProducer producer) - { - _producers.put(producerId, producer); - } - - private void rejectMessagesForConsumerTag(int consumerTag) - { - Iterator<Dispatchable> messages = _queue.iterator(); - if (_logger.isDebugEnabled()) - { - _logger.debug("Rejecting messages from _queue for Consumer tag(" + consumerTag + ")"); - - if (messages.hasNext()) - { - _logger.debug("Checking all messages in _queue for Consumer tag(" + consumerTag + ")"); - } - else - { - _logger.debug("No messages in _queue to reject"); - } - } - while (messages.hasNext()) - { - UnprocessedMessage message = (UnprocessedMessage) messages.next(); - - if (message.getConsumerTag() == consumerTag) - { - - if (_queue.remove(message)) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Removing message(" + System.identityHashCode(message) + ") from _queue DT:" - + message.getDeliveryTag()); - } - - rejectMessage(message, true); - - if (_logger.isDebugEnabled()) - { - _logger.debug("Rejected the message(" + message.toString() + ") for consumer :" + consumerTag); - } - } - } - } - } - - private void resubscribeConsumers() throws AMQException - { - ArrayList<C> consumers = new ArrayList<C>(_consumers.values()); - _consumers.clear(); - - for (C consumer : consumers) - { - consumer.failedOverPre(); - registerConsumer(consumer, true); - consumer.failedOverPost(); - } - } - - private void resubscribeProducers() throws AMQException - { - ArrayList producers = new ArrayList(_producers.values()); - _logger.debug(MessageFormat.format("Resubscribing producers = {0} producers.size={1}", producers, producers.size())); // FIXME: removeKey - for (Iterator it = producers.iterator(); it.hasNext();) - { - P producer = (P) it.next(); - producer.resubscribe(); - } - } - - /** - * Suspends or unsuspends this session. - * - * @param suspend true indicates that the session should be suspended, false indicates that it - * should be unsuspended. - * - * @throws AMQException If the session cannot be suspended for any reason. - * TODO Be aware of possible changes to parameter order as versions change. - */ - protected void suspendChannel(boolean suspend) throws AMQException // , FailoverException - { - synchronized (_suspensionLock) - { - try - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Setting channel flow : " + (suspend ? "suspended" : "unsuspended")); - } - - _suspended = suspend; - sendSuspendChannel(suspend); - } - catch (FailoverException e) - { - throw new AMQException(null, "Fail-over interrupted suspend/unsuspend channel.", e); - } - catch (TransportException e) - { - throw new AMQException(AMQConstant.getConstant(getErrorCode(e)), e.getMessage(), e); - } - } - } - - public abstract void sendSuspendChannel(boolean suspend) throws AMQException, FailoverException; - - Object getMessageDeliveryLock() - { - return _messageDeliveryLock; - } - - /** - * Indicates whether this session consumers pre-fetche messages - * - * @return true if this session consumers pre-fetche messages false otherwise - */ - public boolean prefetch() - { - return _prefetchHighMark > 0; - } - - /** Signifies that the session has pending sends to commit. */ - public void markDirty() - { - _dirty = true; - } - - /** Signifies that the session has no pending sends to commit. */ - public void markClean() - { - _dirty = false; - _failedOverDirty = false; - } - - /** - * Check to see if failover has occured since the last call to markClean(commit or rollback). - * - * @return boolean true if failover has occured. - */ - public boolean hasFailedOverDirty() - { - return _failedOverDirty; - } - - public void setTicket(int ticket) - { - _ticket = ticket; - } - - /** - * Tests whether flow to this session is blocked. - * - * @return true if flow is blocked or false otherwise. - */ - public abstract boolean isFlowBlocked(); - - public abstract void setFlowControl(final boolean active); - - Object getDispatcherLock() - { - Dispatcher dispatcher = _dispatcher; - return dispatcher == null ? null : dispatcher._lock; - } - - public interface Dispatchable - { - void dispatch(AMQSession ssn); - } - - public void dispatch(UnprocessedMessage message) - { - if (_dispatcher == null) - { - throw new java.lang.IllegalStateException("dispatcher is not started"); - } - - _dispatcher.dispatchMessage(message); - } - - /** Used for debugging in the dispatcher. */ - private static final Logger _dispatcherLogger = LoggerFactory.getLogger("org.apache.qpid.client.AMQSession.Dispatcher"); - - /** Responsible for decoding a message fragment and passing it to the appropriate message consumer. */ - class Dispatcher implements Runnable - { - - /** Track the 'stopped' state of the dispatcher, a session starts in the stopped state. */ - private final AtomicBoolean _closed = new AtomicBoolean(false); - - private final Object _lock = new Object(); - private final String dispatcherID = "" + System.identityHashCode(this); - - public Dispatcher() - { - } - - public void close() - { - _closed.set(true); - _dispatcherThread.interrupt(); - - // fixme awaitTermination - - } - - private AtomicBoolean getClosed() - { - return _closed; - } - - - public void rollback() - { - - synchronized (_lock) - { - boolean isStopped = connectionStopped(); - - if (!isStopped) - { - setConnectionStopped(true); - } - - setRollbackMark(); - - _dispatcherLogger.debug("Session Pre Dispatch Queue cleared"); - - for (C consumer : _consumers.values()) - { - if (!consumer.isBrowseOnly()) - { - consumer.rollback(); - } - else - { - // should perhaps clear the _SQ here. - consumer.clearReceiveQueue(); - } - - } - - for (int i = 0; i < _removedConsumers.size(); i++) - { - // Sends acknowledgement to server - _removedConsumers.get(i).rollback(); - _removedConsumers.remove(i); - } - - setConnectionStopped(isStopped); - } - - } - - public void recover() - { - - synchronized (_lock) - { - boolean isStopped = connectionStopped(); - - if (!isStopped) - { - setConnectionStopped(true); - } - - _dispatcherLogger.debug("Session clearing the consumer queues"); - - for (C consumer : _consumers.values()) - { - List<Long> tags = consumer.drainReceiverQueueAndRetrieveDeliveryTags(); - _prefetchedMessageTags.addAll(tags); - } - - setConnectionStopped(isStopped); - } - - } - - - public void run() - { - if (_dispatcherLogger.isDebugEnabled()) - { - _dispatcherLogger.debug(_dispatcherThread.getName() + " started"); - } - - // Allow disptacher to start stopped - synchronized (_lock) - { - while (!_closed.get() && connectionStopped()) - { - try - { - _lock.wait(); - } - catch (InterruptedException e) - { - Thread.currentThread().interrupt(); - } - } - } - - try - { - - while (((_queue.blockingPeek()) != null) && !_closed.get()) - { - synchronized (_lock) - { - Dispatchable disp = _queue.nonBlockingTake(); - - if(disp != null) - { - disp.dispatch(AMQSession.this); - } - } - } - } - catch (InterruptedException e) - { - // ignored as run will exit immediately - } - - if (_dispatcherLogger.isDebugEnabled()) - { - _dispatcherLogger.debug(_dispatcherThread.getName() + " thread terminating for channel " + _channelId + ":" + AMQSession.this); - } - - } - - // only call while holding lock - final boolean connectionStopped() - { - return _connectionStopped.get(); - } - - boolean setConnectionStopped(boolean connectionStopped) - { - boolean currently = _connectionStopped.get(); - if(connectionStopped != currently) - { - synchronized (_lock) - { - _connectionStopped.set(connectionStopped); - _lock.notify(); - - if (_dispatcherLogger.isDebugEnabled()) - { - _dispatcherLogger.debug("Set Dispatcher Connection " + (connectionStopped - ? "Stopped" - : "Started") - + ": Currently " + (currently ? "Stopped" : "Started")); - } - } - } - return currently; - } - - private void dispatchMessage(UnprocessedMessage message) - { - long deliveryTag = message.getDeliveryTag(); - - synchronized (_lock) - { - - try - { - while (connectionStopped()) - { - _lock.wait(); - } - } - catch (InterruptedException e) - { - Thread.currentThread().interrupt(); - } - - if (!(message instanceof CloseConsumerMessage) - && tagLE(deliveryTag, _rollbackMark.get())) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Rejecting message because delivery tag " + deliveryTag - + " <= rollback mark " + _rollbackMark.get()); - } - rejectMessage(message, true); - } - else if (_usingDispatcherForCleanup) - { - _prefetchedMessageTags.add(deliveryTag); - } - else - { - synchronized (_messageDeliveryLock) - { - notifyConsumer(message); - } - } - } - - long current = _rollbackMark.get(); - if (updateRollbackMark(current, deliveryTag)) - { - _rollbackMark.compareAndSet(current, deliveryTag); - } - } - - private void notifyConsumer(UnprocessedMessage message) - { - final C consumer = _consumers.get(message.getConsumerTag()); - - if ((consumer == null) || consumer.isClosed() || consumer.isClosing()) - { - if (_dispatcherLogger.isInfoEnabled()) - { - if (consumer == null) - { - _dispatcherLogger.info("Dispatcher(" + dispatcherID + ")Received a message(" - + System.identityHashCode(message) + ")" + "[" - + message.getDeliveryTag() + "] from queue " - + message.getConsumerTag() + " )without a handler - rejecting(requeue)..."); - } - else - { - if (consumer.isBrowseOnly()) - { - _dispatcherLogger.info("Received a message(" - + System.identityHashCode(message) + ")" + "[" - + message.getDeliveryTag() + "] from queue " + " consumer(" - + message.getConsumerTag() + ") is closed and a browser so dropping..."); - //DROP MESSAGE - return; - - } - else - { - _dispatcherLogger.info("Received a message(" - + System.identityHashCode(message) + ")" + "[" - + message.getDeliveryTag() + "] from queue " + " consumer(" - + message.getConsumerTag() + ") is closed rejecting(requeue)..."); - } - } - } - // Don't reject if we're already closing - if (!_closed.get()) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Rejecting message with delivery tag " + message.getDeliveryTag() - + " for closing consumer " + String.valueOf(consumer == null? null: consumer.getConsumerTag())); - } - rejectMessage(message, true); - } - } - else - { - consumer.notifyMessage(message); - } - } - } - - protected abstract boolean tagLE(long tag1, long tag2); - - protected abstract boolean updateRollbackMark(long current, long deliveryTag); - - public abstract AMQMessageDelegateFactory getMessageDelegateFactory(); - - private class SuspenderRunner implements Runnable - { - private AtomicBoolean _suspend; - - public SuspenderRunner(AtomicBoolean suspend) - { - _suspend = suspend; - } - - public void run() - { - try - { - synchronized (_suspensionLock) - { - // If the session has closed by the time we get here - // then we should not attempt to write to the sesion/channel. - if (!(AMQSession.this.isClosed() || AMQSession.this.isClosing())) - { - suspendChannel(_suspend.get()); - } - } - } - catch (AMQException e) - { - _logger.warn("Unable to " + (_suspend.get() ? "suspend" : "unsuspend") + " session " + AMQSession.this + " due to: ", e); - if (_logger.isDebugEnabled()) - { - _logger.debug("Is the _queue empty?" + _queue.isEmpty()); - _logger.debug("Is the dispatcher closed?" + (_dispatcher == null ? "it's Null" : _dispatcher.getClosed())); - } - } - } - } - - /** - * Checks if the Session and its parent connection are closed - * - * @return <tt>true</tt> if this is closed, <tt>false</tt> otherwise. - */ - @Override - public boolean isClosed() - { - return super.isClosed() || _connection.isClosed(); - } - - /** - * Checks if the Session and its parent connection are capable of performing - * closing operations - * - * @return <tt>true</tt> if we are closing, <tt>false</tt> otherwise. - */ - @Override - public boolean isClosing() - { - return super.isClosing() || _connection.isClosing(); - } - - public boolean isDeclareExchanges() - { - return _declareExchanges; - } - - JMSException toJMSException(String message, TransportException e) - { - int code = getErrorCode(e); - JMSException jmse = new JMSException(message, Integer.toString(code)); - jmse.setLinkedException(e); - jmse.initCause(e); - return jmse; - } - - private int getErrorCode(TransportException e) - { - int code = AMQConstant.INTERNAL_ERROR.getCode(); - if (e instanceof SessionException) - { - SessionException se = (SessionException) e; - if(se.getException() != null && se.getException().getErrorCode() != null) - { - code = se.getException().getErrorCode().getValue(); - } - } - return code; - } - - JMSException toJMSException(String message, AMQException e) - { - JMSException ex; - - AMQConstant errorCode = e.getErrorCode(); - if (errorCode == AMQConstant.ACCESS_REFUSED) - { - ex = new JMSSecurityException(message, String.valueOf(errorCode.getCode())); - } - else - { - ex = new JMSException(message, errorCode == null ? null : String.valueOf(errorCode.getCode())); - } - ex.initCause(e); - - ex.setLinkedException(e); - return ex; - } - - private boolean isBrowseOnlyDestination(Destination destination) - { - return ((destination instanceof AMQDestination) && ((AMQDestination)destination).isBrowseOnly()); - } - - private void setRollbackMark() - { - // Let the dispatcher know that all the incomming messages - // should be rolled back(reject/release) - _rollbackMark.set(_highestDeliveryTag.get()); - if (_logger.isDebugEnabled()) - { - _logger.debug("Rollback mark is set to " + _rollbackMark.get()); - } - } - -} - diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQSessionAdapter.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQSessionAdapter.java deleted file mode 100644 index e94099f066..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQSessionAdapter.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.client; - -import javax.jms.*; -import java.io.Serializable; - -public abstract class AMQSessionAdapter<T extends Session> implements Session -{ - private final T _session; - - protected AMQSessionAdapter(final T session) - { - _session = session; - } - - public T getSession() - { - return _session; - } - - public BytesMessage createBytesMessage() throws JMSException - { - return _session.createBytesMessage(); - } - - public MapMessage createMapMessage() throws JMSException - { - return _session.createMapMessage(); - } - - public Message createMessage() throws JMSException - { - return _session.createMessage(); - } - - public ObjectMessage createObjectMessage() throws JMSException - { - return _session.createObjectMessage(); - } - - public ObjectMessage createObjectMessage(final Serializable serializable) throws JMSException - { - return _session.createObjectMessage(serializable); - } - - public StreamMessage createStreamMessage() throws JMSException - { - return _session.createStreamMessage(); - } - - public TextMessage createTextMessage() throws JMSException - { - return _session.createTextMessage(); - } - - public TextMessage createTextMessage(final String s) throws JMSException - { - return _session.createTextMessage(s); - } - - public boolean getTransacted() throws JMSException - { - return _session.getTransacted(); - } - - public int getAcknowledgeMode() throws JMSException - { - return _session.getAcknowledgeMode(); - } - - public void commit() throws JMSException - { - _session.commit(); - } - - public void rollback() throws JMSException - { - _session.rollback(); - } - - public void close() throws JMSException - { - _session.close(); - } - - public void recover() throws JMSException - { - _session.recover(); - } - - public MessageListener getMessageListener() throws JMSException - { - return _session.getMessageListener(); - } - - public void setMessageListener(final MessageListener messageListener) throws JMSException - { - _session.setMessageListener(messageListener); - } - - public void run() - { - _session.run(); - } - - public MessageProducer createProducer(final Destination destination) throws JMSException - { - return _session.createProducer(destination); - } - - public MessageConsumer createConsumer(final Destination destination) throws JMSException - { - return _session.createConsumer(destination); - } - - public MessageConsumer createConsumer(final Destination destination, final String s) throws JMSException - { - return _session.createConsumer(destination, s); - } - - public MessageConsumer createConsumer(final Destination destination, final String s, final boolean b) - throws JMSException - { - return _session.createConsumer(destination, s, b); - } - - public Queue createQueue(final String s) throws JMSException - { - return _session.createQueue(s); - } - - public Topic createTopic(final String s) throws JMSException - { - return _session.createTopic(s); - } - - public TopicSubscriber createDurableSubscriber(final Topic topic, final String s) throws JMSException - { - return _session.createDurableSubscriber(topic, s); - } - - public TopicSubscriber createDurableSubscriber(final Topic topic, final String s, final String s1, final boolean b) - throws JMSException - { - return _session.createDurableSubscriber(topic, s, s1, b); - } - - public QueueBrowser createBrowser(final Queue queue) throws JMSException - { - return _session.createBrowser(queue); - } - - public QueueBrowser createBrowser(final Queue queue, final String s) throws JMSException - { - return _session.createBrowser(queue, s); - } - - public TemporaryQueue createTemporaryQueue() throws JMSException - { - return _session.createTemporaryQueue(); - } - - public TemporaryTopic createTemporaryTopic() throws JMSException - { - return _session.createTemporaryTopic(); - } - - public void unsubscribe(final String s) throws JMSException - { - _session.unsubscribe(s); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQSessionDirtyException.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQSessionDirtyException.java deleted file mode 100644 index a33d05f0c7..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQSessionDirtyException.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.client; - -import org.apache.qpid.AMQException; -import org.apache.qpid.protocol.AMQConstant; - -/** - * AMQSessionDirtyException represents all failures to send data on a transacted session that is - * no longer in a state that the client expects. i.e. failover has occured so previously sent messages - * will not be part of the transaction. - */ -public class AMQSessionDirtyException extends AMQException -{ - public AMQSessionDirtyException(String msg) - { - super(AMQConstant.RESOURCE_ERROR, msg, null); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQSession_0_10.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQSession_0_10.java deleted file mode 100644 index 08d7ea3f67..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQSession_0_10.java +++ /dev/null @@ -1,1487 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; - -import static org.apache.qpid.transport.Option.BATCH; -import static org.apache.qpid.transport.Option.NONE; -import static org.apache.qpid.transport.Option.SYNC; -import static org.apache.qpid.transport.Option.UNRELIABLE; - -import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Timer; -import java.util.TimerTask; -import java.util.UUID; -import java.util.concurrent.ConcurrentLinkedQueue; - -import javax.jms.Destination; -import javax.jms.JMSException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.AMQDestination.Binding; -import org.apache.qpid.client.AMQDestination.DestSyntax; -import org.apache.qpid.client.failover.FailoverException; -import org.apache.qpid.client.failover.FailoverNoopSupport; -import org.apache.qpid.client.failover.FailoverProtectedOperation; -import org.apache.qpid.client.message.AMQMessageDelegateFactory; -import org.apache.qpid.client.message.FieldTableSupport; -import org.apache.qpid.client.message.MessageFactoryRegistry; -import org.apache.qpid.client.message.UnprocessedMessage_0_10; -import org.apache.qpid.client.messaging.address.AddressHelper; -import org.apache.qpid.client.messaging.address.Link; -import org.apache.qpid.client.messaging.address.Link.SubscriptionQueue; -import org.apache.qpid.client.messaging.address.Node; -import org.apache.qpid.common.AMQPFilterTypes; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.transport.*; -import org.apache.qpid.util.Serial; -import org.apache.qpid.util.Strings; - -/** - * This is a 0.10 Session - */ -public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, BasicMessageProducer_0_10> - implements SessionListener -{ - - /** - * This class logger - */ - private static final Logger _logger = LoggerFactory.getLogger(AMQSession_0_10.class); - - private static Timer timer = new Timer("ack-flusher", true); - private final String _name; - - private static class Flusher extends TimerTask - { - - private WeakReference<AMQSession_0_10> session; - public Flusher(AMQSession_0_10 session) - { - this.session = new WeakReference<AMQSession_0_10>(session); - } - - public void run() { - AMQSession_0_10 ssn = session.get(); - if (ssn == null) - { - cancel(); - } - else - { - try - { - ssn.flushAcknowledgments(true); - } - catch (Exception t) - { - _logger.error("error flushing acks", t); - } - } - } - } - - - /** - * The underlying QpidSession - */ - private Session _qpidSession; - - /** - * The latest qpid Exception that has been raised. - */ - private Object _currentExceptionLock = new Object(); - private AMQException _currentException; - - // a ref on the qpid connection - private org.apache.qpid.transport.Connection _qpidConnection; - - private long maxAckDelay = Long.getLong("qpid.session.max_ack_delay", 1000); - private TimerTask flushTask = null; - private RangeSet unacked = RangeSetFactory.createRangeSet(); - private int unackedCount = 0; - - /** - * Used to store the range of in tx messages - */ - private final RangeSet _txRangeSet = RangeSetFactory.createRangeSet(); - private int _txSize = 0; - private boolean _isHardError = Boolean.getBoolean("qpid.session.legacy_exception_behaviour"); - //--- constructors - - - /** - * Creates a new session on a connection. - * - * @param con The connection on which to create the session. - * @param channelId The unique identifier for the session. - * @param transacted Indicates whether or not the session is transactional. - * @param acknowledgeMode The acknowledgement mode for the session. - * @param messageFactoryRegistry The message factory factory for the session. - * @param defaultPrefetchHighMark The maximum number of messages to prefetched before suspending the session. - * @param defaultPrefetchLowMark The number of prefetched messages at which to resume the session. - * @param qpidConnection The qpid connection - */ - AMQSession_0_10(org.apache.qpid.transport.Connection qpidConnection, AMQConnection con, int channelId, - boolean transacted, int acknowledgeMode, MessageFactoryRegistry messageFactoryRegistry, - int defaultPrefetchHighMark, int defaultPrefetchLowMark,String name) - { - - super(con, channelId, transacted, acknowledgeMode, messageFactoryRegistry, defaultPrefetchHighMark, - defaultPrefetchLowMark); - _qpidConnection = qpidConnection; - _name = name; - _qpidSession = createSession(); - - if (maxAckDelay > 0) - { - flushTask = new Flusher(this); - timer.schedule(flushTask, new Date(), maxAckDelay); - } - } - - protected Session createSession() - { - Session qpidSession; - if (_name == null) - { - qpidSession = _qpidConnection.createSession(1); - } - else - { - qpidSession = _qpidConnection.createSession(_name,1); - } - if (isTransacted()) - { - qpidSession.txSelect(); - qpidSession.setTransacted(true); - } - qpidSession.setSessionListener(this); - - return qpidSession; - } - - - /** - * Creates a new session on a connection with the default 0-10 message factory. - * - * @param con The connection on which to create the session. - * @param channelId The unique identifier for the session. - * @param transacted Indicates whether or not the session is transactional. - * @param acknowledgeMode The acknowledgement mode for the session. - * @param defaultPrefetchHigh The maximum number of messages to prefetched before suspending the session. - * @param defaultPrefetchLow The number of prefetched messages at which to resume the session. - * @param qpidConnection The connection - */ - AMQSession_0_10(org.apache.qpid.transport.Connection qpidConnection, AMQConnection con, int channelId, - boolean transacted, int acknowledgeMode, int defaultPrefetchHigh, int defaultPrefetchLow, - String name) - { - - this(qpidConnection, con, channelId, transacted, acknowledgeMode, MessageFactoryRegistry.newDefaultRegistry(), - defaultPrefetchHigh, defaultPrefetchLow,name); - } - - private void addUnacked(int id) - { - synchronized (unacked) - { - unacked.add(id); - unackedCount++; - } - } - - private void clearUnacked() - { - synchronized (unacked) - { - unacked.clear(); - unackedCount = 0; - } - } - - protected Connection getQpidConnection() - { - return _qpidConnection; - } - - //------- overwritten methods of class AMQSession - - void failoverPrep() - { - syncDispatchQueue(true); - clearUnacked(); - } - - /** - * Acknowledge one or many messages. - * - * @param deliveryTag The tag of the last message to be acknowledged. - * @param multiple <tt>true</tt> to acknowledge all messages up to and including the one specified by the - * delivery tag, <tt>false</tt> to just acknowledge that message. - */ - - public void acknowledgeMessage(long deliveryTag, boolean multiple) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Sending ack for delivery tag " + deliveryTag + " on session " + getChannelId()); - } - // acknowledge this message - if (multiple) - { - for (Long messageTag : getUnacknowledgedMessageTags()) - { - if( messageTag <= deliveryTag ) - { - addUnacked(messageTag.intValue()); - getUnacknowledgedMessageTags().remove(messageTag); - } - } - //empty the list of unack messages - - } - else - { - addUnacked((int) deliveryTag); - getUnacknowledgedMessageTags().remove(deliveryTag); - } - - long prefetch = getAMQConnection().getMaxPrefetch(); - - if (unackedCount >= prefetch/2 || maxAckDelay <= 0 || getAcknowledgeMode() == javax.jms.Session.AUTO_ACKNOWLEDGE) - { - flushAcknowledgments(); - } - } - - protected void flushAcknowledgments() - { - flushAcknowledgments(false); - } - - void flushAcknowledgments(boolean setSyncBit) - { - synchronized (unacked) - { - if (unackedCount > 0) - { - messageAcknowledge - (unacked, getAcknowledgeMode() != org.apache.qpid.jms.Session.NO_ACKNOWLEDGE,setSyncBit); - clearUnacked(); - } - } - } - - void messageAcknowledge(final RangeSet ranges, final boolean accept) - { - messageAcknowledge(ranges,accept,false); - } - - void messageAcknowledge(final RangeSet ranges, final boolean accept, final boolean setSyncBit) - { - final Session ssn = getQpidSession(); - flushProcessed(ranges,accept); - if (accept) - { - ssn.messageAccept(ranges, UNRELIABLE, setSyncBit ? SYNC : NONE); - } - } - - /** - * Flush any outstanding commands. This causes session complete to be sent. - * @param ranges the range of command ids. - * @param batch true if batched. - */ - void flushProcessed(final RangeSet ranges, final boolean batch) - { - final Session ssn = getQpidSession(); - for (final Range range : ranges) - { - ssn.processed(range); - } - ssn.flushProcessed(batch ? BATCH : NONE); - } - - /** - * Bind a queue with an exchange. - * - * @param queueName Specifies the name of the queue to bind. If the queue name is empty, - * refers to the current - * queue for the session, which is the last declared queue. - * @param exchangeName The exchange name. - * @param routingKey Specifies the routing key for the binding. - * @param arguments 0_8 specific - */ - public void sendQueueBind(final AMQShortString queueName, final AMQShortString routingKey, - final FieldTable arguments, final AMQShortString exchangeName, - final AMQDestination destination, final boolean nowait) - throws AMQException - { - if (destination == null || destination.getDestSyntax() == DestSyntax.BURL) - { - Map args = FieldTableSupport.convertToMap(arguments); - - if(destination != null) - { - for (AMQShortString rk: destination.getBindingKeys()) - { - doSendQueueBind(queueName, exchangeName, args, rk); - } - if(!Arrays.asList(destination.getBindingKeys()).contains(routingKey)) - { - doSendQueueBind(queueName, exchangeName, args, routingKey); - } - } - else - { - doSendQueueBind(queueName, exchangeName, args, routingKey); - } - } - else - { - // Leaving this here to ensure the public method bindQueue in AMQSession.java works as expected. - List<Binding> bindings = new ArrayList<Binding>(); - bindings.addAll(destination.getNode().getBindings()); - - String defaultExchange = destination.getAddressType() == AMQDestination.TOPIC_TYPE ? - destination.getAddressName(): "amq.topic"; - - for (Binding binding: bindings) - { - // Currently there is a bug (QPID-3317) with setting up and tearing down x-bindings for link. - // The null check below is a way to side step that issue while fixing QPID-4146 - // Note this issue only affects producers. - if (binding.getQueue() == null && queueName == null) - { - continue; - } - String queue = binding.getQueue() == null? - queueName.asString(): binding.getQueue(); - - String exchange = binding.getExchange() == null ? - defaultExchange : - binding.getExchange(); - - _logger.debug("Binding queue : " + queue + - " exchange: " + exchange + - " using binding key " + binding.getBindingKey() + - " with args " + Strings.printMap(binding.getArgs())); - doBind(destination, binding, queue, exchange); - } - } - - if (!nowait) - { - // We need to sync so that we get notify of an error. - sync(); - } - } - - private void doSendQueueBind(final AMQShortString queueName, - final AMQShortString exchangeName, - final Map args, - final AMQShortString rk) - { - _logger.debug("Binding queue : " + queueName.toString() + - " exchange: " + exchangeName.toString() + - " using binding key " + rk.asString()); - getQpidSession().exchangeBind(queueName.toString(), - exchangeName.toString(), - rk.toString(), - args); - } - - - /** - * Close this session. - * - * @param timeout no used / 0_8 specific - * @throws AMQException - * @throws FailoverException - */ - public void sendClose(long timeout) throws AMQException, FailoverException - { - cancelTimerTask(); - flushAcknowledgments(); - try - { - getQpidSession().sync(); - getQpidSession().close(); - } - catch (SessionException se) - { - setCurrentException(se); - } - - AMQException amqe = getCurrentException(); - if (amqe != null) - { - throw amqe; - } - } - - /** - * Create a queue with a given name. - * - * @param name The queue name - * @param autoDelete If this field is set and the exclusive field is also set, - * then the queue is deleted when the connection closes. - * @param durable If set when creating a new queue, - * the queue will be marked as durable. - * @param exclusive Exclusive queues can only be used from one connection at a time. - * @param arguments Exclusive queues can only be used from one connection at a time. - * @throws AMQException - * @throws FailoverException - */ - public void sendCreateQueue(AMQShortString name, final boolean autoDelete, final boolean durable, - final boolean exclusive, Map<String, Object> arguments) throws AMQException, FailoverException - { - getQpidSession().queueDeclare(name.toString(), null, arguments, durable ? Option.DURABLE : Option.NONE, - autoDelete ? Option.AUTO_DELETE : Option.NONE, - exclusive ? Option.EXCLUSIVE : Option.NONE); - // We need to sync so that we get notify of an error. - sync(); - } - - /** - * This method asks the broker to redeliver all unacknowledged messages - * - * @throws AMQException - * @throws FailoverException - */ - public void sendRecover() throws AMQException, FailoverException - { - // release all unacked messages - RangeSet all = RangeSetFactory.createRangeSet(); - RangeSet delivered = gatherRangeSet(getUnacknowledgedMessageTags()); - RangeSet prefetched = gatherRangeSet(getPrefetchedMessageTags()); - for (Iterator<Range> deliveredIter = delivered.iterator(); deliveredIter.hasNext();) - { - Range range = deliveredIter.next(); - all.add(range); - } - for (Iterator<Range> prefetchedIter = prefetched.iterator(); prefetchedIter.hasNext();) - { - Range range = prefetchedIter.next(); - all.add(range); - } - flushProcessed(all, false); - getQpidSession().messageRelease(delivered, Option.SET_REDELIVERED); - getQpidSession().messageRelease(prefetched); - - // We need to sync so that we get notify of an error. - sync(); - } - - private RangeSet gatherRangeSet(ConcurrentLinkedQueue<Long> messageTags) - { - RangeSet ranges = RangeSetFactory.createRangeSet(); - while (true) - { - Long tag = messageTags.poll(); - if (tag == null) - { - break; - } - - ranges.add(tag.intValue()); - } - - return ranges; - } - - public void releaseForRollback() - { - if (_txSize > 0) - { - flushProcessed(_txRangeSet, false); - getQpidSession().messageRelease(_txRangeSet, Option.SET_REDELIVERED); - _txRangeSet.clear(); - _txSize = 0; - } - } - - /** - * Release (0_8 notion of Reject) an acquired message - * - * @param deliveryTag the message ID - * @param requeue always true - */ - public void rejectMessage(long deliveryTag, boolean requeue) - { - // The value of requeue is always true - RangeSet ranges = RangeSetFactory.createRangeSet(); - ranges.add((int) deliveryTag); - flushProcessed(ranges, false); - if (requeue) - { - getQpidSession().messageRelease(ranges); - } - else - { - getQpidSession().messageRelease(ranges, Option.SET_REDELIVERED); - } - //I don't think we need to sync - } - - /** - * Create an 0_10 message consumer - */ - public BasicMessageConsumer_0_10 createMessageConsumer(final AMQDestination destination, final int prefetchHigh, - final int prefetchLow, final boolean noLocal, - final boolean exclusive, String messageSelector, - final FieldTable rawSelector, final boolean noConsume, - final boolean autoClose) throws JMSException - { - return new BasicMessageConsumer_0_10(getChannelId(), getAMQConnection(), destination, messageSelector, noLocal, - getMessageFactoryRegistry(), this, rawSelector, prefetchHigh, prefetchLow, - exclusive, getAcknowledgeMode(), noConsume, autoClose); - } - - /** - * Bind a queue with an exchange. - */ - - public boolean isQueueBound(final AMQShortString exchangeName, final AMQShortString queueName, final AMQShortString routingKey) - { - return isQueueBound(exchangeName,queueName,routingKey,null); - } - - public boolean isQueueBound(final AMQDestination destination) - { - return isQueueBound(destination.getExchangeName(),destination.getAMQQueueName(),destination.getRoutingKey(),destination.getBindingKeys()); - } - - public boolean isQueueBound(final AMQShortString exchangeName, final AMQShortString queueName, final AMQShortString routingKey,AMQShortString[] bindingKeys) - { - String rk = null; - if (bindingKeys != null && bindingKeys.length>0) - { - rk = bindingKeys[0].toString(); - } - else if (routingKey != null) - { - rk = routingKey.toString(); - } - - return isQueueBound(exchangeName == null ? null : exchangeName.toString(),queueName == null ? null : queueName.toString(),rk,null); - } - - public boolean isQueueBound(final String exchangeName, final String queueName, final String bindingKey,Map<String,Object> args) - { - boolean res; - ExchangeBoundResult bindingQueryResult = - getQpidSession().exchangeBound(exchangeName,queueName, bindingKey, args).get(); - - if (bindingKey == null) - { - res = !(bindingQueryResult.getExchangeNotFound() || bindingQueryResult.getQueueNotFound()); - } - else - { - if (args == null) - { - res = !(bindingQueryResult.getExchangeNotFound() || bindingQueryResult.getKeyNotMatched() || bindingQueryResult.getQueueNotFound() || bindingQueryResult - .getQueueNotMatched()); - } - else - { - res = !(bindingQueryResult.getExchangeNotFound() || bindingQueryResult.getKeyNotMatched() || bindingQueryResult.getQueueNotFound() || bindingQueryResult - .getQueueNotMatched() || bindingQueryResult.getArgsNotMatched()); - } - } - return res; - } - - @Override - protected boolean isBound(AMQShortString exchangeName, AMQShortString amqQueueName, AMQShortString routingKey) - { - return isQueueBound(exchangeName, amqQueueName, routingKey); - } - - /** - * This method is invoked when a consumer is created - * Registers the consumer with the broker - */ - public void sendConsume(BasicMessageConsumer_0_10 consumer, AMQShortString queueName, - boolean nowait, int tag) - throws AMQException, FailoverException - { - queueName = preprocessAddressTopic(consumer, queueName); - boolean preAcquire = consumer.isPreAcquire(); - - AMQDestination destination = consumer.getDestination(); - long capacity = consumer.getCapacity(); - - Map<String, Object> arguments = FieldTable.convertToMap(consumer.getArguments()); - - Link link = destination.getLink(); - if (link != null && link.getSubscription() != null && link.getSubscription().getArgs() != null) - { - arguments.putAll(link.getSubscription().getArgs()); - } - - boolean acceptModeNone = getAcknowledgeMode() == NO_ACKNOWLEDGE; - - String queue = queueName == null ? destination.getAddressName() : queueName.toString(); - getQpidSession().messageSubscribe - (queue, String.valueOf(tag), - acceptModeNone ? MessageAcceptMode.NONE : MessageAcceptMode.EXPLICIT, - preAcquire ? MessageAcquireMode.PRE_ACQUIRED : MessageAcquireMode.NOT_ACQUIRED, null, 0, arguments, - consumer.isExclusive() ? Option.EXCLUSIVE : Option.NONE); - - String consumerTag = (consumer).getConsumerTagString(); - - if (capacity == 0) - { - getQpidSession().messageSetFlowMode(consumerTag, MessageFlowMode.CREDIT); - } - else - { - getQpidSession().messageSetFlowMode(consumerTag, MessageFlowMode.WINDOW); - } - getQpidSession().messageFlow(consumerTag, MessageCreditUnit.BYTE, 0xFFFFFFFF, - Option.UNRELIABLE); - - if(capacity > 0 && getDispatcher() != null && (isStarted() || isImmediatePrefetch())) - { - // set the flow - getQpidSession().messageFlow(consumerTag, - MessageCreditUnit.MESSAGE, - capacity, - Option.UNRELIABLE); - } - sync(); - } - - /** - * Create an 0_10 message producer - */ - public BasicMessageProducer_0_10 createMessageProducer(final Destination destination, final Boolean mandatory, - final Boolean immediate, final long producerId) throws JMSException - { - try - { - return new BasicMessageProducer_0_10(getAMQConnection(), (AMQDestination) destination, isTransacted(), getChannelId(), this, - producerId, immediate, mandatory); - } - catch (AMQException e) - { - throw toJMSException("Error creating producer",e); - } - catch(TransportException e) - { - throw toJMSException("Exception while creating message producer:" + e.getMessage(), e); - } - - } - - /** - * creates an exchange if it does not already exist - */ - public void sendExchangeDeclare(final AMQShortString name, final AMQShortString type, final boolean nowait, - boolean durable, boolean autoDelete, boolean internal) throws AMQException, FailoverException - { - //The 'internal' parameter is ignored on the 0-10 path, the protocol does not support it - sendExchangeDeclare(name.asString(), type.asString(), null, null, nowait, durable, autoDelete); - } - - public void sendExchangeDeclare(final AMQShortString name, final AMQShortString type, final boolean nowait, - boolean durable, boolean autoDelete, FieldTable arguments, final boolean passive) throws AMQException, FailoverException - { - sendExchangeDeclare(name.asString(), type.asString(), null, - arguments == null ? null : FieldTableSupport.convertToMap(arguments), - nowait, durable, autoDelete); - } - - - public void sendExchangeDeclare(final String name, final String type, - final String alternateExchange, final Map<String, Object> args, - final boolean nowait, boolean durable, boolean autoDelete) throws AMQException - { - getQpidSession().exchangeDeclare( - name, - type, - alternateExchange, - args, - name.toString().startsWith("amq.") ? Option.PASSIVE : Option.NONE, - durable ? Option.DURABLE : Option.NONE, - autoDelete ? Option.AUTO_DELETE : Option.NONE); - // We need to sync so that we get notify of an error. - if (!nowait) - { - sync(); - } - } - - /** - * deletes an exchange - */ - public void sendExchangeDelete(final String name, final boolean nowait) - throws AMQException, FailoverException - { - getQpidSession().exchangeDelete(name); - // We need to sync so that we get notify of an error. - if (!nowait) - { - sync(); - } - } - - /** - * Declare a queue with the given queueName - */ - public AMQShortString send0_10QueueDeclare(final AMQDestination amqd, final boolean noLocal, - final boolean nowait, boolean passive) - throws AMQException - { - AMQShortString queueName; - if (amqd.getAMQQueueName() == null) - { - // generate a name for this queue - queueName = new AMQShortString("TempQueue" + UUID.randomUUID()); - amqd.setQueueName(queueName); - } - else - { - queueName = amqd.getAMQQueueName(); - } - - if (amqd.getDestSyntax() == DestSyntax.BURL) - { - Map<String,Object> arguments = new HashMap<String,Object>(); - if (noLocal) - { - arguments.put(AddressHelper.NO_LOCAL, true); - } - - getQpidSession().queueDeclare(queueName.toString(), "" , arguments, - amqd.isAutoDelete() ? Option.AUTO_DELETE : Option.NONE, - amqd.isDurable() ? Option.DURABLE : Option.NONE, - amqd.isExclusive() ? Option.EXCLUSIVE : Option.NONE, - passive ? Option.PASSIVE : Option.NONE); - } - else - { - // This code is here to ensure address based destination work with the declareQueue public method in AMQSession.java - Node node = amqd.getNode(); - Map<String,Object> arguments = new HashMap<String,Object>(); - arguments.putAll((Map<? extends String, ? extends Object>) node.getDeclareArgs()); - if (arguments == null || arguments.get(AddressHelper.NO_LOCAL) == null) - { - arguments.put(AddressHelper.NO_LOCAL, noLocal); - } - getQpidSession().queueDeclare(queueName.toString(), node.getAlternateExchange() , - arguments, - node.isAutoDelete() ? Option.AUTO_DELETE : Option.NONE, - node.isDurable() ? Option.DURABLE : Option.NONE, - node.isExclusive() ? Option.EXCLUSIVE : Option.NONE); - } - - // passive --> false - if (!nowait) - { - // We need to sync so that we get notify of an error. - sync(); - } - return queueName; - } - - /** - * deletes a queue - */ - public void sendQueueDelete(final AMQShortString queueName) throws AMQException, FailoverException - { - getQpidSession().queueDelete(queueName.toString()); - // ifEmpty --> false - // ifUnused --> false - // We need to sync so that we get notify of an error. - sync(); - } - - /** - * Activate/deactivate the message flow for all the consumers of this session. - */ - public void sendSuspendChannel(boolean suspend) throws AMQException, FailoverException - { - if (suspend) - { - for (BasicMessageConsumer consumer : getConsumers()) - { - getQpidSession().messageStop(String.valueOf(consumer.getConsumerTag()), - Option.UNRELIABLE); - } - sync(); - } - else - { - for (BasicMessageConsumer_0_10 consumer : getConsumers()) - { - String consumerTag = String.valueOf(consumer.getConsumerTag()); - //only set if msg list is null - try - { - long capacity = consumer.getCapacity(); - - if (capacity == 0) - { - if (consumer.getMessageListener() != null) - { - getQpidSession().messageFlow(consumerTag, - MessageCreditUnit.MESSAGE, 1, - Option.UNRELIABLE); - } - } - else - { - getQpidSession() - .messageFlow(consumerTag, MessageCreditUnit.MESSAGE, - capacity, - Option.UNRELIABLE); - } - getQpidSession() - .messageFlow(consumerTag, MessageCreditUnit.BYTE, 0xFFFFFFFF, - Option.UNRELIABLE); - } - catch (Exception e) - { - throw new AMQException(AMQConstant.INTERNAL_ERROR, "Error while trying to get the listener", e); - } - } - } - // We need to sync so that we get notify of an error. - sync(); - } - - - public void sendRollback() throws AMQException, FailoverException - { - getQpidSession().txRollback(); - // We need to sync so that we get notify of an error. - sync(); - } - - //------ Private methods - /** - * Access to the underlying Qpid Session - * - * @return The associated Qpid Session. - */ - protected Session getQpidSession() - { - return _qpidSession; - } - - - /** - * Get the latest thrown exception. - * - * @throws SessionException get the latest thrown error. - */ - public AMQException getCurrentException() - { - AMQException amqe = null; - synchronized (_currentExceptionLock) - { - if (_currentException != null) - { - amqe = _currentException; - _currentException = null; - } - } - return amqe; - } - - public void opened(Session ssn) {} - - public void resumed(Session ssn) - { - _qpidConnection = ssn.getConnection(); - } - - public void message(Session ssn, MessageTransfer xfr) - { - messageReceived(new UnprocessedMessage_0_10(xfr)); - } - - public void exception(Session ssn, SessionException exc) - { - setCurrentException(exc); - } - - public void closed(Session ssn) - { - try - { - super.closed(null); - if (flushTask != null) - { - flushTask.cancel(); - flushTask = null; - } - } catch (Exception e) - { - _logger.error("Error closing JMS session", e); - } - } - - public AMQException getLastException() - { - return getCurrentException(); - } - - @Override - protected AMQShortString declareQueue(final AMQDestination amqd, - final boolean noLocal, final boolean nowait, final boolean passive) - throws AMQException - { - return new FailoverNoopSupport<AMQShortString, AMQException>( - new FailoverProtectedOperation<AMQShortString, AMQException>() - { - public AMQShortString execute() throws AMQException, FailoverException - { - // Generate the queue name if the destination indicates that a client generated name is to be used. - if (amqd.isNameRequired()) - { - String binddingKey = ""; - for(AMQShortString key : amqd.getBindingKeys()) - { - binddingKey = binddingKey + "_" + key.toString(); - } - amqd.setQueueName(new AMQShortString( binddingKey + "@" - + amqd.getExchangeName().toString() + "_" + UUID.randomUUID())); - } - return send0_10QueueDeclare(amqd, noLocal, nowait, passive); - } - }, getAMQConnection()).execute(); - } - - protected Long requestQueueDepth(AMQDestination amqd, boolean sync) - { - flushAcknowledgments(); - if (sync) - { - getQpidSession().sync(); - } - return getQpidSession().queueQuery(amqd.getQueueName()).get().getMessageCount(); - } - - - /** - * Store non committed messages for this session - * @param id - */ - @Override protected void addDeliveredMessage(long id) - { - _txRangeSet.add((int) id); - _txSize++; - } - - /** - * With 0.10 messages are consumed with window mode, we must send a completion - * before the window size is reached so credits don't dry up. - */ - protected void sendTxCompletionsIfNecessary() - { - // this is a heuristic, we may want to have that configurable - if (_txSize > 0 && (getAMQConnection().getMaxPrefetch() == 1 || - getAMQConnection().getMaxPrefetch() != 0 && _txSize % (getAMQConnection().getMaxPrefetch() / 2) == 0)) - { - // send completed so consumer credits don't dry up - messageAcknowledge(_txRangeSet, false); - } - } - - public void commitImpl() throws AMQException, FailoverException, TransportException - { - if( _txSize > 0 ) - { - messageAcknowledge(_txRangeSet, true); - _txRangeSet.clear(); - _txSize = 0; - } - - getQpidSession().setAutoSync(true); - try - { - getQpidSession().txCommit(); - } - finally - { - getQpidSession().setAutoSync(false); - } - // We need to sync so that we get notify of an error. - sync(); - } - - protected final boolean tagLE(long tag1, long tag2) - { - return Serial.le((int) tag1, (int) tag2); - } - - protected final boolean updateRollbackMark(long currentMark, long deliveryTag) - { - return Serial.lt((int) currentMark, (int) deliveryTag); - } - - public void sync() throws AMQException - { - try - { - getQpidSession().sync(); - } - catch (SessionException se) - { - setCurrentException(se); - } - - AMQException amqe = getCurrentException(); - if (amqe != null) - { - throw amqe; - } - } - - public void setCurrentException(SessionException se) - { - synchronized (_currentExceptionLock) - { - ExecutionException ee = se.getException(); - int code = AMQConstant.INTERNAL_ERROR.getCode(); - if (ee != null) - { - code = ee.getErrorCode().getValue(); - } - AMQException amqe = new AMQException(AMQConstant.getConstant(code), _isHardError, se.getMessage(), se.getCause()); - _currentException = amqe; - } - if (!_isHardError) - { - cancelTimerTask(); - stopDispatcherThread(); - try - { - closed(_currentException); - } - catch(Exception e) - { - _logger.warn("Error closing session", e); - } - } - getAMQConnection().exceptionReceived(_currentException); - } - - public AMQMessageDelegateFactory getMessageDelegateFactory() - { - return AMQMessageDelegateFactory.FACTORY_0_10; - } - - @Override - public boolean isExchangeExist(AMQDestination dest,boolean assertNode) throws AMQException - { - boolean match = true; - ExchangeQueryResult result = getQpidSession().exchangeQuery(dest.getAddressName(), Option.NONE).get(); - match = !result.getNotFound(); - Node node = dest.getNode(); - - if (match) - { - if (assertNode) - { - match = (result.getDurable() == node.isDurable()) && - (node.getExchangeType() != null && - node.getExchangeType().equals(result.getType())) && - (matchProps(result.getArguments(),node.getDeclareArgs())); - } - else - { - _logger.debug("Setting Exchange type " + result.getType()); - node.setExchangeType(result.getType()); - dest.setExchangeClass(new AMQShortString(result.getType())); - } - } - - if (assertNode) - { - if (!match) - { - throw new AMQException("Assert failed for address : " + dest +", Result was : " + result); - } - } - - return match; - } - - @Override - public boolean isQueueExist(AMQDestination dest, boolean assertNode) throws AMQException - { - Node node = dest.getNode(); - return isQueueExist(dest.getAddressName(), assertNode, - node.isDurable(), node.isAutoDelete(), - node.isExclusive(), node.getDeclareArgs()); - } - - public boolean isQueueExist(String queueName, boolean assertNode, - boolean durable, boolean autoDelete, - boolean exclusive, Map<String, Object> args) throws AMQException - { - boolean match = true; - try - { - QueueQueryResult result = getQpidSession().queueQuery(queueName, Option.NONE).get(); - match = queueName.equals(result.getQueue()); - - if (match && assertNode) - { - match = (result.getDurable() == durable) && - (result.getAutoDelete() == autoDelete) && - (result.getExclusive() == exclusive) && - (matchProps(result.getArguments(),args)); - } - - if (assertNode) - { - if (!match) - { - throw new AMQException("Assert failed for queue : " + queueName +", Result was : " + result); - } - } - } - catch(SessionException e) - { - if (e.getException().getErrorCode() == ExecutionErrorCode.RESOURCE_DELETED - || e.getException().getErrorCode() == ExecutionErrorCode.NOT_FOUND) - { - match = false; - } - else - { - throw new AMQException(AMQConstant.getConstant(e.getException().getErrorCode().getValue()), - "Error querying queue",e); - } - } - return match; - } - - private boolean matchProps(Map<String,Object> target,Map<String,Object> source) - { - boolean match = true; - for (String key: source.keySet()) - { - match = target.containsKey(key) && - (target.get(key).equals(source.get(key)) - || (target.get(key) instanceof Number) - && source.get(key) instanceof Number && - (((Number) target.get(key)).longValue()) == (((Number) source.get(key)).longValue())); - - if (!match) - { - StringBuffer buf = new StringBuffer(); - buf.append("Property given in address did not match with the args sent by the broker."); - buf.append(" Expected { ").append(key).append(" : ").append(source.get(key)).append(" }, "); - buf.append(" Actual { ").append(key).append(" : ").append(target.get(key)).append(" }"); - _logger.debug(buf.toString()); - return match; - } - } - - return match; - } - - @Override - public int resolveAddressType(AMQDestination dest) throws AMQException - { - int type = dest.getAddressType(); - String name = dest.getAddressName(); - if (type != AMQDestination.UNKNOWN_TYPE) - { - return type; - } - else - { - ExchangeBoundResult result = getQpidSession().exchangeBound(name,name,null,null).get(); - if (result.getQueueNotFound() && result.getExchangeNotFound()) { - //neither a queue nor an exchange exists with that name; treat it as a queue - type = AMQDestination.QUEUE_TYPE; - } else if (result.getExchangeNotFound()) { - //name refers to a queue - type = AMQDestination.QUEUE_TYPE; - } else if (result.getQueueNotFound()) { - //name refers to an exchange - type = AMQDestination.TOPIC_TYPE; - } else { - //both a queue and exchange exist for that name - throw new AMQException("Ambiguous address, please specify queue or topic as node type"); - } - dest.setAddressType(type); - return type; - } - } - - @Override - void createSubscriptionQueue(AMQDestination dest, boolean noLocal, String messageSelector) throws AMQException - { - Link link = dest.getLink(); - String queueName = dest.getQueueName(); - - if (queueName == null) - { - queueName = link.getName() == null ? "TempQueue" + UUID.randomUUID() : link.getName(); - dest.setQueueName(new AMQShortString(queueName)); - } - - SubscriptionQueue queueProps = link.getSubscriptionQueue(); - Map<String,Object> arguments = queueProps.getDeclareArgs(); - if (!arguments.containsKey((AddressHelper.NO_LOCAL))) - { - arguments.put(AddressHelper.NO_LOCAL, noLocal); - } - - if (link.isDurable() && queueName.startsWith("TempQueue")) - { - throw new AMQException("You cannot mark a subscription queue as durable without providing a name for the link."); - } - - getQpidSession().queueDeclare(queueName, - queueProps.getAlternateExchange(), arguments, - queueProps.isAutoDelete() ? Option.AUTO_DELETE : Option.NONE, - link.isDurable() ? Option.DURABLE : Option.NONE, - queueProps.isExclusive() ? Option.EXCLUSIVE : Option.NONE); - - Map<String,Object> bindingArguments = new HashMap<String, Object>(); - bindingArguments.put(AMQPFilterTypes.JMS_SELECTOR.getValue().toString(), messageSelector == null ? "" : messageSelector); - getQpidSession().exchangeBind(queueName, - dest.getAddressName(), - dest.getSubject(), - bindingArguments); - } - - protected void acknowledgeImpl() - { - RangeSet ranges = gatherRangeSet(getUnacknowledgedMessageTags()); - - if(ranges.size() > 0 ) - { - messageAcknowledge(ranges, true); - getQpidSession().sync(); - } - } - - @Override - void resubscribe() throws AMQException - { - // Also reset the delivery tag tracker, to insure we dont - // return the first <total number of msgs received on session> - // messages sent by the brokers following the first rollback - // after failover - getHighestDeliveryTag().set(-1); - // Clear txRangeSet/unacknowledgedMessageTags so we don't complete commands corresponding to - //messages that came from the old broker. - _txRangeSet.clear(); - _txSize = 0; - getUnacknowledgedMessageTags().clear(); - getPrefetchedMessageTags().clear(); - super.resubscribe(); - getQpidSession().sync(); - } - - @Override - void stop() throws AMQException - { - super.stop(); - setUsingDispatcherForCleanup(true); - drainDispatchQueue(); - setUsingDispatcherForCleanup(false); - - for (BasicMessageConsumer consumer : getConsumers()) - { - List<Long> tags = consumer.drainReceiverQueueAndRetrieveDeliveryTags(); - getPrefetchedMessageTags().addAll(tags); - } - - RangeSet delivered = gatherRangeSet(getUnacknowledgedMessageTags()); - RangeSet prefetched = gatherRangeSet(getPrefetchedMessageTags()); - RangeSet all = RangeSetFactory.createRangeSet(delivered.size() - + prefetched.size()); - - for (Iterator<Range> deliveredIter = delivered.iterator(); deliveredIter.hasNext();) - { - Range range = deliveredIter.next(); - all.add(range); - } - - for (Iterator<Range> prefetchedIter = prefetched.iterator(); prefetchedIter.hasNext();) - { - Range range = prefetchedIter.next(); - all.add(range); - } - - flushProcessed(all, false); - getQpidSession().messageRelease(delivered,Option.SET_REDELIVERED); - getQpidSession().messageRelease(prefetched); - sync(); - } - - @Override - public boolean isFlowBlocked() - { - return _qpidSession.isFlowBlocked(); - } - - @Override - public void setFlowControl(boolean active) - { - // Supported by 0-8..0-9-1 only - throw new UnsupportedOperationException("Operation not supported by this protocol"); - } - - private void cancelTimerTask() - { - if (flushTask != null) - { - flushTask.cancel(); - flushTask = null; - } - } - - @Override - protected void handleQueueNodeCreation(AMQDestination dest, boolean noLocal) throws AMQException - { - Node node = dest.getNode(); - Map<String,Object> arguments = node.getDeclareArgs(); - if (!arguments.containsKey((AddressHelper.NO_LOCAL))) - { - arguments.put(AddressHelper.NO_LOCAL, noLocal); - } - getQpidSession().queueDeclare(dest.getAddressName(), - node.getAlternateExchange(), arguments, - node.isAutoDelete() ? Option.AUTO_DELETE : Option.NONE, - node.isDurable() ? Option.DURABLE : Option.NONE, - node.isExclusive() ? Option.EXCLUSIVE : Option.NONE); - - createBindings(dest, dest.getNode().getBindings()); - sync(); - } - - @Override - void handleExchangeNodeCreation(AMQDestination dest) throws AMQException - { - Node node = dest.getNode(); - sendExchangeDeclare(dest.getAddressName(), - node.getExchangeType(), - node.getAlternateExchange(), - node.getDeclareArgs(), - false, - node.isDurable(), - node.isAutoDelete()); - - // If bindings are specified without a queue name and is called by the producer, - // the broker will send an exception as expected. - createBindings(dest, dest.getNode().getBindings()); - sync(); - } - - protected void doBind(final AMQDestination dest, final Binding binding, final String queue, final String exchange) - { - getQpidSession().exchangeBind(queue, - exchange, - binding.getBindingKey(), - binding.getArgs()); - } - - void handleLinkDelete(AMQDestination dest) throws AMQException - { - // We need to destroy link bindings - String defaultExchangeForBinding = dest.getAddressType() == AMQDestination.TOPIC_TYPE ? dest - .getAddressName() : "amq.topic"; - - String defaultQueueName = null; - if (AMQDestination.QUEUE_TYPE == dest.getAddressType()) - { - defaultQueueName = dest.getQueueName(); - } - else - { - defaultQueueName = dest.getLink().getName() != null ? dest.getLink().getName() : dest.getQueueName(); - } - - for (Binding binding: dest.getLink().getBindings()) - { - String queue = binding.getQueue() == null? - defaultQueueName: binding.getQueue(); - - String exchange = binding.getExchange() == null ? - defaultExchangeForBinding : - binding.getExchange(); - - if (_logger.isDebugEnabled()) - { - _logger.debug("Unbinding queue : " + queue + - " exchange: " + exchange + - " using binding key " + binding.getBindingKey() + - " with args " + Strings.printMap(binding.getArgs())); - } - getQpidSession().exchangeUnbind(queue, exchange, - binding.getBindingKey()); - } - } - - void deleteSubscriptionQueue(AMQDestination dest) throws AMQException - { - // We need to delete the subscription queue. - if (dest.getAddressType() == AMQDestination.TOPIC_TYPE && - dest.getLink().getSubscriptionQueue().isExclusive() && - isQueueExist(dest.getQueueName(), false, false, false, false, null)) - { - getQpidSession().queueDelete(dest.getQueueName()); - } - } - - @Override - void handleNodeDelete(AMQDestination dest) throws AMQException - { - if (AMQDestination.TOPIC_TYPE == dest.getAddressType()) - { - if (isExchangeExist(dest,false)) - { - getQpidSession().exchangeDelete(dest.getAddressName()); - dest.setAddressResolved(0); - } - } - else - { - if (isQueueExist(dest,false)) - { - getQpidSession().queueDelete(dest.getAddressName()); - dest.setAddressResolved(0); - } - } - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQSession_0_8.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQSession_0_8.java deleted file mode 100644 index 5fb9329af7..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQSession_0_8.java +++ /dev/null @@ -1,1565 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; - - -import static org.apache.qpid.configuration.ClientProperties.DEFAULT_FLOW_CONTROL_WAIT_FAILURE; -import static org.apache.qpid.configuration.ClientProperties.DEFAULT_FLOW_CONTROL_WAIT_NOTIFY_PERIOD; -import static org.apache.qpid.configuration.ClientProperties.QPID_FLOW_CONTROL_WAIT_FAILURE; -import static org.apache.qpid.configuration.ClientProperties.QPID_FLOW_CONTROL_WAIT_NOTIFY_PERIOD; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; - -import javax.jms.Destination; -import javax.jms.JMSException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.AMQUndeliveredException; -import org.apache.qpid.client.failover.FailoverException; -import org.apache.qpid.client.failover.FailoverNoopSupport; -import org.apache.qpid.client.failover.FailoverProtectedOperation; -import org.apache.qpid.client.failover.FailoverRetrySupport; -import org.apache.qpid.client.message.AMQMessageDelegateFactory; -import org.apache.qpid.client.message.AbstractJMSMessage; -import org.apache.qpid.client.message.MessageFactoryRegistry; -import org.apache.qpid.client.message.ReturnMessage; -import org.apache.qpid.client.message.UnprocessedMessage; -import org.apache.qpid.client.messaging.address.AddressHelper; -import org.apache.qpid.client.messaging.address.Link; -import org.apache.qpid.client.messaging.address.Node; -import org.apache.qpid.client.protocol.AMQProtocolHandler; -import org.apache.qpid.client.state.AMQState; -import org.apache.qpid.client.state.AMQStateManager; -import org.apache.qpid.client.state.listener.SpecificMethodFrameListener; -import org.apache.qpid.common.AMQPFilterTypes; -import org.apache.qpid.configuration.ClientProperties; -import org.apache.qpid.framing.*; -import org.apache.qpid.jms.Session; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.transport.TransportException; -import org.apache.qpid.util.Strings; - -public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMessageProducer_0_8> -{ - /** Used for debugging. */ - private static final Logger _logger = LoggerFactory.getLogger(AMQSession.class); - - public static final String QPID_SYNC_AFTER_CLIENT_ACK = "qpid.sync_after_client.ack"; - - private final boolean _syncAfterClientAck = - Boolean.parseBoolean(System.getProperty(QPID_SYNC_AFTER_CLIENT_ACK, "true")); - - private final boolean _useLegacyQueueDepthBehaviour = - Boolean.parseBoolean(System.getProperty(ClientProperties.QPID_USE_LEGACY_GETQUEUEDEPTH_BEHAVIOUR, "false")); - - /** - * The period to wait while flow controlled before sending a log message confirming that the session is still - * waiting on flow control being revoked - */ - private final long _flowControlWaitPeriod = Long.getLong(QPID_FLOW_CONTROL_WAIT_NOTIFY_PERIOD, - DEFAULT_FLOW_CONTROL_WAIT_NOTIFY_PERIOD); - - /** - * The period to wait while flow controlled before declaring a failure - */ - private final long _flowControlWaitFailure = Long.getLong(QPID_FLOW_CONTROL_WAIT_FAILURE, - DEFAULT_FLOW_CONTROL_WAIT_FAILURE); - private AtomicInteger _currentPrefetch = new AtomicInteger(); - - /** Flow control */ - private FlowControlIndicator _flowControl = new FlowControlIndicator(); - private final AtomicBoolean _creditChanged = new AtomicBoolean(); - - /** - * Creates a new session on a connection. - * - * @param con The connection on which to create the session. - * @param channelId The unique identifier for the session. - * @param transacted Indicates whether or not the session is transactional. - * @param acknowledgeMode The acknowledgement mode for the session. - * @param messageFactoryRegistry The message factory factory for the session. - * @param defaultPrefetchHighMark The maximum number of messages to prefetched before suspending the session. - * @param defaultPrefetchLowMark The number of prefetched messages at which to resume the session. - */ - protected AMQSession_0_8(AMQConnection con, int channelId, boolean transacted, int acknowledgeMode, - MessageFactoryRegistry messageFactoryRegistry, int defaultPrefetchHighMark, int defaultPrefetchLowMark) - { - - super(con,channelId,transacted,acknowledgeMode,messageFactoryRegistry,defaultPrefetchHighMark,defaultPrefetchLowMark); - _currentPrefetch.set(0); - } - - /** - * Creates a new session on a connection with the default message factory factory. - * - * @param con The connection on which to create the session. - * @param channelId The unique identifier for the session. - * @param transacted Indicates whether or not the session is transactional. - * @param acknowledgeMode The acknowledgement mode for the session. - * @param defaultPrefetchHigh The maximum number of messages to prefetched before suspending the session. - * @param defaultPrefetchLow The number of prefetched messages at which to resume the session. - */ - AMQSession_0_8(AMQConnection con, int channelId, boolean transacted, int acknowledgeMode, int defaultPrefetchHigh, - int defaultPrefetchLow) - { - this(con, channelId, transacted, acknowledgeMode, MessageFactoryRegistry.newDefaultRegistry(), defaultPrefetchHigh, - defaultPrefetchLow); - } - - private ProtocolVersion getProtocolVersion() - { - return getProtocolHandler().getProtocolVersion(); - } - - protected void acknowledgeImpl() throws JMSException - { - boolean syncRequired = false; - try - { - reduceCreditAfterAcknowledge(); - } - catch (AMQException e) - { - throw new JMSAMQException(e); - } - while (true) - { - Long tag = getUnacknowledgedMessageTags().poll(); - if (tag == null) - { - break; - } - - acknowledgeMessage(tag, false); - syncRequired = true; - } - _currentPrefetch.set(0); - try - { - if (syncRequired && _syncAfterClientAck) - { - sync(); - } - } - catch (AMQException a) - { - throw new JMSAMQException("Failed to sync after acknowledge", a); - } - } - - public void acknowledgeMessage(long deliveryTag, boolean multiple) - { - BasicAckBody body = getMethodRegistry().createBasicAckBody(deliveryTag, multiple); - - final AMQFrame ackFrame = body.generateFrame(getChannelId()); - - if (_logger.isDebugEnabled()) - { - _logger.debug("Sending ack for delivery tag " + deliveryTag + " on channel " + getChannelId()); - } - - getProtocolHandler().writeFrame(ackFrame, !isTransacted()); - getUnacknowledgedMessageTags().remove(deliveryTag); - } - - public void sendQueueBind(final AMQShortString queueName, final AMQShortString routingKey, final FieldTable arguments, - final AMQShortString exchangeName, final AMQDestination destination, - final boolean nowait) throws AMQException, FailoverException - { - if (destination == null || destination.getDestSyntax() == AMQDestination.DestSyntax.BURL) - { - - getProtocolHandler().syncWrite(getProtocolHandler().getMethodRegistry().createQueueBindBody - (getTicket(), queueName, exchangeName, routingKey, false, arguments). - generateFrame(getChannelId()), QueueBindOkBody.class); - - } - else - { - // Leaving this here to ensure the public method bindQueue in AMQSession.java works as expected. - List<AMQDestination.Binding> bindings = new ArrayList<AMQDestination.Binding>(); - bindings.addAll(destination.getNode().getBindings()); - - String defaultExchange = destination.getAddressType() == AMQDestination.TOPIC_TYPE ? - destination.getAddressName(): "amq.topic"; - - for (AMQDestination.Binding binding: bindings) - { - // Currently there is a bug (QPID-3317) with setting up and tearing down x-bindings for link. - // The null check below is a way to side step that issue while fixing QPID-4146 - // Note this issue only affects producers. - if (binding.getQueue() == null && queueName == null) - { - continue; - } - String queue = binding.getQueue() == null? - queueName.asString(): binding.getQueue(); - - String exchange = binding.getExchange() == null ? - defaultExchange : - binding.getExchange(); - - _logger.debug("Binding queue : " + queue + - " exchange: " + exchange + - " using binding key " + binding.getBindingKey() + - " with args " + Strings.printMap(binding.getArgs())); - doBind(destination, binding, queue, exchange); - } - } - } - - public void sendClose(long timeout) throws AMQException, FailoverException - { - // we also need to check the state manager for 08/09 as the - // _connection variable may not be updated in time by the error receiving - // thread. - // We can't close the session if we are already in the process of - // closing/closed the connection. - - if (!(getProtocolHandler().getStateManager().getCurrentState().equals(AMQState.CONNECTION_CLOSED) - || getProtocolHandler().getStateManager().getCurrentState().equals(AMQState.CONNECTION_CLOSING))) - { - - getProtocolHandler().closeSession(this); - getProtocolHandler().syncWrite(getProtocolHandler().getMethodRegistry().createChannelCloseBody(AMQConstant.REPLY_SUCCESS.getCode(), - new AMQShortString("JMS client closing channel"), 0, 0).generateFrame(getChannelId()), - ChannelCloseOkBody.class, timeout); - // When control resumes at this point, a reply will have been received that - // indicates the broker has closed the channel successfully. - } - } - - public void commitImpl() throws AMQException, FailoverException, TransportException - { - // Acknowledge all delivered messages - while (true) - { - Long tag = getDeliveredMessageTags().poll(); - if (tag == null) - { - break; - } - - acknowledgeMessage(tag, false); - } - - final AMQProtocolHandler handler = getProtocolHandler(); - reduceCreditAfterAcknowledge(); - handler.syncWrite(getProtocolHandler().getMethodRegistry().createTxCommitBody().generateFrame(getChannelId()), TxCommitOkBody.class); - _currentPrefetch.set(0); - } - - public void sendCreateQueue(AMQShortString name, final boolean autoDelete, final boolean durable, final boolean exclusive, final Map<String, Object> arguments) throws AMQException, - FailoverException - { - FieldTable table = null; - if(arguments != null && !arguments.isEmpty()) - { - table = new FieldTable(); - for(Map.Entry<String, Object> entry : arguments.entrySet()) - { - table.setObject(entry.getKey(), entry.getValue()); - } - } - sendQueueDeclare(name, durable, exclusive, autoDelete, table, false); - } - - public void sendRecover() throws AMQException, FailoverException - { - enforceRejectBehaviourDuringRecover(); - getPrefetchedMessageTags().clear(); - getUnacknowledgedMessageTags().clear(); - - if (isStrictAMQP()) - { - // We can't use the BasicRecoverBody-OK method as it isn't part of the spec. - - BasicRecoverBody body = getMethodRegistry().createBasicRecoverBody(false); - getAMQConnection().getProtocolHandler().writeFrame(body.generateFrame(getChannelId())); - _logger.warn("Session Recover cannot be guaranteed with STRICT_AMQP. Messages may arrive out of order."); - } - else - { - // in Qpid the 0-8 spec was hacked to have a recover-ok method... this is bad - // in 0-9 we used the cleaner addition of a new sync recover method with its own ok - if(getProtocolHandler().getProtocolVersion().equals(ProtocolVersion.v8_0)) - { - BasicRecoverBody body = getMethodRegistry().createBasicRecoverBody(false); - getAMQConnection().getProtocolHandler().syncWrite(body.generateFrame(getChannelId()), BasicRecoverSyncOkBody.class); - } - else - { - BasicRecoverSyncBody body = getMethodRegistry().createBasicRecoverSyncBody(false); - getAMQConnection().getProtocolHandler().syncWrite(body.generateFrame(getChannelId()), BasicRecoverSyncOkBody.class); - } - } - } - - private void enforceRejectBehaviourDuringRecover() - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Prefetched message: _unacknowledgedMessageTags :" + getUnacknowledgedMessageTags()); - } - boolean messageListenerFound = false; - boolean serverRejectBehaviourFound = false; - for(BasicMessageConsumer_0_8 consumer : getConsumers()) - { - if (consumer.isMessageListenerSet()) - { - messageListenerFound = true; - } - if (RejectBehaviour.SERVER.equals(consumer.getRejectBehaviour())) - { - serverRejectBehaviourFound = true; - } - } - - if (serverRejectBehaviourFound) - { - //reject(false) any messages we don't want returned again - switch(getAcknowledgeMode()) - { - case Session.DUPS_OK_ACKNOWLEDGE: - case Session.AUTO_ACKNOWLEDGE: - if (!messageListenerFound) - { - break; - } - case Session.CLIENT_ACKNOWLEDGE: - for(Long tag : getUnacknowledgedMessageTags()) - { - rejectMessage(tag, false); - } - break; - } - } - } - - public void releaseForRollback() - { - // Reject all the messages that have been received in this session and - // have not yet been acknowledged. Should look to remove - // _deliveredMessageTags and use _txRangeSet as used by 0-10. - // Otherwise messages will be able to arrive out of order to a second - // consumer on the queue. Whilst this is within the JMS spec it is not - // user friendly and avoidable. - boolean normalRejectBehaviour = true; - for (BasicMessageConsumer_0_8 consumer : getConsumers()) - { - if(RejectBehaviour.SERVER.equals(consumer.getRejectBehaviour())) - { - normalRejectBehaviour = false; - //no need to consult other consumers now, found server behaviour. - break; - } - } - - while (true) - { - Long tag = getDeliveredMessageTags().poll(); - if (tag == null) - { - break; - } - - rejectMessage(tag, normalRejectBehaviour); - } - } - - public void rejectMessage(long deliveryTag, boolean requeue) - { - if ((getAcknowledgeMode() == CLIENT_ACKNOWLEDGE) || (getAcknowledgeMode() == SESSION_TRANSACTED)|| - ((getAcknowledgeMode() == AUTO_ACKNOWLEDGE || getAcknowledgeMode() == DUPS_OK_ACKNOWLEDGE ) && hasMessageListeners())) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Rejecting delivery tag:" + deliveryTag + ":SessionHC:" + this.hashCode()); - } - - BasicRejectBody body = getMethodRegistry().createBasicRejectBody(deliveryTag, requeue); - AMQFrame frame = body.generateFrame(getChannelId()); - - getAMQConnection().getProtocolHandler().writeFrame(frame); - } - } - - public boolean isQueueBound(final AMQDestination destination) throws JMSException - { - return isQueueBound(destination.getExchangeName(),destination.getAMQQueueName(),destination.getAMQQueueName()); - } - - - public boolean isQueueBound(final AMQShortString exchangeName, final AMQShortString queueName, final AMQShortString routingKey) - throws JMSException - { - try - { - AMQMethodEvent response = new FailoverRetrySupport<AMQMethodEvent, AMQException>( - new FailoverProtectedOperation<AMQMethodEvent, AMQException>() - { - public AMQMethodEvent execute() throws AMQException, FailoverException - { - return sendExchangeBound(exchangeName, routingKey, queueName); - - } - }, getAMQConnection()).execute(); - - // Extract and return the response code from the query. - ExchangeBoundOkBody responseBody = (ExchangeBoundOkBody) response.getMethod(); - - return (responseBody.getReplyCode() == 0); - } - catch (AMQException e) - { - throw new JMSAMQException("Queue bound query failed: " + e.getMessage(), e); - } - } - - /** - * Checks if a particular queue is bound to an exchange with a given key. - * - * Returns false if not connected to a Qpid broker which supports the necessary AMQP extension. - */ - @Override - protected boolean isBound(final AMQShortString exchangeName, final AMQShortString queueName, final AMQShortString routingKey) - throws AMQException - { - if(!getAMQConnection().getDelegate().supportsIsBound()) - { - return false; - } - - AMQMethodEvent response = new FailoverNoopSupport<AMQMethodEvent, AMQException>( - new FailoverProtectedOperation<AMQMethodEvent, AMQException>() - { - public AMQMethodEvent execute() throws AMQException, FailoverException - { - return sendExchangeBound(exchangeName, routingKey, queueName); - - } - }, getAMQConnection()).execute(); - - // Extract and return the response code from the query. - ExchangeBoundOkBody responseBody = (ExchangeBoundOkBody) response.getMethod(); - - return (responseBody.getReplyCode() == 0); - } - - - protected boolean exchangeExists(final AMQShortString exchangeName) - throws AMQException - { - if(!getAMQConnection().getDelegate().supportsIsBound()) - { - return false; - } - - AMQMethodEvent response = new FailoverNoopSupport<AMQMethodEvent, AMQException>( - new FailoverProtectedOperation<AMQMethodEvent, AMQException>() - { - public AMQMethodEvent execute() throws AMQException, FailoverException - { - return sendExchangeBound(exchangeName, null, null); - - } - }, getAMQConnection()).execute(); - - // Extract and return the response code from the query. - ExchangeBoundOkBody responseBody = (ExchangeBoundOkBody) response.getMethod(); - - // valid if no issues, or just no bindings - return (responseBody.getReplyCode() == 0 || responseBody.getReplyCode() == 3); - } - - private AMQMethodEvent sendExchangeBound(AMQShortString exchangeName, - AMQShortString routingKey, - AMQShortString queueName) throws AMQException, FailoverException - { - AMQFrame boundFrame = getProtocolHandler().getMethodRegistry().createExchangeBoundBody - (exchangeName, routingKey, queueName).generateFrame(getChannelId()); - - return getProtocolHandler().syncWrite(boundFrame, ExchangeBoundOkBody.class); - } - - @Override - public void sendConsume(BasicMessageConsumer_0_8 consumer, - AMQShortString queueName, - boolean nowait, - int tag) throws AMQException, FailoverException - { - queueName = preprocessAddressTopic(consumer, queueName); - - AMQDestination destination = consumer.getDestination(); - - Map<String, Object> arguments = FieldTable.convertToMap(consumer.getArguments()); - - Link link = destination.getLink(); - if (link != null && link.getSubscription() != null && link.getSubscription().getArgs() != null) - { - arguments.putAll(link.getSubscription().getArgs()); - } - - BasicConsumeBody body = getMethodRegistry().createBasicConsumeBody(getTicket(), - queueName, - new AMQShortString(String.valueOf(tag)), - consumer.isNoLocal(), - consumer.getAcknowledgeMode() == Session.NO_ACKNOWLEDGE, - consumer.isExclusive(), - nowait, - FieldTable.convertToFieldTable(arguments)); - - - AMQFrame jmsConsume = body.generateFrame(getChannelId()); - - if (nowait) - { - getProtocolHandler().writeFrame(jmsConsume); - } - else - { - getProtocolHandler().syncWrite(jmsConsume, BasicConsumeOkBody.class); - } - } - - @Override - void createSubscriptionQueue(AMQDestination dest, boolean noLocal, String messageSelector) throws AMQException - { - final Link link = dest.getLink(); - final String queueName ; - - if (dest.getQueueName() == null) - { - queueName = link.getName() == null ? "TempQueue" + UUID.randomUUID() : link.getName(); - dest.setQueueName(new AMQShortString(queueName)); - } - else - { - queueName = dest.getQueueName(); - } - - final Link.SubscriptionQueue queueProps = link.getSubscriptionQueue(); - final Map<String,Object> arguments = queueProps.getDeclareArgs(); - if (!arguments.containsKey((AddressHelper.NO_LOCAL))) - { - arguments.put(AddressHelper.NO_LOCAL, noLocal); - } - - if (link.isDurable() && queueName.startsWith("TempQueue")) - { - throw new AMQException("You cannot mark a subscription queue as durable without providing a name for the link."); - } - - (new FailoverNoopSupport<Void, AMQException>( - new FailoverProtectedOperation<Void, AMQException>() - { - public Void execute() throws AMQException, FailoverException - { - - // not setting alternate exchange - sendQueueDeclare(AMQShortString.valueOf(queueName), - link.isDurable(), - queueProps.isExclusive(), - queueProps.isAutoDelete(), - FieldTable.convertToFieldTable(arguments), - false); - - return null; - } - }, getAMQConnection())).execute(); - - - Map<String,Object> bindingArguments = new HashMap<String, Object>(); - bindingArguments.put(AMQPFilterTypes.JMS_SELECTOR.getValue().toString(), messageSelector == null ? "" : messageSelector); - - final AMQDestination.Binding binding = new AMQDestination.Binding(dest.getAddressName(), queueName, dest.getSubject(), bindingArguments); - doBind(dest, binding, queueName, dest.getAddressName()); - - } - - @Override - public void sendExchangeDeclare(final AMQShortString name, final AMQShortString type, final boolean nowait, - boolean durable, boolean autoDelete, boolean internal) throws AMQException, FailoverException - { - //The 'noWait' parameter is only used on the 0-10 path, it is ignored on the 0-8/0-9/0-9-1 path - - ExchangeDeclareBody body = getMethodRegistry().createExchangeDeclareBody(getTicket(),name,type, - name.toString().startsWith("amq."), - durable, autoDelete, internal, false, null); - AMQFrame exchangeDeclare = body.generateFrame(getChannelId()); - - getProtocolHandler().syncWrite(exchangeDeclare, ExchangeDeclareOkBody.class); - } - - @Override - public void sendExchangeDeclare(final AMQShortString name, final AMQShortString type, final boolean nowait, - boolean durable, boolean autoDelete, FieldTable arguments, final boolean passive) throws AMQException, FailoverException - { - //The 'noWait' parameter is only used on the 0-10 path, it is ignored on the 0-8/0-9/0-9-1 path - - MethodRegistry methodRegistry = getMethodRegistry(); - ExchangeDeclareBody body = methodRegistry.createExchangeDeclareBody(getTicket(), - name, - type, - passive || name.toString().startsWith("amq."), - durable, - autoDelete, - false, - false, - arguments); - AMQFrame exchangeDeclare = body.generateFrame(getChannelId()); - - getProtocolHandler().syncWrite(exchangeDeclare, ExchangeDeclareOkBody.class); - } - - public void sendExchangeDelete(final String name) throws AMQException, FailoverException - { - ExchangeDeleteBody body = - getMethodRegistry().createExchangeDeleteBody(getTicket(),AMQShortString.valueOf(name),false, false); - AMQFrame exchangeDeclare = body.generateFrame(getChannelId()); - - getProtocolHandler().syncWrite(exchangeDeclare, ExchangeDeclareOkBody.class); - } - - private void sendQueueDeclare(final AMQDestination amqd, boolean passive) throws AMQException, FailoverException - { - AMQShortString queueName = amqd.getAMQQueueName(); - boolean durable = amqd.isDurable(); - boolean exclusive = amqd.isExclusive(); - boolean autoDelete = amqd.isAutoDelete(); - FieldTable arguments = null; - sendQueueDeclare(queueName, durable, exclusive, autoDelete, arguments, passive); - } - - private void sendQueueDeclare(final AMQShortString queueName, - final boolean durable, - final boolean exclusive, - final boolean autoDelete, final FieldTable arguments, final boolean passive) - throws AMQException, FailoverException - { - QueueDeclareBody body = - getMethodRegistry().createQueueDeclareBody(getTicket(), - queueName, - passive, - durable, - exclusive, - autoDelete, - false, - arguments); - - AMQFrame queueDeclare = body.generateFrame(getChannelId()); - - getProtocolHandler().syncWrite(queueDeclare, QueueDeclareOkBody.class); - } - - @Override - protected AMQShortString declareQueue(final AMQDestination amqd, final boolean noLocal, - final boolean nowait, final boolean passive) throws AMQException - { - //The 'noWait' parameter is only used on the 0-10 path, it is ignored on the 0-8/0-9/0-9-1 path - - final AMQProtocolHandler protocolHandler = getProtocolHandler(); - return new FailoverNoopSupport<AMQShortString, AMQException>( - new FailoverProtectedOperation<AMQShortString, AMQException>() - { - public AMQShortString execute() throws AMQException, FailoverException - { - // Generate the queue name if the destination indicates that a client generated name is to be used. - if (amqd.isNameRequired()) - { - amqd.setQueueName(protocolHandler.generateQueueName()); - } - - sendQueueDeclare(amqd, passive); - - return amqd.getAMQQueueName(); - } - }, getAMQConnection()).execute(); - } - - public void sendQueueDelete(final AMQShortString queueName) throws AMQException, FailoverException - { - QueueDeleteBody body = getMethodRegistry().createQueueDeleteBody(getTicket(), - queueName, - false, - false, - true); - AMQFrame queueDeleteFrame = body.generateFrame(getChannelId()); - - getProtocolHandler().syncWrite(queueDeleteFrame, QueueDeleteOkBody.class); - } - - public void sendSuspendChannel(boolean suspend) throws AMQException, FailoverException - { - ChannelFlowBody body = getMethodRegistry().createChannelFlowBody(!suspend); - AMQFrame channelFlowFrame = body.generateFrame(getChannelId()); - getAMQConnection().getProtocolHandler().syncWrite(channelFlowFrame, ChannelFlowOkBody.class); - } - - public BasicMessageConsumer_0_8 createMessageConsumer(final AMQDestination destination, final int prefetchHigh, - final int prefetchLow, final boolean noLocal, final boolean exclusive, String messageSelector, final FieldTable arguments, - final boolean noConsume, final boolean autoClose) throws JMSException - { - return new BasicMessageConsumer_0_8(getChannelId(), getAMQConnection(), destination, messageSelector, noLocal, - getMessageFactoryRegistry(),this, arguments, prefetchHigh, prefetchLow, - exclusive, getAcknowledgeMode(), noConsume, autoClose); - } - - - public BasicMessageProducer_0_8 createMessageProducer(final Destination destination, final Boolean mandatory, - final Boolean immediate, long producerId) throws JMSException - { - try - { - return new BasicMessageProducer_0_8(getAMQConnection(), (AMQDestination) destination, isTransacted(), getChannelId(), - this, getProtocolHandler(), producerId, immediate, mandatory); - } - catch (AMQException e) - { - JMSException ex = new JMSException("Error creating producer"); - ex.initCause(e); - ex.setLinkedException(e); - - throw ex; - } - } - - - @Override public void messageReceived(UnprocessedMessage message) - { - - if (message instanceof ReturnMessage) - { - // Return of the bounced message. - returnBouncedMessage((ReturnMessage) message); - } - else - { - super.messageReceived(message); - } - } - - private void returnBouncedMessage(final ReturnMessage msg) - { - try - { - // Bounced message is processed here, away from the mina thread - AbstractJMSMessage bouncedMessage = - getMessageFactoryRegistry().createMessage(0, - false, - msg.getExchange(), - msg.getRoutingKey(), - msg.getContentHeader(), - msg.getBodies(), - _queueDestinationCache, - _topicDestinationCache, - AMQDestination.UNKNOWN_TYPE); - AMQConstant errorCode = AMQConstant.getConstant(msg.getReplyCode()); - AMQShortString reason = msg.getReplyText(); - _logger.debug("Message returned with error code " + errorCode + " (" + reason + ")"); - - // @TODO should this be moved to an exception handler of sorts. Somewhere errors are converted to correct execeptions. - if (errorCode == AMQConstant.NO_CONSUMERS) - { - getAMQConnection().exceptionReceived(new AMQNoConsumersException("Error: " + reason, - bouncedMessage, - null)); - } - else if (errorCode == AMQConstant.NO_ROUTE) - { - getAMQConnection().exceptionReceived(new AMQNoRouteException("Error: " + reason, bouncedMessage, null)); - } - else - { - getAMQConnection().exceptionReceived( - new AMQUndeliveredException(errorCode, "Error: " + reason, bouncedMessage, null)); - } - - } - catch (Exception e) - { - _logger.error( - "Caught exception trying to raise undelivered message exception (dump follows) - ignoring...", - e); - } - } - - - - - public void sendRollback() throws AMQException, FailoverException - { - TxRollbackBody body = getMethodRegistry().createTxRollbackBody(); - AMQFrame frame = body.generateFrame(getChannelId()); - getProtocolHandler().syncWrite(frame, TxRollbackOkBody.class); - } - - public void setPrefetchLimits(final int messagePrefetch, final long sizePrefetch) - throws AMQException, FailoverException - { - _currentPrefetch.set(0); - if(messagePrefetch > 0 || sizePrefetch > 0) - { - BasicQosBody basicQosBody = - getProtocolHandler().getMethodRegistry().createBasicQosBody(sizePrefetch, messagePrefetch, false); - - getProtocolHandler().syncWrite(basicQosBody.generateFrame(getChannelId()), BasicQosOkBody.class); - } - } - - - - protected boolean ensureCreditForReceive() throws AMQException - { - return new FailoverNoopSupport<>( - new FailoverProtectedOperation<Boolean, AMQException>() - { - public Boolean execute() throws AMQException, FailoverException - { - int currentPrefetch = _currentPrefetch.get(); - if (currentPrefetch >= getPrefetch() && getPrefetch() >= 0) - { - BasicQosBody basicQosBody = getProtocolHandler().getMethodRegistry() - .createBasicQosBody(0, currentPrefetch + 1, false); - - getProtocolHandler().syncWrite(basicQosBody.generateFrame(getChannelId()), - BasicQosOkBody.class); - if(currentPrefetch == 0 && !isSuspended()) - { - sendSuspendChannel(false); - } - _creditChanged.set(true); - return true; - } - else - { - return false; - } - } - }, getProtocolHandler().getConnection()).execute(); - - } - - protected void reduceCreditAfterAcknowledge() throws AMQException - { - boolean manageCredit = isManagingCredit(); - - if(manageCredit && _creditChanged.compareAndSet(true,false)) - { - new FailoverNoopSupport<>( - new FailoverProtectedOperation<Void, AMQException>() - { - public Void execute() throws AMQException, FailoverException - { - int prefetch = getPrefetch(); - if(prefetch == 0) - { - sendSuspendChannel(true); - } - else - { - BasicQosBody basicQosBody = - getProtocolHandler().getMethodRegistry() - .createBasicQosBody(0, prefetch == -1 ? 0 : prefetch, false); - - getProtocolHandler().syncWrite(basicQosBody.generateFrame(getChannelId()), - BasicQosOkBody.class); - } - return null; - } - }, getProtocolHandler().getConnection()).execute(); - } - } - - protected void reduceCreditInPostDeliver() - { - int acknowledgeMode = getAcknowledgeMode(); - boolean manageCredit = (acknowledgeMode == AUTO_ACKNOWLEDGE || acknowledgeMode == DUPS_OK_ACKNOWLEDGE) && getPrefetch() == 0; - - if(manageCredit && _creditChanged.compareAndSet(true,false)) - { - ChannelFlowBody body = getMethodRegistry().createChannelFlowBody(false); - AMQFrame channelFlowFrame = body.generateFrame(getChannelId()); - getProtocolHandler().writeFrame(channelFlowFrame, true); - } - } - - - protected void updateCurrentPrefetch(int delta) - { - _currentPrefetch.addAndGet(delta); - } - - - - public DestinationCache<AMQQueue> getQueueDestinationCache() - { - return _queueDestinationCache; - } - - public DestinationCache<AMQTopic> getTopicDestinationCache() - { - return _topicDestinationCache; - } - - class QueueDeclareOkHandler extends SpecificMethodFrameListener - { - - private long _messageCount; - private long _consumerCount; - - public QueueDeclareOkHandler() - { - super(getChannelId(), QueueDeclareOkBody.class); - } - - public boolean processMethod(int channelId, AMQMethodBody frame) //throws AMQException - { - boolean matches = super.processMethod(channelId, frame); - if (matches) - { - QueueDeclareOkBody declareOk = (QueueDeclareOkBody) frame; - _messageCount = declareOk.getMessageCount(); - _consumerCount = declareOk.getConsumerCount(); - } - return matches; - } - - public long getMessageCount() - { - return _messageCount; - } - - public long getConsumerCount() - { - return _consumerCount; - } - } - - protected Long requestQueueDepth(AMQDestination amqd, boolean sync) throws AMQException, FailoverException - { - - if(_useLegacyQueueDepthBehaviour || isBound(null, amqd.getAMQQueueName(), null)) - { - AMQFrame queueDeclare = - getMethodRegistry().createQueueDeclareBody(getTicket(), - amqd.getAMQQueueName(), - true, - amqd.isDurable(), - amqd.isExclusive(), - amqd.isAutoDelete(), - false, - null).generateFrame(getChannelId()); - QueueDeclareOkHandler okHandler = new QueueDeclareOkHandler(); - getProtocolHandler().writeCommandFrameAndWaitForReply(queueDeclare, okHandler); - return okHandler.getMessageCount(); - } - else - { - return 0l; - } - } - - protected boolean tagLE(long tag1, long tag2) - { - return tag1 <= tag2; - } - - protected boolean updateRollbackMark(long currentMark, long deliveryTag) - { - return false; - } - - public AMQMessageDelegateFactory getMessageDelegateFactory() - { - return AMQMessageDelegateFactory.FACTORY_0_8; - } - - public void sync() throws AMQException - { - declareExchange(new AMQShortString("amq.direct"), new AMQShortString("direct"), false); - } - - @Override - public void resolveAddress(final AMQDestination dest, final boolean isConsumer, final boolean noLocal) - throws AMQException - { - if(!isAddrSyntaxSupported()) - { - throw new UnsupportedAddressSyntaxException(dest); - } - super.resolveAddress(dest, isConsumer, noLocal); - } - - private boolean isAddrSyntaxSupported() - { - return ((AMQConnectionDelegate_8_0)(getAMQConnection().getDelegate())).isAddrSyntaxSupported(); - } - - public int resolveAddressType(AMQDestination dest) throws AMQException - { - int type = dest.getAddressType(); - String name = dest.getAddressName(); - if (type != AMQDestination.UNKNOWN_TYPE) - { - return type; - } - else - { - boolean isExchange = exchangeExists(AMQShortString.valueOf(name)); - boolean isQueue = isBound(null,AMQShortString.valueOf(name), null); - - if (!isExchange && !isQueue) - { - type = dest instanceof AMQTopic ? AMQDestination.TOPIC_TYPE : AMQDestination.QUEUE_TYPE; - } - else if (!isExchange) - { - //name refers to a queue - type = AMQDestination.QUEUE_TYPE; - } - else if (!isQueue) - { - //name refers to an exchange - type = AMQDestination.TOPIC_TYPE; - } - else - { - //both a queue and exchange exist for that name - throw new AMQException("Ambiguous address, please specify queue or topic as node type"); - } - dest.setAddressType(type); - return type; - } - } - - protected void handleQueueNodeCreation(final AMQDestination dest, boolean noLocal) throws AMQException - { - final Node node = dest.getNode(); - final Map<String,Object> arguments = node.getDeclareArgs(); - if (!arguments.containsKey((AddressHelper.NO_LOCAL))) - { - arguments.put(AddressHelper.NO_LOCAL, noLocal); - } - String altExchange = node.getAlternateExchange(); - if(altExchange != null && !"".equals(altExchange)) - { - arguments.put("alternateExchange", altExchange); - } - - (new FailoverNoopSupport<Void, AMQException>( - new FailoverProtectedOperation<Void, AMQException>() - { - public Void execute() throws AMQException, FailoverException - { - - sendQueueDeclare(AMQShortString.valueOf(dest.getAddressName()), - node.isDurable(), - node.isExclusive(), - node.isAutoDelete(), - FieldTable.convertToFieldTable(arguments), - false); - - return null; - } - }, getAMQConnection())).execute(); - - - createBindings(dest, dest.getNode().getBindings()); - sync(); - } - - void handleExchangeNodeCreation(AMQDestination dest) throws AMQException - { - Node node = dest.getNode(); - String altExchange = dest.getNode().getAlternateExchange(); - Map<String, Object> arguments = node.getDeclareArgs(); - - if(altExchange != null && !"".equals(altExchange)) - { - arguments.put("alternateExchange", altExchange); - } - - // can't set alt. exchange - declareExchange(AMQShortString.valueOf(dest.getAddressName()), - AMQShortString.valueOf(node.getExchangeType()), - false, - node.isDurable(), - node.isAutoDelete(), - FieldTable.convertToFieldTable(arguments), false); - - // If bindings are specified without a queue name and is called by the producer, - // the broker will send an exception as expected. - createBindings(dest, dest.getNode().getBindings()); - sync(); - } - - - protected void doBind(final AMQDestination dest, - final AMQDestination.Binding binding, - final String queue, - final String exchange) throws AMQException - { - final String bindingKey = binding.getBindingKey() == null ? queue : binding.getBindingKey(); - - new FailoverNoopSupport<Object, AMQException>(new FailoverProtectedOperation<Object, AMQException>() - { - public Object execute() throws AMQException, FailoverException - { - - - MethodRegistry methodRegistry = getProtocolHandler().getMethodRegistry(); - QueueBindBody queueBindBody = - methodRegistry.createQueueBindBody(getTicket(), - AMQShortString.valueOf(queue), - AMQShortString.valueOf(exchange), - AMQShortString.valueOf(bindingKey), - false, - FieldTable.convertToFieldTable(binding.getArgs())); - - getProtocolHandler().syncWrite(queueBindBody. - generateFrame(getChannelId()), QueueBindOkBody.class); - return null; - } - }, getAMQConnection()).execute(); - - } - - - protected void doUnbind(final AMQDestination.Binding binding, - final String queue, - final String exchange) throws AMQException - { - new FailoverNoopSupport<Object, AMQException>(new FailoverProtectedOperation<Object, AMQException>() - { - public Object execute() throws AMQException, FailoverException - { - - if (isBound(null, AMQShortString.valueOf(queue), null)) - { - - if(ProtocolVersion.v8_0.equals(getProtocolVersion())) - { - throw new AMQException(AMQConstant.NOT_IMPLEMENTED, "Cannot unbind a queue in AMQP 0-8"); - } - - MethodRegistry methodRegistry = getProtocolHandler().getMethodRegistry(); - - String bindingKey = binding.getBindingKey() == null ? queue : binding.getBindingKey(); - - AMQMethodBody body = methodRegistry.createQueueUnbindBody(getTicket(), - AMQShortString.valueOf(queue), - AMQShortString.valueOf(exchange), - AMQShortString.valueOf(bindingKey), - null); - - getProtocolHandler().syncWrite(body.generateFrame(getChannelId()), QueueUnbindOkBody.class); - return null; - } - else - { - return null; - } - } - }, getAMQConnection()).execute(); - } - - public boolean isQueueExist(AMQDestination dest, boolean assertNode) throws AMQException - { - Node node = dest.getNode(); - return isQueueExist(dest.getAddressName(), assertNode, - node.isDurable(), node.isAutoDelete(), - node.isExclusive(), node.getDeclareArgs()); - } - - public boolean isQueueExist(final String queueName, boolean assertNode, - final boolean durable, final boolean autoDelete, - final boolean exclusive, final Map<String, Object> args) throws AMQException - { - boolean match = isBound(null,AMQShortString.valueOf(queueName), null); - - if (assertNode) - { - if(!match) - { - throw new AMQException("Assert failed for queue : " + queueName +". Queue does not exist." ); - - } - else - { - - new FailoverNoopSupport<Void, AMQException>( - new FailoverProtectedOperation<Void, AMQException>() - { - public Void execute() throws AMQException, FailoverException - { - - sendQueueDeclare(AMQShortString.valueOf(queueName), - durable, - exclusive, - autoDelete, - FieldTable.convertToFieldTable(args), - true); - - return null; - } - }, getAMQConnection()); - - } - } - - - return match; - } - - public boolean isExchangeExist(AMQDestination dest,boolean assertNode) throws AMQException - { - boolean match = exchangeExists(AMQShortString.valueOf(dest.getAddressName())); - - Node node = dest.getNode(); - - if (match) - { - if (assertNode) - { - - declareExchange(AMQShortString.valueOf(dest.getAddressName()), - AMQShortString.valueOf(node.getExchangeType()), - false, - node.isDurable(), - node.isAutoDelete(), - FieldTable.convertToFieldTable(node.getDeclareArgs()), true); - - } - else - { - // TODO - some way to determine the exchange type - /* - _logger.debug("Setting Exchange type " + result.getType()); - node.setExchangeType(result.getType()); - dest.setExchangeClass(new AMQShortString(result.getType())); - */ - - } - } - - if (assertNode) - { - if (!match) - { - throw new AMQException("Assert failed for address : " + dest +". Exchange not found."); - } - } - - return match; - } - - @Override - void handleNodeDelete(final AMQDestination dest) throws AMQException - { - if (AMQDestination.TOPIC_TYPE == dest.getAddressType()) - { - if (isExchangeExist(dest,false)) - { - - new FailoverNoopSupport<Object, AMQException>(new FailoverProtectedOperation<Object, AMQException>() - { - public Object execute() throws AMQException, FailoverException - { - sendExchangeDelete(dest.getAddressName()); - return null; - } - }, getAMQConnection()).execute(); - dest.setAddressResolved(0); - } - } - else - { - if (isQueueExist(dest,false)) - { - - new FailoverNoopSupport<Object, AMQException>(new FailoverProtectedOperation<Object, AMQException>() - { - public Object execute() throws AMQException, FailoverException - { - sendQueueDelete(AMQShortString.valueOf(dest.getAddressName())); - return null; - } - }, getAMQConnection()).execute(); - dest.setAddressResolved(0); - } - } - } - - @Override - void handleLinkDelete(AMQDestination dest) throws AMQException - { - // We need to destroy link bindings - String defaultExchangeForBinding = dest.getAddressType() == AMQDestination.TOPIC_TYPE ? dest - .getAddressName() : "amq.topic"; - - String defaultQueueName = null; - if (AMQDestination.QUEUE_TYPE == dest.getAddressType()) - { - defaultQueueName = dest.getQueueName(); - } - else - { - defaultQueueName = dest.getLink().getName() != null ? dest.getLink().getName() : dest.getQueueName(); - } - - for (AMQDestination.Binding binding: dest.getLink().getBindings()) - { - String queue = binding.getQueue() == null? - defaultQueueName: binding.getQueue(); - - String exchange = binding.getExchange() == null ? - defaultExchangeForBinding : - binding.getExchange(); - - if (_logger.isDebugEnabled()) - { - _logger.debug("Unbinding queue : " + queue + - " exchange: " + exchange + - " using binding key " + binding.getBindingKey() + - " with args " + Strings.printMap(binding.getArgs())); - } - doUnbind(binding, queue, exchange); - } - } - - - void deleteSubscriptionQueue(final AMQDestination dest) throws AMQException - { - // We need to delete the subscription queue. - if (dest.getAddressType() == AMQDestination.TOPIC_TYPE && - dest.getLink().getSubscriptionQueue().isExclusive() && - isQueueExist(dest.getQueueName(), false, false, false, false, null)) - { - (new FailoverNoopSupport<Void, AMQException>( - new FailoverProtectedOperation<Void, AMQException>() - { - public Void execute() throws AMQException, FailoverException - { - - sendQueueDelete(AMQShortString.valueOf(dest.getQueueName())); - return null; - } - }, getAMQConnection())).execute(); - - } - } - - protected void flushAcknowledgments() - { - - } - - @Override - protected void deleteTemporaryDestination(final TemporaryDestination amqQueue) - throws JMSException - { - // Currently TemporaryDestination is set to be auto-delete which, for 0-8..0-9-1, means that the queue will be deleted - // by the server when there are no more subscriptions to that queue/topic (rather than when the client disconnects). - // This is not quite right for JMSCompliance as the queue/topic should remain until the connection closes, or the - // client explicitly deletes it. - - /* intentional no-op */ - } - - public boolean isQueueBound(String exchangeName, String queueName, - String bindingKey, Map<String, Object> args) throws JMSException - { - return isQueueBound(exchangeName == null ? null : new AMQShortString(exchangeName), - queueName == null ? null : new AMQShortString(queueName), - bindingKey == null ? null : new AMQShortString(bindingKey)); - } - - private AMQProtocolHandler getProtocolHandler() - { - return getAMQConnection().getProtocolHandler(); - } - - public MethodRegistry getMethodRegistry() - { - MethodRegistry methodRegistry = getProtocolHandler().getMethodRegistry(); - return methodRegistry; - } - - public AMQException getLastException() - { - // if the Connection has closed then we should throw any exception that - // has occurred that we were not waiting for - AMQStateManager manager = getProtocolHandler().getStateManager(); - - Exception e = manager.getLastException(); - if (manager.getCurrentState().equals(AMQState.CONNECTION_CLOSED) - && e != null) - { - if (e instanceof AMQException) - { - return (AMQException) e; - } - else - { - AMQException amqe = new AMQException(AMQConstant - .getConstant(AMQConstant.INTERNAL_ERROR.getCode()), - e.getMessage(), e.getCause()); - return amqe; - } - } - else - { - return null; - } - } - - boolean isManagingCredit() - { - int acknowledgeMode = getAcknowledgeMode(); - return acknowledgeMode == CLIENT_ACKNOWLEDGE - || acknowledgeMode == SESSION_TRANSACTED - || ((acknowledgeMode == AUTO_ACKNOWLEDGE || acknowledgeMode == DUPS_OK_ACKNOWLEDGE) && getPrefetch() == 0); - } - - - public boolean isFlowBlocked() - { - synchronized (_flowControl) - { - return !_flowControl.getFlowControl(); - } - } - - public void setFlowControl(final boolean active) - { - _flowControl.setFlowControl(active); - if (_logger.isInfoEnabled()) - { - _logger.info("Broker enforced flow control " + (active ? "no longer in effect" : "has been enforced")); - } - } - - void checkFlowControl() throws InterruptedException, JMSException - { - long expiryTime = 0L; - synchronized (_flowControl) - { - while (!_flowControl.getFlowControl() && - (expiryTime == 0L ? (expiryTime = System.currentTimeMillis() + _flowControlWaitFailure) - : expiryTime) >= System.currentTimeMillis() ) - { - - _flowControl.wait(_flowControlWaitPeriod); - if (_logger.isInfoEnabled()) - { - _logger.info("Message send delayed by " + (System.currentTimeMillis() + _flowControlWaitFailure - expiryTime)/1000 + "s due to broker enforced flow control"); - } - } - if(!_flowControl.getFlowControl()) - { - _logger.error("Message send failed due to timeout waiting on broker enforced flow control"); - throw new JMSException("Unable to send message for " + _flowControlWaitFailure /1000 + " seconds due to broker enforced flow control"); - } - } - } - - - - public abstract static class DestinationCache<T extends AMQDestination> - { - private final Map<AMQShortString, Map<AMQShortString, T>> cache = new HashMap<AMQShortString, Map<AMQShortString, T>>(); - - public T getDestination(AMQShortString exchangeName, AMQShortString routingKey) - { - Map<AMQShortString, T> routingMap = cache.get(exchangeName); - if(routingMap == null) - { - routingMap = new LinkedHashMap<AMQShortString, T>() - { - - protected boolean removeEldestEntry(Map.Entry<AMQShortString, T> eldest) - { - return size() >= 200; - } - }; - cache.put(exchangeName,routingMap); - } - T destination = routingMap.get(routingKey); - if(destination == null) - { - destination = newDestination(exchangeName, routingKey); - routingMap.put(routingKey,destination); - } - return destination; - } - - protected abstract T newDestination(AMQShortString exchangeName, AMQShortString routingKey); - } - - private static class TopicDestinationCache extends DestinationCache<AMQTopic> - { - protected AMQTopic newDestination(AMQShortString exchangeName, AMQShortString routingKey) - { - return new AMQTopic(exchangeName, routingKey, null); - } - } - - private static class QueueDestinationCache extends DestinationCache<AMQQueue> - { - protected AMQQueue newDestination(AMQShortString exchangeName, AMQShortString routingKey) - { - return new AMQQueue(exchangeName, routingKey, routingKey); - } - } - - private static final class FlowControlIndicator - { - private volatile boolean _flowControl = true; - - public synchronized void setFlowControl(boolean flowControl) - { - _flowControl = flowControl; - notify(); - } - - public boolean getFlowControl() - { - return _flowControl; - } - } - - private final TopicDestinationCache _topicDestinationCache = new TopicDestinationCache(); - private final QueueDestinationCache _queueDestinationCache = new QueueDestinationCache(); - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQTemporaryQueue.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQTemporaryQueue.java deleted file mode 100644 index 263dfa6827..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQTemporaryQueue.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.client; - -import org.apache.qpid.framing.AMQShortString; - -import javax.jms.JMSException; -import javax.jms.TemporaryQueue; -import java.util.UUID; - -/** AMQ implementation of a TemporaryQueue. */ -final class AMQTemporaryQueue extends AMQQueue implements TemporaryQueue, TemporaryDestination -{ - private static final long serialVersionUID = -5457866720195625708L; - private final AMQSession _session; - private boolean _deleted; - - /** Create a new instance of an AMQTemporaryQueue */ - public AMQTemporaryQueue(AMQSession session) - { - super(session.getTemporaryQueueExchangeName(), new AMQShortString("TempQueue" + UUID.randomUUID()), true); - _session = session; - } - - /** @see javax.jms.TemporaryQueue#delete() */ - public synchronized void delete() throws JMSException - { - if (_session.hasConsumer(this)) - { - throw new JMSException("Temporary Queue has consumers so cannot be deleted"); - } - - try - { - _session.deleteTemporaryDestination(this); - } - finally - { - _deleted = true; - } - } - - public AMQSession getSession() - { - return _session; - } - - public boolean isDeleted() - { - return _deleted; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQTemporaryTopic.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQTemporaryTopic.java deleted file mode 100644 index 9163583364..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQTemporaryTopic.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.client; - -import org.apache.qpid.framing.AMQShortString; - -import javax.jms.JMSException; -import javax.jms.TemporaryTopic; -import java.util.UUID; - -/** - * AMQ implementation of TemporaryTopic. - */ -class AMQTemporaryTopic extends AMQTopic implements TemporaryTopic, TemporaryDestination -{ - - private static final long serialVersionUID = -4990099300883216207L; - private final AMQSession _session; - private boolean _deleted; - /** - * Create new temporary topic. - */ - public AMQTemporaryTopic(AMQSession session) - { - super(session.getTemporaryTopicExchangeName(),new AMQShortString("tmp_" + UUID.randomUUID())); - _session = session; - } - - /** - * @see javax.jms.TemporaryTopic#delete() - */ - public void delete() throws JMSException - { - if(_session.hasConsumer(this)) - { - throw new JMSException("Temporary Topic has consumers so cannot be deleted"); - } - - try - { - _session.deleteTemporaryDestination(this); - } - finally - { - _deleted = true; - } - } - - public AMQSession getSession() - { - return _session; - } - - public boolean isDeleted() - { - return _deleted; - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQTopic.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQTopic.java deleted file mode 100644 index 9cdbc1e189..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQTopic.java +++ /dev/null @@ -1,255 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; - -import java.net.URISyntaxException; - -import javax.jms.InvalidDestinationException; -import javax.jms.JMSException; -import javax.jms.Topic; - -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.messaging.Address; -import org.apache.qpid.url.BindingURL; - -public class AMQTopic extends AMQDestination implements Topic -{ - private static final long serialVersionUID = -4773561540716587036L; - - public AMQTopic(String address) throws URISyntaxException - { - super(address); - } - - public AMQTopic(Address address) - { - super(address); - } - - public AMQTopic() - { - super(); - } - - /** - * Constructor for use in creating a topic using a BindingURL. - * - * @param binding The binding url object. - */ - public AMQTopic(BindingURL binding) - { - super(binding); - } - - public AMQTopic(AMQShortString exchange, AMQShortString routingKey, AMQShortString queueName) - { - super(exchange, AMQShortString.valueOf(ExchangeDefaults.TOPIC_EXCHANGE_CLASS), routingKey, true, true, queueName, false); - } - - public AMQTopic(AMQShortString exchange, AMQShortString routingKey, AMQShortString queueName,AMQShortString[] bindingKeys) - { - super(exchange, AMQShortString.valueOf(ExchangeDefaults.TOPIC_EXCHANGE_CLASS), routingKey, true, true, queueName, false,bindingKeys); - } - - public AMQTopic(AMQConnection conn, String routingKey) - { - this(conn.getDefaultTopicExchangeName(), new AMQShortString(routingKey)); - } - - public AMQTopic(String exchangeName, String routingKey) - { - this(AMQShortString.valueOf(exchangeName), new AMQShortString(routingKey)); - } - - public AMQTopic(AMQShortString exchangeName, String routingKey) - { - this(exchangeName, new AMQShortString(routingKey)); - } - - public AMQTopic(AMQShortString exchangeName, AMQShortString routingKey) - { - this(exchangeName, routingKey, null); - } - - public AMQTopic(AMQShortString exchangeName, AMQShortString name, boolean isAutoDelete, AMQShortString queueName, boolean isDurable) - { - super(exchangeName, AMQShortString.valueOf(ExchangeDefaults.TOPIC_EXCHANGE_CLASS), name, true, isAutoDelete, queueName, isDurable); - } - - - protected AMQTopic(AMQShortString exchangeName, AMQShortString exchangeClass, AMQShortString name, boolean isAutoDelete, AMQShortString queueName, boolean isDurable) - { - super(exchangeName, exchangeClass, name, true, isAutoDelete, queueName, isDurable); - } - - protected AMQTopic(AMQShortString exchangeName, AMQShortString exchangeClass, AMQShortString routingKey, boolean isExclusive, - boolean isAutoDelete, AMQShortString queueName, boolean isDurable) - { - super(exchangeName, exchangeClass, routingKey, isExclusive, isAutoDelete, queueName, isDurable ); - } - - protected AMQTopic(AMQShortString exchangeName, AMQShortString exchangeClass, AMQShortString routingKey, boolean isExclusive, - boolean isAutoDelete, AMQShortString queueName, boolean isDurable,AMQShortString[] bindingKeys) - { - super(exchangeName, exchangeClass, routingKey, isExclusive, isAutoDelete, queueName, isDurable,bindingKeys); - } - - public static AMQTopic createDurableTopic(Topic topic, String subscriptionName, AMQConnection connection) - throws JMSException - { - if (topic instanceof AMQDestination && topic instanceof javax.jms.Topic) - { - AMQDestination qpidTopic = (AMQDestination)topic; - if (qpidTopic.getDestSyntax() == DestSyntax.ADDR) - { - try - { - AMQTopic t = new AMQTopic(qpidTopic.getAddress()); - AMQShortString queueName = getDurableTopicQueueName(subscriptionName, connection); - // link is never null if dest was created using an address string. - t.getLink().setName(queueName.asString()); - t.getLink().getSubscriptionQueue().setAutoDelete(false); - t.getLink().setDurable(true); - - // The legacy fields are also populated just in case. - t.setQueueName(queueName); - t.setAutoDelete(false); - t.setDurable(true); - return t; - } - catch(Exception e) - { - JMSException ex = new JMSException("Error creating durable topic"); - ex.initCause(e); - ex.setLinkedException(e); - throw ex; - } - } - else - { - return new AMQTopic(qpidTopic.getExchangeName(), qpidTopic.getExchangeClass(), qpidTopic.getRoutingKey(), false, - getDurableTopicQueueName(subscriptionName, connection), - true); - } - } - else - { - throw new InvalidDestinationException("The destination object used is not from this provider or of type javax.jms.Topic"); - } - } - - public static AMQShortString getDurableTopicQueueName(String subscriptionName, AMQConnection connection) throws JMSException - { - return new AMQShortString(connection.getClientID() + ":" + subscriptionName); - } - - public String getTopicName() throws JMSException - { - if (getRoutingKey() != null) - { - return getRoutingKey().asString(); - } - else if (getSubject() != null) - { - return getSubject(); - } - else - { - return null; - } - } - - @Override - public AMQShortString getExchangeName() - { - if (super.getExchangeName() == null && super.getAddressName() != null) - { - return new AMQShortString(super.getAddressName()); - } - else - { - return super.getExchangeName(); - } - } - - public AMQShortString getRoutingKey() - { - if (super.getRoutingKey() != null) - { - return super.getRoutingKey(); - } - else if (getSubject() != null) - { - return new AMQShortString(getSubject()); - } - else - { - setRoutingKey(new AMQShortString("")); - setSubject(""); - return super.getRoutingKey(); - } - } - - public boolean isNameRequired() - { - return !isDurable(); - } - - /** - * Override since the queue is always private and we must ensure it remains null. If not, - * reuse of the topic when registering consumers will make all consumers listen on the same (private) queue rather - * than getting their own (private) queue. - * <p> - * This is relatively nasty but it is difficult to come up with a more elegant solution, given - * the requirement in the case on AMQQueue and possibly other AMQDestination subclasses to - * use the underlying queue name even where it is server generated. - */ - public void setQueueName(String queueName) - { - } - - public boolean equals(Object o) - { - if (getDestSyntax() == DestSyntax.ADDR) - { - return super.equals(o); - } - else - { - return (o instanceof AMQTopic) - && ((AMQTopic)o).getExchangeName().equals(getExchangeName()) - && ((AMQTopic)o).getRoutingKey().equals(getRoutingKey()); - } - } - - public int hashCode() - { - if (getDestSyntax() == DestSyntax.ADDR) - { - return super.hashCode(); - } - else - { - return getExchangeName().hashCode() + getRoutingKey().hashCode(); - } - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQTopicSessionAdaptor.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQTopicSessionAdaptor.java deleted file mode 100644 index 0f44ac5501..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQTopicSessionAdaptor.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.client; - -import javax.jms.*; -import javax.jms.IllegalStateException; - -class AMQTopicSessionAdaptor extends AMQSessionAdapter<TopicSession> implements TopicSession -{ - - public AMQTopicSessionAdaptor(TopicSession session) - { - super(session); - } - - public TopicSubscriber createSubscriber(Topic topic) throws JMSException - { - return getSession().createSubscriber(topic); - } - - public TopicSubscriber createSubscriber(Topic topic, String string, boolean b) throws JMSException - { - return getSession().createSubscriber(topic, string, b); - } - - public TopicPublisher createPublisher(Topic topic) throws JMSException - { - return getSession().createPublisher(topic); - } - - //The following methods cannot be called from a TopicSession as per JMS spec - public Queue createQueue(String string) throws JMSException - { - throw new IllegalStateException("Cannot call createQueue from TopicSession"); - } - - public QueueBrowser createBrowser(Queue queue) throws JMSException - { - throw new IllegalStateException("Cannot call createBrowser from TopicSession"); - } - - public QueueBrowser createBrowser(Queue queue, String string) throws JMSException - { - throw new IllegalStateException("Cannot call createBrowser from TopicSession"); - } - - public TemporaryQueue createTemporaryQueue() throws JMSException - { - throw new IllegalStateException("Cannot call createTemporaryQueue from TopicSession"); - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQUndefinedDestination.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQUndefinedDestination.java deleted file mode 100644 index b9099145d5..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQUndefinedDestination.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.client; - -import org.apache.qpid.framing.AMQShortString; - -public class AMQUndefinedDestination extends AMQDestination -{ - - private static final AMQShortString UNKNOWN_EXCHANGE_CLASS = new AMQShortString("unknown"); - private static final long serialVersionUID = -1487224209485888847L; - - - public AMQUndefinedDestination(AMQShortString exchange, AMQShortString routingKey, AMQShortString queueName) - { - super(exchange, UNKNOWN_EXCHANGE_CLASS, routingKey, queueName); - } - - public boolean isNameRequired() - { - return getAMQQueueName() == null; - } - - @Override - public boolean neverDeclare() - { - return true; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQXAResource.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQXAResource.java deleted file mode 100644 index cce6b91781..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/AMQXAResource.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.client; - -import java.util.List; - -import javax.transaction.xa.XAResource; - -public interface AMQXAResource extends XAResource -{ - public String getBrokerUUID(); - - public List<XAResource> getSiblings(); -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer.java b/qpid/java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer.java deleted file mode 100644 index 3c947043c6..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer.java +++ /dev/null @@ -1,1094 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; - -import javax.jms.InvalidSelectorException; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageListener; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.AMQInternalException; -import org.apache.qpid.client.failover.FailoverException; -import org.apache.qpid.client.filter.JMSSelectorFilter; -import org.apache.qpid.client.filter.MessageFilter; -import org.apache.qpid.client.message.AMQMessageDelegateFactory; -import org.apache.qpid.client.message.AbstractJMSMessage; -import org.apache.qpid.client.message.CloseConsumerMessage; -import org.apache.qpid.client.message.MessageFactoryRegistry; -import org.apache.qpid.common.AMQPFilterTypes; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.FieldTableFactory; -import org.apache.qpid.jms.MessageConsumer; -import org.apache.qpid.jms.Session; -import org.apache.qpid.transport.TransportException; - -public abstract class BasicMessageConsumer<U> extends Closeable implements MessageConsumer -{ - private static final Logger _logger = LoggerFactory.getLogger(BasicMessageConsumer.class); - - private final AMQConnection _connection; - - private final MessageFilter _messageSelectorFilter; - - private final boolean _noLocal; - - private AMQDestination _destination; - - /** - * When true indicates that a blocking receive call is in progress - */ - private final AtomicBoolean _receiving = new AtomicBoolean(false); - /** - * Holds an atomic reference to the listener installed. - */ - private final AtomicReference<MessageListener> _messageListener = new AtomicReference<MessageListener>(); - - private int _consumerTag; - - private final int _channelId; - - private final BlockingQueue _synchronousQueue; - - private final MessageFactoryRegistry _messageFactory; - - private final AMQSession _session; - - /** - * We need to store the "raw" field table so that we can resubscribe in the event of failover being required - */ - private final FieldTable _arguments; - - /** - * We store the high water prefetch field in order to be able to reuse it when resubscribing in the event of - * failover - */ - private final int _prefetchHigh; - - /** - * We store the low water prefetch field in order to be able to reuse it when resubscribing in the event of - * failover - */ - private final int _prefetchLow; - - private boolean _exclusive; - - private final int _acknowledgeMode; - - /** - * List of tags delievered, The last of which which should be acknowledged on commit in transaction mode. - */ - private ConcurrentLinkedQueue<Long> _receivedDeliveryTags = new ConcurrentLinkedQueue<Long>(); - - /** - * The thread that was used to call receive(). This is important for being able to interrupt that thread if a - * receive() is in progress. - */ - private Thread _receivingThread; - - - /** - * Used to store this consumer queue name - * Usefull when more than binding key should be used - */ - private AMQShortString _queuename; - - /** - * autoClose denotes that the consumer will automatically cancel itself when there are no more messages to receive - * on the queue. This is used for queue browsing. - */ - private final boolean _autoClose; - - private final boolean _browseOnly; - private List<StackTraceElement> _closedStack = null; - - private boolean _isDurableSubscriber = false; - private int _addressType = AMQDestination.UNKNOWN_TYPE; - - protected BasicMessageConsumer(int channelId, AMQConnection connection, AMQDestination destination, - String messageSelector, boolean noLocal, MessageFactoryRegistry messageFactory, - AMQSession session, FieldTable rawSelector, - int prefetchHigh, int prefetchLow, boolean exclusive, - int acknowledgeMode, boolean browseOnly, boolean autoClose) throws JMSException - { - _channelId = channelId; - _connection = connection; - _noLocal = noLocal; - _destination = destination; - _messageFactory = messageFactory; - _session = session; - _prefetchHigh = prefetchHigh; - _prefetchLow = prefetchLow; - _exclusive = exclusive; - - _synchronousQueue = new LinkedBlockingQueue(); - _autoClose = autoClose; - _browseOnly = browseOnly; - - try - { - if (messageSelector == null || "".equals(messageSelector.trim())) - { - _messageSelectorFilter = null; - } - else - { - _messageSelectorFilter = new JMSSelectorFilter(messageSelector); - } - } - catch (final AMQInternalException ie) - { - InvalidSelectorException ise = new InvalidSelectorException("cannot create consumer because of selector issue"); - ise.setLinkedException(ie); - throw ise; - } - - // Force queue browsers not to use acknowledge modes. - if (_browseOnly) - { - _acknowledgeMode = Session.NO_ACKNOWLEDGE; - } - else - { - _acknowledgeMode = acknowledgeMode; - } - - final FieldTable ft = FieldTableFactory.newFieldTable(); - if(destination.getConsumerArguments() != null) - { - ft.addAll(FieldTable.convertToFieldTable(destination.getConsumerArguments())); - } - // rawSelector is used by HeadersExchange and is not a JMS Selector - if (rawSelector != null) - { - ft.addAll(rawSelector); - } - - // We must always send the selector argument even if empty, so that we can tell when a selector is removed from a - // durable topic subscription that the broker arguments don't match any more. This is because it is not otherwise - // possible to determine when querying the broker whether there are no arguments or just a non-matching selector - // argument, as specifying null for the arguments when querying means they should not be checked at all - ft.put(AMQPFilterTypes.JMS_SELECTOR.getValue(), messageSelector == null ? "" : messageSelector); - if(noLocal) - { - ft.put(AMQPFilterTypes.NO_LOCAL.getValue(), noLocal); - } - - - _arguments = ft; - _addressType = _destination.getAddressType(); - } - - public AMQDestination getDestination() - { - return _destination; - } - - public String getMessageSelector() throws JMSException - { - checkPreConditions(); - - return _messageSelectorFilter == null ? null :_messageSelectorFilter.getSelector(); - } - - public MessageListener getMessageListener() throws JMSException - { - checkPreConditions(); - - return _messageListener.get(); - } - - /** - * The acknowledge mode in force for this consumer. Note that the AMQP protocol allows different ack modes per - * consumer whereas JMS defines this at the session level, hence why we associate it with the consumer in our - * implementation. - */ - public int getAcknowledgeMode() - { - return _acknowledgeMode; - } - - protected boolean isMessageListenerSet() - { - return _messageListener.get() != null; - } - - public void setMessageListener(final MessageListener messageListener) throws JMSException - { - checkPreConditions(); - - // if the current listener is non-null and the session is not stopped, then - // it is an error to call this method. - - // i.e. it is only valid to call this method if - // - // (a) the connection is stopped, in which case the dispatcher is not running - // OR - // (b) the listener is null AND we are not receiving synchronously at present - // - - if (!_session.getAMQConnection().started()) - { - _messageListener.set(messageListener); - _session.setHasMessageListeners(); - - if (_logger.isDebugEnabled()) - { - _logger.debug( - "Session stopped : Message listener(" + messageListener + ") set for destination " + _destination); - } - } - else - { - if (_receiving.get()) - { - throw new javax.jms.IllegalStateException("Another thread is already receiving synchronously."); - } - - if (!_messageListener.compareAndSet(null, messageListener)) - { - throw new javax.jms.IllegalStateException("Attempt to alter listener while session is started."); - } - - if (_logger.isDebugEnabled()) - { - _logger.debug("Message listener set for destination " + _destination); - } - - if (messageListener != null) - { - //todo: handle case where connection has already been started, and the dispatcher has alreaded started - // putting values on the _synchronousQueue - - synchronized (_session) - { - _messageListener.set(messageListener); - _session.setHasMessageListeners(); - _session.startDispatcherIfNecessary(); - - // If we already have messages on the queue, deliver them to the listener - Object o = _synchronousQueue.poll(); - while (o != null) - { - notifyMessage((AbstractJMSMessage) o); - o = _synchronousQueue.poll(); - } - } - } - } - } - - /** - * @param immediate if true then return immediately if the connection is failing over - * - * @return boolean if the acquisition was successful - * - * @throws JMSException if a listener has already been set or another thread is receiving - * @throws InterruptedException if interrupted - */ - private boolean acquireReceiving(boolean immediate) throws JMSException, InterruptedException - { - if (_connection.isFailingOver()) - { - if (immediate) - { - return false; - } - else - { - _connection.blockUntilNotFailingOver(); - } - } - - if (isMessageListenerSet()) - { - throw new javax.jms.IllegalStateException("A listener has already been set."); - } - - if (!_receiving.compareAndSet(false, true)) - { - throw new javax.jms.IllegalStateException("Another thread is already receiving."); - } - - _receivingThread = Thread.currentThread(); - return true; - } - - private void releaseReceiving() - { - _receiving.set(false); - _receivingThread = null; - } - - public FieldTable getArguments() - { - return _arguments; - } - - public int getPrefetch() - { - return _prefetchHigh; - } - - public int getPrefetchHigh() - { - return _prefetchHigh; - } - - public int getPrefetchLow() - { - return _prefetchLow; - } - - public boolean isNoLocal() - { - return _noLocal; - } - - /** - * We store the exclusive field in order to be able to reuse it when resubscribing in the event of failover - */ - public boolean isExclusive() - { - - AMQDestination dest = this.getDestination(); - if (dest.getDestSyntax() == AMQDestination.DestSyntax.ADDR) - { - if (dest.getAddressType() == AMQDestination.TOPIC_TYPE) - { - return true; - } - else - { - return dest.getLink().getSubscription().isExclusive(); - } - } - else - { - return _exclusive; - } - } - - public boolean isReceiving() - { - return _receiving.get(); - } - - public MessageFilter getMessageSelectorFilter() - { - return _messageSelectorFilter; - } - - public Message receive() throws JMSException - { - return receive(0); - } - - public Message receive(long l) throws JMSException - { - - checkPreConditions(); - - try - { - acquireReceiving(false); - } - catch (InterruptedException e) - { - _logger.warn("Interrupted acquire: " + e); - if (isClosed()) - { - return null; - } - } - - _session.startDispatcherIfNecessary(); - - try - { - Object o = getMessageFromQueue(l); - final AbstractJMSMessage m = returnMessageOrThrow(o); - if (m != null) - { - preDeliver(m); - postDeliver(m); - } - return m; - } - catch (InterruptedException e) - { - _logger.warn("Interrupted: " + e); - - return null; - } - catch(TransportException e) - { - throw _session.toJMSException("Exception while receiving:" + e.getMessage(), e); - } - finally - { - releaseReceiving(); - } - } - - public Object getMessageFromQueue(long l) throws InterruptedException - { - Object o; - if (l > 0) - { - o = _synchronousQueue.poll(l, TimeUnit.MILLISECONDS); - } - else if (l < 0) - { - o = _synchronousQueue.poll(); - } - else - { - o = _synchronousQueue.take(); - } - return o; - } - - abstract Message receiveBrowse() throws JMSException; - - public Message receiveNoWait() throws JMSException - { - checkPreConditions(); - - try - { - if (!acquireReceiving(true)) - { - //If we couldn't acquire the receiving thread then return null. - // This will occur if failing over. - return null; - } - } - catch (InterruptedException e) - { - /* - * This seems slightly shoddy but should never actually be executed - * since we told acquireReceiving to return immediately and it shouldn't - * block on anything. - */ - - return null; - } - - _session.startDispatcherIfNecessary(); - - try - { - Object o = getMessageFromQueue(-1); - final AbstractJMSMessage m = returnMessageOrThrow(o); - if (m != null) - { - preDeliver(m); - postDeliver(m); - } - - return m; - } - catch (InterruptedException e) - { - _logger.warn("Interrupted: " + e); - - return null; - } - catch(TransportException e) - { - throw _session.toJMSException("Exception while receiving:" + e.getMessage(), e); - } - finally - { - releaseReceiving(); - } - } - - /** - * We can get back either a Message or an exception from the queue. This method examines the argument and deals with - * it by throwing it (if an exception) or returning it (in any other case). - * - * @param o the object to return or throw - * @return a message only if o is a Message - * @throws JMSException if the argument is a throwable. If it is a JMSException it is rethrown as is, but if not a - * JMSException is created with the linked exception set appropriately - */ - private AbstractJMSMessage returnMessageOrThrow(Object o) throws JMSException - { - // errors are passed via the queue too since there is no way of interrupting the poll() via the API. - if (o instanceof Throwable) - { - JMSException e = new JMSException("Message consumer forcibly closed due to error: " + o); - e.initCause((Throwable) o); - if (o instanceof Exception) - { - e.setLinkedException((Exception) o); - } - - throw e; - } - else if (o instanceof CloseConsumerMessage) - { - setClosed(); - deregisterConsumer(); - return null; - } - else - { - return (AbstractJMSMessage) o; - } - } - - public void close() throws JMSException - { - close(true); - } - - public void close(boolean sendClose) throws JMSException - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Closing consumer:" + debugIdentity()); - } - - if (!setClosed()) - { - setClosing(true); - if (_logger.isDebugEnabled()) - { - StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); - if (_closedStack != null) - { - _logger.debug(_consumerTag + " previously:" + _closedStack.toString()); - } - else - { - _closedStack = Arrays.asList(stackTrace).subList(3, stackTrace.length - 1); - } - } - - if (sendClose) - { - - // The Synchronized block only needs to protect network traffic. - - try - { - // If the session is open or we are in the process - // of closing the session then send a cance - // no point otherwise as the connection will be gone - if (!_session.isClosed() || _session.isClosing()) - { - synchronized(_session.getMessageDeliveryLock()) - { - synchronized (_connection.getFailoverMutex()) - { - sendCancel(); - } - } - } - } - catch (AMQException e) - { - throw new JMSAMQException("Error closing consumer: " + e, e); - } - catch (FailoverException e) - { - throw new JMSAMQException("FailoverException interrupted basic cancel.", e); - } - catch (TransportException e) - { - throw _session.toJMSException("Exception while closing consumer: " + e.getMessage(), e); - } - - } - else - { - // FIXME? - deregisterConsumer(); - } - - // This will occur if session.close is called closing all consumers we may be blocked waiting for a receive - // so we need to let it know it is time to close. - if ((_messageListener != null) && _receiving.get()) - { - if (_logger.isInfoEnabled()) - { - _logger.info("Interrupting thread: " + _receivingThread); - } - - _receivingThread.interrupt(); - } - - - if(!(isBrowseOnly() || getSession().isClosing())) - { - rollback(); - } - } - } - - abstract void sendCancel() throws AMQException, FailoverException; - - /** - * Called when you need to invalidate a consumer. Used for example when failover has occurred and the client has - * vetoed automatic resubscription. The caller must hold the failover mutex. - */ - void markClosed() - { - // synchronized (_closed) - { - setClosed(); - - if (_logger.isDebugEnabled()) - { - if (_closedStack != null) - { - StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); - _logger.debug(_consumerTag + " markClosed():" - + Arrays.asList(stackTrace).subList(3, stackTrace.length - 1)); - _logger.debug(_consumerTag + " previously:" + _closedStack.toString()); - } - else - { - StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); - _closedStack = Arrays.asList(stackTrace).subList(3, stackTrace.length - 1); - } - } - } - - deregisterConsumer(); - } - - /** - * @param closeMessage - * this message signals that we should close the browser - */ - public void notifyCloseMessage(CloseConsumerMessage closeMessage) - { - if (isMessageListenerSet()) - { - // Currently only possible to get this msg type with a browser. - // If we get the message here then we should probably just close - // this consumer. - // Though an AutoClose consumer with message listener is quite odd.. - // Just log out the fact so we know where we are - _logger.warn("Using an AutoCloseconsumer with message listener is not supported."); - } - else - { - try - { - _synchronousQueue.put(closeMessage); - } - catch (InterruptedException e) - { - _logger.info(" SynchronousQueue.put interupted. Usually result of connection closing," - + "but we shouldn't have close yet"); - } - } - } - - - /** - * Called from the AMQSession when a message has arrived for this consumer. This methods handles both the case of a - * message listener or a synchronous receive() caller. - * - * @param messageFrame the raw unprocessed mesage - */ - void notifyMessage(U messageFrame) - { - if (messageFrame instanceof CloseConsumerMessage) - { - notifyCloseMessage((CloseConsumerMessage) messageFrame); - return; - } - - - - try - { - AbstractJMSMessage jmsMessage = createJMSMessageFromUnprocessedMessage(_session.getMessageDelegateFactory(), messageFrame); - - if (_logger.isDebugEnabled()) - { - _logger.debug("Message is of type: " + jmsMessage.getClass().getName()); - } - notifyMessage(jmsMessage); - } - catch (Exception e) - { - if (e instanceof InterruptedException) - { - _logger.info("SynchronousQueue.put interupted. Usually result of connection closing"); - } - else - { - _logger.error("Caught exception (dump follows) - ignoring...", e); - } - } - } - - public abstract AbstractJMSMessage createJMSMessageFromUnprocessedMessage(AMQMessageDelegateFactory delegateFactory, U messageFrame) - throws Exception; - - /** @param jmsMessage this message has already been processed so can't redo preDeliver */ - public void notifyMessage(AbstractJMSMessage jmsMessage) - { - try - { - if (isMessageListenerSet()) - { - preDeliver(jmsMessage); - getMessageListener().onMessage(jmsMessage); - postDeliver(jmsMessage); - } - else - { - // we should not be allowed to add a message is the - // consumer is closed - _synchronousQueue.put(jmsMessage); - } - } - catch (Exception e) - { - if (e instanceof InterruptedException) - { - _logger.info("reNotification : SynchronousQueue.put interupted. Usually result of connection closing"); - } - else - { - _logger.error("reNotification : Caught exception (dump follows) - ignoring...", e); - } - } - } - - protected void preDeliver(AbstractJMSMessage msg) - { - _session.setInRecovery(false); - - switch (_acknowledgeMode) - { - case Session.PRE_ACKNOWLEDGE: - _session.acknowledgeMessage(msg.getDeliveryTag(), false); - break; - case Session.AUTO_ACKNOWLEDGE: - //fall through - case Session.DUPS_OK_ACKNOWLEDGE: - _session.addUnacknowledgedMessage(msg.getDeliveryTag()); - break; - case Session.CLIENT_ACKNOWLEDGE: - // we set the session so that when the user calls acknowledge() it can call the method on session - // to send out the appropriate frame - msg.setAMQSession(_session); - _session.addUnacknowledgedMessage(msg.getDeliveryTag()); - _session.markDirty(); - break; - case Session.SESSION_TRANSACTED: - _session.addDeliveredMessage(msg.getDeliveryTag()); - _session.markDirty(); - break; - case Session.NO_ACKNOWLEDGE: - //do nothing. - //path used for NO-ACK consumers, and browsers (see constructor). - break; - } - } - - void postDeliver(AbstractJMSMessage msg) - { - switch (_acknowledgeMode) - { - case Session.DUPS_OK_ACKNOWLEDGE: - case Session.AUTO_ACKNOWLEDGE: - // we do not auto ack a message if the application code called recover() - if (!_session.isInRecovery()) - { - _session.acknowledgeMessage(msg.getDeliveryTag(), false); - } - - break; - } - } - - void notifyError(Throwable cause) - { - // synchronized (_closed) - { - setClosed(); - if (_logger.isDebugEnabled()) - { - StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); - if (_closedStack != null) - { - _logger.debug(_consumerTag + " notifyError():" - + Arrays.asList(stackTrace).subList(3, stackTrace.length - 1)); - _logger.debug(_consumerTag + " previously" + _closedStack.toString()); - } - else - { - _closedStack = Arrays.asList(stackTrace).subList(3, stackTrace.length - 1); - } - } - } - // QPID-293 can "request redelivery of this error through dispatcher" - - // we have no way of propagating the exception to a message listener - a JMS limitation - so we - // deal with the case where we have a synchronous receive() waiting for a message to arrive - if (!isMessageListenerSet()) - { - // offer only succeeds if there is a thread waiting for an item from the queue - if (_synchronousQueue.offer(cause)) - { - _logger.debug("Passed exception to synchronous queue for propagation to receive()"); - } - } - - deregisterConsumer(); - } - - /** - * Perform cleanup to deregister this consumer. This occurs when closing the consumer in both the clean case and in - * the case of an error occurring. - */ - private void deregisterConsumer() - { - _session.deregisterConsumer(this); - } - - /** The consumer tag allows us to close the consumer by sending a jmsCancel method to the broker */ - public int getConsumerTag() - { - return _consumerTag; - } - - public void setConsumerTag(int consumerTag) - { - _consumerTag = consumerTag; - } - - public AMQSession getSession() - { - return _session; - } - - private void checkPreConditions() throws JMSException - { - - this.checkNotClosed(); - - if ((_session == null) || _session.isClosed()) - { - throw new javax.jms.IllegalStateException("Invalid Session"); - } - } - - public boolean isAutoClose() - { - return _autoClose; - } - - public boolean isBrowseOnly() - { - return _browseOnly; - } - - public void rollback() - { - rollbackPendingMessages(); - } - - public void rollbackPendingMessages() - { - if (_synchronousQueue.size() > 0) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Rejecting the messages(" + _synchronousQueue - .size() + ") in _syncQueue (PRQ)" + "for consumer with tag:" + _consumerTag); - } - - Iterator iterator = _synchronousQueue.iterator(); - - int initialSize = _synchronousQueue.size(); - - boolean removed = false; - while (iterator.hasNext()) - { - - Object o = iterator.next(); - if (o instanceof AbstractJMSMessage) - { - _session.rejectMessage(((AbstractJMSMessage) o), true); - - if (_logger.isDebugEnabled()) - { - _logger.debug("Rejected message:" + ((AbstractJMSMessage) o).getDeliveryTag()); - } - - iterator.remove(); - removed = true; - - } - else - { - _logger.error("Queue contained a :" + o.getClass() - + " unable to reject as it is not an AbstractJMSMessage. Will be cleared"); - iterator.remove(); - removed = true; - } - } - - if (removed && (initialSize == _synchronousQueue.size())) - { - _logger.error("Queue had content removed but didn't change in size." + initialSize); - } - - - if (_synchronousQueue.size() != 0) - { - _logger.warn("Queue was not empty after rejecting all messages Remaining:" + _synchronousQueue.size()); - rollback(); - } - - clearReceiveQueue(); - } - } - - public String debugIdentity() - { - return String.valueOf(_consumerTag) + "[" + System.identityHashCode(this) + "]"; - } - - public void clearReceiveQueue() - { - _synchronousQueue.clear(); - } - - - public List<Long> drainReceiverQueueAndRetrieveDeliveryTags() - { - Iterator<AbstractJMSMessage> iterator = _synchronousQueue.iterator(); - List<Long> tags = new ArrayList<Long>(_synchronousQueue.size()); - - while (iterator.hasNext()) - { - - AbstractJMSMessage msg = iterator.next(); - tags.add(msg.getDeliveryTag()); - iterator.remove(); - } - return tags; - } - - public AMQShortString getQueuename() - { - return _queuename; - } - - public void setQueuename(AMQShortString queuename) - { - this._queuename = queuename; - } - - public void addBindingKey(AMQDestination amqd, String routingKey) throws AMQException - { - _session.addBindingKey(this,amqd,routingKey); - } - - /** to be called when a failover has occured */ - public void failedOverPre() - { - clearReceiveQueue(); - } - - public void failedOverPost() {} - - /** The connection being used by this consumer */ - protected AMQConnection getConnection() - { - return _connection; - } - - protected void setDestination(AMQDestination destination) - { - _destination = destination; - } - - /** We need to know the channel id when constructing frames */ - protected int getChannelId() - { - return _channelId; - } - - /** - * Used in the blocking receive methods to receive a message from the Session thread. - * <p> - * Or to notify of errors. - * <p> - * Argument true indicates we want strict FIFO semantics - */ - protected BlockingQueue getSynchronousQueue() - { - return _synchronousQueue; - } - - protected MessageFactoryRegistry getMessageFactory() - { - return _messageFactory; - } - - protected boolean isDurableSubscriber() - { - return _isDurableSubscriber; - } - - protected void markAsDurableSubscriber() - { - _isDurableSubscriber = true; - } - - void setAddressType(final int addressType) - { - _addressType = addressType; - } - - int getAddressType() - { - return _addressType; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer_0_10.java b/qpid/java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer_0_10.java deleted file mode 100644 index 0cb103f0cb..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer_0_10.java +++ /dev/null @@ -1,621 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; - -import java.util.Iterator; -import java.util.concurrent.atomic.AtomicBoolean; - -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageListener; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.AMQDestination.AddressOption; -import org.apache.qpid.client.message.AMQMessageDelegateFactory; -import org.apache.qpid.client.message.AMQMessageDelegate_0_10; -import org.apache.qpid.client.message.AbstractJMSMessage; -import org.apache.qpid.client.message.MessageFactoryRegistry; -import org.apache.qpid.client.message.UnprocessedMessage_0_10; -import org.apache.qpid.common.ServerPropertyNames; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.jms.Session; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.transport.Acquired; -import org.apache.qpid.transport.MessageCreditUnit; -import org.apache.qpid.transport.Option; -import org.apache.qpid.transport.Range; -import org.apache.qpid.transport.RangeSet; -import org.apache.qpid.transport.RangeSetFactory; -import org.apache.qpid.transport.SessionException; -import org.apache.qpid.transport.TransportException; - -/** - * This is a 0.10 message consumer. - */ -public class BasicMessageConsumer_0_10 extends BasicMessageConsumer<UnprocessedMessage_0_10> -{ - - /** - * This class logger - */ - private final Logger _logger = LoggerFactory.getLogger(getClass()); - - /** - * The underlying QpidSession - */ - private AMQSession_0_10 _0_10session; - - /** - * Indicates whether this consumer receives pre-acquired messages - */ - private final boolean _preAcquire; - - /** - * Specify whether this consumer is performing a sync receive - */ - private final AtomicBoolean _syncReceive = new AtomicBoolean(false); - private String _consumerTagString; - - private final long _capacity; - - /** Flag indicating if the server supports message selectors */ - private final boolean _serverJmsSelectorSupport; - - protected BasicMessageConsumer_0_10(int channelId, AMQConnection connection, AMQDestination destination, - String messageSelector, boolean noLocal, MessageFactoryRegistry messageFactory, - AMQSession<?,?> session, FieldTable rawSelector, - int prefetchHigh, int prefetchLow, boolean exclusive, - int acknowledgeMode, boolean browseOnly, boolean autoClose) - throws JMSException - { - super(channelId, connection, destination, messageSelector, noLocal, messageFactory, session, rawSelector, - prefetchHigh, prefetchLow, exclusive, acknowledgeMode, browseOnly, autoClose); - _0_10session = (AMQSession_0_10) session; - - _serverJmsSelectorSupport = connection.isSupportedServerFeature(ServerPropertyNames.FEATURE_QPID_JMS_SELECTOR); - _preAcquire = evaluatePreAcquire(browseOnly, destination, _serverJmsSelectorSupport); - - _capacity = evaluateCapacity(destination); - - // This is due to the Destination carrying the temporary subscription name which is incorrect. - if (destination.isAddressResolved() && AMQDestination.TOPIC_TYPE == destination.getAddressType()) - { - boolean namedQueue = destination.getLink() != null && destination.getLink().getName() != null ; - - if (!namedQueue) - { - setDestination(destination.copyDestination()); - getDestination().setQueueName(null); - } - } - } - - @Override public void setConsumerTag(int consumerTag) - { - super.setConsumerTag(consumerTag); - _consumerTagString = String.valueOf(consumerTag); - } - - public String getConsumerTagString() - { - return _consumerTagString; - } - - /** - * - * This is invoked by the session thread when emptying the session message queue. - * We first check if the message is valid (match the selector) and then deliver it to the - * message listener or to the sync consumer queue. - * - * @param jmsMessage this message has already been processed so can't redo preDeliver - */ - @Override public void notifyMessage(AbstractJMSMessage jmsMessage) - { - try - { - if (checkPreConditions(jmsMessage)) - { - if (isMessageListenerSet() && _capacity == 0) - { - messageFlow(); - } - _logger.debug("messageOk, trying to notify"); - super.notifyMessage(jmsMessage); - } - else - { - // if we are synchronously waiting for a message - // and messages are not pre-fetched we then need to request another one - if(_capacity == 0) - { - messageFlow(); - } - } - } - catch (AMQException e) - { - _logger.error("Receivecd an Exception when receiving message",e); - getSession().getAMQConnection().exceptionReceived(e); - } - } - - /** - * This method is invoked when this consumer is stopped. - * It tells the broker to stop delivering messages to this consumer. - */ - @Override void sendCancel() throws AMQException - { - _0_10session.getQpidSession().messageCancel(getConsumerTagString()); - postSubscription(); - try - { - _0_10session.getQpidSession().sync(); - getSession().confirmConsumerCancelled(getConsumerTag()); // confirm cancel - } - catch (SessionException se) - { - _0_10session.setCurrentException(se); - } - - AMQException amqe = _0_10session.getCurrentException(); - if (amqe != null) - { - throw amqe; - } - } - - @Override void notifyMessage(UnprocessedMessage_0_10 messageFrame) - { - super.notifyMessage(messageFrame); - } - - @Override - protected void preDeliver(AbstractJMSMessage jmsMsg) - { - super.preDeliver(jmsMsg); - - if (getAcknowledgeMode() == org.apache.qpid.jms.Session.NO_ACKNOWLEDGE) - { - //For 0-10 we need to ensure that all messages are indicated processed in some way to - //ensure their AMQP command-id is marked completed, and so we must send a completion - //even for no-ack messages even though there isnt actually an 'acknowledgement' occurring. - //Add message to the unacked message list to ensure we dont lose record of it before - //sending a completion of some sort. - getSession().addUnacknowledgedMessage(jmsMsg.getDeliveryTag()); - } - } - - @Override public AbstractJMSMessage createJMSMessageFromUnprocessedMessage( - AMQMessageDelegateFactory delegateFactory, UnprocessedMessage_0_10 msg) throws Exception - { - AMQMessageDelegate_0_10.updateExchangeTypeMapping(msg.getMessageTransfer().getHeader(), ((AMQSession_0_10)getSession()).getQpidSession()); - return getMessageFactory().createMessage(msg.getMessageTransfer()); - } - - /** - * Check whether a message can be delivered to this consumer. - * - * @param message The message to be checked. - * @return true if the message matches the selector and can be acquired, false otherwise. - * @throws AMQException If the message preConditions cannot be checked due to some internal error. - */ - private boolean checkPreConditions(AbstractJMSMessage message) throws AMQException - { - boolean messageOk = true; - try - { - if (!_serverJmsSelectorSupport && getMessageSelectorFilter() != null) - { - messageOk = getMessageSelectorFilter().matches(message); - } - } - catch (Exception e) - { - throw new AMQException(AMQConstant.INTERNAL_ERROR, "Error when evaluating message selector", e); - } - - if (_logger.isDebugEnabled()) - { - _logger.debug("messageOk " + messageOk); - _logger.debug("_preAcquire " + _preAcquire); - } - - if (!messageOk) - { - if (_preAcquire) - { - // this is the case for topics - // We need to ack this message - if (_logger.isDebugEnabled()) - { - _logger.debug("filterMessage - trying to ack message"); - } - acknowledgeMessage(message); - } - else - { - if (_logger.isDebugEnabled()) - { - _logger.debug("filterMessage - not ack'ing message as not acquired"); - } - flushUnwantedMessage(message); - } - } - else if (!_preAcquire && !isBrowseOnly()) - { - // now we need to acquire this message if needed - // this is the case of queue with a message selector set - if (_logger.isDebugEnabled()) - { - _logger.debug("filterMessage - trying to acquire message"); - } - messageOk = acquireMessage(message); - _logger.debug("filterMessage - message acquire status : " + messageOk); - } - - return messageOk; - } - - - /** - * Acknowledge a message - * - * @param message The message to be acknowledged - * @throws AMQException If the message cannot be acquired due to some internal error. - */ - private void acknowledgeMessage(final AbstractJMSMessage message) throws AMQException - { - _0_10session.messageAcknowledge - (Range.newInstance((int) message.getDeliveryTag()), - getAcknowledgeMode() != org.apache.qpid.jms.Session.NO_ACKNOWLEDGE); - - final AMQException amqe = _0_10session.getCurrentException(); - if (amqe != null) - { - throw amqe; - } - } - - /** - * Flush an unwanted message. For 0-10 we need to ensure that all messages are indicated - * processed to ensure their AMQP command-id is marked completed. - * - * @param message The unwanted message to be flushed - * @throws AMQException If the unwanted message cannot be flushed due to some internal error. - */ - private void flushUnwantedMessage(final AbstractJMSMessage message) throws AMQException - { - _0_10session.flushProcessed(Range.newInstance((int) message.getDeliveryTag()),false); - - final AMQException amqe = _0_10session.getCurrentException(); - if (amqe != null) - { - throw amqe; - } - } - - /** - * Acquire a message - * - * @param message The message to be acquired - * @return true if the message has been acquired, false otherwise. - * @throws AMQException If the message cannot be acquired due to some internal error. - */ - private boolean acquireMessage(final AbstractJMSMessage message) throws AMQException - { - boolean result = false; - - final Acquired acq = _0_10session.getQpidSession().messageAcquire(Range.newInstance((int)message.getDeliveryTag())).get(); - - final RangeSet acquired = acq.getTransfers(); - if (acquired != null && acquired.size() > 0) - { - result = true; - } - return result; - } - - private void messageFlow() - { - _0_10session.getQpidSession().messageFlow(getConsumerTagString(), - MessageCreditUnit.MESSAGE, 1, - Option.UNRELIABLE); - } - - public void setMessageListener(final MessageListener messageListener) throws JMSException - { - super.setMessageListener(messageListener); - try - { - if (messageListener != null && _capacity == 0) - { - messageFlow(); - } - if (messageListener != null && !getSynchronousQueue().isEmpty()) - { - Iterator messages= getSynchronousQueue().iterator(); - while (messages.hasNext()) - { - AbstractJMSMessage message=(AbstractJMSMessage) messages.next(); - messages.remove(); - getSession().rejectMessage(message, true); - } - } - } - catch(TransportException e) - { - throw getSession().toJMSException("Exception while setting message listener:" + e.getMessage(), e); - } - } - - public void failedOverPost() - { - if (_0_10session.isStarted() && _syncReceive.get()) - { - messageFlow(); - } - } - - /** - * When messages are not prefetched we need to request a message from the - * broker. - * Note that if the timeout is too short a message may be queued in _synchronousQueue until - * this consumer closes or request it. - * @param l - * @return - * @throws InterruptedException - */ - public Object getMessageFromQueue(long l) throws InterruptedException - { - if (_capacity == 0) - { - _syncReceive.set(true); - } - if (_0_10session.isStarted() && isMessageListenerSet() && _capacity == 0 && getSynchronousQueue().isEmpty()) - { - messageFlow(); - } - Object o = super.getMessageFromQueue(l); - if (o == null && _0_10session.isStarted()) - { - - _0_10session.getQpidSession().messageFlush - (getConsumerTagString(), Option.UNRELIABLE, Option.SYNC); - _0_10session.getQpidSession().sync(); - _0_10session.getQpidSession().messageFlow - (getConsumerTagString(), MessageCreditUnit.BYTE, - 0xFFFFFFFF, Option.UNRELIABLE); - - if (_capacity > 0) - { - _0_10session.getQpidSession().messageFlow - (getConsumerTagString(), - MessageCreditUnit.MESSAGE, - _capacity, - Option.UNRELIABLE); - } - _0_10session.syncDispatchQueue(false); - o = super.getMessageFromQueue(-1); - } - if (_capacity == 0) - { - _syncReceive.set(false); - } - return o; - } - - void postDeliver(AbstractJMSMessage msg) - { - super.postDeliver(msg); - - switch (getAcknowledgeMode()) - { - case Session.SESSION_TRANSACTED: - _0_10session.sendTxCompletionsIfNecessary(); - break; - case Session.NO_ACKNOWLEDGE: - if (!getSession().isInRecovery()) - { - getSession().acknowledgeMessage(msg.getDeliveryTag(), false); - } - break; - case Session.AUTO_ACKNOWLEDGE: - if (!getSession().isInRecovery() && getSession().getAMQConnection().getSyncAck()) - { - ((AMQSession_0_10) getSession()).getQpidSession().sync(); - } - break; - } - - } - - Message receiveBrowse() throws JMSException - { - return receiveNoWait(); - } - - @Override public void rollbackPendingMessages() - { - if (getSynchronousQueue().size() > 0) - { - RangeSet ranges = RangeSetFactory.createRangeSet(); - Iterator iterator = getSynchronousQueue().iterator(); - while (iterator.hasNext()) - { - - Object o = iterator.next(); - if (o instanceof AbstractJMSMessage) - { - ranges.add((int) ((AbstractJMSMessage) o).getDeliveryTag()); - iterator.remove(); - } - else - { - _logger.error("Queue contained a :" + o.getClass() - + " unable to reject as it is not an AbstractJMSMessage. Will be cleared"); - iterator.remove(); - } - } - - _0_10session.flushProcessed(ranges, false); - _0_10session.getQpidSession().messageRelease(ranges); - clearReceiveQueue(); - } - } - - - void postSubscription() throws AMQException - { - AMQDestination dest = this.getDestination(); - if (dest != null && dest.getDestSyntax() == AMQDestination.DestSyntax.ADDR) - { - if (dest.getDelete() == AddressOption.ALWAYS || - dest.getDelete() == AddressOption.RECEIVER ) - { - getSession().handleNodeDelete(dest); - } - // Subscription queue is handled as part of linkDelete method. - getSession().handleLinkDelete(dest); - if (!isDurableSubscriber()) - { - ((AMQSession_0_10) getSession()).deleteSubscriptionQueue(dest); - } - } - } - - long getCapacity() - { - return _capacity; - } - - boolean isPreAcquire() - { - return _preAcquire; - } - - private boolean evaluatePreAcquire(boolean browseOnly, AMQDestination destination, boolean serverJmsSelectorSupport) - { - boolean preAcquire; - if (browseOnly) - { - preAcquire = false; - } - else - { - boolean isQueue = (destination instanceof AMQQueue || getDestination().getAddressType() == AMQDestination.QUEUE_TYPE); - if (!serverJmsSelectorSupport && isQueue && getMessageSelectorFilter() != null) - { - preAcquire = false; - } - else - { - preAcquire = true; - } - } - return preAcquire; - } - - private long evaluateCapacity(AMQDestination destination) - { - long capacity = 0; - if (destination.getLink() != null && destination.getLink().getConsumerCapacity() >= 0) - { - capacity = destination.getLink().getConsumerCapacity(); - } - else if (getSession().prefetch()) - { - capacity = getSession().getPrefetch(); - } - return capacity; - } - - @Override - public Message receive(final long l) throws JMSException - { - long capacity = getCapacity(); - try - { - AMQSession_0_10 session = (AMQSession_0_10) getSession(); - - if (capacity == 0 && getMessageListener() == null) - { - session.getQpidSession().messageFlow(getConsumerTagString(), - MessageCreditUnit.MESSAGE, 1, - Option.UNRELIABLE); - - session.sync(); - - } - - Message message = super.receive(l); - - if (message == null && capacity == 0 && getMessageListener() == null) - { - session.getQpidSession().messageFlow(getConsumerTagString(), - MessageCreditUnit.MESSAGE, 0, - Option.UNRELIABLE); - session.sync(); - - message = super.receiveNoWait(); - } - return message; - } - catch (AMQException e) - { - throw new JMSAMQException(e); - } - } - - @Override - public Message receiveNoWait() throws JMSException - { - long capacity = getCapacity(); - try - { - AMQSession_0_10 session = (AMQSession_0_10) getSession(); - - if (capacity == 0 && getMessageListener() == null) - { - session.getQpidSession().messageFlow(getConsumerTagString(), - MessageCreditUnit.MESSAGE, 1, - Option.UNRELIABLE); - - session.sync(); - } - Message message = super.receiveNoWait(); - if (message == null && capacity == 0 && getMessageListener() == null) - { - session.getQpidSession().messageFlow(getConsumerTagString(), - MessageCreditUnit.MESSAGE, 0, - Option.UNRELIABLE); - session.sync(); - - message = super.receiveNoWait(); - } - return message; - } - catch (AMQException e) - { - throw new JMSAMQException(e); - } - - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer_0_8.java b/qpid/java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer_0_8.java deleted file mode 100644 index 4f2715bd7b..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer_0_8.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.client; - -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.Session; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.failover.FailoverException; -import org.apache.qpid.client.message.AMQMessageDelegateFactory; -import org.apache.qpid.client.message.AbstractJMSMessage; -import org.apache.qpid.client.message.MessageFactoryRegistry; -import org.apache.qpid.client.message.UnprocessedMessage_0_8; -import org.apache.qpid.common.AMQPFilterTypes; -import org.apache.qpid.configuration.ClientProperties; -import org.apache.qpid.framing.AMQFrame; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicCancelBody; -import org.apache.qpid.framing.BasicCancelOkBody; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.jms.ConnectionURL; - -public class BasicMessageConsumer_0_8 extends BasicMessageConsumer<UnprocessedMessage_0_8> -{ - private final Logger _logger = LoggerFactory.getLogger(getClass()); - private AMQSession_0_8.DestinationCache<AMQTopic> _topicDestinationCache; - private AMQSession_0_8.DestinationCache<AMQQueue> _queueDestinationCache; - - private final RejectBehaviour _rejectBehaviour; - - protected BasicMessageConsumer_0_8(int channelId, AMQConnection connection, AMQDestination destination, - String messageSelector, boolean noLocal, MessageFactoryRegistry messageFactory, AMQSession_0_8 session, - FieldTable rawSelector, int prefetchHigh, int prefetchLow, boolean exclusive, - int acknowledgeMode, boolean browseOnly, boolean autoClose) throws JMSException - { - super(channelId, connection, destination,messageSelector,noLocal,messageFactory,session, - rawSelector, prefetchHigh, prefetchLow, exclusive, acknowledgeMode, - browseOnly, autoClose); - final FieldTable consumerArguments = getArguments(); - if (isAutoClose()) - { - consumerArguments.put(AMQPFilterTypes.AUTO_CLOSE.getValue(), Boolean.TRUE); - } - - if (isBrowseOnly()) - { - consumerArguments.put(AMQPFilterTypes.NO_CONSUME.getValue(), Boolean.TRUE); - } - - - _topicDestinationCache = session.getTopicDestinationCache(); - _queueDestinationCache = session.getQueueDestinationCache(); - - - // This is due to the Destination carrying the temporary subscription name which is incorrect. - if (destination.isAddressResolved() && AMQDestination.TOPIC_TYPE == destination.getAddressType()) - { - boolean namedQueue = destination.getLink() != null && destination.getLink().getName() != null ; - - if (!namedQueue) - { - setDestination(destination.copyDestination()); - getDestination().setQueueName(null); - } - } - - if (destination.getRejectBehaviour() != null) - { - _rejectBehaviour = destination.getRejectBehaviour(); - } - else - { - ConnectionURL connectionURL = connection.getConnectionURL(); - String rejectBehaviour = connectionURL.getOption(ConnectionURL.OPTIONS_REJECT_BEHAVIOUR); - if (rejectBehaviour != null) - { - _rejectBehaviour = RejectBehaviour.valueOf(rejectBehaviour.toUpperCase()); - } - else - { - // use the default value for all connections, if not set - rejectBehaviour = System.getProperty(ClientProperties.REJECT_BEHAVIOUR_PROP_NAME, RejectBehaviour.NORMAL.toString()); - _rejectBehaviour = RejectBehaviour.valueOf( rejectBehaviour.toUpperCase()); - } - } - } - - @Override - public AMQSession_0_8 getSession() - { - return (AMQSession_0_8) super.getSession(); - } - - void sendCancel() throws AMQException, FailoverException - { - BasicCancelBody body = getSession().getMethodRegistry().createBasicCancelBody(new AMQShortString(String.valueOf(getConsumerTag())), false); - - final AMQFrame cancelFrame = body.generateFrame(getChannelId()); - - getConnection().getProtocolHandler().syncWrite(cancelFrame, BasicCancelOkBody.class); - postSubscription(); - getSession().sync(); - if (_logger.isDebugEnabled()) - { - _logger.debug("CancelOk'd for consumer:" + debugIdentity()); - } - } - - void postSubscription() throws AMQException - { - AMQDestination dest = this.getDestination(); - if (dest != null && dest.getDestSyntax() == AMQDestination.DestSyntax.ADDR) - { - if (dest.getDelete() == AMQDestination.AddressOption.ALWAYS || - dest.getDelete() == AMQDestination.AddressOption.RECEIVER ) - { - getSession().handleNodeDelete(dest); - } - // Subscription queue is handled as part of linkDelete method. - getSession().handleLinkDelete(dest); - if (!isDurableSubscriber()) - { - getSession().deleteSubscriptionQueue(dest); - } - } - } - - public AbstractJMSMessage createJMSMessageFromUnprocessedMessage(AMQMessageDelegateFactory delegateFactory, UnprocessedMessage_0_8 messageFrame)throws Exception - { - - return getMessageFactory().createMessage(messageFrame.getDeliveryTag(), - messageFrame.isRedelivered(), messageFrame.getExchange() == null ? AMQShortString.EMPTY_STRING : messageFrame.getExchange(), - messageFrame.getRoutingKey(), messageFrame.getContentHeader(), messageFrame.getBodies(), - _queueDestinationCache, _topicDestinationCache, getAddressType()); - - } - - Message receiveBrowse() throws JMSException - { - return receive(); - } - - public RejectBehaviour getRejectBehaviour() - { - return _rejectBehaviour; - } - - - @Override - public Message receive(final long l) throws JMSException - { - boolean manageCredit = getSession().isManagingCredit(); - boolean creditModified = false; - try - { - if (manageCredit) - { - creditModified = getSession().ensureCreditForReceive(); - } - Message message = super.receive(l); - if (creditModified && message == null) - { - getSession().reduceCreditAfterAcknowledge(); - } - if (manageCredit && !(getSession().getAcknowledgeMode() == Session.AUTO_ACKNOWLEDGE - || getSession().getAcknowledgeMode() == Session.DUPS_OK_ACKNOWLEDGE) && message != null) - { - getSession().updateCurrentPrefetch(1); - } - return message; - } - catch (AMQException e) - { - throw new JMSAMQException(e); - } - } - - @Override - public Message receiveNoWait() throws JMSException - { - boolean manageCredit = getSession().isManagingCredit(); - boolean creditModified = false; - try - { - if (manageCredit) - { - creditModified = getSession().ensureCreditForReceive(); - if (creditModified) - { - getSession().sync(); - } - } - Message message = super.receiveNoWait(); - if (creditModified && message == null) - { - getSession().reduceCreditAfterAcknowledge(); - } - if (manageCredit && !(getSession().getAcknowledgeMode() == Session.AUTO_ACKNOWLEDGE - || getSession().getAcknowledgeMode() == Session.DUPS_OK_ACKNOWLEDGE) && message != null) - { - getSession().updateCurrentPrefetch(1); - } - return message; - } - catch (AMQException e) - { - throw new JMSAMQException(e); - } - } - - - void postDeliver(AbstractJMSMessage msg) - { - getSession().reduceCreditInPostDeliver(); - super.postDeliver(msg); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer.java b/qpid/java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer.java deleted file mode 100644 index f72d915c25..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer.java +++ /dev/null @@ -1,736 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; - -import java.util.UUID; - -import javax.jms.BytesMessage; -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.InvalidDestinationException; -import javax.jms.JMSException; -import javax.jms.MapMessage; -import javax.jms.Message; -import javax.jms.ObjectMessage; -import javax.jms.StreamMessage; -import javax.jms.TextMessage; -import javax.jms.Topic; - -import org.slf4j.Logger; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.message.AbstractJMSMessage; -import org.apache.qpid.client.message.MessageConverter; -import org.apache.qpid.transport.TransportException; -import org.apache.qpid.util.UUIDGen; -import org.apache.qpid.util.UUIDs; - -public abstract class BasicMessageProducer extends Closeable implements org.apache.qpid.jms.MessageProducer -{ - - - enum PublishMode { ASYNC_PUBLISH_ALL, SYNC_PUBLISH_PERSISTENT, SYNC_PUBLISH_ALL }; - - private final Logger _logger ; - - private AMQConnection _connection; - - private boolean _disableTimestamps; - - /** - * Priority of messages created by this producer. - */ - private int _messagePriority = Message.DEFAULT_PRIORITY; - - /** - * Time to live of messages. Specified in milliseconds but AMQ has 1 second resolution. - */ - private long _timeToLive; - - /** - * Delivery mode used for this producer. - */ - private int _deliveryMode = DeliveryMode.PERSISTENT; - - private AMQDestination _destination; - - /** - * True if this producer was created from a transacted session - */ - private boolean _transacted; - - private int _channelId; - - /** - * This is an id generated by the session and is used to tie individual producers to the session. This means we - * can deregister a producer with the session when the producer is clsoed. We need to be able to tie producers - * to the session so that when an error is propagated to the session it can close the producer (meaning that - * a client that happens to hold onto a producer reference will get an error if he tries to use it subsequently). - */ - private long _producerId; - - private AMQSession _session; - - private final boolean _immediate; - - private final Boolean _mandatory; - - private boolean _disableMessageId; - - private UUIDGen _messageIdGenerator = UUIDs.newGenerator(); - - private String _userID; // ref user id used in the connection. - - - /** - * The default value for immediate flag used this producer is false. That is, a consumer does - * not need to be attached to a queue. - */ - private final boolean _defaultImmediateValue = Boolean.parseBoolean(System.getProperty("qpid.default_immediate", "false")); - - /** - * The default value for mandatory flag used by this producer is true. That is, server will not - * silently drop messages where no queue is connected to the exchange for the message. - */ - private final boolean _defaultMandatoryValue = Boolean.parseBoolean(System.getProperty("qpid.default_mandatory", "true")); - - /** - * The default value for mandatory flag used by this producer when publishing to a Topic is false. That is, server - * will silently drop messages where no queue is connected to the exchange for the message. - */ - private final boolean _defaultMandatoryTopicValue = - Boolean.parseBoolean(System.getProperty("qpid.default_mandatory_topic", - System.getProperties().containsKey("qpid.default_mandatory") - ? System.getProperty("qpid.default_mandatory") - : "false")); - - private PublishMode _publishMode = PublishMode.ASYNC_PUBLISH_ALL; - - protected BasicMessageProducer(Logger logger,AMQConnection connection, AMQDestination destination, boolean transacted, int channelId, - AMQSession session, long producerId, Boolean immediate, Boolean mandatory) throws AMQException - { - _logger = logger; - _connection = connection; - _destination = destination; - _transacted = transacted; - _channelId = channelId; - _session = session; - _producerId = producerId; - if (destination != null && !(destination.neverDeclare())) - { - declareDestination(destination); - } - - _immediate = immediate == null ? _defaultImmediateValue : immediate; - _mandatory = mandatory == null - ? destination == null ? null - : destination instanceof Topic - ? _defaultMandatoryTopicValue - : _defaultMandatoryValue - : mandatory; - - _userID = connection.getUsername(); - setPublishMode(); - } - - protected AMQConnection getConnection() - { - return _connection; - } - - void setPublishMode() - { - // Publish mode could be configured at destination level as well. - // Will add support for this when we provide a more robust binding URL - - String syncPub = _connection.getSyncPublish(); - // Support for deprecated option sync_persistence - if (syncPub.equals("persistent") || _connection.getSyncPersistence()) - { - _publishMode = PublishMode.SYNC_PUBLISH_PERSISTENT; - } - else if (syncPub.equals("all")) - { - _publishMode = PublishMode.SYNC_PUBLISH_ALL; - } - - if (_logger.isDebugEnabled()) - { - _logger.debug("MessageProducer " + toString() + " using publish mode : " + _publishMode); - } - } - - void resubscribe() throws AMQException - { - if (_destination != null && !_destination.neverDeclare()) - { - declareDestination(_destination); - } - } - - abstract void declareDestination(AMQDestination destination) throws AMQException; - - public void setDisableMessageID(boolean b) throws JMSException - { - checkPreConditions(); - checkNotClosed(); - _disableMessageId = b; - } - - public boolean getDisableMessageID() throws JMSException - { - checkNotClosed(); - - return _disableMessageId; - } - - public void setDisableMessageTimestamp(boolean b) throws JMSException - { - checkPreConditions(); - _disableTimestamps = b; - } - - public boolean getDisableMessageTimestamp() throws JMSException - { - checkNotClosed(); - - return _disableTimestamps; - } - - public void setDeliveryMode(int i) throws JMSException - { - checkPreConditions(); - if ((i != DeliveryMode.NON_PERSISTENT) && (i != DeliveryMode.PERSISTENT)) - { - throw new JMSException("DeliveryMode must be either NON_PERSISTENT or PERSISTENT. Value of " + i - + " is illegal"); - } - - _deliveryMode = i; - } - - public int getDeliveryMode() throws JMSException - { - checkNotClosed(); - - return _deliveryMode; - } - - public void setPriority(int i) throws JMSException - { - checkPreConditions(); - if ((i < 0) || (i > 9)) - { - throw new IllegalArgumentException("Priority of " + i + " is illegal. Value must be in range 0 to 9"); - } - - _messagePriority = i; - } - - public int getPriority() throws JMSException - { - checkNotClosed(); - - return _messagePriority; - } - - public void setTimeToLive(long l) throws JMSException - { - checkPreConditions(); - if (l < 0) - { - throw new IllegalArgumentException("Time to live must be non-negative - supplied value was " + l); - } - - _timeToLive = l; - } - - public long getTimeToLive() throws JMSException - { - checkNotClosed(); - - return _timeToLive; - } - - protected AMQDestination getAMQDestination() - { - return _destination; - } - - /** - * The Destination used for this consumer, if specified upon creation. - */ - public Destination getDestination() throws JMSException - { - checkNotClosed(); - - return _destination; - } - - public void close() throws JMSException - { - setClosed(); - _session.deregisterProducer(_producerId); - AMQDestination dest = getAMQDestination(); - AMQSession ssn = getSession(); - if (!ssn.isClosed() && dest != null && dest.getDestSyntax() == AMQDestination.DestSyntax.ADDR) - { - try - { - if (dest.getDelete() == AMQDestination.AddressOption.ALWAYS || - dest.getDelete() == AMQDestination.AddressOption.SENDER ) - { - ssn.handleNodeDelete(dest); - } - ssn.handleLinkDelete(dest); - } - catch(TransportException e) - { - throw getSession().toJMSException("Exception while closing producer:" + e.getMessage(), e); - } - catch (AMQException e) - { - JMSException ex = new JMSException("Exception while closing producer:" + e.getMessage()); - ex.setLinkedException(e); - ex.initCause(e); - throw ex; - } - } - } - - public void send(Message message) throws JMSException - { - checkPreConditions(); - checkInitialDestination(); - - synchronized (_connection.getFailoverMutex()) - { - sendImpl(_destination, message, _deliveryMode, _messagePriority, _timeToLive, _mandatory, _immediate); - } - } - - public void send(Message message, int deliveryMode) throws JMSException - { - checkPreConditions(); - checkInitialDestination(); - - synchronized (_connection.getFailoverMutex()) - { - sendImpl(_destination, message, deliveryMode, _messagePriority, _timeToLive, _mandatory, _immediate); - } - } - - public void send(Message message, int deliveryMode, boolean immediate) throws JMSException - { - checkPreConditions(); - checkInitialDestination(); - synchronized (_connection.getFailoverMutex()) - { - sendImpl(_destination, message, deliveryMode, _messagePriority, _timeToLive, _mandatory, immediate); - } - } - - public void send(Message message, int deliveryMode, int priority, long timeToLive) throws JMSException - { - checkPreConditions(); - checkInitialDestination(); - synchronized (_connection.getFailoverMutex()) - { - sendImpl(_destination, message, deliveryMode, priority, timeToLive, _mandatory, _immediate); - } - } - - public void send(Destination destination, Message message) throws JMSException - { - checkPreConditions(); - checkDestination(destination); - synchronized (_connection.getFailoverMutex()) - { - validateDestination(destination); - sendImpl((AMQDestination) destination, message, _deliveryMode, _messagePriority, _timeToLive, - _mandatory == null - ? destination instanceof Topic - ? _defaultMandatoryTopicValue - : _defaultMandatoryValue - : _mandatory, - _immediate); - } - } - - public void send(Destination destination, Message message, int deliveryMode, int priority, long timeToLive) - throws JMSException - { - checkPreConditions(); - checkDestination(destination); - synchronized (_connection.getFailoverMutex()) - { - validateDestination(destination); - sendImpl((AMQDestination) destination, message, deliveryMode, priority, timeToLive, - _mandatory == null - ? destination instanceof Topic - ? _defaultMandatoryTopicValue - : _defaultMandatoryValue - : _mandatory, - _immediate); - } - } - - public void send(Destination destination, Message message, int deliveryMode, int priority, long timeToLive, - boolean mandatory) throws JMSException - { - checkPreConditions(); - checkDestination(destination); - synchronized (_connection.getFailoverMutex()) - { - validateDestination(destination); - sendImpl((AMQDestination) destination, message, deliveryMode, priority, timeToLive, mandatory, _immediate); - } - } - - public void send(Destination destination, Message message, int deliveryMode, int priority, long timeToLive, - boolean mandatory, boolean immediate) throws JMSException - { - checkPreConditions(); - checkDestination(destination); - synchronized (_connection.getFailoverMutex()) - { - validateDestination(destination); - sendImpl((AMQDestination) destination, message, deliveryMode, priority, timeToLive, mandatory, immediate); - } - } - - private AbstractJMSMessage convertToNativeMessage(Message message) throws JMSException - { - if (message instanceof AbstractJMSMessage) - { - return (AbstractJMSMessage) message; - } - else - { - AbstractJMSMessage newMessage; - - if (message instanceof BytesMessage) - { - newMessage = new MessageConverter(_session, (BytesMessage) message).getConvertedMessage(); - } - else if (message instanceof MapMessage) - { - newMessage = new MessageConverter(_session, (MapMessage) message).getConvertedMessage(); - } - else if (message instanceof ObjectMessage) - { - newMessage = new MessageConverter(_session, (ObjectMessage) message).getConvertedMessage(); - } - else if (message instanceof TextMessage) - { - newMessage = new MessageConverter(_session, (TextMessage) message).getConvertedMessage(); - } - else if (message instanceof StreamMessage) - { - newMessage = new MessageConverter(_session, (StreamMessage) message).getConvertedMessage(); - } - else - { - newMessage = new MessageConverter(_session, message).getConvertedMessage(); - } - - if (newMessage != null) - { - return newMessage; - } - else - { - throw new JMSException("Unable to send message, due to class conversion error: " - + message.getClass().getName()); - } - } - } - - private void validateDestination(Destination destination) throws JMSException - { - if (!(destination instanceof AMQDestination)) - { - throw new InvalidDestinationException("Unsupported destination class: " - + ((destination != null) ? destination.getClass() : null)); - } - - AMQDestination amqDestination = (AMQDestination) destination; - if(!amqDestination.isExchangeExistsChecked()) - { - try - { - declareDestination(amqDestination); - } - catch(Exception e) - { - JMSException ex = new InvalidDestinationException("Error validating destination"); - ex.initCause(e); - ex.setLinkedException(e); - - throw ex; - } - amqDestination.setExchangeExistsChecked(true); - } - } - - /** - * The caller of this method must hold the failover mutex. - * - * @param destination - * @param origMessage - * @param deliveryMode - * @param priority - * @param timeToLive - * @param mandatory - * @param immediate - * - * @throws JMSException - */ - protected void sendImpl(AMQDestination destination, Message origMessage, int deliveryMode, int priority, long timeToLive, - boolean mandatory, boolean immediate) throws JMSException - { - checkTemporaryDestination(destination); - origMessage.setJMSDestination(destination); - - AbstractJMSMessage message = convertToNativeMessage(origMessage); - - UUID messageId = null; - if (_disableMessageId) - { - message.setJMSMessageID((UUID)null); - } - else - { - messageId = _messageIdGenerator.generate(); - message.setJMSMessageID(messageId); - } - - try - { - sendMessage(destination, origMessage, message, messageId, deliveryMode, priority, timeToLive, mandatory, immediate); - } - catch (TransportException e) - { - throw getSession().toJMSException("Exception whilst sending:" + e.getMessage(), e); - } - - if (message != origMessage) - { - _logger.debug("Updating original message"); - origMessage.setJMSPriority(message.getJMSPriority()); - origMessage.setJMSTimestamp(message.getJMSTimestamp()); - if (_logger.isDebugEnabled()) - { - _logger.debug("Setting JMSExpiration:" + message.getJMSExpiration()); - } - origMessage.setJMSExpiration(message.getJMSExpiration()); - origMessage.setJMSMessageID(message.getJMSMessageID()); - } - - if (_transacted) - { - _session.markDirty(); - } - } - - abstract void sendMessage(AMQDestination destination, Message origMessage, AbstractJMSMessage message, - UUID messageId, int deliveryMode, int priority, long timeToLive, boolean mandatory, - boolean immediate) throws JMSException; - - private void checkTemporaryDestination(AMQDestination destination) throws InvalidDestinationException - { - if (destination instanceof TemporaryDestination) - { - _logger.debug("destination is temporary destination"); - TemporaryDestination tempDest = (TemporaryDestination) destination; - if (tempDest.getSession().isClosed()) - { - _logger.debug("session is closed"); - throw new InvalidDestinationException("Session for temporary destination has been closed"); - } - - if (tempDest.isDeleted()) - { - _logger.debug("destination is deleted"); - throw new InvalidDestinationException("Cannot send to a deleted temporary destination"); - } - } - } - - private void checkPreConditions() throws JMSException - { - checkNotClosed(); - - if ((_session == null) || _session.isClosed()) - { - throw new javax.jms.IllegalStateException("Invalid Session"); - } - if(_session.getAMQConnection().isClosed()) - { - throw new javax.jms.IllegalStateException("Connection closed"); - } - } - - private void checkInitialDestination() throws JMSException - { - if (_destination == null) - { - throw new UnsupportedOperationException("Destination is null"); - } - checkValidQueue(); - } - - private void checkDestination(Destination suppliedDestination) throws JMSException - { - if ((_destination != null) && (suppliedDestination != null)) - { - throw new UnsupportedOperationException( - "This message producer was created with a Destination, therefore you cannot use an unidentified Destination"); - } - - if(suppliedDestination instanceof AMQQueue) - { - AMQQueue destination = (AMQQueue) suppliedDestination; - checkValidQueue(destination); - } - if (suppliedDestination == null) - { - throw new InvalidDestinationException("Supplied Destination was invalid"); - } - - } - - private void checkValidQueue() throws JMSException - { - if(_destination instanceof AMQQueue) - { - checkValidQueue((AMQQueue) _destination); - } - } - - private void checkValidQueue(AMQQueue destination) throws JMSException - { - if (!destination.isCheckedForQueueBinding() && validateQueueOnSend()) - { - if (getSession().isStrictAMQP()) - { - getLogger().warn("AMQP does not support destination validation before publish"); - destination.setCheckedForQueueBinding(true); - } - else - { - if (isBound(destination)) - { - destination.setCheckedForQueueBinding(true); - } - else - { - throw new InvalidDestinationException("Queue: " + destination.getQueueName() - + " is not a valid destination (no binding on server)"); - } - } - } - } - - private boolean validateQueueOnSend() - { - return _connection.validateQueueOnSend(); - } - - /** - * The session used to create this producer - */ - public AMQSession getSession() - { - return _session; - } - - public boolean isBound(AMQDestination destination) throws JMSException - { - try - { - return _session.isQueueBound(destination.getExchangeName(), null, destination.getRoutingKey()); - } - catch (TransportException e) - { - throw getSession().toJMSException("Exception whilst checking destination binding:" + e.getMessage(), e); - } - } - - /** - * If true, messages will not get a timestamp. - */ - protected boolean isDisableTimestamps() - { - return _disableTimestamps; - } - - protected void setDisableTimestamps(boolean disableTimestamps) - { - _disableTimestamps = disableTimestamps; - } - - protected void setDestination(AMQDestination destination) - { - _destination = destination; - } - - protected int getChannelId() - { - return _channelId; - } - - protected void setChannelId(int channelId) - { - _channelId = channelId; - } - - protected void setSession(AMQSession session) - { - _session = session; - } - - protected String getUserID() - { - return _userID; - } - - protected void setUserID(String userID) - { - _userID = userID; - } - - protected PublishMode getPublishMode() - { - return _publishMode; - } - - protected void setPublishMode(PublishMode publishMode) - { - _publishMode = publishMode; - } - - Logger getLogger() - { - return _logger; - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer_0_10.java b/qpid/java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer_0_10.java deleted file mode 100644 index 06a3b08272..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer_0_10.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. - */ -package org.apache.qpid.client; - -import static org.apache.qpid.transport.Option.NONE; -import static org.apache.qpid.transport.Option.SYNC; -import static org.apache.qpid.transport.Option.UNRELIABLE; - -import java.nio.ByteBuffer; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import javax.jms.DeliveryMode; -import javax.jms.JMSException; -import javax.jms.Message; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.AMQDestination.DestSyntax; -import org.apache.qpid.client.message.AMQMessageDelegate_0_10; -import org.apache.qpid.client.message.AbstractJMSMessage; -import org.apache.qpid.client.message.QpidMessageProperties; -import org.apache.qpid.client.messaging.address.Link.Reliability; -import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.transport.Header; -import org.apache.qpid.transport.MessageAcceptMode; -import org.apache.qpid.transport.MessageAcquireMode; -import org.apache.qpid.transport.MessageDeliveryMode; -import org.apache.qpid.transport.MessageDeliveryPriority; -import org.apache.qpid.transport.MessageProperties; -import org.apache.qpid.transport.Option; -import org.apache.qpid.util.GZIPUtils; -import org.apache.qpid.util.Strings; - -/** - * This is a 0_10 message producer. - */ -public class BasicMessageProducer_0_10 extends BasicMessageProducer -{ - - private static final Logger _logger = LoggerFactory.getLogger(BasicMessageProducer_0_10.class); - private byte[] userIDBytes; - - BasicMessageProducer_0_10(AMQConnection connection, AMQDestination destination, boolean transacted, int channelId, - AMQSession session, long producerId, Boolean immediate, Boolean mandatory) throws AMQException - { - super(_logger, connection, destination, transacted, channelId, session, producerId, immediate, mandatory); - - userIDBytes = Strings.toUTF8(getUserID()); - } - - void declareDestination(AMQDestination destination) throws AMQException - { - if (destination.getDestSyntax() == DestSyntax.BURL) - { - if (getSession().isDeclareExchanges()) - { - String name = destination.getExchangeName().toString(); - ((AMQSession_0_10) getSession()).getQpidSession().exchangeDeclare - (name, - destination.getExchangeClass().toString(), - null, null, - name.startsWith("amq.") ? Option.PASSIVE : Option.NONE, - destination.isExchangeDurable() ? Option.DURABLE : Option.NONE, - destination.isExchangeAutoDelete() ? Option.AUTO_DELETE : Option.NONE); - } - } - else - { - try - { - getSession().resolveAddress(destination,false,false); - getSession().handleLinkCreation(destination); - getSession().sync(); - } - catch(Exception e) - { - AMQException ex = new AMQException("Exception occured while verifying destination",e); - throw ex; - } - } - } - - //--- Overwritten methods - - /** - * Sends a message to a given destination - */ - void sendMessage(AMQDestination destination, Message origMessage, AbstractJMSMessage message, - UUID messageId, int deliveryMode, int priority, long timeToLive, boolean mandatory, - boolean immediate) throws JMSException - { - message.prepareForSending(); - - AMQMessageDelegate_0_10 delegate = (AMQMessageDelegate_0_10) message.getDelegate(); - - DeliveryProperties deliveryProp = delegate.getDeliveryProperties(); - MessageProperties messageProps = delegate.getMessageProperties(); - - // On the receiving side, this will be read in to the JMSXUserID as well. - messageProps.setUserId(userIDBytes); - - if (messageId != null) - { - messageProps.setMessageId(messageId); - } - else if (messageProps.hasMessageId()) - { - messageProps.clearMessageId(); - } - - long currentTime = 0; - if (timeToLive > 0 || !isDisableTimestamps()) - { - currentTime = System.currentTimeMillis(); - } - - if (timeToLive > 0) - { - deliveryProp.setTtl(timeToLive); - message.setJMSExpiration(currentTime + timeToLive); - } - - if (!isDisableTimestamps()) - { - - deliveryProp.setTimestamp(currentTime); - message.setJMSTimestamp(currentTime); - } - - if (!deliveryProp.hasDeliveryMode() || deliveryProp.getDeliveryMode().getValue() != deliveryMode) - { - MessageDeliveryMode mode; - switch (deliveryMode) - { - case DeliveryMode.PERSISTENT: - mode = MessageDeliveryMode.PERSISTENT; - break; - case DeliveryMode.NON_PERSISTENT: - mode = MessageDeliveryMode.NON_PERSISTENT; - break; - default: - throw new IllegalArgumentException("illegal delivery mode: " + deliveryMode); - } - deliveryProp.setDeliveryMode(mode); - message.setJMSDeliveryMode(deliveryMode); - } - if (!deliveryProp.hasPriority() || deliveryProp.getPriority().getValue() != priority) - { - deliveryProp.setPriority(MessageDeliveryPriority.get((short) priority)); - message.setJMSPriority(priority); - } - String exchangeName = destination.getExchangeName() == null ? "" : destination.getExchangeName().toString(); - if ( deliveryProp.getExchange() == null || ! deliveryProp.getExchange().equals(exchangeName)) - { - deliveryProp.setExchange(exchangeName); - } - String routingKey = destination.getRoutingKey().toString(); - if (deliveryProp.getRoutingKey() == null || ! deliveryProp.getRoutingKey().equals(routingKey)) - { - deliveryProp.setRoutingKey(routingKey); - } - - if (destination.getDestSyntax() == AMQDestination.DestSyntax.ADDR && - (destination.getSubject() != null || - (messageProps.getApplicationHeaders() != null && messageProps.getApplicationHeaders().get(QpidMessageProperties.QPID_SUBJECT) != null)) - ) - { - Map<String,Object> appProps = messageProps.getApplicationHeaders(); - if (appProps == null) - { - appProps = new HashMap<String,Object>(); - messageProps.setApplicationHeaders(appProps); - } - - if (appProps.get(QpidMessageProperties.QPID_SUBJECT) == null) - { - // use default subject in address string - appProps.put(QpidMessageProperties.QPID_SUBJECT,destination.getSubject()); - } - - if (destination.getAddressType() == AMQDestination.TOPIC_TYPE) - { - deliveryProp.setRoutingKey((String) - messageProps.getApplicationHeaders().get(QpidMessageProperties.QPID_SUBJECT)); - } - } - - ByteBuffer data = message.getData(); - - if(data != null - && data.remaining() > getConnection().getMessageCompressionThresholdSize() - && getConnection().getDelegate().isMessageCompressionSupported() - && getConnection().isMessageCompressionDesired() - && messageProps.getContentEncoding() == null) - { - byte[] compressed = GZIPUtils.compressBufferToArray(data); - if(compressed != null) - { - messageProps.setContentEncoding(GZIPUtils.GZIP_CONTENT_ENCODING); - data = ByteBuffer.wrap(compressed); - } - } - - - messageProps.setContentLength(data == null ? 0 : data.remaining()); - - // send the message - try - { - org.apache.qpid.transport.Session ssn = (org.apache.qpid.transport.Session) - ((AMQSession_0_10) getSession()).getQpidSession(); - - // if true, we need to sync the delivery of this message - boolean sync = false; - - sync = ( (getPublishMode() == PublishMode.SYNC_PUBLISH_ALL) || - (getPublishMode() == PublishMode.SYNC_PUBLISH_PERSISTENT && - deliveryMode == DeliveryMode.PERSISTENT) - ); - - boolean unreliable = (destination.getDestSyntax() == DestSyntax.ADDR) && - (destination.getLink().getReliability() == Reliability.UNRELIABLE); - - - ByteBuffer buffer = data == null ? ByteBuffer.allocate(0) : data.slice(); - - ssn.messageTransfer(destination.getExchangeName() == null ? "" : destination.getExchangeName().toString(), - MessageAcceptMode.NONE, - MessageAcquireMode.PRE_ACQUIRED, - new Header(deliveryProp, messageProps), - buffer, sync ? SYNC : NONE, unreliable ? UNRELIABLE : NONE); - if (sync) - { - ssn.sync(); - ((AMQSession_0_10) getSession()).getCurrentException(); - } - - } - catch (Exception e) - { - JMSException jmse = new JMSException("Exception when sending message:" + e.getMessage()); - jmse.setLinkedException(e); - jmse.initCause(e); - throw jmse; - } - } - - @Override - public boolean isBound(AMQDestination destination) throws JMSException - { - return getSession().isQueueBound(destination); - } - - // We should have a close and closed method to distinguish between normal close - // and a close due to session or connection error. - @Override - public void close() throws JMSException - { - super.close(); - } - -} - diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer_0_8.java b/qpid/java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer_0_8.java deleted file mode 100644 index e4c879aca8..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer_0_8.java +++ /dev/null @@ -1,389 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.client; - -import java.nio.ByteBuffer; -import java.util.UUID; - -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.Queue; -import javax.jms.Topic; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.failover.FailoverException; -import org.apache.qpid.client.message.AMQMessageDelegate_0_8; -import org.apache.qpid.client.message.AbstractJMSMessage; -import org.apache.qpid.client.message.QpidMessageProperties; -import org.apache.qpid.client.protocol.AMQProtocolHandler; -import org.apache.qpid.client.protocol.BlockingMethodFrameListener; -import org.apache.qpid.configuration.ClientProperties; -import org.apache.qpid.framing.AMQFrame; -import org.apache.qpid.framing.AMQMethodBody; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicAckBody; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.BasicNackBody; -import org.apache.qpid.framing.BasicPublishBody; -import org.apache.qpid.framing.CompositeAMQDataBlock; -import org.apache.qpid.framing.ContentBody; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.ExchangeDeclareBody; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.MethodRegistry; -import org.apache.qpid.util.GZIPUtils; - -public class BasicMessageProducer_0_8 extends BasicMessageProducer -{ - private static final Logger _logger = LoggerFactory.getLogger(BasicMessageProducer_0_8.class); - private static final boolean SET_EXPIRATION_AS_TTL = Boolean.getBoolean(ClientProperties.SET_EXPIRATION_AS_TTL); - - BasicMessageProducer_0_8(AMQConnection connection, AMQDestination destination, boolean transacted, int channelId, - AMQSession session, AMQProtocolHandler protocolHandler, long producerId, Boolean immediate, Boolean mandatory) throws AMQException - { - super(_logger,connection, destination,transacted,channelId,session, producerId, immediate, mandatory); - } - - void declareDestination(AMQDestination destination) throws AMQException - { - - if (destination.getDestSyntax() == AMQDestination.DestSyntax.ADDR) - { - getSession().resolveAddress(destination, false, false); - - getSession().handleLinkCreation(destination); - getSession().sync(); - } - else - { - if (getSession().isDeclareExchanges()) - { - final MethodRegistry methodRegistry = getSession().getMethodRegistry(); - ExchangeDeclareBody body = - methodRegistry.createExchangeDeclareBody(getSession().getTicket(), - destination.getExchangeName(), - destination.getExchangeClass(), - destination.getExchangeName() - .toString() - .startsWith("amq."), - destination.isExchangeDurable(), - destination.isExchangeAutoDelete(), - destination.isExchangeInternal(), - true, - null); - AMQFrame declare = body.generateFrame(getChannelId()); - - getConnection().getProtocolHandler().writeFrame(declare); - } - } - } - - void sendMessage(AMQDestination destination, Message origMessage, AbstractJMSMessage message, - UUID messageId, int deliveryMode,int priority, long timeToLive, boolean mandatory, - boolean immediate) throws JMSException - { - - - - AMQMessageDelegate_0_8 delegate = (AMQMessageDelegate_0_8) message.getDelegate(); - BasicContentHeaderProperties contentHeaderProperties = delegate.getContentHeaderProperties(); - - AMQShortString routingKey = destination.getRoutingKey(); - - FieldTable headers = delegate.getContentHeaderProperties().getHeaders(); - - if (destination.getDestSyntax() == AMQDestination.DestSyntax.ADDR && - (destination.getSubject() != null - || (headers != null && headers.get(QpidMessageProperties.QPID_SUBJECT) != null))) - { - - if (headers.get(QpidMessageProperties.QPID_SUBJECT) == null) - { - // use default subject in address string - headers.setString(QpidMessageProperties.QPID_SUBJECT, destination.getSubject()); - } - - if (destination.getAddressType() == AMQDestination.TOPIC_TYPE) - { - routingKey = AMQShortString.valueOf(headers.getString(QpidMessageProperties.QPID_SUBJECT)); - } - } - - BasicPublishBody body = getSession().getMethodRegistry().createBasicPublishBody(getSession().getTicket(), - destination.getExchangeName(), - routingKey, - mandatory, - immediate); - - AMQFrame publishFrame = body.generateFrame(getChannelId()); - - message.prepareForSending(); - ByteBuffer payload = message.getData(); - - contentHeaderProperties.setUserId(getUserID()); - - //Set the JMS_QPID_DESTTYPE for 0-8/9 messages - int type; - if (destination instanceof Topic) - { - type = AMQDestination.TOPIC_TYPE; - } - else if (destination instanceof Queue) - { - type = AMQDestination.QUEUE_TYPE; - } - else - { - type = AMQDestination.UNKNOWN_TYPE; - } - - //Set JMS_QPID_DESTTYPE - delegate.getContentHeaderProperties().getHeaders().setInteger(CustomJMSXProperty.JMS_QPID_DESTTYPE.getShortStringName(), type); - - if (!isDisableTimestamps()) - { - final long currentTime = System.currentTimeMillis(); - contentHeaderProperties.setTimestamp(currentTime); - - if (timeToLive > 0) - { - if(!SET_EXPIRATION_AS_TTL) - { - //default behaviour used by Qpid - contentHeaderProperties.setExpiration(currentTime + timeToLive); - } - else - { - //alternative behaviour for brokers interpreting the expiration header directly as a TTL. - contentHeaderProperties.setExpiration(timeToLive); - } - } - else - { - contentHeaderProperties.setExpiration(0); - } - } - - contentHeaderProperties.setDeliveryMode((byte) deliveryMode); - contentHeaderProperties.setPriority((byte) priority); - - int size = (payload != null) ? payload.remaining() : 0; - - byte[] compressed; - if(size > getConnection().getMessageCompressionThresholdSize() - && getConnection().getDelegate().isMessageCompressionSupported() - && getConnection().isMessageCompressionDesired() - && contentHeaderProperties.getEncoding() == null - && (compressed = GZIPUtils.compressBufferToArray(payload)) != null) - { - contentHeaderProperties.setEncoding("gzip"); - payload = ByteBuffer.wrap(compressed); - size = compressed.length; - - } - final int contentBodyFrameCount = calculateContentBodyFrameCount(payload); - final AMQFrame[] frames = new AMQFrame[2 + contentBodyFrameCount]; - - if (payload != null) - { - createContentBodies(payload, frames, 2, getChannelId()); - } - - if ((contentBodyFrameCount != 0) && getLogger().isDebugEnabled()) - { - getLogger().debug("Sending content body frames to " + destination); - } - - - AMQFrame contentHeaderFrame = - ContentHeaderBody.createAMQFrame(getChannelId(), - contentHeaderProperties, size); - if(contentHeaderFrame.getSize() > getSession().getAMQConnection().getMaximumFrameSize()) - { - throw new JMSException("Unable to send message as the headers are too large (" - + contentHeaderFrame.getSize() - + " bytes, but the maximum negotiated frame size is " - + getSession().getAMQConnection().getMaximumFrameSize() - + ")."); - } - if (getLogger().isDebugEnabled()) - { - getLogger().debug("Sending content header frame to " + destination); - } - - frames[0] = publishFrame; - frames[1] = contentHeaderFrame; - final CompositeAMQDataBlock compositeFrame = new CompositeAMQDataBlock(frames); - - try - { - getSession().checkFlowControl(); - } - catch (InterruptedException e) - { - JMSException jmse = new JMSException("Interrupted while waiting for flow control to be removed"); - jmse.setLinkedException(e); - jmse.initCause(e); - throw jmse; - } - - AMQConnectionDelegate_8_0 connectionDelegate80 = (AMQConnectionDelegate_8_0) (getConnection().getDelegate()); - - boolean useConfirms = getPublishMode() == PublishMode.SYNC_PUBLISH_ALL - && (connectionDelegate80.isConfirmedPublishSupported() - || (!getSession().isTransacted() && connectionDelegate80.isConfirmedPublishNonTransactionalSupported())); - - if(!useConfirms) - { - getConnection().getProtocolHandler().writeFrame(compositeFrame); - } - else - { - final PublishConfirmMessageListener frameListener = new PublishConfirmMessageListener(getChannelId()); - try - { - - getConnection().getProtocolHandler().writeCommandFrameAndWaitForReply(compositeFrame, - frameListener); - - if(frameListener.isRejected()) - { - throw new JMSException("The message was not accepted by the server (e.g. because the address was no longer valid)"); - } - } - catch (AMQException e) - { - throw new JMSAMQException(e); - } - catch (FailoverException e) - { - throw new JMSAMQException("Fail-over interrupted send. Status of the send is uncertain.", e); - - } - } - } - - /** - * Create content bodies. This will split a large message into numerous bodies depending on the negotiated - * maximum frame size. - * - * @param payload - * @param frames - * @param offset - * @param channelId @return the array of content bodies - */ - private void createContentBodies(ByteBuffer payload, AMQFrame[] frames, int offset, int channelId) - { - - if (frames.length == (offset + 1)) - { - byte[] data = new byte[payload.remaining()]; - payload.get(data); - frames[offset] = ContentBody.createAMQFrame(channelId, new ContentBody(data)); - } - else - { - - final long framePayloadMax = getSession().getAMQConnection().getMaximumFrameSize() - 1; - long remaining = payload.remaining(); - for (int i = offset; i < frames.length; i++) - { - payload.position((int) framePayloadMax * (i - offset)); - int length = (remaining >= framePayloadMax) ? (int) framePayloadMax : (int) remaining; - payload.limit(payload.position() + length); - byte[] data = new byte[payload.remaining()]; - payload.get(data); - - frames[i] = ContentBody.createAMQFrame(channelId, new ContentBody(data)); - - remaining -= length; - } - } - - } - - private int calculateContentBodyFrameCount(ByteBuffer payload) - { - // we subtract one from the total frame maximum size to account for the end of frame marker in a body frame - // (0xCE byte). - int frameCount; - if ((payload == null) || (payload.remaining() == 0)) - { - frameCount = 0; - } - else - { - int dataLength = payload.remaining(); - final long framePayloadMax = getSession().getAMQConnection().getMaximumFrameSize() - 1; - int lastFrame = ((dataLength % framePayloadMax) > 0) ? 1 : 0; - frameCount = (int) (dataLength / framePayloadMax) + lastFrame; - } - - return frameCount; - } - - @Override - public AMQSession_0_8 getSession() - { - return (AMQSession_0_8) super.getSession(); - } - - private static class PublishConfirmMessageListener extends BlockingMethodFrameListener - { - private boolean _rejected; - - /** - * Creates a new method listener, that filters incoming method to just those that match the specified channel id. - * - * @param channelId The channel id to filter incoming methods with. - */ - public PublishConfirmMessageListener(final int channelId) - { - super(channelId); - } - - @Override - public boolean processMethod(final int channelId, final AMQMethodBody frame) - { - if (frame instanceof BasicAckBody) - { - return true; - } - else if (frame instanceof BasicNackBody) - { - _rejected = true; - return true; - } - else - { - return false; - } - } - - public boolean isRejected() - { - return _rejected; - } - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/ChannelToSessionMap.java b/qpid/java/client/src/main/java/org/apache/qpid/client/ChannelToSessionMap.java deleted file mode 100644 index 0ba5cfdacb..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/ChannelToSessionMap.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.client; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicInteger; - -public final class ChannelToSessionMap -{ - private final Map<Integer, AMQSession> _sessionMap = Collections.synchronizedMap(new LinkedHashMap<Integer, AMQSession>()); - private AtomicInteger _idFactory = new AtomicInteger(0); - private int _maxChannelID; - private int _minChannelID; - - public AMQSession get(int channelId) - { - return _sessionMap.get(channelId); - } - - public void put(int channelId, AMQSession session) - { - _sessionMap.put(channelId, session); - } - - public void remove(int channelId) - { - _sessionMap.remove(channelId); - } - - public List<AMQSession> values() - { - return new ArrayList<>(_sessionMap.values()); - } - - public int size() - { - return _sessionMap.size(); - } - - public void clear() - { - _sessionMap.clear(); - } - - /* - * Synchronized on whole method so that we don't need to consider the - * increment-then-reset path in too much detail - */ - public synchronized int getNextChannelId() - { - int id = _minChannelID; - - boolean done = false; - while (!done) - { - id = _idFactory.getAndIncrement(); - if (id == _maxChannelID) - { - //go back to the start - _idFactory.set(_minChannelID); - } - - done = (!_sessionMap.keySet().contains(id)); - } - - return id; - } - - public void setMaxChannelID(int maxChannelID) - { - _maxChannelID = maxChannelID; - } - - public void setMinChannelID(int minChannelID) - { - _minChannelID = minChannelID; - _idFactory.set(_minChannelID); - } -}
\ No newline at end of file diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/Closeable.java b/qpid/java/client/src/main/java/org/apache/qpid/client/Closeable.java deleted file mode 100644 index 2a3eb40a07..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/Closeable.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.client; - -import javax.jms.IllegalStateException; -import javax.jms.JMSException; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * Captures the 'closed' state of an object, that is initially open, can be tested to see if it is closed, and provides - * a 'close' method to close it. - * <p> - * TODO Might be better to make this an interface. This whole class doesn't really encapsulate a terribly neat - * piece of re-usable functionality. A simple interface defining a close method would suffice. - * <p> - * TODO The convenience method {@link #checkNotClosed} is not that helpfull, what if the caller wants to do something - * other than throw an exception? It doesn't really represent a very usefull re-usable piece of code. Consider - * inlining it and dropping the method. - */ -public abstract class Closeable -{ - /** - * We use an atomic boolean so that we do not have to synchronized access to this flag. Synchronizing access to this - * flag would mean have a synchronized block in every method. - */ - private final AtomicBoolean _closed = new AtomicBoolean(false); - - /** - * Are we in the process of closing. We have this distinction so we can - * still signal we are in the process of closing so other objects can tell - * the difference and tidy up. - */ - private final AtomicBoolean _closing = new AtomicBoolean(false); - - /** - * Checks if this is closed, and raises a JMSException if it is. - * - * @throws JMSException If this is closed. - */ - protected void checkNotClosed() throws JMSException - { - if (isClosed()) - { - throw new IllegalStateException("Object " + toString() + " has been closed"); - } - } - - /** - * Checks if this is closed. - * - * @return <tt>true</tt> if this is closed, <tt>false</tt> otherwise. - */ - public boolean isClosed() - { - return _closed.get(); - } - - /** - * Checks if this is closing. - * - * @return <tt>true</tt> if we are closing, <tt>false</tt> otherwise. - */ - public boolean isClosing() - { - return _closing.get(); - } - - public void resetClosedFlag() - { - _closed.set(false); - } - - protected boolean setClosed() - { - return _closed.getAndSet(true); - } - - protected void setClosing(boolean closing) - { - _closing.set(closing); - } - - /** - * Closes this object. - * - * @throws JMSException If this cannot be closed for any reason. - */ - public abstract void close() throws JMSException; -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/ConnectionTuneParameters.java b/qpid/java/client/src/main/java/org/apache/qpid/client/ConnectionTuneParameters.java deleted file mode 100644 index 40264f837e..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/ConnectionTuneParameters.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.client; - -public class ConnectionTuneParameters -{ - private long _frameMax; - - private int _channelMax; - - /** Heart-beating interval in seconds, null if not set, use 0 to disable */ - private Integer _heartbeat; - - private float _heartbeatTimeoutFactor; - - public float getHeartbeatTimeoutFactor() - { - return _heartbeatTimeoutFactor; - } - - public void setHeartbeatTimeoutFactor(float heartbeatTimeoutFactor) - { - _heartbeatTimeoutFactor = heartbeatTimeoutFactor; - } - - public long getFrameMax() - { - return _frameMax; - } - - public void setFrameMax(long frameMax) - { - _frameMax = frameMax; - } - - public int getChannelMax() - { - return _channelMax; - } - - public void setChannelMax(int channelMax) - { - _channelMax = channelMax; - } - - public Integer getHeartbeat() - { - return _heartbeat; - } - - public void setHeartbeat(Integer hearbeat) - { - _heartbeat = hearbeat; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/CustomJMSXProperty.java b/qpid/java/client/src/main/java/org/apache/qpid/client/CustomJMSXProperty.java deleted file mode 100644 index b2d1072e2b..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/CustomJMSXProperty.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.client; - -import org.apache.qpid.framing.AMQShortString; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.List; - -public enum CustomJMSXProperty -{ - JMS_AMQP_NULL, - JMS_QPID_DESTTYPE, - JMSXGroupID, - JMSXGroupSeq, - JMSXUserID; - - private static List<String> _names; - - static - { - CustomJMSXProperty[] properties = values(); - _names = new ArrayList<String>(properties.length); - for(CustomJMSXProperty property : properties) - { - _names.add(property.toString()); - } - - } - - private final AMQShortString _nameAsShortString; - - CustomJMSXProperty() - { - _nameAsShortString = new AMQShortString(toString()); - } - - public AMQShortString getShortStringName() - { - return _nameAsShortString; - } - - public static Enumeration asEnumeration() - { - return Collections.enumeration(_names); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/HeartbeatListener.java b/qpid/java/client/src/main/java/org/apache/qpid/client/HeartbeatListener.java deleted file mode 100644 index 32a7cb0b73..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/HeartbeatListener.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.client; - -public interface HeartbeatListener -{ - void heartbeatReceived(); - - void heartbeatSent(); - - static final HeartbeatListener DEFAULT = new HeartbeatListener() - { - public void heartbeatReceived() - { - } - - public void heartbeatSent() - { - } - }; -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/JMSAMQException.java b/qpid/java/client/src/main/java/org/apache/qpid/client/JMSAMQException.java deleted file mode 100644 index 8bb88a273e..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/JMSAMQException.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.client; - -import org.apache.qpid.AMQException; - -import javax.jms.JMSException; - -/** - * JMSException does not accept wrapped exceptions in its constructor. Presumably this is because it is a relatively old - * Java exception class, before this was added as a default to Throwable. This exception class accepts wrapped exceptions - * as well as error messages, through its constructor, but is a JMSException. - */ -public class JMSAMQException extends JMSException -{ - /** - * Creates a JMSException, wrapping another exception class. - * - * @param message The error message. - * @param cause The underlying exception that caused this one. May be null if none is to be set. - */ - public JMSAMQException(String message, Exception cause) - { - super(message); - - if (cause != null) - { - setLinkedException(cause); - initCause(cause); - } - } - - /** - * @param cause The underlying exception. - * - * @deprecated Use the other constructor and write a helpfull message. This one will be deleted. - */ - public JMSAMQException(AMQException cause) - { - super(cause.getMessage(), String.valueOf(cause.getErrorCode())); - setLinkedException(cause); - initCause(cause); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/JmsNotImplementedException.java b/qpid/java/client/src/main/java/org/apache/qpid/client/JmsNotImplementedException.java deleted file mode 100644 index 903514c35f..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/JmsNotImplementedException.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.client; - -import javax.jms.JMSException; - -public class JmsNotImplementedException extends JMSException -{ - public JmsNotImplementedException() - { - super("Not implemented"); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/MessageConsumerPair.java b/qpid/java/client/src/main/java/org/apache/qpid/client/MessageConsumerPair.java deleted file mode 100644 index 134159afe1..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/MessageConsumerPair.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.client; - -public class MessageConsumerPair -{ - private BasicMessageConsumer _consumer; - private Object _item; - - public MessageConsumerPair(BasicMessageConsumer consumer, Object item) - { - _consumer = consumer; - _item = item; - } - - public BasicMessageConsumer getConsumer() - { - return _consumer; - } - - public Object getItem() - { - return _item; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/QpidConnectionMetaData.java b/qpid/java/client/src/main/java/org/apache/qpid/client/QpidConnectionMetaData.java deleted file mode 100644 index 03574ceab3..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/QpidConnectionMetaData.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.client; - -import org.apache.qpid.common.QpidProperties; - -import javax.jms.ConnectionMetaData; -import javax.jms.JMSException; -import java.util.Enumeration; - -public class QpidConnectionMetaData implements ConnectionMetaData -{ - - private AMQConnection con; - - QpidConnectionMetaData(AMQConnection conn) - { - this.con = conn; - } - - public int getJMSMajorVersion() throws JMSException - { - return 1; - } - - public int getJMSMinorVersion() throws JMSException - { - return 1; - } - - public String getJMSProviderName() throws JMSException - { - return "Apache " + QpidProperties.getProductName(); - } - - public String getJMSVersion() throws JMSException - { - return "1.1"; - } - - public Enumeration getJMSXPropertyNames() throws JMSException - { - return CustomJMSXProperty.asEnumeration(); - } - - public int getProviderMajorVersion() throws JMSException - { - return con.getProtocolVersion().getMajorVersion(); - } - - public int getProviderMinorVersion() throws JMSException - { - return con.getProtocolVersion().getMinorVersion(); - } - - public String getProviderVersion() throws JMSException - { - return QpidProperties.getProductName() + " (Client: [" + getClientVersion() + "] ; Broker [" + getBrokerVersion() + "] ; Protocol: [ " - + getProtocolVersion() + "] )"; - } - - private String getProtocolVersion() - { - return con.getProtocolVersion().toString(); - } - - public String getBrokerVersion() - { - // TODO - get broker version - return "<unkown>"; - } - - public String getClientVersion() - { - return QpidProperties.getBuildVersion(); - } - - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/QueueReceiverAdaptor.java b/qpid/java/client/src/main/java/org/apache/qpid/client/QueueReceiverAdaptor.java deleted file mode 100644 index b778ee22d6..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/QueueReceiverAdaptor.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.client; - -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.Queue; -import javax.jms.QueueReceiver; - -/** - * Class that wraps a MessageConsumer for backwards JMS compatibility - * Returned by methods in AMQSession etc - */ -public class QueueReceiverAdaptor implements QueueReceiver { - - private MessageConsumer _consumer; - private Queue _queue; - - protected QueueReceiverAdaptor(Queue queue, MessageConsumer consumer) - { - _consumer = consumer; - _queue = queue; - } - - public String getMessageSelector() throws JMSException - { - checkPreConditions(); - return _consumer.getMessageSelector(); - } - - public MessageListener getMessageListener() throws JMSException - { - checkPreConditions(); - return _consumer.getMessageListener(); - } - - public void setMessageListener(MessageListener messageListener) throws JMSException - { - checkPreConditions(); - _consumer.setMessageListener(messageListener); - } - - public Message receive() throws JMSException - { - checkPreConditions(); - return _consumer.receive(); - } - - public Message receive(long l) throws JMSException - { - checkPreConditions(); - return _consumer.receive(l); - } - - public Message receiveNoWait() throws JMSException - { - checkPreConditions(); - return _consumer.receiveNoWait(); - } - - public void close() throws JMSException - { - _consumer.close(); - } - - /** - * Return the queue associated with this receiver - * @return - * @throws JMSException - */ - public Queue getQueue() throws JMSException - { - checkPreConditions(); - return _queue; - } - - private void checkPreConditions() throws javax.jms.IllegalStateException { - BasicMessageConsumer msgConsumer = (BasicMessageConsumer)_consumer; - - if (msgConsumer.isClosed() ){ - throw new javax.jms.IllegalStateException("Consumer is closed"); - } - - if(_queue == null){ - throw new UnsupportedOperationException("Queue is null"); - } - - AMQSession session = msgConsumer.getSession(); - - if(session == null || session.isClosed()){ - throw new javax.jms.IllegalStateException("Invalid Session"); - } - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/QueueSenderAdapter.java b/qpid/java/client/src/main/java/org/apache/qpid/client/QueueSenderAdapter.java deleted file mode 100644 index 0b797df9dd..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/QueueSenderAdapter.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ - -package org.apache.qpid.client; - -import javax.jms.Destination; -import javax.jms.InvalidDestinationException; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.Queue; -import javax.jms.QueueSender; - -public class QueueSenderAdapter implements QueueSender -{ - - private BasicMessageProducer _delegate; - private Queue _queue; - private boolean closed = false; - - public QueueSenderAdapter(BasicMessageProducer msgProducer, Queue queue) - { - _delegate = msgProducer; - _queue = queue; - } - - public Queue getQueue() throws JMSException - { - checkPreConditions(); - - return _queue; - } - - public void send(Message msg) throws JMSException - { - checkQueuePreConditions(_queue); - _delegate.send(msg); - } - - public void send(Queue queue, Message msg) throws JMSException - { - checkQueuePreConditions(queue); - _delegate.send(queue, msg); - } - - public void publish(Message msg, int deliveryMode, int priority, long timeToLive) throws JMSException - { - checkQueuePreConditions(_queue); - _delegate.send(msg, deliveryMode, priority, timeToLive); - } - - public void send(Queue queue, Message msg, int deliveryMode, int priority, long timeToLive) throws JMSException - { - checkQueuePreConditions(queue); - _delegate.send(queue, msg, deliveryMode, priority, timeToLive); - } - - public void close() throws JMSException - { - _delegate.close(); - closed = true; - } - - public int getDeliveryMode() throws JMSException - { - checkPreConditions(); - - return _delegate.getDeliveryMode(); - } - - public Destination getDestination() throws JMSException - { - checkPreConditions(); - - return _delegate.getDestination(); - } - - public boolean getDisableMessageID() throws JMSException - { - checkPreConditions(); - - return _delegate.getDisableMessageID(); - } - - public boolean getDisableMessageTimestamp() throws JMSException - { - checkPreConditions(); - - return _delegate.getDisableMessageTimestamp(); - } - - public int getPriority() throws JMSException - { - checkPreConditions(); - - return _delegate.getPriority(); - } - - public long getTimeToLive() throws JMSException - { - checkPreConditions(); - - return _delegate.getTimeToLive(); - } - - public void send(Destination dest, Message msg) throws JMSException - { - checkQueuePreConditions((Queue) dest); - _delegate.send(dest, msg); - } - - public void send(Message msg, int deliveryMode, int priority, long timeToLive) throws JMSException - { - checkQueuePreConditions(_queue); - _delegate.send(msg, deliveryMode, priority, timeToLive); - } - - public void send(Destination dest, Message msg, int deliveryMode, int priority, long timeToLive) throws JMSException - { - checkQueuePreConditions((Queue) dest); - _delegate.send(dest, msg, deliveryMode, priority, timeToLive); - } - - public void setDeliveryMode(int deliveryMode) throws JMSException - { - checkPreConditions(); - _delegate.setDeliveryMode(deliveryMode); - } - - public void setDisableMessageID(boolean disableMessageID) throws JMSException - { - checkPreConditions(); - _delegate.setDisableMessageID(disableMessageID); - } - - public void setDisableMessageTimestamp(boolean disableMessageTimestamp) throws JMSException - { - checkPreConditions(); - _delegate.setDisableMessageTimestamp(disableMessageTimestamp); - } - - public void setPriority(int priority) throws JMSException - { - checkPreConditions(); - _delegate.setPriority(priority); - } - - public void setTimeToLive(long timeToLive) throws JMSException - { - checkPreConditions(); - _delegate.setTimeToLive(timeToLive); - } - - private void checkPreConditions() throws JMSException - { - if (closed) - { - throw new javax.jms.IllegalStateException("Publisher is closed"); - } - - AMQSession session = ((BasicMessageProducer) _delegate).getSession(); - - if ((session == null) || session.isClosed()) - { - throw new javax.jms.IllegalStateException("Invalid Session"); - } - } - - private void checkQueuePreConditions(Queue queue) throws JMSException - { - checkPreConditions() ; - - if (queue == null) - { - throw new UnsupportedOperationException("Queue is null."); - } - - if (!(queue instanceof AMQDestination)) - { - throw new InvalidDestinationException("Queue: " + queue + " is not a valid Qpid queue"); - } - - AMQDestination destination = (AMQDestination) queue; - if (!destination.isCheckedForQueueBinding() && checkQueueBeforePublish()) - { - if (_delegate.getSession().isStrictAMQP()) - { - _delegate.getLogger().warn("AMQP does not support destination validation before publish, "); - destination.setCheckedForQueueBinding(true); - } - else - { - if (_delegate.isBound(destination)) - { - destination.setCheckedForQueueBinding(true); - } - else - { - throw new InvalidDestinationException("Queue: " + queue - + " is not a valid destination (no bindings on server"); - } - } - } - } - - private boolean checkQueueBeforePublish() - { - return "true".equalsIgnoreCase(System.getProperty("org.apache.qpid.client.verifyQueueBindingBeforePublish", "true")); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/RejectBehaviour.java b/qpid/java/client/src/main/java/org/apache/qpid/client/RejectBehaviour.java deleted file mode 100644 index e58a356bdc..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/RejectBehaviour.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.client; - -/** - * This enum can be used only with for 0-8/0-9/0-9-1 protocols connections to notify - * the client to delegate the requeue/DLQ decision to the server - * if <code>SERVER</code> value is specified. Otherwise the messages won't be moved to - * the DLQ (or dropped) when delivery count exceeds the maximum. - */ -public enum RejectBehaviour -{ - NORMAL, SERVER; -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/TemporaryDestination.java b/qpid/java/client/src/main/java/org/apache/qpid/client/TemporaryDestination.java deleted file mode 100644 index 6da3825359..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/TemporaryDestination.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.client; - -import org.apache.qpid.framing.AMQShortString; - -import javax.jms.Destination; -import javax.jms.JMSException; - -/** - * Provides support for convenience interface implemented by both AMQTemporaryTopic and AMQTemporaryQueue - * so that operations related to their "temporary-ness" can be abstracted out. - */ -interface TemporaryDestination extends Destination -{ - - public AMQShortString getAMQQueueName(); - public void delete() throws JMSException; - public AMQSession getSession(); - public boolean isDeleted(); - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/TopicPublisherAdapter.java b/qpid/java/client/src/main/java/org/apache/qpid/client/TopicPublisherAdapter.java deleted file mode 100644 index 0f3be4ba18..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/TopicPublisherAdapter.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.client; - -import javax.jms.Destination; -import javax.jms.IllegalStateException; -import javax.jms.InvalidDestinationException; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.Topic; -import javax.jms.TopicPublisher; - -public class TopicPublisherAdapter implements TopicPublisher -{ - - private BasicMessageProducer _delegate; - private Topic _topic; - - public TopicPublisherAdapter(BasicMessageProducer msgProducer, Topic topic) - { - _delegate = msgProducer; - _topic = topic; - } - - public Topic getTopic() throws JMSException - { - checkPreConditions(); - return _topic; - } - - public void publish(Message msg) throws JMSException - { - checkPreConditions(); - checkTopic(_topic); - _delegate.send(msg); - } - - public void publish(Topic topic, Message msg) throws JMSException - { - checkPreConditions(); - checkTopic(topic); - _delegate.send(topic, msg); - } - - public void publish(Message msg, int deliveryMode, int priority, long timeToLive) - throws JMSException - { - checkPreConditions(); - checkTopic(_topic); - _delegate.send(msg, deliveryMode, priority, timeToLive); - } - - public int getDeliveryMode() throws JMSException { - checkPreConditions(); - return _delegate.getDeliveryMode(); - } - - public void publish(Topic topic, Message msg, int deliveryMode, int priority, long timeToLive) - throws JMSException - { - checkPreConditions(); - checkTopic(topic); - _delegate.send(topic, msg, deliveryMode, priority, timeToLive); - } - - public void close() throws JMSException - { - _delegate.close(); - } - - public boolean getDisableMessageID() throws JMSException { - checkPreConditions(); - return _delegate.getDisableMessageID(); - } - - public boolean getDisableMessageTimestamp() throws JMSException { - checkPreConditions(); - return _delegate.getDisableMessageTimestamp(); - } - - public Destination getDestination() throws JMSException - { - checkPreConditions(); - return _delegate.getDestination(); - } - - public int getPriority() throws JMSException { - checkPreConditions(); - return _delegate.getPriority(); - } - - public long getTimeToLive() throws JMSException { - checkPreConditions(); - return _delegate.getTimeToLive(); - } - - public void send(Message msg) throws JMSException - { - checkPreConditions(); - checkTopic(_topic); - _delegate.send(msg); - } - - public void send(Destination dest, Message msg) throws JMSException - { - checkPreConditions(); - checkTopic(dest); - _delegate.send(dest, msg); - } - - public void send(Message msg, int deliveryMode, int priority, long timeToLive) - throws JMSException - { - checkPreConditions(); - checkTopic(_topic); - _delegate.send(msg, deliveryMode, priority, timeToLive); - } - - public void send(Destination dest, Message msg, int deliveryMode, int priority, long timeToLive) throws JMSException - { - checkPreConditions(); - checkTopic(dest); - _delegate.send(dest, msg, deliveryMode, priority, timeToLive); - } - - public void setDeliveryMode(int deliveryMode) throws JMSException - { - checkPreConditions(); - _delegate.setDeliveryMode(deliveryMode); - } - - public void setDisableMessageID(boolean disableMessageID) throws JMSException - { - checkPreConditions(); - _delegate.setDisableMessageID(disableMessageID); - } - - public void setDisableMessageTimestamp(boolean disableMessageTimestamp) throws JMSException - { - checkPreConditions(); - _delegate.setDisableMessageTimestamp(disableMessageTimestamp); - } - - public void setPriority(int priority) throws JMSException - { - checkPreConditions(); - _delegate.setPriority(priority); - } - - public void setTimeToLive(long timeToLive) throws JMSException - { - checkPreConditions(); - _delegate.setTimeToLive(timeToLive); - } - - private void checkPreConditions() throws IllegalStateException - { - if (_delegate.isClosed()) - { - throw new javax.jms.IllegalStateException("Publisher is _closed"); - } - - AMQSession session = _delegate.getSession(); - if (session == null || session.isClosed()) - { - throw new javax.jms.IllegalStateException("Invalid Session"); - } - } - - private void checkTopic(Destination topic) throws InvalidDestinationException - { - if (topic == null) - { - throw new UnsupportedOperationException("Topic is null"); - } - if (!(topic instanceof Topic)) - { - throw new InvalidDestinationException("Destination " + topic + " is not a topic"); - } - if(!(topic instanceof AMQDestination)) - { - throw new InvalidDestinationException("Destination " + topic + " is not a Qpid topic"); - } - - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/TopicSubscriberAdaptor.java b/qpid/java/client/src/main/java/org/apache/qpid/client/TopicSubscriberAdaptor.java deleted file mode 100644 index efe91f6797..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/TopicSubscriberAdaptor.java +++ /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. - * - */ -package org.apache.qpid.client; - -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageListener; -import javax.jms.Topic; -import javax.jms.TopicSubscriber; - -import org.apache.qpid.AMQException; - -/** - * Wraps a MessageConsumer to fulfill the extended TopicSubscriber contract - * - */ -class TopicSubscriberAdaptor<C extends BasicMessageConsumer> implements TopicSubscriber -{ - private final Topic _topic; - private final C _consumer; - private final boolean _noLocal; - - TopicSubscriberAdaptor(Topic topic, C consumer, boolean noLocal) - { - _topic = topic; - _consumer = consumer; - _noLocal = noLocal; - consumer.setAddressType(AMQDestination.TOPIC_TYPE); - } - - TopicSubscriberAdaptor(Topic topic, C consumer) - { - this(topic, consumer, consumer.isNoLocal()); - } - - public Topic getTopic() throws JMSException - { - checkPreConditions(); - return _topic; - } - - public boolean getNoLocal() throws JMSException - { - checkPreConditions(); - return _noLocal; - } - - public String getMessageSelector() throws JMSException - { - checkPreConditions(); - return _consumer.getMessageSelector(); - } - - public MessageListener getMessageListener() throws JMSException - { - checkPreConditions(); - return _consumer.getMessageListener(); - } - - public void setMessageListener(MessageListener messageListener) throws JMSException - { - checkPreConditions(); - _consumer.setMessageListener(messageListener); - } - - public Message receive() throws JMSException - { - checkPreConditions(); - return _consumer.receive(); - } - - public Message receive(long l) throws JMSException - { - return _consumer.receive(l); - } - - public Message receiveNoWait() throws JMSException - { - checkPreConditions(); - return _consumer.receiveNoWait(); - } - - public void close() throws JMSException - { - _consumer.close(); - } - - private void checkPreConditions() throws javax.jms.IllegalStateException{ - C msgConsumer = _consumer; - - if (msgConsumer.isClosed() ){ - throw new javax.jms.IllegalStateException("Consumer is closed"); - } - - if(_topic == null){ - throw new UnsupportedOperationException("Topic is null"); - } - - AMQSession session = msgConsumer.getSession(); - - if(session == null || session.isClosed()){ - throw new javax.jms.IllegalStateException("Invalid Session"); - } - } - - C getMessageConsumer() - { - return _consumer; - } - - public void addBindingKey(Topic topic, String bindingKey) throws AMQException - { - _consumer.addBindingKey((AMQDestination) topic, bindingKey); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/UnsupportedAddressSyntaxException.java b/qpid/java/client/src/main/java/org/apache/qpid/client/UnsupportedAddressSyntaxException.java deleted file mode 100644 index c65fd7c189..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/UnsupportedAddressSyntaxException.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.client; - -class UnsupportedAddressSyntaxException extends UnsupportedOperationException -{ - UnsupportedAddressSyntaxException(final AMQDestination dest) - { - super("The address '" + dest.toString() + "' uses the " + AMQDestination.DestSyntax.ADDR + " addressing syntax" - + " which is not supported for AMQP 0-8/0-9/0-9-1 connections. Use the " + AMQDestination.DestSyntax.BURL - + " syntax instead:\n" - + "\tBURL:<Exchange Class>://<Exchange Name>/[<Destination>]/[<Queue>][?<option>='<value>'[&<option>='<value>']]\n"); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/XAConnectionImpl.java b/qpid/java/client/src/main/java/org/apache/qpid/client/XAConnectionImpl.java deleted file mode 100644 index d625a9ae69..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/XAConnectionImpl.java +++ /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. - */ -package org.apache.qpid.client; - -import org.apache.qpid.AMQException; -import org.apache.qpid.jms.ConnectionURL; - -import javax.jms.JMSException; -import javax.jms.XAConnection; -import javax.jms.XAQueueConnection; -import javax.jms.XAQueueSession; -import javax.jms.XASession; -import javax.jms.XATopicConnection; -import javax.jms.XATopicSession; - -/** - * This class implements the javax.jms.XAConnection interface - */ -public class XAConnectionImpl extends AMQConnection implements XAConnection, XAQueueConnection, XATopicConnection -{ - //-- constructor - /** - * Create a XAConnection from a connectionURL - */ - public XAConnectionImpl(ConnectionURL connectionURL) throws AMQException - { - super(connectionURL); - } - - //-- interface XAConnection - /** - * Creates an XASession. - * - * @return A newly created XASession. - * @throws JMSException If the XAConnectiono fails to create an XASession due to - * some internal error. - */ - public synchronized XASession createXASession() throws JMSException - { - checkNotClosed(); - return getDelegate().createXASession(); - } - - //-- Interface XAQueueConnection - /** - * Creates an XAQueueSession. - * - * @return A newly created XASession. - * @throws JMSException If the XAQueueConnectionImpl fails to create an XASession due to - * some internal error. - */ - public XAQueueSession createXAQueueSession() throws JMSException - { - return (XAQueueSession) createXASession(); - } - - //-- Interface XATopicConnection - /** - * Creates an XAQueueSession. - * - * @return A newly created XASession. - * @throws JMSException If the XAQueueConnectionImpl fails to create an XASession due to - * some internal error. - */ - public XATopicSession createXATopicSession() throws JMSException - { - return (XATopicSession) createXASession(); - } - - //Specialized call for JCA - public XASession createXASession(int ackMode) throws JMSException - { - checkNotClosed(); - return getDelegate().createXASession(ackMode); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/XAResourceImpl.java b/qpid/java/client/src/main/java/org/apache/qpid/client/XAResourceImpl.java deleted file mode 100644 index 7e82981ad3..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/XAResourceImpl.java +++ /dev/null @@ -1,602 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.transaction.xa.XAException; -import javax.transaction.xa.XAResource; -import javax.transaction.xa.Xid; - -import org.apache.qpid.dtx.XidImpl; -import org.apache.qpid.transport.DtxXaStatus; -import org.apache.qpid.transport.ExecutionErrorCode; -import org.apache.qpid.transport.Future; -import org.apache.qpid.transport.Option; -import org.apache.qpid.transport.RecoverResult; -import org.apache.qpid.transport.SessionException; -import org.apache.qpid.transport.XaResult; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This is an implementation of javax.njms.XAResource. - */ -public class XAResourceImpl implements AMQXAResource -{ - /** - * this XAResourceImpl's logger - */ - private static final Logger _logger = LoggerFactory.getLogger(XAResourceImpl.class); - - /** - * Reference to the associated XASession - */ - private XASessionImpl _xaSession = null; - - /** - * The XID of this resource - */ - private Xid _xid; - - /** - * The time for this resource - */ - private int _timeout; - - //--- constructor - - private List<XAResource> _siblings = new ArrayList<XAResource>(); - - /** - * Create an XAResource associated with a XASession - * - * @param xaSession The session XAresource - */ - protected XAResourceImpl(XASessionImpl xaSession) - { - _xaSession = xaSession; - } - - //--- The XAResource - /** - * Commits the global transaction specified by xid. - * - * @param xid A global transaction identifier - * @param b If true, use a one-phase commit protocol to commit the work done on behalf of xid. - * @throws XAException An error has occurred. An error has occurred. Possible XAExceptions are XA_HEURHAZ, - * XA_HEURCOM, XA_HEURRB, XA_HEURMIX, XAER_RMERR, XAER_RMFAIL, XAER_NOTA, XAER_INVAL, or XAER_PROTO. - */ - public void commit(Xid xid, boolean b) throws XAException - { - if (_logger.isDebugEnabled()) - { - _logger.debug("commit tx branch with xid: {} ", xid); - } - Future<XaResult> future = - _xaSession.getQpidSession().dtxCommit(convertXid(xid), b ? Option.ONE_PHASE : Option.NONE); - - // now wait on the future for the result - XaResult result = null; - try - { - result = future.get(); - } - catch (SessionException e) - { - // we need to restore the qpid session that has been closed - _xaSession.createSession(); - convertExecutionErrorToXAErr(e.getException().getErrorCode()); - } - finally - { - _xid = null; - } - checkStatus(result.getStatus()); - } - - /** - * Ends the work performed on behalf of a transaction branch. - * The resource manager disassociates the XA resource from the transaction branch specified - * and lets the transaction complete. - * <ul> - * <li> If TMSUSPEND is specified in the flags, the transaction branch is temporarily suspended in an incomplete state. - * The transaction context is in a suspended state and must be resumed via the start method with TMRESUME specified. - * <li> If TMFAIL is specified, the portion of work has failed. The resource manager may mark the transaction as rollback-only - * <li> If TMSUCCESS is specified, the portion of work has completed successfully. - * </ul> - * - * @param xid A global transaction identifier that is the same as the identifier used previously in the start method - * @param flag One of TMSUCCESS, TMFAIL, or TMSUSPEND. - * @throws XAException An error has occurred. An error has occurred. Possible XAException values are XAER_RMERR, - * XAER_RMFAILED, XAER_NOTA, XAER_INVAL, XAER_PROTO, or XA_RB*. - */ - public void end(Xid xid, int flag) throws XAException - { - if (_logger.isDebugEnabled()) - { - _logger.debug("end tx branch with xid: {}", xid); - } - switch (flag) - { - case(XAResource.TMSUCCESS): - break; - case(XAResource.TMFAIL): - break; - case(XAResource.TMSUSPEND): - break; - default: - throw new XAException(XAException.XAER_INVAL); - } - _xaSession.flushAcknowledgments(); - Future<XaResult> future = _xaSession.getQpidSession() - .dtxEnd(convertXid(xid), - flag == XAResource.TMFAIL ? Option.FAIL : Option.NONE, - flag == XAResource.TMSUSPEND ? Option.SUSPEND : Option.NONE); - // now wait on the future for the result - XaResult result = null; - try - { - result = future.get(); - } - catch (SessionException e) - { - // we need to restore the qpid session that has been closed - _xaSession.createSession(); - convertExecutionErrorToXAErr(e.getException().getErrorCode()); - } - - checkStatus(result.getStatus()); - - if(_logger.isDebugEnabled()) - { - _logger.debug("Calling end for " + _siblings.size() + " XAResource siblings"); - } - - for(XAResource sibling: _siblings) - { - - sibling.end(xid, flag); - } - - _siblings.clear(); - } - - - /** - * Tells the resource manager to forget about a heuristically completed transaction branch. - * - * @param xid String(xid.getGlobalTransactionId() A global transaction identifier - * @throws XAException An error has occurred. Possible exception values are XAER_RMERR, XAER_RMFAIL, - * XAER_NOTA, XAER_INVAL, or XAER_PROTO. - */ - public void forget(Xid xid) throws XAException - { - if (_logger.isDebugEnabled()) - { - _logger.debug("forget tx branch with xid: {}", xid); - } - _xaSession.getQpidSession().dtxForget(convertXid(xid)); - try - { - _xaSession.getQpidSession().sync(); - } - catch (SessionException e) - { - // we need to restore the qpid session that has been closed - _xaSession.createSession(); - convertExecutionErrorToXAErr(e.getException().getErrorCode()); - } - finally - { - _xid = null; - } - } - - - /** - * Obtains the current transaction timeout value set for this XAResource instance. - * If XAResource.setTransactionTimeout was not used prior to invoking this method, - * the return value is the default timeout i.e. 0; - * - * @return The transaction timeout value in seconds. - * @throws XAException An error has occurred. Possible exception values are XAER_RMERR, XAER_RMFAIL. - */ - public int getTransactionTimeout() throws XAException - { - return _timeout; - } - - /** - * This method is called to determine if the resource manager instance represented - * by the target object is the same as the resouce manager instance represented by - * the parameter xaResource. - * - * @param xaResource An XAResource object whose resource manager instance is to - * be compared with the resource manager instance of the target object - * @return <code>true</code> if it's the same RM instance; otherwise <code>false</code>. - * @throws XAException An error has occurred. Possible exception values are XAER_RMERR, XAER_RMFAIL. - */ - public boolean isSameRM(XAResource xaResource) throws XAException - { - if(this == xaResource) - { - return true; - } - - if(!(xaResource instanceof AMQXAResource)) - { - return false; - } - - String myUUID = getBrokerUUID(); - String otherUUID = ((AMQXAResource)xaResource).getBrokerUUID(); - - if(_logger.isDebugEnabled()) - { - _logger.debug("Comparing my UUID " + myUUID + " with other UUID " + otherUUID); - } - - boolean isSameRm = (myUUID != null && otherUUID != null && myUUID.equals(otherUUID)); - - if(isSameRm) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("XAResource " + xaResource + " is from the ResourceManager. Adding XAResource as sibling for AMQP protocol support. "); - } - _siblings.add(xaResource); - } - - return isSameRm; - - } - - /** - * Prepare for a transaction commit of the transaction specified in <code>Xid</code>. - * - * @param xid A global transaction identifier. - * @return A value indicating the resource manager's vote on the outcome of the transaction. - * The possible values are: XA_RDONLY or XA_OK. - * @throws XAException An error has occurred. Possible exception values are: XAER_RMERR or XAER_NOTA - */ - public int prepare(Xid xid) throws XAException - { - if (_logger.isDebugEnabled()) - { - _logger.debug("prepare {}", xid); - } - Future<XaResult> future = _xaSession.getQpidSession().dtxPrepare(convertXid(xid)); - XaResult result = null; - try - { - result = future.get(); - } - catch (SessionException e) - { - // we need to restore the qpid session that has been closed - _xaSession.createSession(); - convertExecutionErrorToXAErr(e.getException().getErrorCode()); - } - DtxXaStatus status = result.getStatus(); - int outcome = XAResource.XA_OK; - switch (status) - { - case XA_OK: - break; - case XA_RDONLY: - outcome = XAResource.XA_RDONLY; - break; - default: - checkStatus(status); - } - return outcome; - } - - /** - * Obtains a list of prepared transaction branches. - * <p> - * The transaction manager calls this method during recovery to obtain the list of transaction branches - * that are currently in prepared or heuristically completed states. - * - * @param flag One of TMSTARTRSCAN, TMENDRSCAN, TMNOFLAGS. - * TMNOFLAGS must be used when no other flags are set in the parameter. - * @return zero or more XIDs of the transaction branches that are currently in a prepared or heuristically - * completed state. - * @throws XAException An error has occurred. Possible value is XAER_INVAL. - */ - public Xid[] recover(int flag) throws XAException - { - // the flag is ignored - Future<RecoverResult> future = _xaSession.getQpidSession().dtxRecover(); - RecoverResult res = null; - try - { - res = future.get(); - } - catch (SessionException e) - { - // we need to restore the qpid session that has been closed - _xaSession.createSession(); - convertExecutionErrorToXAErr( e.getException().getErrorCode()); - } - Xid[] result = new Xid[res.getInDoubt() != null ? res.getInDoubt().size() : 0]; - if(result.length != 0) - { - int i = 0; - for (Object obj : res.getInDoubt()) - { - org.apache.qpid.transport.Xid xid = (org.apache.qpid.transport.Xid) obj; - result[i] = new XidImpl(xid.getBranchId(), (int) xid.getFormat(), xid.getGlobalId()); - i++; - } - } - return result; - } - - /** - * Informs the resource manager to roll back work done on behalf of a transaction branch - * - * @param xid A global transaction identifier. - * @throws XAException An error has occurred. - */ - public void rollback(Xid xid) throws XAException - { - if (_logger.isDebugEnabled()) - { - _logger.debug("rollback tx branch with xid: {}", xid); - } - - Future<XaResult> future = _xaSession.getQpidSession().dtxRollback(convertXid(xid)); - // now wait on the future for the result - XaResult result = null; - try - { - result = future.get(); - } - catch (SessionException e) - { - // we need to restore the qpid session that has been closed - _xaSession.createSession(); - convertExecutionErrorToXAErr( e.getException().getErrorCode()); - } - finally - { - _xid = null; - } - checkStatus(result.getStatus()); - } - - /** - * Sets the current transaction timeout value for this XAResource instance. - * Once set, this timeout value is effective until setTransactionTimeout is - * invoked again with a different value. - * To reset the timeout value to the default value used by the resource manager, set the value to zero. - * - * @param timeout The transaction timeout value in seconds. - * @return true if transaction timeout value is set successfully; otherwise false. - * @throws XAException An error has occurred. Possible exception values are XAER_RMERR, XAER_RMFAIL, or XAER_INVAL. - */ - public boolean setTransactionTimeout(int timeout) throws XAException - { - _timeout = timeout; - if (timeout != _timeout && _xid != null) - { - setDtxTimeout(_timeout); - } - return true; - } - - private void setDtxTimeout(int timeout) throws XAException - { - _xaSession.getQpidSession() - .dtxSetTimeout(XidImpl.convert(_xid), timeout); - } - - /** - * Starts work on behalf of a transaction branch specified in xid. - * <ul> - * <li> If TMJOIN is specified, an exception is thrown as it is not supported - * <li> If TMRESUME is specified, the start applies to resuming a suspended transaction specified in the parameter xid. - * <li> If neither TMJOIN nor TMRESUME is specified and the transaction specified by xid has previously been seen by the - * resource manager, the resource manager throws the XAException exception with XAER_DUPID error code. - * </ul> - * - * @param xid A global transaction identifier to be associated with the resource - * @param flag One of TMNOFLAGS, TMJOIN, or TMRESUME - * @throws XAException An error has occurred. Possible exceptions - * are XA_RB*, XAER_RMERR, XAER_RMFAIL, XAER_DUPID, XAER_OUTSIDE, XAER_NOTA, XAER_INVAL, or XAER_PROTO. - */ - public void start(Xid xid, int flag) throws XAException - { - if (_logger.isDebugEnabled()) - { - _logger.debug("start tx branch with xid: {}", xid); - } - switch (flag) - { - case(XAResource.TMNOFLAGS): - break; - case(XAResource.TMJOIN): - break; - case(XAResource.TMRESUME): - break; - default: - throw new XAException(XAException.XAER_INVAL); - } - Future<XaResult> future = _xaSession.getQpidSession() - .dtxStart(convertXid(xid), - flag == XAResource.TMJOIN ? Option.JOIN : Option.NONE, - flag == XAResource.TMRESUME ? Option.RESUME : Option.NONE); - // now wait on the future for the result - XaResult result = null; - try - { - result = future.get(); - } - catch (SessionException e) - { - // we need to restore the qpid session that has been closed - _xaSession.createSession(); - convertExecutionErrorToXAErr(e.getException().getErrorCode()); - // TODO: The amqp spec does not allow to make the difference - // between an already known XID and a wrong arguments (join and resume are set) - // TODO: make sure amqp addresses that - } - checkStatus(result.getStatus()); - _xid = xid; - if (_timeout > 0) - { - setDtxTimeout(_timeout); - } - - for(XAResource sibling: _siblings) - { - sibling.start(xid, flag); - } - } - - /** - * Is this resource currently enlisted in a transaction? - * - * @return true if the resource is associated with a transaction, false otherwise. - */ - public boolean isEnlisted() - { - return (_xid != null) ; - } - - //------------------------------------------------------------------------ - // Private methods - //------------------------------------------------------------------------ - - /** - * Check xa method outcome and, when required, convert the status into the corresponding xa exception - * @param status method status code - * @throws XAException corresponding XA Exception when required - */ - private void checkStatus(DtxXaStatus status) throws XAException - { - switch (status) - { - case XA_OK: - // Do nothing this ok - break; - case XA_RBROLLBACK: - // The tx has been rolled back for an unspecified reason. - throw new XAException(XAException.XA_RBROLLBACK); - case XA_RBTIMEOUT: - // The transaction branch took too long. - throw new XAException(XAException.XA_RBTIMEOUT); - case XA_HEURHAZ: - // The transaction branch may have been heuristically completed. - throw new XAException(XAException.XA_HEURHAZ); - case XA_HEURCOM: - // The transaction branch has been heuristically committed. - throw new XAException(XAException.XA_HEURCOM); - case XA_HEURRB: - // The transaction branch has been heuristically rolled back. - throw new XAException(XAException.XA_HEURRB); - case XA_HEURMIX: - // The transaction branch has been heuristically committed and rolled back. - throw new XAException(XAException.XA_HEURMIX); - case XA_RDONLY: - // The transaction branch was read-only and has been committed. - throw new XAException(XAException.XA_RDONLY); - default: - // this should not happen - if (_logger.isDebugEnabled()) - { - _logger.debug("got unexpected status value: {}", status); - } - //A resource manager error has occured in the transaction branch. - throw new XAException(XAException.XAER_RMERR); - } - } - - /** - * Convert execution error to xa exception. - * @param error the execution error code - * @throws XAException - */ - private void convertExecutionErrorToXAErr(ExecutionErrorCode error) throws XAException - { - switch (error) - { - case NOT_ALLOWED: - // The XID already exists. - throw new XAException(XAException.XAER_DUPID); - case NOT_FOUND: - // The XID is not valid. - try - { - throw new XAException(XAException.XAER_NOTA); - } - catch (XAException e) - { - _logger.error(e.getMessage(), e); - throw e; - } - case ILLEGAL_STATE: - // Routine was invoked in an inproper context. - throw new XAException(XAException.XAER_PROTO); - case NOT_IMPLEMENTED: - // the command is not implemented - throw new XAException(XAException.XAER_RMERR); - case COMMAND_INVALID: - // Invalid call - throw new XAException(XAException.XAER_INVAL); - default: - // this should not happen - if (_logger.isDebugEnabled()) - { - _logger.debug("Got unexpected error: " + error); - } - //A resource manager error has occured in the transaction branch. - throw new XAException(XAException.XAER_RMERR); - } - } - - /** - * convert a generic xid into qpid format - * @param xid xid to be converted - * @return the qpid formated xid - * @throws XAException when xid is null - */ - private org.apache.qpid.transport.Xid convertXid(Xid xid) throws XAException - { - if (xid == null) - { - // Invalid arguments were given. - throw new XAException(XAException.XAER_INVAL); - } - return XidImpl.convert(xid); - } - - public String getBrokerUUID() - { - return ((AMQSession_0_10)_xaSession).getAMQConnection().getBrokerUUID(); - } - - public List<XAResource> getSiblings() - { - return Collections.unmodifiableList(_siblings); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/XASessionImpl.java b/qpid/java/client/src/main/java/org/apache/qpid/client/XASessionImpl.java deleted file mode 100644 index fa0bdcb4c9..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/XASessionImpl.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.client; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.message.MessageFactoryRegistry; -import org.apache.qpid.transport.RangeSet; - -import javax.jms.JMSException; -import javax.jms.QueueSession; -import javax.jms.Session; -import javax.jms.TopicSession; -import javax.jms.TransactionInProgressException; -import javax.jms.XAQueueSession; -import javax.jms.XASession; -import javax.jms.XATopicSession; -import javax.transaction.xa.XAResource; - -/** - * This is an implementation of the javax.jms.XASession interface. - */ -public class XASessionImpl extends AMQSession_0_10 implements XASession, XATopicSession, XAQueueSession -{ - /** - * XAResource associated with this XASession - */ - private final XAResourceImpl _xaResource; - - /** - * This XASession Qpid DtxSession - */ - private org.apache.qpid.transport.Session _qpidDtxSession; - - /** - * The standard session - */ - private Session _jmsSession; - - - // Constructors - /** - * Create a JMS XASession - */ - public XASessionImpl(org.apache.qpid.transport.Connection qpidConnection, AMQConnection con, int channelId, - int defaultPrefetchHigh, int defaultPrefetchLow) - { - this(qpidConnection, con, channelId, false, Session.AUTO_ACKNOWLEDGE, - MessageFactoryRegistry.newDefaultRegistry(), defaultPrefetchHigh, defaultPrefetchLow, null); - } - - public XASessionImpl(org.apache.qpid.transport.Connection qpidConnection, AMQConnection con, int channelId, - int ackMode, int defaultPrefetchHigh, int defaultPrefetchLow) - { - this(qpidConnection, con, channelId, false, ackMode, MessageFactoryRegistry.newDefaultRegistry(), - defaultPrefetchHigh, defaultPrefetchLow, null); - - } - - public XASessionImpl(org.apache.qpid.transport.Connection qpidConnection, AMQConnection con, int channelId, - boolean transacted, int ackMode, MessageFactoryRegistry registry, int defaultPrefetchHigh, int defaultPrefetchLow, - String name) - { - super(qpidConnection, - con, - channelId, - transacted, - ackMode, - registry, - defaultPrefetchHigh, - defaultPrefetchLow, - name); - _xaResource = new XAResourceImpl(this); - } - - - // public methods - - /** - * Create a qpid session. - */ - @Override - public org.apache.qpid.transport.Session createSession() - { - _qpidDtxSession = getQpidConnection().createSession(0,true); - _qpidDtxSession.dtxSelect(); - _qpidDtxSession.setSessionListener(this); - return _qpidDtxSession; - } - - /** - * Gets the session associated with this XASession. - * - * @return The session object. - * @throws JMSException if an internal error occurs. - */ - public Session getSession() throws JMSException - { - return this; - } - - /** - * Returns an XA resource. - * - * @return An XA resource. - */ - public XAResource getXAResource() - { - return _xaResource; - } - - // overwritten mehtods - /** - * Throws a {@link TransactionInProgressException}, since it should - * not be called for an XASession object. - * - * @throws TransactionInProgressException always. - */ - public void commit() throws JMSException - { - throw new TransactionInProgressException( - "XASession: A direct invocation of the commit operation is probibited!"); - } - - /** - * Throws a {@link TransactionInProgressException}, since it should - * not be called for an XASession object. - * - * @throws TransactionInProgressException always. - */ - public void rollback() throws JMSException - { - throw new TransactionInProgressException( - "XASession: A direct invocation of the rollback operation is probibited!"); - } - - /** - * Access to the underlying Qpid Session - * - * @return The associated Qpid Session. - */ - protected org.apache.qpid.transport.Session getQpidSession() - { - return _qpidDtxSession; - } - - // interface XAQueueSession - /** - * Gets the topic session associated with this <CODE>XATopicSession</CODE>. - * - * @return the topic session object - * @throws JMSException If an internal error occurs. - */ - public QueueSession getQueueSession() throws JMSException - { - return this; - } - - // interface XATopicSession - - /** - * Gets the topic session associated with this <CODE>XATopicSession</CODE>. - * - * @return the topic session object - * @throws JMSException If an internal error occurs. - */ - public TopicSession getTopicSession() throws JMSException - { - return this; - } - - @Override - protected void acknowledgeImpl() - { - if (_xaResource.isEnlisted()) - { - acknowledgeMessage(Long.MAX_VALUE, true) ; - } - else - { - super.acknowledgeImpl() ; - } - } - - @Override - void resubscribe() throws AMQException - { - super.resubscribe(); - createSession(); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/failover/ConnectionRedirectException.java b/qpid/java/client/src/main/java/org/apache/qpid/client/failover/ConnectionRedirectException.java deleted file mode 100644 index 78efdb4317..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/failover/ConnectionRedirectException.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.client.failover; - -import org.apache.qpid.AMQException; - -public class ConnectionRedirectException extends AMQException -{ - private final String _host; - private final int _port; - - public ConnectionRedirectException(final String host, final int port) - { - super("Redirecting to " + host + ":" + port); - _host = host; - _port = port; - } - - public String getHost() - { - return _host; - } - - public int getPort() - { - return _port; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/failover/FailoverException.java b/qpid/java/client/src/main/java/org/apache/qpid/client/failover/FailoverException.java deleted file mode 100644 index 31a2868c13..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/failover/FailoverException.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.client.failover; - -/** - * FailoverException is used to indicate that a synchronous request has failed to receive the reply that it is waiting - * for because the fail-over process has been started whilst it was waiting for its reply. Synchronous methods generally - * raise this exception to indicate that they must be re-tried once the fail-over process has completed. - * <p> - * TODO This exception is created and passed as an argument to a method, rather than thrown. The exception is being - * used to represent an event, passed out to other threads. Use of exceptions as arguments rather than as - * exceptions is extremly confusing. Ideally use a condition or set a flag and check it instead. - * This exceptions-as-events pattern seems to be in a similar style to Mina code, which is not pretty, but - * potentially acceptable for that reason. We have the option of extending the mina model to add more events - * to it, that is, anything that is interested in handling failover as an event occurs below the main - * amq event handler, which knows the specific interface of the qpid handlers, which can pass this down as - * an explicit event, without it being an exception. Add failover method to BlockingMethodFrameListener, - * have it set a flag or interrupt the waiting thread, which then creates and raises this exception. - */ -public class FailoverException extends Exception -{ - public FailoverException(String message) - { - super(message); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/failover/FailoverHandler.java b/qpid/java/client/src/main/java/org/apache/qpid/client/failover/FailoverHandler.java deleted file mode 100644 index c9566db68c..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/failover/FailoverHandler.java +++ /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. - * - */ -package org.apache.qpid.client.failover; - -import java.util.concurrent.CountDownLatch; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQDisconnectedException; -import org.apache.qpid.client.protocol.AMQProtocolHandler; -import org.apache.qpid.client.state.AMQState; -import org.apache.qpid.client.state.AMQStateManager; - -/** - * FailoverHandler is a continuation that performs the failover procedure on a protocol session. As described in the - * class level comment for {@link AMQProtocolHandler}, a protocol connection can span many physical transport - * connections, failing over to a new connection if the transport connection fails. The procedure to establish a new - * connection is expressed as a continuation, in order that it may be run in a seperate thread to the i/o thread that - * detected the failure and is used to handle the communication to establish a new connection. - * <p> - * The reason this needs to be a separate thread is because this work cannot be done inside the i/o processor - * thread. The significant task is the connection setup which involves a protocol exchange until a particular state - * is achieved. This procedure waits until the state is achieved which would prevent the i/o thread doing the work - * it needs to do to achieve the new state. - * <p> - * The failover procedure does the following: - * - * <ol> - * <li>Sets the failing over condition to true.</li> - * <li>Creates a {@link FailoverException} and gets the protocol connection handler to propagate this event to all - * interested parties.</li> - * <li>Takes the failover mutex on the protocol connection handler.</li> - * <li>Abandons the fail over if any of the interested parties vetoes it. The mutex is released and the condition - * reset.</li> - * <li>Creates a new {@link AMQStateManager} and re-established the connection through it.</li> - * <li>Informs the AMQConnection if the connection cannot be re-established.</li> - * <li>Recreates all sessions from the old connection to the new.</li> - * <li>Resets the failing over condition and releases the mutex.</li> - * </ol> - * - * <p> - * TODO The failover latch and mutex are used like a lock and condition. If the retrotranlator supports lock/condition - * then could change over to using them. 1.4 support still needed. - * <p> - * TODO If the condition is set to null on a vetoes fail-over and there are already other threads waiting on the - * condition, they will never be released. It might be an idea to reset the condition in a finally block. - * <p> - * TODO Creates a {@link AMQDisconnectedException} and passes it to the AMQConnection. No need to use an - * exception-as-argument here, could just as easily call a specific method for this purpose on AMQConnection. - * <p> - * TODO Creates a {@link FailoverException} and propagates it to the MethodHandlers. No need to use an - * exception-as-argument here, could just as easily call a specific method for this purpose on - * {@link org.apache.qpid.protocol.AMQMethodListener}. - */ -public class FailoverHandler implements Runnable -{ - /** Used for debugging. */ - private static final Logger _logger = LoggerFactory.getLogger(FailoverHandler.class); - - /** Holds the protocol handler for the failed connection, upon which the new connection is to be set up. */ - private AMQProtocolHandler _amqProtocolHandler; - - /** Used to hold the host to fail over to. This is optional and if not set a reconnect to the previous host is tried. */ - private String _host; - - /** Used to hold the port to fail over to. */ - private int _port; - - /** - * Creates a failover handler on a protocol session, for a particular MINA session (network connection). - * - * @param amqProtocolHandler The protocol handler that spans the failover. - */ - public FailoverHandler(AMQProtocolHandler amqProtocolHandler) - { - _amqProtocolHandler = amqProtocolHandler; - } - - /** - * Performs the failover procedure. See the class level comment, {@link FailoverHandler}, for a description of the - * failover procedure. - */ - public void run() - { - if (Thread.currentThread().isDaemon()) - { - throw new IllegalStateException("FailoverHandler must run on a non-daemon thread."); - } - - // Create a latch, upon which tasks that must not run in parallel with a failover can wait for completion of - // the fail over. - _amqProtocolHandler.setFailoverLatch(new CountDownLatch(1)); - - // We wake up listeners. If they can handle failover, they will extend the - // FailoverRetrySupport class and will in turn block on the latch until failover - // has completed before retrying the operation. - _amqProtocolHandler.notifyFailoverStarting(); - - // Since failover impacts several structures we protect them all with a single mutex. These structures - // are also in child objects of the connection. This allows us to manipulate them without affecting - // client code which runs in a separate thread. - synchronized (_amqProtocolHandler.getConnection().getFailoverMutex()) - { - //Clear the exception now that we have the failover mutex there can be no one else waiting for a frame so - // we can clear the exception. - _amqProtocolHandler.failoverInProgress(); - - // We switch in a new state manager temporarily so that the interaction to get to the "connection open" - // state works, without us having to terminate any existing "state waiters". We could theoretically - // have a state waiter waiting until the connection is closed for some reason. Or in future we may have - // a slightly more complex state model therefore I felt it was worthwhile doing this. - AMQStateManager existingStateManager = _amqProtocolHandler.getStateManager(); - - - // Use a fresh new StateManager for the reconnection attempts - _amqProtocolHandler.setStateManager(new AMQStateManager()); - - - if (!_amqProtocolHandler.getConnection().firePreFailover(_host != null)) - { - _logger.info("Failover process veto-ed by client"); - - //Restore Existing State Manager - _amqProtocolHandler.setStateManager(existingStateManager); - - //todo: ritchiem these exceptions are useless... Would be better to attempt to propogate exception that - // prompted the failover event. - if (_host != null) - { - _amqProtocolHandler.getConnection().exceptionReceived(new AMQDisconnectedException("Redirect was vetoed by client", null)); - } - else - { - _amqProtocolHandler.getConnection().exceptionReceived(new AMQDisconnectedException("Failover was vetoed by client", null)); - } - - _amqProtocolHandler.getFailoverLatch().countDown(); - _amqProtocolHandler.setFailoverLatch(null); - - return; - } - - _logger.info("Starting failover process"); - - boolean failoverSucceeded; - // when host is non null we have a specified failover host otherwise we all the client to cycle through - // all specified hosts - - // if _host has value then we are performing a redirect. - if (_host != null) - { - failoverSucceeded = _amqProtocolHandler.getConnection().attemptReconnection(_host, _port, true); - } - else - { - failoverSucceeded = _amqProtocolHandler.getConnection().attemptReconnection(); - } - - if (!failoverSucceeded) - { - //Restore Existing State Manager - _amqProtocolHandler.setStateManager(existingStateManager); - - _amqProtocolHandler.getConnection().exceptionReceived( - new AMQDisconnectedException("Server closed connection and no failover " + - "was successful", null)); - } - else - { - // Set the new Protocol Session in the StateManager. - existingStateManager.setProtocolSession(_amqProtocolHandler.getProtocolSession()); - - // Now that the ProtocolHandler has been reconnected clean up - // the state of the old state manager. As if we simply reinstate - // it any old exception that had occured prior to failover may - // prohibit reconnection. - // e.g. During testing when the broker is shutdown gracefully. - // The broker - // Clear any exceptions we gathered - if (existingStateManager.getCurrentState() != AMQState.CONNECTION_OPEN) - { - // Clear the state of the previous state manager as it may - // have received an exception - existingStateManager.clearLastException(); - existingStateManager.changeState(AMQState.CONNECTION_OPEN); - } - - - //Restore Existing State Manager - _amqProtocolHandler.setStateManager(existingStateManager); - try - { - if (_amqProtocolHandler.getConnection().firePreResubscribe()) - { - _logger.info("Resubscribing on new connection"); - _amqProtocolHandler.getConnection().resubscribeSessions(); - } - else - { - _logger.info("Client vetoed automatic resubscription"); - } - - _amqProtocolHandler.getConnection().fireFailoverComplete(); - _amqProtocolHandler.setFailoverState(FailoverState.NOT_STARTED); - _logger.info("Connection failover completed successfully"); - } - catch (Exception e) - { - _logger.info("Failover process failed - exception being propagated by protocol handler"); - _amqProtocolHandler.setFailoverState(FailoverState.FAILED); - _amqProtocolHandler.exception(e); - } - } - } - - _amqProtocolHandler.getFailoverLatch().countDown(); - } - - /** - * Sets the host name to fail over to. This is optional and if not set a reconnect to the previous host is tried. - * - * @param host The host name to fail over to. - */ - public void setHost(String host) - { - _host = host; - } - - /** - * Sets the port to fail over to. - * - * @param port The port to fail over to. - */ - public void setPort(int port) - { - _port = port; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/failover/FailoverNoopSupport.java b/qpid/java/client/src/main/java/org/apache/qpid/client/failover/FailoverNoopSupport.java deleted file mode 100644 index da17bedcfd..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/failover/FailoverNoopSupport.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.client.failover; - -import org.apache.qpid.client.AMQConnection; - -/** - * FailoverNoopSupport is a {@link FailoverSupport} implementation that does not really provide any failover support - * at all. It wraps a {@link FailoverProtectedOperation} but should that operation throw {@link FailoverException} this - * support class simply re-raises that exception as an IllegalStateException. This support wrapper should only be - * used where the caller can be certain that the failover protected operation cannot acutally throw a failover exception, - * for example, because the caller already holds a lock preventing that condition from arising. - * - * <p><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Perform a fail-over protected operation raising providing no handling of fail-over conditions. - * </table> - */ -public class FailoverNoopSupport<T, E extends Exception> implements FailoverSupport<T, E> -{ - /** The protected operation that is to be retried in the event of fail-over. */ - private FailoverProtectedOperation<T, E> operation; - - /** The connection on which the fail-over protected operation is to be performed. */ - private AMQConnection connection; - - /** - * Creates an automatic retrying fail-over handler for the specified operation. - * - * @param operation The fail-over protected operation to wrap in this handler. - */ - public FailoverNoopSupport(FailoverProtectedOperation<T, E> operation, AMQConnection con) - { - this.operation = operation; - this.connection = con; - } - - /** - * Delegates to another continuation which is to be provided with fail-over handling. - * - * @return The return value from the delegated to continuation. - * @throws E Any exception that the delegated to continuation may raise. - */ - public T execute() throws E - { - try - { - return operation.execute(); - } - catch (FailoverException e) - { - throw new IllegalStateException("Fail-over interrupted no-op failover support. " - + "No-op support should only be used where the caller is certain fail-over cannot occur.", e); - } - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/failover/FailoverProtectedOperation.java b/qpid/java/client/src/main/java/org/apache/qpid/client/failover/FailoverProtectedOperation.java deleted file mode 100644 index d7e4128183..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/failover/FailoverProtectedOperation.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.client.failover; - -/** - * FailoverProtectedOperation is a continuation for an operation that may throw a {@link FailoverException} because - * it has been interrupted by the fail-over process. The {@link FailoverRetrySupport} class defines support wrappers - * for failover protected operations, in order to provide different handling schemes when failovers occurr. - * <p> - * The type of checked exception that the operation may perform has been generified, in order that fail over - * protected operations can be defined that raise arbitrary exceptions. The actuall exception types used should not - * be sub-classes of FailoverException, or else catching FailoverException in the {@link FailoverRetrySupport} classes - * will mask the exception. - */ -public interface FailoverProtectedOperation<T, E extends Exception> -{ - /** - * Performs the continuations work. - * - * @return Provdes scope for the continuation to return an arbitrary value. - * - * @throws FailoverException If the operation is interrupted by a fail-over notification. - */ - public abstract T execute() throws E, FailoverException; -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/failover/FailoverRetrySupport.java b/qpid/java/client/src/main/java/org/apache/qpid/client/failover/FailoverRetrySupport.java deleted file mode 100644 index 74bf9a54fd..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/failover/FailoverRetrySupport.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.client.failover; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.client.AMQConnection; - -/** - * FailoverRetrySupport is a continuation that wraps another continuation, delaying its execution until it is notified - * that a blocking condition has been met, and executing the continuation within a mutex. If the continuation fails, due - * to the original condition being broken, whilst the continuation is waiting for a reponse to a synchronous request, - * FailoverRetrySupport automatcally rechecks the condition and re-acquires the mutex and re-runs the continution. This - * automatic retrying is continued until the continuation succeeds, or throws an exception (different to - * FailoverException, which is used to signal the failure of the original condition). - * <p> - * The blocking condition used is that the connection is not currently failing over, and the mutex used is the - * connection failover mutex, which guards against the fail-over process being run during fail-over vulnerable methods. - * These are used like a lock and condition variable. - * <p> - * The wrapped operation may throw a FailoverException, this is an exception that can be raised by a - * {@link org.apache.qpid.client.protocol.BlockingMethodFrameListener}, in response to it being notified that a - * fail-over wants to start whilst it was waiting. Methods that are vulnerable to fail-over are those that are - * synchronous, where a failure will prevent them from getting the reply they are waiting for and asynchronous - * methods that should not be attempted when a fail-over is in progress. - * <p> - * Wrapping a synchronous method in a FailoverRetrySupport will have the effect that the operation will not be - * started during fail-over, but be delayed until any current fail-over has completed. Should a fail-over process want - * to start whilst waiting for the synchronous reply, the FailoverRetrySupport will detect this and retry the operation - * until it succeeds. Synchronous methods are usually coordinated with a - * {@link org.apache.qpid.client.protocol.BlockingMethodFrameListener} which is notified when a fail-over process wants - * to start and throws a FailoverException in response to this. - * <p> - * Wrapping an asynchronous method in a FailoverRetrySupport will have the effect that the operation will not be - * started during fail-over, but be delayed until any current fail-over has completed. - * <p> - * TODO InterruptedException not handled well. - */ -public class FailoverRetrySupport<T, E extends Exception> implements FailoverSupport<T, E> -{ - /** Used for debugging. */ - private static final Logger _log = LoggerFactory.getLogger(FailoverRetrySupport.class); - - /** The protected operation that is to be retried in the event of fail-over. */ - private FailoverProtectedOperation<T, E> operation; - - /** The connection on which the fail-over protected operation is to be performed. */ - private AMQConnection connection; - - /** - * Creates an automatic retrying fail-over handler for the specified operation. - * - * @param operation The fail-over protected operation to wrap in this handler. - */ - public FailoverRetrySupport(FailoverProtectedOperation<T, E> operation, AMQConnection con) - { - this.operation = operation; - this.connection = con; - } - - /** - * Delays a continuation until the "not failing over" condition is met on the specified connection. Repeats - * until the operation throws AMQException or succeeds without being interrupted by fail-over. - * - * @return The result of executing the continuation. - * - * @throws E Any underlying exception is allowed to fall through. - */ - public T execute() throws E - { - return connection.executeRetrySupport(operation); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/failover/FailoverState.java b/qpid/java/client/src/main/java/org/apache/qpid/client/failover/FailoverState.java deleted file mode 100644 index 268bac6155..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/failover/FailoverState.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.client.failover; - -/** - * Defines the possible states of the failover process; not started, in progress, failed. - */ -public final class FailoverState -{ - /** The string description on this state. */ - private final String _state; - - /** Failover has not yet been attempted on this connection. */ - public static final FailoverState NOT_STARTED = new FailoverState("NOT STARTED"); - - /** Failover has been requested on this connection but has not completed. */ - public static final FailoverState IN_PROGRESS = new FailoverState("IN PROGRESS"); - - /** Failover has been attempted and failed. */ - public static final FailoverState FAILED = new FailoverState("FAILED"); - - /** - * Creates a type safe enumeration of a fail-over state. - * - * @param state The fail-over state description string. - */ - private FailoverState(String state) - { - _state = state; - } - - /** - * Prints this state, mainly for debugging purposes. - * - * @return The string description of this state. - */ - public String toString() - { - return "FailoverState: " + _state; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/failover/FailoverSupport.java b/qpid/java/client/src/main/java/org/apache/qpid/client/failover/FailoverSupport.java deleted file mode 100644 index be3fa230e1..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/failover/FailoverSupport.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.client.failover; - -/** - * FailoverSupport defines an interface for different types of fail-over handlers, that provide different types of - * behaviour for handling fail-overs during operations that can be interrupted by the fail-over process. For example, - * the support could automatically retry once the fail-over process completes, could prevent an operation from being - * started whilst fail-over is running, or could quietly abandon the operation or raise an exception, and so on. - * <p> - * TODO Continuation, extend some sort of re-usable Continuation interface, which might look very like this one. - */ -public interface FailoverSupport<T, E extends Exception> -{ - /** - * Delegates to another continuation which is to be provided with fail-over handling. - * - * @return The return value from the delegated to continuation. - * - * @throws E Any exception that the delegated to continuation may raise. - */ - public T execute() throws E; -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/filter/JMSSelectorFilter.java b/qpid/java/client/src/main/java/org/apache/qpid/client/filter/JMSSelectorFilter.java deleted file mode 100644 index bab518b0ec..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/filter/JMSSelectorFilter.java +++ /dev/null @@ -1,213 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQInternalException; -import org.apache.qpid.client.message.AbstractJMSMessage; -import org.apache.qpid.filter.FilterableMessage; -import org.apache.qpid.filter.SelectorParsingException; -import org.apache.qpid.filter.selector.ParseException; -import org.apache.qpid.filter.selector.SelectorParser; -import org.apache.qpid.filter.BooleanExpression; -import org.apache.qpid.filter.selector.TokenMgrError; - -import javax.jms.DeliveryMode; -import javax.jms.JMSException; - - -public class JMSSelectorFilter implements MessageFilter -{ - private static final Logger _logger = LoggerFactory.getLogger(JMSSelectorFilter.class); - - private final String _selector; - private final BooleanExpression _matcher; - - public JMSSelectorFilter(String selector) throws AMQInternalException - { - if (selector == null || "".equals(selector)) - { - throw new IllegalArgumentException("Cannot create a JMSSelectorFilter with a null or empty selector string"); - } - _selector = selector; - if (_logger.isDebugEnabled()) - { - _logger.debug("Created JMSSelectorFilter with selector:" + _selector); - } - try - { - _matcher = new SelectorParser().parse(selector); - } - catch (ParseException e) - { - throw new AMQInternalException("Unable to parse selector \""+selector+"\"", e); - } - catch (SelectorParsingException e) - { - throw new AMQInternalException("Unable to parse selector \""+selector+"\"", e); - } - catch (TokenMgrError e) - { - throw new AMQInternalException("Unable to parse selector \""+selector+"\"", e); - } - } - - public boolean matches(AbstractJMSMessage message) - { - try - { - boolean match = _matcher.matches(wrap(message)); - if (_logger.isDebugEnabled()) - { - _logger.debug(message + " match(" + match + ") selector(" + _selector + "): " + _selector); - } - return match; - } - catch (SelectorParsingException e) - { - _logger.warn("Caught exception when evaluating message selector for message " + message, e); - } - return false; - } - - private FilterableMessage wrap(final AbstractJMSMessage message) - { - return new FilterableMessage() - { - public boolean isPersistent() - { - try - { - return message.getJMSDeliveryMode() == DeliveryMode.PERSISTENT; - } - catch (JMSException e) - { - throw new SelectorParsingException(e); - } - } - - public boolean isRedelivered() - { - try - { - return message.getJMSRedelivered(); - } - catch (JMSException e) - { - throw new SelectorParsingException(e); - } - } - - public Object getHeader(String name) - { - try - { - return message.getObjectProperty(name); - } - catch (JMSException e) - { - throw new SelectorParsingException(e); - } - } - - public String getReplyTo() - { - return message.getReplyToString(); - } - - public String getType() - { - try - { - return message.getJMSType(); - } - catch (JMSException e) - { - throw new SelectorParsingException(e); - } - } - - public byte getPriority() - { - try - { - return (byte) message.getJMSPriority(); - } - catch (JMSException e) - { - throw new SelectorParsingException(e); - } - } - - public String getMessageId() - { - try - { - return message.getJMSMessageID(); - } - catch (JMSException e) - { - throw new SelectorParsingException(e); - } - } - - public long getTimestamp() - { - try - { - return message.getJMSTimestamp(); - } - catch (JMSException e) - { - throw new SelectorParsingException(e); - } - } - - public String getCorrelationId() - { - try - { - return message.getJMSCorrelationID(); - } - catch (JMSException e) - { - throw new SelectorParsingException(e); - } - } - - public long getExpiration() - { - try - { - return message.getJMSExpiration(); - } - catch (JMSException e) - { - throw new SelectorParsingException(e); - } - } - }; - } - - public String getSelector() - { - return _selector; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/filter/MessageFilter.java b/qpid/java/client/src/main/java/org/apache/qpid/client/filter/MessageFilter.java deleted file mode 100644 index fec78d6ba5..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/filter/MessageFilter.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.client.filter; - -import org.apache.qpid.client.message.AbstractJMSMessage; - - -public interface MessageFilter -{ - boolean matches(AbstractJMSMessage message); - String getSelector(); -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/AccessRequestOkMethodHandler.java b/qpid/java/client/src/main/java/org/apache/qpid/client/handler/AccessRequestOkMethodHandler.java deleted file mode 100644 index fa544f2d2e..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/AccessRequestOkMethodHandler.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.client.handler; - - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.apache.qpid.client.state.StateAwareMethodListener; -import org.apache.qpid.framing.AccessRequestOkBody; - -public class AccessRequestOkMethodHandler implements StateAwareMethodListener<AccessRequestOkBody> -{ - private static final Logger _logger = LoggerFactory.getLogger(AccessRequestOkMethodHandler.class); - - private static AccessRequestOkMethodHandler _handler = new AccessRequestOkMethodHandler(); - - public static AccessRequestOkMethodHandler getInstance() - { - return _handler; - } - - public void methodReceived(AMQProtocolSession session, AccessRequestOkBody method, int channelId) - throws AMQException - { - _logger.debug("AccessRequestOk method received"); - session.setTicket(method.getTicket(), channelId); - - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/BasicCancelOkMethodHandler.java b/qpid/java/client/src/main/java/org/apache/qpid/client/handler/BasicCancelOkMethodHandler.java deleted file mode 100644 index 9b5eea3bba..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/BasicCancelOkMethodHandler.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.client.handler; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.apache.qpid.client.state.StateAwareMethodListener; -import org.apache.qpid.framing.BasicCancelOkBody; - -public class BasicCancelOkMethodHandler implements StateAwareMethodListener<BasicCancelOkBody> -{ - private static final Logger _logger = LoggerFactory.getLogger(BasicCancelOkMethodHandler.class); - - private static final BasicCancelOkMethodHandler _instance = new BasicCancelOkMethodHandler(); - - public static BasicCancelOkMethodHandler getInstance() - { - return _instance; - } - - private BasicCancelOkMethodHandler() - { } - - public void methodReceived(AMQProtocolSession session, BasicCancelOkBody body, int channelId) - throws AMQException - { - if (_logger.isInfoEnabled()) - { - _logger.info("New BasicCancelOk method received for consumer:" + body.getConsumerTag()); - } - - session.confirmConsumerCancelled(channelId, body.getConsumerTag()); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/BasicDeliverMethodHandler.java b/qpid/java/client/src/main/java/org/apache/qpid/client/handler/BasicDeliverMethodHandler.java deleted file mode 100644 index 3f57e180e7..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/BasicDeliverMethodHandler.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.client.handler; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.message.UnprocessedMessage_0_8; -import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.apache.qpid.client.state.StateAwareMethodListener; -import org.apache.qpid.framing.BasicDeliverBody; - -public class BasicDeliverMethodHandler implements StateAwareMethodListener<BasicDeliverBody> -{ - private static final Logger _logger = LoggerFactory.getLogger(BasicDeliverMethodHandler.class); - - private static final BasicDeliverMethodHandler _instance = new BasicDeliverMethodHandler(); - - public static BasicDeliverMethodHandler getInstance() - { - return _instance; - } - - public void methodReceived(AMQProtocolSession session, BasicDeliverBody body, int channelId) - throws AMQException - { - final UnprocessedMessage_0_8 msg = new UnprocessedMessage_0_8( - body.getDeliveryTag(), - body.getConsumerTag().toIntValue(), - body.getExchange(), - body.getRoutingKey(), - body.getRedelivered()); - if(_logger.isDebugEnabled()) - { - _logger.debug("New JmsDeliver method received:" + session); - } - session.unprocessedMessageReceived(channelId, msg); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/BasicReturnMethodHandler.java b/qpid/java/client/src/main/java/org/apache/qpid/client/handler/BasicReturnMethodHandler.java deleted file mode 100644 index a09d298ae8..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/BasicReturnMethodHandler.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.client.handler; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.message.ReturnMessage; -import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.apache.qpid.client.state.StateAwareMethodListener; -import org.apache.qpid.framing.BasicReturnBody; - -public class BasicReturnMethodHandler implements StateAwareMethodListener<BasicReturnBody> -{ - private static final Logger _logger = LoggerFactory.getLogger(BasicReturnMethodHandler.class); - - private static final BasicReturnMethodHandler _instance = new BasicReturnMethodHandler(); - - public static BasicReturnMethodHandler getInstance() - { - return _instance; - } - - - public void methodReceived(AMQProtocolSession session, BasicReturnBody body, int channelId) - throws AMQException - { - _logger.debug("New JmsBounce method received"); - final ReturnMessage msg = new ReturnMessage( - body.getExchange(), - body.getRoutingKey(), - body.getReplyText(), - body.getReplyCode() - ); - - session.unprocessedMessageReceived(channelId, msg); - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ChannelCloseMethodHandler.java b/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ChannelCloseMethodHandler.java deleted file mode 100644 index 85328d78ea..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ChannelCloseMethodHandler.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.client.handler; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQChannelClosedException; -import org.apache.qpid.AMQException; -import org.apache.qpid.AMQInvalidRoutingKeyException; -import org.apache.qpid.client.AMQNoConsumersException; -import org.apache.qpid.client.AMQNoRouteException; -import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.apache.qpid.client.state.StateAwareMethodListener; -import org.apache.qpid.framing.AMQFrame; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.ChannelCloseBody; -import org.apache.qpid.framing.ChannelCloseOkBody; -import org.apache.qpid.protocol.AMQConstant; - -public class ChannelCloseMethodHandler implements StateAwareMethodListener<ChannelCloseBody> -{ - private static final Logger _logger = LoggerFactory.getLogger(ChannelCloseMethodHandler.class); - - private static ChannelCloseMethodHandler _handler = new ChannelCloseMethodHandler(); - - public static ChannelCloseMethodHandler getInstance() - { - return _handler; - } - - public void methodReceived(AMQProtocolSession session, ChannelCloseBody method, int channelId) - throws AMQException - { - _logger.debug("ChannelClose method received"); - - AMQConstant errorCode = AMQConstant.getConstant(method.getReplyCode()); - AMQShortString reason = method.getReplyText(); - if (_logger.isDebugEnabled()) - { - _logger.debug("Channel close reply code: " + errorCode + ", reason: " + reason); - } - - ChannelCloseOkBody body = session.getMethodRegistry().createChannelCloseOkBody(); - AMQFrame frame = body.generateFrame(channelId); - session.writeFrame(frame); - try - { - if (errorCode != AMQConstant.REPLY_SUCCESS) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Channel close received with errorCode " + errorCode + ", and reason " + reason); - } - - if (errorCode == AMQConstant.NO_CONSUMERS) - { - throw new AMQNoConsumersException("Error: " + reason, null, null); - } - else if (errorCode == AMQConstant.NO_ROUTE) - { - throw new AMQNoRouteException("Error: " + reason, null, null); - } - else if (errorCode == AMQConstant.ARGUMENT_INVALID) - { - _logger.debug("Broker responded with Invalid Argument."); - - throw new org.apache.qpid.AMQInvalidArgumentException(String.valueOf(reason), null); - } - else if (errorCode == AMQConstant.INVALID_ROUTING_KEY) - { - _logger.debug("Broker responded with Invalid Routing Key."); - - throw new AMQInvalidRoutingKeyException(String.valueOf(reason), null); - } - else - { - - throw new AMQChannelClosedException(errorCode, "Error: " + reason, null); - } - - } - } - finally - { - // fixme why is this only done when the close is expected... - // should the above forced closes not also cause a close? - // ---------- - // Closing the session only when it is expected allows the errors to be processed - // Calling this here will prevent failover. So we should do this for all exceptions - // that should never cause failover. Such as authentication errors. - // ---- - // 2009-09-07 - ritchiem - // calling channelClosed will only close this session and will not - // prevent failover. If we don't close the session here then we will - // have problems during the session close as it will attempt to - // close the session that the broker has closed, - - session.channelClosed(channelId, errorCode, String.valueOf(reason)); - } - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ChannelCloseOkMethodHandler.java b/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ChannelCloseOkMethodHandler.java deleted file mode 100644 index 058484c339..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ChannelCloseOkMethodHandler.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.client.handler; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.apache.qpid.client.state.StateAwareMethodListener; -import org.apache.qpid.framing.ChannelCloseOkBody; -import org.apache.qpid.protocol.AMQConstant; - -public class ChannelCloseOkMethodHandler implements StateAwareMethodListener<ChannelCloseOkBody> -{ - private static final Logger _logger = LoggerFactory.getLogger(ChannelCloseOkMethodHandler.class); - - private static final ChannelCloseOkMethodHandler _instance = new ChannelCloseOkMethodHandler(); - - public static ChannelCloseOkMethodHandler getInstance() - { - return _instance; - } - - public void methodReceived(AMQProtocolSession session, ChannelCloseOkBody method, int channelId) - throws AMQException - { - _logger.info("Received channel-close-ok for channel-id " + channelId); - - session.channelClosed(channelId, AMQConstant.REPLY_SUCCESS, "Channel closed successfully"); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ChannelFlowMethodHandler.java b/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ChannelFlowMethodHandler.java deleted file mode 100644 index 46b1f08db3..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ChannelFlowMethodHandler.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.client.handler; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.apache.qpid.client.state.StateAwareMethodListener; -import org.apache.qpid.framing.ChannelFlowBody; - - -public class ChannelFlowMethodHandler implements StateAwareMethodListener<ChannelFlowBody> -{ - private static final Logger _logger = LoggerFactory.getLogger(ChannelFlowMethodHandler.class); - private static final ChannelFlowMethodHandler _instance = new ChannelFlowMethodHandler(); - - public static ChannelFlowMethodHandler getInstance() - { - return _instance; - } - - private ChannelFlowMethodHandler() - { } - - public void methodReceived(AMQProtocolSession session, ChannelFlowBody body, int channelId) - throws AMQException - { - session.setFlowControl(channelId, body.getActive()); - } - - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ChannelFlowOkMethodHandler.java b/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ChannelFlowOkMethodHandler.java deleted file mode 100644 index c15404ea08..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ChannelFlowOkMethodHandler.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.client.handler; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.apache.qpid.client.state.StateAwareMethodListener; -import org.apache.qpid.framing.ChannelFlowOkBody; - -public class ChannelFlowOkMethodHandler implements StateAwareMethodListener<ChannelFlowOkBody> -{ - private static final Logger _logger = LoggerFactory.getLogger(ChannelFlowOkMethodHandler.class); - private static final ChannelFlowOkMethodHandler _instance = new ChannelFlowOkMethodHandler(); - - public static ChannelFlowOkMethodHandler getInstance() - { - return _instance; - } - - private ChannelFlowOkMethodHandler() - { } - - public void methodReceived(AMQProtocolSession session, ChannelFlowOkBody body, int channelId) - throws AMQException - { - - _logger.debug("Received Channel.Flow-Ok message, active = " + body.getActive()); - } - - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ClientMethodDispatcherImpl.java b/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ClientMethodDispatcherImpl.java deleted file mode 100644 index de2f2f52a9..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ClientMethodDispatcherImpl.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.client.handler; - -import java.util.HashMap; -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.apache.qpid.client.state.AMQMethodNotImplementedException; -import org.apache.qpid.client.state.AMQStateManager; -import org.apache.qpid.framing.*; - -public class ClientMethodDispatcherImpl implements MethodDispatcher -{ - - private static final BasicCancelOkMethodHandler _basicCancelOkMethodHandler = BasicCancelOkMethodHandler.getInstance(); - private static final BasicDeliverMethodHandler _basicDeliverMethodHandler = BasicDeliverMethodHandler.getInstance(); - private static final BasicReturnMethodHandler _basicReturnMethodHandler = BasicReturnMethodHandler.getInstance(); - private static final ChannelCloseMethodHandler _channelCloseMethodHandler = ChannelCloseMethodHandler.getInstance(); - private static final ChannelCloseOkMethodHandler _channelCloseOkMethodHandler = ChannelCloseOkMethodHandler.getInstance(); - private static final ChannelFlowOkMethodHandler _channelFlowOkMethodHandler = ChannelFlowOkMethodHandler.getInstance(); - private static final ChannelFlowMethodHandler _channelFlowMethodHandler = ChannelFlowMethodHandler.getInstance(); - private static final ConnectionCloseMethodHandler _connectionCloseMethodHandler = ConnectionCloseMethodHandler.getInstance(); - private static final ConnectionOpenOkMethodHandler _connectionOpenOkMethodHandler = ConnectionOpenOkMethodHandler.getInstance(); - private static final ConnectionRedirectMethodHandler _connectionRedirectMethodHandler = ConnectionRedirectMethodHandler.getInstance(); - private static final ConnectionSecureMethodHandler _connectionSecureMethodHandler = ConnectionSecureMethodHandler.getInstance(); - private static final ConnectionStartMethodHandler _connectionStartMethodHandler = ConnectionStartMethodHandler.getInstance(); - private static final ConnectionTuneMethodHandler _connectionTuneMethodHandler = ConnectionTuneMethodHandler.getInstance(); - private static final ExchangeBoundOkMethodHandler _exchangeBoundOkMethodHandler = ExchangeBoundOkMethodHandler.getInstance(); - private static final QueueDeleteOkMethodHandler _queueDeleteOkMethodHandler = QueueDeleteOkMethodHandler.getInstance(); - - private static final Logger _logger = LoggerFactory.getLogger(ClientMethodDispatcherImpl.class); - - - private static interface DispatcherFactory - { - public ClientMethodDispatcherImpl createMethodDispatcher(AMQProtocolSession session); - } - - private static final Map<ProtocolVersion, DispatcherFactory> _dispatcherFactories = - new HashMap<ProtocolVersion, DispatcherFactory>(); - - static - { - _dispatcherFactories.put(ProtocolVersion.v8_0, - new DispatcherFactory() - { - public ClientMethodDispatcherImpl createMethodDispatcher(AMQProtocolSession session) - { - return new ClientMethodDispatcherImpl_8_0(session); - } - }); - - _dispatcherFactories.put(ProtocolVersion.v0_9, - new DispatcherFactory() - { - public ClientMethodDispatcherImpl createMethodDispatcher(AMQProtocolSession session) - { - return new ClientMethodDispatcherImpl_0_9(session); - } - }); - - - _dispatcherFactories.put(ProtocolVersion.v0_91, - new DispatcherFactory() - { - public ClientMethodDispatcherImpl createMethodDispatcher(AMQProtocolSession session) - { - return new ClientMethodDispatcherImpl_0_91(session); - } - }); - - } - - public static ClientMethodDispatcherImpl newMethodDispatcher(ProtocolVersion version, AMQProtocolSession session) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("New Method Dispatcher:" + session); - } - - DispatcherFactory factory = _dispatcherFactories.get(version); - if(factory == null) - { - throw new UnsupportedOperationException("The protocol version " + version + " is not supported"); - } - return factory.createMethodDispatcher(session); - } - - private AMQProtocolSession _session; - - public ClientMethodDispatcherImpl(AMQProtocolSession session) - { - _session = session; - } - - public AMQStateManager getStateManager() - { - return _session.getStateManager(); - } - - public boolean dispatchAccessRequestOk(AccessRequestOkBody body, int channelId) throws AMQException - { - return false; - } - - @Override - public boolean dispatchQueueUnbindOk(final QueueUnbindOkBody body, final int channelId) - throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - @Override - public boolean dispatchBasicRecoverSyncOk(final BasicRecoverSyncOkBody basicRecoverSyncOkBody, - final int channelId) - throws AMQException - { - return false; - } - - @Override - public boolean dispatchChannelAlert(final ChannelAlertBody channelAlertBody, final int channelId) - throws AMQException - { - return false; - } - - @Override - public boolean dispatchConfirmSelectOk(final ConfirmSelectOkBody confirmSelectOkBody, final int channelId) - throws AMQException - { - return false; - } - - public boolean dispatchBasicCancelOk(BasicCancelOkBody body, int channelId) throws AMQException - { - _basicCancelOkMethodHandler.methodReceived(_session, body, channelId); - return true; - } - - public boolean dispatchBasicConsumeOk(BasicConsumeOkBody body, int channelId) throws AMQException - { - return false; - } - - public boolean dispatchBasicDeliver(BasicDeliverBody body, int channelId) throws AMQException - { - _basicDeliverMethodHandler.methodReceived(_session, body, channelId); - return true; - } - - public boolean dispatchBasicGetEmpty(BasicGetEmptyBody body, int channelId) throws AMQException - { - return false; - } - - public boolean dispatchBasicGetOk(BasicGetOkBody body, int channelId) throws AMQException - { - return false; - } - - public boolean dispatchBasicQosOk(BasicQosOkBody body, int channelId) throws AMQException - { - return false; - } - - public boolean dispatchBasicReturn(BasicReturnBody body, int channelId) throws AMQException - { - _basicReturnMethodHandler.methodReceived(_session, body, channelId); - return true; - } - - public boolean dispatchChannelClose(ChannelCloseBody body, int channelId) throws AMQException - { - _channelCloseMethodHandler.methodReceived(_session, body, channelId); - return true; - } - - public boolean dispatchChannelCloseOk(ChannelCloseOkBody body, int channelId) throws AMQException - { - _channelCloseOkMethodHandler.methodReceived(_session, body, channelId); - return true; - } - - public boolean dispatchChannelFlow(ChannelFlowBody body, int channelId) throws AMQException - { - _channelFlowMethodHandler.methodReceived(_session, body, channelId); - return true; - } - - public boolean dispatchChannelFlowOk(ChannelFlowOkBody body, int channelId) throws AMQException - { - _channelFlowOkMethodHandler.methodReceived(_session, body, channelId); - return true; - } - - public boolean dispatchChannelOpenOk(ChannelOpenOkBody body, int channelId) throws AMQException - { - return false; - } - - public boolean dispatchConnectionClose(ConnectionCloseBody body, int channelId) throws AMQException - { - _connectionCloseMethodHandler.methodReceived(_session, body, channelId); - return true; - } - - public boolean dispatchConnectionCloseOk(ConnectionCloseOkBody body, int channelId) throws AMQException - { - return false; - } - - public boolean dispatchConnectionOpenOk(ConnectionOpenOkBody body, int channelId) throws AMQException - { - _connectionOpenOkMethodHandler.methodReceived(_session, body, channelId); - return true; - } - - public boolean dispatchConnectionRedirect(ConnectionRedirectBody body, int channelId) throws AMQException - { - _connectionRedirectMethodHandler.methodReceived(_session, body, channelId); - return true; - } - - public boolean dispatchConnectionSecure(ConnectionSecureBody body, int channelId) throws AMQException - { - _connectionSecureMethodHandler.methodReceived(_session, body, channelId); - return true; - } - - public boolean dispatchConnectionStart(ConnectionStartBody body, int channelId) throws AMQException - { - _connectionStartMethodHandler.methodReceived(_session, body, channelId); - return true; - } - - public boolean dispatchConnectionTune(ConnectionTuneBody body, int channelId) throws AMQException - { - _connectionTuneMethodHandler.methodReceived(_session, body, channelId); - return true; - } - - public boolean dispatchQueueDeleteOk(QueueDeleteOkBody body, int channelId) throws AMQException - { - _queueDeleteOkMethodHandler.methodReceived(_session, body, channelId); - return true; - } - - public boolean dispatchQueuePurgeOk(QueuePurgeOkBody body, int channelId) throws AMQException - { - return false; - } - - public boolean dispatchAccessRequest(AccessRequestBody body, int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - @Override - public boolean dispatchBasicAck(BasicAckBody body, int channelId) throws AMQException - { - return false; - } - - @Override - public boolean dispatchBasicNack(final BasicNackBody basicNackBody, final int channelId) - { - return false; - } - - - public boolean dispatchBasicCancel(BasicCancelBody body, int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - public boolean dispatchBasicConsume(BasicConsumeBody body, int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - public boolean dispatchBasicGet(BasicGetBody body, int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - public boolean dispatchBasicPublish(BasicPublishBody body, int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - public boolean dispatchBasicQos(BasicQosBody body, int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - public boolean dispatchBasicRecover(BasicRecoverBody body, int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - public boolean dispatchBasicReject(BasicRejectBody body, int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - public boolean dispatchChannelOpen(ChannelOpenBody body, int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - public boolean dispatchConnectionOpen(ConnectionOpenBody body, int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - public boolean dispatchConnectionSecureOk(ConnectionSecureOkBody body, int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - public boolean dispatchConnectionStartOk(ConnectionStartOkBody body, int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - public boolean dispatchConnectionTuneOk(ConnectionTuneOkBody body, int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - public boolean dispatchExchangeBound(ExchangeBoundBody body, int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - public boolean dispatchExchangeDeclare(ExchangeDeclareBody body, int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - public boolean dispatchExchangeDelete(ExchangeDeleteBody body, int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - public boolean dispatchQueueBind(QueueBindBody body, int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - public boolean dispatchQueueDeclare(QueueDeclareBody body, int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - public boolean dispatchQueueDelete(QueueDeleteBody body, int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - public boolean dispatchQueuePurge(QueuePurgeBody body, int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - - public boolean dispatchTxCommit(TxCommitBody body, int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - public boolean dispatchTxRollback(TxRollbackBody body, int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - public boolean dispatchTxSelect(TxSelectBody body, int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - @Override - public boolean dispatchQueueUnbind(final QueueUnbindBody queueUnbindBody, final int channelId) throws AMQException - { - return false; - } - - @Override - public boolean dispatchBasicRecoverSync(final BasicRecoverSyncBody basicRecoverSyncBody, final int channelId) - throws AMQException - { - return false; - } - - @Override - public boolean dispatchConfirmSelect(final ConfirmSelectBody body, final int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - public boolean dispatchExchangeBoundOk(ExchangeBoundOkBody body, int channelId) throws AMQException - { - _exchangeBoundOkMethodHandler.methodReceived(_session, body, channelId); - return true; - } - - public boolean dispatchExchangeDeclareOk(ExchangeDeclareOkBody body, int channelId) throws AMQException - { - return false; - } - - public boolean dispatchExchangeDeleteOk(ExchangeDeleteOkBody body, int channelId) throws AMQException - { - return false; - } - - public boolean dispatchQueueBindOk(QueueBindOkBody body, int channelId) throws AMQException - { - return false; - } - - public boolean dispatchQueueDeclareOk(QueueDeclareOkBody body, int channelId) throws AMQException - { - return false; - } - - public boolean dispatchTxCommitOk(TxCommitOkBody body, int channelId) throws AMQException - { - return false; - } - - public boolean dispatchTxRollbackOk(TxRollbackOkBody body, int channelId) throws AMQException - { - return false; - } - - public boolean dispatchTxSelectOk(TxSelectOkBody body, int channelId) throws AMQException - { - return false; - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ClientMethodDispatcherImpl_0_9.java b/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ClientMethodDispatcherImpl_0_9.java deleted file mode 100644 index 4232f59292..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ClientMethodDispatcherImpl_0_9.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.client.handler; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.apache.qpid.client.state.AMQMethodNotImplementedException; -import org.apache.qpid.framing.BasicRecoverSyncBody; -import org.apache.qpid.framing.BasicRecoverSyncOkBody; -import org.apache.qpid.framing.ChannelAlertBody; -import org.apache.qpid.framing.MethodDispatcher; -import org.apache.qpid.framing.QueueUnbindBody; -import org.apache.qpid.framing.QueueUnbindOkBody; - -public class ClientMethodDispatcherImpl_0_9 extends ClientMethodDispatcherImpl implements MethodDispatcher -{ - public ClientMethodDispatcherImpl_0_9(AMQProtocolSession session) - { - super(session); - } - - public boolean dispatchBasicRecoverSyncOk(BasicRecoverSyncOkBody body, int channelId) throws AMQException - { - return false; - } - - @Override - public boolean dispatchChannelAlert(final ChannelAlertBody body, final int channelId) - throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - public boolean dispatchBasicRecoverSync(BasicRecoverSyncBody body, int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - public boolean dispatchQueueUnbind(QueueUnbindBody body, int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - public boolean dispatchQueueUnbindOk(QueueUnbindOkBody body, int channelId) throws AMQException - { - return false; - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ClientMethodDispatcherImpl_0_91.java b/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ClientMethodDispatcherImpl_0_91.java deleted file mode 100644 index 573ab52cc3..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ClientMethodDispatcherImpl_0_91.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.client.handler; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.apache.qpid.client.state.AMQMethodNotImplementedException; -import org.apache.qpid.framing.BasicRecoverSyncBody; -import org.apache.qpid.framing.BasicRecoverSyncOkBody; -import org.apache.qpid.framing.ChannelAlertBody; -import org.apache.qpid.framing.MethodDispatcher; -import org.apache.qpid.framing.QueueUnbindBody; -import org.apache.qpid.framing.QueueUnbindOkBody; - -public class ClientMethodDispatcherImpl_0_91 extends ClientMethodDispatcherImpl implements MethodDispatcher -{ - public ClientMethodDispatcherImpl_0_91(AMQProtocolSession session) - { - super(session); - } - - public boolean dispatchBasicRecoverSyncOk(BasicRecoverSyncOkBody body, int channelId) throws AMQException - { - return false; - } - - @Override - public boolean dispatchChannelAlert(final ChannelAlertBody body, final int channelId) - throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - public boolean dispatchBasicRecoverSync(BasicRecoverSyncBody body, int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - public boolean dispatchQueueUnbind(QueueUnbindBody body, int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - public boolean dispatchQueueUnbindOk(QueueUnbindOkBody body, int channelId) throws AMQException - { - return false; - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ClientMethodDispatcherImpl_8_0.java b/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ClientMethodDispatcherImpl_8_0.java deleted file mode 100644 index 7d421622e7..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ClientMethodDispatcherImpl_8_0.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.client.handler; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.apache.qpid.client.state.AMQMethodNotImplementedException; -import org.apache.qpid.framing.BasicRecoverSyncBody; -import org.apache.qpid.framing.BasicRecoverSyncOkBody; -import org.apache.qpid.framing.ChannelAlertBody; -import org.apache.qpid.framing.MethodDispatcher; -import org.apache.qpid.framing.QueueUnbindBody; -import org.apache.qpid.framing.QueueUnbindOkBody; - -public class ClientMethodDispatcherImpl_8_0 extends ClientMethodDispatcherImpl implements MethodDispatcher -{ - public ClientMethodDispatcherImpl_8_0(AMQProtocolSession session) - { - super(session); - } - - public boolean dispatchChannelAlert(ChannelAlertBody body, int channelId) throws AMQException - { - return false; - } - - @Override - public boolean dispatchQueueUnbindOk(final QueueUnbindOkBody queueUnbindOkBody, final int channelId) - { - return false; - } - - @Override - public boolean dispatchBasicRecoverSyncOk(final BasicRecoverSyncOkBody basicRecoverSyncOkBody, - final int channelId) - { - return false; - } - - @Override - public boolean dispatchQueueUnbind(final QueueUnbindBody body, final int channelId) throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } - - @Override - public boolean dispatchBasicRecoverSync(final BasicRecoverSyncBody body, final int channelId) - throws AMQException - { - throw new AMQMethodNotImplementedException(body); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/CloseWhenNoRouteSettingsHelper.java b/qpid/java/client/src/main/java/org/apache/qpid/client/handler/CloseWhenNoRouteSettingsHelper.java deleted file mode 100644 index e8343fda0a..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/CloseWhenNoRouteSettingsHelper.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.client.handler; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.jms.ConnectionURL; -import org.apache.qpid.properties.ConnectionStartProperties; - -/** - * Used during connection establishment to optionally set the "close when no route" client property - */ -class CloseWhenNoRouteSettingsHelper -{ - private static final Logger _log = LoggerFactory.getLogger(CloseWhenNoRouteSettingsHelper.class); - - /** - * @param url the client's connection URL which may contain the option - * {@value ConnectionStartProperties#QPID_CLOSE_WHEN_NO_ROUTE} - * @param serverProperties the properties received from the broker which may contain the option - * {@value ConnectionStartProperties#QPID_CLOSE_WHEN_NO_ROUTE} - * @param clientProperties the client properties to optionally set the close-when-no-route option on - */ - public void setClientProperties(FieldTable clientProperties, ConnectionURL url, FieldTable serverProperties) - { - boolean brokerSupportsCloseWhenNoRoute = - serverProperties != null && serverProperties.containsKey(ConnectionStartProperties.QPID_CLOSE_WHEN_NO_ROUTE); - boolean brokerCloseWhenNoRoute = brokerSupportsCloseWhenNoRoute && - Boolean.parseBoolean(serverProperties.getString(ConnectionStartProperties.QPID_CLOSE_WHEN_NO_ROUTE)); - - String closeWhenNoRouteOption = url.getOption(ConnectionURL.OPTIONS_CLOSE_WHEN_NO_ROUTE); - if(closeWhenNoRouteOption != null) - { - if(brokerSupportsCloseWhenNoRoute) - { - boolean desiredCloseWhenNoRoute = Boolean.valueOf(closeWhenNoRouteOption); - if(desiredCloseWhenNoRoute != brokerCloseWhenNoRoute) - { - clientProperties.setBoolean(ConnectionStartProperties.QPID_CLOSE_WHEN_NO_ROUTE, desiredCloseWhenNoRoute); - _log.debug( - "Set client property {} to {}", - ConnectionStartProperties.QPID_CLOSE_WHEN_NO_ROUTE, desiredCloseWhenNoRoute); - } - else - { - _log.debug( - "Client's desired {} value {} already matches the server's", - ConnectionURL.OPTIONS_CLOSE_WHEN_NO_ROUTE, desiredCloseWhenNoRoute); - } - } - else - { - _log.warn("The broker being connected to does not support the " + ConnectionURL.OPTIONS_CLOSE_WHEN_NO_ROUTE + " option"); - } - } - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionCloseMethodHandler.java b/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionCloseMethodHandler.java deleted file mode 100644 index 17b0fe1abb..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionCloseMethodHandler.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.client.handler; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQConnectionClosedException; -import org.apache.qpid.AMQException; -import org.apache.qpid.AMQSecurityException; -import org.apache.qpid.client.AMQAuthenticationException; -import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.apache.qpid.client.state.StateAwareMethodListener; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.ConnectionCloseBody; -import org.apache.qpid.framing.ConnectionCloseOkBody; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.transport.ByteBufferSender; -import org.apache.qpid.transport.TransportException; - -public class ConnectionCloseMethodHandler implements StateAwareMethodListener<ConnectionCloseBody> -{ - private static final Logger _logger = LoggerFactory.getLogger(ConnectionCloseMethodHandler.class); - - private static ConnectionCloseMethodHandler _handler = new ConnectionCloseMethodHandler(); - - public static ConnectionCloseMethodHandler getInstance() - { - return _handler; - } - - private ConnectionCloseMethodHandler() - { - } - - public void methodReceived(AMQProtocolSession session, ConnectionCloseBody method, int channelId) - throws AMQException - { - _logger.info("ConnectionClose frame received"); - - AMQConstant errorCode = AMQConstant.getConstant(method.getReplyCode()); - AMQShortString reason = method.getReplyText(); - - AMQException error = null; - - try - { - - ConnectionCloseOkBody closeOkBody = session.getMethodRegistry().createConnectionCloseOkBody(); - // TODO: check whether channel id of zero is appropriate - // Be aware of possible changes to parameter order as versions change. - session.writeFrame(closeOkBody.generateFrame(0)); - - if (errorCode != AMQConstant.REPLY_SUCCESS) - { - if (errorCode == AMQConstant.NOT_ALLOWED) - { - _logger.info("Error :" + errorCode + ":" + Thread.currentThread().getName()); - - error = new AMQAuthenticationException(errorCode, reason == null ? null : reason.toString(), null); - } - else if (errorCode == AMQConstant.ACCESS_REFUSED) - { - _logger.info("Error :" + errorCode + ":" + Thread.currentThread().getName()); - - error = new AMQSecurityException(reason == null ? null : reason.toString(), null); - } - else - { - _logger.info("Connection close received with error code " + errorCode); - - error = new AMQConnectionClosedException(errorCode, "Error: " + reason, null); - } - } - } - finally - { - ByteBufferSender sender = session.getSender(); - - if (error != null) - { - session.notifyError(error); - } - - // Close the open TCP connection - try - { - sender.close(); - } - catch(TransportException e) - { - //Ignore, they are already logged by the Sender and this - //is a connection-close being processed by the IoReceiver - //which will as it closes initiate failover if necessary. - } - } - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionOpenOkMethodHandler.java b/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionOpenOkMethodHandler.java deleted file mode 100644 index 1b197de910..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionOpenOkMethodHandler.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.client.handler; - -import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.apache.qpid.client.state.AMQState; -import org.apache.qpid.client.state.StateAwareMethodListener; -import org.apache.qpid.framing.ConnectionOpenOkBody; - -public class ConnectionOpenOkMethodHandler implements StateAwareMethodListener<ConnectionOpenOkBody> -{ - private static final ConnectionOpenOkMethodHandler _instance = new ConnectionOpenOkMethodHandler(); - - public static ConnectionOpenOkMethodHandler getInstance() - { - return _instance; - } - - private ConnectionOpenOkMethodHandler() - { - } - - public void methodReceived(AMQProtocolSession session, ConnectionOpenOkBody body, int channelId) - { - session.getStateManager().changeState(AMQState.CONNECTION_OPEN); - } - - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionRedirectMethodHandler.java b/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionRedirectMethodHandler.java deleted file mode 100644 index 6440f3e290..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionRedirectMethodHandler.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.client.handler; - -import java.nio.ByteBuffer; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.failover.ConnectionRedirectException; -import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.apache.qpid.client.state.StateAwareMethodListener; -import org.apache.qpid.framing.ConnectionRedirectBody; -import org.apache.qpid.transport.ByteBufferSender; -import org.apache.qpid.transport.TransportException; - -public class ConnectionRedirectMethodHandler implements StateAwareMethodListener<ConnectionRedirectBody> -{ - private static final Logger _logger = LoggerFactory.getLogger(ConnectionRedirectMethodHandler.class); - - private static final int DEFAULT_REDIRECT_PORT = 5672; - - private static ConnectionRedirectMethodHandler _handler = new ConnectionRedirectMethodHandler(); - - public static ConnectionRedirectMethodHandler getInstance() - { - return _handler; - } - - private ConnectionRedirectMethodHandler() - { } - - public void methodReceived(AMQProtocolSession session, ConnectionRedirectBody method, int channelId) - throws AMQException - { - _logger.info("ConnectionRedirect frame received"); - - String host = method.getHost().toString(); - // the host is in the form hostname:port with the port being optional - int portIndex = host.indexOf(':'); - - int port; - if (portIndex == -1) - { - port = DEFAULT_REDIRECT_PORT; - } - else - { - port = Integer.parseInt(host.substring(portIndex + 1)); - host = host.substring(0, portIndex); - - } - - session.notifyError(new ConnectionRedirectException(host,port)); - - ByteBufferSender sender = session.getSender(); - - // Close the open TCP connection - try - { - sender.close(); - } - catch(TransportException e) - { - //Ignore, they are already logged by the Sender and this - //is a connection-close being processed by the IoReceiver - //which will as it closes initiate failover if necessary. - } - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionSecureMethodHandler.java b/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionSecureMethodHandler.java deleted file mode 100644 index 8afb6ffcb4..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionSecureMethodHandler.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.client.handler; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.apache.qpid.client.state.StateAwareMethodListener; -import org.apache.qpid.framing.ConnectionSecureBody; -import org.apache.qpid.framing.ConnectionSecureOkBody; - -import javax.security.sasl.SaslClient; -import javax.security.sasl.SaslException; - -public class ConnectionSecureMethodHandler implements StateAwareMethodListener<ConnectionSecureBody> -{ - private static final ConnectionSecureMethodHandler _instance = new ConnectionSecureMethodHandler(); - - public static ConnectionSecureMethodHandler getInstance() - { - return _instance; - } - - public void methodReceived(AMQProtocolSession session, ConnectionSecureBody body, int channelId) - throws AMQException - { - SaslClient client = session.getSaslClient(); - if (client == null) - { - throw new AMQException(null, "No SASL client set up - cannot proceed with authentication", null); - } - - - - try - { - // Evaluate server challenge - byte[] response = client.evaluateChallenge(body.getChallenge()); - - ConnectionSecureOkBody secureOkBody = session.getMethodRegistry().createConnectionSecureOkBody(response); - - session.writeFrame(secureOkBody.generateFrame(channelId)); - } - catch (SaslException e) - { - throw new AMQException(null, "Error processing SASL challenge: " + e, e); - } - - - } - - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionStartMethodHandler.java b/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionStartMethodHandler.java deleted file mode 100644 index 2e817f2966..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionStartMethodHandler.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.client.handler; - -import java.io.UnsupportedEncodingException; -import java.util.StringTokenizer; - -import javax.security.sasl.Sasl; -import javax.security.sasl.SaslClient; -import javax.security.sasl.SaslException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.apache.qpid.client.security.AMQCallbackHandler; -import org.apache.qpid.client.security.CallbackHandlerRegistry; -import org.apache.qpid.client.state.AMQState; -import org.apache.qpid.client.state.StateAwareMethodListener; -import org.apache.qpid.common.QpidProperties; -import org.apache.qpid.configuration.ClientProperties; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.ConnectionStartBody; -import org.apache.qpid.framing.ConnectionStartOkBody; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.FieldTableFactory; -import org.apache.qpid.framing.ProtocolVersion; -import org.apache.qpid.jms.ConnectionURL; -import org.apache.qpid.properties.ConnectionStartProperties; - -public class ConnectionStartMethodHandler implements StateAwareMethodListener<ConnectionStartBody> -{ - private static final Logger _log = LoggerFactory.getLogger(ConnectionStartMethodHandler.class); - - private static final ConnectionStartMethodHandler _instance = new ConnectionStartMethodHandler(); - - private final CloseWhenNoRouteSettingsHelper _closeWhenNoRouteHelper = new CloseWhenNoRouteSettingsHelper(); - - public static ConnectionStartMethodHandler getInstance() - { - return _instance; - } - - private ConnectionStartMethodHandler() - { } - - @Override - public void methodReceived(AMQProtocolSession session, ConnectionStartBody body, int channelId) - throws AMQException - { - _log.debug("public void methodReceived(AMQStateManager stateManager, AMQProtocolSession protocolSession, " - + "AMQMethodEvent evt): called"); - - ProtocolVersion pv = new ProtocolVersion((byte) body.getVersionMajor(), (byte) body.getVersionMinor()); - - // 0-9-1 is indistinguishable from 0-9 using only major and minor ... if we established the connection as 0-9-1 - // and now get back major = 0 , minor = 9 then we can assume it means 0-9-1 - - if(pv.equals(ProtocolVersion.v0_9) && session.getProtocolVersion().equals(ProtocolVersion.v0_91)) - { - pv = ProtocolVersion.v0_91; - } - - // For the purposes of interop, we can make the client accept the broker's version string. - // If it does, it then internally records the version as being the latest one that it understands. - // It needs to do this since frame lookup is done by version. - if (Boolean.getBoolean("qpid.accept.broker.version") && !pv.isSupported()) - { - - pv = ProtocolVersion.getLatestSupportedVersion(); - } - - if (pv.isSupported()) - { - session.setProtocolVersion(pv); - - try - { - // Used to hold the SASL mechanism to authenticate with. - String mechanism; - - if (body.getMechanisms()== null) - { - throw new AMQException(null, "mechanism not specified in ConnectionStart method frame", null); - } - else - { - mechanism = chooseMechanism(body.getMechanisms()); - _log.debug("mechanism = " + mechanism); - } - - if (mechanism == null) - { - throw new AMQException(null, "No supported security mechanism found, passed: " + new String(body.getMechanisms()), null); - } - - byte[] saslResponse; - try - { - SaslClient sc = - Sasl.createSaslClient(new String[] { mechanism }, null, "AMQP", "localhost", null, - createCallbackHandler(mechanism, session)); - if (sc == null) - { - throw new AMQException(null, "Client SASL configuration error: no SaslClient could be created for mechanism " + mechanism - + ". Please ensure all factories are registered. See DynamicSaslRegistrar for " - + " details of how to register non-standard SASL client providers.", null); - } - - session.setSaslClient(sc); - saslResponse = (sc.hasInitialResponse() ? sc.evaluateChallenge(new byte[0]) : null); - } - catch (SaslException e) - { - session.setSaslClient(null); - throw new AMQException(null, "Unable to create SASL client: " + e, e); - } - - if (body.getLocales() == null) - { - throw new AMQException(null, "Locales is not defined in Connection Start method", null); - } - - final String locales = new String(body.getLocales(), "utf8"); - final StringTokenizer tokenizer = new StringTokenizer(locales, " "); - if (tokenizer.hasMoreTokens()) - { - tokenizer.nextToken(); - } - else - { - throw new AMQException(null, "No locales sent from server, passed: " + locales, null); - } - - session.getStateManager().changeState(AMQState.CONNECTION_NOT_TUNED); - - FieldTable clientProperties = FieldTableFactory.newFieldTable(); - - clientProperties.setString(ConnectionStartProperties.CLIENT_ID_0_8, - session.getClientID()); - clientProperties.setString(ConnectionStartProperties.PRODUCT, - QpidProperties.getProductName()); - clientProperties.setString(ConnectionStartProperties.VERSION_0_8, - QpidProperties.getReleaseVersion()); - clientProperties.setString(ConnectionStartProperties.PLATFORM, - ConnectionStartProperties.getPlatformInfo()); - clientProperties.setString(ConnectionStartProperties.PROCESS, - System.getProperty(ClientProperties.PROCESS_NAME, "Qpid Java Client")); - clientProperties.setInteger(ConnectionStartProperties.PID, - ConnectionStartProperties.getPID()); - - FieldTable serverProperties = body.getServerProperties(); - session.setConnectionStartServerProperties(serverProperties); - - ConnectionURL url = getConnectionURL(session); - _closeWhenNoRouteHelper.setClientProperties(clientProperties, url, serverProperties); - - clientProperties.setString(ConnectionStartProperties.QPID_MESSAGE_COMPRESSION_SUPPORTED, - String.valueOf(session.getAMQConnection().isMessageCompressionDesired())); - - ConnectionStartOkBody connectionStartOkBody = session.getMethodRegistry().createConnectionStartOkBody(clientProperties,new AMQShortString(mechanism),saslResponse,new AMQShortString(locales)); - // 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(connectionStartOkBody.generateFrame(channelId)); - - } - catch (UnsupportedEncodingException e) - { - throw new AMQException(null, "Unable to decode data: " + e, e); - } - } - else - { - _log.error("Broker requested Protocol [" + body.getVersionMajor() + "-" + body.getVersionMinor() - + "] which is not supported by this version of the client library"); - - session.closeProtocolSession(); - } - } - - private String chooseMechanism(byte[] availableMechanisms) throws UnsupportedEncodingException - { - final String mechanisms = new String(availableMechanisms, "utf8"); - return CallbackHandlerRegistry.getInstance().selectMechanism(mechanisms); - } - - private AMQCallbackHandler createCallbackHandler(String mechanism, AMQProtocolSession protocolSession) - throws AMQException - { - try - { - AMQCallbackHandler instance = CallbackHandlerRegistry.getInstance().createCallbackHandler(mechanism); - instance.initialise(getConnectionURL(protocolSession)); - - return instance; - } - catch (IllegalArgumentException e) - { - throw new AMQException(null, "Unable to create callback handler: " + e, e); - } - } - - private ConnectionURL getConnectionURL(AMQProtocolSession protocolSession) - { - return protocolSession.getAMQConnection().getConnectionURL(); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionTuneMethodHandler.java b/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionTuneMethodHandler.java deleted file mode 100644 index 1f2df2026b..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionTuneMethodHandler.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.client.handler; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.client.ConnectionTuneParameters; -import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.apache.qpid.client.state.AMQState; -import org.apache.qpid.client.state.StateAwareMethodListener; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.ConnectionOpenBody; -import org.apache.qpid.framing.ConnectionTuneBody; -import org.apache.qpid.framing.ConnectionTuneOkBody; -import org.apache.qpid.framing.MethodRegistry; - -public class ConnectionTuneMethodHandler implements StateAwareMethodListener<ConnectionTuneBody> -{ - private static final Logger _logger = LoggerFactory.getLogger(ConnectionTuneMethodHandler.class); - - private static final ConnectionTuneMethodHandler _instance = new ConnectionTuneMethodHandler(); - - public static ConnectionTuneMethodHandler getInstance() - { - return _instance; - } - - protected ConnectionTuneMethodHandler() - { } - - public void methodReceived(AMQProtocolSession session, ConnectionTuneBody frame, int channelId) - { - _logger.debug("ConnectionTune frame received"); - final MethodRegistry methodRegistry = session.getMethodRegistry(); - - ConnectionTuneParameters params = session.getConnectionTuneParameters(); - - int maxChannelNumber = frame.getChannelMax(); - //0 implies no limit, except that forced by protocol limitations (0xFFFF) - params.setChannelMax(maxChannelNumber == 0 ? AMQProtocolSession.MAX_CHANNEL_MAX : maxChannelNumber); - params.setFrameMax(frame.getFrameMax()); - - //if the heart beat delay hasn't been configured, we use the broker-supplied value - if (params.getHeartbeat() == null) - { - params.setHeartbeat(frame.getHeartbeat()); - } - - session.tuneConnection(params); - - session.getStateManager().changeState(AMQState.CONNECTION_NOT_OPENED); - - ConnectionTuneOkBody tuneOkBody = methodRegistry.createConnectionTuneOkBody(params.getChannelMax(), - params.getFrameMax(), - params.getHeartbeat()); - - session.setMaxFrameSize(params.getFrameMax()); - // Be aware of possible changes to parameter order as versions change. - session.writeFrame(tuneOkBody.generateFrame(channelId)); - - String host = session.getAMQConnection().getVirtualHost(); - AMQShortString virtualHost = new AMQShortString("/" + host); - - ConnectionOpenBody openBody = methodRegistry.createConnectionOpenBody(virtualHost,null,true); - - // Be aware of possible changes to parameter order as versions change. - session.writeFrame(openBody.generateFrame(channelId)); - } - - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ExchangeBoundOkMethodHandler.java b/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ExchangeBoundOkMethodHandler.java deleted file mode 100644 index b60127cf93..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/ExchangeBoundOkMethodHandler.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.client.handler; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.apache.qpid.client.state.StateAwareMethodListener; -import org.apache.qpid.framing.ExchangeBoundOkBody; - -/** - * @author Apache Software Foundation - */ -public class ExchangeBoundOkMethodHandler implements StateAwareMethodListener<ExchangeBoundOkBody> -{ - private static final Logger _logger = LoggerFactory.getLogger(ExchangeBoundOkMethodHandler.class); - private static final ExchangeBoundOkMethodHandler _instance = new ExchangeBoundOkMethodHandler(); - - public static ExchangeBoundOkMethodHandler getInstance() - { - return _instance; - } - - private ExchangeBoundOkMethodHandler() - { } - - public void methodReceived(AMQProtocolSession session, ExchangeBoundOkBody body, int channelId) - throws AMQException - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Received Exchange.Bound-Ok message, response code: " + body.getReplyCode() + " text: " - + body.getReplyText()); - } - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/QueueDeleteOkMethodHandler.java b/qpid/java/client/src/main/java/org/apache/qpid/client/handler/QueueDeleteOkMethodHandler.java deleted file mode 100644 index 3c76a8ac38..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/handler/QueueDeleteOkMethodHandler.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.client.handler; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.apache.qpid.client.state.StateAwareMethodListener; -import org.apache.qpid.framing.QueueDeleteOkBody; - -/** - * @author Apache Software Foundation - */ -public class QueueDeleteOkMethodHandler implements StateAwareMethodListener<QueueDeleteOkBody> -{ - private static final Logger _logger = LoggerFactory.getLogger(QueueDeleteOkMethodHandler.class); - private static final QueueDeleteOkMethodHandler _instance = new QueueDeleteOkMethodHandler(); - - public static QueueDeleteOkMethodHandler getInstance() - { - return _instance; - } - - private QueueDeleteOkMethodHandler() - { } - - public void methodReceived(AMQProtocolSession session, QueueDeleteOkBody body, int channelId) - throws AMQException - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Received Queue.Delete-Ok message, message count: " + body.getMessageCount()); - } - } - - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate.java deleted file mode 100644 index d01c4ac33d..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate.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.client.message; - -import org.apache.qpid.client.AMQSession; - -import javax.jms.Destination; -import javax.jms.JMSException; -import java.util.Enumeration; -import java.util.UUID; - -public interface AMQMessageDelegate -{ - void acknowledgeThis() throws JMSException; - - String getJMSMessageID() throws JMSException; - - void setJMSMessageID(String string) throws JMSException; - - long getJMSTimestamp() throws JMSException; - - void setJMSTimestamp(long l) throws JMSException; - - byte[] getJMSCorrelationIDAsBytes() throws JMSException; - - void setJMSCorrelationIDAsBytes(byte[] bytes) throws JMSException; - - void setJMSCorrelationID(String string) throws JMSException; - - String getJMSCorrelationID() throws JMSException; - - Destination getJMSReplyTo() throws JMSException; - - void setJMSReplyTo(Destination destination) throws JMSException; - - Destination getJMSDestination() throws JMSException; - - int getJMSDeliveryMode() throws JMSException; - - void setJMSDeliveryMode(int i) throws JMSException; - - String getJMSType() throws JMSException; - - void setJMSType(String string) throws JMSException; - - long getJMSExpiration() throws JMSException; - - void setJMSExpiration(long l) throws JMSException; - - int getJMSPriority() throws JMSException; - - void setJMSPriority(int i) throws JMSException; - - void clearProperties() throws JMSException; - - boolean propertyExists(String string) throws JMSException; - - boolean getBooleanProperty(String string) throws JMSException; - - byte getByteProperty(String string) throws JMSException; - - short getShortProperty(String string) throws JMSException; - - int getIntProperty(String string) throws JMSException; - - long getLongProperty(String string) throws JMSException; - - float getFloatProperty(String string) throws JMSException; - - double getDoubleProperty(String string) throws JMSException; - - String getStringProperty(String string) throws JMSException; - - Object getObjectProperty(String string) throws JMSException; - - Enumeration getPropertyNames() throws JMSException; - - void setBooleanProperty(String string, boolean b) throws JMSException; - - void setByteProperty(String string, byte b) throws JMSException; - - void setShortProperty(String string, short i) throws JMSException; - - void setIntProperty(String string, int i) throws JMSException; - - void setLongProperty(String string, long l) throws JMSException; - - void setFloatProperty(String string, float v) throws JMSException; - - void setDoubleProperty(String string, double v) throws JMSException; - - void setStringProperty(String string, String string1) throws JMSException; - - void setObjectProperty(String string, Object object) throws JMSException; - - void acknowledge() throws JMSException; - - public void setJMSDestination(Destination destination); - - public void setContentType(String contentType); - public String getContentType(); - - public void setEncoding(String encoding); - public String getEncoding(); - - - String getReplyToString(); - - void removeProperty(final String propertyName) throws JMSException; - - void setAMQSession(final AMQSession<?,?> s); - - AMQSession<?,?> getAMQSession(); - - long getDeliveryTag(); - - void setJMSMessageID(final UUID messageId) throws JMSException; -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegateFactory.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegateFactory.java deleted file mode 100644 index e5b95f54f4..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegateFactory.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.client.message; - -public interface AMQMessageDelegateFactory<D extends AMQMessageDelegate> -{ - public static AMQMessageDelegateFactory DEFAULT_FACTORY = null; - - public static AMQMessageDelegateFactory<AMQMessageDelegate_0_8> FACTORY_0_8 = - new AMQMessageDelegateFactory<AMQMessageDelegate_0_8>() - { - public AMQMessageDelegate_0_8 createDelegate() - { - return new AMQMessageDelegate_0_8(); - } - }; - - public static AMQMessageDelegateFactory<AMQMessageDelegate_0_10> FACTORY_0_10 = - new AMQMessageDelegateFactory<AMQMessageDelegate_0_10>() - { - public AMQMessageDelegate_0_10 createDelegate() - { - return new AMQMessageDelegate_0_10(); - } - }; - - - public D createDelegate(); - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate_0_10.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate_0_10.java deleted file mode 100644 index fa0a6be91c..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate_0_10.java +++ /dev/null @@ -1,1002 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.MessageFormatException; -import javax.jms.MessageNotWriteableException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.AMQPInvalidClassException; -import org.apache.qpid.client.AMQDestination; -import org.apache.qpid.client.AMQDestination.DestSyntax; -import org.apache.qpid.client.CustomJMSXProperty; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.jms.Message; -import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.transport.ExchangeQueryResult; -import org.apache.qpid.transport.Future; -import org.apache.qpid.transport.Header; -import org.apache.qpid.transport.MessageDeliveryMode; -import org.apache.qpid.transport.MessageDeliveryPriority; -import org.apache.qpid.transport.MessageProperties; -import org.apache.qpid.transport.ReplyTo; -import org.apache.qpid.transport.TransportException; - -/** - * This extends AbstractAMQMessageDelegate which contains common code between - * both the 0_8 and 0_10 Message types. - * - */ -public class AMQMessageDelegate_0_10 extends AbstractAMQMessageDelegate -{ - private static final Logger _logger = LoggerFactory.getLogger(AMQMessageDelegate_0_10.class); - - private static final float DESTINATION_CACHE_LOAD_FACTOR = 0.75f; - private static final int DESTINATION_CACHE_SIZE = 500; - private static final int DESTINATION_CACHE_CAPACITY = (int) (DESTINATION_CACHE_SIZE / DESTINATION_CACHE_LOAD_FACTOR); - - private static final Map<ReplyTo, Destination> _destinationCache = - Collections.synchronizedMap(new LinkedHashMap<ReplyTo,Destination>(DESTINATION_CACHE_CAPACITY, - DESTINATION_CACHE_LOAD_FACTOR, - true) - { - @Override - protected boolean removeEldestEntry(Map.Entry<ReplyTo, Destination> eldest) - { - return size() >= DESTINATION_CACHE_SIZE; - } - }); - - public static final String JMS_TYPE = "x-jms-type"; - - - private boolean _readableProperties = false; - - private Destination _destination; - - private MessageProperties _messageProps; - private DeliveryProperties _deliveryProps; - private String _messageID; - private boolean isStrictJMS = Boolean.getBoolean("strict-jms"); - - protected AMQMessageDelegate_0_10() - { - this(new MessageProperties(), new DeliveryProperties(), -1); - _readableProperties = false; - } - - protected AMQMessageDelegate_0_10(MessageProperties messageProps, DeliveryProperties deliveryProps, long deliveryTag) - { - this(AMQDestination.getDefaultDestSyntax(),messageProps,deliveryProps,deliveryTag); - } - - protected AMQMessageDelegate_0_10(DestSyntax destSyntax,MessageProperties messageProps, DeliveryProperties deliveryProps, long deliveryTag) - { - super(deliveryTag); - _messageProps = messageProps; - _deliveryProps = deliveryProps; - _readableProperties = (_messageProps != null); - - AMQDestination dest; - - if (destSyntax == AMQDestination.DestSyntax.BURL) - { - dest = generateDestination(new AMQShortString(_deliveryProps.getExchange()), - new AMQShortString(_deliveryProps.getRoutingKey())); - } - else - { - String subject = null; - if (isStrictJMS && messageProps != null && messageProps.getApplicationHeaders() != null) - { - subject = (String)messageProps.getApplicationHeaders().get(QpidMessageProperties.QPID_SUBJECT); - if (subject != null) - { - messageProps.getApplicationHeaders().remove(QpidMessageProperties.QPID_SUBJECT); - messageProps.getApplicationHeaders().put(QpidMessageProperties.QPID_SUBJECT_JMS_PROPERTY,subject); - } - } - dest = (AMQDestination) convertToAddressBasedDestination(_deliveryProps.getExchange(), - _deliveryProps.getRoutingKey(), subject, false, AMQDestination.UNKNOWN_TYPE); - } - - setJMSDestination(dest); - } - - /** - * Use the 0-10 ExchangeQuery call to validate the exchange type. - * - * This is used primarily to provide the correct JMSDestination value. - * - * The query is performed synchronously iff the map exchange is not already - * present in the exchange Map. - * - * @param header The message headers, from which the exchange name can be extracted - * @param session The 0-10 session to use to call ExchangeQuery - */ - public static void updateExchangeTypeMapping(Header header, org.apache.qpid.transport.Session session) - { - DeliveryProperties deliveryProps = header.getDeliveryProperties(); - if (deliveryProps != null) - { - String exchange = deliveryProps.getExchange(); - checkAndUpdateExchange(exchange,session); - - } - - MessageProperties msgProps = header.getMessageProperties(); - if (msgProps != null && msgProps.getReplyTo() != null) - { - String exchange = msgProps.getReplyTo().getExchange(); - checkAndUpdateExchange(exchange,session); - - } - } - - private static void checkAndUpdateExchange(String exchange, org.apache.qpid.transport.Session session) - { - if (exchange != null && !exchangeMapContains(exchange)) - { - Future<ExchangeQueryResult> future = - session.exchangeQuery(exchange.toString()); - ExchangeQueryResult res = future.get(); - - updateExchangeType(exchange, res.getType()); - } - } - - - public String getJMSMessageID() throws JMSException - { - if (_messageID == null && _messageProps.getMessageId() != null) - { - UUID id = _messageProps.getMessageId(); - _messageID = "ID:" + id; - } - return _messageID; - } - - public void setJMSMessageID(String messageId) throws JMSException - { - if(messageId == null) - { - _messageProps.clearMessageId(); - } - else - { - if(messageId.startsWith("ID:")) - { - _messageID = messageId; - } - else - { - throw new JMSException("MessageId '"+messageId+"' is not of the correct format, it must be prefixed with 'ID:'"); - } - } - } - - /* Used by the internal implementation */ - public void setJMSMessageID(UUID messageId) throws JMSException - { - if(messageId == null) - { - _messageProps.clearMessageId(); - } - else - { - _messageProps.setMessageId(messageId); - } - } - - public long getJMSTimestamp() throws JMSException - { - return _deliveryProps.getTimestamp(); - } - - public void setJMSTimestamp(long timestamp) throws JMSException - { - _deliveryProps.setTimestamp(timestamp); - } - - public byte[] getJMSCorrelationIDAsBytes() throws JMSException - { - return _messageProps.getCorrelationId(); - } - - public void setJMSCorrelationIDAsBytes(byte[] bytes) throws JMSException - { - _messageProps.setCorrelationId(bytes); - } - - public void setJMSCorrelationID(String correlationId) throws JMSException - { - - setJMSCorrelationIDAsBytes(correlationId == null ? null : correlationId.getBytes()); - } - - public String getJMSCorrelationID() throws JMSException - { - - byte[] correlationIDAsBytes = getJMSCorrelationIDAsBytes(); - return correlationIDAsBytes == null ? null : new String(correlationIDAsBytes); - } - - public Destination getJMSReplyTo() - { - ReplyTo replyTo = _messageProps.getReplyTo(); - - if ((replyTo == null) || ((replyTo.getExchange() == null) && (replyTo.getRoutingKey() == null))) - { - return null; - } - else - { - Destination dest = _destinationCache.get(replyTo); - - if (dest == null) - { - String exchange = replyTo.getExchange(); - String routingKey = replyTo.getRoutingKey(); - - if (AMQDestination.getDefaultDestSyntax() == AMQDestination.DestSyntax.BURL) - { - dest = generateDestination(new AMQShortString(exchange), new AMQShortString(routingKey)); - } - else - { - dest = convertToAddressBasedDestination(exchange,routingKey,null, false, - AMQDestination.UNKNOWN_TYPE); - } - _destinationCache.put(replyTo, dest); - } - - return dest; - } - } - - public void setJMSReplyTo(Destination destination) throws JMSException - { - if (destination == null) - { - _messageProps.clearReplyTo(); - return; - } - - if (!(destination instanceof AMQDestination)) - { - throw new IllegalArgumentException( - "ReplyTo destination may only be an AMQDestination - passed argument was type " + destination.getClass()); - } - - final AMQDestination amqd = (AMQDestination) destination; - - if (amqd.getDestSyntax() == AMQDestination.DestSyntax.ADDR) - { - try - { - int type = getAMQSession().resolveAddressType(amqd); - if (type == AMQDestination.QUEUE_TYPE) - { - getAMQSession().setLegacyFieldsForQueueType(amqd); - } - else - { - getAMQSession().setLegacyFieldsForTopicType(amqd); - } - } - catch(AMQException ex) - { - JMSException e = new JMSException("Error occured while figuring out the node type"); - e.initCause(ex); - e.setLinkedException(ex); - throw e; - } - catch (TransportException e) - { - JMSException jmse = new JMSException("Exception occured while figuring out the node type:" + e.getMessage()); - jmse.initCause(e); - jmse.setLinkedException(e); - throw jmse; - } - } - - final ReplyTo replyTo = new ReplyTo(amqd.getExchangeName().toString(), amqd.getRoutingKey().toString()); - _destinationCache.put(replyTo, destination); - _messageProps.setReplyTo(replyTo); - } - - public Destination getJMSDestination() throws JMSException - { - return _destination; - } - - public void setJMSDestination(Destination destination) - { - _destination = destination; - } - - public void setContentType(String contentType) - { - _messageProps.setContentType(contentType); - } - - public String getContentType() - { - return _messageProps.getContentType(); - } - - public void setEncoding(String encoding) - { - if(encoding == null || encoding.length() == 0) - { - _messageProps.clearContentEncoding(); - } - else - { - _messageProps.setContentEncoding(encoding); - } - } - - public String getEncoding() - { - return _messageProps.getContentEncoding(); - } - - public String getReplyToString() - { - Destination replyTo = getJMSReplyTo(); - if(replyTo != null) - { - return ((AMQDestination)replyTo).toString(); - } - else - { - return null; - } - - } - - public int getJMSDeliveryMode() throws JMSException - { - - MessageDeliveryMode deliveryMode = _deliveryProps.getDeliveryMode(); - if(deliveryMode != null) - { - switch(deliveryMode) - { - case PERSISTENT : - return DeliveryMode.PERSISTENT; - case NON_PERSISTENT: - return DeliveryMode.NON_PERSISTENT; - default: - throw new JMSException("Unknown Message Delivery Mode: " + _deliveryProps.getDeliveryMode()); - } - } - else - { - return Message.DEFAULT_DELIVERY_MODE; - } - - } - - public void setJMSDeliveryMode(int deliveryMode) throws JMSException - { - switch(deliveryMode) - { - case DeliveryMode.PERSISTENT: - _deliveryProps.setDeliveryMode(MessageDeliveryMode.PERSISTENT); - break; - case DeliveryMode.NON_PERSISTENT: - _deliveryProps.setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT); - break; - default: - throw new JMSException("Unknown JMS Delivery Mode: " + deliveryMode); - } - - } - - - public String getJMSType() throws JMSException - { - if(getApplicationHeaders().containsKey(JMS_TYPE)) - { - return getStringProperty(JMS_TYPE); - } - else - { - return null; - } - } - - private Map<String, Object> getApplicationHeaders() - { - Map<String, Object> map = _messageProps.getApplicationHeaders(); - return map == null ? Collections.EMPTY_MAP : map; - } - - public void setJMSType(String type) throws JMSException - { - Map<String, Object> headers = _messageProps.getApplicationHeaders(); - if(type == null) - { - if(headers != null) - { - headers.remove(JMS_TYPE); - } - } - else - { - if(headers == null) - { - headers = new HashMap<String,Object>(); - _messageProps.setApplicationHeaders(headers); - - } - headers.put(JMS_TYPE, type); - } - } - - public long getJMSExpiration() throws JMSException - { - return _deliveryProps.getExpiration(); - } - - public void setJMSExpiration(long l) throws JMSException - { - _deliveryProps.setExpiration(l); - } - - - - public boolean propertyExists(String propertyName) throws JMSException - { - return getApplicationHeaders().containsKey(propertyName); - } - - public boolean getBooleanProperty(String propertyName) throws JMSException - { - checkPropertyName(propertyName); - - Object o = getApplicationHeaders().get(propertyName); - - if(o instanceof Boolean) - { - return ((Boolean)o).booleanValue(); - } - else if(o instanceof String) - { - return Boolean.valueOf((String) o).booleanValue(); - } - else if(getApplicationHeaders().containsKey(propertyName)) - { - throw new MessageFormatException("getBooleanProperty(\""+propertyName+"\") failed as value is not boolean: " + o); - } - else - { - return Boolean.valueOf(null); - } - } - - public byte getByteProperty(String propertyName) throws JMSException - { - checkPropertyName(propertyName); - - Map<String, Object> propertyMap = getApplicationHeaders(); - - Object o = propertyMap.get(propertyName); - - if(o instanceof Byte) - { - return ((Byte)o).byteValue(); - } - else if(o instanceof String) - { - return Byte.valueOf((String) o).byteValue(); - } - else if(getApplicationHeaders().containsKey(propertyName)) - { - throw new MessageFormatException("getByteProperty(\""+propertyName+"\") failed as value is not a byte: " + o); - } - else - { - return Byte.valueOf(null); - } - } - - public short getShortProperty(String propertyName) throws JMSException - { - checkPropertyName(propertyName); - - Map<String, Object> propertyMap = getApplicationHeaders(); - - Object o = propertyMap.get(propertyName); - - if(o instanceof Short) - { - return ((Short)o).shortValue(); - } - else if(o instanceof String) - { - return Short.valueOf((String) o); - } - else - { - try - { - return Short.valueOf(getByteProperty(propertyName)); - } - catch(MessageFormatException e) - { - throw new MessageFormatException("getShortProperty(\""+propertyName+"\") failed as value is not a short: " + o); - } - } - - - } - - public int getIntProperty(String propertyName) throws JMSException - { - checkPropertyName(propertyName); - - Map<String, Object> propertyMap = getApplicationHeaders(); - - Object o = propertyMap.get(propertyName); - - if(o instanceof Integer) - { - return ((Integer)o).intValue(); - } - else if(o instanceof String) - { - return Integer.valueOf((String) o); - } - else - { - try - { - return Integer.valueOf(getShortProperty(propertyName)); - } - catch(MessageFormatException e) - { - throw new MessageFormatException("getIntProperty(\""+propertyName+"\") failed as value is not an int: " + o); - } - - } - } - - public long getLongProperty(String propertyName) throws JMSException - { - checkPropertyName(propertyName); - - Map<String, Object> propertyMap = getApplicationHeaders(); - - Object o = propertyMap.get(propertyName); - - if(o instanceof Long) - { - return ((Long)o).longValue(); - } - else if(o instanceof String) - { - return Long.valueOf((String) o); - } - else - { - try - { - return Long.valueOf(getIntProperty(propertyName)); - } - catch(MessageFormatException e) - { - throw new MessageFormatException("getLongProperty(\""+propertyName+"\") failed as value is not a long: " + o); - } - - } - } - - public float getFloatProperty(String propertyName) throws JMSException - { - checkPropertyName(propertyName); - Map<String, Object> propertyMap = getApplicationHeaders(); - - Object o = propertyMap.get(propertyName); - - if(o instanceof Float) - { - return ((Float)o).floatValue(); - } - else if(o instanceof String) - { - return Float.valueOf((String) o).floatValue(); - } - else if(getApplicationHeaders().containsKey(propertyName)) - { - throw new MessageFormatException("getFloatProperty(\""+propertyName+"\") failed as value is not a float: " + o); - } - else - { - throw new NullPointerException("No such property: " + propertyName); - } - - } - - public double getDoubleProperty(String propertyName) throws JMSException - { - checkPropertyName(propertyName); - - Map<String, Object> propertyMap = getApplicationHeaders(); - - Object o = propertyMap.get(propertyName); - - if(o instanceof Double) - { - return ((Double)o).doubleValue(); - } - else if (o instanceof String) - { - return Double.valueOf((String)o); - } - else - { - try - { - return Double.valueOf(getFloatProperty(propertyName)); - } - catch(MessageFormatException e) - { - throw new MessageFormatException("getDoubleProperty(\""+propertyName+"\") failed as value is not a double: " + o); - } - - } - } - - public String getStringProperty(String propertyName) throws JMSException - { - if (propertyName.equals(CustomJMSXProperty.JMSXUserID.toString())) - { - final byte[] userIdBytes = _messageProps.getUserId(); - return userIdBytes == null ? null : new String(userIdBytes); - } - else if (QpidMessageProperties.AMQP_0_10_APP_ID.equals(propertyName) && - _messageProps.getAppId() != null) - { - return new String(_messageProps.getAppId()); - } - else if (QpidMessageProperties.AMQP_0_10_ROUTING_KEY.equals(propertyName) && - _deliveryProps.getRoutingKey() != null) - { - return _deliveryProps.getRoutingKey(); - } - else if (isStrictJMS && QpidMessageProperties.QPID_SUBJECT.equals(propertyName)) - { - return (String)getApplicationHeaders().get(QpidMessageProperties.QPID_SUBJECT_JMS_PROPERTY); - } - else - { - checkPropertyName(propertyName); - Map<String, Object> propertyMap = getApplicationHeaders(); - - Object o = propertyMap.get(propertyName); - - if(o instanceof String) - { - return (String) o; - } - else if(o == null) - { - return null; - } - else if(o.getClass().isArray()) - { - throw new MessageFormatException("getString(\""+propertyName+"\") failed as value of type " + o.getClass()+ " is an array."); - } - else - { - return String.valueOf(o); - } - - } - } - - public Object getObjectProperty(String propertyName) throws JMSException - { - checkPropertyName(propertyName); - Map<String, Object> propertyMap = getApplicationHeaders(); - - return propertyMap.get(propertyName); - - } - - public Enumeration getPropertyNames() throws JMSException - { - List<String> props = new ArrayList<String>(); - Map<String, Object> propertyMap = getApplicationHeaders(); - for (String prop: getApplicationHeaders().keySet()) - { - Object value = propertyMap.get(prop); - if (value instanceof Boolean || value instanceof Number - || value instanceof String) - { - props.add(prop); - } - } - - return java.util.Collections.enumeration(props); - } - - public void setBooleanProperty(String propertyName, boolean b) throws JMSException - { - checkPropertyName(propertyName); - checkWritableProperties(); - setApplicationHeader(propertyName, b); - } - - public void setByteProperty(String propertyName, byte b) throws JMSException - { - checkPropertyName(propertyName); - checkWritableProperties(); - setApplicationHeader(propertyName, b); - } - - public void setShortProperty(String propertyName, short i) throws JMSException - { - checkPropertyName(propertyName); - checkWritableProperties(); - setApplicationHeader(propertyName, i); - } - - public void setIntProperty(String propertyName, int i) throws JMSException - { - checkPropertyName(propertyName); - checkWritableProperties(); - setApplicationHeader(propertyName, i); - } - - public void setLongProperty(String propertyName, long l) throws JMSException - { - checkPropertyName(propertyName); - checkWritableProperties(); - setApplicationHeader(propertyName, l); - } - - public void setFloatProperty(String propertyName, float f) throws JMSException - { - checkPropertyName(propertyName); - checkWritableProperties(); - setApplicationHeader(propertyName, f); - } - - public void setDoubleProperty(String propertyName, double v) throws JMSException - { - checkPropertyName(propertyName); - checkWritableProperties(); - setApplicationHeader(propertyName, v); - } - - public void setStringProperty(String propertyName, String value) throws JMSException - { - checkPropertyName(propertyName); - checkWritableProperties(); - if (QpidMessageProperties.AMQP_0_10_APP_ID.equals(propertyName)) - { - _messageProps.setAppId(value.getBytes()); - } - else - { - setApplicationHeader(propertyName, value); - } - } - - private static final Set<Class> ALLOWED = new HashSet(); - static - { - ALLOWED.add(Boolean.class); - ALLOWED.add(Byte.class); - ALLOWED.add(Short.class); - ALLOWED.add(Integer.class); - ALLOWED.add(Long.class); - ALLOWED.add(Float.class); - ALLOWED.add(Double.class); - ALLOWED.add(Character.class); - ALLOWED.add(String.class); - ALLOWED.add(byte[].class); - } - - public void setObjectProperty(String propertyName, Object object) throws JMSException - { - checkPropertyName(propertyName); - checkWritableProperties(); - if (object == null) - { - throw new MessageFormatException(AMQPInvalidClassException.INVALID_OBJECT_MSG + "null"); - } - else if (!ALLOWED.contains(object.getClass())) - { - throw new MessageFormatException(AMQPInvalidClassException.INVALID_OBJECT_MSG + object.getClass()); - } - setApplicationHeader(propertyName, object); - } - - private void setApplicationHeader(String propertyName, Object object) - { - Map<String, Object> headers = _messageProps.getApplicationHeaders(); - if(headers == null) - { - headers = new HashMap<String,Object>(); - _messageProps.setApplicationHeaders(headers); - } - headers.put(propertyName, object); - } - - public void removeProperty(String propertyName) throws JMSException - { - Map<String, Object> headers = _messageProps.getApplicationHeaders(); - if(headers != null) - { - headers.remove(propertyName); - } - } - - - - protected void checkWritableProperties() throws MessageNotWriteableException - { - if (_readableProperties) - { - throw new MessageNotWriteableException("You need to call clearProperties() to make the message writable"); - } - } - - - public int getJMSPriority() throws JMSException - { - MessageDeliveryPriority messageDeliveryPriority = _deliveryProps.getPriority(); - return messageDeliveryPriority == null ? Message.DEFAULT_PRIORITY : messageDeliveryPriority.getValue(); - } - - public void setJMSPriority(int i) throws JMSException - { - _deliveryProps.setPriority(MessageDeliveryPriority.get((short)i)); - } - - public void clearProperties() throws JMSException - { - if(!getApplicationHeaders().isEmpty()) - { - getApplicationHeaders().clear(); - } - - _readableProperties = false; - } - - protected void checkPropertyName(CharSequence propertyName) - { - if (propertyName == null) - { - throw new IllegalArgumentException("Property name must not be null"); - } - else if (propertyName.length() == 0) - { - throw new IllegalArgumentException("Property name must not be the empty string"); - } - - checkIdentiferFormat(propertyName); - } - - protected void checkIdentiferFormat(CharSequence propertyName) - { -// JMS requirements 3.5.1 Property Names -// Identifiers: -// - An identifier is an unlimited-length character sequence that must begin -// with a Java identifier start character; all following characters must be Java -// identifier part characters. An identifier start character is any character for -// which the method Character.isJavaIdentifierStart returns true. This includes -// '_' and '$'. An identifier part character is any character for which the -// method Character.isJavaIdentifierPart returns true. -// - Identifiers cannot be the names NULL, TRUE, or FALSE. -// Identifiers cannot be NOT, AND, OR, BETWEEN, LIKE, IN, IS, or -// ESCAPE. -// Identifiers are either header field references or property references. The -// type of a property value in a message selector corresponds to the type -// used to set the property. If a property that does not exist in a message is -// referenced, its value is NULL. The semantics of evaluating NULL values -// in a selector are described in Section 3.8.1.2, Null Values. -// The conversions that apply to the get methods for properties do not -// apply when a property is used in a message selector expression. For -// example, suppose you set a property as a string value, as in the -// following: -// myMessage.setStringProperty("NumberOfOrders", "2") -// The following expression in a message selector would evaluate to false, -// because a string cannot be used in an arithmetic expression: -// "NumberOfOrders > 1" -// Identifiers are case sensitive. -// Message header field references are restricted to JMSDeliveryMode, -// JMSPriority, JMSMessageID, JMSTimestamp, JMSCorrelationID, and -// JMSType. JMSMessageID, JMSCorrelationID, and JMSType values may be -// null and if so are treated as a NULL value. - - if (isStrictJMS) - { - // JMS start character - if (!(Character.isJavaIdentifierStart(propertyName.charAt(0)))) - { - throw new IllegalArgumentException("Identifier '" + propertyName + "' does not start with a valid JMS identifier start character"); - } - - // JMS part character - int length = propertyName.length(); - for (int c = 1; c < length; c++) - { - if (!(Character.isJavaIdentifierPart(propertyName.charAt(c)))) - { - throw new IllegalArgumentException("Identifier '" + propertyName + "' contains an invalid JMS identifier character"); - } - } - - // JMS invalid names - if ((propertyName.equals("NULL") - || propertyName.equals("TRUE") - || propertyName.equals("FALSE") - || propertyName.equals("NOT") - || propertyName.equals("AND") - || propertyName.equals("OR") - || propertyName.equals("BETWEEN") - || propertyName.equals("LIKE") - || propertyName.equals("IN") - || propertyName.equals("IS") - || propertyName.equals("ESCAPE"))) - { - throw new IllegalArgumentException("Identifier '" + propertyName + "' is not allowed in JMS"); - } - } - - } - - - public MessageProperties getMessageProperties() - { - return _messageProps; - } - - - public DeliveryProperties getDeliveryProperties() - { - return _deliveryProps; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate_0_8.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate_0_8.java deleted file mode 100644 index 486023e847..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate_0_8.java +++ /dev/null @@ -1,683 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 java.net.URISyntaxException; -import java.util.Collections; -import java.util.Enumeration; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.MessageNotWriteableException; -import javax.jms.Queue; - -import org.apache.qpid.client.AMQDestination; -import org.apache.qpid.client.AMQQueue; -import org.apache.qpid.client.AMQSession; -import org.apache.qpid.client.AMQSession_0_8; -import org.apache.qpid.client.AMQTopic; -import org.apache.qpid.client.CustomJMSXProperty; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.url.AMQBindingURL; -import org.apache.qpid.url.BindingURL; - - -public class AMQMessageDelegate_0_8 extends AbstractAMQMessageDelegate -{ - private static final float DESTINATION_CACHE_LOAD_FACTOR = 0.75f; - private static final int DESTINATION_CACHE_SIZE = 500; - private static final int DESTINATION_CACHE_CAPACITY = (int) (DESTINATION_CACHE_SIZE / DESTINATION_CACHE_LOAD_FACTOR); - - private static final Map<String, Destination> _destinationCache = - Collections.synchronizedMap(new LinkedHashMap<String,Destination>(DESTINATION_CACHE_CAPACITY, - DESTINATION_CACHE_LOAD_FACTOR, - true) - { - @Override - protected boolean removeEldestEntry(Map.Entry<String, Destination> eldest) - { - return size() >= DESTINATION_CACHE_SIZE; - } - }); - - public static final String JMS_TYPE = "x-jms-type"; - public static final boolean STRICT_JMS = Boolean.getBoolean("strict-jms"); - - - private boolean _readableProperties = false; - - private Destination _destination; - private JMSHeaderAdapter _headerAdapter; - private static final boolean STRICT_AMQP_COMPLIANCE = - Boolean.parseBoolean(System.getProperties().getProperty(AMQSession.STRICT_AMQP, AMQSession.STRICT_AMQP_DEFAULT)); - - private BasicContentHeaderProperties _contentHeaderProperties; - - // The base set of items that needs to be set. - private AMQMessageDelegate_0_8(BasicContentHeaderProperties properties, long deliveryTag) - { - super(deliveryTag); - _contentHeaderProperties = properties; - _readableProperties = (_contentHeaderProperties != null); - _headerAdapter = new JMSHeaderAdapter(_readableProperties ? _contentHeaderProperties.getHeaders() - : (new BasicContentHeaderProperties()).getHeaders() ); - } - - // Used for the creation of new messages - protected AMQMessageDelegate_0_8() - { - this(new BasicContentHeaderProperties(), -1); - _readableProperties = false; - _headerAdapter = new JMSHeaderAdapter(_contentHeaderProperties.getHeaders()); - - } - - // Used when generating a received message object - protected AMQMessageDelegate_0_8(long deliveryTag, BasicContentHeaderProperties contentHeader, AMQShortString exchange, - AMQShortString routingKey, AMQSession_0_8.DestinationCache<AMQQueue> queueDestinationCache, - AMQSession_0_8.DestinationCache<AMQTopic> topicDestinationCache, - int addressType) - { - this(contentHeader, deliveryTag); - - Integer type = contentHeader.getHeaders().getInteger(CustomJMSXProperty.JMS_QPID_DESTTYPE.getShortStringName()); - - AMQDestination dest = null; - - if(AMQDestination.getDefaultDestSyntax() == AMQDestination.DestSyntax.BURL) - { - // If we have a type set the attempt to use that. - if (type != null) - { - switch (type.intValue()) - { - case AMQDestination.QUEUE_TYPE: - dest = queueDestinationCache.getDestination(exchange, routingKey); - break; - case AMQDestination.TOPIC_TYPE: - dest = topicDestinationCache.getDestination(exchange, routingKey); - break; - default: - // Use the generateDestination method - dest = null; - } - } - - if (dest == null) - { - dest = generateDestination(exchange, routingKey); - } - } - else - { - String subject = null; - if (contentHeader.getHeaders() != null - && contentHeader.getHeaders().containsKey(QpidMessageProperties.QPID_SUBJECT)) - { - subject = contentHeader.getHeaders().getString(QpidMessageProperties.QPID_SUBJECT); - } - if(type == null) - { - type = addressType; - } - dest = (AMQDestination) convertToAddressBasedDestination(AMQShortString.toString(exchange), - AMQShortString.toString(routingKey), subject, - true, type); - } - setJMSDestination(dest); - } - - - - public String getJMSMessageID() throws JMSException - { - return getContentHeaderProperties().getMessageIdAsString(); - } - - public void setJMSMessageID(String messageId) throws JMSException - { - if (messageId != null) - { - getContentHeaderProperties().setMessageId(messageId); - } - } - - public void setJMSMessageID(UUID messageId) throws JMSException - { - if (messageId != null) - { - getContentHeaderProperties().setMessageId(asShortStringMsgId(messageId)); - } - } - - private static final byte[] HEX_DIGITS = {0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39, - 0x61,0x62,0x63,0x64,0x65,0x66}; - - private static AMQShortString asShortStringMsgId(UUID messageId) - { - long msb = messageId.getMostSignificantBits(); - long lsb = messageId.getLeastSignificantBits(); - - byte[] messageIdBytes = new byte[39]; - messageIdBytes[0] = (byte) 'I'; - messageIdBytes[1] = (byte) 'D'; - messageIdBytes[2] = (byte) ':'; - - messageIdBytes[3] = HEX_DIGITS[(int)((msb >> 60) & 0xFl)]; - messageIdBytes[4] = HEX_DIGITS[(int)((msb >> 56) & 0xFl)]; - messageIdBytes[5] = HEX_DIGITS[(int)((msb >> 52) & 0xFl)]; - messageIdBytes[6] = HEX_DIGITS[(int)((msb >> 48) & 0xFl)]; - messageIdBytes[7] = HEX_DIGITS[(int)((msb >> 44) & 0xFl)]; - messageIdBytes[8] = HEX_DIGITS[(int)((msb >> 40) & 0xFl)]; - messageIdBytes[9] = HEX_DIGITS[(int)((msb >> 36) & 0xFl)]; - messageIdBytes[10] = HEX_DIGITS[(int)((msb >> 32) & 0xFl)]; - - messageIdBytes[11] = (byte) '-'; - messageIdBytes[12] = HEX_DIGITS[(int)((msb >> 28) & 0xFl)]; - messageIdBytes[13] = HEX_DIGITS[(int)((msb >> 24) & 0xFl)]; - messageIdBytes[14] = HEX_DIGITS[(int)((msb >> 20) & 0xFl)]; - messageIdBytes[15] = HEX_DIGITS[(int)((msb >> 16) & 0xFl)]; - messageIdBytes[16] = (byte) '-'; - messageIdBytes[17] = HEX_DIGITS[(int)((msb >> 12) & 0xFl)]; - messageIdBytes[18] = HEX_DIGITS[(int)((msb >> 8) & 0xFl)]; - messageIdBytes[19] = HEX_DIGITS[(int)((msb >> 4) & 0xFl)]; - messageIdBytes[20] = HEX_DIGITS[(int)(msb & 0xFl)]; - messageIdBytes[21] = (byte) '-'; - - messageIdBytes[22] = HEX_DIGITS[(int)((lsb >> 60) & 0xFl)]; - messageIdBytes[23] = HEX_DIGITS[(int)((lsb >> 56) & 0xFl)]; - messageIdBytes[24] = HEX_DIGITS[(int)((lsb >> 52) & 0xFl)]; - messageIdBytes[25] = HEX_DIGITS[(int)((lsb >> 48) & 0xFl)]; - - messageIdBytes[26] = (byte) '-'; - - messageIdBytes[27] = HEX_DIGITS[(int)((lsb >> 44) & 0xFl)]; - messageIdBytes[28] = HEX_DIGITS[(int)((lsb >> 40) & 0xFl)]; - messageIdBytes[29] = HEX_DIGITS[(int)((lsb >> 36) & 0xFl)]; - messageIdBytes[30] = HEX_DIGITS[(int)((lsb >> 32) & 0xFl)]; - messageIdBytes[31] = HEX_DIGITS[(int)((lsb >> 28) & 0xFl)]; - messageIdBytes[32] = HEX_DIGITS[(int)((lsb >> 24) & 0xFl)]; - messageIdBytes[33] = HEX_DIGITS[(int)((lsb >> 20) & 0xFl)]; - messageIdBytes[34] = HEX_DIGITS[(int)((lsb >> 16) & 0xFl)]; - messageIdBytes[35] = HEX_DIGITS[(int)((lsb >> 12) & 0xFl)]; - messageIdBytes[36] = HEX_DIGITS[(int)((lsb >> 8) & 0xFl)]; - messageIdBytes[37] = HEX_DIGITS[(int)((lsb >> 4) & 0xFl)]; - messageIdBytes[38] = HEX_DIGITS[(int)(lsb & 0xFl)]; - - return new AMQShortString(messageIdBytes,0,39); - } - - public long getJMSTimestamp() throws JMSException - { - return getContentHeaderProperties().getTimestamp(); - } - - public void setJMSTimestamp(long timestamp) throws JMSException - { - getContentHeaderProperties().setTimestamp(timestamp); - } - - public byte[] getJMSCorrelationIDAsBytes() throws JMSException - { - return getContentHeaderProperties().getCorrelationIdAsString().getBytes(); - } - - public void setJMSCorrelationIDAsBytes(byte[] bytes) throws JMSException - { - getContentHeaderProperties().setCorrelationId(new String(bytes)); - } - - public void setJMSCorrelationID(String correlationId) throws JMSException - { - getContentHeaderProperties().setCorrelationId(correlationId); - } - - public String getJMSCorrelationID() throws JMSException - { - return getContentHeaderProperties().getCorrelationIdAsString(); - } - - public Destination getJMSReplyTo() throws JMSException - { - String replyToEncoding = getContentHeaderProperties().getReplyToAsString(); - if (replyToEncoding == null) - { - return null; - } - else - { - Destination dest = _destinationCache.get(replyToEncoding); - if (dest == null) - { - try - { - BindingURL binding = new AMQBindingURL(replyToEncoding); - dest = AMQDestination.createDestination(binding); - } - catch (URISyntaxException e) - { - if(replyToEncoding.startsWith("/")) - { - dest = new DefaultRouterDestination(replyToEncoding); - } - else if(replyToEncoding.contains("/")) - { - String[] parts = replyToEncoding.split("/",2); - dest = new NonBURLReplyToDestination(parts[0], parts[1]); - - - } - else - { - if(getAMQSession().isQueueBound(AMQShortString.valueOf(replyToEncoding), null, null)) - { - dest = new NonBURLReplyToDestination(replyToEncoding, ""); - } - else - { - dest = new DefaultRouterDestination(replyToEncoding); - } - } - - } - - _destinationCache.put(replyToEncoding, dest); - } - - return dest; - } - } - - public void setJMSReplyTo(Destination destination) throws JMSException - { - if (destination == null) - { - getContentHeaderProperties().setReplyTo((String) null); - return; // We're done here - } - - if (!(destination instanceof AMQDestination)) - { - throw new IllegalArgumentException( - "ReplyTo destination may only be an AMQDestination - passed argument was type " + destination.getClass()); - } - - final AMQDestination amqd = (AMQDestination) destination; - - final AMQShortString encodedDestination = amqd.getEncodedName(); - _destinationCache.put(encodedDestination.asString(), destination); - getContentHeaderProperties().setReplyTo(encodedDestination); - } - - public Destination getJMSDestination() throws JMSException - { - return _destination; - } - - public void setJMSDestination(Destination destination) - { - _destination = destination; - } - - public void setContentType(String contentType) - { - getContentHeaderProperties().setContentType(contentType); - } - - public String getContentType() - { - return getContentHeaderProperties().getContentTypeAsString(); - } - - public void setEncoding(String encoding) - { - getContentHeaderProperties().setEncoding(encoding); - } - - public String getEncoding() - { - return getContentHeaderProperties().getEncodingAsString(); - } - - public String getReplyToString() - { - return getContentHeaderProperties().getReplyToAsString(); - } - - public int getJMSDeliveryMode() throws JMSException - { - return getContentHeaderProperties().getDeliveryMode(); - } - - public void setJMSDeliveryMode(int i) throws JMSException - { - getContentHeaderProperties().setDeliveryMode((byte) i); - } - - public BasicContentHeaderProperties getContentHeaderProperties() - { - return _contentHeaderProperties; - } - - - public String getJMSType() throws JMSException - { - return getContentHeaderProperties().getTypeAsString(); - } - - public void setJMSType(String string) throws JMSException - { - getContentHeaderProperties().setType(string); - } - - public long getJMSExpiration() throws JMSException - { - return getContentHeaderProperties().getExpiration(); - } - - public void setJMSExpiration(long l) throws JMSException - { - getContentHeaderProperties().setExpiration(l); - } - - - - public boolean propertyExists(String propertyName) throws JMSException - { - return getJmsHeaders().propertyExists(propertyName); - } - - public boolean getBooleanProperty(String propertyName) throws JMSException - { - if (STRICT_AMQP_COMPLIANCE) - { - throw new UnsupportedOperationException("JMS Properties not supported in AMQP"); - } - - return getJmsHeaders().getBoolean(propertyName); - } - - public byte getByteProperty(String propertyName) throws JMSException - { - if (STRICT_AMQP_COMPLIANCE) - { - throw new UnsupportedOperationException("JMS Properties not supported in AMQP"); - } - - return getJmsHeaders().getByte(propertyName); - } - - public short getShortProperty(String propertyName) throws JMSException - { - if (STRICT_AMQP_COMPLIANCE) - { - throw new UnsupportedOperationException("JMS Properties not supported in AMQP"); - } - - return getJmsHeaders().getShort(propertyName); - } - - public int getIntProperty(String propertyName) throws JMSException - { - if (STRICT_AMQP_COMPLIANCE) - { - throw new UnsupportedOperationException("JMS Properties not supported in AMQP"); - } - - return getJmsHeaders().getInteger(propertyName); - } - - public long getLongProperty(String propertyName) throws JMSException - { - if (STRICT_AMQP_COMPLIANCE) - { - throw new UnsupportedOperationException("JMS Properties not supported in AMQP"); - } - - return getJmsHeaders().getLong(propertyName); - } - - public float getFloatProperty(String propertyName) throws JMSException - { - if (STRICT_AMQP_COMPLIANCE) - { - throw new UnsupportedOperationException("JMS Properties not supported in AMQP"); - } - - return getJmsHeaders().getFloat(propertyName); - } - - public double getDoubleProperty(String propertyName) throws JMSException - { - if (STRICT_AMQP_COMPLIANCE) - { - throw new UnsupportedOperationException("JMS Properties not supported in AMQP"); - } - - return getJmsHeaders().getDouble(propertyName); - } - - public String getStringProperty(String propertyName) throws JMSException - { - //NOTE: if the JMSX Property is a non AMQP property then we must check _strictAMQP and throw as below. - if (propertyName.equals(CustomJMSXProperty.JMSXUserID.toString())) - { - return _contentHeaderProperties.getUserIdAsString(); - } - else - { - if (STRICT_AMQP_COMPLIANCE) - { - throw new UnsupportedOperationException("JMS Properties not supported in AMQP"); - } - - return getJmsHeaders().getString(propertyName); - } - } - - public Object getObjectProperty(String propertyName) throws JMSException - { - return getJmsHeaders().getObject(propertyName); - } - - public Enumeration getPropertyNames() throws JMSException - { - Set<String> keys = getJmsHeaders().getPropertyNames(); - return Collections.enumeration(keys); - } - - public void setBooleanProperty(String propertyName, boolean b) throws JMSException - { - if (STRICT_AMQP_COMPLIANCE) - { - throw new UnsupportedOperationException("JMS Properties not supported in AMQP"); - } - - checkWritableProperties(); - getJmsHeaders().setBoolean(propertyName, b); - } - - public void setByteProperty(String propertyName, byte b) throws JMSException - { - if (STRICT_AMQP_COMPLIANCE) - { - throw new UnsupportedOperationException("JMS Properties not supported in AMQP"); - } - - checkWritableProperties(); - getJmsHeaders().setByte(propertyName, b); - } - - public void setShortProperty(String propertyName, short i) throws JMSException - { - if (STRICT_AMQP_COMPLIANCE) - { - throw new UnsupportedOperationException("JMS Properties not supported in AMQP"); - } - - checkWritableProperties(); - getJmsHeaders().setShort(propertyName, i); - } - - public void setIntProperty(String propertyName, int i) throws JMSException - { - checkWritableProperties(); - getJmsHeaders().setInteger(propertyName, i); - } - - public void setLongProperty(String propertyName, long l) throws JMSException - { - if (STRICT_AMQP_COMPLIANCE) - { - throw new UnsupportedOperationException("JMS Properties not supported in AMQP"); - } - - checkWritableProperties(); - getJmsHeaders().setLong(propertyName, l); - } - - public void setFloatProperty(String propertyName, float f) throws JMSException - { - if (STRICT_AMQP_COMPLIANCE) - { - throw new UnsupportedOperationException("JMS Properties not supported in AMQP"); - } - - checkWritableProperties(); - getJmsHeaders().setFloat(propertyName, f); - } - - public void setDoubleProperty(String propertyName, double v) throws JMSException - { - if (STRICT_AMQP_COMPLIANCE) - { - throw new UnsupportedOperationException("JMS Properties not supported in AMQP"); - } - - checkWritableProperties(); - getJmsHeaders().setDouble(propertyName, v); - } - - public void setStringProperty(String propertyName, String value) throws JMSException - { - checkWritableProperties(); - getJmsHeaders().setString(propertyName, value); - } - - public void setObjectProperty(String propertyName, Object object) throws JMSException - { - checkWritableProperties(); - getJmsHeaders().setObject(propertyName, object); - } - - public void removeProperty(String propertyName) throws JMSException - { - getJmsHeaders().remove(propertyName); - } - - - private JMSHeaderAdapter getJmsHeaders() - { - return _headerAdapter; - } - - protected void checkWritableProperties() throws MessageNotWriteableException - { - if (_readableProperties) - { - throw new MessageNotWriteableException("You need to call clearProperties() to make the message writable"); - } - } - - - public int getJMSPriority() throws JMSException - { - return getContentHeaderProperties().getPriority(); - } - - public void setJMSPriority(int i) throws JMSException - { - getContentHeaderProperties().setPriority((byte) i); - } - - public void clearProperties() throws JMSException - { - getJmsHeaders().clear(); - - _readableProperties = false; - } - - private static class DefaultRouterDestination extends AMQDestination implements Queue - { - private static final long serialVersionUID = -5042408431861384536L; - - public DefaultRouterDestination(final String replyToEncoding) - { - super(AMQShortString.EMPTY_STRING, - AMQShortString.valueOf("direct"), - AMQShortString.valueOf(replyToEncoding), - AMQShortString.valueOf(replyToEncoding)); - } - - @Override - public boolean isNameRequired() - { - return false; - } - - @Override - public boolean neverDeclare() - { - return true; - } - } - - private static class NonBURLReplyToDestination extends AMQDestination implements Queue - { - private static final long serialVersionUID = 122897705932489259L; - - public NonBURLReplyToDestination(final String exchange, final String routingKey) - { - super(AMQShortString.valueOf(exchange), - null, - AMQShortString.valueOf(routingKey), - AMQShortString.valueOf(routingKey)); - } - - @Override - public boolean isNameRequired() - { - return false; - } - - @Override - public boolean neverDeclare() - { - return true; - } - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/AMQPEncodedListMessage.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/AMQPEncodedListMessage.java deleted file mode 100644 index 1d2cb43322..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/AMQPEncodedListMessage.java +++ /dev/null @@ -1,935 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; - -import org.apache.qpid.transport.codec.BBDecoder; -import org.apache.qpid.transport.codec.BBEncoder; - -import javax.jms.JMSException; -import javax.jms.MessageFormatException; -import javax.jms.MessageEOFException; -import java.lang.NumberFormatException; -import java.nio.ByteBuffer; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -public class AMQPEncodedListMessage extends JMSStreamMessage implements - org.apache.qpid.jms.ListMessage, javax.jms.MapMessage -{ - private static final Logger _logger = LoggerFactory - .getLogger(AMQPEncodedListMessage.class); - - public static final String MIME_TYPE = "amqp/list"; - - private List<Object> _list = new ArrayList<Object>(); - - public AMQPEncodedListMessage(AMQMessageDelegateFactory delegateFactory) throws JMSException - { - super(delegateFactory); - currentIndex = 0; - } - - AMQPEncodedListMessage(AMQMessageDelegate delegate, ByteBuffer data) - throws AMQException - { - super(delegate, data); - if (data != null) - { - try - { - populateListFromData(data); - } - catch (JMSException je) - { - throw new AMQException(null, - "Error populating ListMessage from ByteBuffer", je); - } - } - currentIndex = 0; - } - - public String toBodyString() throws JMSException - { - return _list == null ? "" : _list.toString(); - } - - protected String getMimeType() - { - return MIME_TYPE; - } - - /* ListMessage Implementation. */ - public boolean add(Object a) throws JMSException - { - checkWritable(); - checkAllowedValue(a); - try - { - return _list.add(a); - } - catch (Exception e) - { - MessageFormatException ex = new MessageFormatException("Error adding to ListMessage"); - ex.initCause(e); - ex.setLinkedException(e); - throw ex; - - } - } - - public void add(int index, Object element) throws JMSException - { - checkWritable(); - checkAllowedValue(element); - try - { - _list.add(index, element); - } - catch (Exception e) - { - MessageFormatException ex = new MessageFormatException("Error adding to ListMessage at " - + index); - ex.initCause(e); - ex.setLinkedException(e); - throw ex; - } - } - - public boolean contains(Object o) throws JMSException - { - try - { - return _list.contains(o); - } - catch (Exception e) - { - JMSException ex = new JMSException("Error when looking up object"); - ex.initCause(e); - ex.setLinkedException(e); - throw ex; - } - } - - public Object get(int index) throws JMSException - { - try - { - return _list.get(index); - } - catch (IndexOutOfBoundsException e) - { - MessageFormatException ex = new MessageFormatException( - "Error getting ListMessage element at " + index); - ex.initCause(e); - ex.setLinkedException(e); - throw ex; - } - } - - public int indexOf(Object o) - { - return _list.indexOf(o); - } - - public Iterator iterator() - { - return _list.iterator(); - } - - public Object remove(int index) throws JMSException - { - checkWritable(); - try - { - return _list.remove(index); - } - catch (IndexOutOfBoundsException e) - { - MessageFormatException ex = new MessageFormatException( - "Error removing ListMessage element at " + index); - ex.initCause(e); - ex.setLinkedException(e); - throw ex; - } - } - - public boolean remove(Object o) throws JMSException - { - checkWritable(); - return _list.remove(o); - } - - public Object set(int index, Object element) throws JMSException - { - checkWritable(); - checkAllowedValue(element); - try - { - return _list.set(index, element); - } - catch (Exception e) - { - MessageFormatException ex = new MessageFormatException( - "Error setting ListMessage element at " + index); - ex.initCause(e); - ex.setLinkedException(e); - throw ex; - } - } - - public int size() - { - return _list.size(); - } - - public Object[] toArray() - { - return _list.toArray(); - } - - /* MapMessage Implementation */ - private boolean isValidIndex(int index) - { - if (index >= 0 && index < size()) - return true; - - return false; - } - - private int getValidIndex(String indexStr) throws JMSException - { - if ((indexStr == null) || indexStr.equals("")) - { - throw new IllegalArgumentException( - "Property name cannot be null, or the empty String."); - } - - int index = 0; - try - { - index = Integer.parseInt(indexStr); - } - catch (NumberFormatException e) - { - JMSException ex = new JMSException("Invalid index string"); - ex.initCause(e); - ex.setLinkedException(e); - throw ex; - } - if (isValidIndex(index)) - return index; - - throw new MessageFormatException("Property " + indexStr - + " should be a valid index into the list of size " + size()); - } - - private void setGenericForMap(String propName, Object o) - throws JMSException - { - checkWritable(); - int index = 0; - try - { - index = Integer.parseInt(propName); - } - catch (NumberFormatException e) - { - JMSException ex = new JMSException("The property name should be a valid index"); - ex.initCause(e); - ex.setLinkedException(e); - throw ex; - } - - if (isValidIndex(index)) - remove(index); - add(index, o); - } - - public boolean getBoolean(String propName) throws JMSException - { - return getBooleanImpl(getValidIndex(propName)); - } - - public byte getByte(String propName) throws JMSException - { - return getByteImpl(getValidIndex(propName)); - } - - public short getShort(String propName) throws JMSException - { - return getShortImpl(getValidIndex(propName)); - } - - public int getInt(String propName) throws JMSException - { - return getIntImpl(getValidIndex(propName)); - } - - public long getLong(String propName) throws JMSException - { - return getLongImpl(getValidIndex(propName)); - } - - public char getChar(String propName) throws JMSException - { - return getCharImpl(getValidIndex(propName)); - - } - - public float getFloat(String propName) throws JMSException - { - return getFloatImpl(getValidIndex(propName)); - } - - public double getDouble(String propName) throws JMSException - { - return getDoubleImpl(getValidIndex(propName)); - } - - public String getString(String propName) throws JMSException - { - return getStringImpl(getValidIndex(propName)); - } - - public byte[] getBytes(String propName) throws JMSException - { - return getBytesImpl(getValidIndex(propName)); - } - - public Object getObject(String propName) throws JMSException - { - return get(getValidIndex(propName)); - } - - public Enumeration getMapNames() throws JMSException - { - List<String> names = new ArrayList<String>(); - int i = 0; - - while (i < size()) - names.add(Integer.toString(i++)); - - return Collections.enumeration(names); - } - - public void setBoolean(String propName, boolean b) throws JMSException - { - setGenericForMap(propName, b); - } - - public void setByte(String propName, byte b) throws JMSException - { - setGenericForMap(propName, b); - } - - public void setShort(String propName, short i) throws JMSException - { - setGenericForMap(propName, i); - } - - public void setChar(String propName, char c) throws JMSException - { - setGenericForMap(propName, c); - } - - public void setInt(String propName, int i) throws JMSException - { - setGenericForMap(propName, i); - } - - public void setLong(String propName, long l) throws JMSException - { - setGenericForMap(propName, l); - } - - public void setFloat(String propName, float v) throws JMSException - { - setGenericForMap(propName, v); - } - - public void setDouble(String propName, double v) throws JMSException - { - setGenericForMap(propName, v); - } - - public void setString(String propName, String string1) throws JMSException - { - setGenericForMap(propName, string1); - } - - public void setBytes(String propName, byte[] bytes) throws JMSException - { - setGenericForMap(propName, bytes); - } - - public void setBytes(String propName, byte[] bytes, int offset, int length) - throws JMSException - { - if ((offset == 0) && (length == bytes.length)) - { - setBytes(propName, bytes); - } - else - { - byte[] newBytes = new byte[length]; - System.arraycopy(bytes, offset, newBytes, 0, length); - setBytes(propName, newBytes); - } - } - - public void setObject(String propName, Object value) throws JMSException - { - checkAllowedValue(value); - setGenericForMap(propName, value); - } - - public boolean itemExists(String propName) throws JMSException - { - return isValidIndex(Integer.parseInt(propName)); - } - - // StreamMessage methods - - private int currentIndex; - - private static final String MESSAGE_EOF_EXCEPTION = "End of Stream (ListMessage) at index: "; - - private void setGenericForStream(Object o) throws JMSException - { - checkWritable(); - add(o); - currentIndex++; - } - - @Override - public boolean readBoolean() throws JMSException - { - checkReadable(); - if (isValidIndex(currentIndex)) - return getBooleanImpl(currentIndex++); - - throw new MessageEOFException(MESSAGE_EOF_EXCEPTION + currentIndex); - } - - @Override - public byte readByte() throws JMSException - { - checkReadable(); - if (isValidIndex(currentIndex)) - return getByteImpl(currentIndex++); - - throw new MessageEOFException(MESSAGE_EOF_EXCEPTION + currentIndex); - } - - @Override - public int readBytes(byte[] value) throws JMSException - { - checkReadable(); - if (isValidIndex(currentIndex)) - { - ByteBuffer res = ByteBuffer.wrap(getBytesImpl(currentIndex++)); - res.get(value); - return value.length; - } - - throw new MessageEOFException(MESSAGE_EOF_EXCEPTION + currentIndex); - } - - @Override - public char readChar() throws JMSException - { - checkReadable(); - if (isValidIndex(currentIndex)) - return getCharImpl(currentIndex++); - - throw new MessageEOFException(MESSAGE_EOF_EXCEPTION + currentIndex); - } - - @Override - public double readDouble() throws JMSException - { - checkReadable(); - if (isValidIndex(currentIndex)) - return getDoubleImpl(currentIndex++); - - throw new MessageEOFException(MESSAGE_EOF_EXCEPTION + currentIndex); - } - - @Override - public float readFloat() throws JMSException - { - checkReadable(); - if (isValidIndex(currentIndex)) - return getFloatImpl(currentIndex++); - - throw new MessageEOFException(MESSAGE_EOF_EXCEPTION + currentIndex); - } - - @Override - public int readInt() throws JMSException - { - checkReadable(); - if (isValidIndex(currentIndex)) - return getIntImpl(currentIndex++); - - throw new MessageEOFException(MESSAGE_EOF_EXCEPTION + currentIndex); - } - - @Override - public long readLong() throws JMSException - { - checkReadable(); - if (isValidIndex(currentIndex)) - return getLongImpl(currentIndex++); - - throw new MessageEOFException(MESSAGE_EOF_EXCEPTION + currentIndex); - } - - @Override - public Object readObject() throws JMSException - { - checkReadable(); - if (isValidIndex(currentIndex)) - return get(currentIndex++); - - throw new MessageEOFException(MESSAGE_EOF_EXCEPTION + currentIndex); - } - - @Override - public short readShort() throws JMSException - { - checkReadable(); - if (isValidIndex(currentIndex)) - return getShortImpl(currentIndex++); - - throw new MessageEOFException(MESSAGE_EOF_EXCEPTION + currentIndex); - } - - @Override - public String readString() throws JMSException - { - checkReadable(); - if (isValidIndex(currentIndex)) - return getStringImpl(currentIndex++); - - throw new MessageEOFException(MESSAGE_EOF_EXCEPTION + currentIndex); - } - - @Override - public void writeBoolean(boolean value) throws JMSException - { - setGenericForStream(value); - } - - @Override - public void writeByte(byte value) throws JMSException - { - setGenericForStream(value); - } - - @Override - public void writeBytes(byte[] value) throws JMSException - { - setGenericForStream(value); - } - - @Override - public void writeBytes(byte[] value, int offset, int length) - throws JMSException - { - setGenericForStream(value); - } - - @Override - public void writeChar(char value) throws JMSException - { - setGenericForStream(value); - } - - @Override - public void writeDouble(double value) throws JMSException - { - setGenericForStream(value); - } - - @Override - public void writeFloat(float value) throws JMSException - { - setGenericForStream(value); - } - - @Override - public void writeInt(int value) throws JMSException - { - setGenericForStream(value); - } - - @Override - public void writeLong(long value) throws JMSException - { - setGenericForStream(value); - } - - @Override - public void writeObject(Object value) throws JMSException - { - checkAllowedValue(value); - setGenericForStream(value); - } - - @Override - public void writeShort(short value) throws JMSException - { - setGenericForStream(value); - } - - @Override - public void writeString(String value) throws JMSException - { - setGenericForStream(value); - } - - // Common methods - - private void checkAllowedValue(Object value) throws MessageFormatException - { - if (((value instanceof Boolean) || (value instanceof Byte) - || (value instanceof Short) || (value instanceof Integer) - || (value instanceof Long) || (value instanceof Character) - || (value instanceof Float) || (value instanceof Double) - || (value instanceof String) || (value instanceof byte[]) - || (value instanceof List) || (value instanceof Map) - || (value instanceof UUID) || (value == null)) == false) - { - throw new MessageFormatException("Invalid value " + value - + "of type " + value.getClass().getName() + "."); - } - } - - @Override - public void reset() - { - currentIndex = 0; - setReadable(true); - } - - @Override - public void clearBody() throws JMSException - { - super.clearBody(); - _list.clear(); - currentIndex = 0; - setReadable(false); - } - - private boolean getBooleanImpl(int index) throws JMSException - { - Object value = get(index); - - if (value instanceof Boolean) - { - return ((Boolean) value).booleanValue(); - } - else if ((value instanceof String) || (value == null)) - { - try - { - return Boolean.valueOf((String) value); - } - catch (NumberFormatException e) - { - // FALLTHROUGH to exception - } - } - - throw new MessageFormatException("Property at " + index + " of type " - + value.getClass().getName() - + " cannot be converted to boolean."); - } - - private byte getByteImpl(int index) throws JMSException - { - Object value = get(index); - - if (value instanceof Byte) - { - return ((Byte) value).byteValue(); - } - else if ((value instanceof String) || (value == null)) - { - try - { - return Byte.valueOf((String) value).byteValue(); - } catch (NumberFormatException e) - { - // FALLTHROUGH to exception - } - } - - throw new MessageFormatException("Property at " + index + " of type " - + value.getClass().getName() + " cannot be converted to byte."); - } - - private short getShortImpl(int index) throws JMSException - { - Object value = get(index); - - if (value instanceof Short) - { - return ((Short) value).shortValue(); - } - else if (value instanceof Byte) - { - return ((Byte) value).shortValue(); - } - else if ((value instanceof String) || (value == null)) - { - try - { - return Short.valueOf((String) value).shortValue(); - } catch (NumberFormatException e) - { - // FALLTHROUGH to exception - } - } - - throw new MessageFormatException("Property at " + index + " of type " - + value.getClass().getName() + " cannot be converted to short."); - } - - private int getIntImpl(int index) throws JMSException - { - Object value = get(index); - - if (value instanceof Integer) - { - return ((Integer) value).intValue(); - } - - if (value instanceof Short) - { - return ((Short) value).intValue(); - } - - if (value instanceof Byte) - { - return ((Byte) value).intValue(); - } - - if ((value instanceof String) || (value == null)) - { - try - { - return Integer.valueOf((String) value).intValue(); - } - catch (NumberFormatException e) - { - // FALLTHROUGH to exception - } - } - - throw new MessageFormatException("Property at " + index + " of type " - + value.getClass().getName() + " cannot be converted to int."); - } - - private long getLongImpl(int index) throws JMSException - { - Object value = get(index); - - if (value instanceof Long) - { - return ((Long) value).longValue(); - } else if (value instanceof Integer) - { - return ((Integer) value).longValue(); - } - - if (value instanceof Short) - { - return ((Short) value).longValue(); - } - - if (value instanceof Byte) - { - return ((Byte) value).longValue(); - } else if ((value instanceof String) || (value == null)) - { - try - { - return Long.valueOf((String) value).longValue(); - } catch (NumberFormatException e) - { - // FALLTHROUGH to exception - } - } - - throw new MessageFormatException("Property at " + index + " of type " - + value.getClass().getName() + " cannot be converted to long."); - } - - private char getCharImpl(int index) throws JMSException - { - Object value = get(index); - - if (value instanceof Character) - { - return ((Character) value).charValue(); - } else if (value == null) - { - throw new NullPointerException("Property at " + index - + " has null value and therefore cannot " - + "be converted to char."); - } else - { - throw new MessageFormatException("Property at " + index - + " of type " + value.getClass().getName() - + " cannot be converted to a char."); - } - } - - private float getFloatImpl(int index) throws JMSException - { - Object value = get(index); - - if (value instanceof Float) - { - return ((Float) value).floatValue(); - } - else if ((value instanceof String) || (value == null)) - { - try - { - return Float.valueOf((String) value).floatValue(); - } - catch (NumberFormatException e) - { - // FALLTHROUGH to exception - } - } - - throw new MessageFormatException("Property at " + index + " of type " - + value.getClass().getName() + " cannot be converted to float."); - } - - private double getDoubleImpl(int index) throws JMSException - { - Object value = get(index); - - if (value instanceof Double) - { - return ((Double) value).doubleValue(); - } - else if (value instanceof Float) - { - return ((Float) value).doubleValue(); - } - else if ((value instanceof String) || (value == null)) - { - try - { - return Double.valueOf((String) value).doubleValue(); - } - catch (NumberFormatException e) - { - // FALLTHROUGH to exception - } - } - - throw new MessageFormatException("Property at " + index + " of type " - + value.getClass().getName() - + " cannot be converted to double."); - } - - private String getStringImpl(int index) throws JMSException - { - Object value = get(index); - - if ((value instanceof String) || (value == null)) - { - return (String) value; - } else if (value instanceof byte[]) - { - throw new MessageFormatException("Property at " + index - + " of type byte[] " + "cannot be converted to String."); - } else - { - return value.toString(); - } - } - - private byte[] getBytesImpl(int index) throws JMSException - { - Object value = get(index); - - if ((value instanceof byte[]) || (value == null)) - { - return (byte[]) value; - } - else - { - throw new MessageFormatException("Property at " + index - + " of type " + value.getClass().getName() - + " cannot be converted to byte[]."); - } - } - - protected void populateListFromData(ByteBuffer data) throws JMSException - { - if (data != null) - { - data.rewind(); - BBDecoder decoder = new BBDecoder(); - decoder.init(data); - _list = decoder.readList(); - } - else - { - _list.clear(); - } - } - - public ByteBuffer getData() throws JMSException - { - BBEncoder encoder = new BBEncoder(1024); - encoder.writeList(_list); - return encoder.segment(); - } - - public void setList(List<Object> l) - { - _list = l; - } - - public List<Object> asList() - { - return _list; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/AMQPEncodedListMessageFactory.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/AMQPEncodedListMessageFactory.java deleted file mode 100644 index b503dccb91..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/AMQPEncodedListMessageFactory.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.apache.qpid.client.message; -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - - -import org.apache.qpid.AMQException; - -import javax.jms.JMSException; -import java.nio.ByteBuffer; - -public class AMQPEncodedListMessageFactory extends AbstractJMSMessageFactory -{ - @Override - protected AbstractJMSMessage createMessage(AMQMessageDelegate delegate, - ByteBuffer data) throws AMQException - { - return new AMQPEncodedListMessage(delegate,data); - } - - - public AbstractJMSMessage createMessage( - AMQMessageDelegateFactory delegateFactory) throws JMSException - { - return new AMQPEncodedListMessage(delegateFactory); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/AMQPEncodedMapMessage.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/AMQPEncodedMapMessage.java deleted file mode 100644 index 69ecd7bfba..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/AMQPEncodedMapMessage.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.client.message; - - -import org.apache.qpid.AMQException; -import org.apache.qpid.transport.codec.BBDecoder; -import org.apache.qpid.transport.codec.BBEncoder; - -import javax.jms.JMSException; -import javax.jms.MessageFormatException; -import java.nio.ByteBuffer; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -public class AMQPEncodedMapMessage extends JMSMapMessage -{ - public static final String MIME_TYPE = "amqp/map"; - - public AMQPEncodedMapMessage(AMQMessageDelegateFactory delegateFactory) throws JMSException - { - this(delegateFactory, null); - } - - AMQPEncodedMapMessage(AMQMessageDelegateFactory delegateFactory, ByteBuffer data) throws JMSException - { - super(delegateFactory, data); - } - - AMQPEncodedMapMessage(AMQMessageDelegate delegate, ByteBuffer data) throws AMQException - { - super(delegate, data); - } - - @ Override - protected String getMimeType() - { - return MIME_TYPE; - } - - @ Override - public void setObject(String propName, Object value) throws JMSException - { - checkWritable(); - checkPropertyName(propName); - if ((value instanceof Boolean) || (value instanceof Byte) || (value instanceof Short) || (value instanceof Integer) - || (value instanceof Long) || (value instanceof Character) || (value instanceof Float) - || (value instanceof Double) || (value instanceof String) || (value instanceof byte[]) - || (value instanceof List) || (value instanceof Map) || (value instanceof UUID) || (value == null)) - { - getMap().put(propName, value); - } - else - { - throw new MessageFormatException("Cannot set property " + propName + " to value " + value + "of type " - + value.getClass().getName() + "."); - } - } - - // The super clas methods resets the buffer - @ Override - public ByteBuffer getData() - { - BBEncoder encoder = new BBEncoder(1024); - encoder.writeMap(getMap()); - return encoder.segment(); - } - - @ Override - protected void populateMapFromData(ByteBuffer data) throws JMSException - { - if (data != null) - { - data.rewind(); - BBDecoder decoder = new BBDecoder(); - decoder.init(data); - setMap(decoder.readMap()); - } - else - { - getMap().clear(); - } - } - - // for testing - public Map<String,Object> getMap() - { - return super.getMap(); - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/AMQPEncodedMapMessageFactory.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/AMQPEncodedMapMessageFactory.java deleted file mode 100644 index 183ec4cb40..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/AMQPEncodedMapMessageFactory.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.client.message; - - -import org.apache.qpid.AMQException; - -import javax.jms.JMSException; -import java.nio.ByteBuffer; - -public class AMQPEncodedMapMessageFactory extends AbstractJMSMessageFactory -{ - - @Override - protected AbstractJMSMessage createMessage(AMQMessageDelegate delegate, - ByteBuffer data) throws AMQException - { - return new AMQPEncodedMapMessage(delegate,data); - } - - - public AbstractJMSMessage createMessage( - AMQMessageDelegateFactory delegateFactory) throws JMSException - { - return new AMQPEncodedMapMessage(delegateFactory); - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/AbstractAMQMessageDelegate.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/AbstractAMQMessageDelegate.java deleted file mode 100644 index d1ca6adb60..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/AbstractAMQMessageDelegate.java +++ /dev/null @@ -1,347 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.client.message; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Session; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.client.AMQAnyDestination; -import org.apache.qpid.client.AMQDestination; -import org.apache.qpid.client.AMQQueue; -import org.apache.qpid.client.AMQSession; -import org.apache.qpid.client.AMQTopic; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.AMQShortString; - -/** - * This abstract class provides exchange lookup functionality that is shared - * between all MessageDelegates. Update facilities are provided so that the 0-10 - * code base can update the mappings. The 0-8 code base does not have the - * facility to update the exchange map so it can only use the default mappings. - * - * That said any updates that a 0-10 client performs will also benefit any 0-8 - * connections in this VM. - * - */ -public abstract class AbstractAMQMessageDelegate implements AMQMessageDelegate -{ - private static final Logger _logger = LoggerFactory.getLogger(AMQMessageDelegate.class); - - private static Map<String, Integer> _exchangeTypeToDestinationType = new ConcurrentHashMap<String, Integer>(); - private static Map<String,ExchangeInfo> _exchangeMap = new ConcurrentHashMap<String, ExchangeInfo>(); - - /** - * Add default Mappings for the Direct, Default, Topic and Fanout exchanges. - */ - static - { - _exchangeTypeToDestinationType.put("", AMQDestination.QUEUE_TYPE); - _exchangeTypeToDestinationType.put(ExchangeDefaults.DIRECT_EXCHANGE_CLASS, AMQDestination.QUEUE_TYPE); - _exchangeTypeToDestinationType.put(ExchangeDefaults.TOPIC_EXCHANGE_CLASS, AMQDestination.TOPIC_TYPE); - _exchangeTypeToDestinationType.put(ExchangeDefaults.FANOUT_EXCHANGE_CLASS, AMQDestination.TOPIC_TYPE); - _exchangeTypeToDestinationType.put(ExchangeDefaults.HEADERS_EXCHANGE_CLASS, AMQDestination.QUEUE_TYPE); - - _exchangeMap.put(ExchangeDefaults.DEFAULT_EXCHANGE_NAME, - new ExchangeInfo(ExchangeDefaults.DEFAULT_EXCHANGE_NAME, - ExchangeDefaults.DIRECT_EXCHANGE_CLASS, - AMQDestination.QUEUE_TYPE)); - - _exchangeMap.put(ExchangeDefaults.DIRECT_EXCHANGE_NAME, - new ExchangeInfo(ExchangeDefaults.DIRECT_EXCHANGE_NAME, - ExchangeDefaults.DIRECT_EXCHANGE_CLASS, - AMQDestination.QUEUE_TYPE)); - - _exchangeMap.put(ExchangeDefaults.TOPIC_EXCHANGE_NAME, - new ExchangeInfo(ExchangeDefaults.TOPIC_EXCHANGE_NAME, - ExchangeDefaults.TOPIC_EXCHANGE_CLASS, - AMQDestination.TOPIC_TYPE)); - - _exchangeMap.put(ExchangeDefaults.FANOUT_EXCHANGE_NAME, - new ExchangeInfo(ExchangeDefaults.FANOUT_EXCHANGE_NAME, - ExchangeDefaults.FANOUT_EXCHANGE_CLASS, - AMQDestination.TOPIC_TYPE)); - - _exchangeMap.put(ExchangeDefaults.HEADERS_EXCHANGE_NAME, - new ExchangeInfo(ExchangeDefaults.HEADERS_EXCHANGE_NAME, - ExchangeDefaults.HEADERS_EXCHANGE_CLASS, - AMQDestination.QUEUE_TYPE)); - } - - /** If the acknowledge mode is CLIENT_ACKNOWLEDGE the session is required */ - private AMQSession<?,?> _session; - private final long _deliveryTag; - - protected AbstractAMQMessageDelegate(long deliveryTag) - { - _deliveryTag = deliveryTag; - } - - /** - * Get the AMQ message number assigned to this message - * - * @return the message number - */ - public long getDeliveryTag() - { - return _deliveryTag; - } - - /** - * Called when a Destination is requried. - * - * This will create the AMQDestination that is the correct type and value - * based on the incomming values. - * @param exchange The exchange name - * @param routingKey The routing key to be used for the Destination - * @return AMQDestination of the correct subtype - */ - protected AMQDestination generateDestination(AMQShortString exchange, AMQShortString routingKey) - { - AMQDestination dest; - ExchangeInfo exchangeInfo = _exchangeMap.get(exchange.asString()); - - if (exchangeInfo == null) - { - exchangeInfo = new ExchangeInfo(exchange.asString(),"",AMQDestination.UNKNOWN_TYPE); - } - - if ("topic".equals(exchangeInfo.getExchangeType())) - { - dest = new AMQTopic(exchange, routingKey, null); - } - else if ("direct".equals(exchangeInfo.getExchangeType())) - { - dest = new AMQQueue(exchange, routingKey, routingKey); - } - else - { - dest = new AMQAnyDestination(exchange, - new AMQShortString(exchangeInfo.getExchangeType()), - routingKey, - false, - false, - routingKey, - false, - new AMQShortString[] {routingKey}); - } - - return dest; - } - - /** - * Update the exchange name to type mapping. - * - * If the newType is not known then an UNKNOWN_TYPE is created. Only if the - * exchange is of a known type: amq.direct, amq.topic, amq.fanout can we - * create a suitable AMQDestination representation - * - * @param exchange the name of the exchange - * @param newtype the AMQP exchange class name i.e. direct - */ - protected static void updateExchangeType(String exchange, String newtype) - { - Integer type = _exchangeTypeToDestinationType.get(newtype); - if (type == null) - { - type = AMQDestination.UNKNOWN_TYPE; - } - - _exchangeMap.put(exchange, new ExchangeInfo(exchange,newtype,type)); - } - - /** - * Accessor method to allow lookups of the given exchange name. - * - * This check allows the prevention of extra work required such as asking - * the broker for the exchange class name. - * - * @param exchange the exchange name to lookup - * @return true if there is a mapping for this exchange - */ - protected static boolean exchangeMapContains(String exchange) - { - return _exchangeMap.containsKey(exchange); - } - - public void acknowledgeThis() throws JMSException - { - // the JMS 1.1 spec says in section 3.6 that calls to acknowledge are ignored when client acknowledge - // is not specified. In our case, we only set the session field where client acknowledge mode is specified. - if (_session != null && _session.getAcknowledgeMode() == Session.CLIENT_ACKNOWLEDGE) - { - if (_session.getAMQConnection().isClosed()) - { - throw new javax.jms.IllegalStateException("Connection is already closed"); - } - - // we set multiple to true here since acknowledgement implies acknowledge of all previous messages - // received on the session - _session.acknowledgeMessage(getDeliveryTag(), true); - } - } - - public void acknowledge() throws JMSException - { - if (_session != null && _session.getAcknowledgeMode() == Session.CLIENT_ACKNOWLEDGE) - { - _session.acknowledge(); - } - } - - /** - * The session is set when CLIENT_ACKNOWLEDGE mode is used so that the CHANNEL ACK can be sent when the user calls - * acknowledge() - * - * @param s the AMQ session that delivered this message - */ - public void setAMQSession(AMQSession<?,?> s) - { - _session = s; - } - - public AMQSession<?,?> getAMQSession() - { - return _session; - } - - protected Destination convertToAddressBasedDestination(String exchange, - String routingKey, - String subject, - boolean useNodeTypeForDestinationType, - int type) - { - String addr; - boolean isQueue = true; - if ("".equals(exchange)) // type Queue - { - subject = (subject == null) ? "" : "/" + subject; - addr = routingKey + subject; - - } - else - { - addr = exchange + "/" + routingKey; - isQueue = false; - } - - if(useNodeTypeForDestinationType) - { - if(type == AMQDestination.UNKNOWN_TYPE && "".equals(exchange)) - { - type = AMQDestination.QUEUE_TYPE; - } - - switch(type) - { - case AMQDestination.QUEUE_TYPE: - addr = addr + " ; { node: { type: queue } } "; - break; - case AMQDestination.TOPIC_TYPE: - addr = addr + " ; { node: { type: topic } } "; - break; - default: - // do nothing - } - } - - - try - { - AMQDestination dest = (AMQDestination)AMQDestination.createDestination("ADDR:" + addr, - useNodeTypeForDestinationType); - if (isQueue) - { - dest.setQueueName(new AMQShortString(routingKey)); - dest.setRoutingKey(new AMQShortString(routingKey)); - dest.setExchangeName(new AMQShortString("")); - } - else - { - dest.setRoutingKey(new AMQShortString(routingKey)); - dest.setExchangeName(new AMQShortString(exchange)); - } - return dest; - } - catch(Exception e) - { - // An exception is only thrown here if the address syntax is invalid. - // Logging the exception, but not throwing as this is only important to Qpid developers. - // An exception here means a bug in the code. - _logger.error("Exception when constructing an address string from the ReplyTo struct"); - - // falling back to the old way of doing it to ensure the application continues. - return generateDestination(new AMQShortString(exchange), new AMQShortString(routingKey)); - } - } -} - -class ExchangeInfo -{ - private String exchangeName; - private String exchangeType; - private int destType = AMQDestination.QUEUE_TYPE; - - public ExchangeInfo(String exchangeName, String exchangeType, - int destType) - { - super(); - this.exchangeName = exchangeName; - this.exchangeType = exchangeType; - this.destType = destType; - } - - public String getExchangeName() - { - return exchangeName; - } - - public void setExchangeName(String exchangeName) - { - this.exchangeName = exchangeName; - } - - public String getExchangeType() - { - return exchangeType; - } - - public void setExchangeType(String exchangeType) - { - this.exchangeType = exchangeType; - } - - public int getDestType() - { - return destType; - } - - public void setDestType(int destType) - { - this.destType = destType; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/AbstractBytesTypedMessage.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/AbstractBytesTypedMessage.java deleted file mode 100644 index 9c7bd0bdcf..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/AbstractBytesTypedMessage.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.client.message; - -import org.apache.qpid.AMQException; -import org.apache.qpid.transport.util.Functions; - -import javax.jms.JMSException; -import javax.jms.MessageNotReadableException; -import javax.jms.MessageNotWriteableException; -import java.nio.ByteBuffer; - -/** - * @author Apache Software Foundation - */ -public abstract class AbstractBytesTypedMessage extends AbstractJMSMessage -{ - private boolean _readableMessage = false; - - AbstractBytesTypedMessage(AMQMessageDelegateFactory delegateFactory, boolean fromReceivedMessage) - { - - super(delegateFactory, fromReceivedMessage); // this instanties a content header - _readableMessage = fromReceivedMessage; - } - - AbstractBytesTypedMessage(AMQMessageDelegate delegate, boolean fromReceivedMessage) throws AMQException - { - - super(delegate, fromReceivedMessage); - _readableMessage = fromReceivedMessage; - - } - - protected void checkReadable() throws MessageNotReadableException - { - if (!_readableMessage) - { - throw new MessageNotReadableException("You need to call reset() to make the message readable"); - } - } - - @Override - protected void checkWritable() throws MessageNotWriteableException - { - super.checkWritable(); - if(_readableMessage) - { - throw new MessageNotWriteableException("You need to call clearBody() to make the message writable"); - } - } - - public void clearBody() throws JMSException - { - super.clearBody(); - _readableMessage = false; - } - - protected void setReadable(boolean readable) - { - _readableMessage = readable; - } - - - public String toBodyString() throws JMSException - { - try - { - ByteBuffer data = getData(); - if (data != null) - { - return Functions.str(data, 100, 0); - } - else - { - return ""; - } - - } - catch (Exception e) - { - JMSException jmse = new JMSException(e.toString()); - jmse.setLinkedException(e); - jmse.initCause(e); - throw jmse; - } - - } - - - abstract public void reset(); - - - - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/AbstractJMSMessage.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/AbstractJMSMessage.java deleted file mode 100644 index 9e15b08f12..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/AbstractJMSMessage.java +++ /dev/null @@ -1,463 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.apache.qpid.AMQException; -import org.apache.qpid.client.AMQSession; - -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.MessageNotWriteableException; -import java.nio.ByteBuffer; -import java.util.Enumeration; -import java.util.UUID; - -public abstract class AbstractJMSMessage implements org.apache.qpid.jms.Message -{ - - - /** If the acknowledge mode is CLIENT_ACKNOWLEDGE the session is required */ - - private AMQMessageDelegate _delegate; - private boolean _redelivered; - private boolean _receivedFromServer; - - protected AbstractJMSMessage(AMQMessageDelegateFactory delegateFactory, boolean fromReceivedData) - { - _delegate = delegateFactory.createDelegate(); - setContentType(getMimeType()); - } - - protected AbstractJMSMessage(AMQMessageDelegate delegate, boolean fromReceivedData) throws AMQException - { - - _delegate = delegate; - setContentType(getMimeType()); - } - - public String getJMSMessageID() throws JMSException - { - return _delegate.getJMSMessageID(); - } - - public void setJMSMessageID(String messageId) throws JMSException - { - _delegate.setJMSMessageID(messageId); - } - - public void setJMSMessageID(UUID messageId) throws JMSException - { - _delegate.setJMSMessageID(messageId); - } - - - public long getJMSTimestamp() throws JMSException - { - return _delegate.getJMSTimestamp(); - } - - public void setJMSTimestamp(long timestamp) throws JMSException - { - _delegate.setJMSTimestamp(timestamp); - } - - public byte[] getJMSCorrelationIDAsBytes() throws JMSException - { - return _delegate.getJMSCorrelationIDAsBytes(); - } - - public void setJMSCorrelationIDAsBytes(byte[] bytes) throws JMSException - { - _delegate.setJMSCorrelationIDAsBytes(bytes); - } - - public void setJMSCorrelationID(String correlationId) throws JMSException - { - _delegate.setJMSCorrelationID(correlationId); - } - - public String getJMSCorrelationID() throws JMSException - { - return _delegate.getJMSCorrelationID(); - } - - public Destination getJMSReplyTo() throws JMSException - { - return _delegate.getJMSReplyTo(); - } - - public void setJMSReplyTo(Destination destination) throws JMSException - { - _delegate.setJMSReplyTo(destination); - } - - public Destination getJMSDestination() throws JMSException - { - return _delegate.getJMSDestination(); - } - - public void setJMSDestination(Destination destination) - { - _delegate.setJMSDestination(destination); - } - - public int getJMSDeliveryMode() throws JMSException - { - return _delegate.getJMSDeliveryMode(); - } - - public void setJMSDeliveryMode(int i) throws JMSException - { - _delegate.setJMSDeliveryMode(i); - } - - - public boolean getJMSRedelivered() throws JMSException - { - return _redelivered; - } - - public void setJMSRedelivered(boolean b) throws JMSException - { - _redelivered = b; - } - - - public String getJMSType() throws JMSException - { - return _delegate.getJMSType(); - } - - public void setJMSType(String string) throws JMSException - { - _delegate.setJMSType(string); - } - - public long getJMSExpiration() throws JMSException - { - return _delegate.getJMSExpiration(); - } - - public void setJMSExpiration(long l) throws JMSException - { - _delegate.setJMSExpiration(l); - } - - public int getJMSPriority() throws JMSException - { - return _delegate.getJMSPriority(); - } - - public void setJMSPriority(int i) throws JMSException - { - _delegate.setJMSPriority(i); - } - - - public boolean propertyExists(String propertyName) throws JMSException - { - return _delegate.propertyExists(propertyName); - } - - public boolean getBooleanProperty(final String s) - throws JMSException - { - return _delegate.getBooleanProperty(s); - } - - public byte getByteProperty(final String s) - throws JMSException - { - return _delegate.getByteProperty(s); - } - - public short getShortProperty(final String s) - throws JMSException - { - return _delegate.getShortProperty(s); - } - - public int getIntProperty(final String s) - throws JMSException - { - return _delegate.getIntProperty(s); - } - - public long getLongProperty(final String s) - throws JMSException - { - return _delegate.getLongProperty(s); - } - - public float getFloatProperty(final String s) - throws JMSException - { - return _delegate.getFloatProperty(s); - } - - public double getDoubleProperty(final String s) - throws JMSException - { - return _delegate.getDoubleProperty(s); - } - - public String getStringProperty(final String s) - throws JMSException - { - return _delegate.getStringProperty(s); - } - - public Object getObjectProperty(final String s) - throws JMSException - { - return _delegate.getObjectProperty(s); - } - - public Enumeration getPropertyNames() - throws JMSException - { - return _delegate.getPropertyNames(); - } - - public void setBooleanProperty(final String s, final boolean b) - throws JMSException - { - _delegate.setBooleanProperty(s, b); - } - - public void setByteProperty(final String s, final byte b) - throws JMSException - { - _delegate.setByteProperty(s, b); - } - - public void setShortProperty(final String s, final short i) - throws JMSException - { - _delegate.setShortProperty(s, i); - } - - public void setIntProperty(final String s, final int i) - throws JMSException - { - _delegate.setIntProperty(s, i); - } - - public void setLongProperty(final String s, final long l) - throws JMSException - { - _delegate.setLongProperty(s, l); - } - - public void setFloatProperty(final String s, final float v) - throws JMSException - { - _delegate.setFloatProperty(s, v); - } - - public void setDoubleProperty(final String s, final double v) - throws JMSException - { - _delegate.setDoubleProperty(s, v); - } - - public void setStringProperty(final String s, final String s1) - throws JMSException - { - _delegate.setStringProperty(s, s1); - } - - public void setObjectProperty(final String s, final Object o) - throws JMSException - { - _delegate.setObjectProperty(s, o); - } - - - - public void clearProperties() throws JMSException - { - _delegate.clearProperties(); - } - - public void clearBody() throws JMSException - { - _receivedFromServer = false; - } - - public void acknowledgeThis() throws JMSException - { - _delegate.acknowledgeThis(); - } - - public void acknowledge() throws JMSException - { - _delegate.acknowledge(); - } - - /* - * Get a String representation of the body of the message. Used in the toString() method which outputs this before - * message properties. - */ - public abstract String toBodyString() throws JMSException; - - protected abstract String getMimeType(); - - public String toHeaderString() throws JMSException - { - StringBuffer buf = new StringBuffer(); - buf.append("\nJMS Correlation ID: ").append(getJMSCorrelationID()); - buf.append("\nJMS timestamp: ").append(getJMSTimestamp()); - buf.append("\nJMS expiration: ").append(getJMSExpiration()); - buf.append("\nJMS priority: ").append(getJMSPriority()); - buf.append("\nJMS delivery mode: ").append(getJMSDeliveryMode()); - buf.append("\nJMS reply to: ").append(getReplyToString()); - buf.append("\nJMS Redelivered: ").append(_redelivered); - buf.append("\nJMS Destination: ").append(getJMSDestination()); - buf.append("\nJMS Type: ").append(getJMSType()); - buf.append("\nJMS MessageID: ").append(getJMSMessageID()); - buf.append("\nJMS Content-Type: ").append(getContentType()); - buf.append("\nAMQ message number: ").append(getDeliveryTag()); - - buf.append("\nProperties:"); - final Enumeration propertyNames = getPropertyNames(); - if (!propertyNames.hasMoreElements()) - { - buf.append("<NONE>"); - } - else - { - buf.append('\n'); - while(propertyNames.hasMoreElements()) - { - String propertyName = (String) propertyNames.nextElement(); - buf.append("\t").append(propertyName).append(" = ").append(getObjectProperty(propertyName)).append("\n"); - } - - } - return buf.toString(); - } - - public String toString() - { - try - { - StringBuffer buf = new StringBuffer("Body:\n"); - - buf.append(toBodyString()); - buf.append(toHeaderString()); - - return buf.toString(); - } - catch (JMSException e) - { - throw new RuntimeException(e); - } - } - - - public AMQMessageDelegate getDelegate() - { - return _delegate; - } - - abstract public ByteBuffer getData() throws JMSException; - - - protected void checkWritable() throws MessageNotWriteableException - { - if (_receivedFromServer) - { - throw new MessageNotWriteableException("You need to call clearBody() to make the message writable"); - } - } - - - public void setReceivedFromServer() - { - _receivedFromServer = true; - } - - - - /** - * The session is set when CLIENT_ACKNOWLEDGE mode is used so that the CHANNEL ACK can be sent when the user calls - * acknowledge() - * - * @param s the AMQ session that delivered this message - */ - public void setAMQSession(AMQSession s) - { - _delegate.setAMQSession(s); - } - - public AMQSession getAMQSession() - { - return _delegate.getAMQSession(); - } - - /** - * Get the AMQ message number assigned to this message - * - * @return the message number - */ - public long getDeliveryTag() - { - return _delegate.getDeliveryTag(); - } - - /** Invoked prior to sending the message. Allows the message to be modified if necessary before sending. */ - public void prepareForSending() throws JMSException - { - } - - - public void setContentType(String contentType) - { - _delegate.setContentType(contentType); - } - - public String getContentType() - { - return _delegate.getContentType(); - } - - public void setEncoding(String encoding) - { - _delegate.setEncoding(encoding); - } - - public String getEncoding() - { - return _delegate.getEncoding(); - } - - public String getReplyToString() - { - return _delegate.getReplyToString(); - } - - protected void removeProperty(final String propertyName) throws JMSException - { - _delegate.removeProperty(propertyName); - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/AbstractJMSMessageFactory.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/AbstractJMSMessageFactory.java deleted file mode 100644 index 65f4478baa..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/AbstractJMSMessageFactory.java +++ /dev/null @@ -1,247 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.client.message; - -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; -import java.nio.ByteBuffer; -import java.util.Iterator; -import java.util.List; - -import javax.jms.JMSException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.AMQQueue; -import org.apache.qpid.client.AMQSession_0_8; -import org.apache.qpid.client.AMQTopic; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.ContentBody; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.transport.MessageProperties; -import org.apache.qpid.util.GZIPUtils; - -public abstract class AbstractJMSMessageFactory implements MessageFactory -{ - private static final Logger _logger = LoggerFactory.getLogger(AbstractJMSMessageFactory.class); - - protected AbstractJMSMessage create08MessageWithBody(long messageNbr, - ContentHeaderBody contentHeader, - AMQShortString exchange, - AMQShortString routingKey, - List bodies, - AMQSession_0_8.DestinationCache<AMQQueue> queueDestinationCache, - AMQSession_0_8.DestinationCache<AMQTopic> topicDestinationCache, - final int addressType) throws AMQException - { - ByteBuffer data; - final boolean debug = _logger.isDebugEnabled(); - - byte[] uncompressed; - - if(GZIPUtils.GZIP_CONTENT_ENCODING.equals(contentHeader.getProperties().getEncodingAsString()) - && (uncompressed = GZIPUtils.uncompressStreamToArray(new BodyInputStream(bodies))) != null ) - { - contentHeader.getProperties().setEncoding((String)null); - data = ByteBuffer.wrap(uncompressed); - } - else - { - // we optimise the non-fragmented case to avoid copying - if ((bodies != null) && (bodies.size() == 1)) - { - if (debug) - { - _logger.debug("Non-fragmented message body (bodySize=" + contentHeader.getBodySize() + ")"); - } - - data = ByteBuffer.wrap(((ContentBody) bodies.get(0)).getPayload()); - } - else if (bodies != null) - { - if (debug) - { - _logger.debug("Fragmented message body (" + bodies - .size() + " frames, bodySize=" + contentHeader.getBodySize() + ")"); - } - - data = ByteBuffer.allocate((int) contentHeader.getBodySize()); // XXX: Is cast a problem? - final Iterator it = bodies.iterator(); - while (it.hasNext()) - { - ContentBody cb = (ContentBody) it.next(); - final ByteBuffer payload = ByteBuffer.wrap(cb.getPayload()); - if (payload.isDirect() || payload.isReadOnly()) - { - data.put(payload); - } - else - { - data.put(payload.array(), payload.arrayOffset(), payload.limit()); - } - - } - - data.flip(); - } - else // bodies == null - { - data = ByteBuffer.allocate(0); - } - } - - if (debug) - { - _logger.debug("Creating message from buffer with position=" + data.position() + " and remaining=" + data - .remaining()); - } - - AMQMessageDelegate delegate = new AMQMessageDelegate_0_8(messageNbr, - contentHeader.getProperties(), - exchange, routingKey, queueDestinationCache, - topicDestinationCache, addressType); - - return createMessage(delegate, data); - } - - protected abstract AbstractJMSMessage createMessage(AMQMessageDelegate delegate, ByteBuffer data) throws AMQException; - - - protected AbstractJMSMessage create010MessageWithBody(long messageNbr, MessageProperties msgProps, - DeliveryProperties deliveryProps, - java.nio.ByteBuffer body) throws AMQException - { - ByteBuffer data; - final boolean debug = _logger.isDebugEnabled(); - - - if (body != null) - { - data = body; - } - else // body == null - { - data = ByteBuffer.allocate(0); - } - - if (debug) - { - _logger.debug("Creating message from buffer with position=" + data.position() + " and remaining=" + data - .remaining()); - } - if(GZIPUtils.GZIP_CONTENT_ENCODING.equals(msgProps.getContentEncoding())) - { - byte[] uncompressed = GZIPUtils.uncompressBufferToArray(data); - if(uncompressed != null) - { - msgProps.setContentEncoding(null); - data = ByteBuffer.wrap(uncompressed); - } - } - AMQMessageDelegate delegate = new AMQMessageDelegate_0_10(msgProps, deliveryProps, messageNbr); - - AbstractJMSMessage message = createMessage(delegate, data); - return message; - } - - @Override - public AbstractJMSMessage createMessage(long messageNbr, boolean redelivered, ContentHeaderBody contentHeader, - AMQShortString exchange, AMQShortString routingKey, List bodies, - AMQSession_0_8.DestinationCache<AMQQueue> queueDestinationCache, - AMQSession_0_8.DestinationCache<AMQTopic> topicDestinationCache, - int addressType) - throws JMSException, AMQException - { - final AbstractJMSMessage msg = create08MessageWithBody(messageNbr, contentHeader, exchange, routingKey, bodies, queueDestinationCache, topicDestinationCache, addressType); - msg.setJMSRedelivered(redelivered); - msg.setReceivedFromServer(); - return msg; - } - - public AbstractJMSMessage createMessage(long messageNbr, boolean redelivered, MessageProperties msgProps, - DeliveryProperties deliveryProps, java.nio.ByteBuffer body) - throws JMSException, AMQException - { - final AbstractJMSMessage msg = - create010MessageWithBody(messageNbr,msgProps,deliveryProps, body); - msg.setJMSRedelivered(redelivered); - msg.setReceivedFromServer(); - return msg; - } - - private class BodyInputStream extends InputStream - { - private final Iterator<ContentBody> _bodiesIter; - private byte[] _currentBuffer; - private int _currentPos; - public BodyInputStream(final List<ContentBody> bodies) - { - _bodiesIter = bodies.iterator(); - _currentBuffer = _bodiesIter.next().getPayload(); - _currentPos = 0; - } - - @Override - public int read() throws IOException - { - byte[] buf = new byte[1]; - int size = read(buf); - if(size == -1) - { - throw new EOFException(); - } - else - { - return ((int)buf[0])&0xff; - } - } - - @Override - public int read(final byte[] dst, final int off, final int len) - { - while(_currentPos == _currentBuffer.length) - { - if(!_bodiesIter.hasNext()) - { - return -1; - } - else - { - _currentBuffer = _bodiesIter.next().getPayload(); - _currentPos = 0; - } - } - int size = Math.min(len, _currentBuffer.length - _currentPos); - System.arraycopy(_currentBuffer,_currentPos, dst,off,size); - _currentPos+=size; - return size; - } - - @Override - public void close() - { - } - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/CloseConsumerMessage.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/CloseConsumerMessage.java deleted file mode 100644 index 4af04912e5..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/CloseConsumerMessage.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.client.message; - -import org.apache.qpid.client.BasicMessageConsumer; - -public final class CloseConsumerMessage extends UnprocessedMessage -{ - - public CloseConsumerMessage(BasicMessageConsumer consumer) - { - super(consumer.getConsumerTag()); - } - - - public long getDeliveryTag() - { - return 0; - } - - public boolean isRedelivered() - { - return false; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/FieldTableSupport.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/FieldTableSupport.java deleted file mode 100644 index 3d3b753ad3..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/FieldTableSupport.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.client.message; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.FieldTable; - -public class FieldTableSupport -{ - private FieldTableSupport() - { - } - - public static FieldTable convertToFieldTable(Map<String,?> props) - { - FieldTable ft = new FieldTable(); - if (props != null) - { - for (String key : props.keySet()) - { - ft.setObject(key, props.get(key)); - } - } - return ft; - } - - public static Map<String,Object> convertToMap(FieldTable ft) - { - Map<String,Object> map = new HashMap<String,Object>(); - if(ft != null) - { - for (AMQShortString key: ft.keySet() ) - { - map.put(key.asString(), ft.getObject(key)); - } - } - - return map; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSBytesMessage.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSBytesMessage.java deleted file mode 100644 index 6ffa051ff8..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSBytesMessage.java +++ /dev/null @@ -1,369 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 java.io.EOFException; -import java.nio.ByteBuffer; -import javax.jms.BytesMessage; -import javax.jms.JMSException; -import javax.jms.MessageEOFException; -import javax.jms.MessageFormatException; -import org.apache.qpid.AMQException; -import org.apache.qpid.typedmessage.TypedBytesContentReader; -import org.apache.qpid.typedmessage.TypedBytesContentWriter; -import org.apache.qpid.typedmessage.TypedBytesFormatException; - -public class JMSBytesMessage extends AbstractBytesTypedMessage implements BytesMessage -{ - public static final String MIME_TYPE = "application/octet-stream"; - - - private TypedBytesContentReader _typedBytesContentReader; - private TypedBytesContentWriter _typedBytesContentWriter; - - - public JMSBytesMessage(AMQMessageDelegateFactory delegateFactory) - { - super(delegateFactory,false); - _typedBytesContentWriter = new TypedBytesContentWriter(); - } - - JMSBytesMessage(AMQMessageDelegate delegate, ByteBuffer data) throws AMQException - { - super(delegate, data!=null); - _typedBytesContentReader = new TypedBytesContentReader(data); - } - - - public void reset() - { - setReadable(true); - - if(_typedBytesContentReader != null) - { - _typedBytesContentReader.reset(); - } - else if (_typedBytesContentWriter != null) - { - _typedBytesContentReader = new TypedBytesContentReader(_typedBytesContentWriter.getData()); - } - } - - @Override - public void clearBody() throws JMSException - { - super.clearBody(); - _typedBytesContentReader = null; - _typedBytesContentWriter = new TypedBytesContentWriter(); - - } - - protected String getMimeType() - { - return MIME_TYPE; - } - - @Override - public java.nio.ByteBuffer getData() throws JMSException - { - return _typedBytesContentWriter == null ? _typedBytesContentReader.getData() : _typedBytesContentWriter.getData(); - } - - public long getBodyLength() throws JMSException - { - checkReadable(); - return _typedBytesContentReader.size(); - } - - public boolean readBoolean() throws JMSException - { - checkReadable(); - checkAvailable(1); - - return _typedBytesContentReader.readBooleanImpl(); - } - - private void checkAvailable(final int i) throws MessageEOFException - { - try - { - _typedBytesContentReader.checkAvailable(1); - } - catch (EOFException e) - { - throw new MessageEOFException(e.getMessage()); - } - } - - public byte readByte() throws JMSException - { - checkReadable(); - checkAvailable(1); - return _typedBytesContentReader.readByteImpl(); - } - - public int readUnsignedByte() throws JMSException - { - checkReadable(); - checkAvailable(1); - return _typedBytesContentReader.readByteImpl() & 0xFF; - } - - public short readShort() throws JMSException - { - checkReadable(); - checkAvailable(2); - return _typedBytesContentReader.readShortImpl(); - } - - public int readUnsignedShort() throws JMSException - { - checkReadable(); - checkAvailable(2); - return _typedBytesContentReader.readShortImpl() & 0xFFFF; - } - - /** - * Note that this method reads a unicode character as two bytes from the stream - * - * @return the character read from the stream - * @throws JMSException - */ - public char readChar() throws JMSException - { - checkReadable(); - checkAvailable(2); - return _typedBytesContentReader.readCharImpl(); - } - - public int readInt() throws JMSException - { - checkReadable(); - checkAvailable(4); - return _typedBytesContentReader.readIntImpl(); - } - - public long readLong() throws JMSException - { - checkReadable(); - checkAvailable(8); - return _typedBytesContentReader.readLongImpl(); - } - - public float readFloat() throws JMSException - { - checkReadable(); - checkAvailable(4); - return _typedBytesContentReader.readFloatImpl(); - } - - public double readDouble() throws JMSException - { - checkReadable(); - checkAvailable(8); - return _typedBytesContentReader.readDoubleImpl(); - } - - public String readUTF() throws JMSException - { - checkReadable(); - // we check only for one byte since theoretically the string could be only a - // single byte when using UTF-8 encoding - - try - { - return _typedBytesContentReader.readLengthPrefixedUTF(); - } - catch (TypedBytesFormatException e) - { - throw new MessageFormatException(e.getMessage()); - } - } - - public int readBytes(byte[] bytes) throws JMSException - { - if (bytes == null) - { - throw new IllegalArgumentException("byte array must not be null"); - } - checkReadable(); - int count = (_typedBytesContentReader.remaining() >= bytes.length ? bytes.length : _typedBytesContentReader.remaining()); - if (count == 0) - { - return -1; - } - else - { - _typedBytesContentReader.readRawBytes(bytes, 0, count); - return count; - } - } - - public int readBytes(byte[] bytes, int maxLength) throws JMSException - { - if (bytes == null) - { - throw new IllegalArgumentException("byte array must not be null"); - } - if (maxLength > bytes.length) - { - throw new IllegalArgumentException("maxLength must be <= bytes.length"); - } - checkReadable(); - int count = (_typedBytesContentReader.remaining() >= maxLength ? maxLength : _typedBytesContentReader.remaining()); - if (count == 0) - { - return -1; - } - else - { - _typedBytesContentReader.readRawBytes(bytes, 0, count); - return count; - } - } - - - public void writeBoolean(boolean b) throws JMSException - { - checkWritable(); - _typedBytesContentWriter.writeBooleanImpl(b); - } - - public void writeByte(byte b) throws JMSException - { - checkWritable(); - _typedBytesContentWriter.writeByteImpl(b); - } - - public void writeShort(short i) throws JMSException - { - checkWritable(); - _typedBytesContentWriter.writeShortImpl(i); - } - - public void writeChar(char c) throws JMSException - { - checkWritable(); - _typedBytesContentWriter.writeCharImpl(c); - } - - public void writeInt(int i) throws JMSException - { - checkWritable(); - _typedBytesContentWriter.writeIntImpl(i); - } - - public void writeLong(long l) throws JMSException - { - checkWritable(); - _typedBytesContentWriter.writeLongImpl(l); - } - - public void writeFloat(float v) throws JMSException - { - checkWritable(); - _typedBytesContentWriter.writeFloatImpl(v); - } - - public void writeDouble(double v) throws JMSException - { - checkWritable(); - _typedBytesContentWriter.writeDoubleImpl(v); - } - - public void writeUTF(String string) throws JMSException - { - checkWritable(); - try - { - _typedBytesContentWriter.writeLengthPrefixedUTF(string); - } - catch (TypedBytesFormatException e) - { - throw new MessageFormatException(e.getMessage()); - } - } - - public void writeBytes(byte[] bytes) throws JMSException - { - writeBytes(bytes, 0, bytes.length); - } - - public void writeBytes(byte[] bytes, int offset, int length) throws JMSException - { - checkWritable(); - _typedBytesContentWriter.writeBytesRaw(bytes, offset, length); - } - - public void writeObject(Object object) throws JMSException - { - checkWritable(); - if (object == null) - { - throw new NullPointerException("Argument must not be null"); - } - Class clazz = object.getClass(); - if (clazz == Byte.class) - { - writeByte((Byte) object); - } - else if (clazz == Boolean.class) - { - writeBoolean((Boolean) object); - } - else if (clazz == byte[].class) - { - writeBytes((byte[]) object); - } - else if (clazz == Short.class) - { - writeShort((Short) object); - } - else if (clazz == Character.class) - { - writeChar((Character) object); - } - else if (clazz == Integer.class) - { - writeInt((Integer) object); - } - else if (clazz == Long.class) - { - writeLong((Long) object); - } - else if (clazz == Float.class) - { - writeFloat((Float) object); - } - else if (clazz == Double.class) - { - writeDouble((Double) object); - } - else if (clazz == String.class) - { - writeUTF((String) object); - } - else - { - throw new MessageFormatException("Only primitives plus byte arrays and String are valid types"); - } - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSBytesMessageFactory.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSBytesMessageFactory.java deleted file mode 100644 index c8c01f16ee..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSBytesMessageFactory.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.client.message; - -import org.apache.qpid.AMQException; - -import javax.jms.JMSException; -import java.nio.ByteBuffer; - -public class JMSBytesMessageFactory extends AbstractJMSMessageFactory -{ - protected AbstractJMSMessage createMessage(AMQMessageDelegate delegate, ByteBuffer data) throws AMQException - { - return new JMSBytesMessage(delegate, data); - } - - public AbstractJMSMessage createMessage(AMQMessageDelegateFactory delegateFactory) throws JMSException - { - return new JMSBytesMessage(delegateFactory); - } - - // 0_10 specific - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSHeaderAdapter.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSHeaderAdapter.java deleted file mode 100644 index e27b3d81cb..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSHeaderAdapter.java +++ /dev/null @@ -1,476 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 java.util.Collections; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; - -import javax.jms.JMSException; -import javax.jms.MessageFormatException; - -import org.apache.qpid.AMQPInvalidClassException; -import org.apache.qpid.framing.FieldTable; - - -public final class JMSHeaderAdapter -{ - private static final Map<String,String> AMQP_TO_JMS_HEADER_NAME_MAPPINGS; - private static final Map<String,String> JMS_TO_AMQP_HEADER_NAME_MAPPINGS; - - - - static - { - String[][] mappings = { - { QpidMessageProperties.QPID_SUBJECT, QpidMessageProperties.QPID_SUBJECT_JMS_PROPERTY } - }; - - Map<String,String> amqpToJmsHeaderNameMappings = new HashMap<>(); - Map<String,String> jmsToAmqpHeaderNameMappings = new HashMap<>(); - - for(String[] mapping : mappings) - { - amqpToJmsHeaderNameMappings.put(mapping[0], mapping[1]); - jmsToAmqpHeaderNameMappings.put(mapping[1], mapping[0]); - } - - AMQP_TO_JMS_HEADER_NAME_MAPPINGS = Collections.unmodifiableMap(amqpToJmsHeaderNameMappings); - JMS_TO_AMQP_HEADER_NAME_MAPPINGS = Collections.unmodifiableMap(jmsToAmqpHeaderNameMappings); - } - - private static final boolean STRICT_JMS = Boolean.getBoolean("strict-jms"); - - - private final FieldTable _headers; - - public JMSHeaderAdapter(FieldTable headers) - { - _headers = headers; - } - - - private String mapJmsToAmqpName(String name) - { - return JMS_TO_AMQP_HEADER_NAME_MAPPINGS.containsKey(name) ? JMS_TO_AMQP_HEADER_NAME_MAPPINGS.get(name) : name; - } - - public boolean getBoolean(String name) throws JMSException - { - checkPropertyName(name); - String amqpName = mapJmsToAmqpName(name); - Boolean b = _headers.getBoolean(amqpName); - - if (b == null) - { - if (_headers.containsKey(amqpName)) - { - Object str = _headers.getObject(amqpName); - - if (!(str instanceof String)) - { - throw new MessageFormatException("getBoolean can't use " + name + " item."); - } - else - { - return Boolean.valueOf((String) str); - } - } - else - { - b = Boolean.valueOf(null); - } - } - - return b; - } - - - public byte[] getBytes(String name) throws JMSException - { - checkPropertyName(name); - String amqpName = mapJmsToAmqpName(name); - byte[] bs = _headers.getBytes(amqpName); - - if (bs == null) - { - throw new MessageFormatException("getBytes can't use " + name + " item."); - } - else - { - return bs; - } - } - - public byte getByte(String name) throws JMSException - { - checkPropertyName(name); - String amqpName = mapJmsToAmqpName(name); - Byte b = _headers.getByte(amqpName); - if (b == null) - { - if (_headers.containsKey(amqpName)) - { - Object str = _headers.getObject(amqpName); - - if (!(str instanceof String)) - { - throw new MessageFormatException("getByte can't use " + name + " item."); - } - else - { - return Byte.valueOf((String) str); - } - } - else - { - b = Byte.valueOf(null); - } - } - - return b; - } - - public short getShort(String name) throws JMSException - { - checkPropertyName(name); - String amqpName = mapJmsToAmqpName(name); - Short s = _headers.getShort(amqpName); - - if (s == null) - { - s = Short.valueOf(getByte(amqpName)); - } - - return s; - } - - public int getInteger(String name) throws JMSException - { - checkPropertyName(name); - String amqpName = mapJmsToAmqpName(name); - Integer i = _headers.getInteger(amqpName); - - if (i == null) - { - i = Integer.valueOf(getShort(amqpName)); - } - - return i; - } - - public long getLong(String name) throws JMSException - { - checkPropertyName(name); - String amqpName = mapJmsToAmqpName(name); - Long l = _headers.getLong(amqpName); - - if (l == null) - { - l = Long.valueOf(getInteger(amqpName)); - } - - return l; - } - - public float getFloat(String name) throws JMSException - { - checkPropertyName(name); - String amqpName = mapJmsToAmqpName(name); - Float f = _headers.getFloat(amqpName); - - if (f == null) - { - if (_headers.containsKey(amqpName)) - { - Object str = _headers.getObject(amqpName); - - if (!(str instanceof String)) - { - throw new MessageFormatException("getFloat can't use " + name + " item."); - } - else - { - return Float.valueOf((String) str); - } - } - else - { - throw new NullPointerException("No such property: " + name); - } - - } - - return f; - } - - public double getDouble(String name) throws JMSException - { - checkPropertyName(name); - String amqpName = mapJmsToAmqpName(name); - Double d = _headers.getDouble(amqpName); - - if (d == null) - { - d = Double.valueOf(getFloat(amqpName)); - } - - return d; - } - - public String getString(String name) throws JMSException - { - checkPropertyName(name); - String amqpName = mapJmsToAmqpName(name); - String s = _headers.getString(amqpName); - - if (s == null) - { - if (_headers.containsKey(amqpName)) - { - Object o = _headers.getObject(amqpName); - if (o instanceof byte[]) - { - throw new MessageFormatException("getObject couldn't find " + name + " item."); - } - else - { - if (o == null) - { - return null; - } - else - { - s = String.valueOf(o); - } - } - } - } - - return s; - } - - public Object getObject(String name) throws JMSException - { - checkPropertyName(name); - String amqpName = mapJmsToAmqpName(name); - return _headers.getObject(amqpName); - } - - public void setBoolean(String name, boolean b) throws JMSException - { - checkPropertyName(name); - String amqpName = mapJmsToAmqpName(name); - _headers.setBoolean(amqpName, b); - } - - public void setByte(String name, byte b) throws JMSException - { - checkPropertyName(name); - String amqpName = mapJmsToAmqpName(name); - _headers.setByte(amqpName, b); - } - - public void setShort(String name, short i) throws JMSException - { - checkPropertyName(name); - String amqpName = mapJmsToAmqpName(name); - _headers.setShort(amqpName, i); - } - - public void setInteger(String name, int i) throws JMSException - { - checkPropertyName(name); - String amqpName = mapJmsToAmqpName(name); - _headers.setInteger(amqpName, i); - } - - public void setLong(String name, long l) throws JMSException - { - checkPropertyName(name); - String amqpName = mapJmsToAmqpName(name); - _headers.setLong(amqpName, l); - } - - public void setFloat(String name, float v) throws JMSException - { - checkPropertyName(name); - String amqpName = mapJmsToAmqpName(name); - _headers.setFloat(amqpName, v); - } - - public void setDouble(String name, double v) throws JMSException - { - checkPropertyName(name); - String amqpName = mapJmsToAmqpName(name); - _headers.setDouble(amqpName, v); - } - - public void setString(String name, String value) throws JMSException - { - checkPropertyName(name); - String amqpName = mapJmsToAmqpName(name); - _headers.setString(amqpName, value); - } - - public void setObject(String name, Object object) throws JMSException - { - checkPropertyName(name); - String amqpName = mapJmsToAmqpName(name); - try - { - _headers.setObject(amqpName, object); - } - catch (AMQPInvalidClassException aice) - { - MessageFormatException mfe = new MessageFormatException(AMQPInvalidClassException.INVALID_OBJECT_MSG + (object == null ? "null" : object.getClass())); - mfe.setLinkedException(aice); - mfe.initCause(aice); - throw mfe; - } - } - - public Set<String> getPropertyNames() - { - Set<String> names = new LinkedHashSet<>(_headers.keys()); - for(Map.Entry<String,String> entry : AMQP_TO_JMS_HEADER_NAME_MAPPINGS.entrySet()) - { - if(names.contains(entry.getKey())) - { - names.add(entry.getValue()); - if(STRICT_JMS) - { - names.remove(entry.getKey()); - } - } - } - return names; - } - - public void clear() - { - _headers.clear(); - } - - public boolean propertyExists(String name) - { - checkPropertyName(name); - String propertyName = mapJmsToAmqpName(name); - return _headers.propertyExists(propertyName); - } - - public Object remove(String name) - { - checkPropertyName(name); - String propertyName = mapJmsToAmqpName(name); - return _headers.remove(propertyName); - } - - public boolean isEmpty() - { - return _headers.isEmpty(); - } - - protected void checkPropertyName(CharSequence propertyName) - { - if (propertyName == null) - { - throw new IllegalArgumentException("Property name must not be null"); - } - else if (propertyName.length() == 0) - { - throw new IllegalArgumentException("Property name must not be the empty string"); - } - - checkIdentifierFormat(propertyName); - } - - protected void checkIdentifierFormat(CharSequence propertyName) - { -// JMS requirements 3.5.1 Property Names -// Identifiers: -// - An identifier is an unlimited-length character sequence that must begin -// with a Java identifier start character; all following characters must be Java -// identifier part characters. An identifier start character is any character for -// which the method Character.isJavaIdentifierStart returns true. This includes -// '_' and '$'. An identifier part character is any character for which the -// method Character.isJavaIdentifierPart returns true. -// - Identifiers cannot be the names NULL, TRUE, or FALSE. -// Identifiers cannot be NOT, AND, OR, BETWEEN, LIKE, IN, IS, or -// ESCAPE. -// Identifiers are either header field references or property references. The -// type of a property value in a message selector corresponds to the type -// used to set the property. If a property that does not exist in a message is -// referenced, its value is NULL. The semantics of evaluating NULL values -// in a selector are described in Section 3.8.1.2, Null Values. -// The conversions that apply to the get methods for properties do not -// apply when a property is used in a message selector expression. For -// example, suppose you set a property as a string value, as in the -// following: -// myMessage.setStringProperty("NumberOfOrders", "2") -// The following expression in a message selector would evaluate to false, -// because a string cannot be used in an arithmetic expression: -// "NumberOfOrders > 1" -// Identifiers are case sensitive. -// Message header field references are restricted to JMSDeliveryMode, -// JMSPriority, JMSMessageID, JMSTimestamp, JMSCorrelationID, and -// JMSType. JMSMessageID, JMSCorrelationID, and JMSType values may be -// null and if so are treated as a NULL value. - - if (STRICT_JMS) - { - // JMS start character - if (!(Character.isJavaIdentifierStart(propertyName.charAt(0)))) - { - throw new IllegalArgumentException("Identifier '" + propertyName + "' does not start with a valid JMS identifier start character"); - } - - // JMS part character - int length = propertyName.length(); - for (int c = 1; c < length; c++) - { - if (!(Character.isJavaIdentifierPart(propertyName.charAt(c)))) - { - throw new IllegalArgumentException("Identifier '" + propertyName + "' contains an invalid JMS identifier character"); - } - } - - // JMS invalid names - if ((propertyName.equals("NULL") - || propertyName.equals("TRUE") - || propertyName.equals("FALSE") - || propertyName.equals("NOT") - || propertyName.equals("AND") - || propertyName.equals("OR") - || propertyName.equals("BETWEEN") - || propertyName.equals("LIKE") - || propertyName.equals("IN") - || propertyName.equals("IS") - || propertyName.equals("ESCAPE"))) - { - throw new IllegalArgumentException("Identifier '" + propertyName + "' is not allowed in JMS"); - } - } - - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSMapMessage.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSMapMessage.java deleted file mode 100644 index af36c75ef2..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSMapMessage.java +++ /dev/null @@ -1,518 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 java.io.EOFException; -import java.nio.ByteBuffer; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; -import javax.jms.JMSException; -import javax.jms.MessageEOFException; -import javax.jms.MessageFormatException; -import org.apache.qpid.AMQException; -import org.apache.qpid.typedmessage.TypedBytesContentReader; -import org.apache.qpid.typedmessage.TypedBytesContentWriter; -import org.apache.qpid.typedmessage.TypedBytesFormatException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class JMSMapMessage extends AbstractJMSMessage implements javax.jms.MapMessage -{ - private static final Logger _logger = LoggerFactory.getLogger(JMSMapMessage.class); - - public static final String MIME_TYPE = "jms/map-message"; - - private Map<String, Object> _map = new HashMap<String, Object>(); - - public JMSMapMessage(AMQMessageDelegateFactory delegateFactory) throws JMSException - { - this(delegateFactory, null); - } - - JMSMapMessage(AMQMessageDelegateFactory delegateFactory, ByteBuffer data) throws JMSException - { - - super(delegateFactory, data!=null); // this instantiates a content header - if(data != null) - { - populateMapFromData(data); - } - - } - - JMSMapMessage(AMQMessageDelegate delegate, ByteBuffer data) throws AMQException - { - - super(delegate, data != null); - try - { - populateMapFromData(data); - } - catch (JMSException je) - { - throw new AMQException(null, "Error populating MapMessage from ByteBuffer", je); - - } - - } - - - public String toBodyString() throws JMSException - { - return _map == null ? "" : _map.toString(); - } - - protected String getMimeType() - { - return MIME_TYPE; - } - - @Override - public void clearBody() throws JMSException - { - super.clearBody(); - _map.clear(); - } - - public boolean getBoolean(String propName) throws JMSException - { - Object value = _map.get(propName); - - if (value instanceof Boolean) - { - return ((Boolean) value).booleanValue(); - } - else if ((value instanceof String) || (value == null)) - { - return Boolean.valueOf((String) value); - } - else - { - throw new MessageFormatException("Property " + propName + " of type " + value.getClass().getName() - + " cannot be converted to boolean."); - } - - } - - public byte getByte(String propName) throws JMSException - { - Object value = _map.get(propName); - - if (value instanceof Byte) - { - return ((Byte) value).byteValue(); - } - else if ((value instanceof String) || (value == null)) - { - return Byte.valueOf((String) value).byteValue(); - } - else - { - throw new MessageFormatException("Property " + propName + " of type " + value.getClass().getName() - + " cannot be converted to byte."); - } - } - - public short getShort(String propName) throws JMSException - { - Object value = _map.get(propName); - - if (value instanceof Short) - { - return ((Short) value).shortValue(); - } - else if (value instanceof Byte) - { - return ((Byte) value).shortValue(); - } - else if ((value instanceof String) || (value == null)) - { - return Short.valueOf((String) value).shortValue(); - } - else - { - throw new MessageFormatException("Property " + propName + " of type " + value.getClass().getName() - + " cannot be converted to short."); - } - - } - - public int getInt(String propName) throws JMSException - { - Object value = _map.get(propName); - - if (value instanceof Integer) - { - return ((Integer) value).intValue(); - } - else if (value instanceof Short) - { - return ((Short) value).intValue(); - } - else if (value instanceof Byte) - { - return ((Byte) value).intValue(); - } - else if ((value instanceof String) || (value == null)) - { - return Integer.valueOf((String) value).intValue(); - } - else - { - throw new MessageFormatException("Property " + propName + " of type " + value.getClass().getName() - + " cannot be converted to int."); - } - - } - - public long getLong(String propName) throws JMSException - { - Object value = _map.get(propName); - - if (value instanceof Long) - { - return ((Long) value).longValue(); - } - else if (value instanceof Integer) - { - return ((Integer) value).longValue(); - } - - if (value instanceof Short) - { - return ((Short) value).longValue(); - } - - if (value instanceof Byte) - { - return ((Byte) value).longValue(); - } - else if ((value instanceof String) || (value == null)) - { - return Long.valueOf((String) value).longValue(); - } - else - { - throw new MessageFormatException("Property " + propName + " of type " + value.getClass().getName() - + " cannot be converted to long."); - } - - } - - public char getChar(String propName) throws JMSException - { - Object value = _map.get(propName); - - if (!_map.containsKey(propName)) - { - throw new MessageFormatException("Property " + propName + " not present"); - } - else if (value instanceof Character) - { - return ((Character) value).charValue(); - } - else if (value == null) - { - throw new NullPointerException("Property " + propName + " has null value and therefore cannot " - + "be converted to char."); - } - else - { - throw new MessageFormatException("Property " + propName + " of type " + value.getClass().getName() - + " cannot be converted to boolan."); - } - - } - - public float getFloat(String propName) throws JMSException - { - Object value = _map.get(propName); - - if (value instanceof Float) - { - return ((Float) value).floatValue(); - } - else if ((value instanceof String) || (value == null)) - { - return Float.valueOf((String) value).floatValue(); - } - else - { - throw new MessageFormatException("Property " + propName + " of type " + value.getClass().getName() - + " cannot be converted to float."); - } - } - - public double getDouble(String propName) throws JMSException - { - Object value = _map.get(propName); - - if (value instanceof Double) - { - return ((Double) value).doubleValue(); - } - else if (value instanceof Float) - { - return ((Float) value).doubleValue(); - } - else if ((value instanceof String) || (value == null)) - { - return Double.valueOf((String) value).doubleValue(); - } - else - { - throw new MessageFormatException("Property " + propName + " of type " + value.getClass().getName() - + " cannot be converted to double."); - } - } - - public String getString(String propName) throws JMSException - { - Object value = _map.get(propName); - - if ((value instanceof String) || (value == null)) - { - return (String) value; - } - else if (value instanceof byte[]) - { - throw new MessageFormatException("Property " + propName + " of type byte[] " + "cannot be converted to String."); - } - else - { - return value.toString(); - } - - } - - public byte[] getBytes(String propName) throws JMSException - { - Object value = _map.get(propName); - - if (!_map.containsKey(propName)) - { - throw new MessageFormatException("Property " + propName + " not present"); - } - else if ((value instanceof byte[]) || (value == null)) - { - return (byte[]) value; - } - else - { - throw new MessageFormatException("Property " + propName + " of type " + value.getClass().getName() - + " cannot be converted to byte[]."); - } - } - - public Object getObject(String propName) throws JMSException - { - return _map.get(propName); - } - - public Enumeration getMapNames() throws JMSException - { - return Collections.enumeration(_map.keySet()); - } - - public void setBoolean(String propName, boolean b) throws JMSException - { - checkWritable(); - checkPropertyName(propName); - _map.put(propName, b); - } - - public void setByte(String propName, byte b) throws JMSException - { - checkWritable(); - checkPropertyName(propName); - _map.put(propName, b); - } - - public void setShort(String propName, short i) throws JMSException - { - checkWritable(); - checkPropertyName(propName); - _map.put(propName, i); - } - - public void setChar(String propName, char c) throws JMSException - { - checkWritable(); - checkPropertyName(propName); - _map.put(propName, c); - } - - public void setInt(String propName, int i) throws JMSException - { - checkWritable(); - checkPropertyName(propName); - _map.put(propName, i); - } - - public void setLong(String propName, long l) throws JMSException - { - checkWritable(); - checkPropertyName(propName); - _map.put(propName, l); - } - - public void setFloat(String propName, float v) throws JMSException - { - checkWritable(); - checkPropertyName(propName); - _map.put(propName, v); - } - - public void setDouble(String propName, double v) throws JMSException - { - checkWritable(); - checkPropertyName(propName); - _map.put(propName, v); - } - - public void setString(String propName, String string1) throws JMSException - { - checkWritable(); - checkPropertyName(propName); - _map.put(propName, string1); - } - - public void setBytes(String propName, byte[] bytes) throws JMSException - { - checkWritable(); - checkPropertyName(propName); - _map.put(propName, bytes); - } - - public void setBytes(String propName, byte[] bytes, int offset, int length) throws JMSException - { - if ((offset == 0) && (length == bytes.length)) - { - setBytes(propName, bytes); - } - else - { - byte[] newBytes = new byte[length]; - System.arraycopy(bytes, offset, newBytes, 0, length); - setBytes(propName, newBytes); - } - } - - public void setObject(String propName, Object value) throws JMSException - { - checkWritable(); - checkPropertyName(propName); - if ((value instanceof Boolean) || (value instanceof Byte) || (value instanceof Short) || (value instanceof Integer) - || (value instanceof Long) || (value instanceof Character) || (value instanceof Float) - || (value instanceof Double) || (value instanceof String) || (value instanceof byte[]) || (value == null)) - { - _map.put(propName, value); - } - else - { - throw new MessageFormatException("Cannot set property " + propName + " to value " + value + "of type " - + value.getClass().getName() + "."); - } - } - - protected void checkPropertyName(String propName) - { - if ((propName == null) || propName.equals("")) - { - throw new IllegalArgumentException("Property name cannot be null, or the empty String."); - } - } - - public boolean itemExists(String propName) throws JMSException - { - return _map.containsKey(propName); - } - - protected void populateMapFromData(ByteBuffer data) throws JMSException - { - if (data != null) - { - TypedBytesContentReader reader = new TypedBytesContentReader(data); - data.rewind(); - - final int entries = reader.readIntImpl(); - for (int i = 0; i < entries; i++) - { - String propName = null; - try - { - propName = reader.readStringImpl(); - Object value = reader.readObject(); - _map.put(propName, value); - - } - catch (TypedBytesFormatException e) - { - throw new MessageFormatException(e.getMessage()); - } - catch (EOFException e) - { - throw new MessageEOFException(e.getMessage()); - } - } - } - else - { - _map.clear(); - } - } - - public ByteBuffer getData() - throws JMSException - { - TypedBytesContentWriter writer = new TypedBytesContentWriter(); - - final int size = _map.size(); - writer.writeIntImpl(size); - for (Map.Entry<String, Object> entry : _map.entrySet()) - { - writer.writeNullTerminatedStringImpl(entry.getKey()); - - try - { - writer.writeObject(entry.getValue()); - } - catch (TypedBytesFormatException e) - { - throw new MessageFormatException(e.getMessage()); - } - } - - return writer.getData(); - } - - protected Map<String, Object> getMap() - { - return _map; - } - - protected void setMap(Map<String, Object> map) - { - _map = map; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSMapMessageFactory.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSMapMessageFactory.java deleted file mode 100644 index 72bc8d59ea..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSMapMessageFactory.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.client.message; - -import org.apache.qpid.AMQException; - -import javax.jms.JMSException; -import java.nio.ByteBuffer; - -public class JMSMapMessageFactory extends AbstractJMSMessageFactory -{ - public AbstractJMSMessage createMessage(AMQMessageDelegateFactory delegateFactory) throws JMSException - { - return new JMSMapMessage(delegateFactory); - } - - protected AbstractJMSMessage createMessage(AMQMessageDelegate delegate, ByteBuffer data) throws AMQException - { - return new JMSMapMessage(delegate, data); - - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSObjectMessage.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSObjectMessage.java deleted file mode 100644 index c2a919c1c5..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSObjectMessage.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.message; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.util.ClassLoadingAwareObjectInputStream; -import org.apache.qpid.util.ByteBufferInputStream; - -import javax.jms.JMSException; -import javax.jms.MessageFormatException; -import javax.jms.ObjectMessage; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.nio.ByteBuffer; - -public class JMSObjectMessage extends AbstractJMSMessage implements ObjectMessage -{ - public static final String MIME_TYPE = "application/java-object-stream"; - private static final int DEFAULT_OUTPUT_BUFFER_SIZE = 256; - - private Serializable _readData; - private ByteBuffer _data; - - private Exception _exception; - - private static final ByteBuffer EMPTY_BYTE_BUFFER = ByteBuffer.allocate(0); - - - /** - * Creates empty, writable message for use by producers - * @param delegateFactory - */ - public JMSObjectMessage(AMQMessageDelegateFactory delegateFactory) - { - super(delegateFactory, false); - } - - /** - * Creates read only message for delivery to consumers - */ - - JMSObjectMessage(AMQMessageDelegate delegate, final ByteBuffer data) throws AMQException - { - super(delegate, data!=null); - - try - { - _readData = read(data); - } - catch (IOException e) - { - _exception = e; - } - catch (ClassNotFoundException e) - { - _exception = e; - } - } - - public void clearBody() throws JMSException - { - super.clearBody(); - _exception = null; - _readData = null; - _data = null; - } - - public String toBodyString() throws JMSException - { - return String.valueOf(getObject()); - } - - public String getMimeType() - { - return MIME_TYPE; - } - - @Override - public ByteBuffer getData() throws JMSException - { - if(_exception != null) - { - final MessageFormatException messageFormatException = - new MessageFormatException("Unable to deserialize message"); - messageFormatException.setLinkedException(_exception); - throw messageFormatException; - } - if(_readData == null) - { - - return _data == null ? EMPTY_BYTE_BUFFER : _data.duplicate(); - } - else - { - try - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(DEFAULT_OUTPUT_BUFFER_SIZE); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(_readData); - oos.flush(); - return ByteBuffer.wrap(baos.toByteArray()); - } - catch (IOException e) - { - final JMSException jmsException = new JMSException("Unable to encode object of type: " + - _readData.getClass().getName() + ", value " + _readData); - jmsException.setLinkedException(e); - throw jmsException; - } - } - } - - public void setObject(Serializable serializable) throws JMSException - { - checkWritable(); - clearBody(); - - try - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(DEFAULT_OUTPUT_BUFFER_SIZE); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(serializable); - oos.flush(); - _data = ByteBuffer.wrap(baos.toByteArray()); - } - catch (IOException e) - { - final JMSException jmsException = new JMSException("Unable to encode object of type: " + - serializable.getClass().getName() + ", value " + serializable); - jmsException.setLinkedException(e); - throw jmsException; - } - - } - - public Serializable getObject() throws JMSException - { - if(_exception != null) - { - final MessageFormatException messageFormatException = new MessageFormatException("Unable to deserialize message"); - messageFormatException.setLinkedException(_exception); - throw messageFormatException; - } - else if(_readData != null || _data == null) - { - return _readData; - } - else - { - Exception exception = null; - - final ByteBuffer data = _data.duplicate(); - try - { - return read(data); - } - catch (ClassNotFoundException e) - { - exception = e; - } - catch (IOException e) - { - exception = e; - } - - JMSException jmsException = new JMSException("Could not deserialize object"); - jmsException.setLinkedException(exception); - throw jmsException; - } - - } - - private Serializable read(final ByteBuffer data) throws IOException, ClassNotFoundException - { - Serializable result = null; - if (data != null && data.hasRemaining()) - { - ClassLoadingAwareObjectInputStream in = new ClassLoadingAwareObjectInputStream(new ByteBufferInputStream(data)); - try - { - result = (Serializable) in.readObject(); - } - finally - { - in.close(); - } - } - return result; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSObjectMessageFactory.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSObjectMessageFactory.java deleted file mode 100644 index a1727811ae..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSObjectMessageFactory.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.client.message; - -import org.apache.qpid.AMQException; - -import javax.jms.JMSException; -import java.nio.ByteBuffer; - -public class JMSObjectMessageFactory extends AbstractJMSMessageFactory -{ - protected AbstractJMSMessage createMessage(AMQMessageDelegate delegate, ByteBuffer data) throws AMQException - { - return new JMSObjectMessage(delegate, data); - } - - public AbstractJMSMessage createMessage(AMQMessageDelegateFactory delegateFactory) throws JMSException - { - return new JMSObjectMessage(delegateFactory); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSStreamMessage.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSStreamMessage.java deleted file mode 100644 index 223facbb59..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSStreamMessage.java +++ /dev/null @@ -1,378 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 java.io.EOFException; -import java.nio.ByteBuffer; -import javax.jms.JMSException; -import javax.jms.MessageEOFException; -import javax.jms.MessageFormatException; -import javax.jms.StreamMessage; -import org.apache.qpid.AMQException; -import org.apache.qpid.typedmessage.TypedBytesContentReader; -import org.apache.qpid.typedmessage.TypedBytesContentWriter; -import org.apache.qpid.typedmessage.TypedBytesFormatException; - -/** - * @author Apache Software Foundation - */ -public class JMSStreamMessage extends AbstractBytesTypedMessage implements StreamMessage -{ - public static final String MIME_TYPE="jms/stream-message"; - - - private TypedBytesContentReader _typedBytesContentReader; - private TypedBytesContentWriter _typedBytesContentWriter; - - public JMSStreamMessage(AMQMessageDelegateFactory delegateFactory) - { - super(delegateFactory,false); - _typedBytesContentWriter = new TypedBytesContentWriter(); - - } - - JMSStreamMessage(AMQMessageDelegateFactory delegateFactory, ByteBuffer data) throws AMQException - { - super(delegateFactory, data!=null); - _typedBytesContentWriter = new TypedBytesContentWriter(); - - } - - JMSStreamMessage(AMQMessageDelegate delegate, ByteBuffer data) throws AMQException - { - super(delegate, data!=null); - _typedBytesContentReader = new TypedBytesContentReader(data); - } - - public void reset() - { - setReadable(true); - - if(_typedBytesContentReader != null) - { - _typedBytesContentReader.reset(); - } - else if (_typedBytesContentWriter != null) - { - _typedBytesContentReader = new TypedBytesContentReader(_typedBytesContentWriter.getData()); - } - } - - @Override - public void clearBody() throws JMSException - { - super.clearBody(); - _typedBytesContentReader = null; - _typedBytesContentWriter = new TypedBytesContentWriter(); - - } - - - protected String getMimeType() - { - return MIME_TYPE; - } - - @Override - public java.nio.ByteBuffer getData() throws JMSException - { - return _typedBytesContentWriter == null ? _typedBytesContentReader.getData() : _typedBytesContentWriter.getData(); - } - - public boolean readBoolean() throws JMSException - { - checkReadable(); - try - { - return _typedBytesContentReader.readBoolean(); - } - catch (EOFException e) - { - throw new MessageEOFException(e.getMessage()); - } - catch (TypedBytesFormatException e) - { - throw new MessageFormatException(e.getMessage()); - } - } - - - public byte readByte() throws JMSException - { - checkReadable(); - try - { - return _typedBytesContentReader.readByte(); - } - catch (EOFException e) - { - throw new MessageEOFException(e.getMessage()); - } - catch (TypedBytesFormatException e) - { - throw new MessageFormatException(e.getMessage()); - } - } - - public short readShort() throws JMSException - { - checkReadable(); - try - { - return _typedBytesContentReader.readShort(); - } - catch (EOFException e) - { - throw new MessageEOFException(e.getMessage()); - } - catch (TypedBytesFormatException e) - { - throw new MessageFormatException(e.getMessage()); - } - } - - /** - * Note that this method reads a unicode character as two bytes from the stream - * - * @return the character read from the stream - * @throws JMSException - */ - public char readChar() throws JMSException - { - checkReadable(); - try - { - return _typedBytesContentReader.readChar(); - } - catch (EOFException e) - { - throw new MessageEOFException(e.getMessage()); - } - catch (TypedBytesFormatException e) - { - throw new MessageFormatException(e.getMessage()); - } - } - - public int readInt() throws JMSException - { - checkReadable(); - try - { - return _typedBytesContentReader.readInt(); - } - catch (EOFException e) - { - throw new MessageEOFException(e.getMessage()); - } - catch (TypedBytesFormatException e) - { - throw new MessageFormatException(e.getMessage()); - } - } - - public long readLong() throws JMSException - { - checkReadable(); - try - { - return _typedBytesContentReader.readLong(); - } - catch (EOFException e) - { - throw new MessageEOFException(e.getMessage()); - } - catch (TypedBytesFormatException e) - { - throw new MessageFormatException(e.getMessage()); - } - } - - public float readFloat() throws JMSException - { - checkReadable(); - try - { - return _typedBytesContentReader.readFloat(); - } - catch (EOFException e) - { - throw new MessageEOFException(e.getMessage()); - } - catch (TypedBytesFormatException e) - { - throw new MessageFormatException(e.getMessage()); - } - } - - public double readDouble() throws JMSException - { - checkReadable(); - try - { - return _typedBytesContentReader.readDouble(); - } - catch (EOFException e) - { - throw new MessageEOFException(e.getMessage()); - } - catch (TypedBytesFormatException e) - { - throw new MessageFormatException(e.getMessage()); - } - } - - public String readString() throws JMSException - { - checkReadable(); - try - { - return _typedBytesContentReader.readString(); - } - catch (EOFException e) - { - throw new MessageEOFException(e.getMessage()); - } - catch (TypedBytesFormatException e) - { - throw new MessageFormatException(e.getMessage()); - } - } - - public int readBytes(byte[] bytes) throws JMSException - { - if(bytes == null) - { - throw new IllegalArgumentException("Must provide non-null array to read into"); - } - - checkReadable(); - try - { - return _typedBytesContentReader.readBytes(bytes); - } - catch (EOFException e) - { - throw new MessageEOFException(e.getMessage()); - } - catch (TypedBytesFormatException e) - { - throw new MessageFormatException(e.getMessage()); - } - } - - - public Object readObject() throws JMSException - { - checkReadable(); - try - { - return _typedBytesContentReader.readObject(); - } - catch (EOFException e) - { - throw new MessageEOFException(e.getMessage()); - } - catch (TypedBytesFormatException e) - { - throw new MessageFormatException(e.getMessage()); - } - } - - public void writeBoolean(boolean b) throws JMSException - { - checkWritable(); - _typedBytesContentWriter.writeBoolean(b); - } - - public void writeByte(byte b) throws JMSException - { - checkWritable(); - _typedBytesContentWriter.writeByte(b); - } - - public void writeShort(short i) throws JMSException - { - checkWritable(); - _typedBytesContentWriter.writeShort(i); - } - - public void writeChar(char c) throws JMSException - { - checkWritable(); - _typedBytesContentWriter.writeChar(c); - } - - public void writeInt(int i) throws JMSException - { - checkWritable(); - _typedBytesContentWriter.writeInt(i); - } - - public void writeLong(long l) throws JMSException - { - checkWritable(); - _typedBytesContentWriter.writeLong(l); - } - - public void writeFloat(float v) throws JMSException - { - checkWritable(); - _typedBytesContentWriter.writeFloat(v); - } - - public void writeDouble(double v) throws JMSException - { - checkWritable(); - _typedBytesContentWriter.writeDouble(v); - } - - public void writeString(String string) throws JMSException - { - checkWritable(); - _typedBytesContentWriter.writeString(string); - } - - public void writeBytes(byte[] bytes) throws JMSException - { - checkWritable(); - _typedBytesContentWriter.writeBytes(bytes); - } - - public void writeBytes(byte[] bytes, int offset, int length) throws JMSException - { - checkWritable(); - _typedBytesContentWriter.writeBytes(bytes, offset, length); - } - - public void writeObject(Object object) throws JMSException - { - checkWritable(); - try - { - _typedBytesContentWriter.writeObject(object); - } - catch (TypedBytesFormatException e) - { - throw new MessageFormatException(e.getMessage()); - } - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSStreamMessageFactory.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSStreamMessageFactory.java deleted file mode 100644 index 56fa8e5e38..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSStreamMessageFactory.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.client.message; - -import org.apache.qpid.AMQException; - -import javax.jms.JMSException; -import java.nio.ByteBuffer; - -public class JMSStreamMessageFactory extends AbstractJMSMessageFactory -{ - protected AbstractJMSMessage createMessage(AMQMessageDelegate delegate, ByteBuffer data) throws AMQException - { - return new JMSStreamMessage(delegate, data); - } - public AbstractJMSMessage createMessage(AMQMessageDelegateFactory delegateFactory) throws JMSException - { - return new JMSStreamMessage(delegateFactory); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSTextMessage.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSTextMessage.java deleted file mode 100644 index 097a3bb5c0..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSTextMessage.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.client.message; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.CustomJMSXProperty; - -import javax.jms.JMSException; -import javax.jms.MessageFormatException; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CharsetEncoder; - -public class JMSTextMessage extends AbstractJMSMessage implements javax.jms.TextMessage -{ - private static final String MIME_TYPE = "text/plain"; - - private Exception _exception; - private String _decodedValue; - - /** - * This constant represents the name of a property that is set when the message payload is null. - */ - private static final String PAYLOAD_NULL_PROPERTY = CustomJMSXProperty.JMS_AMQP_NULL.toString(); - private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); - - private CharsetDecoder _decoder = DEFAULT_CHARSET.newDecoder(); - private CharsetEncoder _encoder = DEFAULT_CHARSET.newEncoder(); - - private static final ByteBuffer EMPTY_BYTE_BUFFER = ByteBuffer.allocate(0); - - public JMSTextMessage(AMQMessageDelegateFactory delegateFactory) throws JMSException - { - super(delegateFactory, false); // this instantiates a content header - } - - JMSTextMessage(AMQMessageDelegate delegate, ByteBuffer data) - throws AMQException - { - super(delegate, data!=null); - - try - { - if(propertyExists(PAYLOAD_NULL_PROPERTY)) - { - _decodedValue = null; - } - else - { - _decodedValue = _decoder.decode(data).toString(); - } - } - catch (CharacterCodingException e) - { - _exception = e; - } - catch (JMSException e) - { - _exception = e; - } - - } - - public String toBodyString() throws JMSException - { - return getText(); - } - - protected String getMimeType() - { - return MIME_TYPE; - } - - @Override - public ByteBuffer getData() throws JMSException - { - _encoder.reset(); - try - { - if(_exception != null) - { - final MessageFormatException messageFormatException = new MessageFormatException("Cannot decode original message"); - messageFormatException.setLinkedException(_exception); - throw messageFormatException; - } - else if(_decodedValue == null) - { - return EMPTY_BYTE_BUFFER; - } - else - { - return _encoder.encode(CharBuffer.wrap(_decodedValue)); - } - } - catch (CharacterCodingException e) - { - final JMSException jmsException = new JMSException("Cannot encode string in UFT-8: " + _decodedValue); - jmsException.setLinkedException(e); - throw jmsException; - } - } - - @Override - public void clearBody() throws JMSException - { - super.clearBody(); - _decodedValue = null; - _exception = null; - } - - public void setText(String text) throws JMSException - { - checkWritable(); - - clearBody(); - _decodedValue = text; - - } - - public String getText() throws JMSException - { - return _decodedValue; - } - - @Override - public void prepareForSending() throws JMSException - { - super.prepareForSending(); - if (_decodedValue == null) - { - setBooleanProperty(PAYLOAD_NULL_PROPERTY, true); - } - else - { - removeProperty(PAYLOAD_NULL_PROPERTY); - } - } - - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSTextMessageFactory.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSTextMessageFactory.java deleted file mode 100644 index 0b28e6ca85..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/JMSTextMessageFactory.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.client.message; - -import org.apache.qpid.AMQException; - -import javax.jms.JMSException; -import java.nio.ByteBuffer; - -public class JMSTextMessageFactory extends AbstractJMSMessageFactory -{ - - public AbstractJMSMessage createMessage(AMQMessageDelegateFactory delegateFactory) throws JMSException - { - return new JMSTextMessage(delegateFactory); - } - - protected AbstractJMSMessage createMessage(AMQMessageDelegate delegate, ByteBuffer data) throws AMQException - { - return new JMSTextMessage(delegate, data); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/MessageConverter.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/MessageConverter.java deleted file mode 100644 index 5abd02f150..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/MessageConverter.java +++ /dev/null @@ -1,202 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.client.AMQSession; - -import javax.jms.BytesMessage; -import javax.jms.JMSException; -import javax.jms.MapMessage; -import javax.jms.Message; -import javax.jms.MessageEOFException; -import javax.jms.ObjectMessage; -import javax.jms.StreamMessage; -import javax.jms.TextMessage; -import java.util.Enumeration; - -public class MessageConverter -{ - - /** - * Log4J logger - */ - private final Logger _logger = LoggerFactory.getLogger(getClass()); - - /** - * AbstractJMSMessage which will hold the converted message - */ - private AbstractJMSMessage _newMessage; - - public MessageConverter(AbstractJMSMessage message) throws JMSException - { - _newMessage = message; - } - - public MessageConverter(AMQSession session, BytesMessage bytesMessage) throws JMSException - { - bytesMessage.reset(); - - JMSBytesMessage nativeMsg = (JMSBytesMessage) session.createBytesMessage(); - - byte[] buf = new byte[1024]; - - int len; - - while ((len = bytesMessage.readBytes(buf)) != -1) - { - nativeMsg.writeBytes(buf, 0, len); - } - - _newMessage = nativeMsg; - setMessageProperties(bytesMessage); - } - - public MessageConverter(AMQSession session, MapMessage message) throws JMSException - { - MapMessage nativeMessage = session.createMapMessage(); - - Enumeration mapNames = message.getMapNames(); - while (mapNames.hasMoreElements()) - { - String name = (String) mapNames.nextElement(); - nativeMessage.setObject(name, message.getObject(name)); - } - - _newMessage = (AbstractJMSMessage) nativeMessage; - setMessageProperties(message); - } - - public MessageConverter(AMQSession session, ObjectMessage origMessage) throws JMSException - { - - ObjectMessage nativeMessage = session.createObjectMessage(); - - nativeMessage.setObject(origMessage.getObject()); - - _newMessage = (AbstractJMSMessage) nativeMessage; - setMessageProperties(origMessage); - - } - - public MessageConverter(AMQSession session, TextMessage message) throws JMSException - { - TextMessage nativeMessage = session.createTextMessage(); - - nativeMessage.setText(message.getText()); - - _newMessage = (AbstractJMSMessage) nativeMessage; - setMessageProperties(message); - } - - public MessageConverter(AMQSession session, StreamMessage message) throws JMSException - { - StreamMessage nativeMessage = session.createStreamMessage(); - - try - { - message.reset(); - while (true) - { - nativeMessage.writeObject(message.readObject()); - } - } - catch (MessageEOFException e) - { - // we're at the end so don't mind the exception - } - - _newMessage = (AbstractJMSMessage) nativeMessage; - setMessageProperties(message); - } - - public MessageConverter(AMQSession session, Message message) throws JMSException - { - // Send a message with just properties. - // Throwing away content - Message nativeMessage = session.createMessage(); - - _newMessage = (AbstractJMSMessage) nativeMessage; - setMessageProperties(message); - } - - public AbstractJMSMessage getConvertedMessage() - { - return _newMessage; - } - - /** - * Sets all message properties - */ - protected void setMessageProperties(Message message) throws JMSException - { - setNonJMSProperties(message); - setJMSProperties(message); - } - - /** - * Sets all non-JMS defined properties on converted message - */ - protected void setNonJMSProperties(Message message) throws JMSException - { - Enumeration propertyNames = message.getPropertyNames(); - while (propertyNames.hasMoreElements()) - { - String propertyName = String.valueOf(propertyNames.nextElement()); - // TODO: Shouldn't need to check for JMS properties here as don't think getPropertyNames() should return them - if (!propertyName.startsWith("JMSX_")) - { - Object value = message.getObjectProperty(propertyName); - _newMessage.setObjectProperty(propertyName, value); - } - } - } - - /** - * Exposed JMS defined properties on converted message: - * JMSDestination - we don't set here - * JMSDeliveryMode - set - * JMSExpiration - we don't set here - * JMSPriority - we don't set here - * JMSMessageID - we don't set here - * JMSTimestamp - we don't set here - * JMSCorrelationID - set - * JMSReplyTo - set - * JMSType - set - * JMSRedlivered - we don't set here - */ - protected void setJMSProperties(Message message) throws JMSException - { - _newMessage.setJMSDeliveryMode(message.getJMSDeliveryMode()); - - if (message.getJMSReplyTo() != null) - { - _newMessage.setJMSReplyTo(message.getJMSReplyTo()); - } - - _newMessage.setJMSType(message.getJMSType()); - - _newMessage.setJMSCorrelationID(message.getJMSCorrelationID()); - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/MessageFactory.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/MessageFactory.java deleted file mode 100644 index b073275421..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/MessageFactory.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.client.message; - -import java.util.List; - -import javax.jms.JMSException; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.AMQQueue; -import org.apache.qpid.client.AMQSession_0_8; -import org.apache.qpid.client.AMQTopic; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.transport.MessageProperties; - - -public interface MessageFactory -{ - AbstractJMSMessage createMessage(long deliveryTag, - boolean redelivered, - ContentHeaderBody contentHeader, - AMQShortString exchange, - AMQShortString routingKey, - List bodies, - AMQSession_0_8.DestinationCache<AMQQueue> queueDestinationCache, - AMQSession_0_8.DestinationCache<AMQTopic> topicDestinationCache, - final int addressType) - throws JMSException, AMQException; - - AbstractJMSMessage createMessage(long deliveryTag, boolean redelivered, - MessageProperties msgProps, - DeliveryProperties deliveryProps, - java.nio.ByteBuffer body) - throws JMSException, AMQException; - - AbstractJMSMessage createMessage(AMQMessageDelegateFactory delegateFactory) throws JMSException; -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/MessageFactoryRegistry.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/MessageFactoryRegistry.java deleted file mode 100644 index de46887895..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/MessageFactoryRegistry.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.jms.JMSException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.AMQQueue; -import org.apache.qpid.client.AMQSession_0_8; -import org.apache.qpid.client.AMQTopic; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.transport.MessageProperties; -import org.apache.qpid.transport.MessageTransfer; - -public class MessageFactoryRegistry -{ - /** - * This class logger - */ - private final Logger _logger = LoggerFactory.getLogger(getClass()); - - private final Map<String, MessageFactory> _mimeStringToFactoryMap = new HashMap<String, MessageFactory>(); - private final Map<AMQShortString, MessageFactory> _mimeShortStringToFactoryMap = - new HashMap<AMQShortString, MessageFactory>(); - private final MessageFactory _default = new JMSBytesMessageFactory(); - - /** - * Construct a new registry with the default message factories registered - * - * @return a message factory registry - */ - public static MessageFactoryRegistry newDefaultRegistry() - { - MessageFactoryRegistry mf = new MessageFactoryRegistry(); - mf.registerFactory(JMSMapMessage.MIME_TYPE, new JMSMapMessageFactory()); - mf.registerFactory("text/plain", new JMSTextMessageFactory()); - mf.registerFactory("text/xml", new JMSTextMessageFactory()); - mf.registerFactory(JMSBytesMessage.MIME_TYPE, new JMSBytesMessageFactory()); - mf.registerFactory(JMSObjectMessage.MIME_TYPE, new JMSObjectMessageFactory()); - mf.registerFactory(JMSStreamMessage.MIME_TYPE, new JMSStreamMessageFactory()); - mf.registerFactory(AMQPEncodedMapMessage.MIME_TYPE, new AMQPEncodedMapMessageFactory()); - mf.registerFactory(AMQPEncodedListMessage.MIME_TYPE, new AMQPEncodedListMessageFactory()); - mf.registerFactory(null, mf._default); - - return mf; - } - - - public void registerFactory(String mimeType, MessageFactory mf) - { - if (mf == null) - { - throw new IllegalArgumentException("Message factory must not be null"); - } - - _mimeStringToFactoryMap.put(mimeType, mf); - _mimeShortStringToFactoryMap.put(new AMQShortString(mimeType), mf); - } - - public MessageFactory deregisterFactory(String mimeType) - { - _mimeShortStringToFactoryMap.remove(new AMQShortString(mimeType)); - - return _mimeStringToFactoryMap.remove(mimeType); - } - - /** - * Create a message. This looks up the MIME type from the content header and instantiates the appropriate - * concrete message type. - * - * @param deliveryTag the AMQ message id - * @param redelivered true if redelivered - * @param contentHeader the content header that was received - * @param bodies a list of ContentBody instances @return the message. - * @param queueDestinationCache - * @param topicDestinationCache @throws AMQException - * @param addressType - * @throws JMSException - */ - public AbstractJMSMessage createMessage(long deliveryTag, - boolean redelivered, - AMQShortString exchange, - AMQShortString routingKey, - ContentHeaderBody contentHeader, - List bodies, - AMQSession_0_8.DestinationCache<AMQQueue> queueDestinationCache, - AMQSession_0_8.DestinationCache<AMQTopic> topicDestinationCache, - final int addressType) - throws AMQException, JMSException - { - BasicContentHeaderProperties properties = contentHeader.getProperties(); - - // Get the message content type. This may be null for pure AMQP messages, but will always be set for JMS over - // AMQP. When the type is null, it can only be assumed that the message is a byte message. - AMQShortString contentTypeShortString = properties.getContentType(); - contentTypeShortString = (contentTypeShortString == null) ? new AMQShortString( - JMSBytesMessage.MIME_TYPE) : contentTypeShortString; - - MessageFactory mf = _mimeShortStringToFactoryMap.get(contentTypeShortString); - if (mf == null) - { - mf = _default; - } - - return mf.createMessage(deliveryTag, redelivered, contentHeader, exchange, routingKey, bodies, queueDestinationCache, topicDestinationCache, addressType); - } - - public AbstractJMSMessage createMessage(MessageTransfer transfer) throws AMQException, JMSException - { - - MessageProperties mprop = transfer.getHeader().getMessageProperties(); - String messageType = ""; - if ( mprop == null || mprop.getContentType() == null) - { - _logger.debug("no message type specified, building a byte message"); - messageType = JMSBytesMessage.MIME_TYPE; - } - else - { - messageType = mprop.getContentType(); - } - MessageFactory mf = _mimeStringToFactoryMap.get(messageType); - if (mf == null) - { - mf = _default; - } - - boolean redelivered = false; - DeliveryProperties deliverProps; - if((deliverProps = transfer.getHeader().getDeliveryProperties()) != null) - { - redelivered = deliverProps.getRedelivered(); - } - return mf.createMessage(transfer.getId(), - redelivered, - mprop == null? new MessageProperties():mprop, - deliverProps == null? new DeliveryProperties():deliverProps, - transfer.getBody()); - } - - - public AbstractJMSMessage createMessage(AMQMessageDelegateFactory delegateFactory, String mimeType) throws AMQException, JMSException - { - if (mimeType == null) - { - throw new IllegalArgumentException("Mime type must not be null"); - } - - MessageFactory mf = _mimeStringToFactoryMap.get(mimeType); - if (mf == null) - { - mf = _default; - } - - return mf.createMessage(delegateFactory); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/QpidMessageProperties.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/QpidMessageProperties.java deleted file mode 100644 index 254980d554..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/QpidMessageProperties.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.client.message; - -/** - * Place holder for Qpid specific message properties - */ -public class QpidMessageProperties -{ - private QpidMessageProperties() - { - } - - public static final String QPID_SUBJECT = "qpid.subject"; - public static final String QPID_SUBJECT_JMS_PROPERTY = "JMS_qpid_subject"; - public static final String QPID_SUBJECT_JMS_PROPER = QPID_SUBJECT_JMS_PROPERTY.substring(4); - - // AMQP 0-10 related properties - public static final String AMQP_0_10_APP_ID = "x-amqp-0-10.app-id"; - public static final String AMQP_0_10_ROUTING_KEY = "x-amqp-0-10.routing-key"; -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/ReturnMessage.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/ReturnMessage.java deleted file mode 100644 index e253e43a86..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/ReturnMessage.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.client.message; - - -import org.apache.qpid.framing.AMQShortString; - -public class ReturnMessage extends UnprocessedMessage_0_8 -{ - final private AMQShortString _replyText; - final private int _replyCode; - - public ReturnMessage(AMQShortString exchange, AMQShortString routingKey, AMQShortString replyText, int replyCode) - { - super(-1,0,exchange,routingKey,false); - _replyText = replyText; - _replyCode = replyCode; - } - - public int getReplyCode() - { - return _replyCode; - } - - public AMQShortString getReplyText() - { - return _replyText; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage.java deleted file mode 100644 index bb0e3b447f..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage.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.client.message; - -import org.apache.qpid.client.AMQSession; - - -/** - * This class contains everything needed to process a JMS message. It assembles the deliver body, the content header and - * the content body/ies. - * - * Note that the actual work of creating a JMS message for the client code's use is done outside of the MINA dispatcher - * thread in order to minimise the amount of work done in the MINA dispatcher thread. - */ -public abstract class UnprocessedMessage implements AMQSession.Dispatchable -{ - private final int _consumerTag; - - - public UnprocessedMessage(int consumerTag) - { - _consumerTag = consumerTag; - } - - - abstract public long getDeliveryTag(); - - - public int getConsumerTag() - { - return _consumerTag; - } - - public void dispatch(AMQSession ssn) - { - ssn.dispatch(this); - } - -}
\ No newline at end of file diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage_0_10.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage_0_10.java deleted file mode 100644 index f31bc88509..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage_0_10.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.client.message; - -import org.apache.qpid.transport.MessageTransfer; - -/** - * This class contains everything needed to process a JMS message. It assembles the deliver body, the content header and - * the content body/ies. - * - * Note that the actual work of creating a JMS message for the client code's use is done outside of the MINA dispatcher - * thread in order to minimise the amount of work done in the MINA dispatcher thread. - */ -public class UnprocessedMessage_0_10 extends UnprocessedMessage -{ - private MessageTransfer _transfer; - - public UnprocessedMessage_0_10(MessageTransfer xfr) - { - super(Integer.parseInt(xfr.getDestination())); - _transfer = xfr; - } - - // additional 0_10 method - - public long getDeliveryTag() - { - return _transfer.getId(); - } - - public MessageTransfer getMessageTransfer() - { - return _transfer; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage_0_8.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage_0_8.java deleted file mode 100644 index 5ed98dc8ea..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage_0_8.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicDeliverBody; -import org.apache.qpid.framing.ContentBody; -import org.apache.qpid.framing.ContentHeaderBody; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * This class contains everything needed to process a JMS message. It assembles the deliver body, the content header and - * the content body/ies. - * - * Note that the actual work of creating a JMS message for the client code's use is done outside of the MINA dispatcher - * thread in order to minimise the amount of work done in the MINA dispatcher thread. - */ -public class UnprocessedMessage_0_8 extends UnprocessedMessage -{ - private long _bytesReceived = 0; - - - private AMQShortString _exchange; - private AMQShortString _routingKey; - private final long _deliveryId; - private boolean _redelivered; - - private BasicDeliverBody _deliverBody; - private ContentHeaderBody _contentHeader; - - /** List of ContentBody instances. Due to fragmentation you don't know how big this will be in general */ - private List<ContentBody> _bodies; - - public UnprocessedMessage_0_8(long deliveryId, int consumerTag, AMQShortString exchange, AMQShortString routingKey, boolean redelivered) - { - super(consumerTag); - _exchange = exchange; - _routingKey = routingKey; - - _redelivered = redelivered; - _deliveryId = deliveryId; - } - - - public AMQShortString getExchange() - { - return _exchange; - } - - public AMQShortString getRoutingKey() - { - return _routingKey; - } - - public long getDeliveryTag() - { - return _deliveryId; - } - - public boolean isRedelivered() - { - return _redelivered; - } - - - public void receiveBody(ContentBody body) - { - - if (body.getPayload() != null) - { - final long payloadSize = body.getPayload().length; - - if (_bodies == null) - { - if (payloadSize == getContentHeader().getBodySize()) - { - _bodies = Collections.singletonList(body); - } - else - { - _bodies = new ArrayList<ContentBody>(); - _bodies.add(body); - } - - } - else - { - _bodies.add(body); - } - _bytesReceived += payloadSize; - } - } - - public void setMethodBody(BasicDeliverBody deliverBody) - { - _deliverBody = deliverBody; - } - - public void setContentHeader(ContentHeaderBody contentHeader) - { - this._contentHeader = contentHeader; - } - - public boolean isAllBodyDataReceived() - { - return _bytesReceived == getContentHeader().getBodySize(); - } - - public BasicDeliverBody getDeliverBody() - { - return _deliverBody; - } - - public ContentHeaderBody getContentHeader() - { - return _contentHeader; - } - - public List<ContentBody> getBodies() - { - return _bodies; - } - - public String toString() - { - StringBuilder buf = new StringBuilder(); - - if (_contentHeader != null) - { - buf.append("ContentHeader " + _contentHeader); - } - if(_deliverBody != null) - { - buf.append("Delivery tag " + _deliverBody.getDeliveryTag()); - buf.append("Consumer tag " + _deliverBody.getConsumerTag()); - buf.append("Deliver Body " + _deliverBody); - } - - return buf.toString(); - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/messaging/address/AddressHelper.java b/qpid/java/client/src/main/java/org/apache/qpid/client/messaging/address/AddressHelper.java deleted file mode 100644 index 81ccaee1f3..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/messaging/address/AddressHelper.java +++ /dev/null @@ -1,307 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.messaging.address; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import org.apache.qpid.client.AMQDestination; -import org.apache.qpid.client.AMQDestination.Binding; -import org.apache.qpid.client.messaging.address.Link.Reliability; -import org.apache.qpid.client.messaging.address.Link.Subscription; -import org.apache.qpid.client.messaging.address.Link.SubscriptionQueue; -import org.apache.qpid.configuration.Accessor; -import org.apache.qpid.configuration.Accessor.MapAccessor; -import org.apache.qpid.messaging.Address; - -/** - * Utility class for extracting information from the address class - */ -public class AddressHelper -{ - public static final String NODE = "node"; - public static final String LINK = "link"; - public static final String X_DECLARE = "x-declare"; - public static final String X_BINDINGS = "x-bindings"; - public static final String X_SUBSCRIBES = "x-subscribes"; - public static final String X_SUBSCRIBE = "x-subscribe"; - public static final String CREATE = "create"; - public static final String ASSERT = "assert"; - public static final String DELETE = "delete"; - public static final String FILTER = "filter"; - public static final String NO_LOCAL = "no-local"; - public static final String DURABLE = "durable"; - public static final String EXCLUSIVE = "exclusive"; - public static final String AUTO_DELETE = "auto-delete"; - public static final String TYPE = "type"; - public static final String ALT_EXCHANGE = "alternate-exchange"; - public static final String BINDINGS = "bindings"; - public static final String BROWSE = "browse"; - public static final String MODE = "mode"; - public static final String CAPACITY = "capacity"; - public static final String CAPACITY_SOURCE = "source"; - public static final String CAPACITY_TARGET = "target"; - public static final String NAME = "name"; - public static final String EXCHANGE = "exchange"; - public static final String QUEUE = "queue"; - public static final String KEY = "key"; - public static final String ARGUMENTS = "arguments"; - public static final String RELIABILITY = "reliability"; - - private Address _address; - private Accessor _addressPropAccess; - private Accessor _nodePropAccess; - private Accessor _linkPropAccess; - private Map _addressPropMap; - private Map _nodePropMap; - private Map _linkPropMap; - - public AddressHelper(Address address) - { - this._address = address; - this._addressPropMap = address.getOptions(); - this._addressPropAccess = new MapAccessor(_addressPropMap); - this._nodePropMap = address.getOptions() == null - || address.getOptions().get(NODE) == null ? null - : (Map) address.getOptions().get(NODE); - - if (_nodePropMap != null) - { - _nodePropAccess = new MapAccessor(_nodePropMap); - } - - this._linkPropMap = address.getOptions() == null - || address.getOptions().get(LINK) == null ? null - : (Map) address.getOptions().get(LINK); - - if (_linkPropMap != null) - { - _linkPropAccess = new MapAccessor(_linkPropMap); - } - } - - public String getCreate() - { - return _addressPropAccess.getString(CREATE); - } - - public String getAssert() - { - return _addressPropAccess.getString(ASSERT); - } - - public String getDelete() - { - return _addressPropAccess.getString(DELETE); - } - - public boolean isBrowseOnly() - { - String mode = _addressPropAccess.getString(MODE); - return mode != null && mode.equals(BROWSE) ? true : false; - } - - @SuppressWarnings("unchecked") - public List<Binding> getBindings(Map props) - { - List<Map> bindingList = (props == null) ? Collections.EMPTY_LIST : (List<Map>) props.get(X_BINDINGS); - if (bindingList != null && !bindingList.isEmpty()) - { - List<Binding> bindings = new ArrayList<Binding>(bindingList.size()); - for (Map bindingMap : bindingList) - { - Binding binding = new Binding( - (String) bindingMap.get(EXCHANGE), - (String) bindingMap.get(QUEUE), - (String) bindingMap.get(KEY), - bindingMap.get(ARGUMENTS) == null ? Collections.EMPTY_MAP - : (Map<String, Object>) bindingMap - .get(ARGUMENTS)); - bindings.add(binding); - } - return bindings; - } - else - { - return Collections.emptyList(); - } - } - - public Map getDeclareArgs(Map props) - { - if (props != null && props.get(X_DECLARE) != null) - { - return (Map) props.get(X_DECLARE); - - } else - { - return Collections.EMPTY_MAP; - } - } - - public int getNodeType() - { - if (_nodePropAccess == null || _nodePropAccess.getString(TYPE) == null) - { - // need to query and figure out - return AMQDestination.UNKNOWN_TYPE; - } - else if (_nodePropAccess.getString(TYPE).equals("queue")) - { - return AMQDestination.QUEUE_TYPE; - } - else if (_nodePropAccess.getString(TYPE).equals("topic")) - { - return AMQDestination.TOPIC_TYPE; - } - else - { - throw new IllegalArgumentException("unknown exchange type"); - } - } - - public Node getNode() - { - Node node = new Node(_address.getName()); - if (_nodePropAccess != null) - { - Map xDeclareMap = getDeclareArgs(_nodePropMap); - MapAccessor xDeclareMapAccessor = new MapAccessor(xDeclareMap); - - node.setDurable(getBooleanProperty(_nodePropAccess,DURABLE,false)); - node.setAutoDelete(getBooleanProperty(xDeclareMapAccessor,AUTO_DELETE,false)); - node.setExclusive(getBooleanProperty(xDeclareMapAccessor,EXCLUSIVE,false)); - node.setAlternateExchange(xDeclareMapAccessor.getString(ALT_EXCHANGE)); - if (xDeclareMapAccessor.getString(TYPE) != null) - { - node.setExchangeType(xDeclareMapAccessor.getString(TYPE)); - } - node.setBindings(getBindings(_nodePropMap)); - if (!xDeclareMap.isEmpty() && xDeclareMap.containsKey(ARGUMENTS)) - { - node.setDeclareArgs((Map<String,Object>)xDeclareMap.get(ARGUMENTS)); - } - } - return node; - } - - // This should really be in the Accessor interface - private boolean getBooleanProperty(Accessor access, String propName, boolean defaultValue) - { - Boolean result = access.getBoolean(propName); - return (result == null) ? defaultValue : result.booleanValue(); - } - - public Link getLink() - { - Link link = new Link(); - link.setSubscription(new Subscription()); - link.setSubscriptionQueue(new SubscriptionQueue()); - if (_linkPropAccess != null) - { - link.setDurable(getBooleanProperty(_linkPropAccess,DURABLE,false)); - link.setName(_linkPropAccess.getString(NAME)); - - String reliability = _linkPropAccess.getString(RELIABILITY); - if ( reliability != null) - { - if (reliability.equalsIgnoreCase("unreliable")) - { - link.setReliability(Reliability.UNRELIABLE); - } - else if (reliability.equalsIgnoreCase("at-least-once")) - { - link.setReliability(Reliability.AT_LEAST_ONCE); - } - else - { - throw new IllegalArgumentException("The reliability mode '" + - reliability + "' is not yet supported"); - } - } - - if (((Map) _address.getOptions().get(LINK)).get(CAPACITY) instanceof Map) - { - MapAccessor capacityProps = new MapAccessor((Map) ((Map) _address.getOptions().get(LINK)).get(CAPACITY)); - - Integer sourceCapacity = capacityProps.getInt(CAPACITY_SOURCE); - link.setConsumerCapacity(sourceCapacity == null ? -1 : sourceCapacity); - - Integer targetCapacity = capacityProps.getInt(CAPACITY_TARGET); - link.setProducerCapacity(targetCapacity == null ? -1 : targetCapacity); - } - else - { - int cap = _linkPropAccess.getInt(CAPACITY) == null ? -1 : _linkPropAccess.getInt(CAPACITY); - link.setConsumerCapacity(cap); - link.setProducerCapacity(cap); - } - link.setFilter(_linkPropAccess.getString(FILTER)); - // so far filter type not used - - Map linkMap = (Map) _address.getOptions().get(LINK); - - if (linkMap != null) - { - Map x_subscribe = null; - - if(linkMap.containsKey(X_SUBSCRIBE)) - { - x_subscribe = (Map)((Map) _address.getOptions().get(LINK)).get(X_SUBSCRIBE); - } - else if(linkMap.containsKey(X_SUBSCRIBES)) - { - // left in for backwards compatibility with old broken constant - x_subscribe = (Map)((Map) _address.getOptions().get(LINK)).get(X_SUBSCRIBES); - } - - if(x_subscribe != null) - { - if (x_subscribe.containsKey(ARGUMENTS)) - { - link.getSubscription().setArgs((Map<String, Object>) x_subscribe.get(ARGUMENTS)); - } - - boolean exclusive = x_subscribe.containsKey(EXCLUSIVE) ? - Boolean.parseBoolean((String) x_subscribe.get(EXCLUSIVE)) : false; - - link.getSubscription().setExclusive(exclusive); - } - } - - link.setBindings(getBindings(linkMap)); - Map xDeclareMap = getDeclareArgs(linkMap); - SubscriptionQueue queue = link.getSubscriptionQueue(); - if (!xDeclareMap.isEmpty() && xDeclareMap.containsKey(ARGUMENTS)) - { - MapAccessor xDeclareMapAccessor = new MapAccessor(xDeclareMap); - queue.setAutoDelete(getBooleanProperty(xDeclareMapAccessor,AUTO_DELETE,true)); - queue.setExclusive(getBooleanProperty(xDeclareMapAccessor,EXCLUSIVE,true)); - queue.setAlternateExchange(xDeclareMapAccessor.getString(ALT_EXCHANGE)); - queue.setDeclareArgs((Map<String,Object>)xDeclareMap.get(ARGUMENTS)); - } - } - - return link; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/messaging/address/Link.java b/qpid/java/client/src/main/java/org/apache/qpid/client/messaging/address/Link.java deleted file mode 100644 index b40abf3f98..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/messaging/address/Link.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.messaging.address; - -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.qpid.client.AMQDestination.Binding; - -public class Link -{ - public enum FilterType { SQL92, XQUERY, SUBJECT } - - public enum Reliability { UNRELIABLE, AT_MOST_ONCE, AT_LEAST_ONCE, EXACTLY_ONCE } - - private String name; - private String _filter; - private FilterType _filterType = FilterType.SUBJECT; - private boolean _isNoLocal; - private boolean _isDurable; - private int _consumerCapacity = -1; - private int _producerCapacity = -1; - private Subscription subscription; - private Reliability reliability = Reliability.AT_LEAST_ONCE; - private List<Binding> _bindings = Collections.emptyList(); - private SubscriptionQueue _subscriptionQueue; - - public Reliability getReliability() - { - return reliability; - } - - public void setReliability(Reliability reliability) - { - this.reliability = reliability; - } - - public boolean isDurable() - { - return _isDurable; - } - - public void setDurable(boolean durable) - { - _isDurable = durable; - } - - public String getFilter() - { - return _filter; - } - - public void setFilter(String filter) - { - this._filter = filter; - } - - public FilterType getFilterType() - { - return _filterType; - } - - public void setFilterType(FilterType type) - { - _filterType = type; - } - - public boolean isNoLocal() - { - return _isNoLocal; - } - - public void setNoLocal(boolean noLocal) - { - _isNoLocal = noLocal; - } - - public int getConsumerCapacity() - { - return _consumerCapacity; - } - - public void setConsumerCapacity(int capacity) - { - _consumerCapacity = capacity; - } - - public int getProducerCapacity() - { - return _producerCapacity; - } - - public void setProducerCapacity(int capacity) - { - _producerCapacity = capacity; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name; - } - - public Subscription getSubscription() - { - return this.subscription; - } - - public void setSubscription(Subscription subscription) - { - this.subscription = subscription; - } - - public List<Binding> getBindings() - { - return _bindings; - } - - public void setBindings(List<Binding> bindings) - { - _bindings = bindings; - } - - public SubscriptionQueue getSubscriptionQueue() - { - return _subscriptionQueue; - } - - public void setSubscriptionQueue(SubscriptionQueue subscriptionQueue) - { - this._subscriptionQueue = subscriptionQueue; - } - - public static class SubscriptionQueue - { - private Map<String,Object> _declareArgs = new HashMap<String,Object>(); - private boolean _isAutoDelete = true; - private boolean _isExclusive = true; - private String _alternateExchange; - - public Map<String,Object> getDeclareArgs() - { - return _declareArgs; - } - - public void setDeclareArgs(Map<String,Object> options) - { - _declareArgs = options; - } - - public boolean isAutoDelete() - { - return _isAutoDelete; - } - - public void setAutoDelete(boolean autoDelete) - { - _isAutoDelete = autoDelete; - } - - public boolean isExclusive() - { - return _isExclusive; - } - - public void setExclusive(boolean exclusive) - { - _isExclusive = exclusive; - } - - public String getAlternateExchange() - { - return _alternateExchange; - } - - public void setAlternateExchange(String altExchange) - { - _alternateExchange = altExchange; - } - } - - public static class Subscription - { - private Map<String,Object> args = Collections.emptyMap(); - private boolean exclusive = false; - - public Map<String, Object> getArgs() - { - return args; - } - - public void setArgs(Map<String, Object> args) - { - this.args = args; - } - - public boolean isExclusive() - { - return exclusive; - } - - public void setExclusive(boolean exclusive) - { - this.exclusive = exclusive; - } - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/messaging/address/Node.java b/qpid/java/client/src/main/java/org/apache/qpid/client/messaging/address/Node.java deleted file mode 100644 index cc8e11b91a..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/messaging/address/Node.java +++ /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. - * - */ - -package org.apache.qpid.client.messaging.address; - -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.qpid.client.AMQDestination; -import org.apache.qpid.client.AMQDestination.Binding; - -public class Node -{ - private int _nodeType = AMQDestination.UNKNOWN_TYPE; - private String _name; - private boolean _isDurable; - private boolean _isAutoDelete; - private boolean _isExclusive; - private String _alternateExchange; - private String _exchangeType = "topic"; // used when node is an exchange instead of a queue. - private List<Binding> _bindings = Collections.emptyList(); - private Map<String,Object> _declareArgs = new HashMap<String,Object>(); - - protected Node(String name) - { - _name = name; - } - - public String getName() - { - return _name; - } - - public void setNodeType(int nodeType) - { - _nodeType = nodeType; - } - - public int getType() - { - return _nodeType; - } - - public boolean isDurable() - { - return _isDurable; - } - - public void setDurable(boolean durable) - { - _isDurable = durable; - } - - public boolean isExclusive() - { - return _isExclusive; - } - - public void setExclusive(boolean exclusive) - { - _isExclusive = exclusive; - } - - public boolean isAutoDelete() - { - return _isAutoDelete; - } - - public void setAutoDelete(boolean autoDelete) - { - _isAutoDelete = autoDelete; - } - - public String getAlternateExchange() - { - return _alternateExchange; - } - - public void setAlternateExchange(String altExchange) - { - _alternateExchange = altExchange; - } - - public List<Binding> getBindings() - { - return _bindings; - } - - public void setBindings(List<Binding> bindings) - { - _bindings = bindings; - } - - public Map<String,Object> getDeclareArgs() - { - return _declareArgs; - } - - public void setDeclareArgs(Map<String,Object> options) - { - _declareArgs = options; - } - - public void setExchangeType(String type) - { - _exchangeType = type; - } - - public String getExchangeType() - { - return _exchangeType; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/messaging/address/QpidExchangeOptions.java b/qpid/java/client/src/main/java/org/apache/qpid/client/messaging/address/QpidExchangeOptions.java deleted file mode 100644 index 3ad9aff9ea..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/messaging/address/QpidExchangeOptions.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.client.messaging.address; - -import java.util.HashMap; - -public class QpidExchangeOptions extends HashMap<String,Object> -{ - public static final String QPID_MSG_SEQUENCE = "qpid.msg_sequence"; - public static final String QPID_INITIAL_VALUE_EXCHANGE = "qpid.ive"; - public static final String QPID_EXCLUSIVE_BINDING = "qpid.exclusive-binding"; - - public void setMessageSequencing() - { - this.put(QPID_MSG_SEQUENCE, 1); - } - - public void setInitialValueExchange() - { - this.put(QPID_INITIAL_VALUE_EXCHANGE, 1); - } - - public void setExclusiveBinding() - { - this.put(QPID_EXCLUSIVE_BINDING, 1); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/messaging/address/QpidQueueOptions.java b/qpid/java/client/src/main/java/org/apache/qpid/client/messaging/address/QpidQueueOptions.java deleted file mode 100644 index 24295a0832..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/messaging/address/QpidQueueOptions.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.client.messaging.address; - -import java.util.HashMap; - -public class QpidQueueOptions extends HashMap<String,Object> -{ - public static final String QPID_MAX_COUNT = "qpid.max_count"; - public static final String QPID_MAX_SIZE = "qpid.max_size"; - public static final String QPID_POLICY_TYPE = "qpid.policy_type"; - public static final String QPID_LVQ_KEY = "qpid.LVQ_key"; - public static final String QPID_LAST_VALUE_QUEUE = "qpid.last_value_queue"; - public static final String QPID_LAST_VALUE_QUEUE_NO_BROWSE = "qpid.last_value_queue_no_browse"; - - public void validatePolicyType(String type) - { - if (type == null || - !("reject".equals(type) || "flow_to_disk".equals(type) || - "ring".equals(type) || "ring_strict".equals(type))) - { - throw new IllegalArgumentException("Invalid Queue Policy Type" + - " should be one of {reject|flow_to_disk|ring|ring_strict}"); - } - } - - public void setPolicyType(String s) - { - validatePolicyType(s); - this.put(QPID_POLICY_TYPE, s); - } - - public void setMaxCount(Integer i) - { - this.put(QPID_MAX_COUNT, i); - } - - public void setMaxSize(Integer i) - { - this.put(QPID_MAX_SIZE, i); - } - - - public void setOrderingPolicy(String s) - { - if (QpidQueueOptions.QPID_LAST_VALUE_QUEUE.equals(s)) - { - this.put(QPID_LAST_VALUE_QUEUE, 1); - } - else if (QpidQueueOptions.QPID_LAST_VALUE_QUEUE_NO_BROWSE.equals(s)) - { - this.put(QPID_LAST_VALUE_QUEUE_NO_BROWSE,1); - } - else - { - throw new IllegalArgumentException("Invalid Ordering Policy" + - " should be one of {" + QpidQueueOptions.QPID_LAST_VALUE_QUEUE + "|" + - QPID_LAST_VALUE_QUEUE_NO_BROWSE + "}"); - } - } - - public void setLvqKey(String key) - { - this.put(QPID_LVQ_KEY, key); - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolHandler.java b/qpid/java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolHandler.java deleted file mode 100644 index 200b1d72a4..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolHandler.java +++ /dev/null @@ -1,964 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol; - -import java.io.IOException; -import java.net.SocketAddress; -import java.nio.ByteBuffer; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.concurrent.CopyOnWriteArraySet; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQConnectionClosedException; -import org.apache.qpid.AMQDisconnectedException; -import org.apache.qpid.AMQException; -import org.apache.qpid.AMQTimeoutException; -import org.apache.qpid.client.AMQConnection; -import org.apache.qpid.client.AMQSession; -import org.apache.qpid.client.HeartbeatListener; -import org.apache.qpid.client.failover.FailoverException; -import org.apache.qpid.client.failover.FailoverHandler; -import org.apache.qpid.client.failover.FailoverState; -import org.apache.qpid.client.state.AMQState; -import org.apache.qpid.client.state.AMQStateManager; -import org.apache.qpid.client.state.StateWaiter; -import org.apache.qpid.client.state.listener.SpecificMethodFrameListener; -import org.apache.qpid.codec.AMQDecoder; -import org.apache.qpid.codec.ClientDecoder; -import org.apache.qpid.configuration.ClientProperties; -import org.apache.qpid.framing.AMQBody; -import org.apache.qpid.framing.AMQDataBlock; -import org.apache.qpid.framing.AMQFrame; -import org.apache.qpid.framing.AMQMethodBody; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.ConnectionCloseBody; -import org.apache.qpid.framing.ConnectionCloseOkBody; -import org.apache.qpid.framing.HeartbeatBody; -import org.apache.qpid.framing.MethodRegistry; -import org.apache.qpid.framing.ProtocolInitiation; -import org.apache.qpid.framing.ProtocolVersion; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.protocol.AMQMethodListener; -import org.apache.qpid.protocol.ProtocolEngine; -import org.apache.qpid.thread.Threading; -import org.apache.qpid.transport.ByteBufferSender; -import org.apache.qpid.transport.ConnectionSettings; -import org.apache.qpid.transport.TransportException; -import org.apache.qpid.transport.network.NetworkConnection; -import org.apache.qpid.util.BytesDataOutput; - -/** - * AMQProtocolHandler is the client side protocol handler for AMQP, it handles all protocol events received from the - * network by MINA. The primary purpose of AMQProtocolHandler is to translate the generic event model of MINA into the - * specific event model of AMQP, by revealing the type of the received events (from decoded data), and passing the - * event on to more specific handlers for the type. In this sense, it channels the richer event model of AMQP, - * expressed in terms of methods and so on, through the cruder, general purpose event model of MINA, expressed in - * terms of "message received" and so on. - * <p> - * There is a 1:1 mapping between an AMQProtocolHandler and an {@link AMQConnection}. The connection class is - * exposed to the end user of the AMQP client API, and also implements the JMS Connection API, so provides the public - * API calls through which an individual connection can be manipulated. This protocol handler talks to the network - * through MINA, in a behind the scenes role; it is not an exposed part of the client API. - * <p> - * There is a 1:many mapping between an AMQProtocolHandler and a set of {@link AMQSession}s. At the MINA level, - * there is one session per connection. At the AMQP level there can be many channels which are also called sessions in - * JMS parlance. The {@link AMQSession}s are managed through an {@link AMQProtocolSession} instance. The protocol - * session is similar to the MINA per-connection session, except that it can span the lifecycle of multiple MINA sessions - * in the event of failover. See below for more information about this. - * <p> - * Mina provides a session container that can be used to store/retrieve arbitrary objects as String named - * attributes. A more convenient, type-safe, container for session data is provided in the form of - * {@link AMQProtocolSession}. - * - * <p> - * A common way to use MINA is to have a single instance of the event handler, and for MINA to pass in its session - * object with every event, and for per-connection data to be held in the MINA session (perhaps using a type-safe wrapper - * as described above). This event handler is different, because dealing with failover complicates things. To the - * end client of an AMQConnection, a failed over connection is still handled through the same connection instance, but - * behind the scenes a new transport connection, and MINA session will have been created. The MINA session object cannot - * be used to track the state of the fail-over process, because it is destroyed and a new one is created, as the old - * connection is shutdown and a new one created. For this reason, an AMQProtocolHandler is created per AMQConnection - * and the protocol session data is held outside of the MINA IOSession. - * <p> - * This handler is responsible for setting up the filter chain to filter all events for this handler through. - * The filter chain is set up as a stack of event handers that perform the following functions (working upwards from - * the network traffic at the bottom), handing off incoming events to an asynchronous thread pool to do the work, - * optionally handling secure sockets encoding/decoding, encoding/decoding the AMQP format itself. - * <p> - * TODO Use a single handler instance, by shifting everything to do with the 'protocol session' state, including - * failover state, into AMQProtocolSession, and tracking that from AMQConnection? The lifecycles of - * AMQProtocolSesssion and AMQConnection will be the same, so if there is high cohesion between them, they could - * be merged, although there is sense in keeping the session model separate. Will clarify things by having data - * held per protocol handler, per protocol session, per network connection, per channel, in separate classes, so - * that lifecycles of the fields match lifecycles of their containing objects. - */ -public class AMQProtocolHandler implements ProtocolEngine -{ - /** Used for debugging. */ - private static final Logger _logger = LoggerFactory.getLogger(AMQProtocolHandler.class); - private static final Logger _protocolLogger = LoggerFactory.getLogger("qpid.protocol"); - private static final boolean PROTOCOL_DEBUG = (System.getProperty("amqj.protocol.logging.level") != null); - - private static final long MAXIMUM_STATE_WAIT_TIME = Long.parseLong(System.getProperty("amqj.MaximumStateWait", "30000")); - - /** - * The connection that this protocol handler is associated with. There is a 1-1 mapping between connection - * instances and protocol handler instances. - */ - private AMQConnection _connection; - - /** Our wrapper for a protocol session that provides access to session values in a typesafe manner. */ - private volatile AMQProtocolSession _protocolSession; - - /** Holds the state of the protocol session. */ - private AMQStateManager _stateManager; - - /** Holds the method listeners, */ - private final CopyOnWriteArraySet<AMQMethodListener> _frameListeners = new CopyOnWriteArraySet<AMQMethodListener>(); - - /** - * We create the failover handler when the session is created since it needs a reference to the IoSession in order - * to be able to send errors during failover back to the client application. The session won't be available in the - * case where we failing over due to a Connection.Redirect message from the broker. - */ - private FailoverHandler _failoverHandler; - - /** - * This flag is used to track whether failover is being attempted. It is used to prevent the application constantly - * attempting failover where it is failing. - */ - private FailoverState _failoverState = FailoverState.NOT_STARTED; - - /** Used to provide a condition to wait upon for operations that are required to wait for failover to complete. */ - private CountDownLatch _failoverLatch; - - /** The last failover exception that occurred */ - private FailoverException _lastFailoverException; - - /** Defines the default timeout to use for synchronous protocol commands. */ - private final long DEFAULT_SYNC_TIMEOUT = Long.getLong(ClientProperties.QPID_SYNC_OP_TIMEOUT, - Long.getLong(ClientProperties.AMQJ_DEFAULT_SYNCWRITE_TIMEOUT, - ClientProperties.DEFAULT_SYNC_OPERATION_TIMEOUT)); - - /** Object to lock on when changing the latch */ - private Object _failoverLatchChange = new Object(); - private AMQDecoder _decoder; - - private ProtocolVersion _suggestedProtocolVersion; - - private long _writtenBytes; - private long _readBytes; - - private int _messageReceivedCount; - private int _messagesOut; - - - private NetworkConnection _network; - private ByteBufferSender _sender; - private long _lastReadTime = System.currentTimeMillis(); - private long _lastWriteTime = System.currentTimeMillis(); - private HeartbeatListener _heartbeatListener = HeartbeatListener.DEFAULT; - private Throwable _initialConnectionException; - - /** - * Creates a new protocol handler, associated with the specified client connection instance. - * - * @param con The client connection that this is the event handler for. - */ - public AMQProtocolHandler(AMQConnection con) - { - _connection = con; - _protocolSession = new AMQProtocolSession(this, _connection); - _stateManager = new AMQStateManager(_protocolSession); - _failoverHandler = new FailoverHandler(this); - } - - /** - * Called when the network connection is closed. This can happen, either because the client explicitly requested - * that the connection be closed, in which case nothing is done, or because the connection died. In the case - * where the connection died, an attempt to failover automatically to a new connection may be started. The failover - * process will be started, provided that it is the clients policy to allow failover, and provided that a failover - * has not already been started or failed. - * <p> - * TODO Clarify: presumably exceptionCaught is called when the client is sending during a connection failure and - * not otherwise? The above comment doesn't make that clear. - */ - public void closed() - { - if (_connection.isClosed()) - { - _logger.debug("Session closed called by client"); - } - else - { - // Use local variable to keep flag whether fail-over allowed or not, - // in order to execute AMQConnection#exceptionRecievedout out of synchronization block, - // otherwise it might deadlock with failover mutex - boolean failoverNotAllowed = false; - boolean failedWithoutConnecting = false; - Throwable initialConnectionException = null; - synchronized (this) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Session closed called with failover state " + _failoverState); - } - - // reconnetablility was introduced here so as not to disturb the client as they have made their intentions - // known through the policy settings. - if (_failoverState == FailoverState.NOT_STARTED) - { - // close the sender - try - { - _sender.close(); - } - catch (Exception e) - { - _logger.warn("Exception occurred on closing the sender", e); - } - if (_connection.failoverAllowed()) - { - _failoverState = FailoverState.IN_PROGRESS; - - _logger.debug("FAILOVER STARTING"); - startFailoverThread(); - } - else if (_connection.isConnected()) - { - failoverNotAllowed = true; - if (_logger.isDebugEnabled()) - { - _logger.debug("Failover not allowed by policy:" + _connection.getFailoverPolicy()); - } - } - else - { - failedWithoutConnecting = true; - initialConnectionException = _initialConnectionException; - _logger.debug("We are in process of establishing the initial connection"); - } - _initialConnectionException = null; - } - else - { - _logger.debug("Not starting the failover thread as state currently " + _failoverState); - } - } - - if (failoverNotAllowed) - { - _connection.exceptionReceived(new AMQDisconnectedException( - "Server closed connection and reconnection not permitted.", _stateManager.getLastException())); - } - else if(failedWithoutConnecting) - { - if(initialConnectionException == null) - { - initialConnectionException = _stateManager.getLastException(); - } - String message = initialConnectionException == null ? "" : initialConnectionException.getMessage(); - _connection.exceptionReceived(new AMQDisconnectedException( - "Connection could not be established: " + message, initialConnectionException)); - } - } - - if (_logger.isDebugEnabled()) - { - _logger.debug("Protocol Session [" + this + "] closed"); - } - } - - /** See {@link FailoverHandler} to see rationale for separate thread. */ - private void startFailoverThread() - { - if(!_connection.isClosed()) - { - final Thread failoverThread; - try - { - failoverThread = Threading.getThreadFactory().createThread(_failoverHandler); - } - catch (Exception e) - { - throw new RuntimeException("Failed to create thread", e); - } - failoverThread.setName("Failover"); - // Do not inherit daemon-ness from current thread as this can be a daemon - // thread such as a AnonymousIoService thread. - failoverThread.setDaemon(false); - failoverThread.start(); - } - } - - @Override - public void encryptedTransport() - { - } - - public void readerIdle() - { - _logger.debug("Protocol Session [" + this + "] idle: reader"); - // failover: - _logger.warn("Timed out while waiting for heartbeat from peer."); - _network.close(); - } - - public void writerIdle() - { - _logger.debug("Protocol Session [" + this + "] idle: writer"); - writeFrame(HeartbeatBody.FRAME); - _heartbeatListener.heartbeatSent(); - } - - /** - * Invoked when any exception is thrown by the NetworkDriver - */ - public void exception(Throwable cause) - { - boolean causeIsAConnectionProblem = - cause instanceof AMQConnectionClosedException || - cause instanceof IOException || - cause instanceof TransportException; - - if (causeIsAConnectionProblem) - { - //ensure the IoSender and IoReceiver are closed - try - { - _network.close(); - } - catch (Exception e) - { - //ignore - } - } - FailoverState state = getFailoverState(); - if (state == FailoverState.NOT_STARTED) - { - if (causeIsAConnectionProblem) - { - _logger.info("Connection exception caught therefore going to attempt failover: " + cause, cause); - _initialConnectionException = cause; - } - else - { - _connection.exceptionReceived(cause); - } - - // FIXME Need to correctly handle other exceptions. Things like ... - // AMQChannelClosedException - // which will cause the JMSSession to end due to a channel close and so that Session needs - // to be removed from the map so we can correctly still call close without an exception when trying to close - // the server closed session. See also CloseChannelMethodHandler as the sessionClose is never called on exception - } - // we reach this point if failover was attempted and failed therefore we need to let the calling app - // know since we cannot recover the situation - else if (state == FailoverState.FAILED) - { - _logger.error("Exception caught by protocol handler: " + cause, cause); - - // we notify the state manager of the error in case we have any clients waiting on a state - // change. Those "waiters" will be interrupted and can handle the exception - AMQException amqe = new AMQException("Protocol handler error: " + cause, cause); - propagateExceptionToAllWaiters(amqe); - _connection.exceptionReceived(cause); - } - else - { - _logger.warn("Exception caught by protocol handler: " + cause, cause); - } - } - - /** - * There are two cases where we have other threads potentially blocking for events to be handled by this class. - * These are for the state manager (waiting for a state change) or a frame listener (waiting for a particular type - * of frame to arrive). When an error occurs we need to notify these waiters so that they can react appropriately. - * - * This should be called only when the exception is fatal for the connection. - * - * @param e the exception to propagate - * - * @see #propagateExceptionToFrameListeners - */ - public void propagateExceptionToAllWaiters(Exception e) - { - getStateManager().error(e); - - propagateExceptionToFrameListeners(e); - } - - /** - * This caters for the case where we only need to propagate an exception to the the frame listeners to interupt any - * protocol level waits. - * - * This will would normally be used to notify all Frame Listeners that Failover is about to occur and they should - * stop waiting and relinquish the Failover lock. See {@link FailoverHandler}. - * - * Once the {@link FailoverHandler} has re-established the connection then the listeners will be able to re-attempt - * their protocol request and so listen again for the correct frame. - * - * @param e the exception to propagate - */ - public void propagateExceptionToFrameListeners(Exception e) - { - synchronized (_frameListeners) - { - if (!_frameListeners.isEmpty()) - { - final Iterator it = _frameListeners.iterator(); - while (it.hasNext()) - { - final AMQMethodListener ml = (AMQMethodListener) it.next(); - ml.error(e); - } - } - } - } - - public void notifyFailoverStarting() - { - // Set the last exception in the sync block to ensure the ordering with add. - // either this gets done and the add does the ml.error - // or the add completes first and the iterator below will do ml.error - synchronized (_frameListeners) - { - _lastFailoverException = new FailoverException("Failing over about to start"); - } - - //Only notify the Frame listeners that failover is going to occur as the State listeners shouldn't be - // interrupted unless failover cannot restore the state. - propagateExceptionToFrameListeners(_lastFailoverException); - } - - public void failoverInProgress() - { - _lastFailoverException = null; - } - - public void received(ByteBuffer msg) - { - _readBytes += msg.remaining(); - _lastReadTime = System.currentTimeMillis(); - final List<AMQDataBlock> dataBlocks = _protocolSession.getMethodProcessor().getProcessedMethods(); - try - { - _decoder.decodeBuffer(msg); - - // Decode buffer - int size = dataBlocks.size(); - for (int i = 0; i < size; i++) - { - AMQDataBlock message = dataBlocks.get(i); - if (PROTOCOL_DEBUG) - { - _protocolLogger.info(String.format("RECV: [%s] %s", this, message)); - } - - if(message instanceof AMQFrame) - { - - final long msgNumber = ++_messageReceivedCount; - - if (((msgNumber % 1000) == 0) && _logger.isDebugEnabled()) - { - _logger.debug("Received " + _messageReceivedCount + " protocol messages"); - } - - AMQFrame frame = (AMQFrame) message; - - final AMQBody bodyFrame = frame.getBodyFrame(); - - bodyFrame.handle(frame.getChannel(), _protocolSession); - - _connection.bytesReceived(_readBytes); - } - else if (message instanceof ProtocolInitiation) - { - // We get here if the server sends a response to our initial protocol header - // suggesting an alternate ProtocolVersion; the server will then close the - // connection. - ProtocolInitiation protocolInit = (ProtocolInitiation) message; - _suggestedProtocolVersion = protocolInit.checkVersion(); - _logger.info("Broker suggested using protocol version:" + _suggestedProtocolVersion); - - // get round a bug in old versions of qpid whereby the connection is not closed - _stateManager.changeState(AMQState.CONNECTION_CLOSED); - } - } - } - catch (Exception e) - { - _logger.error("Exception processing frame", e); - propagateExceptionToFrameListeners(e); - exception(e); - } - finally - { - dataBlocks.clear(); - } - - - } - - public void methodBodyReceived(final int channelId, final AMQBody bodyFrame) - throws AMQException - { - - if (_logger.isDebugEnabled()) - { - _logger.debug("(" + System.identityHashCode(this) + ")Method frame received: " + bodyFrame); - } - - final AMQMethodEvent<AMQMethodBody> evt = - new AMQMethodEvent<AMQMethodBody>(channelId, (AMQMethodBody) bodyFrame); - - try - { - - boolean wasAnyoneInterested = getStateManager().methodReceived(evt); - synchronized (_frameListeners) - { - if (!_frameListeners.isEmpty()) - { - //This iterator is safe from the error state as the frame listeners always add before they send so their - // will be ready and waiting for this response. - Iterator it = _frameListeners.iterator(); - while (it.hasNext()) - { - final AMQMethodListener listener = (AMQMethodListener) it.next(); - wasAnyoneInterested = listener.methodReceived(evt) || wasAnyoneInterested; - } - } - } - if (!wasAnyoneInterested) - { - throw new AMQException(null, "AMQMethodEvent " + evt + " was not processed by any listener. Listeners:" - + _frameListeners, null); - } - } - catch (AMQException e) - { - propagateExceptionToFrameListeners(e); - - exception(e); - } - - } - - public StateWaiter createWaiter(Set<AMQState> states) throws AMQException - { - return getStateManager().createWaiter(states); - } - - public void writeFrame(AMQDataBlock frame) - { - writeFrame(frame, true); - } - - public synchronized void writeFrame(AMQDataBlock frame, boolean flush) - { - final ByteBuffer buf = asByteBuffer(frame); - _lastWriteTime = System.currentTimeMillis(); - _writtenBytes += buf.remaining(); - _sender.send(buf); - if(flush) - { - _sender.flush(); - } - - if (PROTOCOL_DEBUG) - { - _protocolLogger.debug(String.format("SEND: [%s] %s", this, frame)); - } - - final long sentMessages = _messagesOut++; - - final boolean debug = _logger.isDebugEnabled(); - - if (debug && ((sentMessages % 1000) == 0)) - { - _logger.debug("Sent " + _messagesOut + " protocol messages"); - } - - _connection.bytesSent(_writtenBytes); - - } - - private static final int REUSABLE_BYTE_BUFFER_CAPACITY = 65 * 1024; - private final byte[] _reusableBytes = new byte[REUSABLE_BYTE_BUFFER_CAPACITY]; - private final ByteBuffer _reusableByteBuffer = ByteBuffer.wrap(_reusableBytes); - private final BytesDataOutput _reusableDataOutput = new BytesDataOutput(_reusableBytes); - - private ByteBuffer asByteBuffer(AMQDataBlock block) - { - final int size = (int) block.getSize(); - - final byte[] data; - - - if(size > REUSABLE_BYTE_BUFFER_CAPACITY) - { - data= new byte[size]; - } - else - { - - data = _reusableBytes; - } - _reusableDataOutput.setBuffer(data); - - try - { - block.writePayload(_reusableDataOutput); - } - catch (IOException e) - { - throw new RuntimeException(e); - } - - final ByteBuffer buf; - - if(size < REUSABLE_BYTE_BUFFER_CAPACITY) - { - buf = _reusableByteBuffer; - buf.position(0); - } - else - { - buf = ByteBuffer.wrap(data); - } - buf.limit(_reusableDataOutput.length()); - - return buf; - } - - - /** - * Convenience method that writes a frame to the protocol session and waits for a particular response. Equivalent to - * calling getProtocolSession().write() then waiting for the response. - * - * @param frame - * @param listener the blocking listener. Note the calling thread will block. - */ - public AMQMethodEvent writeCommandFrameAndWaitForReply(AMQDataBlock frame, BlockingMethodFrameListener listener) - throws AMQException, FailoverException - { - return writeCommandFrameAndWaitForReply(frame, listener, DEFAULT_SYNC_TIMEOUT); - } - - /** - * Convenience method that writes a frame to the protocol session and waits for a particular response. Equivalent to - * calling getProtocolSession().write() then waiting for the response. - * - * @param frame - * @param listener the blocking listener. Note the calling thread will block. - */ - public AMQMethodEvent writeCommandFrameAndWaitForReply(AMQDataBlock frame, BlockingMethodFrameListener listener, - long timeout) throws AMQException, FailoverException - { - try - { - synchronized (_frameListeners) - { - if (_lastFailoverException != null) - { - throw _lastFailoverException; - } - - if(_stateManager.getCurrentState() == AMQState.CONNECTION_CLOSED || - _stateManager.getCurrentState() == AMQState.CONNECTION_CLOSING) - { - Exception e = _stateManager.getLastException(); - if (e != null) - { - if (e instanceof AMQException) - { - AMQException amqe = (AMQException) e; - - throw amqe.cloneForCurrentThread(); - } - else - { - throw new AMQException(AMQConstant.INTERNAL_ERROR, e.getMessage(), e); - } - } - } - - _frameListeners.add(listener); - //FIXME: At this point here we should check or before add we should check _stateManager is in an open - // state so as we don't check we are likely just to time out here as I believe is being seen in QPID-1255 - } - writeFrame(frame); - - long actualTimeout = timeout == -1 ? DEFAULT_SYNC_TIMEOUT : timeout; - return listener.blockForFrame(actualTimeout); - // When control resumes before this line, a reply will have been received - // that matches the criteria defined in the blocking listener - } - finally - { - // If we don't removeKey the listener then no-one will - _frameListeners.remove(listener); - } - - } - - /** More convenient method to write a frame and wait for it's response. */ - public AMQMethodEvent syncWrite(AMQFrame frame, Class responseClass) throws AMQException, FailoverException - { - return syncWrite(frame, responseClass, DEFAULT_SYNC_TIMEOUT); - } - - /** More convenient method to write a frame and wait for it's response. */ - public AMQMethodEvent syncWrite(AMQFrame frame, Class responseClass, long timeout) throws AMQException, FailoverException - { - return writeCommandFrameAndWaitForReply(frame, new SpecificMethodFrameListener(frame.getChannel(), responseClass), - timeout); - } - - public void closeSession(AMQSession session) throws AMQException - { - _protocolSession.closeSession(session); - } - - /** - * Closes the connection. - * <p> - * If a failover exception occurs whilst closing the connection it is ignored, as the connection is closed - * anyway. - * - * @param timeout The timeout to wait for an acknowledgment to the close request. - * - * @throws AMQException If the close fails for any reason. - */ - public void closeConnection(long timeout) throws AMQException - { - if (!getStateManager().getCurrentState().equals(AMQState.CONNECTION_CLOSED)) - { - // Connection is already closed then don't do a syncWrite - try - { - final ConnectionCloseBody body = _protocolSession.getMethodRegistry().createConnectionCloseBody( - AMQConstant.REPLY_SUCCESS.getCode(), - // replyCode - new AMQShortString("JMS client is closing the connection."), - 0, - 0); - final AMQFrame frame = body.generateFrame(0); - - syncWrite(frame, ConnectionCloseOkBody.class, timeout); - _network.close(); - closed(); - } - catch (AMQTimeoutException e) - { - closed(); - } - catch (FailoverException e) - { - _logger.debug("FailoverException interrupted connection close, ignoring as connection closed anyway."); - } - } - } - - /** @return the number of bytes read from this protocol session */ - public long getReadBytes() - { - return _readBytes; - } - - /** @return the number of bytes written to this protocol session */ - public long getWrittenBytes() - { - return _writtenBytes; - } - - public void blockUntilNotFailingOver() throws InterruptedException - { - synchronized(_failoverLatchChange) - { - if (_failoverLatch != null) - { - if(!_failoverLatch.await(MAXIMUM_STATE_WAIT_TIME, TimeUnit.MILLISECONDS)) - { - - } - } - } - } - - public AMQShortString generateQueueName() - { - return _protocolSession.generateQueueName(); - } - - public CountDownLatch getFailoverLatch() - { - return _failoverLatch; - } - - public void setFailoverLatch(CountDownLatch failoverLatch) - { - synchronized (_failoverLatchChange) - { - _failoverLatch = failoverLatch; - } - } - - public AMQConnection getConnection() - { - return _connection; - } - - public AMQStateManager getStateManager() - { - return _stateManager; - } - - public void setStateManager(AMQStateManager stateManager) - { - _stateManager = stateManager; - _stateManager.setProtocolSession(_protocolSession); - } - - public AMQProtocolSession getProtocolSession() - { - return _protocolSession; - } - - synchronized FailoverState getFailoverState() - { - return _failoverState; - } - - public synchronized void setFailoverState(FailoverState failoverState) - { - _failoverState= failoverState; - } - - public byte getProtocolMajorVersion() - { - return _protocolSession.getProtocolMajorVersion(); - } - - public byte getProtocolMinorVersion() - { - return _protocolSession.getProtocolMinorVersion(); - } - - public MethodRegistry getMethodRegistry() - { - return _protocolSession.getMethodRegistry(); - } - - public ProtocolVersion getProtocolVersion() - { - return _protocolSession.getProtocolVersion(); - } - - public SocketAddress getRemoteAddress() - { - return _network.getRemoteAddress(); - } - - public SocketAddress getLocalAddress() - { - return _network.getLocalAddress(); - } - - public void setNetworkConnection(NetworkConnection network) - { - setNetworkConnection(network, network.getSender()); - } - - public void setNetworkConnection(NetworkConnection network, ByteBufferSender sender) - { - _network = network; - _sender = sender; - } - - @Override - public long getLastReadTime() - { - return _lastReadTime; - } - - @Override - public long getLastWriteTime() - { - return _lastWriteTime; - } - - protected ByteBufferSender getSender() - { - return _sender; - } - - void initHeartbeats(int delay, float timeoutFactor) - { - if (delay > 0) - { - _network.setMaxWriteIdle(delay); - int readerIdle = (int)(delay * timeoutFactor); - _network.setMaxReadIdle(readerIdle); - } - } - - public NetworkConnection getNetworkConnection() - { - return _network; - } - - public ProtocolVersion getSuggestedProtocolVersion() - { - return _suggestedProtocolVersion; - } - - - public void setHeartbeatListener(HeartbeatListener listener) - { - _heartbeatListener = listener == null ? HeartbeatListener.DEFAULT : listener; - } - - public void heartbeatBodyReceived() - { - _heartbeatListener.heartbeatReceived(); - } - - public void setMaxFrameSize(final long frameMax) - { - _decoder.setMaxFrameSize(frameMax == 0l || frameMax > (long) Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) frameMax); - } - - public void init(final ConnectionSettings settings) - { - _decoder = new ClientDecoder(_protocolSession.getMethodProcessor()); - _protocolSession.init(settings); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolSession.java b/qpid/java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolSession.java deleted file mode 100644 index 15cb908807..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolSession.java +++ /dev/null @@ -1,555 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import javax.jms.JMSException; -import javax.security.sasl.SaslClient; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.AMQConnection; -import org.apache.qpid.client.AMQSession; -import org.apache.qpid.client.ConnectionTuneParameters; -import org.apache.qpid.client.handler.ClientMethodDispatcherImpl; -import org.apache.qpid.client.message.UnprocessedMessage; -import org.apache.qpid.client.message.UnprocessedMessage_0_8; -import org.apache.qpid.client.state.AMQStateManager; -import org.apache.qpid.framing.AMQDataBlock; -import org.apache.qpid.framing.AMQMethodBody; -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.FrameCreatingMethodProcessor; -import org.apache.qpid.framing.HeartbeatBody; -import org.apache.qpid.framing.MethodDispatcher; -import org.apache.qpid.framing.MethodRegistry; -import org.apache.qpid.framing.ProtocolInitiation; -import org.apache.qpid.framing.ProtocolVersion; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.protocol.AMQVersionAwareProtocolSession; -import org.apache.qpid.transport.ByteBufferSender; -import org.apache.qpid.transport.ConnectionSettings; -import org.apache.qpid.transport.TransportException; - -/** - * Wrapper for protocol session that provides type-safe access to session attributes. - * <p> - * The underlying protocol session is still available but clients should not use it to obtain session attributes. - */ -public class AMQProtocolSession implements AMQVersionAwareProtocolSession -{ - - protected static final Logger _logger = LoggerFactory.getLogger(AMQProtocolSession.class); - - //Usable channels are numbered 1 to <ChannelMax> - public static final int MAX_CHANNEL_MAX = 0xFFFF; - public static final int MIN_USABLE_CHANNEL_NUM = 1; - - private final AMQProtocolHandler _protocolHandler; - - private ConcurrentMap<Integer, AMQSession> _channelId2SessionMap = new ConcurrentHashMap<Integer, AMQSession>(); - - private ConcurrentMap _closingChannels = new ConcurrentHashMap(); - - /** - * Maps from a channel id to an unprocessed message. This is used to tie together the JmsDeliverBody (which arrives - * first) with the subsequent content header and content bodies. - */ - private final ConcurrentMap<Integer, UnprocessedMessage> _channelId2UnprocessedMsgMap = new ConcurrentHashMap<Integer, UnprocessedMessage>(); - private final UnprocessedMessage[] _channelId2UnprocessedMsgArray = new UnprocessedMessage[16]; - - private int _queueId = 1; - private final Object _queueIdLock = new Object(); - - private ProtocolVersion _protocolVersion; - - private final MethodRegistry _methodRegistry = - new MethodRegistry(ProtocolVersion.getLatestSupportedVersion()); - - private final FrameCreatingMethodProcessor _methodProcessor = - new FrameCreatingMethodProcessor(ProtocolVersion.getLatestSupportedVersion()); - - private MethodDispatcher _methodDispatcher; - - private final AMQConnection _connection; - - private ConnectionTuneParameters _connectionTuneParameters; - private FieldTable _connectionStartServerProperties; - - private SaslClient _saslClient; - - private static final int FAST_CHANNEL_ACCESS_MASK = 0xFFFFFFF0; - - public AMQProtocolSession(AMQProtocolHandler protocolHandler, AMQConnection connection) - { - _protocolHandler = protocolHandler; - _protocolVersion = connection.getProtocolVersion(); - if (_logger.isDebugEnabled()) - { - _logger.debug("Using ProtocolVersion for Session:" + _protocolVersion); - } - _methodDispatcher = ClientMethodDispatcherImpl.newMethodDispatcher(ProtocolVersion.getLatestSupportedVersion(), - this); - _connection = connection; - } - - public void init(ConnectionSettings settings) - { - // start the process of setting up the connection. This is the first place that - // data is written to the server. - initialiseTuneParameters(settings); - - _protocolHandler.writeFrame(new ProtocolInitiation(_connection.getProtocolVersion())); - } - - public ConnectionTuneParameters getConnectionTuneParameters() - { - return _connectionTuneParameters; - } - - private void initialiseTuneParameters(ConnectionSettings settings) - { - _connectionTuneParameters = new ConnectionTuneParameters(); - _connectionTuneParameters.setHeartbeat(settings.getHeartbeatInterval08()); - _connectionTuneParameters.setHeartbeatTimeoutFactor(settings.getHeartbeatTimeoutFactor()); - } - - public void tuneConnection(ConnectionTuneParameters params) - { - _connectionTuneParameters = params; - AMQConnection con = getAMQConnection(); - - con.setMaximumChannelCount(params.getChannelMax()); - con.setMaximumFrameSize(params.getFrameMax()); - - _protocolHandler.initHeartbeats(params.getHeartbeat(), params.getHeartbeatTimeoutFactor()); - } - - public String getClientID() - { - try - { - return getAMQConnection().getClientID(); - } - catch (JMSException e) - { - // we never throw a JMSException here - return null; - } - } - - public void setClientID(String clientID) throws JMSException - { - getAMQConnection().setClientID(clientID); - } - - public AMQStateManager getStateManager() - { - return _protocolHandler.getStateManager(); - } - - public String getVirtualHost() - { - return getAMQConnection().getVirtualHost(); - } - - public SaslClient getSaslClient() - { - return _saslClient; - } - - /** - * Store the SASL client currently being used for the authentication handshake - * - * @param client if non-null, stores this in the session. if null clears any existing client being stored - */ - public void setSaslClient(SaslClient client) - { - _saslClient = client; - } - - /** - * Callback invoked from the BasicDeliverMethodHandler when a message has been received. - * - * @param message - * - * @throws AMQException if this was not expected - */ - public void unprocessedMessageReceived(final int channelId, UnprocessedMessage message) throws AMQException - { - if ((channelId & FAST_CHANNEL_ACCESS_MASK) == 0) - { - _channelId2UnprocessedMsgArray[channelId] = message; - } - else - { - _channelId2UnprocessedMsgMap.put(channelId, message); - } - } - - public void contentHeaderReceived(int channelId, ContentHeaderBody contentHeader) throws AMQException - { - final UnprocessedMessage_0_8 msg = (UnprocessedMessage_0_8) ((channelId & FAST_CHANNEL_ACCESS_MASK) == 0 ? _channelId2UnprocessedMsgArray[channelId] - : _channelId2UnprocessedMsgMap.get(channelId)); - - if (msg == null) - { - throw new AMQException(null, "Error: received content header without having received a BasicDeliver frame first on session:" + this, null); - } - - if (msg.getContentHeader() != null) - { - throw new AMQException(null, "Error: received duplicate content header or did not receive correct number of content body frames on session:" + this, null); - } - - msg.setContentHeader(contentHeader); - if (contentHeader.getBodySize() == 0) - { - deliverMessageToAMQSession(channelId, msg); - } - } - - public void contentBodyReceived(final int channelId, ContentBody contentBody) throws AMQException - { - UnprocessedMessage_0_8 msg; - final boolean fastAccess = (channelId & FAST_CHANNEL_ACCESS_MASK) == 0; - if (fastAccess) - { - msg = (UnprocessedMessage_0_8) _channelId2UnprocessedMsgArray[channelId]; - } - else - { - msg = (UnprocessedMessage_0_8) _channelId2UnprocessedMsgMap.get(channelId); - } - - if (msg == null) - { - throw new AMQException(null, "Error: received content body without having received a JMSDeliver frame first", null); - } - - if (msg.getContentHeader() == null) - { - if (fastAccess) - { - _channelId2UnprocessedMsgArray[channelId] = null; - } - else - { - _channelId2UnprocessedMsgMap.remove(channelId); - } - throw new AMQException(null, "Error: received content body without having received a ContentHeader frame first", null); - } - - msg.receiveBody(contentBody); - - if (msg.isAllBodyDataReceived()) - { - deliverMessageToAMQSession(channelId, msg); - } - } - - public void heartbeatBodyReceived(int channelId, HeartbeatBody body) throws AMQException - { - _protocolHandler.heartbeatBodyReceived(); - } - - /** - * Deliver a message to the appropriate session, removing the unprocessed message from our map - * - * @param channelId the channel id the message should be delivered to - * @param msg the message - */ - private void deliverMessageToAMQSession(int channelId, UnprocessedMessage msg) - { - AMQSession session = getSession(channelId); - session.messageReceived(msg); - if ((channelId & FAST_CHANNEL_ACCESS_MASK) == 0) - { - _channelId2UnprocessedMsgArray[channelId] = null; - } - else - { - _channelId2UnprocessedMsgMap.remove(channelId); - } - } - - protected AMQSession getSession(int channelId) - { - return _connection.getSession(channelId); - } - - public void writeFrame(AMQDataBlock frame) - { - _protocolHandler.writeFrame(frame); - } - - /** - * Starts the process of closing a session - * - * @param session the AMQSession being closed - */ - public void closeSession(AMQSession session) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("closeSession called on protocol session for session " + session.getChannelId()); - } - final int channelId = session.getChannelId(); - if (channelId <= 0) - { - throw new IllegalArgumentException("Attempt to close a channel with id < 0"); - } - // we need to know when a channel is closing so that we can respond - // with a channel.close frame when we receive any other type of frame - // on that channel - _closingChannels.putIfAbsent(channelId, session); - } - - /** - * Called from the ChannelClose handler when a channel close frame is received. This method decides whether this is - * a response or an initiation. The latter case causes the AMQSession to be closed and an exception to be thrown if - * appropriate. - * - * @param channelId the id of the channel (session) - * - * @return true if the client must respond to the server, i.e. if the server initiated the channel close, false if - * the channel close is just the server responding to the client's earlier request to close the channel. - */ - public boolean channelClosed(int channelId, AMQConstant code, String text) throws AMQException - { - - // if this is not a response to an earlier request to close the channel - if (_closingChannels.remove(channelId) == null) - { - final AMQSession session = getSession(channelId); - try - { - session.closed(new AMQException(code, text, null)); - } - catch (JMSException e) - { - throw new AMQException(null, "JMSException received while closing session", e); - } - - return true; - } - else - { - return false; - } - } - - public AMQConnection getAMQConnection() - { - return _connection; - } - - public void closeProtocolSession() throws AMQException - { - try - { - _protocolHandler.getNetworkConnection().close(); - } - catch(TransportException e) - { - //ignore such exceptions, they were already logged - //and this is a forcible close. - } - } - - public ByteBufferSender getSender() - { - return _protocolHandler.getSender(); - } - - protected AMQShortString generateQueueName() - { - int id; - synchronized (_queueIdLock) - { - id = _queueId++; - } - // convert '.', '/', ':' and ';' to single '_', for spec compliance and readability - String localAddress = _protocolHandler.getLocalAddress().toString().replaceAll("[./:;]", "_"); - String queueName = "tmp_" + localAddress + "_" + id; - return new AMQShortString(queueName.replaceAll("_+", "_")); - } - - public void confirmConsumerCancelled(int channelId, AMQShortString consumerTag) - { - final AMQSession session = getSession(channelId); - - session.confirmConsumerCancelled(consumerTag.toIntValue()); - } - - public void setProtocolVersion(final ProtocolVersion pv) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Setting ProtocolVersion to :" + pv); - } - _protocolVersion = pv; - _methodRegistry.setProtocolVersion(pv); - _methodProcessor.setProtocolVersion(pv); - _methodDispatcher = ClientMethodDispatcherImpl.newMethodDispatcher(pv, this); - } - - public byte getProtocolMinorVersion() - { - return _protocolVersion.getMinorVersion(); - } - - public byte getProtocolMajorVersion() - { - return _protocolVersion.getMajorVersion(); - } - - public ProtocolVersion getProtocolVersion() - { - return _protocolVersion; - } - - public MethodRegistry getMethodRegistry() - { - return _methodRegistry; - } - - public MethodDispatcher getMethodDispatcher() - { - return _methodDispatcher; - } - - public void setTicket(int ticket, int channelId) - { - final AMQSession session = getSession(channelId); - session.setTicket(ticket); - } - - public void setMethodDispatcher(MethodDispatcher methodDispatcher) - { - _methodDispatcher = methodDispatcher; - } - - public void setFlowControl(final int channelId, final boolean active) - { - final AMQSession session = getSession(channelId); - session.setFlowControl(active); - } - - public void methodFrameReceived(final int channel, final AMQMethodBody amqMethodBody) throws AMQException - { - _protocolHandler.methodBodyReceived(channel, amqMethodBody); - } - - public void notifyError(Exception error) - { - _protocolHandler.propagateExceptionToAllWaiters(error); - } - - public void setSender(ByteBufferSender sender) - { - // No-op, interface munging - } - - - @Override - public String toString() - { - return "AMQProtocolSession[" + _connection + ']'; - } - - /** - * The handler from which this session was created and which is used to handle protocol events. We send failover - * events to the handler. - */ - protected AMQProtocolHandler getProtocolHandler() - { - return _protocolHandler; - } - - /** Maps from the channel id to the AMQSession that it represents. */ - protected ConcurrentMap<Integer, AMQSession> getChannelId2SessionMap() - { - return _channelId2SessionMap; - } - - protected void setChannelId2SessionMap(ConcurrentMap<Integer, AMQSession> channelId2SessionMap) - { - _channelId2SessionMap = channelId2SessionMap; - } - - protected ConcurrentMap getClosingChannels() - { - return _closingChannels; - } - - protected void setClosingChannels(ConcurrentMap closingChannels) - { - _closingChannels = closingChannels; - } - - /** Counter to ensure unique queue names */ - protected int getQueueId() - { - return _queueId; - } - - protected void setQueueId(int queueId) - { - _queueId = queueId; - } - - protected Object getQueueIdLock() - { - return _queueIdLock; - } - - protected AMQConnection getConnection() - { - return _connection; - } - - public void setConnectionStartServerProperties(FieldTable serverProperties) - { - _connectionStartServerProperties = serverProperties; - } - - public FieldTable getConnectionStartServerProperties() - { - return _connectionStartServerProperties; - } - - public void setMaxFrameSize(final long frameMax) - { - _protocolHandler.setMaxFrameSize(frameMax); - } - - public FrameCreatingMethodProcessor getMethodProcessor() - { - return _methodProcessor; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/protocol/BlockingMethodFrameListener.java b/qpid/java/client/src/main/java/org/apache/qpid/client/protocol/BlockingMethodFrameListener.java deleted file mode 100644 index 603e2ee10c..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/protocol/BlockingMethodFrameListener.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.failover.FailoverException; -import org.apache.qpid.client.util.BlockingWaiter; -import org.apache.qpid.framing.AMQMethodBody; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.protocol.AMQMethodListener; - -/** - * BlockingMethodFrameListener is a 'rendezvous' which acts as a {@link AMQMethodListener} that delegates handling of - * incoming methods to a method listener implemented as a sub-class of this and hands off the processed method or - * error to a consumer. The producer of the event does not have to wait for the consumer to take the event, so this - * differs from a 'rendezvous' in that sense. - * <p> - * BlockingMethodFrameListeners are used to coordinate waiting for replies to method calls that expect a response. - * They are always used in a 'one-shot' manner, that is, to recieve just one response. Usually the caller has to register - * them as method listeners with an event dispatcher and remember to de-register them (in a finally block) once they - * have been completed. - * <p> - * The {@link #processMethod} must return <tt>true</tt> on any incoming method that it handles. This indicates to - * this listeners that the method it is waiting for has arrived. Incoming methods are also filtered by channel prior to - * being passed to the {@link #processMethod} method, so responses are only received for a particular channel. The - * channel id must be passed to the constructor. - * <p> - * Errors from the producer are rethrown to the consumer. - * <p> - * TODO Might be neater if this method listener simply wrapped another that provided the method handling using a - * methodRecevied method. The processMethod takes an additional channelId, however none of the implementations - * seem to use it. So wrapping the listeners is possible. - * <p> - * TODO If the retrotranslator can handle it, could use a SynchronousQueue to implement this rendezvous. Need to - * check that SynchronousQueue has a non-blocking put method available. - */ -public abstract class BlockingMethodFrameListener extends BlockingWaiter<AMQMethodEvent> implements AMQMethodListener -{ - - /** Holds the channel id for the channel upon which this listener is waiting for a response. */ - private int _channelId; - - /** - * Creates a new method listener, that filters incoming method to just those that match the specified channel id. - * - * @param channelId The channel id to filter incoming methods with. - */ - public BlockingMethodFrameListener(int channelId) - { - _channelId = channelId; - } - - /** - * Delegates any additional handling of the incoming methods to another handler. - * - * @param channelId The channel id of the incoming method. - * @param frame The method body. - * - * @return <tt>true</tt> if the method was handled, <tt>false</tt> otherwise. - */ - public abstract boolean processMethod(int channelId, AMQMethodBody frame); - - public boolean process(AMQMethodEvent evt) - { - AMQMethodBody method = evt.getMethod(); - - return (evt.getChannelId() == _channelId) && processMethod(evt.getChannelId(), method); - } - - /** - * Informs this listener that an AMQP method has been received. - * - * @param evt The AMQP method. - * - * @return <tt>true</tt> if this listener has handled the method, <tt>false</tt> otherwise. - */ - public boolean methodReceived(AMQMethodEvent evt) - { - return received(evt); - } - - /** - * Blocks until a method is received that is handled by the delegated to method listener, or the specified timeout - * has passed. - * - * @param timeout The timeout in milliseconds. - * - * @return The AMQP method that was received. - * - * @throws AMQException - * @throws FailoverException - */ - public AMQMethodEvent blockForFrame(long timeout) throws AMQException, FailoverException - { - try - { - return (AMQMethodEvent) block(timeout); - } - finally - { - //Prevent any more errors being notified to this waiter. - close(); - } - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/security/AMQCallbackHandler.java b/qpid/java/client/src/main/java/org/apache/qpid/client/security/AMQCallbackHandler.java deleted file mode 100644 index 068e105731..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/security/AMQCallbackHandler.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.client.security; - -import org.apache.qpid.jms.ConnectionURL; - -import javax.security.auth.callback.CallbackHandler; - -public interface AMQCallbackHandler extends CallbackHandler -{ - void initialise(ConnectionURL connectionURL); -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/security/CallbackHandlerRegistry.java b/qpid/java/client/src/main/java/org/apache/qpid/client/security/CallbackHandlerRegistry.java deleted file mode 100644 index 8d53438bb7..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/security/CallbackHandlerRegistry.java +++ /dev/null @@ -1,315 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.security; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.StringTokenizer; -import java.util.TreeMap; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.util.FileUtils; - -/** - * CallbackHandlerRegistry is a registry for call back handlers for user authentication and interaction during user - * authentication. It is capable of reading its configuration from a properties file containing call back handler - * implementing class names for different SASL mechanism names. Instantiating this registry also has the effect of - * configuring and registering the SASL client factory implementations using {@link DynamicSaslRegistrar}. - * <p> - * The callback configuration should be specified in a properties file, refered to by the System property - * "amp.callbackhandler.properties". The format of the properties file is: - * <p> - * <pre> - * CallbackHanlder.n.mechanism=fully.qualified.class.name where n is an ordinal - * </pre> - * <p> - * Where mechanism is an IANA-registered mechanism name and the fully qualified class name refers to a - * class that implements org.apache.qpid.client.security.AMQCallbackHanlder and provides a call back handler for the - * specified mechanism. - */ -public class CallbackHandlerRegistry -{ - private static final Logger _logger = LoggerFactory.getLogger(CallbackHandlerRegistry.class); - - /** The name of the system property that holds the name of the callback handler properties file. */ - private static final String FILE_PROPERTY = "amq.callbackhandler.properties"; - - /** The default name of the callback handler properties resource. */ - public static final String DEFAULT_RESOURCE_NAME = "org/apache/qpid/client/security/CallbackHandlerRegistry.properties"; - - /** A static reference to the singleton instance of this registry. */ - private static final CallbackHandlerRegistry _instance; - - /** Holds a map from SASL mechanism names to call back handlers. */ - private Map<String, Class<AMQCallbackHandler>> _mechanismToHandlerClassMap = new HashMap<String, Class<AMQCallbackHandler>>(); - - /** Ordered collection of mechanisms for which callback handlers exist. */ - private Collection<String> _mechanisms; - - private static final Collection<String> MECHS_THAT_NEED_USERPASS = Arrays.asList(new String [] {"PLAIN", "AMQPLAIN", "CRAM-MD5","CRAM-MD5-HASHED", "SCRAM-SHA-1", "SCRAM-SHA-256"}); - - static - { - // Register any configured SASL client factories. - DynamicSaslRegistrar.registerSaslProviders(); - - String filename = System.getProperty(FILE_PROPERTY); - InputStream is = - FileUtils.openFileOrDefaultResource(filename, DEFAULT_RESOURCE_NAME, - CallbackHandlerRegistry.class.getClassLoader()); - - final Properties props = new Properties(); - - try - { - - props.load(is); - } - catch (IOException e) - { - _logger.error("Error reading properties: " + e, e); - } - finally - { - if (is != null) - { - try - { - is.close(); - - } - catch (IOException e) - { - _logger.error("Unable to close properties stream: " + e, e); - } - } - } - - _instance = new CallbackHandlerRegistry(props); - _logger.info("Callback handlers available for SASL mechanisms: " + _instance._mechanisms); - - } - - /** - * Gets the singleton instance of this registry. - * - * @return The singleton instance of this registry. - */ - public static CallbackHandlerRegistry getInstance() - { - return _instance; - } - - public AMQCallbackHandler createCallbackHandler(final String mechanism) - { - final Class<AMQCallbackHandler> mechanismClass = _mechanismToHandlerClassMap.get(mechanism); - - if (mechanismClass == null) - { - throw new IllegalArgumentException("Mechanism " + mechanism + " not known"); - } - - try - { - return mechanismClass.newInstance(); - } - catch (InstantiationException e) - { - throw new IllegalArgumentException("Unable to create an instance of mechanism " + mechanism, e); - } - catch (IllegalAccessException e) - { - throw new IllegalArgumentException("Unable to create an instance of mechanism " + mechanism, e); - } - } - - /** - * Gets collections of supported SASL mechanism names, ordered by preference - * - * @return collection of SASL mechanism names. - */ - public Collection<String> getMechanisms() - { - return Collections.unmodifiableCollection(_mechanisms); - } - - /** - * Creates the call back handler registry from its configuration resource or file. - * - * This also has the side effect of configuring and registering the SASL client factory - * implementations using {@link DynamicSaslRegistrar}. - * - * This constructor is default protection to allow for effective unit testing. Clients must use - * {@link #getInstance()} to obtain the singleton instance. - */ - CallbackHandlerRegistry(final Properties props) - { - parseProperties(props); - } - - /** - * Scans the specified properties as a mapping from IANA registered SASL mechanism to call back handler - * implementations, that provide the necessary call back handling for obtaining user log in credentials - * during authentication for the specified mechanism, and builds a map from mechanism names to handler - * classes. - * - * @param props - */ - private void parseProperties(Properties props) - { - - final Map<Integer, String> mechanisms = new TreeMap<Integer, String>(); - - Enumeration e = props.propertyNames(); - while (e.hasMoreElements()) - { - final String propertyName = (String) e.nextElement(); - final String[] parts = propertyName.split("\\.", 2); - - checkPropertyNameFormat(propertyName, parts); - - final String mechanism = parts[0]; - final int ordinal = getPropertyOrdinal(propertyName, parts); - final String className = props.getProperty(propertyName); - Class clazz = null; - try - { - clazz = Class.forName(className); - if (!AMQCallbackHandler.class.isAssignableFrom(clazz)) - { - _logger.warn("SASL provider " + clazz + " does not implement " + AMQCallbackHandler.class - + ". Skipping"); - continue; - } - _mechanismToHandlerClassMap.put(mechanism, clazz); - - mechanisms.put(ordinal, mechanism); - } - catch (ClassNotFoundException ex) - { - _logger.warn("Unable to load class " + className + ". Skipping that SASL provider"); - - continue; - } - } - - _mechanisms = mechanisms.values(); // order guaranteed by keys of treemap (i.e. our ordinals) - - - } - - private void checkPropertyNameFormat(final String propertyName, final String[] parts) - { - if (parts.length != 2) - { - throw new IllegalArgumentException("Unable to parse property " + propertyName + " when configuring SASL providers"); - } - } - - private int getPropertyOrdinal(final String propertyName, final String[] parts) - { - try - { - return Integer.parseInt(parts[1]); - } - catch(NumberFormatException nfe) - { - throw new IllegalArgumentException("Unable to parse property " + propertyName + " when configuring SASL providers", nfe); - } - } - - /** - * Selects a SASL mechanism that is mutually available to both parties. If more than one - * mechanism is mutually available the one appearing first (by ordinal) will be returned. - * - * @param peerMechanismList space separated list of mechanisms - * @return selected mechanism, or null if none available - */ - public String selectMechanism(final String peerMechanismList) - { - final Set<String> peerList = mechListToSet(peerMechanismList); - - return selectMechInternal(peerList, Collections.<String>emptySet()); - } - - /** - * Selects a SASL mechanism that is mutually available to both parties. - * - * @param peerMechanismList space separated list of mechanisms - * @param restrictionList space separated list of mechanisms - * @return selected mechanism, or null if none available - */ - public String selectMechanism(final String peerMechanismList, final String restrictionList) - { - final Set<String> peerList = mechListToSet(peerMechanismList); - final Set<String> restrictionSet = mechListToSet(restrictionList); - - return selectMechInternal(peerList, restrictionSet); - } - - private String selectMechInternal(final Set<String> peerSet, final Set<String> restrictionSet) - { - for (final String mech : _mechanisms) - { - if (peerSet.contains(mech)) - { - if (restrictionSet.isEmpty() || restrictionSet.contains(mech)) - { - return mech; - } - } - } - - return null; - } - - private Set<String> mechListToSet(final String mechanismList) - { - if (mechanismList == null) - { - return Collections.emptySet(); - } - - final StringTokenizer tokenizer = new StringTokenizer(mechanismList, " "); - final Set<String> mechanismSet = new HashSet<String>(tokenizer.countTokens()); - while (tokenizer.hasMoreTokens()) - { - mechanismSet.add(tokenizer.nextToken()); - } - return Collections.unmodifiableSet(mechanismSet); - } - - public boolean isUserPassRequired(String selectedMech) - { - return MECHS_THAT_NEED_USERPASS.contains(selectedMech); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/security/CallbackHandlerRegistry.properties b/qpid/java/client/src/main/java/org/apache/qpid/client/security/CallbackHandlerRegistry.properties deleted file mode 100644 index b77fa033d6..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/security/CallbackHandlerRegistry.properties +++ /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. -# - -# -# Format: -# <mechanism name>.ordinal=<implementation> -# -# @see CallbackHandlerRegistry -# - -EXTERNAL.1=org.apache.qpid.client.security.UsernamePasswordCallbackHandler -GSSAPI.2=org.apache.qpid.client.security.UsernamePasswordCallbackHandler -SCRAM-SHA-256.3=org.apache.qpid.client.security.UsernamePasswordCallbackHandler -SCRAM-SHA-1.4=org.apache.qpid.client.security.UsernamePasswordCallbackHandler -CRAM-MD5-HASHED.5=org.apache.qpid.client.security.UsernameHashedPasswordCallbackHandler -CRAM-MD5.6=org.apache.qpid.client.security.UsernamePasswordCallbackHandler -PLAIN.7=org.apache.qpid.client.security.UsernamePasswordCallbackHandler -AMQPLAIN.8=org.apache.qpid.client.security.UsernamePasswordCallbackHandler -ANONYMOUS.9=org.apache.qpid.client.security.UsernamePasswordCallbackHandler - diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/security/DynamicSaslRegistrar.java b/qpid/java/client/src/main/java/org/apache/qpid/client/security/DynamicSaslRegistrar.java deleted file mode 100644 index 2be9a0ffde..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/security/DynamicSaslRegistrar.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.client.security; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.util.FileUtils; - -import javax.security.sasl.SaslClientFactory; -import java.io.IOException; -import java.io.InputStream; -import java.security.Provider; -import java.security.Security; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; -import java.util.TreeMap; - -/** - * DynamicSaslRegistrar provides a collection of helper methods for reading a configuration file that contains a mapping - * from SASL mechanism names to implementing client factory class names and registering a security provider with the - * Java runtime system, that uses the configured client factory implementations. - * <p> - * The sasl configuration should be specified in a properties file, refered to by the System property - * "amp.dynamicsaslregistrar.properties". The format of the properties file is: - * <p> - * <pre> - * mechanism=fully.qualified.class.name - * </pre> - * <p> - * Where mechanism is an IANA-registered mechanism name and the fully qualified class name refers to a class that - * implements javax.security.sasl.SaslClientFactory and provides the specified mechanism. - */ -public class DynamicSaslRegistrar -{ - private static final Logger _logger = LoggerFactory.getLogger(DynamicSaslRegistrar.class); - - /** The name of the system property that holds the name of the SASL configuration properties. */ - private static final String FILE_PROPERTY = "amq.dynamicsaslregistrar.properties"; - - /** The default name of the SASL properties file resource. */ - public static final String DEFAULT_RESOURCE_NAME = "org/apache/qpid/client/security/DynamicSaslRegistrar.properties"; - - private DynamicSaslRegistrar() - { - } - - /** Reads the properties file, and creates a dynamic security provider to register the SASL implementations with. */ - public static ProviderRegistrationResult registerSaslProviders() - { - _logger.debug("public static void registerSaslProviders(): called"); - ProviderRegistrationResult result = ProviderRegistrationResult.FAILED; - // Open the SASL properties file, using the default name is one is not specified. - String filename = System.getProperty(FILE_PROPERTY); - InputStream is = - FileUtils.openFileOrDefaultResource(filename, DEFAULT_RESOURCE_NAME, - DynamicSaslRegistrar.class.getClassLoader()); - - try - { - Properties props = new Properties(); - props.load(is); - - _logger.debug("props = " + props); - - Map<String, Class<? extends SaslClientFactory>> factories = parseProperties(props); - - if (factories.size() > 0) - { - // Ensure we are used before the defaults - JCAProvider qpidProvider = new JCAProvider(factories); - if (Security.insertProviderAt(qpidProvider, 1) == -1) - { - Provider registeredProvider = findProvider(JCAProvider.QPID_CLIENT_SASL_PROVIDER_NAME); - if (registeredProvider == null) - { - result = ProviderRegistrationResult.FAILED; - _logger.error("Unable to load custom SASL providers."); - } - else if (registeredProvider.equals(qpidProvider)) - { - result = ProviderRegistrationResult.EQUAL_ALREADY_REGISTERED; - _logger.debug("Custom SASL provider is already registered with equal properties."); - } - else - { - result = ProviderRegistrationResult.DIFFERENT_ALREADY_REGISTERED; - _logger.warn("Custom SASL provider was already registered with different properties."); - if (_logger.isDebugEnabled()) - { - _logger.debug("Custom SASL provider " + registeredProvider + " properties: " + new HashMap<Object, Object>(registeredProvider)); - } - } - } - else - { - result = ProviderRegistrationResult.SUCCEEDED; - _logger.info("Additional SASL providers successfully registered."); - } - } - else - { - result = ProviderRegistrationResult.NO_SASL_FACTORIES; - _logger.warn("No additional SASL factories found to register."); - } - } - catch (IOException e) - { - result = ProviderRegistrationResult.FAILED; - _logger.error("Error reading properties: " + e, e); - } - finally - { - if (is != null) - { - try - { - is.close(); - - } - catch (IOException e) - { - _logger.error("Unable to close properties stream: " + e, e); - } - } - } - return result; - } - - static Provider findProvider(String name) - { - Provider[] providers = Security.getProviders(); - Provider registeredProvider = null; - for (Provider provider : providers) - { - if (name.equals(provider.getName())) - { - registeredProvider = provider; - break; - } - } - return registeredProvider; - } - - /** - * Parses the specified properties as a mapping from IANA registered SASL mechanism names to implementing client - * factories. If the client factories cannot be instantiated or do not implement SaslClientFactory then the - * properties refering to them are ignored. - * - * @param props The properties to scan for Sasl client factory implementations. - * - * @return A map from SASL mechanism names to implementing client factory classes. - * - * @todo Why tree map here? Do really want mechanisms in alphabetical order? Seems more likely that the declared - * order of the mechanisms is intended to be preserved, so that they are registered in the declared order of - * preference. Consider LinkedHashMap instead. - */ - private static Map<String, Class<? extends SaslClientFactory>> parseProperties(Properties props) - { - Enumeration e = props.propertyNames(); - - TreeMap<String, Class<? extends SaslClientFactory>> factoriesToRegister = - new TreeMap<String, Class<? extends SaslClientFactory>>(); - - while (e.hasMoreElements()) - { - String mechanism = (String) e.nextElement(); - String className = props.getProperty(mechanism); - try - { - Class<?> clazz = Class.forName(className); - if (!(SaslClientFactory.class.isAssignableFrom(clazz))) - { - _logger.error("Class " + clazz + " does not implement " + SaslClientFactory.class + " - skipping"); - - continue; - } - - _logger.debug("Found class "+ clazz.getName() +" for mechanism "+mechanism); - factoriesToRegister.put(mechanism, (Class<? extends SaslClientFactory>) clazz); - } - catch (Exception ex) - { - _logger.error("Error instantiating SaslClientFactory class " + className + " - skipping"); - } - } - - return factoriesToRegister; - } - - public static enum ProviderRegistrationResult - { - SUCCEEDED, - EQUAL_ALREADY_REGISTERED, - DIFFERENT_ALREADY_REGISTERED, - NO_SASL_FACTORIES, - FAILED; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/security/DynamicSaslRegistrar.properties b/qpid/java/client/src/main/java/org/apache/qpid/client/security/DynamicSaslRegistrar.properties deleted file mode 100644 index 24a76982ef..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/security/DynamicSaslRegistrar.properties +++ /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. -# -AMQPLAIN=org.apache.qpid.client.security.amqplain.AmqPlainSaslClientFactory -CRAM-MD5-HASHED=org.apache.qpid.client.security.crammd5hashed.CRAMMD5HashedSaslClientFactory -ANONYMOUS=org.apache.qpid.client.security.anonymous.AnonymousSaslClientFactory -SCRAM-SHA-1=org.apache.qpid.client.security.scram.ScramSHA1SaslClientFactory -SCRAM-SHA-256=org.apache.qpid.client.security.scram.ScramSHA256SaslClientFactory diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/security/JCAProvider.java b/qpid/java/client/src/main/java/org/apache/qpid/client/security/JCAProvider.java deleted file mode 100644 index c9bcaf0d15..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/security/JCAProvider.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.client.security; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.security.sasl.SaslClientFactory; -import java.security.Provider; -import java.util.Map; - -/** - * JCAProvider is a security provider for SASL client factories that is configured from a map of SASL mechanism names - * to client factories implementation class names. It is intended that the map of client factories can be read from a - * configuration file or other application configuration mechanism. - * - * <p><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Register SASL mechanism implementations. - * </table> - */ -public class JCAProvider extends Provider -{ - static final String QPID_CLIENT_SASL_PROVIDER_NAME = "AMQSASLProvider-Client"; - static final String QPID_CLIENT_SASL_PROVIDER_INFO = "A JCA provider that registers all " - + "AMQ SASL providers that want to be registered"; - static final double QPID_CLIENT_SASL_PROVIDER_VERSION = 1.0; - - private static final Logger log = LoggerFactory.getLogger(JCAProvider.class); - - /** - * 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(QPID_CLIENT_SASL_PROVIDER_NAME, QPID_CLIENT_SASL_PROVIDER_VERSION, QPID_CLIENT_SASL_PROVIDER_INFO); - 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()); - log.debug("Recording SASL Client factory for " + me.getKey() + " as " + me.getValue().getName()); - } - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/security/UsernameHashedPasswordCallbackHandler.java b/qpid/java/client/src/main/java/org/apache/qpid/client/security/UsernameHashedPasswordCallbackHandler.java deleted file mode 100644 index fe24d48329..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/security/UsernameHashedPasswordCallbackHandler.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.client.security; - -import org.apache.qpid.jms.ConnectionURL; - -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.NameCallback; -import javax.security.auth.callback.PasswordCallback; -import javax.security.auth.callback.UnsupportedCallbackException; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; - -public class UsernameHashedPasswordCallbackHandler implements AMQCallbackHandler -{ - private ConnectionURL _connectionURL; - - /** - * @see org.apache.qpid.client.security.AMQCallbackHandler#initialise(org.apache.qpid.jms.ConnectionURL) - */ - @Override - public void initialise(ConnectionURL connectionURL) - { - _connectionURL = connectionURL; - } - - public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException - { - for (int i = 0; i < callbacks.length; i++) - { - Callback cb = callbacks[i]; - if (cb instanceof NameCallback) - { - ((NameCallback) cb).setName(_connectionURL.getUsername()); - } - else if (cb instanceof PasswordCallback) - { - try - { - ((PasswordCallback) cb).setPassword(getHash(_connectionURL.getPassword())); - } - catch (NoSuchAlgorithmException e) - { - UnsupportedCallbackException uce = new UnsupportedCallbackException(cb); - uce.initCause(e); - throw uce; - } - } - else - { - throw new UnsupportedCallbackException(cb); - } - } - } - - private char[] getHash(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException - { - - byte[] data = text.getBytes("utf-8"); - - MessageDigest md = MessageDigest.getInstance("MD5"); - - for (byte b : data) - { - md.update(b); - } - - byte[] digest = md.digest(); - - char[] hash = new char[digest.length]; - - int index = 0; - for (byte b : digest) - { - hash[index++] = (char) b; - } - - return hash; - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/security/UsernamePasswordCallbackHandler.java b/qpid/java/client/src/main/java/org/apache/qpid/client/security/UsernamePasswordCallbackHandler.java deleted file mode 100644 index 99b5f247ef..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/security/UsernamePasswordCallbackHandler.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.client.security; - -import org.apache.qpid.jms.ConnectionURL; - -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.NameCallback; -import javax.security.auth.callback.PasswordCallback; -import javax.security.auth.callback.UnsupportedCallbackException; -import java.io.IOException; - -public class UsernamePasswordCallbackHandler implements AMQCallbackHandler -{ - private ConnectionURL _connectionURL; - - /** - * @see org.apache.qpid.client.security.AMQCallbackHandler#initialise(org.apache.qpid.jms.ConnectionURL) - */ - @Override - public void initialise(final ConnectionURL connectionURL) - { - _connectionURL = connectionURL; - } - - public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException - { - for (int i = 0; i < callbacks.length; i++) - { - Callback cb = callbacks[i]; - if (cb instanceof NameCallback) - { - ((NameCallback)cb).setName(_connectionURL.getUsername()); - } - else if (cb instanceof PasswordCallback) - { - ((PasswordCallback)cb).setPassword(_connectionURL.getPassword().toCharArray()); - } - else - { - throw new UnsupportedCallbackException(cb); - } - } - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/security/amqplain/AmqPlainSaslClient.java b/qpid/java/client/src/main/java/org/apache/qpid/client/security/amqplain/AmqPlainSaslClient.java deleted file mode 100644 index 5f9a240e8f..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/security/amqplain/AmqPlainSaslClient.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.client.security.amqplain; - -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.FieldTableFactory; - -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.sasl.SaslClient; -import javax.security.sasl.SaslException; - -/** - * Implements the "AMQPlain" authentication protocol that uses FieldTables to send username and pwd. - * - */ -public class AmqPlainSaslClient implements SaslClient -{ - /** - * The name of this mechanism - */ - public static final String MECHANISM = "AMQPLAIN"; - - private CallbackHandler _cbh; - - public AmqPlainSaslClient(CallbackHandler cbh) - { - _cbh = cbh; - } - - public String getMechanismName() - { - return "AMQPLAIN"; - } - - public boolean hasInitialResponse() - { - return true; - } - - public byte[] evaluateChallenge(byte[] challenge) throws SaslException - { - // we do not care about the prompt or the default name - NameCallback nameCallback = new NameCallback("prompt", "defaultName"); - PasswordCallback pwdCallback = new PasswordCallback("prompt", false); - Callback[] callbacks = new Callback[]{nameCallback, pwdCallback}; - try - { - _cbh.handle(callbacks); - } - catch (Exception e) - { - throw new SaslException("Error handling SASL callbacks: " + e, e); - } - FieldTable table = FieldTableFactory.newFieldTable(); - table.setString("LOGIN", nameCallback.getName()); - table.setString("PASSWORD", new String(pwdCallback.getPassword())); - return table.getDataAsBytes(); - } - - public boolean isComplete() - { - return true; - } - - public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException - { - throw new SaslException("Not supported"); - } - - public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException - { - throw new SaslException("Not supported"); - } - - public Object getNegotiatedProperty(String propName) - { - return null; - } - - public void dispose() throws SaslException - { - _cbh = null; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/security/amqplain/AmqPlainSaslClientFactory.java b/qpid/java/client/src/main/java/org/apache/qpid/client/security/amqplain/AmqPlainSaslClientFactory.java deleted file mode 100644 index f1d7da2e94..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/security/amqplain/AmqPlainSaslClientFactory.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.client.security.amqplain; - -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; -import java.util.Map; - -public class AmqPlainSaslClientFactory implements SaslClientFactory -{ - public SaslClient createSaslClient(String[] mechanisms, String authorizationId, String protocol, String serverName, Map props, CallbackHandler cbh) throws SaslException - { - for (int i = 0; i < mechanisms.length; i++) - { - if (mechanisms[i].equals(AmqPlainSaslClient.MECHANISM)) - { - if (cbh == null) - { - throw new SaslException("CallbackHandler must not be null"); - } - return new AmqPlainSaslClient(cbh); - } - } - 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[]{AmqPlainSaslClient.MECHANISM}; - } - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/security/anonymous/AnonymousSaslClient.java b/qpid/java/client/src/main/java/org/apache/qpid/client/security/anonymous/AnonymousSaslClient.java deleted file mode 100644 index 0f56b2ef6c..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/security/anonymous/AnonymousSaslClient.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.client.security.anonymous; - -import javax.security.sasl.SaslClient; -import javax.security.sasl.SaslException; - -public class AnonymousSaslClient implements SaslClient -{ - public String getMechanismName() { - return "ANONYMOUS"; - } - public boolean hasInitialResponse() { - return true; - } - public byte[] evaluateChallenge(byte[] challenge) throws SaslException { - return new byte[0]; - } - public boolean isComplete() { - return true; - } - public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException - { - throw new IllegalStateException("No security layer supported"); - } - public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException - { - throw new IllegalStateException("No security layer supported"); - } - public Object getNegotiatedProperty(String propName) { - return null; - } - public void dispose() throws SaslException {} -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/security/anonymous/AnonymousSaslClientFactory.java b/qpid/java/client/src/main/java/org/apache/qpid/client/security/anonymous/AnonymousSaslClientFactory.java deleted file mode 100644 index 283ba5f632..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/security/anonymous/AnonymousSaslClientFactory.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.client.security.anonymous; - -import javax.security.auth.callback.CallbackHandler; -import javax.security.sasl.SaslClient; -import javax.security.sasl.SaslClientFactory; -import javax.security.sasl.SaslException; -import java.util.Arrays; -import java.util.Map; - -public class AnonymousSaslClientFactory implements SaslClientFactory -{ - public SaslClient createSaslClient(String[] mechanisms, String authId, - String protocol, String server, - Map props, CallbackHandler cbh) throws SaslException - { - if (Arrays.asList(mechanisms).contains("ANONYMOUS")) { - return new AnonymousSaslClient(); - } else { - return null; - } - } - public String[] getMechanismNames(Map props) - { - if (props == null || props.isEmpty()) { - return new String[]{"ANONYMOUS"}; - } else { - return new String[0]; - } - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/security/crammd5hashed/CRAMMD5HashedSaslClient.java b/qpid/java/client/src/main/java/org/apache/qpid/client/security/crammd5hashed/CRAMMD5HashedSaslClient.java deleted file mode 100644 index 9965176772..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/security/crammd5hashed/CRAMMD5HashedSaslClient.java +++ /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. - * - */ -package org.apache.qpid.client.security.crammd5hashed; - -import java.util.Map; - -import javax.security.auth.callback.CallbackHandler; -import javax.security.sasl.Sasl; -import javax.security.sasl.SaslClient; -import javax.security.sasl.SaslException; - -import org.apache.qpid.client.security.UsernameHashedPasswordCallbackHandler; - -/** - * A {@link CRAMMD5HashedSaslClient} merely wraps an instance of a CRAM-MD5 SASL client delegating - * all method calls to it, except {@link #getMechanismName()} which returns "CRAM-MD5-HASHED". - * - * This mechanism must be used with {@link UsernameHashedPasswordCallbackHandler} which is responsible - * for the additional hash of the password. - */ -public class CRAMMD5HashedSaslClient implements SaslClient -{ - private final SaslClient _cramMd5SaslClient; - - public CRAMMD5HashedSaslClient(String authorizationId, String protocol, String serverName, Map<String, ?> props, CallbackHandler cbh) throws SaslException - { - super(); - String[] mechanisms = {"CRAM-MD5"}; - _cramMd5SaslClient = Sasl.createSaslClient(mechanisms, authorizationId, protocol, serverName, props, cbh); - } - - public void dispose() throws SaslException - { - _cramMd5SaslClient.dispose(); - } - - public String getMechanismName() - { - return CRAMMD5HashedSaslClientFactory.MECHANISM; - } - - public byte[] evaluateChallenge(byte[] challenge) throws SaslException - { - return _cramMd5SaslClient.evaluateChallenge(challenge); - } - - - public Object getNegotiatedProperty(String propName) - { - return _cramMd5SaslClient.getNegotiatedProperty(propName); - } - - public boolean hasInitialResponse() - { - return _cramMd5SaslClient.hasInitialResponse(); - } - - public boolean isComplete() - { - return _cramMd5SaslClient.isComplete(); - } - - public byte[] unwrap(byte[] incoming, int offset, int len) - throws SaslException - { - return _cramMd5SaslClient.unwrap(incoming, offset, len); - } - - public byte[] wrap(byte[] outgoing, int offset, int len) - throws SaslException - { - return _cramMd5SaslClient.wrap(outgoing, offset, len); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/security/crammd5hashed/CRAMMD5HashedSaslClientFactory.java b/qpid/java/client/src/main/java/org/apache/qpid/client/security/crammd5hashed/CRAMMD5HashedSaslClientFactory.java deleted file mode 100644 index b3ce1a0d23..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/security/crammd5hashed/CRAMMD5HashedSaslClientFactory.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.client.security.crammd5hashed; - -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; -import java.util.Map; - -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"); - } - - return new CRAMMD5HashedSaslClient(authorizationId, protocol, serverName, props, cbh); - } - } - return null; - } - - public String[] getMechanismNames(Map<String,?> 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[]{MECHANISM}; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/security/scram/AbstractScramSaslClient.java b/qpid/java/client/src/main/java/org/apache/qpid/client/security/scram/AbstractScramSaslClient.java deleted file mode 100644 index 735fb4fb7f..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/security/scram/AbstractScramSaslClient.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.client.security.scram; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.nio.charset.Charset; -import java.security.InvalidKeyException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Arrays; -import java.util.UUID; - -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; -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.SaslClient; -import javax.security.sasl.SaslException; -import javax.xml.bind.DatatypeConverter; - -public abstract class AbstractScramSaslClient implements SaslClient -{ - - private static final byte[] INT_1 = new byte[]{0, 0, 0, 1}; - private static final String GS2_HEADER = "n,,"; - private static final Charset ASCII = Charset.forName("ASCII"); - - private final String _digestName; - private final String _hmacName; - - private String _username; - private final String _clientNonce = UUID.randomUUID().toString(); - private String _serverNonce; - private byte[] _salt; - private int _iterationCount; - private String _clientFirstMessageBare; - private byte[] _serverSignature; - - enum State - { - INITIAL, - CLIENT_FIRST_SENT, - CLIENT_PROOF_SENT, - COMPLETE - } - - public final String _mechanism; - - private final CallbackHandler _callbackHandler; - - private State _state = State.INITIAL; - - public AbstractScramSaslClient(final CallbackHandler cbh, - final String mechanism, - final String digestName, - final String hmacName) - { - _callbackHandler = cbh; - _mechanism = mechanism; - _digestName = digestName; - _hmacName = hmacName; - - } - - @Override - public String getMechanismName() - { - return _mechanism; - } - - @Override - public boolean hasInitialResponse() - { - return true; - } - - @Override - public byte[] evaluateChallenge(final byte[] challenge) throws SaslException - { - byte[] response; - switch(_state) - { - case INITIAL: - response = initialResponse(); - _state = State.CLIENT_FIRST_SENT; - break; - case CLIENT_FIRST_SENT: - response = calculateClientProof(challenge); - _state = State.CLIENT_PROOF_SENT; - break; - case CLIENT_PROOF_SENT: - evaluateOutcome(challenge); - response = new byte[0]; - _state = State.COMPLETE; - break; - default: - throw new SaslException("No challenge expected in state " + _state); - } - return response; - } - - private void evaluateOutcome(final byte[] challenge) throws SaslException - { - String serverFinalMessage = new String(challenge, ASCII); - String[] parts = serverFinalMessage.split(","); - if(!parts[0].startsWith("v=")) - { - throw new SaslException("Server final message did not contain verifier"); - } - byte[] serverSignature = DatatypeConverter.parseBase64Binary(parts[0].substring(2)); - if(!Arrays.equals(_serverSignature, serverSignature)) - { - throw new SaslException("Server signature did not match"); - } - } - - private byte[] calculateClientProof(final byte[] challenge) throws SaslException - { - try - { - String serverFirstMessage = new String(challenge, ASCII); - String[] parts = serverFirstMessage.split(","); - if(parts.length < 3) - { - throw new SaslException("Server challenge '" + serverFirstMessage + "' cannot be parsed"); - } - else if(parts[0].startsWith("m=")) - { - throw new SaslException("Server requires mandatory extension which is not supported: " + parts[0]); - } - else if(!parts[0].startsWith("r=")) - { - throw new SaslException("Server challenge '" + serverFirstMessage + "' cannot be parsed, cannot find nonce"); - } - String nonce = parts[0].substring(2); - if(!nonce.startsWith(_clientNonce)) - { - throw new SaslException("Server challenge did not use correct client nonce"); - } - _serverNonce = nonce; - if(!parts[1].startsWith("s=")) - { - throw new SaslException("Server challenge '" + serverFirstMessage + "' cannot be parsed, cannot find salt"); - } - String base64Salt = parts[1].substring(2); - _salt = DatatypeConverter.parseBase64Binary(base64Salt); - if(!parts[2].startsWith("i=")) - { - throw new SaslException("Server challenge '" + serverFirstMessage + "' cannot be parsed, cannot find iteration count"); - } - String iterCountString = parts[2].substring(2); - _iterationCount = Integer.parseInt(iterCountString); - if(_iterationCount <= 0) - { - throw new SaslException("Iteration count " + _iterationCount + " is not a positive integer"); - } - PasswordCallback passwordCallback = new PasswordCallback("Password", false); - _callbackHandler.handle(new Callback[] { passwordCallback }); - byte[] passwordBytes = saslPrep(new String(passwordCallback.getPassword())).getBytes("UTF-8"); - - byte[] saltedPassword = generateSaltedPassword(passwordBytes); - - - String clientFinalMessageWithoutProof = - "c=" + DatatypeConverter.printBase64Binary(GS2_HEADER.getBytes(ASCII)) - + ",r=" + _serverNonce; - - String authMessage = _clientFirstMessageBare + "," + serverFirstMessage + "," + clientFinalMessageWithoutProof; - - byte[] clientKey = computeHmac(saltedPassword, "Client Key"); - byte[] storedKey = MessageDigest.getInstance(_digestName).digest(clientKey); - - byte[] clientSignature = computeHmac(storedKey, authMessage); - - byte[] clientProof = clientKey.clone(); - for(int i = 0 ; i < clientProof.length; i++) - { - clientProof[i] ^= clientSignature[i]; - } - byte[] serverKey = computeHmac(saltedPassword, "Server Key"); - _serverSignature = computeHmac(serverKey, authMessage); - - String finalMessageWithProof = clientFinalMessageWithoutProof - + ",p=" + DatatypeConverter.printBase64Binary(clientProof); - return finalMessageWithProof.getBytes(); - } - catch (UnsupportedEncodingException e) - { - throw new SaslException(e.getMessage(), e); - } - catch (IllegalArgumentException e) - { - throw new SaslException(e.getMessage(), e); - } - catch (UnsupportedCallbackException e) - { - throw new SaslException(e.getMessage(), e); - } - catch (IOException e) - { - throw new SaslException(e.getMessage(), e); - } - catch (NoSuchAlgorithmException e) - { - throw new SaslException(e.getMessage(), e); - } - } - - private byte[] computeHmac(final byte[] key, final String string) - throws SaslException, UnsupportedEncodingException - { - Mac mac = createHmac(key); - mac.update(string.getBytes(ASCII)); - return mac.doFinal(); - } - - private byte[] generateSaltedPassword(final byte[] passwordBytes) throws SaslException - { - Mac mac = createHmac(passwordBytes); - - mac.update(_salt); - mac.update(INT_1); - byte[] result = mac.doFinal(); - - byte[] previous = null; - for(int i = 1; i < _iterationCount; i++) - { - mac.update(previous != null? previous: result); - previous = mac.doFinal(); - for(int x = 0; x < result.length; x++) - { - result[x] ^= previous[x]; - } - } - - return result; - } - - private Mac createHmac(final byte[] keyBytes) - throws SaslException - { - try - { - SecretKeySpec key = new SecretKeySpec(keyBytes, _hmacName); - Mac mac = Mac.getInstance(_hmacName); - mac.init(key); - return mac; - } - catch (NoSuchAlgorithmException e) - { - throw new SaslException(e.getMessage(), e); - } - catch (InvalidKeyException e) - { - throw new SaslException(e.getMessage(), e); - } - } - - - private byte[] initialResponse() throws SaslException - { - try - { - StringBuffer buf = new StringBuffer("n="); - NameCallback nameCallback = new NameCallback("Username?"); - _callbackHandler.handle(new Callback[] { nameCallback }); - _username = nameCallback.getName(); - buf.append(saslPrep(_username)); - buf.append(",r="); - buf.append(_clientNonce); - _clientFirstMessageBare = buf.toString(); - return (GS2_HEADER + _clientFirstMessageBare).getBytes(ASCII); - } - catch (UnsupportedCallbackException e) - { - throw new SaslException(e.getMessage(), e); - } - catch (IOException e) - { - throw new SaslException(e.getMessage(), e); - } - } - - private String saslPrep(String name) throws SaslException - { - // TODO - a real implementation of SaslPrep - - if(!ASCII.newEncoder().canEncode(name)) - { - throw new SaslException("Can only encode names and passwords which are restricted to ASCII characters"); - } - - name = name.replace("=", "=3D"); - name = name.replace(",", "=2C"); - return name; - } - - @Override - public boolean isComplete() - { - return _state == State.COMPLETE; - } - - @Override - public byte[] unwrap(final byte[] incoming, final int offset, final int len) throws SaslException - { - throw new IllegalStateException("No security layer supported"); - } - - @Override - public byte[] wrap(final byte[] outgoing, final int offset, final int len) throws SaslException - { - throw new IllegalStateException("No security layer supported"); - } - - @Override - public Object getNegotiatedProperty(final String propName) - { - return null; - } - - @Override - public void dispose() throws SaslException - { - - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/security/scram/ScramSHA1SaslClient.java b/qpid/java/client/src/main/java/org/apache/qpid/client/security/scram/ScramSHA1SaslClient.java deleted file mode 100644 index b6704e9d94..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/security/scram/ScramSHA1SaslClient.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.client.security.scram; - -import javax.security.auth.callback.CallbackHandler; - -public class ScramSHA1SaslClient extends AbstractScramSaslClient -{ - - public static final String MECHANISM = "SCRAM-SHA-1"; - - public ScramSHA1SaslClient(final CallbackHandler cbh) - { - super(cbh, MECHANISM, "SHA-1", "HmacSHA1"); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/security/scram/ScramSHA1SaslClientFactory.java b/qpid/java/client/src/main/java/org/apache/qpid/client/security/scram/ScramSHA1SaslClientFactory.java deleted file mode 100644 index 59ef236bde..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/security/scram/ScramSHA1SaslClientFactory.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.client.security.scram; - -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 ScramSHA1SaslClientFactory implements SaslClientFactory -{ - - @Override - public SaslClient createSaslClient(final String[] mechanisms, - final String authorizationId, - final String protocol, - final String serverName, - final Map<String, ?> props, - final CallbackHandler cbh) throws SaslException - { - for (int i = 0; i < mechanisms.length; i++) - { - if (mechanisms[i].equals(ScramSHA1SaslClient.MECHANISM)) - { - if (cbh == null) - { - throw new SaslException("CallbackHandler must not be null"); - } - return new ScramSHA1SaslClient(cbh); - } - } - return null; - } - - @Override - public String[] getMechanismNames(final Map<String, ?> props) - { - return new String[0]; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/security/scram/ScramSHA256SaslClient.java b/qpid/java/client/src/main/java/org/apache/qpid/client/security/scram/ScramSHA256SaslClient.java deleted file mode 100644 index 8779c36f0d..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/security/scram/ScramSHA256SaslClient.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.client.security.scram; - -import javax.security.auth.callback.CallbackHandler; - -public class ScramSHA256SaslClient extends AbstractScramSaslClient -{ - - public static final String MECHANISM = "SCRAM-SHA-256"; - - public ScramSHA256SaslClient(final CallbackHandler cbh) - { - super(cbh, MECHANISM, "SHA-256", "HmacSHA256"); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/security/scram/ScramSHA256SaslClientFactory.java b/qpid/java/client/src/main/java/org/apache/qpid/client/security/scram/ScramSHA256SaslClientFactory.java deleted file mode 100644 index fff762f8ba..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/security/scram/ScramSHA256SaslClientFactory.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.client.security.scram; - -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 ScramSHA256SaslClientFactory implements SaslClientFactory -{ - - @Override - public SaslClient createSaslClient(final String[] mechanisms, - final String authorizationId, - final String protocol, - final String serverName, - final Map<String, ?> props, - final CallbackHandler cbh) throws SaslException - { - for (int i = 0; i < mechanisms.length; i++) - { - if (mechanisms[i].equals(ScramSHA256SaslClient.MECHANISM)) - { - if (cbh == null) - { - throw new SaslException("CallbackHandler must not be null"); - } - return new ScramSHA256SaslClient(cbh); - } - - } - return null; - } - - @Override - public String[] getMechanismNames(final Map<String, ?> props) - { - return new String[0]; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/state/AMQMethodNotImplementedException.java b/qpid/java/client/src/main/java/org/apache/qpid/client/state/AMQMethodNotImplementedException.java deleted file mode 100644 index f7d8b2bf35..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/state/AMQMethodNotImplementedException.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.client.state; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQMethodBody; - -public class AMQMethodNotImplementedException extends AMQException -{ - public AMQMethodNotImplementedException(AMQMethodBody body) - { - super(null, "Unexpected Method Received: " + body.getClass().getName(), null); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/state/AMQState.java b/qpid/java/client/src/main/java/org/apache/qpid/client/state/AMQState.java deleted file mode 100644 index d32d10542f..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/state/AMQState.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.client.state; - -/** - * States used in the AMQ protocol. Used by the finite state machine to determine - * valid responses. - */ -public enum AMQState -{ - - CONNECTION_NOT_STARTED(1, "CONNECTION_NOT_STARTED"), - - CONNECTION_NOT_TUNED(2, "CONNECTION_NOT_TUNED"), - - CONNECTION_NOT_OPENED(3, "CONNECTION_NOT_OPENED"), - - CONNECTION_OPEN(4, "CONNECTION_OPEN"), - - CONNECTION_CLOSING(5, "CONNECTION_CLOSING"), - - CONNECTION_CLOSED(6, "CONNECTION_CLOSED"); - - - private final int _id; - - private final String _name; - - private AMQState(int id, String name) - { - _id = id; - _name = name; - } - - public String toString() - { - return "AMQState: id = " + _id + " name: " + _name; - } - - - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/state/AMQStateChangedEvent.java b/qpid/java/client/src/main/java/org/apache/qpid/client/state/AMQStateChangedEvent.java deleted file mode 100644 index edef54ccd6..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/state/AMQStateChangedEvent.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.client.state; - -/** - * An event that is fired when the protocol state has changed. - * - */ -public class AMQStateChangedEvent -{ - private final AMQState _oldState; - - private final AMQState _newState; - - public AMQStateChangedEvent(AMQState oldState, AMQState newState) - { - _oldState = oldState; - _newState = newState; - } - - public AMQState getOldState() - { - return _oldState; - } - - public AMQState getNewState() - { - return _newState; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/state/AMQStateListener.java b/qpid/java/client/src/main/java/org/apache/qpid/client/state/AMQStateListener.java deleted file mode 100644 index 110471aad0..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/state/AMQStateListener.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.client.state; - -public interface AMQStateListener -{ - void stateChanged(AMQStateChangedEvent evt); -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/state/AMQStateManager.java b/qpid/java/client/src/main/java/org/apache/qpid/client/state/AMQStateManager.java deleted file mode 100644 index a44b6a1ff3..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/state/AMQStateManager.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.client.state; - -import java.util.List; -import java.util.Set; -import java.util.concurrent.CopyOnWriteArrayList; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.apache.qpid.framing.AMQMethodBody; -import org.apache.qpid.protocol.AMQMethodEvent; -import org.apache.qpid.protocol.AMQMethodListener; - -/** - * The state manager is responsible for managing the state of the protocol session. - * <p> - * For each {@link org.apache.qpid.client.protocol.AMQProtocolHandler} there is a separate state manager. - * <p> - * The AMQStateManager is now attached to the {@link org.apache.qpid.client.protocol.AMQProtocolHandler} and that is the sole point of reference so that - * As the {@link AMQProtocolSession} changes due to failover the AMQStateManager need not be copied around. - * <p> - * The StateManager works by any component can wait for a state change to occur by using the following sequence. - * <ul> - * <li>{@literal StateWaiter waiter = stateManager.createWaiter(Set<AMQState> states); } - * <li> // Perform action that will cause state change - * <li>waiter.await(); - * </ul> - * <p> - * The two step process is required as there is an inherit race condition between starting a process that will cause - * the state to change and then attempting to wait for that change. The interest in the change must be first set up so - * that any asynchronous errors that occur can be delivered to the correct waiters. - */ -public class AMQStateManager implements AMQMethodListener -{ - private static final Logger _logger = LoggerFactory.getLogger(AMQStateManager.class); - - private AMQProtocolSession _protocolSession; - - /** The current state */ - private AMQState _currentState; - - private final Object _stateLock = new Object(); - - private static final long MAXIMUM_STATE_WAIT_TIME = Long.parseLong(System.getProperty("amqj.MaximumStateWait", "30000")); - - private final List<StateWaiter> _waiters = new CopyOnWriteArrayList<StateWaiter>(); - private Exception _lastException; - - public AMQStateManager() - { - this(null); - } - - public AMQStateManager(AMQProtocolSession protocolSession) - { - this(AMQState.CONNECTION_NOT_STARTED, protocolSession); - } - - protected AMQStateManager(AMQState state, AMQProtocolSession protocolSession) - { - _protocolSession = protocolSession; - _currentState = state; - } - - public AMQState getCurrentState() - { - synchronized (_stateLock) - { - return _currentState; - } - } - - public void changeState(AMQState newState) - { - _logger.debug("State changing to " + newState + " from old state " + _currentState); - - synchronized (_stateLock) - { - _currentState = newState; - - _logger.debug("Notififying State change to " + _waiters.size() + " : " + _waiters); - - for (StateWaiter waiter : _waiters) - { - waiter.received(newState); - } - } - } - - public <B extends AMQMethodBody> boolean methodReceived(AMQMethodEvent<B> evt) throws AMQException - { - B method = evt.getMethod(); - - method.execute(_protocolSession.getMethodDispatcher(), evt.getChannelId()); - return true; - } - - /** - * Setting of the ProtocolSession will be required when Failover has been successfully completed. - * - * The new {@link AMQProtocolSession} that has been re-established needs to be provided as that is now the - * connection to the network. - * - * @param session The new protocol session - */ - public void setProtocolSession(AMQProtocolSession session) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Setting ProtocolSession:" + session); - } - _protocolSession = session; - } - - /** - * Propagate error to waiters - * - * @param error The error to propagate. - */ - public void error(Exception error) - { - if (error instanceof AMQException) - { - // AMQException should be being notified before closing the - // ProtocolSession. Which will change the State to CLOSED. - // if we have a hard error. - if (((AMQException)error).isHardError()) - { - changeState(AMQState.CONNECTION_CLOSING); - } - } - else - { - // Be on the safe side here and mark the connection closed - changeState(AMQState.CONNECTION_CLOSED); - } - - if (_waiters.size() == 0) - { - _logger.info("No Waiters for error. Saving as last error:" + error.getMessage()); - _lastException = error; - } - for (StateWaiter waiter : _waiters) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("Notifying waiter " + waiter + " for error:" + error.getMessage()); - } - waiter.error(error); - } - } - - /** - * This provides a single place that the maximum time for state change to occur can be accessed. - * It is currently set via System property amqj.MaximumStateWait - * - * @return long Milliseconds value for a timeout - */ - public long getWaitTimeout() - { - return MAXIMUM_STATE_WAIT_TIME; - } - - /** - * Create and add a new waiter to the notification list. - * - * @param states The waiter will attempt to wait for one of these desired set states to be achived. - * - * @return the created StateWaiter. - */ - public StateWaiter createWaiter(Set<AMQState> states) - { - final StateWaiter waiter; - synchronized (_stateLock) - { - waiter = new StateWaiter(this, _currentState, states); - - _waiters.add(waiter); - } - - return waiter; - } - - /** - * Remove the waiter from the notification list. - * - * @param waiter The waiter to remove. - */ - public void removeWaiter(StateWaiter waiter) - { - synchronized (_stateLock) - { - _waiters.remove(waiter); - } - } - - public Exception getLastException() - { - return _lastException; - } - - public void clearLastException() - { - _lastException = null; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/state/StateAwareMethodListener.java b/qpid/java/client/src/main/java/org/apache/qpid/client/state/StateAwareMethodListener.java deleted file mode 100644 index 6b038e09c8..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/state/StateAwareMethodListener.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.client.state; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.apache.qpid.framing.AMQMethodBody; - -/** - * A frame listener that is informed of the protocl state when invoked and has - * the opportunity to update state. - * - */ -public interface StateAwareMethodListener<B extends AMQMethodBody> -{ - - void methodReceived(AMQProtocolSession session, B body, int channelId) throws AMQException; - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/state/StateWaiter.java b/qpid/java/client/src/main/java/org/apache/qpid/client/state/StateWaiter.java deleted file mode 100644 index 75b863ca2b..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/state/StateWaiter.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.client.state; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.failover.FailoverException; -import org.apache.qpid.client.util.BlockingWaiter; - -import java.util.Set; - -/** - * This is an implementation of the {@link BlockingWaiter} to provide error handing and a waiting mechanism for state - * changes. - * - * On construction the current state and a set of States to await for is provided. - * - * When await() is called the state at construction is compared against the awaitStates. If the state at construction is - * a desired state then await() returns immediately. - * - * Otherwise it will block for the set timeout for a desired state to be achieved. - * - * The state changes are notified via the {@link #process} method. - * - * Any notified error is handled by the BlockingWaiter and thrown from the {@link #block} method. - * - */ -public class StateWaiter extends BlockingWaiter<AMQState> -{ - private static final Logger _logger = LoggerFactory.getLogger(StateWaiter.class); - - private final Set<AMQState> _awaitStates; - private final AMQState _startState; - private final AMQStateManager _stateManager; - - /** - * - * @param stateManager The StateManager - * @param currentState - * @param awaitStates - */ - public StateWaiter(AMQStateManager stateManager, AMQState currentState, Set<AMQState> awaitStates) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("New StateWaiter :" + currentState + ":" + awaitStates); - } - _stateManager = stateManager; - _awaitStates = awaitStates; - _startState = currentState; - } - - /** - * When the state is changed this StateWaiter is notified to process the change. - * - * @param state The new state that has been achieved. - * @return - */ - public boolean process(AMQState state) - { - return _awaitStates.contains(state); - } - - /** - * Await for the required State to be achieved within the default timeout. - * @return The achieved state that was requested. - * @throws AMQException The exception that prevented the required state from being achieved. - */ - public AMQState await() throws AMQException - { - return await(_stateManager.getWaitTimeout()); - } - - /** - * Await for the required State to be achieved. - * <p> - * It is the responsibility of this class to remove the waiter from the StateManager - * - * @param timeout The time in milliseconds to wait for any of the states to be achieved. - * @return The achieved state that was requested. - * @throws AMQException The exception that prevented the required state from being achieved. - */ - public AMQState await(long timeout) throws AMQException - { - try - { - if (process(_startState)) - { - return _startState; - } - - try - { - return (AMQState) block(timeout); - } - catch (FailoverException e) - { - _logger.error("Failover occured whilst waiting for states:" + _awaitStates); - - return null; - } - } - finally - { - //Prevent any more errors being notified to this waiter. - close(); - - //Remove the waiter from the notifcation list in the statee manager - _stateManager.removeWaiter(this); - } - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/state/listener/SpecificMethodFrameListener.java b/qpid/java/client/src/main/java/org/apache/qpid/client/state/listener/SpecificMethodFrameListener.java deleted file mode 100644 index f0d7feb059..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/state/listener/SpecificMethodFrameListener.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.client.state.listener; - - -import org.apache.qpid.client.protocol.BlockingMethodFrameListener; -import org.apache.qpid.framing.AMQMethodBody; - -public class SpecificMethodFrameListener extends BlockingMethodFrameListener -{ - private final Class _expectedClass; - - public SpecificMethodFrameListener(int channelId, Class expectedClass) - { - super(channelId); - _expectedClass = expectedClass; - } - - public boolean processMethod(int channelId, AMQMethodBody frame) - { - return _expectedClass.isInstance(frame); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/transport/ClientConnectionDelegate.java b/qpid/java/client/src/main/java/org/apache/qpid/client/transport/ClientConnectionDelegate.java deleted file mode 100644 index 51354a5941..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/transport/ClientConnectionDelegate.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.client.transport; - -import org.apache.qpid.client.HeartbeatListener; -import org.apache.qpid.transport.ConnectionHeartbeat; -import org.ietf.jgss.GSSContext; -import org.ietf.jgss.GSSException; -import org.ietf.jgss.GSSManager; -import org.ietf.jgss.GSSName; -import org.ietf.jgss.Oid; - -import org.apache.qpid.client.security.AMQCallbackHandler; -import org.apache.qpid.client.security.CallbackHandlerRegistry; -import org.apache.qpid.jms.ConnectionURL; -import org.apache.qpid.transport.ClientDelegate; -import org.apache.qpid.transport.Connection; -import org.apache.qpid.transport.ConnectionException; -import org.apache.qpid.transport.ConnectionOpenOk; -import org.apache.qpid.transport.ConnectionSettings; -import org.apache.qpid.transport.util.Logger; -import org.apache.qpid.util.Strings; - -import javax.security.sasl.Sasl; -import javax.security.sasl.SaslClient; -import javax.security.sasl.SaslException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * - */ -public class ClientConnectionDelegate extends ClientDelegate -{ - private static final Logger LOGGER = Logger.get(ClientDelegate.class); - - private static final String KRB5_OID_STR = "1.2.840.113554.1.2.2"; - protected static final Oid KRB5_OID; - - static - { - Oid oid; - try - { - oid = new Oid(KRB5_OID_STR); - } - catch (GSSException ignore) - { - oid = null; - } - - KRB5_OID = oid; - } - - private final ConnectionURL _connectionURL; - private HeartbeatListener _heartbeatListener = HeartbeatListener.DEFAULT; - - /** - * @param settings - * @param connectionURL - */ - public ClientConnectionDelegate(ConnectionSettings settings, ConnectionURL connectionURL) - { - super(settings); - this._connectionURL = connectionURL; - } - - @Override - protected SaslClient createSaslClient(List<Object> brokerMechs) throws ConnectionException, SaslException - { - final String brokerMechanisms = Strings.join(" ", brokerMechs); - final String restrictionList = getConnectionSettings().getSaslMechs(); - final String selectedMech = CallbackHandlerRegistry.getInstance().selectMechanism(brokerMechanisms, restrictionList); - if (selectedMech == null) - { - throw new ConnectionException("Client and broker have no SASL mechanisms in common." + - " Broker allows : " + brokerMechanisms + - " Client has : " + CallbackHandlerRegistry.getInstance().getMechanisms() + - " Client restricted itself to : " + (restrictionList != null ? restrictionList : "no restriction")); - } - - if ((_connectionURL.getUsername() == null || _connectionURL.getPassword() == null) - && CallbackHandlerRegistry.getInstance().isUserPassRequired(selectedMech)) - { - throw new ConnectionException("Username and Password is required for the selected mechanism : " + selectedMech + - " Broker allows : " + brokerMechanisms + - " Client has : " + CallbackHandlerRegistry.getInstance().getMechanisms() + - " Client restricted itself to : " + (restrictionList != null ? restrictionList : "no restriction")); - } - - Map<String,Object> saslProps = new HashMap<String,Object>(); - if (getConnectionSettings().isUseSASLEncryption()) - { - saslProps.put(Sasl.QOP, "auth-conf"); - } - - final AMQCallbackHandler handler = CallbackHandlerRegistry.getInstance().createCallbackHandler(selectedMech); - handler.initialise(_connectionURL); - final SaslClient sc = Sasl.createSaslClient(new String[] {selectedMech}, null, getConnectionSettings().getSaslProtocol(), getConnectionSettings().getSaslServerName(), saslProps, handler); - - return sc; - } - - @Override - public void connectionOpenOk(Connection conn, ConnectionOpenOk ok) - { - SaslClient sc = conn.getSaslClient(); - if (sc != null) - { - if (sc.getMechanismName().equals("GSSAPI")) - { - String id = getKerberosUser(); - if (id != null) - { - conn.setUserID(id); - } - } - else if (sc.getMechanismName().equals("EXTERNAL")) - { - if (conn.getSecurityLayer() != null) - { - conn.setUserID(conn.getSecurityLayer().getUserID()); - } - } - } - - super.connectionOpenOk(conn, ok); - } - - private String getKerberosUser() - { - LOGGER.debug("Obtaining userID from kerberos"); - String service = getConnectionSettings().getSaslProtocol() + "@" + getConnectionSettings().getSaslServerName(); - GSSManager manager = GSSManager.getInstance(); - - try - { - GSSName acceptorName = manager.createName(service, - GSSName.NT_HOSTBASED_SERVICE, KRB5_OID); - - GSSContext secCtx = manager.createContext(acceptorName, - KRB5_OID, - null, - GSSContext.INDEFINITE_LIFETIME); - - secCtx.initSecContext(new byte[0], 0, 1); - - if (secCtx.getSrcName() != null) - { - return secCtx.getSrcName().toString(); - } - - } - catch (GSSException e) - { - LOGGER.warn("Unable to retrieve userID from Kerberos due to error",e); - } - - return null; - } - - @Override - public void connectionHeartbeat(Connection conn, ConnectionHeartbeat heartbeat) - { - _heartbeatListener.heartbeatReceived(); - } - - - public void setHeartbeatListener(HeartbeatListener listener) - { - _heartbeatListener = listener == null ? HeartbeatListener.DEFAULT : listener; - } - - @Override - public void writerIdle(final Connection connection) - { - super.writerIdle(connection); - _heartbeatListener.heartbeatSent(); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/url/URLParser.java b/qpid/java/client/src/main/java/org/apache/qpid/client/url/URLParser.java deleted file mode 100644 index 754b5ff6a7..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/url/URLParser.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.client.url; - - -import org.apache.qpid.client.AMQBrokerDetails; -import org.apache.qpid.client.AMQConnectionFactory; -import org.apache.qpid.client.AMQConnectionURL; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.url.URLHelper; -import org.apache.qpid.url.URLSyntaxException; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.StringTokenizer; - -public class URLParser -{ - private AMQConnectionURL _url; - - public URLParser(AMQConnectionURL url)throws URLSyntaxException - { - _url = url; - parseURL(_url.getURL()); - } - - private void parseURL(String fullURL) throws URLSyntaxException - { - // Connection URL format - // amqp://[user:pass@][clientid]/virtualhost?brokerlist='tcp://host:port?option=\'value\',option=\'value\';tcp://host:port?option=\'value\'',failover='method?option=\'value\',option='value''" - // Options are of course optional except for requiring a single broker in the broker list. - try - { - URI connection = new URI(fullURL); - - if ((connection.getScheme() == null) || !(connection.getScheme().equalsIgnoreCase(AMQConnectionURL.AMQ_PROTOCOL))) - { - throw new URISyntaxException(fullURL, "Not an AMQP URL"); - } - - if ((connection.getHost() == null) || connection.getHost().equals("")) - { - String tmp = connection.getAuthority(); - // hack to read a clientid such as "my_clientID" - if (tmp != null && tmp.indexOf('@') < tmp.length()-1) - { - _url.setClientName(tmp.substring(tmp.indexOf('@')+1,tmp.length())); - } - else - { - String uid = AMQConnectionFactory.getUniqueClientID(); - if (uid == null) - { - throw URLHelper.parseError(-1, "Client Name not specified", fullURL); - } - else - { - _url.setClientName(uid); - } - } - - } - else - { - _url.setClientName(connection.getHost()); - } - - String userInfo = connection.getUserInfo(); - - if (userInfo == null) - { - // Fix for Java 1.5 which doesn't parse UserInfo for non http URIs - userInfo = connection.getAuthority(); - - if (userInfo != null) - { - int atIndex = userInfo.indexOf('@'); - - if (atIndex != -1) - { - userInfo = userInfo.substring(0, atIndex); - } - else - { - userInfo = null; - } - } - - } - - if (userInfo != null) - { - parseUserInfo(userInfo); - } - - String virtualHost = connection.getPath(); - - if ((virtualHost != null) && (!virtualHost.equals(""))) - { - _url.setVirtualHost(virtualHost); - } - else - { - int authLength = connection.getAuthority().length(); - int start = AMQConnectionURL.AMQ_PROTOCOL.length() + 3; - int testIndex = start + authLength; - if ((testIndex < fullURL.length()) && (fullURL.charAt(testIndex) == '?')) - { - throw URLHelper.parseError(start, testIndex - start, "Virtual host found", fullURL); - } - else - { - throw URLHelper.parseError(-1, "Virtual host not specified", fullURL); - } - - } - - URLHelper.parseOptions(_url.getOptions(), connection.getQuery()); - - processOptions(); - } - catch (URISyntaxException uris) - { - if (uris instanceof URLSyntaxException) - { - throw (URLSyntaxException) uris; - } - - int slash = fullURL.indexOf("\\"); - - if (slash == -1) - { - throw URLHelper.parseError(uris.getIndex(), uris.getReason(), uris.getInput()); - } - else - { - if ((slash != 0) && (fullURL.charAt(slash - 1) == ':')) - { - throw URLHelper.parseError(slash - 2, fullURL.indexOf('?') - slash + 2, - "Virtual host looks like a windows path, forward slash not allowed in URL", fullURL); - } - else - { - throw URLHelper.parseError(slash, "Forward slash not allowed in URL", fullURL); - } - } - - } - } - - private void parseUserInfo(String userinfo) throws URLSyntaxException - { - // user info = user:pass - - int colonIndex = userinfo.indexOf(':'); - - if (colonIndex == -1) - { - throw URLHelper.parseError(AMQConnectionURL.AMQ_PROTOCOL.length() + 3, userinfo.length(), - "Null password in user information not allowed.", _url.getURL()); - } - else - { - _url.setUsername(userinfo.substring(0, colonIndex)); - _url.setPassword(userinfo.substring(colonIndex + 1)); - } - - } - - private void processOptions() throws URLSyntaxException - { - if (_url.getOptions().containsKey(AMQConnectionURL.OPTIONS_BROKERLIST)) - { - String brokerlist = _url.getOptions().get(AMQConnectionURL.OPTIONS_BROKERLIST); - - // brokerlist tcp://host:port?option='value',option='value';tcp://host:port/virtualpath?option='value' - StringTokenizer st = new StringTokenizer(brokerlist, "" + URLHelper.BROKER_SEPARATOR); - - while (st.hasMoreTokens()) - { - String broker = st.nextToken(); - - _url.addBrokerDetails(new AMQBrokerDetails(broker)); - } - - _url.getOptions().remove(AMQConnectionURL.OPTIONS_BROKERLIST); - } - - if (_url.getOptions().containsKey(AMQConnectionURL.OPTIONS_FAILOVER)) - { - String failover = _url.getOptions().get(AMQConnectionURL.OPTIONS_FAILOVER); - - // failover='method?option='value',option='value'' - - int methodIndex = failover.indexOf('?'); - - if (methodIndex > -1) - { - _url.setFailoverMethod(failover.substring(0, methodIndex)); - URLHelper.parseOptions(_url.getFailoverOptions(), failover.substring(methodIndex + 1)); - } - else - { - _url.setFailoverMethod(failover); - } - - _url.getOptions().remove(AMQConnectionURL.OPTIONS_FAILOVER); - } - - if (_url.getOptions().containsKey(AMQConnectionURL.OPTIONS_DEFAULT_TOPIC_EXCHANGE)) - { - _url.setDefaultTopicExchangeName(new AMQShortString(_url.getOptions().get(AMQConnectionURL.OPTIONS_DEFAULT_TOPIC_EXCHANGE))); - } - - if (_url.getOptions().containsKey(AMQConnectionURL.OPTIONS_DEFAULT_QUEUE_EXCHANGE)) - { - _url.setDefaultQueueExchangeName(new AMQShortString(_url.getOptions().get(AMQConnectionURL.OPTIONS_DEFAULT_QUEUE_EXCHANGE))); - } - - if (_url.getOptions().containsKey(AMQConnectionURL.OPTIONS_TEMPORARY_QUEUE_EXCHANGE)) - { - _url.setTemporaryQueueExchangeName(new AMQShortString(_url.getOptions().get(AMQConnectionURL.OPTIONS_TEMPORARY_QUEUE_EXCHANGE))); - } - - if (_url.getOptions().containsKey(AMQConnectionURL.OPTIONS_TEMPORARY_TOPIC_EXCHANGE)) - { - _url.setTemporaryTopicExchangeName(new AMQShortString(_url.getOptions().get(AMQConnectionURL.OPTIONS_TEMPORARY_TOPIC_EXCHANGE))); - } - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/url/URLParser_0_10.java b/qpid/java/client/src/main/java/org/apache/qpid/client/url/URLParser_0_10.java deleted file mode 100644 index af5dbebb01..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/url/URLParser_0_10.java +++ /dev/null @@ -1,424 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.url; - -import org.apache.qpid.client.AMQBrokerDetails; -import org.apache.qpid.jms.BrokerDetails; - -import java.net.MalformedURLException; -import java.util.ArrayList; -import java.util.List; - -/** - * The format Qpid URL is based on the AMQP one. The grammar is as follows: - * <p> - * <p>{@literal qpid_url = "qpid:" [client_props "@"] port_addr_list ["/" future-parameters] } - * <p>{@literal port_addr_list = [port_addr ","]* port_addr } - * <p>{@literal port_addr = tcp_port_addr | tls_prot_addr | future_prot_addr } - * <p>{@literal tcp_port_addr = tcp_id tcp_addr } - * <p>{@literal tcp_id = "tcp:" | "" } - * <p>{@literal tcp_addr = host [":" port] } - * <p>{@literal host = <as per http://www.apps.ietf.org/> } - * <p>{@literal port = number } - * <p>{@literal tls_prot_addr = tls_id tls_addr } - * <p>{@literal tls_id = "tls:" | "" } - * <p>{@literal tls_addr = host [":" port] } - * <p>{@literal future_prot_addr = future_prot_id future_prot_addr } - * <p>{@literal future_prot_id = <placeholder, must end in ":". Example "sctp:"> } - * <p>{@literal future_prot_addr = <placeholder, protocl-specific address> } - * <p>{@literal future_parameters = <placeholder, not used in failover addresses> } - * <p>{@literal client_props = [client_prop ";"]* client_prop } - * <p>{@literal client_prop = prop "=" val } - * <p>{@literal prop = chars as per <as per http://www.apps.ietf.org/> } - * <p>{@literal val = valid as per <as per http://www.apps.ietf.org/> } - * <p> - * Ex: - * <p> - * {@literal qpid:virtualhost=tcp:host-foo,test,client_id=foo@tcp:myhost.com:5672,virtualhost=prod; - * keystore=/opt/keystore@client_id2@tls:mysecurehost.com:5672 } - */ -public class URLParser_0_10 -{ - private static final char[] URL_START_SEQ = new char[]{'q', 'p', 'i', 'd', ':'}; - private static final char PROPERTY_EQUALS_CHAR = '='; - private static final char PROPERTY_SEPARATOR_CHAR = ';'; - private static final char ADDRESS_SEPERATOR_CHAR = ','; - - private static final char TRANSPORT_HOST_SEPARATOR_CHAR = ':'; - private static final char HOST_PORT_SEPARATOR_CHAR = ':'; - private static final char AT_CHAR = '@'; - private static final char END_OF_URL_MARKER = '^'; - - enum URLParserState - { - QPID_URL_START, - ADDRESS_START, - PROPERTY_NAME, - PROPERTY_EQUALS, - PROPERTY_VALUE, - PROPERTY_SEPARATOR, - AT_CHAR, - TRANSPORT, - TRANSPORT_HOST_SEPARATOR, - HOST, - HOST_PORT_SEPARATOR, - PORT, - ADDRESS_END, - ADDRESS_SEPERATOR, - QPID_URL_END, - ERROR - } - - //-- Constructors - - private char[] _url; - private List<BrokerDetails> _brokerDetailList = new ArrayList<BrokerDetails>(); - private String _error; - private int _index = 0; - private BrokerDetails _currentBroker; - private String _currentPropName; - private boolean _endOfURL = false; - private URLParserState _currentParserState; - - public URLParser_0_10(String url) throws MalformedURLException - { - _url = (url + END_OF_URL_MARKER).toCharArray(); - _endOfURL = false; - _currentParserState = URLParserState.QPID_URL_START; - URLParserState prevState = _currentParserState; // for error handling - try - { - while (_currentParserState != URLParserState.ERROR && _currentParserState != URLParserState.QPID_URL_END) - { - prevState = _currentParserState; - _currentParserState = next(); - } - - if (_currentParserState == URLParserState.ERROR) - { - _error = - "Invalid URL format [current_state = " + prevState + ", broker details parsed so far " + _currentBroker + " ] error at (" + _index + ") due to " + _error; - MalformedURLException ex; - ex = new MalformedURLException(_error); - throw ex; - } - } - catch (ArrayIndexOutOfBoundsException e) - { - _error = "Invalid URL format [current_state = " + prevState + ", broker details parsed so far " + _currentBroker + " ] error at (" + _index + ")"; - MalformedURLException ex = new MalformedURLException(_error); - throw ex; - } - } - - //-- interface QpidURL - public List<BrokerDetails> getAllBrokerDetails() - { - return _brokerDetailList; - } - - public String getURL() - { - return new String(_url); - } - - private URLParserState next() - { - switch (_currentParserState) - { - case QPID_URL_START: - return checkSequence(URL_START_SEQ, URLParserState.ADDRESS_START); - case ADDRESS_START: - return startAddress(); - case PROPERTY_NAME: - return extractPropertyName(); - case PROPERTY_EQUALS: - _index++; // skip the equal sign - return URLParserState.PROPERTY_VALUE; - case PROPERTY_VALUE: - return extractPropertyValue(); - case PROPERTY_SEPARATOR: - _index++; // skip "," - return URLParserState.PROPERTY_NAME; - case AT_CHAR: - _index++; // skip the @ sign - return URLParserState.TRANSPORT; - case TRANSPORT: - return extractTransport(); - case TRANSPORT_HOST_SEPARATOR: - _index++; // skip ":" - return URLParserState.HOST; - case HOST: - return extractHost(); - case HOST_PORT_SEPARATOR: - _index++; // skip ":" - return URLParserState.PORT; - case PORT: - return extractPort(); - case ADDRESS_END: - return endAddress(); - case ADDRESS_SEPERATOR: - _index++; // skip "," - return URLParserState.ADDRESS_START; - default: - return URLParserState.ERROR; - } - } - - private URLParserState checkSequence(char[] expected, URLParserState nextPart) - { - for (char expectedChar : expected) - { - if (expectedChar != _url[_index]) - { - _error = "Excepted (" + expectedChar + ") at position " + _index + ", got (" + _url[_index] + ")"; - return URLParserState.ERROR; - } - _index++; - } - return nextPart; - } - - private URLParserState startAddress() - { - _currentBroker = new AMQBrokerDetails(); - - for (int j = _index; j < _url.length; j++) - { - if (_url[j] == PROPERTY_EQUALS_CHAR) - { - return URLParserState.PROPERTY_NAME; - } - else if (_url[j] == ADDRESS_SEPERATOR_CHAR) - { - return URLParserState.TRANSPORT; - } - } - return URLParserState.TRANSPORT; - } - - private URLParserState endAddress() - { - _brokerDetailList.add(_currentBroker); - if (_endOfURL) - { - return URLParserState.QPID_URL_END; - } - else - { - return URLParserState.ADDRESS_SEPERATOR; - } - } - - private URLParserState extractPropertyName() - { - StringBuilder b = new StringBuilder(); - char next = _url[_index]; - while (next != PROPERTY_EQUALS_CHAR && next != AT_CHAR) - { - b.append(next); - next = _url[++_index]; - } - _currentPropName = b.toString(); - if (_currentPropName.trim().equals("")) - { - _error = "Property name cannot be empty"; - return URLParserState.ERROR; - } - else if (next == PROPERTY_EQUALS_CHAR) - { - return URLParserState.PROPERTY_EQUALS; - } - else - { - return URLParserState.AT_CHAR; - } - } - - private URLParserState extractPropertyValue() - { - StringBuilder b = new StringBuilder(); - char next = _url[_index]; - while (next != PROPERTY_SEPARATOR_CHAR && next != AT_CHAR) - { - b.append(next); - next = _url[++_index]; - } - String propValue = b.toString(); - if (propValue.trim().equals("")) - { - _error = "Property values cannot be empty"; - return URLParserState.ERROR; - } - else - { - _currentBroker.setProperty(_currentPropName, propValue); - if (next == PROPERTY_SEPARATOR_CHAR) - { - return URLParserState.PROPERTY_SEPARATOR; - } - else - { - return URLParserState.AT_CHAR; - } - } - } - - private URLParserState extractTransport() - { - String transport = buildUntil(TRANSPORT_HOST_SEPARATOR_CHAR); - if (transport.trim().equals("")) - { - _error = "Transport cannot be empty"; - return URLParserState.ERROR; - } - else if (!(transport.trim().equals(BrokerDetails.PROTOCOL_TCP) || transport.trim() - .equals(BrokerDetails.PROTOCOL_TLS))) - { - _error = "Transport cannot be " + transport + " value must be tcp or tls"; - return URLParserState.ERROR; - } - else - { - _currentBroker.setTransport(transport); - return URLParserState.TRANSPORT_HOST_SEPARATOR; - } - } - - private URLParserState extractHost() - { - char nextSep = 'c'; - String host; - URLParserState nextState; - - for (int i = _index; i < _url.length; i++) - { - if (_url[i] == HOST_PORT_SEPARATOR_CHAR) - { - nextSep = HOST_PORT_SEPARATOR_CHAR; - break; - } - else if (_url[i] == ADDRESS_SEPERATOR_CHAR) - { - nextSep = ADDRESS_SEPERATOR_CHAR; - break; - } - } - - if (nextSep == HOST_PORT_SEPARATOR_CHAR) - { - host = buildUntil(HOST_PORT_SEPARATOR_CHAR); - nextState = URLParserState.HOST_PORT_SEPARATOR; - } - else if (nextSep == ADDRESS_SEPERATOR_CHAR) - { - host = buildUntil(ADDRESS_SEPERATOR_CHAR); - nextState = URLParserState.ADDRESS_END; - } - else - { - host = buildUntil(END_OF_URL_MARKER); - nextState = URLParserState.ADDRESS_END; - _endOfURL = true; - } - - if (host.trim().equals("")) - { - _error = "Host cannot be empty"; - return URLParserState.ERROR; - } - else - { - _currentBroker.setHost(host); - return nextState; - } - } - - - private URLParserState extractPort() - { - - StringBuilder b = new StringBuilder(); - try - { - char next = _url[_index]; - while (next != ADDRESS_SEPERATOR_CHAR && next != END_OF_URL_MARKER ) - { - b.append(next); - next = _url[++_index]; - } - } - catch (ArrayIndexOutOfBoundsException e) - { - _endOfURL = true; - } - String portStr = b.toString(); - if (portStr.trim().equals("")) - { - _error = "Host cannot be empty"; - return URLParserState.ERROR; - } - else - { - try - { - int port = Integer.parseInt(portStr); - _currentBroker.setPort(port); - if( _url[_index] == END_OF_URL_MARKER ) - { - _endOfURL = true; - } - return URLParserState.ADDRESS_END; - } - catch (NumberFormatException e) - { - _error = "Illegal number for port"; - return URLParserState.ERROR; - } - } - } - - private String buildUntil(char c) - { - StringBuilder b = new StringBuilder(); - char next = _url[_index]; - while (next != c) - { - b.append(next); - next = _url[++_index]; - } - return b.toString(); - } - - public static void main(String[] args) - { - String testurl = "qpid:password=pass;username=name@tcp:test1"; - try - { - URLParser_0_10 impl = new URLParser_0_10(testurl); - for (BrokerDetails d : impl.getAllBrokerDetails()) - { - System.out.println(d); - } - } - catch (Exception e) - { - e.printStackTrace(); - } - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/util/BlockingWaiter.java b/qpid/java/client/src/main/java/org/apache/qpid/client/util/BlockingWaiter.java deleted file mode 100644 index 747668ff9c..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/util/BlockingWaiter.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.client.util; - -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.ReentrantLock; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.AMQTimeoutException; -import org.apache.qpid.client.failover.FailoverException; - -/** - * BlockingWaiter is a 'rendezvous' which delegates handling of - * incoming Objects to a listener implemented as a sub-class of this and hands off the process or - * error to a consumer. The producer of the event does not have to wait for the consumer to take the event, so this - * differs from a 'rendezvous' in that sense. - * <p> - * BlockingWaiters are used to coordinate when waiting for an an event that expect a response. - * They are always used in a 'one-shot' manner, that is, to receive just one response. Usually the caller has to register - * them as method listeners with an event dispatcher and remember to de-register them (in a finally block) once they - * have been completed. - * <p> - * The {@link #process} must return <tt>true</tt> on any incoming method that it handles. This indicates to - * this listeners that the object just processed ends the waiting process. - * <p> - * Errors from the producer are rethrown to the consumer. - * <p> - * TODO Interruption is caught but not handled. This could be allowed to fall through. This might actually be useful - * for fail-over where a thread is blocking when failure happens, it could be interrupted to abandon or retry - * when this happens. At the very least, restore the interrupted status flag. - * <p> - * TODO If the retrotranslator can handle it, could use a SynchronousQueue to implement this rendezvous. Need to - * check that SynchronousQueue has a non-blocking put method available. - */ -public abstract class BlockingWaiter<T> -{ - private static final Logger _logger = LoggerFactory.getLogger(BlockingWaiter.class); - - /** This flag is used to indicate that the blocked for method has been received. */ - private volatile boolean _ready = false; - - /** This flag is used to indicate that the received error has been processed. */ - private volatile boolean _errorAck = false; - - /** Used to protect the shared event and ready flag between the producer and consumer. */ - private final ReentrantLock _lock = new ReentrantLock(); - - /** Used to signal that a method has been received */ - private final Condition _receivedCondition = _lock.newCondition(); - - /** Used to signal that a error has been processed */ - private final Condition _errorConditionAck = _lock.newCondition(); - - /** Used to hold the most recent exception that is passed to the {@link #error(Exception)} method. */ - private volatile Exception _error; - - /** Holds the incoming Object. */ - private Object _doneObject = null; - private AtomicBoolean _waiting = new AtomicBoolean(false); - private boolean _closed = false; - - /** - * Delegates processing of the incoming object to the handler. - * - * @param object The object to process. - * - * @return <tt>true</tt> if the waiting is complete, <tt>false</tt> if waiting should continue. - */ - public abstract boolean process(T object); - - /** - * An Object has been received and should be processed to see if our wait condition has been reached. - * - * @param object The object received. - * - * @return <tt>true</tt> if the waiting is complete, <tt>false</tt> if waiting should continue. - */ - public boolean received(T object) - { - - boolean ready = process(object); - - if (ready) - { - // we only update the flag from inside the synchronized block - // so that the blockForFrame method cannot "miss" an update - it - // will only ever read the flag from within the synchronized block - _lock.lock(); - try - { - _doneObject = object; - _ready = ready; - _receivedCondition.signal(); - } - finally - { - _lock.unlock(); - } - } - - return ready; - } - - /** - * Blocks until an object is received that is handled by process, or the specified timeout - * has passed. - * - * Once closed any attempt to wait will throw an exception. - * - * @param timeout The timeout in milliseconds. - * - * @return The object that resolved the blocking. - * - * @throws AMQException - * @throws FailoverException - */ - public Object block(long timeout) throws AMQException, FailoverException - { - if (timeout < 0) - { - throw new IllegalArgumentException("timeout must be zero or greater"); - } - - long nanoTimeout = TimeUnit.MILLISECONDS.toNanos(timeout); - - _lock.lock(); - - try - { - if (_closed) - { - throw throwClosedException(); - } - - if (_error == null) - { - _waiting.set(true); - - while (!_ready && _error == null) - { - try - { - nanoTimeout = _receivedCondition.awaitNanos(nanoTimeout); - - if (nanoTimeout <= 0 && !_ready && _error == null) - { - _error = new AMQTimeoutException("Server did not respond in a timely fashion", null); - _ready = true; - } - } - catch (InterruptedException e) - { - _logger.error(e.getMessage(), e); - // IGNORE -- //fixme this isn't ideal as being interrupted isn't equivalent to success - } - } - } - - if (_error != null) - { - if (_error instanceof AMQException) - { - throw (AMQException) _error; - } - else if (_error instanceof FailoverException) - { - // This should ensure that FailoverException is not wrapped and can be caught. - throw (FailoverException) _error; // needed to expose FailoverException. - } - else - { - throw new AMQException("Woken up due to " + _error.getClass(), _error); - } - } - - } - finally - { - _waiting.set(false); - - //Release Error handling thread - if (_error != null) - { - _errorAck = true; - _errorConditionAck.signal(); - - _error = null; - } - _lock.unlock(); - } - - return _doneObject; - } - - /** - * This is a callback, called when an error has occurred that should interrupt any waiter. - * It is also called from within this class to avoid code repetition but it should only be called by the MINA threads. - * - * Once closed any notification of an exception will be ignored. - * - * @param e The exception being propagated. - */ - public void error(Exception e) - { - // set the error so that the thread that is blocking (against blockForFrame()) - // can pick up the exception and rethrow to the caller - - _lock.lock(); - - try - { - if (_closed) - { - return; - } - - if (_error == null) - { - _error = e; - } - else - { - _logger.error("WARNING: new error '" + (e == null ? "null" : e.getMessage()) + "' arrived while old one not yet processed:" + _error.getMessage()); - } - - if (_waiting.get()) - { - - _ready = true; - _receivedCondition.signal(); - - while (!_errorAck) - { - try - { - _errorConditionAck.await(); - } - catch (InterruptedException e1) - { - _logger.error(e1.getMessage(), e1); - } - } - _errorAck = false; - } - } - finally - { - _lock.unlock(); - } - } - - /** - * Close this Waiter so that no more errors are processed. - * This is a preventative method to ensure that a second error thread does not get stuck in the error method after - * the await has returned. This has not happened but in practise but if two errors occur on the Connection at - * the same time then it is conceivably possible for the second to get stuck if the first one is processed by a - * waiter. - * - * Once closed any attempt to wait will throw an exception. - * Any notification of an exception will be ignored. - */ - public void close() - { - _lock.lock(); - try - { - //if we have already closed then our job is done. - if (_closed) - { - return; - } - - //Close Waiter so no more exceptions are processed - _closed = true; - - //Wake up any await() threads - - //If we are waiting then use the error() to wake them up. - if (_waiting.get()) - { - error(throwClosedException()); - } - //If they are not waiting then there is nothing to do. - - // Wake up any error handling threads - - if (!_errorAck) - { - _errorAck = true; - _errorConditionAck.signal(); - - _error = null; - } - } - finally - { - _lock.unlock(); - } - } - - /** - * Helper method to generate the a closed Exception. - * - * todo: This should be converted to something more friendly. - * - * @return AMQException to throw to waiters when the Waiter is closed. - */ - private AMQException throwClosedException() - { - return new AMQException(null, "Waiter was closed.", null); - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/util/ClassLoadingAwareObjectInputStream.java b/qpid/java/client/src/main/java/org/apache/qpid/client/util/ClassLoadingAwareObjectInputStream.java deleted file mode 100644 index 669a0f1abf..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/util/ClassLoadingAwareObjectInputStream.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.util; - -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectInputStream; -import java.io.ObjectStreamClass; -import java.lang.reflect.Proxy; -import java.util.HashMap; - - -/** - * <code>ClassLoadingAwareObjectInputStream</code> is an Extention of Object input stream to be used - * to de-serialize JMS Object Messages. - * - * <p>This was introduced to resolve the class loading issues which can happen when we use the client - * libraries in a complex class loading Environment.</p> - */ -public class ClassLoadingAwareObjectInputStream extends ObjectInputStream -{ - /** <p>Class loader instance which loaded this class. - * It will be used to load classes when we failed to load classes from dynamic class loading</p> */ - private static final ClassLoader _ON_FAULT_CLASS_LOADER = - ClassLoadingAwareObjectInputStream.class.getClassLoader(); - - /** <p>Maps primitive type names to corresponding class objects.</p> */ - private static final HashMap<String, Class> _primitives = new HashMap<String, Class>(8, 1.0F); - - - public ClassLoadingAwareObjectInputStream(InputStream in) throws IOException - { - super(in); - } - - @Override - protected Class resolveClass(ObjectStreamClass classDesc) - throws IOException, ClassNotFoundException - { - - // Here we use TTCL as our primary class loader to load the classes - ClassLoader cl = Thread.currentThread().getContextClassLoader(); - - return load(classDesc.getName(), cl); - } - - @Override - protected Class resolveProxyClass(String[] interfaces) - throws IOException, ClassNotFoundException - { - // Here we use TTCL as our primary class loader to load the classes - ClassLoader cl = Thread.currentThread().getContextClassLoader(); - - Class[] cinterfaces = new Class[interfaces.length]; - for (int i = 0; i < interfaces.length; i++) - { - cinterfaces[i] = load(interfaces[i], cl); - } - - try - { - return Proxy.getProxyClass(cinterfaces[0].getClassLoader(), cinterfaces); - } - catch (IllegalArgumentException e) - { - throw new ClassNotFoundException(null, e); - } - } - - /** - * <p> - * Method we used to load class that are needed to de-serialize the objects. </p> - * <p> - * Here we first look up for the objects from the given class loader and if its not there - * we will be using the class loader of this class. - * </p> - * @param className Class name to lookup - * @param cl primary class loader which we 1st use to lookup - * @return Class instance we are looking for - * @throws ClassNotFoundException if both primary and secondary lockup's failed. - */ - private Class load(String className, ClassLoader cl) - throws ClassNotFoundException - { - try - { - return Class.forName(className, false, cl); - } - catch (ClassNotFoundException e) - { - final Class clazz = _primitives.get(className); - - if (clazz != null) - { - return clazz; - } - else - { - return Class.forName(className, false, _ON_FAULT_CLASS_LOADER); - } - } - } - - static - { - _primitives.put("boolean", boolean.class); - _primitives.put("byte", byte.class); - _primitives.put("char", char.class); - _primitives.put("short", short.class); - _primitives.put("int", int.class); - _primitives.put("long", long.class); - _primitives.put("float", float.class); - _primitives.put("double", double.class); - _primitives.put("void", void.class); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/util/FlowControllingBlockingQueue.java b/qpid/java/client/src/main/java/org/apache/qpid/client/util/FlowControllingBlockingQueue.java deleted file mode 100644 index 512f6a3b4a..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/util/FlowControllingBlockingQueue.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.util; - -import java.util.Iterator; -import java.util.Queue; -import java.util.concurrent.ConcurrentLinkedQueue; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * A blocking queue that emits events above a user specified threshold allowing the caller to take action (e.g. flow - * control) to try to prevent the queue growing (much) further. The underlying queue itself is not bounded therefore the - * caller is not obliged to react to the events. - * <p> - * This implementation is <b>only</b> safe where we have a single - * thread adding items and a single (different) thread removing items. - * <p> - * TODO Make this implement java.util.Queue and hide the implementation. Then different queue types can be substituted. - */ -public class FlowControllingBlockingQueue<T> -{ - private static final Logger _logger = LoggerFactory.getLogger(FlowControllingBlockingQueue.class); - - /** This queue is bounded and is used to store messages before being dispatched to the consumer */ - private final Queue<T> _queue = new ConcurrentLinkedQueue<T>(); - - private final int _flowControlHighThreshold; - private final int _flowControlLowThreshold; - - private final ThresholdListener _listener; - - /** We require a separate count so we can track whether we have reached the threshold */ - private int _count; - - private boolean disableFlowControl; - - public boolean isEmpty() - { - return _queue.isEmpty(); - } - - - public interface ThresholdListener - { - void aboveThreshold(int currentValue); - - void underThreshold(int currentValue); - } - - public FlowControllingBlockingQueue(int threshold, ThresholdListener listener) - { - this(threshold, threshold, listener); - } - - public FlowControllingBlockingQueue(int highThreshold, int lowThreshold, ThresholdListener listener) - { - _flowControlHighThreshold = highThreshold; - _flowControlLowThreshold = lowThreshold; - _listener = listener; - if (highThreshold == 0) - { - disableFlowControl = true; - } - } - - public T blockingPeek() throws InterruptedException - { - T o = _queue.peek(); - if (o == null) - { - synchronized (this) - { - while ((o = _queue.peek()) == null) - { - wait(); - } - } - } - return o; - } - - public T nonBlockingTake() throws InterruptedException - { - T o = _queue.poll(); - - if (o != null && !disableFlowControl && _listener != null) - { - reportBelowIfNecessary(); - } - - return o; - } - - public T take() throws InterruptedException - { - T o = _queue.poll(); - if(o == null) - { - synchronized(this) - { - while((o = _queue.poll())==null) - { - wait(); - } - } - } - if (!disableFlowControl && _listener != null) - { - reportBelowIfNecessary(); - } - - return o; - } - - public void add(T o) - { - synchronized(this) - { - _queue.add(o); - - notifyAll(); - } - if (!disableFlowControl && _listener != null) - { - reportAboveIfNecessary(); - } - } - - public boolean remove(final T o) - { - final boolean removed = _queue.remove(o); - if (removed && !disableFlowControl && _listener != null) - { - reportBelowIfNecessary(); - } - return removed; - } - - public Iterator<T> iterator() - { - return _queue.iterator(); - } - - private void reportAboveIfNecessary() - { - synchronized (_listener) - { - if (++_count == _flowControlHighThreshold) - { - _listener.aboveThreshold(_count); - } - } - } - - private void reportBelowIfNecessary() - { - synchronized (_listener) - { - if (_count-- == _flowControlLowThreshold) - { - _listener.underThreshold(_count); - } - } - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/jms/BrokerDetails.java b/qpid/java/client/src/main/java/org/apache/qpid/jms/BrokerDetails.java deleted file mode 100644 index 9faa58f11d..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/jms/BrokerDetails.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.jms; - -import java.util.Map; - -import org.apache.qpid.transport.ConnectionSettings; - -public interface BrokerDetails -{ - - /* - * Known URL Options - * @see ConnectionURL - */ - public static final String OPTIONS_RETRY = "retries"; - public static final String OPTIONS_CONNECT_TIMEOUT = "connecttimeout"; - public static final String OPTIONS_CONNECT_DELAY = "connectdelay"; - public static final String OPTIONS_HEARTBEAT = "heartbeat"; - @Deprecated - public static final String OPTIONS_IDLE_TIMEOUT = "idle_timeout"; - public static final String OPTIONS_SASL_MECHS = "sasl_mechs"; - public static final String OPTIONS_SASL_ENCRYPTION = "sasl_encryption"; - public static final String OPTIONS_SSL = "ssl"; - public static final String OPTIONS_TCP_NO_DELAY = "tcp_nodelay"; - public static final String OPTIONS_SASL_PROTOCOL_NAME = "sasl_protocol"; - public static final String OPTIONS_SASL_SERVER_NAME = "sasl_server"; - - public static final String OPTIONS_TRUST_STORE = "trust_store"; - public static final String OPTIONS_TRUST_STORE_PASSWORD = "trust_store_password"; - public static final String OPTIONS_KEY_STORE = "key_store"; - public static final String OPTIONS_KEY_STORE_PASSWORD = "key_store_password"; - public static final String OPTIONS_SSL_VERIFY_HOSTNAME = "ssl_verify_hostname"; - public static final String OPTIONS_SSL_CERT_ALIAS = "ssl_cert_alias"; - - public static final int DEFAULT_PORT = 5672; - - public static final String TCP = "tcp"; - - public static final String DEFAULT_TRANSPORT = TCP; - - public static final String URL_FORMAT_EXAMPLE = - "<transport>://<hostname>[:<port Default=\"" + DEFAULT_PORT + "\">][?<option>='<value>'[,<option>='<value>']]"; - - public static final int DEFAULT_CONNECT_TIMEOUT = 30000; - public static final boolean USE_SSL_DEFAULT = false; - - // pulled these properties from the new BrokerDetails class in the qpid package - public static final String PROTOCOL_TCP = "tcp"; - public static final String PROTOCOL_TLS = "tls"; - - public static final String VIRTUAL_HOST = "virtualhost"; - public static final String CLIENT_ID = "client_id"; - public static final String USERNAME = "username"; - public static final String PASSWORD = "password"; - - String getHost(); - - void setHost(String host); - - int getPort(); - - void setPort(int port); - - String getTransport(); - - void setTransport(String transport); - - String getProperty(String key); - - void setProperty(String key, String value); - - /** - * Ex: keystore path - * - * @return the Properties associated with this connection. - */ - public Map<String,String> getProperties(); - - /** - * Sets the properties associated with this connection - * - * @param props the new properties. - */ - public void setProperties(Map<String,String> props); - - boolean getBooleanProperty(String propName); - - ConnectionSettings buildConnectionSettings(); -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/jms/ChannelLimitReachedException.java b/qpid/java/client/src/main/java/org/apache/qpid/jms/ChannelLimitReachedException.java deleted file mode 100644 index e8c2b9d682..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/jms/ChannelLimitReachedException.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.jms; - -import javax.jms.ResourceAllocationException; - -/** - * Indicates that the maximum number of sessions per connection limit has been reached. - */ -public class ChannelLimitReachedException extends ResourceAllocationException -{ - private static final String ERROR_CODE = "1"; - - private long _limit; - - public ChannelLimitReachedException(long limit) - { - super("Unable to create session, the maximum number of sessions per connection is " + - limit + ". You must either close one or more sessions or increase the " + - "maximum number of sessions available per connection.", ERROR_CODE); - _limit = limit; - } - - public long getLimit() - { - return _limit; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/jms/Connection.java b/qpid/java/client/src/main/java/org/apache/qpid/jms/Connection.java deleted file mode 100644 index 616c6dbbec..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/jms/Connection.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.jms; - -import javax.jms.JMSException; - -public interface Connection extends javax.jms.Connection -{ - /** - * @return the maximum number of sessions supported by this Connection - */ - long getMaximumChannelCount() throws JMSException; - - void setConnectionListener(ConnectionListener listener); - - /** - * Get the connection listener that has been registered with this connection, if any - * - * @return the listener or null if none has been set - */ - ConnectionListener getConnectionListener(); - - /** - * Create a session specifying the prefetch limit of messages. - * - * @param transacted - * @param acknowledgeMode - * @param prefetch the maximum number of messages to buffer in the client. This - * applies as a total across all consumers - * @return - * @throws JMSException - */ - org.apache.qpid.jms.Session createSession(boolean transacted, int acknowledgeMode, - int prefetch) throws JMSException; - - - /** - * Create a session specifying the prefetch limit of messages. - * - * @param transacted - * @param acknowledgeMode - * @param prefetchHigh the maximum number of messages to buffer in the client. - * This applies as a total across all consumers - * @param prefetchLow the number of messages that must be in the buffer in the client to renable message flow. - * This applies as a total across all consumers - * @return - * @throws JMSException - */ - org.apache.qpid.jms.Session createSession(boolean transacted, int acknowledgeMode, - int prefetchHigh, int prefetchLow) throws JMSException; -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/jms/ConnectionListener.java b/qpid/java/client/src/main/java/org/apache/qpid/jms/ConnectionListener.java deleted file mode 100644 index 11c235901c..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/jms/ConnectionListener.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.jms; - -public interface ConnectionListener -{ - /** - * Called when bytes have been transmitted to the server - * @param count the number of bytes sent in total since the connection was opened - */ - void bytesSent(long count); - - /** - * Called when some bytes have been received on a connection - * @param count the number of bytes received in total since the connection was opened - */ - void bytesReceived(long count); - - /** - * Called after the infrastructure has detected that failover is required but before attempting failover. - * @param redirect true if the broker requested redirect. false if failover is occurring due to a connection error. - * @return true to continue failing over, false to veto failover and raise a connection exception - */ - boolean preFailover(boolean redirect); - - /** - * Called after connection has been made to another broker after failover has been started but before - * any resubscription has been done. - * @return true to continue with resubscription, false to prevent automatic resubscription. This is useful in - * cases where the application wants to handle resubscription. Note that in the latter case all sessions, producers - * and consumers are invalidated. - */ - boolean preResubscribe(); - - /** - * Called once failover has completed successfully. This is called irrespective of whether the client has - * vetoed automatic resubscription. - */ - void failoverComplete(); -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/jms/ConnectionURL.java b/qpid/java/client/src/main/java/org/apache/qpid/jms/ConnectionURL.java deleted file mode 100644 index 754b90c372..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/jms/ConnectionURL.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.jms; - -import java.util.List; -import org.apache.qpid.framing.AMQShortString; - -/** - Connection URL format - {@literal amqp://[user:pass@][clientid]/virtualhost?brokerlist='tcp://host:port?option=\'value\'&option=\'value\';tcp://host:port/virtualpath?option=\'value\''&failover='method?option=\'value\'&option='value''" } - Options are of course optional except for requiring a single broker in the broker list. - The option seperator is defined to be either {@literal '&' or ','} - */ -public interface ConnectionURL -{ - public static final String AMQ_PROTOCOL = "amqp"; - public static final String OPTIONS_SYNC_PERSISTENCE = "sync_persistence"; - public static final String OPTIONS_MAXPREFETCH = "maxprefetch"; - public static final String OPTIONS_SYNC_ACK = "sync_ack"; - public static final String OPTIONS_SYNC_PUBLISH = "sync_publish"; - public static final String OPTIONS_USE_LEGACY_MAP_MESSAGE_FORMAT = "use_legacy_map_msg_format"; - public static final String OPTIONS_USE_LEGACY_STREAM_MESSAGE_FORMAT = "use_legacy_stream_msg_format"; - public static final String OPTIONS_BROKERLIST = "brokerlist"; - public static final String OPTIONS_FAILOVER = "failover"; - public static final String OPTIONS_FAILOVER_CYCLE = "cyclecount"; - - /** - * This option is used to apply a connection level override of - * the {@value BrokerDetails#OPTIONS_SSL} option values in the - * {@value ConnectionURL#OPTIONS_BROKERLIST}; - */ - public static final String OPTIONS_SSL = "ssl"; - - /** - * This option is only applicable for 0-8/0-9/0-9-1 protocols connection - * <p> - * It tells the client to delegate the requeue/DLQ decision to the - * server .If this option is not specified, the messages won't be moved to - * the DLQ (or dropped) when delivery count exceeds the maximum. - */ - public static final String OPTIONS_REJECT_BEHAVIOUR = "rejectbehaviour"; - - /** - * <p> - * This option is only applicable for 0-8/0-9/0-9-1 protocol connections. - * </p> - * <p> - * It tells the client to request whether the broker should close the - * connection when a mandatory message isn't routable, rather than return - * the message to the client as it normally would. - * </p> - */ - public static final String OPTIONS_CLOSE_WHEN_NO_ROUTE = "closeWhenNoRoute"; - - - public static final String OPTIONS_COMPRESS_MESSAGES = "compressMessages"; - public static final String OPTIONS_MESSAGES_COMPRESSION_THRESHOLD_SIZE = "messageCompressionThresholdSize"; - - - public static final String OPTIONS_DEFAULT_TOPIC_EXCHANGE = "defaultTopicExchange"; - public static final String OPTIONS_DEFAULT_QUEUE_EXCHANGE = "defaultQueueExchange"; - public static final String OPTIONS_TEMPORARY_TOPIC_EXCHANGE = "temporaryTopicExchange"; - public static final String OPTIONS_TEMPORARY_QUEUE_EXCHANGE = "temporaryQueueExchange"; - public static final String OPTIONS_VERIFY_QUEUE_ON_SEND = "verifyQueueOnSend"; - - public static final byte URL_0_8 = 1; - public static final byte URL_0_10 = 2; - - String getURL(); - - String getFailoverMethod(); - - String getFailoverOption(String key); - - int getBrokerCount(); - - BrokerDetails getBrokerDetails(int index); - - void addBrokerDetails(BrokerDetails broker); - - void setBrokerDetails(List<BrokerDetails> brokers); - - List<BrokerDetails> getAllBrokerDetails(); - - String getClientName(); - - void setClientName(String clientName); - - String getUsername(); - - void setUsername(String username); - - String getPassword(); - - void setPassword(String password); - - String getVirtualHost(); - - void setVirtualHost(String virtualHost); - - String getOption(String key); - - void setOption(String key, String value); - - AMQShortString getDefaultQueueExchangeName(); - - AMQShortString getDefaultTopicExchangeName(); - - AMQShortString getTemporaryQueueExchangeName(); - - AMQShortString getTemporaryTopicExchangeName(); - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/jms/FailoverPolicy.java b/qpid/java/client/src/main/java/org/apache/qpid/jms/FailoverPolicy.java deleted file mode 100644 index 0b4f0800d2..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/jms/FailoverPolicy.java +++ /dev/null @@ -1,316 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.jms; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.jms.failover.FailoverExchangeMethod; -import org.apache.qpid.jms.failover.FailoverMethod; -import org.apache.qpid.jms.failover.FailoverRoundRobinServers; -import org.apache.qpid.jms.failover.FailoverSingleServer; -import org.apache.qpid.jms.failover.NoFailover; - -public class FailoverPolicy -{ - private static final Logger _logger = LoggerFactory.getLogger(FailoverPolicy.class); - - private final long DEFAULT_METHOD_TIMEOUT = Long.getLong("qpid.failover_method_timeout", 120000); - - private FailoverMethod[] _methods = new FailoverMethod[1]; - - private int _currentMethod; - - private int _methodsRetries; - - private int _currentRetry; - - private boolean _timing; - - private long _lastMethodTime; - private long _lastFailTime; - - public FailoverPolicy(ConnectionURL connectionDetails, Connection conn) - { - FailoverMethod method; - - // todo This should be integrated in to the connection url when it supports - // multiple strategies. - - _methodsRetries = 0; - - if (connectionDetails.getFailoverMethod() == null) - { - if (connectionDetails.getBrokerCount() > 1) - { - method = new FailoverRoundRobinServers(connectionDetails); - } - else - { - method = new FailoverSingleServer(connectionDetails); - } - } - else - { - String failoverMethod = connectionDetails.getFailoverMethod(); - - if (failoverMethod.equals(FailoverMethod.SINGLE_BROKER)) - { - method = new FailoverSingleServer(connectionDetails); - } - else - { - if (failoverMethod.equals(FailoverMethod.ROUND_ROBIN)) - { - method = new FailoverRoundRobinServers(connectionDetails); - } - else if (failoverMethod.equals(FailoverMethod.FAILOVER_EXCHANGE)) - { - method = new FailoverExchangeMethod(connectionDetails, conn); - } - else if (failoverMethod.equals(FailoverMethod.NO_FAILOVER)) - { - method = new NoFailover(connectionDetails); - } - else - { - try - { - Class[] constructorSpec = { ConnectionURL.class }; - Object[] params = { connectionDetails }; - - method = - (FailoverMethod) ClassLoader.getSystemClassLoader().loadClass(failoverMethod) - .getConstructor(constructorSpec).newInstance(params); - } - catch (Exception cnfe) - { - throw new IllegalArgumentException("Unknown failover method:" + failoverMethod, cnfe); - } - } - } - } - - if (method == null) - { - throw new IllegalArgumentException("Unknown failover method specified."); - } - - reset(); - - _methods[_currentMethod] = method; - } - - public FailoverPolicy(FailoverMethod method) - { - this(method, 0); - } - - public FailoverPolicy(FailoverMethod method, int retries) - { - _methodsRetries = retries; - - reset(); - - _methods[_currentMethod] = method; - } - - private void reset() - { - _currentMethod = 0; - _currentRetry = 0; - _timing = false; - - } - - public boolean failoverAllowed() - { - boolean failoverAllowed; - - if (_timing) - { - long now = System.currentTimeMillis(); - - if ((now - _lastMethodTime) >= DEFAULT_METHOD_TIMEOUT) - { - _logger.info("Failover method timeout"); - _lastMethodTime = now; - - if (!nextMethod()) - { - return false; - } - - } - else - { - _lastMethodTime = now; - } - } - else - { - _timing = true; - _lastMethodTime = System.currentTimeMillis(); - _lastFailTime = _lastMethodTime; - } - - if (_methods[_currentMethod].failoverAllowed()) - { - failoverAllowed = true; - } - else - { - if (_currentMethod < (_methods.length - 1)) - { - nextMethod(); - _logger.info("Changing method to " + _methods[_currentMethod].methodName()); - - return failoverAllowed(); - } - else - { - return cycleMethods(); - } - } - - return failoverAllowed; - } - - private boolean nextMethod() - { - if (_currentMethod < (_methods.length - 1)) - { - _currentMethod++; - _methods[_currentMethod].reset(); - - return true; - } - else - { - return cycleMethods(); - } - } - - private boolean cycleMethods() - { - if (_currentRetry < _methodsRetries) - { - _currentRetry++; - - _currentMethod = 0; - - _logger.info("Retrying methods starting with " + _methods[_currentMethod].methodName()); - _methods[_currentMethod].reset(); - - return failoverAllowed(); - } - else - { - _logger.debug("All failover methods exhausted"); - - return false; - } - } - - /** - * Notification that connection was successful. - */ - public void attainedConnection() - { - _currentRetry = 0; - - _methods[_currentMethod].attainedConnection(); - - _timing = false; - } - - public BrokerDetails getCurrentBrokerDetails() - { - return _methods[_currentMethod].getCurrentBrokerDetails(); - } - - public BrokerDetails getNextBrokerDetails() - { - return _methods[_currentMethod].getNextBrokerDetails(); - } - - public void setBroker(BrokerDetails broker) - { - _methods[_currentMethod].setBroker(broker); - } - - public void addMethod(FailoverMethod method) - { - int len = _methods.length + 1; - FailoverMethod[] newMethods = new FailoverMethod[len]; - System.arraycopy(_methods, 0, newMethods, 0, _methods.length); - int index = len - 1; - newMethods[index] = method; - _methods = newMethods; - } - - public void setMethodRetries(int retries) - { - _methodsRetries = retries; - } - - public FailoverMethod getCurrentMethod() - { - if ((_currentMethod >= 0) && (_currentMethod < (_methods.length))) - { - return _methods[_currentMethod]; - } - else - { - return null; - } - } - - public String toString() - { - StringBuffer sb = new StringBuffer(); - - sb.append("Failover Policy:\n"); - - if (failoverAllowed()) - { - sb.append("Failover allowed\n"); - } - else - { - sb.append("Failover not allowed\n"); - } - - sb.append("Failover policy methods\n"); - for (int i = 0; i < _methods.length; i++) - { - - if (i == _currentMethod) - { - sb.append(">"); - } - - sb.append(_methods[i].toString()); - } - - return sb.toString(); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/jms/ListMessage.java b/qpid/java/client/src/main/java/org/apache/qpid/jms/ListMessage.java deleted file mode 100644 index 21dd2a89ee..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/jms/ListMessage.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.jms; - -import javax.jms.JMSException; - -import java.util.Iterator; -import java.util.List; - -public interface ListMessage extends javax.jms.StreamMessage -{ - boolean add(Object e) throws JMSException; - - void add(int index, Object e) throws JMSException; - - boolean contains(Object e) throws JMSException; - - Object get(int index) throws JMSException; - - int indexOf(Object e) throws JMSException; - - Iterator<Object> iterator() throws JMSException; - - Object remove(int index) throws JMSException; - - boolean remove(Object e)throws JMSException; - - Object set(int index, Object e) throws JMSException; - - int size() throws JMSException; - - Object[] toArray() throws JMSException; - - List<Object> asList() throws JMSException; - - void setList(List<Object> l) throws JMSException; -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/jms/Message.java b/qpid/java/client/src/main/java/org/apache/qpid/jms/Message.java deleted file mode 100644 index 53c615a1fd..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/jms/Message.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.jms; - -import javax.jms.JMSException; - -public interface Message extends javax.jms.Message -{ - public static final String JMS_TYPE = "x-jms-type"; - - public void acknowledgeThis() throws JMSException; -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/jms/MessageConsumer.java b/qpid/java/client/src/main/java/org/apache/qpid/jms/MessageConsumer.java deleted file mode 100644 index caac2b5c1f..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/jms/MessageConsumer.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.jms; - -/** - */ -public interface MessageConsumer extends javax.jms.MessageConsumer -{ -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/jms/MessageProducer.java b/qpid/java/client/src/main/java/org/apache/qpid/jms/MessageProducer.java deleted file mode 100644 index 82c2b88c30..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/jms/MessageProducer.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.jms; - -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; - -/** - */ -public interface MessageProducer extends javax.jms.MessageProducer -{ - void send(Destination destination, Message message, int deliveryMode, - int priority, long timeToLive, boolean immediate) - throws JMSException; - - void send(Destination destination, Message message, int deliveryMode, - int priority, long timeToLive, boolean mandatory, boolean immediate) - throws JMSException; - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/jms/Session.java b/qpid/java/client/src/main/java/org/apache/qpid/jms/Session.java deleted file mode 100644 index 4801f87295..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/jms/Session.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.jms; - -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.jms.ListMessage; - -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.QueueSession; -import javax.jms.TopicSession; - - -public interface Session extends TopicSession, QueueSession -{ - /** - * Indicates that no client acknowledgements are required. Broker assumes that once it has delivered - * a message packet successfully it is acknowledged. - */ - static final int NO_ACKNOWLEDGE = 257; - - /** - * Pre acknowledge means that an ack is sent per message but sent before user code has processed - * the message (i.e. before the onMessage() call or the receive() method has returned). - */ - static final int PRE_ACKNOWLEDGE = 258; - - MessageConsumer createConsumer(Destination destination, - int prefetch, - boolean noLocal, - boolean exclusive, - String selector) throws JMSException; - - MessageConsumer createConsumer(Destination destination, - int prefetchHigh, - int prefetchLow, - boolean noLocal, - boolean exclusive, - String selector) throws JMSException; - - /** - * @return the prefetch value used by default for consumers created on this session. - */ - int getDefaultPrefetch(); - - /** - * @return the High water prefetch value used by default for consumers created on this session. - */ - int getDefaultPrefetchHigh(); - - /** - * @return the Low water prefetch value used by default for consumers created on this session. - */ - int getDefaultPrefetchLow(); - - /** - * Create a producer - * @param destination - * @param mandatory the value of the mandatory flag used by default on the producer - * @param immediate the value of the immediate flag used by default on the producer - * @return - * @throws JMSException - */ - MessageProducer createProducer(Destination destination, boolean mandatory, boolean immediate) - throws JMSException; - - /** - * Create a producer - * @param destination - * @param immediate the value of the immediate flag used by default on the producer - * @return - * @throws JMSException - */ - MessageProducer createProducer(Destination destination, boolean immediate) - throws JMSException; - - AMQShortString getTemporaryTopicExchangeName(); - - AMQShortString getDefaultQueueExchangeName(); - - AMQShortString getDefaultTopicExchangeName(); - - AMQShortString getTemporaryQueueExchangeName(); - - ListMessage createListMessage() throws JMSException; -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/jms/TopicSubscriber.java b/qpid/java/client/src/main/java/org/apache/qpid/jms/TopicSubscriber.java deleted file mode 100644 index fe43ae8cd0..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/jms/TopicSubscriber.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.jms; - - -import org.apache.qpid.AMQException; - -import javax.jms.Topic; - -public interface TopicSubscriber extends javax.jms.TopicSubscriber -{ - - void addBindingKey(Topic topic, String bindingKey) throws AMQException; -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverExchangeMethod.java b/qpid/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverExchangeMethod.java deleted file mode 100644 index a5eda29274..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverExchangeMethod.java +++ /dev/null @@ -1,317 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.jms.failover; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.client.AMQAnyDestination; -import org.apache.qpid.client.AMQBrokerDetails; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.jms.BrokerDetails; -import org.apache.qpid.jms.Connection; -import org.apache.qpid.jms.ConnectionURL; - -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.Session; -import java.net.InetAddress; -import java.util.ArrayList; -import java.util.List; - -/** - * When using the Failover exchange a single broker is supplied in the URL. - * The connection will then connect to the cluster using the above broker details. - * Once connected, the membership details of the cluster will be obtained via - * subscribing to a queue bound to the failover exchange. - * - * The failover exchange will provide a list of broker URLs in the format "transport:ip:port" - * Out of this list we only select brokers that match the transport of the original - * broker supplied in the connection URL. - * - * Also properties defined for the original broker will be applied to all the brokers selected - * from the list. - */ - -public class FailoverExchangeMethod implements FailoverMethod, MessageListener -{ - private static final Logger _logger = LoggerFactory.getLogger(FailoverExchangeMethod.class); - - /** This is not safe to use until attainConnection is called */ - private Connection _conn; - - /** Protects the broker list when modifications happens */ - private Object _brokerListLock = new Object(); - - /** The session used to subscribe to failover exchange */ - private Session _ssn; - - private BrokerDetails _originalBrokerDetail; - - /** The index into the hostDetails array of the broker to which we are connected */ - private int _currentBrokerIndex = 0; - - /** The broker currently selected **/ - private BrokerDetails _currentBrokerDetail; - - /** Array of BrokerDetail used to make connections. */ - private ConnectionURL _connectionDetails; - - /** Denotes the number of failed attempts **/ - private int _failedAttemps = 0; - - public FailoverExchangeMethod(ConnectionURL connectionDetails, Connection conn) - { - _connectionDetails = connectionDetails; - _originalBrokerDetail = _connectionDetails.getBrokerDetails(0); - - // This is not safe to use until attainConnection is called, as this ref will not initialized fully. - // The reason being this constructor is called inside the AMWConnection constructor. - // It would be best if we find a way to pass this ref after AMQConnection is fully initialized. - _conn = conn; - } - - private void subscribeForUpdates() throws JMSException - { - if (_ssn == null) - { - _ssn = _conn.createSession(false,Session.AUTO_ACKNOWLEDGE); - MessageConsumer cons = _ssn.createConsumer( - new AMQAnyDestination(new AMQShortString("amq.failover"), - new AMQShortString("amq.failover"), - new AMQShortString(""), - true,true,null,false, - new AMQShortString[0])); - cons.setMessageListener(this); - } - } - - public void onMessage(Message m) - { - _logger.info("Failover exchange notified cluster membership change"); - - String currentBrokerIP = ""; - try - { - currentBrokerIP = InetAddress.getByName(_currentBrokerDetail.getHost()).getHostAddress(); - } - catch(Exception e) - { - _logger.warn("Unable to resolve current broker host name",e); - } - - List<BrokerDetails> brokerList = new ArrayList<BrokerDetails>(); - try - { - List<String> list = (List<String>)m.getObjectProperty("amq.failover"); - for (String brokerEntry:list) - { - String[] urls = brokerEntry.substring(5) .split(","); - - for (String url:urls) - { - String[] tokens = url.split(":"); - if (tokens[0].equalsIgnoreCase(_originalBrokerDetail.getTransport())) - { - BrokerDetails broker = new AMQBrokerDetails(); - broker.setTransport(tokens[0]); - broker.setHost(tokens[1]); - broker.setPort(Integer.parseInt(tokens[2])); - broker.setProperties(_originalBrokerDetail.getProperties()); - brokerList.add(broker); - - if (currentBrokerIP.equals(broker.getHost()) && - _currentBrokerDetail.getPort() == broker.getPort()) - { - _currentBrokerIndex = brokerList.indexOf(broker); - } - - break; - } - } - } - } - catch(JMSException e) - { - _logger.error("Error parsing the message sent by failover exchange",e); - } - - synchronized (_brokerListLock) - { - _connectionDetails.setBrokerDetails(brokerList); - } - - _logger.info("============================================================"); - _logger.info("Updated cluster membership details " + _connectionDetails); - _logger.info("============================================================"); - } - - public void attainedConnection() - { - try - { - _failedAttemps = 0; - _logger.info("============================================================"); - _logger.info("Attained connection "); - _logger.info("============================================================"); - subscribeForUpdates(); - } - catch (JMSException e) - { - throw new RuntimeException("Unable to subscribe for cluster membership updates",e); - } - } - - public BrokerDetails getCurrentBrokerDetails() - { - synchronized (_brokerListLock) - { - _currentBrokerDetail = _connectionDetails.getBrokerDetails(_currentBrokerIndex); - return _currentBrokerDetail; - } - } - - public BrokerDetails getNextBrokerDetails() - { - BrokerDetails broker = null; - - synchronized(_brokerListLock) - { - if (_currentBrokerIndex == (_connectionDetails.getBrokerCount() - 1)) - { - _currentBrokerIndex = 0; - } - else - { - _currentBrokerIndex++; - } - - broker = _connectionDetails.getBrokerDetails(_currentBrokerIndex); - - // When the broker list is updated it will include the current broker as well - // There is no point trying it again, so trying the next one. - if (_currentBrokerDetail != null && - broker.getHost().equals(_currentBrokerDetail.getHost()) && - broker.getPort() == _currentBrokerDetail.getPort()) - { - if (_connectionDetails.getBrokerCount() > 1) - { - return getNextBrokerDetails(); - } - else - { - _failedAttemps ++; - return null; - } - } - } - - String delayStr = broker.getProperty(BrokerDetails.OPTIONS_CONNECT_DELAY); - if (delayStr != null) - { - Long delay = Long.parseLong(delayStr); - _logger.info("Delay between connect retries:" + delay); - try - { - Thread.sleep(delay); - } - catch (InterruptedException ie) - { - return null; - } - } - else - { - _logger.info("No delay between connect retries, use tcp://host:port?connectdelay='value' to enable."); - } - - _failedAttemps ++; - _currentBrokerDetail = broker; - - return broker; - } - - public boolean failoverAllowed() - { - // We allow to Failover provided - // our broker list is not empty and - // we haven't gone through all of them - - boolean b = _connectionDetails.getBrokerCount() > 0 && - _failedAttemps <= _connectionDetails.getBrokerCount(); - - - _logger.info("============================================================"); - _logger.info(toString()); - _logger.info("FailoverAllowed " + b); - _logger.info("============================================================"); - - return b; - } - - public void reset() - { - _failedAttemps = 0; - } - - public void setBroker(BrokerDetails broker) - { - // not sure if this method is needed - } - - public void setRetries(int maxRetries) - { - // no max retries we keep trying as long - // as we get updates - } - - public String methodName() - { - return "Failover Exchange"; - } - - public String toString() - { - StringBuffer sb = new StringBuffer(); - sb.append("FailoverExchange:\n"); - sb.append("\n Current Broker Index:"); - sb.append(_currentBrokerIndex); - sb.append("\n Failed Attempts:"); - sb.append(_failedAttemps); - sb.append("\n Orignal broker details:"); - sb.append(_originalBrokerDetail).append("\n"); - sb.append("\n -------- Broker List -----------\n"); - for (int i = 0; i < _connectionDetails.getBrokerCount(); i++) - { - if (i == _currentBrokerIndex) - { - sb.append(">"); - } - - sb.append(_connectionDetails.getBrokerDetails(i)); - sb.append("\n"); - } - sb.append("--------------------------------\n"); - return sb.toString(); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverMethod.java b/qpid/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverMethod.java deleted file mode 100644 index 1cef067e5f..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverMethod.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.jms.failover; - -import org.apache.qpid.jms.BrokerDetails; - -public interface FailoverMethod -{ - public static final String SINGLE_BROKER = "singlebroker"; - public static final String ROUND_ROBIN = "roundrobin"; - public static final String FAILOVER_EXCHANGE= "failover_exchange"; - public static final String RANDOM = "random"; - public static final String NO_FAILOVER = "nofailover"; - - /** - * Reset the Failover to initial conditions - */ - void reset(); - - /** - * Check if failover is possible for this method - * - * @return true if failover is allowed - */ - boolean failoverAllowed(); - - /** - * Notification to the Failover method that a connection has been attained. - */ - void attainedConnection(); - - /** - * If there is no current BrokerDetails the null will be returned. - * @return The current BrokerDetail value to use - */ - BrokerDetails getCurrentBrokerDetails(); - - /** - * Move to the next BrokerDetails if one is available. - * @return the next BrokerDetail or null if there is none. - */ - BrokerDetails getNextBrokerDetails(); - - /** - * Set the currently active broker to be the new value. - * @param broker The new BrokerDetail value - */ - void setBroker(BrokerDetails broker); - - /** - * Set the retries for this method - * @param maxRetries the maximum number of time to retry this Method - */ - void setRetries(int maxRetries); - - /** - * @return The name of this method for display purposes. - */ - String methodName(); -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverRoundRobinServers.java b/qpid/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverRoundRobinServers.java deleted file mode 100644 index 52c7d00000..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverRoundRobinServers.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.jms.failover; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.jms.BrokerDetails; -import org.apache.qpid.jms.ConnectionURL; - -public class FailoverRoundRobinServers implements FailoverMethod -{ - private static final Logger _logger = LoggerFactory.getLogger(FailoverRoundRobinServers.class); - - /** The default number of times to cycle through all servers */ - public static final int DEFAULT_CYCLE_RETRIES = 1; - /** The default number of times to retry each server */ - public static final int DEFAULT_SERVER_RETRIES = 0; - - /** The index into the hostDetails array of the broker to which we are connected */ - private int _currentBrokerIndex = 0; - - /** The number of times to retry connecting for each server */ - private int _serverRetries; - - /** The current number of retry attempts made */ - private int _currentServerRetry = 0; - - /** The number of times to cycle through the servers */ - private int _cycleRetries; - - /** The current number of cycles performed. */ - private int _currentCycleRetries = 0; - - private ConnectionURL _connectionDetails; - - public FailoverRoundRobinServers(ConnectionURL connectionDetails) - { - if (!(connectionDetails.getBrokerCount() > 0)) - { - throw new IllegalArgumentException("At least one broker details must be specified."); - } - - _connectionDetails = connectionDetails; - - // There is no current broker at startup so set it to -1. - _currentBrokerIndex = 0; - - String cycleRetries = _connectionDetails.getFailoverOption(ConnectionURL.OPTIONS_FAILOVER_CYCLE); - - _cycleRetries = DEFAULT_CYCLE_RETRIES; - - if (cycleRetries != null) - { - try - { - _cycleRetries = Integer.parseInt(cycleRetries); - } - catch (NumberFormatException nfe) - { - _logger.warn("Cannot set cycle Retries, " + cycleRetries + " is not a number. Using default: " + DEFAULT_CYCLE_RETRIES); - } - } - - _currentCycleRetries = 0; - - _serverRetries = 0; - _currentServerRetry = 0; - setBroker(getCurrentBrokerDetails()); - } - - public void reset() - { - _currentBrokerIndex = 0; - _currentCycleRetries = 0; - _currentServerRetry = 0; - } - - public boolean failoverAllowed() - { - _logger.info("==== Checking failoverAllowed() ===="); - _logger.info(toString()); - _logger.info("===================================="); - return ((_currentCycleRetries < _cycleRetries) || (_currentServerRetry < _serverRetries)); - } - - public void attainedConnection() - { - _currentCycleRetries = 0; - _currentServerRetry = 0; - } - - public BrokerDetails getCurrentBrokerDetails() - { - return _connectionDetails.getBrokerDetails(_currentBrokerIndex); - } - - public BrokerDetails getNextBrokerDetails() - { - if (_currentBrokerIndex == (_connectionDetails.getBrokerCount() - 1)) - { - if (_currentServerRetry < _serverRetries) - { - _logger.info("Trying " + _connectionDetails.getBrokerDetails(_currentBrokerIndex)); - _currentServerRetry++; - } - else - { - _currentCycleRetries++; - // failed to connect to first broker - _currentBrokerIndex = 0; - - setBroker(_connectionDetails.getBrokerDetails(_currentBrokerIndex)); - - // This is zero rather than -1 as we are already retrieving the details. - _currentServerRetry = 0; - } - // else - should force client to stop as max retries has been reached. - } - else - { - if (_currentServerRetry < _serverRetries) - { - _logger.info("Trying " + _connectionDetails.getBrokerDetails(_currentBrokerIndex)); - - _currentServerRetry++; - } - else - { - _currentBrokerIndex++; - - setBroker(_connectionDetails.getBrokerDetails(_currentBrokerIndex)); - // This is zero rather than -1 as we are already retrieving the details. - _currentServerRetry = 0; - } - } - - BrokerDetails broker = _connectionDetails.getBrokerDetails(_currentBrokerIndex); - - String delayStr = broker.getProperty(BrokerDetails.OPTIONS_CONNECT_DELAY); - if (delayStr != null) - { - Long delay = Long.parseLong(delayStr); - _logger.info("Delay between connect retries:" + delay); - try - { - Thread.sleep(delay); - } - catch (InterruptedException ie) - { - return null; - } - } - else - { - // Only display if option not set. Not if deDelay==false. - if (delayStr == null) - { - _logger.info("No delay between connect retries, use tcp://host:port?connectdelay='value' to enable."); - } - } - - return broker; - } - - public void setBroker(BrokerDetails broker) - { - - _connectionDetails.addBrokerDetails(broker); - - int index = _connectionDetails.getAllBrokerDetails().indexOf(broker); - - String serverRetries = broker.getProperty(BrokerDetails.OPTIONS_RETRY); - - if (serverRetries != null) - { - try - { - _serverRetries = Integer.parseInt(serverRetries); - } - catch (NumberFormatException nfe) - { - _serverRetries = DEFAULT_SERVER_RETRIES; - } - } - - _currentServerRetry = 0; - _currentBrokerIndex = index; - } - - public void setRetries(int maxRetries) - { - _cycleRetries = maxRetries; - } - - public String methodName() - { - return "Cycle Servers"; - } - - public String toString() - { - StringBuffer sb = new StringBuffer(); - - sb.append("Cycle Servers:\n"); - - sb.append("Cycle Retries:"); - sb.append(_cycleRetries); - sb.append("\nCurrent Cycle:"); - sb.append(_currentCycleRetries); - sb.append("\nServer Retries:"); - sb.append(_serverRetries); - sb.append("\nCurrent Retry:"); - sb.append(_currentServerRetry); - sb.append("\nCurrent Broker:"); - sb.append(_currentBrokerIndex); - sb.append("\n"); - - for (int i = 0; i < _connectionDetails.getBrokerCount(); i++) - { - if (i == _currentBrokerIndex) - { - sb.append(">"); - } - - sb.append(_connectionDetails.getBrokerDetails(i)); - sb.append("\n"); - } - - return sb.toString(); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverSingleServer.java b/qpid/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverSingleServer.java deleted file mode 100644 index 1ef71eccba..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverSingleServer.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.jms.failover; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.jms.BrokerDetails; -import org.apache.qpid.jms.ConnectionURL; - -public class FailoverSingleServer implements FailoverMethod -{ - private static final Logger _logger = LoggerFactory.getLogger(FailoverSingleServer.class); - - /** The default number of times to rety a conection to this server */ - public static final int DEFAULT_SERVER_RETRIES = 0; - - /** The details of the Single Server */ - private BrokerDetails _brokerDetail; - - /** The number of times to retry connecting to the sever */ - private int _retries; - - /** The current number of attempts made to the server */ - private int _currentRetries = 0; - - - public FailoverSingleServer(ConnectionURL connectionDetails) - { - if (connectionDetails.getBrokerCount() > 0) - { - setBroker(connectionDetails.getBrokerDetails(0)); - } - else - { - throw new IllegalArgumentException("BrokerDetails details required for connection."); - } - } - - public FailoverSingleServer(BrokerDetails brokerDetail) - { - setBroker(brokerDetail); - } - - public void reset() - { - _currentRetries = 0; - } - - protected void setCurrentRetries(int currentRetries) - { - _currentRetries = currentRetries; - } - - public boolean failoverAllowed() - { - return _currentRetries < _retries; - } - - public void attainedConnection() - { - reset(); - } - - public BrokerDetails getCurrentBrokerDetails() - { - return _brokerDetail; - } - - public BrokerDetails getNextBrokerDetails() - { - if (_currentRetries == _retries) - { - return null; - } - else - { - if (_currentRetries < _retries) - { - _currentRetries++; - } - } - - - String delayStr = _brokerDetail.getProperty(BrokerDetails.OPTIONS_CONNECT_DELAY); - if (delayStr != null && _currentRetries > 0) - { - Long delay = Long.parseLong(delayStr); - _logger.info("Delay between connect retries:" + delay); - try - { - - Thread.sleep(delay); - } - catch (InterruptedException ie) - { - return null; - } - } - else - { - _logger.info("No delay between connect retries, use tcp://host:port?connectdelay='value' to enable."); - } - - return _brokerDetail; - } - - public void setBroker(BrokerDetails broker) - { - if (broker == null) - { - throw new IllegalArgumentException("BrokerDetails details cannot be null"); - } - _brokerDetail = broker; - - String retries = broker.getProperty(BrokerDetails.OPTIONS_RETRY); - if (retries != null) - { - try - { - _retries = Integer.parseInt(retries); - } - catch (NumberFormatException nfe) - { - _retries = DEFAULT_SERVER_RETRIES; - } - } - else - { - _retries = DEFAULT_SERVER_RETRIES; - } - - reset(); - } - - public void setRetries(int retries) - { - _retries = retries; - } - - public int getRetries() - { - return _retries; - } - - public String methodName() - { - return "Single Server"; - } - - public String toString() - { - return methodName()+":\n" + - "Max Retries:" + _retries + - "\nCurrent Retry:" + _currentRetries + - "\n" + _brokerDetail + "\n"; - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/jms/failover/NoFailover.java b/qpid/java/client/src/main/java/org/apache/qpid/jms/failover/NoFailover.java deleted file mode 100644 index 82cb0f9153..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/jms/failover/NoFailover.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.jms.failover; - -import org.apache.qpid.jms.BrokerDetails; -import org.apache.qpid.jms.ConnectionURL; - -/** - * Extend the Single Server Model to gain retry functionality but once connected do not attempt to failover. - */ -public class NoFailover extends FailoverSingleServer -{ - private boolean _connected = false; - - public NoFailover(BrokerDetails brokerDetail) - { - super(brokerDetail); - } - - public NoFailover(ConnectionURL connectionDetails) - { - super(connectionDetails); - } - - @Override - public void attainedConnection() - { - _connected=true; - setCurrentRetries(getRetries()); - } - - @Override - public String methodName() - { - return "NoFailover"; - } - - @Override - public String toString() - { - return super.toString() + (_connected ? "Connection attained." : "Never connected.") + "\n"; - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/jndi/Example.properties b/qpid/java/client/src/main/java/org/apache/qpid/jndi/Example.properties deleted file mode 100644 index def53d8494..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/jndi/Example.properties +++ /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. -# -java.naming.factory.initial = org.apache.qpid.jndi.PropertiesFileInitialConextFactory - -# 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/testpath?brokerlist='vm://:1' - -# register some queues in JNDI using the form -# queue.[jndiName] = [physicalName] -queue.MyQueue = example.MyQueue - -# register some topics in JNDI using the form -# topic.[jndiName] = [physicalName] -topic.ibmStocks = stocks.nyse.ibm - -# Register an AMQP destination in JNDI -# NOTE: Qpid currently only supports direct,topics and headers -# destination.[jniName] = [BindingURL] -destination.direct = direct://amq.direct//directQueue -destination.directQueue = direct://amq.direct//message_queue?routingkey="routing_key" diff --git a/qpid/java/client/src/main/java/org/apache/qpid/jndi/NameParserImpl.java b/qpid/java/client/src/main/java/org/apache/qpid/jndi/NameParserImpl.java deleted file mode 100644 index d7b16fcd6d..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/jndi/NameParserImpl.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.jndi; - -import javax.naming.CompositeName; -import javax.naming.Name; -import javax.naming.NameParser; -import javax.naming.NamingException; - -/** - * A default implementation of {@link NameParser} - * <p> - * Based on class from ActiveMQ. - */ -public class NameParserImpl implements NameParser -{ - public Name parse(String name) throws NamingException - { - return new CompositeName(name); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/jndi/PropertiesFileInitialContextFactory.java b/qpid/java/client/src/main/java/org/apache/qpid/jndi/PropertiesFileInitialContextFactory.java deleted file mode 100644 index a4c3d20042..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/jndi/PropertiesFileInitialContextFactory.java +++ /dev/null @@ -1,380 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.jndi; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.ConcurrentHashMap; - -import javax.jms.ConnectionFactory; -import javax.jms.Destination; -import javax.jms.Queue; -import javax.jms.Topic; -import javax.naming.ConfigurationException; -import javax.naming.Context; -import javax.naming.NamingException; -import javax.naming.spi.InitialContextFactory; - -import org.apache.qpid.client.AMQConnectionFactory; -import org.apache.qpid.client.AMQDestination; -import org.apache.qpid.client.AMQHeadersExchange; -import org.apache.qpid.client.AMQQueue; -import org.apache.qpid.client.AMQTopic; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.url.BindingURL; -import org.apache.qpid.url.URLSyntaxException; -import org.apache.qpid.util.Strings; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - - -public class PropertiesFileInitialContextFactory implements InitialContextFactory -{ - private final Logger _logger = LoggerFactory.getLogger(PropertiesFileInitialContextFactory.class); - - private String CONNECTION_FACTORY_PREFIX = "connectionfactory."; - private String DESTINATION_PREFIX = "destination."; - private String QUEUE_PREFIX = "queue."; - private String TOPIC_PREFIX = "topic."; - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public Context getInitialContext(Hashtable environment) throws NamingException - { - Map data = new ConcurrentHashMap(); - BufferedInputStream inputStream = null; - try - { - - String fileName = (environment.containsKey(Context.PROVIDER_URL)) - ? (String)environment.get(Context.PROVIDER_URL) : System.getProperty(Context.PROVIDER_URL); - - if (fileName != null) - { - _logger.info("Attempting to load " + fileName); - - inputStream = new BufferedInputStream(new FileInputStream((fileName.contains("file:")) - ? new File(new URI(fileName)) : new File(fileName))); - Properties p = new Properties(); - p.load(inputStream); - - Strings.Resolver resolver = new Strings.ChainedResolver - (Strings.SYSTEM_RESOLVER, new Strings.PropertiesResolver(p)); - - for (Map.Entry me : p.entrySet()) - { - String key = (String) me.getKey(); - String value = (String) me.getValue(); - String expanded = Strings.expand(value, resolver); - environment.put(key, expanded); - if (System.getProperty(key) == null) - { - System.setProperty(key, expanded); - } - } - _logger.info("Loaded Context Properties:" + environment.toString()); - } - else - { - _logger.info("No Provider URL specified."); - } - } - catch (IOException ioe) - { - _logger.warn("Unable to load property file specified in Provider_URL:" + environment.get(Context.PROVIDER_URL) +"\n" + - "Due to:" + ioe.getMessage()); - } - catch(URISyntaxException uoe) - { - _logger.warn("Unable to load property file specified in Provider_URL:" + environment.get(Context.PROVIDER_URL) +"\n" + - "Due to:" + uoe.getMessage()); - } - finally - { - try - { - if(inputStream != null) - { - inputStream.close(); - } - } - catch(Exception ignore){} - } - - createConnectionFactories(data, environment); - - createDestinations(data, environment); - - createQueues(data, environment); - - createTopics(data, environment); - - return createContext(data, environment); - } - - // Implementation methods - // ------------------------------------------------------------------------- - protected ReadOnlyContext createContext(Map data, Hashtable environment) - { - return new ReadOnlyContext(environment, data); - } - - protected void createConnectionFactories(Map data, Hashtable environment) throws ConfigurationException - { - for (Iterator iter = environment.entrySet().iterator(); iter.hasNext();) - { - Map.Entry entry = (Map.Entry) iter.next(); - String key = entry.getKey().toString(); - if (key.startsWith(CONNECTION_FACTORY_PREFIX)) - { - String jndiName = key.substring(CONNECTION_FACTORY_PREFIX.length()); - ConnectionFactory cf = createFactory(entry.getValue().toString().trim()); - if (cf != null) - { - data.put(jndiName, cf); - } - } - } - } - - protected void createDestinations(Map data, Hashtable environment) throws ConfigurationException - { - for (Iterator iter = environment.entrySet().iterator(); iter.hasNext();) - { - Map.Entry entry = (Map.Entry) iter.next(); - String key = entry.getKey().toString(); - if (key.startsWith(DESTINATION_PREFIX)) - { - String jndiName = key.substring(DESTINATION_PREFIX.length()); - Destination dest = createDestination(entry.getValue().toString().trim()); - if (dest != null) - { - data.put(jndiName, dest); - } - } - } - } - - protected void createQueues(Map data, Hashtable environment) - { - for (Iterator iter = environment.entrySet().iterator(); iter.hasNext();) - { - Map.Entry entry = (Map.Entry) iter.next(); - String key = entry.getKey().toString(); - if (key.startsWith(QUEUE_PREFIX)) - { - String jndiName = key.substring(QUEUE_PREFIX.length()); - Queue q = createQueue(entry.getValue().toString().trim()); - if (q != null) - { - data.put(jndiName, q); - } - } - } - } - - protected void createTopics(Map data, Hashtable environment) - { - for (Iterator iter = environment.entrySet().iterator(); iter.hasNext();) - { - Map.Entry entry = (Map.Entry) iter.next(); - String key = entry.getKey().toString(); - if (key.startsWith(TOPIC_PREFIX)) - { - String jndiName = key.substring(TOPIC_PREFIX.length()); - Topic t = createTopic(entry.getValue().toString().trim()); - if (t != null) - { - if (_logger.isDebugEnabled()) - { - StringBuffer b = new StringBuffer(); - b.append("Creating the topic: " + jndiName + " with the following binding keys "); - for (AMQShortString binding:((AMQTopic)t).getBindingKeys()) - { - b.append(binding.toString()).append(","); - } - - _logger.debug(b.toString()); - } - data.put(jndiName, t); - } - } - } - } - - /** - * Factory method to create new Connection Factory instances - */ - protected ConnectionFactory createFactory(String url) throws ConfigurationException - { - try - { - return new AMQConnectionFactory(url); - } - catch (URLSyntaxException urlse) - { - _logger.warn("Unable to create factory:" + urlse); - - ConfigurationException ex = new ConfigurationException("Failed to parse entry: " + urlse + " due to : " + urlse.getMessage()); - ex.initCause(urlse); - throw ex; - } - } - - /** - * Factory method to create new Destination instances from an AMQP BindingURL - */ - protected Destination createDestination(String str) throws ConfigurationException - { - try - { - return AMQDestination.createDestination(str, false); - } - catch (Exception e) - { - _logger.warn("Unable to create destination:" + e, e); - - ConfigurationException ex = new ConfigurationException("Failed to parse entry: " + str + " due to : " + e.getMessage()); - ex.initCause(e); - throw ex; - } - } - - /** - * Factory method to create new Queue instances - */ - protected Queue createQueue(Object value) - { - if (value instanceof AMQShortString) - { - return new AMQQueue(AMQShortString.valueOf(ExchangeDefaults.DIRECT_EXCHANGE_NAME), (AMQShortString) value); - } - else if (value instanceof String) - { - return new AMQQueue(AMQShortString.valueOf(ExchangeDefaults.DIRECT_EXCHANGE_NAME), new AMQShortString((String) value)); - } - else if (value instanceof BindingURL) - { - return new AMQQueue((BindingURL) value); - } - - return null; - } - - /** - * Factory method to create new Topic instances - */ - protected Topic createTopic(Object value) - { - if (value instanceof AMQShortString) - { - return new AMQTopic(AMQShortString.valueOf(ExchangeDefaults.TOPIC_EXCHANGE_NAME), (AMQShortString) value); - } - else if (value instanceof String) - { - String[] keys = ((String)value).split(","); - AMQShortString[] bindings = new AMQShortString[keys.length]; - int i = 0; - for (String key:keys) - { - bindings[i] = new AMQShortString(key.trim()); - i++; - } - // The Destination has a dual nature. If this was used for a producer the key is used - // for the routing key. If it was used for the consumer it becomes the bindingKey - return new AMQTopic(AMQShortString.valueOf(ExchangeDefaults.TOPIC_EXCHANGE_NAME),bindings[0],null,bindings); - } - else if (value instanceof BindingURL) - { - return new AMQTopic((BindingURL) value); - } - - return null; - } - - /** - * Factory method to create new HeaderExcahnge instances - */ - protected Destination createHeaderExchange(Object value) - { - if (value instanceof String) - { - return new AMQHeadersExchange((String) value); - } - else if (value instanceof BindingURL) - { - return new AMQHeadersExchange((BindingURL) value); - } - - return null; - } - - // Properties - // ------------------------------------------------------------------------- - public String getConnectionPrefix() - { - return CONNECTION_FACTORY_PREFIX; - } - - public void setConnectionPrefix(String connectionPrefix) - { - this.CONNECTION_FACTORY_PREFIX = connectionPrefix; - } - - public String getDestinationPrefix() - { - return DESTINATION_PREFIX; - } - - public void setDestinationPrefix(String destinationPrefix) - { - this.DESTINATION_PREFIX = destinationPrefix; - } - - public String getQueuePrefix() - { - return QUEUE_PREFIX; - } - - public void setQueuePrefix(String queuePrefix) - { - this.QUEUE_PREFIX = queuePrefix; - } - - public String getTopicPrefix() - { - return TOPIC_PREFIX; - } - - public void setTopicPrefix(String topicPrefix) - { - this.TOPIC_PREFIX = topicPrefix; - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/jndi/ReadOnlyContext.java b/qpid/java/client/src/main/java/org/apache/qpid/jndi/ReadOnlyContext.java deleted file mode 100644 index 1d7525ca91..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/jndi/ReadOnlyContext.java +++ /dev/null @@ -1,521 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.jndi; - -import javax.naming.Binding; -import javax.naming.CompositeName; -import javax.naming.Context; -import javax.naming.LinkRef; -import javax.naming.Name; -import javax.naming.NameClassPair; -import javax.naming.NameNotFoundException; -import javax.naming.NameParser; -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; -import javax.naming.NotContextException; -import javax.naming.OperationNotSupportedException; -import javax.naming.Reference; -import javax.naming.spi.NamingManager; -import java.io.Serializable; -import java.util.Collections; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.Map; - -/** - * Based on class from ActiveMQ. - * A read-only Context - * <p> - * This version assumes it and all its subcontext are read-only and any attempt - * to modify (e.g. through bind) will result in an OperationNotSupportedException. - * Each Context in the tree builds a cache of the entries in all sub-contexts - * to optimise the performance of lookup. - * <p> - * This implementation is intended to optimise the performance of lookup(String) - * to about the level of a HashMap get. It has been observed that the scheme - * resolution phase performed by the JVM takes considerably longer, so for - * optimum performance lookups should be coded like:</p> - * <code> - * Context componentContext = (Context)new InitialContext().lookup("java:comp"); - * String envEntry = (String) componentContext.lookup("env/myEntry"); - * String envEntry2 = (String) componentContext.lookup("env/myEntry2"); - * </code> - */ -public class ReadOnlyContext implements Context, Serializable -{ - private static final long serialVersionUID = -5754338187296859149L; - protected static final NameParser nameParser = new NameParserImpl(); - - private final Hashtable environment; // environment for this context - private final Map bindings; // bindings at my level - private final Map treeBindings; // all bindings under me - - private boolean frozen = false; - private String nameInNamespace = ""; - public static final String SEPARATOR = "/"; - - public ReadOnlyContext() - { - environment = new Hashtable(); - bindings = new HashMap(); - treeBindings = new HashMap(); - } - - public ReadOnlyContext(Hashtable env) - { - if (env == null) - { - this.environment = new Hashtable(); - } - else - { - this.environment = new Hashtable(env); - } - - this.bindings = Collections.EMPTY_MAP; - this.treeBindings = Collections.EMPTY_MAP; - } - - public ReadOnlyContext(Hashtable environment, Map bindings) - { - if (environment == null) - { - this.environment = new Hashtable(); - } - else - { - this.environment = new Hashtable(environment); - } - - this.bindings = bindings; - treeBindings = new HashMap(); - frozen = true; - } - - public ReadOnlyContext(Hashtable environment, Map bindings, String nameInNamespace) - { - this(environment, bindings); - this.nameInNamespace = nameInNamespace; - } - - protected ReadOnlyContext(ReadOnlyContext clone, Hashtable env) - { - this.bindings = clone.bindings; - this.treeBindings = clone.treeBindings; - this.environment = new Hashtable(env); - } - - protected ReadOnlyContext(ReadOnlyContext clone, Hashtable env, String nameInNamespace) - { - this(clone, env); - this.nameInNamespace = nameInNamespace; - } - - public void freeze() - { - frozen = true; - } - - boolean isFrozen() - { - return frozen; - } - - /** - * internalBind is intended for use only during setup or possibly by suitably synchronized superclasses. - * It binds every possible lookup into a map in each context. To do this, each context - * strips off one name segment and if necessary creates a new context for it. Then it asks that context - * to bind the remaining name. It returns a map containing all the bindings from the next context, plus - * the context it just created (if it in fact created it). (the names are suitably extended by the segment - * originally lopped off). - */ - protected Map internalBind(String name, Object value) throws NamingException - { - assert (name != null) && (name.length() > 0); - assert !frozen; - - Map newBindings = new HashMap(); - int pos = name.indexOf('/'); - if (pos == -1) - { - if (treeBindings.put(name, value) != null) - { - throw new NamingException("Something already bound at " + name); - } - - bindings.put(name, value); - newBindings.put(name, value); - } - else - { - String segment = name.substring(0, pos); - assert segment != null; - assert !segment.equals(""); - Object o = treeBindings.get(segment); - if (o == null) - { - o = newContext(); - treeBindings.put(segment, o); - bindings.put(segment, o); - newBindings.put(segment, o); - } - else if (!(o instanceof ReadOnlyContext)) - { - throw new NamingException("Something already bound where a subcontext should go"); - } - - ReadOnlyContext readOnlyContext = (ReadOnlyContext) o; - String remainder = name.substring(pos + 1); - Map subBindings = readOnlyContext.internalBind(remainder, value); - for (Iterator iterator = subBindings.entrySet().iterator(); iterator.hasNext();) - { - Map.Entry entry = (Map.Entry) iterator.next(); - String subName = segment + "/" + (String) entry.getKey(); - Object bound = entry.getValue(); - treeBindings.put(subName, bound); - newBindings.put(subName, bound); - } - } - - return newBindings; - } - - protected ReadOnlyContext newContext() - { - return new ReadOnlyContext(); - } - - public Object addToEnvironment(String propName, Object propVal) throws NamingException - { - return environment.put(propName, propVal); - } - - public Hashtable getEnvironment() throws NamingException - { - return (Hashtable) environment.clone(); - } - - public Object removeFromEnvironment(String propName) throws NamingException - { - return environment.remove(propName); - } - - public Object lookup(String name) throws NamingException - { - if (name.length() == 0) - { - return this; - } - - Object result = treeBindings.get(name); - if (result == null) - { - result = bindings.get(name); - } - - if (result == null) - { - int pos = name.indexOf(':'); - if (pos > 0) - { - String scheme = name.substring(0, pos); - Context ctx = NamingManager.getURLContext(scheme, environment); - if (ctx == null) - { - throw new NamingException("scheme " + scheme + " not recognized"); - } - - return ctx.lookup(name); - } - else - { - // Split out the first name of the path - // and look for it in the bindings map. - CompositeName path = new CompositeName(name); - - if (path.size() == 0) - { - return this; - } - else - { - String first = path.get(0); - Object obj = bindings.get(first); - if (obj == null) - { - throw new NameNotFoundException(name); - } - else if ((obj instanceof Context) && (path.size() > 1)) - { - Context subContext = (Context) obj; - obj = subContext.lookup(path.getSuffix(1)); - } - - return obj; - } - } - } - - if (result instanceof LinkRef) - { - LinkRef ref = (LinkRef) result; - result = lookup(ref.getLinkName()); - } - - if (result instanceof Reference) - { - try - { - result = NamingManager.getObjectInstance(result, null, null, this.environment); - } - catch (NamingException e) - { - throw e; - } - catch (Exception e) - { - throw (NamingException) new NamingException("could not look up : " + name).initCause(e); - } - } - - if (result instanceof ReadOnlyContext) - { - String prefix = getNameInNamespace(); - if (prefix.length() > 0) - { - prefix = prefix + SEPARATOR; - } - - result = new ReadOnlyContext((ReadOnlyContext) result, environment, prefix + name); - } - - return result; - } - - public Object lookup(Name name) throws NamingException - { - return lookup(name.toString()); - } - - public Object lookupLink(String name) throws NamingException - { - return lookup(name); - } - - public Name composeName(Name name, Name prefix) throws NamingException - { - Name result = (Name) prefix.clone(); - result.addAll(name); - - return result; - } - - public String composeName(String name, String prefix) throws NamingException - { - CompositeName result = new CompositeName(prefix); - result.addAll(new CompositeName(name)); - - return result.toString(); - } - - public NamingEnumeration list(String name) throws NamingException - { - Object o = lookup(name); - if (o == this) - { - return new ListEnumeration(); - } - else if (o instanceof Context) - { - return ((Context) o).list(""); - } - else - { - throw new NotContextException(); - } - } - - public NamingEnumeration listBindings(String name) throws NamingException - { - Object o = lookup(name); - if (o == this) - { - return new ListBindingEnumeration(); - } - else if (o instanceof Context) - { - return ((Context) o).listBindings(""); - } - else - { - throw new NotContextException(); - } - } - - public Object lookupLink(Name name) throws NamingException - { - return lookupLink(name.toString()); - } - - public NamingEnumeration list(Name name) throws NamingException - { - return list(name.toString()); - } - - public NamingEnumeration listBindings(Name name) throws NamingException - { - return listBindings(name.toString()); - } - - public void bind(Name name, Object obj) throws NamingException - { - throw new OperationNotSupportedException(); - } - - public void bind(String name, Object obj) throws NamingException - { - throw new OperationNotSupportedException(); - } - - public void close() throws NamingException - { - // ignore - } - - public Context createSubcontext(Name name) throws NamingException - { - throw new OperationNotSupportedException(); - } - - public Context createSubcontext(String name) throws NamingException - { - throw new OperationNotSupportedException(); - } - - public void destroySubcontext(Name name) throws NamingException - { - throw new OperationNotSupportedException(); - } - - public void destroySubcontext(String name) throws NamingException - { - throw new OperationNotSupportedException(); - } - - public String getNameInNamespace() throws NamingException - { - return nameInNamespace; - } - - public NameParser getNameParser(Name name) throws NamingException - { - return nameParser; - } - - public NameParser getNameParser(String name) throws NamingException - { - return nameParser; - } - - public void rebind(Name name, Object obj) throws NamingException - { - throw new OperationNotSupportedException(); - } - - public void rebind(String name, Object obj) throws NamingException - { - throw new OperationNotSupportedException(); - } - - public void rename(Name oldName, Name newName) throws NamingException - { - throw new OperationNotSupportedException(); - } - - public void rename(String oldName, String newName) throws NamingException - { - throw new OperationNotSupportedException(); - } - - public void unbind(Name name) throws NamingException - { - throw new OperationNotSupportedException(); - } - - public void unbind(String name) throws NamingException - { - throw new OperationNotSupportedException(); - } - - private abstract class LocalNamingEnumeration implements NamingEnumeration - { - private Iterator i = bindings.entrySet().iterator(); - - public boolean hasMore() throws NamingException - { - return i.hasNext(); - } - - public boolean hasMoreElements() - { - return i.hasNext(); - } - - protected Map.Entry getNext() - { - return (Map.Entry) i.next(); - } - - public void close() throws NamingException - { } - } - - private class ListEnumeration extends LocalNamingEnumeration - { - public Object next() throws NamingException - { - return nextElement(); - } - - public Object nextElement() - { - Map.Entry entry = getNext(); - - return new NameClassPair((String) entry.getKey(), entry.getValue().getClass().getName()); - } - } - - private class ListBindingEnumeration extends LocalNamingEnumeration - { - public Object next() throws NamingException - { - return nextElement(); - } - - public Object nextElement() - { - Map.Entry entry = getNext(); - - return new Binding((String) entry.getKey(), entry.getValue()); - } - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/nclient/MessagePartListener.java b/qpid/java/client/src/main/java/org/apache/qpid/nclient/MessagePartListener.java deleted file mode 100644 index b90f4308cd..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/nclient/MessagePartListener.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.nclient; - -import org.apache.qpid.transport.MessageTransfer; - -/** - * Assembles message parts. - * <p> The sequence of event for transferring a message is as follows: - * <ul> - * <li> messageHeaders - * <li> n calls to addData - * <li> messageReceived - * </ul> - * It is up to the implementation to assemble the message once the different parts - * are transferred. - */ -public interface MessagePartListener -{ - - /** - * Inform the listener of the message transfer - * - * @param xfr the message transfer object - */ - public void messageTransfer(MessageTransfer xfr); - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/nclient/util/ByteBufferMessage.java b/qpid/java/client/src/main/java/org/apache/qpid/nclient/util/ByteBufferMessage.java deleted file mode 100644 index e8455f6dfa..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/nclient/util/ByteBufferMessage.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.nclient.util; - - -import org.apache.qpid.api.Message; -import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.transport.Header; -import org.apache.qpid.transport.MessageProperties; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - -/** - * <p>A Simple implementation of the message interface - * for small messages. When the readData methods are called - * we assume the message is complete. i.e there want be any - * appendData operations after that.</p> - * - * <p>If you need large message support please see - * <code>FileMessage</code> and <code>StreamingMessage</code> - * </p> - */ -public class ByteBufferMessage implements Message -{ - private List<ByteBuffer> _data; - private ByteBuffer _readBuffer; - private int _dataSize; - private DeliveryProperties _currentDeliveryProps; - private MessageProperties _currentMessageProps; - private int _transferId; - private Header _header; - - public ByteBufferMessage(MessageProperties messageProperties, DeliveryProperties deliveryProperties) - { - _currentMessageProps = messageProperties; - _currentDeliveryProps = deliveryProperties; - } - - public void setHeader(Header header) { - _header = header; - } - - public Header getHeader() { - return _header; - } - - public ByteBufferMessage() - { - _currentDeliveryProps = new DeliveryProperties(); - _currentMessageProps = new MessageProperties(); - } - - public ByteBufferMessage(int transferId) - { - _transferId = transferId; - } - - public int getMessageTransferId() - { - return _transferId; - } - - public void clearData() - { - _data = new LinkedList<ByteBuffer>(); - _readBuffer = null; - } - - public void appendData(byte[] src) throws IOException - { - appendData(ByteBuffer.wrap(src)); - } - - /** - * write the data from the current position up to the buffer limit - */ - public void appendData(ByteBuffer src) throws IOException - { - if(_data == null) - { - _data = Collections.singletonList(src); - } - else - { - if(_data.size() == 1) - { - _data = new ArrayList<ByteBuffer>(_data); - } - _data.add(src); - } - _dataSize += src.remaining(); - } - - public DeliveryProperties getDeliveryProperties() - { - return _currentDeliveryProps; - } - - public MessageProperties getMessageProperties() - { - return _currentMessageProps; - } - - public void setDeliveryProperties(DeliveryProperties props) - { - _currentDeliveryProps = props; - } - - public void setMessageProperties(MessageProperties props) - { - _currentMessageProps = props; - } - - public void readData(byte[] target) - { - getReadBuffer().get(target); - } - - public ByteBuffer readData() - { - return getReadBuffer(); - } - - private void buildReadBuffer() - { - //optimize for the simple cases - if(_data.size() == 1) - { - _readBuffer = _data.get(0).duplicate(); - } - else - { - _readBuffer = ByteBuffer.allocate(_dataSize); - for(ByteBuffer buf:_data) - { - _readBuffer.put(buf); - } - _readBuffer.flip(); - } - } - - private ByteBuffer getReadBuffer() - { - if (_readBuffer != null ) - { - return _readBuffer.slice(); - } - else - { - if (_data.size() >0) - { - buildReadBuffer(); - return _readBuffer.slice(); - } - else - { - return ByteBuffer.allocate(0); - } - } - } - - //hack for testing - @Override public String toString() - { - ByteBuffer temp = getReadBuffer(); - byte[] b = new byte[temp.remaining()]; - temp.get(b); - return new String(b); - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/nclient/util/MessageListener.java b/qpid/java/client/src/main/java/org/apache/qpid/nclient/util/MessageListener.java deleted file mode 100644 index c5edd62143..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/nclient/util/MessageListener.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.nclient.util; - -import org.apache.qpid.api.Message; - -/** - *A message listener - */ -public interface MessageListener -{ - /** - * Process an incoming message. - * - * @param message The incoming message. - */ - public void onMessage(Message message); -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/nclient/util/MessagePartListenerAdapter.java b/qpid/java/client/src/main/java/org/apache/qpid/nclient/util/MessagePartListenerAdapter.java deleted file mode 100644 index a3fce7611f..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/nclient/util/MessagePartListenerAdapter.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.nclient.util; - - -import org.apache.qpid.nclient.MessagePartListener; -import org.apache.qpid.transport.Header; -import org.apache.qpid.transport.MessageTransfer; - -import java.io.IOException; -import java.nio.ByteBuffer; - -/** - * This is a simple message assembler. - * Will call onMessage method of the adaptee - * when all message data is read. - * - * This is a good convinience utility for handling - * small messages - */ -public class MessagePartListenerAdapter implements MessagePartListener -{ - private MessageListener _adaptee; - private ByteBufferMessage _currentMsg; - - public MessagePartListenerAdapter(MessageListener listener) - { - _adaptee = listener; - } - - public void messageTransfer(MessageTransfer xfr) - { - _currentMsg = new ByteBufferMessage(xfr.getId()); - - Header header = xfr.getHeader(); - _currentMsg.setDeliveryProperties(header.getDeliveryProperties()); - _currentMsg.setMessageProperties(header.getMessageProperties()); - - - ByteBuffer body = xfr.getBody(); - if (body == null) - { - body = ByteBuffer.allocate(0); - } - - - try - { - _currentMsg.appendData(body); - } - catch(IOException e) - { - // A chance for IO exception - // doesn't occur as we are using - // a ByteBuffer - } - - _adaptee.onMessage(_currentMsg); - } - -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/AMQConnectionFactoryTest.java b/qpid/java/client/src/test/java/org/apache/qpid/client/AMQConnectionFactoryTest.java deleted file mode 100644 index 6c6aa04ec1..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/client/AMQConnectionFactoryTest.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.client; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; - -import javax.jms.JMSException; - -import junit.framework.TestCase; - -import org.apache.qpid.client.AMQConnectionFactory; -import org.apache.qpid.jms.BrokerDetails; -import org.apache.qpid.jms.ConnectionURL; - -public class AMQConnectionFactoryTest extends TestCase -{ - - //URL will be returned with the password field swapped for '********' - // so ensure that these two strings are kept in sync. - public static final String URL = "amqp://guest:guest@clientID/test?brokerlist='tcp://localhost:5672'"; - public static final String URL_STAR_PWD = "amqp://guest:********@clientID/test?brokerlist='tcp://localhost:5672'"; - - public void testConnectionURLStringMasksPassword() throws Exception - { - AMQConnectionFactory factory = new AMQConnectionFactory(URL); - - //URL will be returned with the password field swapped for '********' - assertEquals("Connection URL not correctly set", URL_STAR_PWD, factory.getConnectionURLString()); - - // Further test that the processed ConnectionURL is as expected after - // the set call - ConnectionURL connectionurl = factory.getConnectionURL(); - - assertNull("Failover is set.", connectionurl.getFailoverMethod()); - assertEquals("guest", connectionurl.getUsername()); - assertEquals("guest", connectionurl.getPassword()); - assertEquals("clientID", connectionurl.getClientName()); - assertEquals("/test", connectionurl.getVirtualHost()); - - assertEquals(1, connectionurl.getBrokerCount()); - - BrokerDetails service = connectionurl.getBrokerDetails(0); - - assertEquals("tcp", service.getTransport()); - assertEquals("localhost", service.getHost()); - assertEquals(5672, service.getPort()); - } - - public void testInstanceCreatedWithDefaultConstructorThrowsExceptionOnCallingConnectWithoutSettingURL() throws Exception - { - AMQConnectionFactory factory = new AMQConnectionFactory(); - - try - { - factory.createConnection(); - fail("Expected exception not thrown"); - } - catch(JMSException e) - { - assertEquals("Unexpected exception", AMQConnectionFactory.NO_URL_CONFIGURED, e.getMessage()); - } - } - - public void testSerialization() throws Exception - { - AMQConnectionFactory factory = new AMQConnectionFactory(); - assertTrue(factory instanceof Serializable); - factory.setConnectionURLString("amqp://guest:guest@clientID/test?brokerlist='tcp://localhost:5672'"); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(bos); - oos.writeObject(factory); - oos.close(); - - ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - ObjectInputStream ois = new ObjectInputStream(bis); - Object deserializedObject = ois.readObject(); - ois.close(); - - AMQConnectionFactory deserialisedFactory = (AMQConnectionFactory) deserializedObject; - assertEquals(factory, deserialisedFactory); - assertEquals(factory.hashCode(), deserialisedFactory.hashCode()); - } -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/AMQConnectionUnitTest.java b/qpid/java/client/src/test/java/org/apache/qpid/client/AMQConnectionUnitTest.java deleted file mode 100644 index d309251b44..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/client/AMQConnectionUnitTest.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.client; - -import java.util.concurrent.atomic.AtomicReference; - -import javax.jms.ExceptionListener; -import javax.jms.JMSException; - -import org.apache.qpid.AMQInvalidArgumentException; -import org.apache.qpid.configuration.ClientProperties; -import org.apache.qpid.jms.ConnectionURL; -import org.apache.qpid.test.utils.QpidTestCase; - -public class AMQConnectionUnitTest extends QpidTestCase -{ - String _url = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672'"; - - public void testVerifyQueueOnSendDefault() throws Exception - { - MockAMQConnection connection = new MockAMQConnection(_url); - assertFalse(connection.validateQueueOnSend()); - } - - public void testVerifyQueueOnSendViaSystemProperty() throws Exception - { - setTestSystemProperty(ClientProperties.VERIFY_QUEUE_ON_SEND, "true"); - MockAMQConnection connection = new MockAMQConnection(_url); - assertTrue(connection.validateQueueOnSend()); - - setTestSystemProperty(ClientProperties.VERIFY_QUEUE_ON_SEND, "false"); - connection = new MockAMQConnection(_url); - assertFalse(connection.validateQueueOnSend()); - } - - public void testVerifyQueueOnSendViaURL() throws Exception - { - MockAMQConnection connection = new MockAMQConnection(_url + "&" + ConnectionURL.OPTIONS_VERIFY_QUEUE_ON_SEND + "='true'"); - assertTrue(connection.validateQueueOnSend()); - - connection = new MockAMQConnection(_url + "&" + ConnectionURL.OPTIONS_VERIFY_QUEUE_ON_SEND + "='false'"); - assertFalse(connection.validateQueueOnSend()); - } - - public void testVerifyQueueOnSendViaURLoverridesSystemProperty() throws Exception - { - setTestSystemProperty(ClientProperties.VERIFY_QUEUE_ON_SEND, "false"); - MockAMQConnection connection = new MockAMQConnection(_url + "&" + ConnectionURL.OPTIONS_VERIFY_QUEUE_ON_SEND + "='true'"); - assertTrue(connection.validateQueueOnSend()); - } - - public void testExceptionReceived() - { - AMQInvalidArgumentException expectedException = new AMQInvalidArgumentException("Test", null); - final AtomicReference<JMSException> receivedException = new AtomicReference<JMSException>(); - try - { - MockAMQConnection connection = new MockAMQConnection(_url); - connection.setExceptionListener(new ExceptionListener() - { - - @Override - public void onException(JMSException jmsException) - { - receivedException.set(jmsException); - } - }); - connection.exceptionReceived(expectedException); - } - catch (Exception e) - { - fail("Failure to test exceptionRecived:" + e.getMessage()); - } - JMSException exception = receivedException.get(); - assertNotNull("Expected JMSException but got null", exception); - assertEquals("JMSException error code is incorrect", Integer.toString(expectedException.getErrorCode().getCode()), exception.getErrorCode()); - assertNotNull("Expected not null message for JMSException", exception.getMessage()); - assertTrue("JMSException error message is incorrect", exception.getMessage().contains(expectedException.getMessage())); - assertEquals("JMSException linked exception is incorrect", expectedException, exception.getLinkedException()); - } - - /** - * This should expand to test all the defaults. - */ - public void testDefaultStreamMessageEncoding() throws Exception - { - MockAMQConnection connection = new MockAMQConnection(_url); - assertTrue("Legacy Stream message encoding should be the default",connection.isUseLegacyStreamMessageFormat()); - } - - /** - * This should expand to test all the connection properties. - */ - public void testStreamMessageEncodingProperty() throws Exception - { - MockAMQConnection connection = new MockAMQConnection(_url + "&use_legacy_stream_msg_format='false'"); - assertFalse("Stream message encoding should be amqp/list",connection.isUseLegacyStreamMessageFormat()); - } - -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/AMQDestinationTest.java b/qpid/java/client/src/test/java/org/apache/qpid/client/AMQDestinationTest.java deleted file mode 100644 index a494192148..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/client/AMQDestinationTest.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.client; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import javax.jms.Destination; -import javax.jms.Queue; -import javax.jms.Topic; - -import junit.framework.TestCase; - -public class AMQDestinationTest extends TestCase -{ - public void testEqualsAndHashCodeForAddressBasedDestinations() throws Exception - { - AMQDestination dest = new AMQQueue("ADDR:Foo; {node :{type:queue}}"); - AMQDestination dest1 = new AMQTopic("ADDR:Foo; {node :{type:topic}}"); - AMQDestination dest10 = new AMQTopic("ADDR:Foo; {node :{type:topic}, link:{name:my-topic}}"); - AMQDestination dest2 = new AMQQueue("ADDR:Foo; {create:always,node :{type:queue}}"); - String bUrl = "BURL:direct://amq.direct/test-route/Foo?routingkey='Foo'"; - AMQDestination dest3 = new AMQQueue(bUrl); - - assertTrue(dest.equals(dest)); - assertFalse(dest.equals(dest1)); - assertTrue(dest.equals(dest2)); - assertFalse(dest.equals(dest3)); - assertTrue(dest1.equals(dest10)); - - assertTrue(dest.hashCode() == dest.hashCode()); - assertTrue(dest.hashCode() != dest1.hashCode()); - assertTrue(dest.hashCode() == dest2.hashCode()); - assertTrue(dest.hashCode() != dest3.hashCode()); - assertTrue(dest1.hashCode() == dest10.hashCode()); - - AMQDestination dest4 = new AMQQueue("ADDR:Foo/Bar; {node :{type:queue}}"); - AMQDestination dest5 = new AMQQueue("ADDR:Foo/Bar2; {node :{type:queue}}"); - assertFalse(dest4.equals(dest5)); - assertTrue(dest4.hashCode() != dest5.hashCode()); - - AMQDestination dest6 = new AMQAnyDestination("ADDR:Foo; {node :{type:queue}}"); - AMQDestination dest7 = new AMQAnyDestination("ADDR:Foo; {create: always, node :{type:queue}, link:{capacity: 10}}"); - AMQDestination dest8 = new AMQAnyDestination("ADDR:Foo; {create: always, link:{capacity: 10}}"); - AMQDestination dest9 = new AMQAnyDestination("ADDR:Foo/bar"); - assertTrue(dest6.equals(dest7)); - assertFalse(dest6.equals(dest8)); //dest8 type unknown, could be a topic - assertFalse(dest7.equals(dest8)); //dest8 type unknown, could be a topic - assertFalse(dest6.equals(dest9)); - assertTrue(dest6.hashCode() == dest7.hashCode()); - assertTrue(dest6.hashCode() != dest8.hashCode()); - assertTrue(dest7.hashCode() != dest8.hashCode()); - assertTrue(dest6.hashCode() != dest9.hashCode()); - } - - /** - * Tests that destinations created with the same options string will share the same address options map. - */ - public void testCacheAddressOptionsMaps() throws Exception - { - // Create destinations 1 and 3 with the same options string, and destinations 2 and 4 with a different one - String optionsStringA = "{create: always, node: {type: topic}}"; - String optionsStringB = "{}"; // empty options - AMQDestination dest1 = createDestinationWithOptions("testDest1", optionsStringA); - AMQDestination dest2 = createDestinationWithOptions("testDest2", optionsStringB); - AMQDestination dest3 = createDestinationWithOptions("testDest3", optionsStringA); - AMQDestination dest4 = createDestinationWithOptions("testDest4", optionsStringB); - - // Destinations 1 and 3 should refer to the same address options map - assertSame("Destinations 1 and 3 were created with the same options and should refer to the same options map.", - dest1.getAddress().getOptions(), dest3.getAddress().getOptions()); - // Destinations 2 and 4 should refer to the same address options map - assertSame("Destinations 2 and 4 were created with the same options and should refer to the same options map.", - dest2.getAddress().getOptions(), dest4.getAddress().getOptions()); - // Destinations 1 and 2 should have a different options map - assertNotSame("Destinations 1 and 2 should not have the same options map.", - dest1.getAddress().getOptions(), dest2.getAddress().getOptions()); - - // Verify the contents of the shared map are as expected - Map<String, Object> optionsA = new HashMap<String, Object>(); - optionsA.put("create", "always"); - optionsA.put("node", Collections.singletonMap("type", "topic")); - assertEquals("Contents of the shared address options map are not as expected.", - optionsA, dest1.getAddress().getOptions()); - assertEquals("Contents of the empty shared address options map are not as expected.", - Collections.emptyMap(), dest2.getAddress().getOptions()); - - // Verify that address options map is immutable - try - { - dest1.getAddress().getOptions().put("testKey", "testValue"); - fail("Should not be able able to modify an address's options map."); - } - catch (UnsupportedOperationException e) - { - // expected - } - } - - private AMQDestination createDestinationWithOptions(String destName, String optionsString) throws Exception - { - String addr = "ADDR:" + destName + "; " + optionsString; - return new AMQAnyDestination(addr); - } - - /** - * Tests that when a queue has no link subscription arguments and no link bindings, its Subscription - * arguments and its bindings list refer to constant empty collections. - */ - public void testEmptyLinkBindingsAndSubscriptionArgs() throws Exception - { - // no link properties - assertEmptyLinkBindingsAndSubscriptionArgs(new AMQAnyDestination("ADDR:testQueue")); - - // has link properties but no x-bindings; has link x-subscribes but no arguments - String xSubscribeAddr = "ADDR:testQueueWithXSubscribes; {link: {x-subscribes: {exclusive: true}}}"; - assertEmptyLinkBindingsAndSubscriptionArgs(new AMQAnyDestination(xSubscribeAddr)); - } - - private void assertEmptyLinkBindingsAndSubscriptionArgs(AMQDestination dest) - { - assertEquals("Default link subscription arguments should be the constant Collections empty map.", - Collections.emptyMap(), dest.getLink().getSubscription().getArgs()); - assertSame("Defaultl link bindings should be the constant Collections empty list.", - Collections.emptyList(), dest.getLink().getBindings()); - } - - /** - * Tests that when a node has no bindings specified, its bindings list refers to a constant empty list, - * so that we are not consuming extra memory unnecessarily. - */ - public void testEmptyNodeBindings() throws Exception - { - // no node properties - assertEmptyNodeBindings(new AMQAnyDestination("ADDR:testDest1")); - // has node properties but no x-bindings - assertEmptyNodeBindings(new AMQAnyDestination("ADDR:testDest2; {node: {type: queue}}")); - assertEmptyNodeBindings(new AMQAnyDestination("ADDR:testDest3; {node: {type: topic}}")); - } - - public void testSerializeAMQQueue_BURL() throws Exception - { - Queue queue = new AMQQueue("BURL:direct://amq.direct/test-route/Foo?routingkey='Foo'"); - assertTrue(queue instanceof Serializable); - - Queue deserialisedQueue = (Queue) serialiseDeserialiseDestination(queue); - - assertEquals(queue, deserialisedQueue); - assertEquals(queue.hashCode(), deserialisedQueue.hashCode()); - } - - public void testSerializeAMQQueue_ADDR() throws Exception - { - Queue queue = new AMQQueue("ADDR:testDest2; {node: {type: queue}}"); - assertTrue(queue instanceof Serializable); - - Queue deserialisedQueue = (Queue) serialiseDeserialiseDestination(queue); - - assertEquals(queue, deserialisedQueue); - assertEquals(queue.hashCode(), deserialisedQueue.hashCode()); - } - - public void testSerializeAMQTopic_BURL() throws Exception - { - Topic topic = new AMQTopic("BURL:topic://amq.topic/mytopic/?routingkey='mytopic'"); - assertTrue(topic instanceof Serializable); - - Topic deserialisedTopic = (Topic) serialiseDeserialiseDestination(topic); - - assertEquals(topic, deserialisedTopic); - assertEquals(topic.hashCode(), deserialisedTopic.hashCode()); - } - - public void testSerializeAMQTopic_ADDR() throws Exception - { - Topic topic = new AMQTopic("ADDR:my-topic; {assert: always, node:{ type: topic }}"); - assertTrue(topic instanceof Serializable); - - Topic deserialisedTopic = (Topic) serialiseDeserialiseDestination(topic); - - assertEquals(topic, deserialisedTopic); - assertEquals(topic.hashCode(), deserialisedTopic.hashCode()); - } - - private void assertEmptyNodeBindings(AMQDestination dest) - { - assertSame("Empty node bindings should refer to the constant Collections empty list.", - Collections.emptyList(), dest.getNode().getBindings()); - } - - private Destination serialiseDeserialiseDestination(final Destination dest) throws Exception - { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(bos); - oos.writeObject(dest); - oos.close(); - - ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - ObjectInputStream ois = new ObjectInputStream(bis); - Object deserializedObject = ois.readObject(); - ois.close(); - return (Destination)deserializedObject; - } - - -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/AMQQueueTest.java b/qpid/java/client/src/test/java/org/apache/qpid/client/AMQQueueTest.java deleted file mode 100644 index bc48ee8895..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/client/AMQQueueTest.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.client; - -import junit.framework.TestCase; - -import org.apache.qpid.framing.AMQShortString; - -public class AMQQueueTest extends TestCase -{ - private AMQShortString exchange = new AMQShortString("test.exchange"); - private AMQShortString routingkey = new AMQShortString("test-route"); - private AMQShortString qname = new AMQShortString("test-queue"); - private AMQShortString[] oneBinding = new AMQShortString[]{new AMQShortString("bindingA")}; - private AMQShortString[] bindings = new AMQShortString[]{new AMQShortString("bindingB"), - new AMQShortString("bindingC")}; - - public void testToURLNoBindings() - { - AMQQueue dest = new AMQQueue(exchange, routingkey, qname); - String url = dest.toURL(); - assertEquals("direct://test.exchange/test-route/test-queue?routingkey='test-route'", url); - } -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/AMQSession_0_10Test.java b/qpid/java/client/src/test/java/org/apache/qpid/client/AMQSession_0_10Test.java deleted file mode 100644 index 2543c5b500..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/client/AMQSession_0_10Test.java +++ /dev/null @@ -1,697 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; - -import java.util.ArrayList; -import java.util.List; - -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.StreamMessage; - -import org.apache.qpid.client.message.AMQPEncodedListMessage; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.transport.*; -import org.apache.qpid.transport.Connection.SessionFactory; -import org.apache.qpid.transport.Connection.State; - -/** - * Tests AMQSession_0_10 methods. - * <p> - * The main purpose of the tests in this test suite is to check that - * {@link SessionException} is not thrown from methods of - * {@link AMQSession_0_10}. - */ -public class AMQSession_0_10Test extends QpidTestCase -{ - - public void testExceptionOnCommit() - { - AMQSession_0_10 session = createThrowingExceptionAMQSession_0_10(); - try - { - session.commit(); - fail("JMSException should be thrown"); - } - catch (Exception e) - { - assertTrue("JMSException is expected", e instanceof JMSException); - assertEquals("541 error code is expected", "541", ((JMSException) e).getErrorCode()); - } - } - - public void testExceptionOnCreateMessageProducer() - { - AMQSession_0_10 session = createThrowingExceptionAMQSession_0_10(); - try - { - session.createMessageProducer(createDestination(), true, true, 1l); - fail("JMSException should be thrown"); - } - catch (Exception e) - { - assertTrue("JMSException is expected but got:" + e, e instanceof JMSException); - assertEquals("541 error code is expected", "541", ((JMSException) e).getErrorCode()); - } - } - - public void testExceptionOnRollback() - { - AMQSession_0_10 session = createThrowingExceptionAMQSession_0_10(); - try - { - session.rollback(); - fail("JMSException should be thrown"); - } - catch (Exception e) - { - assertTrue("JMSException is expected", e instanceof JMSException); - } - } - - public void testExceptionOnRecover() - { - AMQSession_0_10 session = createThrowingExceptionAMQSession_0_10(javax.jms.Session.AUTO_ACKNOWLEDGE); - try - { - session.recover(); - fail("JMSException should be thrown"); - } - catch (Exception e) - { - assertTrue("JMSException is expected", e instanceof JMSException); - } - } - - public void testExceptionOnCreateBrowser() - { - AMQSession_0_10 session = createThrowingExceptionAMQSession_0_10(); - AMQQueue destination = createQueue(); - try - { - session.createBrowser(destination); - fail("JMSException should be thrown"); - } - catch (Exception e) - { - assertTrue("JMSException is expected", e instanceof JMSException); - assertEquals("541 error code is expected", "541", ((JMSException) e).getErrorCode()); - } - } - - public void testExceptionOnCreateConsumer() - { - AMQSession_0_10 session = createThrowingExceptionAMQSession_0_10(); - AMQAnyDestination destination = createDestination(); - try - { - session.createConsumer(destination); - fail("JMSException should be thrown"); - } - catch (Exception e) - { - assertTrue("JMSException is expected", e instanceof JMSException); - assertEquals("541 error code is expected", "541", ((JMSException) e).getErrorCode()); - } - } - - public void testExceptionOnCreateSubscriber() - { - AMQSession_0_10 session = createThrowingExceptionAMQSession_0_10(); - AMQAnyDestination destination = createDestination(); - try - { - session.createSubscriber(destination); - fail("JMSException should be thrown"); - } - catch (Exception e) - { - assertTrue("JMSException is expected", e instanceof JMSException); - assertEquals("541 error code is expected", "541", ((JMSException) e).getErrorCode()); - } - } - - public void testExceptionOnUnsubscribe() - { - AMQSession_0_10 session = createThrowingExceptionAMQSession_0_10(); - try - { - session.unsubscribe("whatever"); - fail("JMSExceptiuon should be thrown"); - } - catch (Exception e) - { - assertTrue("JMSException is expected", e instanceof JMSException); - assertEquals("541 error code is expected", "541", ((JMSException) e).getErrorCode()); - } - } - - public void testCommit() - { - AMQSession_0_10 session = createAMQSession_0_10(); - try - { - session.commit(); - } - catch (Exception e) - { - fail("Unexpected exception is caught:" + e.getMessage()); - } - ProtocolEvent event = findSentProtocolEventOfClass(session, TxCommit.class, false); - assertNotNull("TxCommit was not sent", event); - } - - public void testRollback() - { - AMQSession_0_10 session = createAMQSession_0_10(); - try - { - session.rollback(); - } - catch (Exception e) - { - fail("Unexpected exception is caught:" + e.getMessage()); - } - ProtocolEvent event = findSentProtocolEventOfClass(session, TxRollback.class, false); - assertNotNull("TxRollback was not sent", event); - } - - public void testRecover() - { - AMQSession_0_10 session = createAMQSession_0_10(javax.jms.Session.AUTO_ACKNOWLEDGE); - try - { - session.recover(); - } - catch (Exception e) - { - fail("Unexpected exception is caught:" + e.getMessage()); - } - ProtocolEvent event = findSentProtocolEventOfClass(session, MessageRelease.class, false); - assertNotNull("MessageRelease was not sent", event); - } - - public void testCreateProducer() - { - AMQSession_0_10 session = createAMQSession_0_10(); - try - { - session.createProducer(createQueue()); - } - catch (Exception e) - { - fail("Unexpected exception is caught:" + e.getMessage()); - } - ProtocolEvent event = findSentProtocolEventOfClass(session, ExchangeDeclare.class, false); - assertNotNull("ExchangeDeclare was not sent", event); - } - - public void testCreateConsumer() - { - AMQSession_0_10 session = createAMQSession_0_10(); - try - { - session.createConsumer(createQueue()); - } - catch (Exception e) - { - fail("Unexpected exception is caught:" + e.getMessage()); - } - ProtocolEvent event = findSentProtocolEventOfClass(session, MessageSubscribe.class, false); - assertNotNull("MessageSubscribe was not sent", event); - } - - public void testSync() - { - AMQSession_0_10 session = createAMQSession_0_10(); - try - { - session.sync(); - } - catch (Exception e) - { - fail("Unexpected exception is caught:" + e.getMessage()); - } - ProtocolEvent event = findSentProtocolEventOfClass(session, ExecutionSync.class, false); - assertNotNull("ExecutionSync was not sent", event); - } - - public void testSendQueueDelete() - { - AMQSession_0_10 session = createAMQSession_0_10(); - try - { - session.sendQueueDelete(new AMQShortString("test")); - } - catch (Exception e) - { - fail("Unexpected exception is caught:" + e.getMessage()); - } - ProtocolEvent event = findSentProtocolEventOfClass(session, QueueDelete.class, false); - assertNotNull("QueueDelete event was not sent", event); - QueueDelete exchangeDelete = (QueueDelete) event; - assertEquals("test", exchangeDelete.getQueue()); - } - - public void testSendConsume() - { - AMQSession_0_10 session = createAMQSession_0_10(); - try - { - BasicMessageConsumer_0_10 consumer = session.createMessageConsumer(createDestination(), 1, 1, true, false, - null, null, false, true); - session.sendConsume(consumer, new AMQShortString("test"), true, 1); - } - catch (Exception e) - { - fail("Unexpected exception is caught:" + e.getMessage()); - } - ProtocolEvent event = findSentProtocolEventOfClass(session, MessageSubscribe.class, false); - assertNotNull("MessageSubscribe event was not sent", event); - } - - public void testCreateMessageProducer() - { - AMQSession_0_10 session = createAMQSession_0_10(); - try - { - session.createMessageProducer(createDestination(), true, true, 1l); - } - catch (Exception e) - { - fail("Unexpected exception is caught:" + e.getMessage()); - } - ProtocolEvent event = findSentProtocolEventOfClass(session, ExchangeDeclare.class, false); - assertNotNull("ExchangeDeclare event was not sent", event); - } - - public void testSendExchangeDelete() - { - AMQSession_0_10 session = createAMQSession_0_10(); - try - { - session.sendExchangeDelete("test", true); - } - catch (Exception e) - { - fail("Unexpected exception is caught:" + e.getMessage()); - } - ProtocolEvent event = findSentProtocolEventOfClass(session, ExchangeDelete.class, false); - assertNotNull("ExchangeDelete event was not sent", event); - ExchangeDelete exchangeDelete = (ExchangeDelete) event; - assertEquals("test", exchangeDelete.getExchange()); - } - - public void testExceptionOnMessageConsumerReceive() - { - AMQSession_0_10 session = createThrowingExceptionAMQSession_0_10(); - try - { - BasicMessageConsumer_0_10 consumer = session.createMessageConsumer(createDestination(), 1, 1, true, false, - null, null, false, true); - session.start(); - consumer.receive(1); - fail("JMSException should be thrown"); - } - catch (Exception e) - { - assertTrue("JMSException is expected", e instanceof JMSException); - assertEquals("541 error code is expected", "541", ((JMSException) e).getErrorCode()); - } - } - - public void testMessageConsumerReceive() - { - AMQSession_0_10 session = createAMQSession_0_10(); - try - { - BasicMessageConsumer_0_10 consumer = session.createMessageConsumer(createDestination(), 1, 1, true, false, - null, null, false, true); - session.start(); - consumer.receive(1); - } - catch (Exception e) - { - fail("Unexpected exception is caught:" + e.getMessage()); - } - ProtocolEvent event = findSentProtocolEventOfClass(session, MessageFlow.class, false); - assertNotNull("MessageFlow event was not sent", event); - } - - public void testExceptionOnMessageConsumerReceiveNoWait() - { - AMQSession_0_10 session = createThrowingExceptionAMQSession_0_10(); - try - { - BasicMessageConsumer_0_10 consumer = session.createMessageConsumer(createDestination(), 1, 1, true, false, - null, null, false, true); - session.start(); - consumer.receiveNoWait(); - fail("JMSException should be thrown"); - } - catch (Exception e) - { - assertTrue("JMSException is expected", e instanceof JMSException); - assertEquals("541 error code is expected", "541", ((JMSException) e).getErrorCode()); - } - } - - public void testMessageConsumerClose() - { - AMQSession_0_10 session = createAMQSession_0_10(); - try - { - BasicMessageConsumer_0_10 consumer = session.createMessageConsumer(createDestination(), 1, 1, true, false, - null, null, false, true); - consumer.close(); - } - catch (Exception e) - { - fail("Unexpected exception is caught:" + e.getMessage()); - } - ProtocolEvent event = findSentProtocolEventOfClass(session, MessageCancel.class, false); - assertNotNull("MessageCancel event was not sent", event); - } - - public void testExceptionOnMessageConsumerClose() - { - AMQSession_0_10 session = createThrowingExceptionAMQSession_0_10(); - try - { - BasicMessageConsumer_0_10 consumer = session.createMessageConsumer(createDestination(), 1, 1, true, false, - null, null, false, true); - consumer.close(); - fail("JMSException should be thrown"); - } - catch (Exception e) - { - assertTrue("JMSException is expected", e instanceof JMSException); - assertEquals("541 error code is expected", "541", ((JMSException) e).getErrorCode()); - } - } - - public void testMessageProducerSend() - { - AMQSession_0_10 session = createAMQSession_0_10(); - try - { - MessageProducer producer = session.createProducer(createQueue()); - producer.send(session.createTextMessage("Test")); - session.commit(); - } - catch (Exception e) - { - fail("Unexpected exception is caught:" + e.getMessage()); - } - ProtocolEvent event = findSentProtocolEventOfClass(session, MessageTransfer.class, false); - assertNotNull("MessageTransfer event was not sent", event); - event = findSentProtocolEventOfClass(session, ExchangeDeclare.class, false); - assertNotNull("ExchangeDeclare event was not sent", event); - } - - public void testCreateStreamMessage() throws Exception - { - AMQSession_0_10 session = createAMQSession_0_10(); - StreamMessage m = session.createStreamMessage(); - assertTrue("Legacy Stream message encoding should be the default" + m.getClass(),!(m instanceof AMQPEncodedListMessage)); - } - - public void testGetQueueDepthWithSync() - { - // slow down a flush thread - setTestSystemProperty("qpid.session.max_ack_delay", "10000"); - AMQSession_0_10 session = createAMQSession_0_10(false, javax.jms.Session.DUPS_OK_ACKNOWLEDGE); - try - { - session.acknowledgeMessage(-1, false); - session.getQueueDepth(createDestination(), true); - } - catch (Exception e) - { - fail("Unexpected exception is caught:" + e.getMessage()); - } - ProtocolEvent command = findSentProtocolEventOfClass(session, MessageAccept.class, false); - assertNotNull("MessageAccept command was not sent", command); - command = findSentProtocolEventOfClass(session, ExecutionSync.class, false); - assertNotNull("ExecutionSync command was not sent", command); - command = findSentProtocolEventOfClass(session, QueueQuery.class, false); - assertNotNull("QueueQuery command was not sent", command); - } - - private AMQAnyDestination createDestination() - { - AMQAnyDestination destination = null; - try - { - destination = new AMQAnyDestination(new AMQShortString("amq.direct"), new AMQShortString("direct"), - new AMQShortString("test"), false, true, new AMQShortString("test"), true, null); - } - catch (Exception e) - { - fail("Failued to create destination:" + e.getMessage()); - } - return destination; - } - - private AMQQueue createQueue() - { - AMQQueue destination = null; - try - { - destination = new AMQQueue(new AMQShortString("amq.direct"), new AMQShortString("test"), - new AMQShortString("test")); - } - catch (Exception e) - { - fail("Failued to create destination:" + e.getMessage()); - } - return destination; - } - - private AMQSession_0_10 createThrowingExceptionAMQSession_0_10() - { - return createAMQSession_0_10(true, javax.jms.Session.SESSION_TRANSACTED); - } - - private AMQSession_0_10 createThrowingExceptionAMQSession_0_10(int akcnowledgeMode) - { - return createAMQSession_0_10(true, akcnowledgeMode); - } - - private ProtocolEvent findSentProtocolEventOfClass(AMQSession_0_10 session, Class<? extends ProtocolEvent> class1, - boolean isLast) - { - ProtocolEvent found = null; - List<ProtocolEvent> events = ((MockSession) session.getQpidSession()).getSender().getSendEvents(); - assertNotNull("Events list should not be null", events); - assertFalse("Events list should not be empty", events.isEmpty()); - if (isLast) - { - ProtocolEvent event = events.get(events.size() - 1); - if (event.getClass().isAssignableFrom(class1)) - { - found = event; - } - } - else - { - for (ProtocolEvent protocolEvent : events) - { - if (protocolEvent.getClass().isAssignableFrom(class1)) - { - found = protocolEvent; - break; - } - } - - } - return found; - } - - private AMQSession_0_10 createAMQSession_0_10() - { - return createAMQSession_0_10(false, javax.jms.Session.SESSION_TRANSACTED); - } - - private AMQSession_0_10 createAMQSession_0_10(int acknowledgeMode) - { - return createAMQSession_0_10(false, acknowledgeMode); - } - - private AMQSession_0_10 createAMQSession_0_10(boolean throwException, int acknowledgeMode) - { - AMQConnection amqConnection = null; - try - { - amqConnection = new MockAMQConnection( - "amqp://guest:guest@client/test?brokerlist='tcp://localhost:1'&maxprefetch='0'"); - } - catch (Exception e) - { - fail("Failure to create a mock connection:" + e.getMessage()); - } - boolean isTransacted = acknowledgeMode == javax.jms.Session.SESSION_TRANSACTED ? true : false; - AMQSession_0_10 session = new AMQSession_0_10(createConnection(throwException), amqConnection, 1, isTransacted, acknowledgeMode, - 10, 10, "test"); - return session; - } - - private Connection createConnection(final boolean throwException) - { - MockTransportConnection connection = new MockTransportConnection(); - connection.setState(State.OPEN); - connection.setSender(new MockSender()); - connection.setSessionFactory(new SessionFactory() - { - - public Session newSession(Connection conn, Binary name, long expiry, boolean isNoReplay) - { - return new MockSession(conn, new SessionDelegate(), name, expiry, throwException); - } - }); - return connection; - } - - private final class MockMessageListener implements MessageListener - { - public void onMessage(Message arg0) - { - } - } - - class MockSession extends Session - { - private final boolean _throwException; - private final Connection _connection; - private final SessionDelegate _delegate; - - protected MockSession(Connection connection, SessionDelegate delegate, Binary name, long expiry, - boolean throwException) - { - super(connection, delegate, name, expiry); - _throwException = throwException; - setState(State.OPEN); - _connection = connection; - _delegate = delegate; - } - - public void invoke(Method m, Runnable postIdSettingAction) - { - if (_throwException) - { - if (m instanceof SessionAttach || m instanceof SessionRequestTimeout || m instanceof TxSelect) - { - // do not throw exception for SessionAttach, - // SessionRequestTimeout and TxSelect - // session needs to be instantiated - return; - } - ExecutionException e = new ExecutionException(); - e.setErrorCode(ExecutionErrorCode.INTERNAL_ERROR); - throw new SessionException(e); - } - else - { - super.invoke(m, postIdSettingAction); - if (m instanceof SessionDetach) - { - setState(State.CLOSED); - } - } - } - - public void sync() - { - // to avoid recursive calls - setAutoSync(false); - // simply send sync command - super.executionSync(Option.SYNC); - } - - protected <T> Future<T> invoke(Method m, Class<T> klass) - { - int commandId = getCommandsOut(); - Future<T> future = super.invoke(m, klass); - ExecutionResult result = new ExecutionResult(); - result.setCommandId(commandId); - if (m instanceof ExchangeBound) - { - ExchangeBoundResult struc = new ExchangeBoundResult(); - result.setValue(struc); - } - else if (m instanceof ExchangeQuery) - { - ExchangeQueryResult struc = new ExchangeQueryResult(); - result.setValue(struc); - } - else if (m instanceof QueueQuery) - { - QueueQueryResult struc = new QueueQueryResult(); - result.setValue(struc); - } - _delegate.executionResult(this, result); - return future; - } - - public MockSender getSender() - { - return (MockSender) _connection.getSender(); - } - } - - class MockTransportConnection extends Connection - { - public void setState(State state) - { - super.setState(state); - } - } - - class MockSender implements ProtocolEventSender - { - private List<ProtocolEvent> _sendEvents = new ArrayList<ProtocolEvent>(); - - private void setIdleTimeout(int i) - { - } - - public void send(ProtocolEvent msg) - { - _sendEvents.add(msg); - } - - public void flush() - { - } - - public void close() - { - } - - public List<ProtocolEvent> getSendEvents() - { - return _sendEvents; - } - - } - -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/AMQSession_0_8Test.java b/qpid/java/client/src/test/java/org/apache/qpid/client/AMQSession_0_8Test.java deleted file mode 100644 index 2a8ab22b81..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/client/AMQSession_0_8Test.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.client; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.transport.TestNetworkConnection; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.QueueDeclareOkBody; -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.transport.network.NetworkConnection; -import org.apache.qpid.url.AMQBindingURL; - -public class AMQSession_0_8Test extends QpidTestCase -{ - private AMQConnection _connection; - - public void setUp() throws Exception - { - _connection = new MockAMQConnection("amqp://guest:guest@/test?brokerlist='tcp://localhost:5672'"); - NetworkConnection network = new TestNetworkConnection(); - _connection.getProtocolHandler().setNetworkConnection(network); - } - - public void testQueueNameIsGeneratedOnDeclareQueueWithEmptyQueueName() throws Exception - { - final AMQShortString testQueueName = AMQShortString.valueOf("tmp_127_0_0_1_1_1"); - - _connection.setConnectionListener(new ConnectionListenerSupport() - { - @Override - public void bytesSent(long count) - { - try - { - _connection.getProtocolHandler().methodBodyReceived(1, new QueueDeclareOkBody(testQueueName, 0, 0)); - } - catch (AMQException e) - { - throw new RuntimeException(e); - } - } - }); - - AMQSession_0_8 session = new AMQSession_0_8(_connection, 1, true, 0, 1, 1); - - AMQBindingURL bindingURL = new AMQBindingURL("topic://amq.topic//?routingkey='testTopic'"); - AMQQueue queue = new AMQQueue(bindingURL); - - assertEquals("Unexpected queue name", AMQShortString.EMPTY_STRING, queue.getAMQQueueName()); - - session.declareQueue(queue, true); - - assertEquals("Unexpected queue name", testQueueName, queue.getAMQQueueName()); - } -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/BasicMessageConsumer_0_8_Test.java b/qpid/java/client/src/test/java/org/apache/qpid/client/BasicMessageConsumer_0_8_Test.java deleted file mode 100644 index 066ece7ed1..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/client/BasicMessageConsumer_0_8_Test.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.client; - -import junit.framework.TestCase; - -import org.apache.qpid.test.unit.message.TestAMQSession; -import org.apache.qpid.url.AMQBindingURL; - -import javax.jms.Session; - -public class BasicMessageConsumer_0_8_Test extends TestCase -{ - /** - * Test that if there is a value for Reject Behaviour specified for the Destination - * used to create the Consumer, it overrides the value for the Connection. - */ - public void testDestinationRejectBehaviourOverridesDefaultConnection() throws Exception - { - /* - * Check that when the connection does not have a value applied that this - * is successfully overridden with a specific value by the consumer. - */ - String connUrlString = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672'"; - AMQConnection conn = new MockAMQConnection(connUrlString); - - String url = "exchangeClass://exchangeName/Destination/Queue?rejectbehaviour='server'"; - AMQBindingURL burl = new AMQBindingURL(url); - AMQDestination queue = new AMQQueue(burl); - - TestAMQSession testSession = new TestAMQSession(conn); - BasicMessageConsumer_0_8 consumer = - new BasicMessageConsumer_0_8(0, conn, queue, "", false, null, testSession, null, 10, 5, false, Session.SESSION_TRANSACTED, false, false); - - assertEquals("Reject behaviour was was not as expected", RejectBehaviour.SERVER, consumer.getRejectBehaviour()); - } - - /** - * Check that when the connection does have a specific value applied that this - * is successfully overridden with another specific value by the consumer. - */ - public void testDestinationRejectBehaviourSpecified() throws Exception - { - final String connUrlString = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672'&rejectbehaviour='server'"; - final AMQConnection conn = new MockAMQConnection(connUrlString); - - final String url = "exchangeClass://exchangeName/Destination/Queue?rejectbehaviour='normal'"; - final AMQBindingURL burl = new AMQBindingURL(url); - final AMQDestination queue = new AMQQueue(burl); - - final TestAMQSession testSession = new TestAMQSession(conn); - final BasicMessageConsumer_0_8 consumer = - new BasicMessageConsumer_0_8(0, conn, queue, "", false, null, testSession, null, 10, 5, false, Session.SESSION_TRANSACTED, false, false); - - assertEquals("Reject behaviour was was not as expected", RejectBehaviour.NORMAL, consumer.getRejectBehaviour()); - } - - /** - * Test that if no value for Reject Behaviour is applied to the Destination, then the value - * from the connection is used and acts as expected. - */ - public void testRejectBehaviourDetectedFromConnection() throws Exception - { - /* - * Check that when the connection does have a specific value applied that this - * is successfully detected by the consumer. - */ - String connUrlString = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672'&rejectbehaviour='normal'"; - AMQConnection conn = new MockAMQConnection(connUrlString); - - String url = "exchangeClass://exchangeName/Destination/Queue"; - AMQBindingURL burl = new AMQBindingURL(url); - AMQDestination queue = new AMQQueue(burl); - - assertNull("Reject behaviour should have been null", queue.getRejectBehaviour()); - - TestAMQSession testSession = new TestAMQSession(conn); - BasicMessageConsumer_0_8 consumer = - new BasicMessageConsumer_0_8(0, conn, queue, "", false, null, testSession, null, 10, 5, false, Session.SESSION_TRANSACTED, false, false); - - assertEquals("Reject behaviour was was not as expected", RejectBehaviour.NORMAL, consumer.getRejectBehaviour()); - } - - - protected RejectBehaviour getRejectBehaviour(AMQDestination destination) - { - return destination.getRejectBehaviour(); - } -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/ConnectionListenerSupport.java b/qpid/java/client/src/test/java/org/apache/qpid/client/ConnectionListenerSupport.java deleted file mode 100644 index fc66e60bc0..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/client/ConnectionListenerSupport.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.client; - -import org.apache.qpid.jms.ConnectionListener; - -public class ConnectionListenerSupport implements ConnectionListener -{ - - @Override - public void bytesSent(long count) - { - } - - @Override - public void bytesReceived(long count) - { - } - - @Override - public boolean preFailover(boolean redirect) - { - return true; - } - - @Override - public boolean preResubscribe() - { - return false; - } - - @Override - public void failoverComplete() - { - } - -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/DispatcherDaemonTest.java b/qpid/java/client/src/test/java/org/apache/qpid/client/DispatcherDaemonTest.java deleted file mode 100644 index b9c4bfc676..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/client/DispatcherDaemonTest.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.client; - -import javax.jms.Session; - -import org.apache.qpid.AMQException; -import org.apache.qpid.configuration.ClientProperties; -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.url.URLSyntaxException; - -public class DispatcherDaemonTest extends QpidTestCase -{ - private AMQSession<?,?> _session; - - public void tearDown() throws Exception - { - super.tearDown(); - if (_session != null && _session.getDispatcherThread() != null) - { - _session.getDispatcherThread().interrupt(); - } - } - - public void testDispatcherIsRunInDaemonThreadWithNoMessageListener() throws Exception - { - _session = createSession(); - _session.startDispatcherIfNecessary(); - assertFalse("Dispatcher thread should be non daemon as qpid.jms.daemon.dispatcher is not set", - _session.getDispatcherThread().isDaemon()); - } - - public void testDispatcherIsRunInDaemonThreadWithConsumerMessageListenerAndDaemonFlagOn() throws Exception - { - setTestSystemProperty(ClientProperties.DAEMON_DISPATCHER, "true"); - _session = createSession(); - _session.startDispatcherIfNecessary(); - assertTrue("Dispatcher thread should be daemon as qpid.jms.daemon.dispatcher is set to true", - _session.getDispatcherThread().isDaemon()); - } - - private AMQSession<?,?> createSession() throws AMQException, URLSyntaxException - { - AMQConnection amqConnection = new MockAMQConnection( - "amqp://guest:guest@client/test?brokerlist='tcp://localhost:1'&maxprefetch='0'"); - - AMQSession_0_8 session = new AMQSession_0_8(amqConnection, 1, true, Session.SESSION_TRANSACTED, 1, 1); - return session; - } - -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/MockAMQConnection.java b/qpid/java/client/src/test/java/org/apache/qpid/client/MockAMQConnection.java deleted file mode 100644 index ceb2a323ca..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/client/MockAMQConnection.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.client; - -import java.io.IOException; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.state.AMQState; -import org.apache.qpid.framing.ProtocolVersion; -import org.apache.qpid.jms.BrokerDetails; -import org.apache.qpid.url.URLSyntaxException; - -public class MockAMQConnection extends AMQConnection -{ - public MockAMQConnection(String broker, String username, String password, String clientName, String virtualHost) - throws AMQException, URLSyntaxException - { - super(broker, username, password, clientName, virtualHost); - } - - public MockAMQConnection(String host, int port, String username, String password, String clientName, String virtualHost) - throws AMQException, URLSyntaxException - { - super(host, port, username, password, clientName, virtualHost); - } - - public MockAMQConnection(String connection) - throws AMQException, URLSyntaxException - { - super(connection); - } - - @Override - public ProtocolVersion makeBrokerConnection(BrokerDetails brokerDetail) throws IOException - { - setConnected(true); - getProtocolHandler().getStateManager().changeState(AMQState.CONNECTION_OPEN); - return null; - } - - public AMQConnectionDelegate getDelegate() - { - return super.getDelegate(); - } - - @Override - public void performConnectionTask(final Runnable task) - { - task.run(); - } -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/handler/CloseWhenNoRouteSettingsHelperTest.java b/qpid/java/client/src/test/java/org/apache/qpid/client/handler/CloseWhenNoRouteSettingsHelperTest.java deleted file mode 100644 index f1d7a76c75..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/client/handler/CloseWhenNoRouteSettingsHelperTest.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.client.handler; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.jms.ConnectionURL; -import org.apache.qpid.properties.ConnectionStartProperties; -import org.apache.qpid.test.utils.QpidTestCase; - -public class CloseWhenNoRouteSettingsHelperTest extends QpidTestCase -{ - private static final String FALSE_STR = Boolean.toString(false); - private static final String TRUE_STR = Boolean.toString(true); - - private final CloseWhenNoRouteSettingsHelper _closeWhenNoRouteSettingsHelper = new CloseWhenNoRouteSettingsHelper(); - - public void testCloseWhenNoRouteNegotiation() - { - test("Nothing should be set if option not in URL", - null, - true, - null); - test("Client should disable broker's enabled option", - FALSE_STR, - true, - false); - test("Client should be able to disable broker's enabled option", - TRUE_STR, - false, - true); - test("Client should not enable option if unsupported by broker", - TRUE_STR, - null, - null); - test("Malformed client option should evaluate to false", - "malformed boolean", - true, - false); - } - - private void test(String message, String urlOption, Boolean serverOption, Boolean expectedClientProperty) - { - ConnectionURL url = mock(ConnectionURL.class); - when(url.getOption(ConnectionURL.OPTIONS_CLOSE_WHEN_NO_ROUTE)).thenReturn(urlOption); - - FieldTable serverProperties = new FieldTable(); - if(serverOption != null) - { - serverProperties.setBoolean(ConnectionStartProperties.QPID_CLOSE_WHEN_NO_ROUTE, serverOption); - } - - FieldTable clientProperties = new FieldTable(); - - _closeWhenNoRouteSettingsHelper.setClientProperties(clientProperties, url, serverProperties); - - assertEquals(message, expectedClientProperty, clientProperties.getBoolean(ConnectionStartProperties.QPID_CLOSE_WHEN_NO_ROUTE)); - } -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/message/AMQMessageDelegate_0_10Test.java b/qpid/java/client/src/test/java/org/apache/qpid/client/message/AMQMessageDelegate_0_10Test.java deleted file mode 100644 index 2edd38ea55..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/client/message/AMQMessageDelegate_0_10Test.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.client.message; - -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; - -import javax.jms.Destination; - -import org.apache.qpid.client.AMQDestination; -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.transport.MessageProperties; -import org.apache.qpid.transport.ReplyTo; - -public class AMQMessageDelegate_0_10Test extends QpidTestCase -{ - - private static final String MAX_SHORT = "maxShort"; - private static final String MIN_SHORT = "minShort"; - private static final String MAX_INT = "maxInt"; - private static final String MIN_INT = "minInt"; - private static final String MAX_LONG = "maxLong"; - private static final String MIN_LONG = "minLong"; - - /** - * Tests that when two messages arrive with the same ReplyTo exchange and routingKey values, - * the cache returns the same Destination object from getJMSReplyTo instead of a new one. - */ - public void testDestinationCache() throws Exception - { - //create a message delegate and retrieve the replyTo Destination - AMQMessageDelegate_0_10 delegate1 = generateMessageDelegateWithReplyTo(); - Destination dest1 = delegate1.getJMSReplyTo(); - - //create a new message delegate with the same details, and retrieve the replyTo Destination - AMQMessageDelegate_0_10 delegate2 = generateMessageDelegateWithReplyTo(); - Destination dest2 = delegate2.getJMSReplyTo(); - - //verify that the destination cache means these are the same Destination object - assertSame("Should have received the same Destination objects", dest1, dest2); - } - - - private AMQMessageDelegate_0_10 generateMessageDelegateWithReplyTo() - { - MessageProperties mesProps = new MessageProperties(); - ReplyTo reply = new ReplyTo("amq.direct", "myReplyQueue"); - mesProps.setReplyTo(reply); - - DeliveryProperties delProps = new DeliveryProperties(); - delProps.setExchange("amq.direct"); - delProps.setRoutingKey("myRequestQueue"); - - AMQMessageDelegate_0_10 delegate = new AMQMessageDelegate_0_10(mesProps,delProps,1L); - return delegate; - } - - public void testMessageProperties() throws Exception - { - MessageProperties msgProps = new MessageProperties(); - - Map<String, Object> appHeaders = new HashMap<String, Object>(); - appHeaders.put(MAX_SHORT, String.valueOf(Short.MAX_VALUE)); - appHeaders.put(MIN_SHORT, String.valueOf(Short.MIN_VALUE)); - appHeaders.put(MAX_INT, String.valueOf(Integer.MAX_VALUE)); - appHeaders.put(MIN_INT, String.valueOf(Integer.MIN_VALUE)); - appHeaders.put(MAX_LONG, String.valueOf(Long.MAX_VALUE)); - appHeaders.put(MIN_LONG, String.valueOf(Long.MIN_VALUE)); - - msgProps.setApplicationHeaders(appHeaders); - - AMQMessageDelegate_0_10 delegate = new AMQMessageDelegate_0_10(msgProps,new DeliveryProperties(),1L); - - assertEquals("Max long value not retrieved successfully", Long.MAX_VALUE, delegate.getLongProperty(MAX_LONG)); - assertEquals("Min long value not retrieved successfully", Long.MIN_VALUE, delegate.getLongProperty(MIN_LONG)); - assertEquals("Max int value not retrieved successfully as long", (long) Integer.MAX_VALUE, delegate.getLongProperty(MAX_INT)); - assertEquals("Min int value not retrieved successfully as long", (long) Integer.MIN_VALUE, delegate.getLongProperty(MIN_INT)); - assertEquals("Max short value not retrieved successfully as long", (long) Short.MAX_VALUE, delegate.getLongProperty(MAX_SHORT)); - assertEquals("Min short value not retrieved successfully as long", (long) Short.MIN_VALUE, delegate.getLongProperty(MIN_SHORT)); - - assertEquals("Max int value not retrieved successfully", Integer.MAX_VALUE, delegate.getIntProperty(MAX_INT)); - assertEquals("Min int value not retrieved successfully", Integer.MIN_VALUE, delegate.getIntProperty(MIN_INT)); - assertEquals("Max short value not retrieved successfully as int", (int) Short.MAX_VALUE, delegate.getIntProperty(MAX_SHORT)); - assertEquals("Min short value not retrieved successfully as int", (int) Short.MIN_VALUE, delegate.getIntProperty(MIN_SHORT)); - - assertEquals("Max short value not retrieved successfully", Short.MAX_VALUE, delegate.getShortProperty(MAX_SHORT)); - assertEquals("Min short value not retrieved successfully", Short.MIN_VALUE, delegate.getShortProperty(MIN_SHORT)); - } - - // See QPID_3838 - public void testJMSComplainceForQpidProviderProperties() throws Exception - { - MessageProperties msgProps = new MessageProperties(); - Map<String, Object> appHeaders = new HashMap<String, Object>(); - appHeaders.put(QpidMessageProperties.QPID_SUBJECT, "Hello"); - msgProps.setApplicationHeaders(appHeaders); - - System.setProperty("strict-jms", "true"); - try - { - AMQMessageDelegate_0_10 delegate = new AMQMessageDelegate_0_10(AMQDestination.DestSyntax.ADDR,msgProps,new DeliveryProperties(),1L); - - boolean propFound = false; - for (Enumeration props = delegate.getPropertyNames(); props.hasMoreElements();) - { - String key = (String)props.nextElement(); - if (key.equals(QpidMessageProperties.QPID_SUBJECT_JMS_PROPERTY)) - { - propFound = true; - } - } - assertTrue("qpid.subject was not prefixed with 'JMS_' as expected",propFound); - assertEquals("qpid.subject should still return the correct value","Hello",delegate.getStringProperty(QpidMessageProperties.QPID_SUBJECT)); - } - finally - { - System.setProperty("strict-jms", "false"); - } - } -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/message/AMQPEncodedListMessageUnitTest.java b/qpid/java/client/src/test/java/org/apache/qpid/client/message/AMQPEncodedListMessageUnitTest.java deleted file mode 100644 index e131ab3dd2..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/client/message/AMQPEncodedListMessageUnitTest.java +++ /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. - * - */ -package org.apache.qpid.client.message; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import javax.jms.MessageFormatException; - -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.transport.codec.BBEncoder; - -public class AMQPEncodedListMessageUnitTest extends QpidTestCase -{ - - Map<String,String> _map = new HashMap<String,String>(); - List<Object> _list = new ArrayList<Object>(); - UUID _uuid = UUID.randomUUID(); - - @Override - public void setUp() throws Exception - { - super.setUp(); - _map.put("Key1","String1"); - _map.put("Key2","String2"); - _map.put("Key3","String3"); - - _list.add(1); - _list.add(2); - _list.add(3); - } - - /** - * Test whether we accept the correct types while rejecting invalid types. - */ - public void testAddObject() throws Exception - { - AMQPEncodedListMessage m = new AMQPEncodedListMessage(AMQMessageDelegateFactory.FACTORY_0_10); - m.add(true); - m.add((byte)256); - m.add(Short.MAX_VALUE); - m.add(Integer.MAX_VALUE); - m.add(Long.MAX_VALUE); - m.add(10.22); - m.add("Msg"); - m.add("Msg".getBytes()); - m.add(_list); - m.add(_map); - m.add(_uuid); - - try - { - m.add(new Object()); - fail("Validation for element type failed"); - } - catch (MessageFormatException e) - { - } - } - - public void testListBehaviorForIncommingMsg() throws Exception - { - BBEncoder encoder = new BBEncoder(1024); - encoder.writeList(_list); - AMQPEncodedListMessage m = new AMQPEncodedListMessage(new AMQMessageDelegate_0_10(),encoder.segment()); - - assertTrue("contains(Object) method did not return true as expected",m.contains(1)); - assertFalse("contains(Object) method did not return false as expected",m.contains(5)); - assertEquals("get(index) method returned incorrect value",((Integer)m.get(1)).intValue(),2); - assertEquals("indexOf(Object) method returned incorrect index",m.indexOf(2),1); - try - { - m.get(10); - } - catch (MessageFormatException e) - { - assertTrue("Incorrect exception type. Expected IndexOutOfBoundsException", e.getCause() instanceof IndexOutOfBoundsException); - } - } - - public void testStreamMessageInterfaceForIncommingMsg() throws Exception - { - BBEncoder encoder = new BBEncoder(1024); - encoder.writeList(getList()); - AMQPEncodedListMessage m = new AMQPEncodedListMessage(new AMQMessageDelegate_0_10(),encoder.segment()); - - assertEquals(true,m.readBoolean()); - assertEquals((byte)256,m.readByte()); - assertEquals(Short.MAX_VALUE,m.readShort()); - assertEquals(Integer.MAX_VALUE,m.readInt()); - assertEquals(Long.MAX_VALUE,m.readLong()); - assertEquals(10.22,m.readDouble()); - assertEquals("Msg",m.readString()); - assertEquals(_list,(List)m.readObject()); - assertEquals(_map,(Map)m.readObject()); - assertEquals(_uuid,(UUID)m.readObject()); - } - - public void testMapMessageInterfaceForIncommingMsg() throws Exception - { - BBEncoder encoder = new BBEncoder(1024); - encoder.writeList(getList()); - AMQPEncodedListMessage m = new AMQPEncodedListMessage(new AMQMessageDelegate_0_10(),encoder.segment()); - - assertEquals(true,m.getBoolean("0")); - assertEquals((byte)256,m.getByte("1")); - assertEquals(Short.MAX_VALUE,m.getShort("2")); - assertEquals(Integer.MAX_VALUE,m.getInt("3")); - assertEquals(Long.MAX_VALUE,m.getLong("4")); - assertEquals(10.22,m.getDouble("5")); - assertEquals("Msg",m.getString("6")); - assertEquals(_list,(List)m.getObject("7")); - assertEquals(_map,(Map)m.getObject("8")); - assertEquals(_uuid,(UUID)m.getObject("9")); - } - - public List<Object> getList() - { - List<Object> myList = new ArrayList<Object>(); - myList.add(true); - myList.add((byte)256); - myList.add(Short.MAX_VALUE); - myList.add(Integer.MAX_VALUE); - myList.add(Long.MAX_VALUE); - myList.add(10.22); - myList.add("Msg"); - myList.add(_list); - myList.add(_map); - myList.add(_uuid); - return myList; - } -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/message/AbstractJMSMessageTest.java b/qpid/java/client/src/test/java/org/apache/qpid/client/message/AbstractJMSMessageTest.java deleted file mode 100644 index c535fdd705..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/client/message/AbstractJMSMessageTest.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.client.message; - - -import junit.framework.TestCase; - -import javax.jms.JMSException; - -public class AbstractJMSMessageTest extends TestCase -{ - - public void testSetNullJMSReplyTo08() throws JMSException - { - JMSTextMessage message = new JMSTextMessage(AMQMessageDelegateFactory.FACTORY_0_8); - try - { - message.setJMSReplyTo(null); - } - catch (IllegalArgumentException e) - { - fail("Null destination should be allowed"); - } - } - - public void testSetNullJMSReplyTo10() throws JMSException - { - JMSTextMessage message = new JMSTextMessage(AMQMessageDelegateFactory.FACTORY_0_10); - try - { - message.setJMSReplyTo(null); - } - catch (IllegalArgumentException e) - { - fail("Null destination should be allowed"); - } - } - -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/message/TestMessageHelper.java b/qpid/java/client/src/test/java/org/apache/qpid/client/message/TestMessageHelper.java deleted file mode 100644 index b5c31e7c5e..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/client/message/TestMessageHelper.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.client.message; - -import javax.jms.JMSException; - -public class TestMessageHelper -{ - public static JMSTextMessage newJMSTextMessage() throws JMSException - { - return new JMSTextMessage(AMQMessageDelegateFactory.FACTORY_0_8); - } - - public static JMSBytesMessage newJMSBytesMessage() throws JMSException - { - return new JMSBytesMessage(AMQMessageDelegateFactory.FACTORY_0_8); - } - - public static JMSMapMessage newJMSMapMessage() throws JMSException - { - return new JMSMapMessage(AMQMessageDelegateFactory.FACTORY_0_8); - } - - public static JMSStreamMessage newJMSStreamMessage() - { - return new JMSStreamMessage(AMQMessageDelegateFactory.FACTORY_0_8); - } - - public static JMSObjectMessage newJMSObjectMessage() - { - return new JMSObjectMessage(AMQMessageDelegateFactory.FACTORY_0_8); - } -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/messaging/address/AddressHelperTest.java b/qpid/java/client/src/test/java/org/apache/qpid/client/messaging/address/AddressHelperTest.java deleted file mode 100644 index 7401168978..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/client/messaging/address/AddressHelperTest.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.client.messaging.address; - -import org.apache.qpid.client.AMQDestination; -import org.apache.qpid.client.AMQDestination.AddressOption; -import org.apache.qpid.client.AMQDestination.Binding; -import org.apache.qpid.client.messaging.address.Link.Reliability; -import org.apache.qpid.messaging.Address; -import org.apache.qpid.test.utils.QpidTestCase; - -public class AddressHelperTest extends QpidTestCase -{ - public void testAddressOptions() throws Exception - { - Address addr = Address.parse("queue/test;{create:sender, assert:always, delete:receiver, mode:browse}"); - AddressHelper helper = new AddressHelper(addr); - assertEquals(AddressOption.SENDER,AddressOption.getOption(helper.getCreate())); - assertEquals(AddressOption.ALWAYS,AddressOption.getOption(helper.getAssert())); - assertEquals(AddressOption.RECEIVER,AddressOption.getOption(helper.getDelete())); - assertTrue("'mode' option wasn't read properly",helper.isBrowseOnly()); - } - - public void testNodeProperties() throws Exception - { - Address addr = Address.parse("my-queue;{" + - "node: " + - "{" + - "type: queue ," + - "durable: true ," + - "x-declare: " + - "{" + - "exclusive: true," + - "auto-delete: true," + - "alternate-exchange: 'amq.fanout'," + - "arguments: {" + - "'qpid.max_size': 1000," + - "'qpid.max_count': 100" + - "}" + - "}, " + - "x-bindings: [{exchange : 'amq.direct', queue:my-queue, key : test}, " + - "{exchange : 'amq.fanout', queue:my-queue}," + - "{exchange: 'amq.match', queue:my-queue, arguments: {x-match: any, dep: sales, loc: CA}}," + - "{exchange : 'amq.topic',queue:my-queue, key : 'a.#'}" + - "]" + - - "}" + - "}"); - AddressHelper helper = new AddressHelper(addr); - Node node = helper.getNode(); - assertEquals("'type' property wasn't read properly",AMQDestination.QUEUE_TYPE,helper.getNodeType()); - assertTrue("'durable' property wasn't read properly",node.isDurable()); - assertTrue("'auto-delete' property wasn't read properly",node.isAutoDelete()); - assertTrue("'exclusive' property wasn't read properly",node.isExclusive()); - assertEquals("'alternate-exchange' property wasn't read properly","amq.fanout",node.getAlternateExchange()); - assertEquals("'arguments' in 'x-declare' property wasn't read properly",2,node.getDeclareArgs().size()); - assertEquals("'bindings' property wasn't read properly",4,node.getBindings().size()); - for (Binding binding: node.getBindings()) - { - assertTrue("property 'exchange' in bindings wasn't read properly",binding.getExchange().startsWith("amq.")); - assertEquals("property 'queue' in bindings wasn't read properly","my-queue",binding.getQueue()); - if (binding.getExchange().equals("amq.direct")) - { - assertEquals("'key' property in bindings wasn't read properly","test",binding.getBindingKey()); - } - if (binding.getExchange().equals("amq.match")) - { - assertEquals("'arguments' property in bindings wasn't read properly",3,binding.getArgs().size()); - } - } - } - - public void testLinkProperties() throws Exception - { - Address addr = Address.parse("my-queue;{" + - "link: " + - "{" + - "name: my-queue ," + - "durable: true ," + - "reliability: at-least-once," + - "capacity: {source:10, target:15}," + - "x-declare: " + - "{" + - "exclusive: true," + - "auto-delete: true," + - "alternate-exchange: 'amq.fanout'," + - "arguments: {" + - "'qpid.max_size': 1000," + - "'qpid.max_count': 100" + - "}" + - "}, " + - "x-bindings: [{exchange : 'amq.direct', queue:my-queue, key : test}, " + - "{exchange : 'amq.fanout', queue:my-queue}," + - "{exchange: 'amq.match', queue:my-queue, arguments: {x-match: any, dep: sales, loc: CA}}," + - "{exchange : 'amq.topic',queue:my-queue, key : 'a.#'}" + - "]," + - "x-subscribes:{exclusive: true, arguments: {a:b,x:y}}" + - "}" + - "}"); - - AddressHelper helper = new AddressHelper(addr); - Link link = helper.getLink(); - assertEquals("'name' property wasn't read properly","my-queue",link.getName()); - assertTrue("'durable' property wasn't read properly",link.isDurable()); - assertEquals("'reliability' property wasn't read properly",Reliability.AT_LEAST_ONCE,link.getReliability()); - assertTrue("'auto-delete' property in 'x-declare' wasn't read properly",link.getSubscriptionQueue().isAutoDelete()); - assertTrue("'exclusive' property in 'x-declare' wasn't read properly",link.getSubscriptionQueue().isExclusive()); - assertEquals("'alternate-exchange' property in 'x-declare' wasn't read properly","amq.fanout",link.getSubscriptionQueue().getAlternateExchange()); - assertEquals("'arguments' in 'x-declare' property wasn't read properly",2,link.getSubscriptionQueue().getDeclareArgs().size()); - assertEquals("'bindings' property wasn't read properly",4,link.getBindings().size()); - for (Binding binding: link.getBindings()) - { - assertTrue("property 'exchange' in bindings wasn't read properly",binding.getExchange().startsWith("amq.")); - assertEquals("property 'queue' in bindings wasn't read properly","my-queue",binding.getQueue()); - if (binding.getExchange().equals("amq.direct")) - { - assertEquals("'key' property in bindings wasn't read properly","test",binding.getBindingKey()); - } - if (binding.getExchange().equals("amq.match")) - { - assertEquals("'arguments' property in bindings wasn't read properly",3,binding.getArgs().size()); - } - } - assertTrue("'exclusive' property in 'x-subscribe' wasn't read properly",link.getSubscription().isExclusive()); - assertEquals("'arguments' in 'x-subscribe' property wasn't read properly",2,link.getSubscription().getArgs().size()); - } - -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/protocol/AMQProtocolHandlerTest.java b/qpid/java/client/src/test/java/org/apache/qpid/client/protocol/AMQProtocolHandlerTest.java deleted file mode 100644 index 61e5247ead..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/client/protocol/AMQProtocolHandlerTest.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.client.protocol; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import junit.framework.TestCase; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.AMQAuthenticationException; -import org.apache.qpid.client.MockAMQConnection; -import org.apache.qpid.client.state.AMQState; -import org.apache.qpid.client.transport.TestNetworkConnection; -import org.apache.qpid.framing.AMQBody; -import org.apache.qpid.framing.AMQFrame; -import org.apache.qpid.framing.AMQMethodBody; -import org.apache.qpid.framing.BasicRecoverSyncOkBody; -import org.apache.qpid.framing.ProtocolVersion; -import org.apache.qpid.protocol.AMQConstant; - -/** - * This is a test address QPID-1431 where frame listeners would fail to be notified of an incomming exception. - * - * Currently we do checks at the Session level to ensure that the connection/session are open. However, it is possible - * for the connection to close AFTER this check has been performed. - * - * Performing a similar check at the frameListener level in AMQProtocolHandler makes most sence as this will prevent - * listening when there can be no returning frames. - * - * With the correction in place it also means that the new listener will either make it on to the list for notification - * or it will be notified of any existing exception due to the connection being closed. - * - * There may still be an issue in this space if the client utilises a second thread to close the session as there will - * be no exception set to throw and so the wait will occur. That said when the session is closed the framelisteners - * should be notified. Not sure this is tested. - */ -public class AMQProtocolHandlerTest extends TestCase -{ - private static final Logger _logger = LoggerFactory.getLogger(AMQProtocolHandlerTest.class); - - // The handler to test - private AMQProtocolHandler _handler; - - // A frame to block upon whilst waiting the exception - private AMQFrame _blockFrame; - - // Latch to know when the listener receives an exception - private CountDownLatch _handleCountDown; - // The listener that will receive an exception - private BlockToAccessFrameListener _listener; - - @Override - public void setUp() throws Exception - { - //Create a new ProtocolHandler with a fake connection. - _handler = new AMQProtocolHandler(new MockAMQConnection("amqp://guest:guest@client/test?brokerlist='tcp://localhost:1'")); - _handler.setNetworkConnection(new TestNetworkConnection()); - AMQBody body = new BasicRecoverSyncOkBody(ProtocolVersion.v8_0); - _blockFrame = new AMQFrame(0, body); - - _handleCountDown = new CountDownLatch(1); - - _logger.info("Creating _Listener that should also receive the thrown exception."); - _listener = new BlockToAccessFrameListener(1); - } - - /** - * There are two paths based on the type of exception thrown. - * - * This tests that when an AMQException is thrown we get the same type of AMQException back with the real exception - * wrapped as the cause. - * - * @throws InterruptedException - if we are unable to wait for the test signals - */ - public void testFrameListenerUpdateWithAMQException() throws InterruptedException - { - AMQException trigger = new AMQAuthenticationException(AMQConstant.ACCESS_REFUSED, - "AMQPHTest", new RuntimeException()); - - performWithException(trigger); - - - AMQException receivedException = (AMQException) _listener.getReceivedException(); - - assertEquals("Return exception was not the expected type", - AMQAuthenticationException.class, receivedException.getClass()); - - assertEquals("The _Listener did not receive the correct error code", - trigger.getErrorCode(), receivedException.getErrorCode()); - } - - /** - * There are two paths based on the type of exception thrown. - * - * This tests that when a generic Exception is thrown we get the exception back wrapped in a AMQException - * as the cause. - * @throws InterruptedException - if we are unable to wait for the test signals - */ - public void testFrameListenerUpdateWithException() throws InterruptedException - { - - Exception trigger = new Exception(new RuntimeException()); - - performWithException(trigger); - - assertEquals("The _Listener did not receive the correct error code", - AMQConstant.INTERNAL_ERROR, ((AMQException)_listener.getReceivedException()).getErrorCode()); - } - - /** - * This is the main test method for both test cases. - * - * What occurs is that we create a new thread that will block (<30s[DEFAULT]) for a frame or exception to occur . - * - * We use a CountDownLatch to ensure that the new thread is running before we then yield and sleep to help ensure - * the new thread has entered the synchronized block in the writeCommandFrameAndWaitForReply. - * - * We can then ack like an the incomming exception handler in (ConnectionCloseMethodHandler). - * - * We fire the error to the stateManager, which in this case will recored the error as there are no state listeners. - * - * We then set the connection to be closed, as we would normally close the socket at this point. - * - * Then fire the exception in to any frameListeners. - * - * The blocked listener (created above) when receiving the error simulates the user by creating a new request to - * block for a frame. - * - * This request should fail. Prior to the fix this will fail with a NPE as we are attempting to use a null listener - * in the writeCommand.... call L:268. - * - * This highlights that the listener would be added dispite there being a pending error state that the listener will - * miss as it is not currently part of the _frameListeners set that is being notified by the iterator. - * - * The method waits to ensure that an exception is received before returning. - * - * The calling methods validate that exception that was received based on the one they sent in. - * - * @param trigger The exception to throw through the handler - */ - private void performWithException(Exception trigger) throws InterruptedException - { - - final CountDownLatch callingWriteCommand = new CountDownLatch(1); - - //Set an initial listener that will allow us to create a new blocking method - new Thread(new Runnable() - { - public void run() - { - - try - { - - _logger.info("At initial block, signalling to fire new exception"); - callingWriteCommand.countDown(); - - _handler.writeCommandFrameAndWaitForReply(_blockFrame, _listener); - } - catch (Exception e) - { - _logger.error(e.getMessage(), e); - fail(e.getMessage()); - } - } - }).start(); - - _logger.info("Waiting for 'initial block' to start "); - if (!callingWriteCommand.await(1000, TimeUnit.MILLISECONDS)) - { - fail("Failed to start new thread to block for frame"); - } - - // Do what we can to ensure that this thread does not continue before the above thread has hit the synchronized - // block in the writeCommandFrameAndWaitForReply - Thread.yield(); - Thread.sleep(1000); - - _logger.info("Firing Erorr through state manager. There should be not state waiters here."); - _handler.getStateManager().error(trigger); - - _logger.info("Setting state to be CONNECTION_CLOSED."); - - _handler.getStateManager().changeState(AMQState.CONNECTION_CLOSED); - - _logger.info("Firing exception"); - _handler.propagateExceptionToFrameListeners(trigger); - - _logger.info("Awaiting notifcation from handler that exception arrived."); - - if (!_handleCountDown.await(2000, TimeUnit.MILLISECONDS)) - { - fail("Failed to handle exception and timeout has not occured"); - } - - - assertNotNull("The _Listener did not receive the exception", _listener.getReceivedException()); - - assertTrue("Received exception not an AMQException", - _listener.getReceivedException() instanceof AMQException); - - AMQException receivedException = (AMQException) _listener.getReceivedException(); - - assertTrue("The _Listener did not receive the correct message", - receivedException.getMessage().startsWith(trigger.getMessage())); - - - assertEquals("The _Listener did not receive the correct cause", - trigger, receivedException.getCause()); - - assertEquals("The _Listener did not receive the correct sub cause", - trigger.getCause(), receivedException.getCause().getCause()); - - } - - class BlockToAccessFrameListener extends BlockingMethodFrameListener - { - private Exception _receivedException = null; - - /** - * Creates a new method listener, that filters incoming method to just those that match the specified channel id. - * - * @param channelId The channel id to filter incoming methods with. - */ - public BlockToAccessFrameListener(int channelId) - { - super(channelId); - _logger.info("Creating a listener:" + this); - } - - public boolean processMethod(int channelId, AMQMethodBody frame) - { - return true; - } - - @Override - public void error(Exception e) - { - _logger.info("Exception(" + e + ") Received by:" + this); - // Create a new Thread to start the blocking registration. - new Thread(new Runnable() - { - - public void run() - { - //Set an initial listener that will allow us to create a new blocking method - try - { - _handler.writeCommandFrameAndWaitForReply(_blockFrame, null, 2000L); - _logger.info("listener(" + this + ") Wait completed"); - } - catch (Exception e) - { - _logger.info("listener(" + this + ") threw exception:" + e.getMessage()); - _receivedException = e; - } - - _logger.info("listener(" + this + ") completed"); - _handleCountDown.countDown(); - } - }).start(); - } - - public Exception getReceivedException() - { - return _receivedException; - } - } - -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/security/CallbackHandlerRegistryTest.java b/qpid/java/client/src/test/java/org/apache/qpid/client/security/CallbackHandlerRegistryTest.java deleted file mode 100644 index b451ad630f..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/client/security/CallbackHandlerRegistryTest.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.security; - -import org.apache.qpid.jms.ConnectionURL; -import org.apache.qpid.test.utils.QpidTestCase; - -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.callback.UnsupportedCallbackException; -import java.io.IOException; -import java.util.Properties; - - -/** - * Tests the ability of {@link CallbackHandlerRegistry} to correctly parse - * the properties describing the available callback handlers. Ensures also - * that it is able to select the mechanism and create an implementation - * given a variety of starting conditions. - * - */ -public class CallbackHandlerRegistryTest extends QpidTestCase -{ - private CallbackHandlerRegistry _registry; // Object under test - - public void testCreateHandlerSuccess() - { - final Properties props = new Properties(); - props.put("TESTA.1", TestACallbackHandler.class.getName()); - - _registry = new CallbackHandlerRegistry(props); - assertEquals(1,_registry.getMechanisms().size()); - - final CallbackHandler handler = _registry.createCallbackHandler("TESTA"); - assertTrue(handler instanceof TestACallbackHandler); - } - - public void testCreateHandlerForUnknownMechanismName() - { - final Properties props = new Properties(); - props.put("TEST1.1", TestACallbackHandler.class.getName()); - - _registry = new CallbackHandlerRegistry(props); - - try - { - _registry.createCallbackHandler("NOTFOUND"); - fail("Exception not thrown"); - } - catch (IllegalArgumentException iae) - { - // PASS - } - } - - public void testSelectMechanism() - { - final Properties props = new Properties(); - props.put("TESTA.1", TestACallbackHandler.class.getName()); - props.put("TESTB.2", TestBCallbackHandler.class.getName()); - - _registry = new CallbackHandlerRegistry(props); - assertEquals(2,_registry.getMechanisms().size()); - - final String selectedMechanism = _registry.selectMechanism("TESTA"); - assertEquals("TESTA", selectedMechanism); - } - - public void testSelectReturnsFirstMutallyAvailableMechanism() - { - final Properties props = new Properties(); - props.put("TESTA.1", TestACallbackHandler.class.getName()); - props.put("TESTB.2", TestBCallbackHandler.class.getName()); - - _registry = new CallbackHandlerRegistry(props); - - final String selectedMechanism = _registry.selectMechanism("TESTD TESTB TESTA"); - // TESTA should be returned as it is higher than TESTB in the properties file. - assertEquals("Selected mechanism should respect the ordinal", "TESTA", selectedMechanism); - } - - public void testRestrictedSelectReturnsMechanismFromRestrictedList() - { - final Properties props = new Properties(); - props.put("TESTA.1", TestACallbackHandler.class.getName()); - props.put("TESTB.2", TestBCallbackHandler.class.getName()); - props.put("TESTC.3", TestCCallbackHandler.class.getName()); - - _registry = new CallbackHandlerRegistry(props); - - final String selectedMechanism = _registry.selectMechanism("TESTC TESTB TESTA", "TESTB TESTC"); - // TESTB should be returned as client has restricted the mechanism list to TESTB and TESTC - assertEquals("Selected mechanism should respect the ordinal and be limitted by restricted list","TESTB", selectedMechanism); - } - - public void testOldPropertyFormatRejected() - { - final Properties props = new Properties(); - props.put("CallbackHandler.TESTA", TestACallbackHandler.class.getName()); - - try - { - new CallbackHandlerRegistry(props); - fail("exception not thrown"); - } - catch(IllegalArgumentException iae) - { - // PASS - } - } - - public void testPropertyWithNonnumericalOrdinal() - { - final Properties props = new Properties(); - props.put("TESTA.z", TestACallbackHandler.class.getName()); - try - { - new CallbackHandlerRegistry(props); - fail("exception not thrown"); - } - catch(IllegalArgumentException iae) - { - // PASS - } - } - - public void testUnexpectedCallbackImplementationsIgnored() - { - final Properties props = new Properties(); - props.put("TESTA.1", TestACallbackHandler.class.getName()); - props.put("TESTB.2", "NotFound"); - props.put("TESTC.3", "java.lang.String"); - - _registry = new CallbackHandlerRegistry(props); - - assertEquals(1,_registry.getMechanisms().size()); - } - - static class TestACallbackHandler extends TestCallbackHandler - { - } - - static class TestBCallbackHandler extends TestCallbackHandler - { - } - - static class TestCCallbackHandler extends TestCallbackHandler - { - } - - static abstract class TestCallbackHandler implements AMQCallbackHandler - { - @Override - public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException - { - throw new UnsupportedOperationException(); - } - - @Override - public void initialise(ConnectionURL connectionURL) - { - throw new UnsupportedOperationException(); - } - } - -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/security/DynamicSaslRegistrarTest.java b/qpid/java/client/src/test/java/org/apache/qpid/client/security/DynamicSaslRegistrarTest.java deleted file mode 100644 index 4281984212..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/client/security/DynamicSaslRegistrarTest.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.client.security; - -import java.io.File; -import java.security.Provider; -import java.security.Security; - -import org.apache.qpid.client.security.DynamicSaslRegistrar.ProviderRegistrationResult; -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.test.utils.TestFileUtils; - -public class DynamicSaslRegistrarTest extends QpidTestCase -{ - private Provider _registeredProvider; - - public void setUp() throws Exception - { - super.setUp(); - - //If the client provider is already registered, remove it for the duration of the test - _registeredProvider = DynamicSaslRegistrar.findProvider(JCAProvider.QPID_CLIENT_SASL_PROVIDER_NAME); - if (_registeredProvider != null) - { - Security.removeProvider(JCAProvider.QPID_CLIENT_SASL_PROVIDER_NAME); - } - } - - public void tearDown() throws Exception - { - //Remove any provider left behind by the test. - Security.removeProvider(JCAProvider.QPID_CLIENT_SASL_PROVIDER_NAME); - try - { - //If the client provider was already registered before the test, restore it. - if (_registeredProvider != null) - { - Security.insertProviderAt(_registeredProvider, 1); - } - } - finally - { - super.tearDown(); - } - } - - public void testRegisterDefaultProvider() - { - assertNull("Provider should not yet be registered", DynamicSaslRegistrar.findProvider(JCAProvider.QPID_CLIENT_SASL_PROVIDER_NAME)); - - ProviderRegistrationResult firstRegistrationResult = DynamicSaslRegistrar.registerSaslProviders(); - assertEquals("Unexpected registration result", ProviderRegistrationResult.SUCCEEDED, firstRegistrationResult); - assertNotNull("Providers should now be registered", DynamicSaslRegistrar.findProvider(JCAProvider.QPID_CLIENT_SASL_PROVIDER_NAME)); - } - - public void testRegisterDefaultProviderTwice() - { - assertNull("Provider should not yet be registered", DynamicSaslRegistrar.findProvider(JCAProvider.QPID_CLIENT_SASL_PROVIDER_NAME)); - - DynamicSaslRegistrar.registerSaslProviders(); - assertNotNull("Providers should now be registered", DynamicSaslRegistrar.findProvider(JCAProvider.QPID_CLIENT_SASL_PROVIDER_NAME)); - - ProviderRegistrationResult result = DynamicSaslRegistrar.registerSaslProviders(); - assertEquals("Unexpected registration result when trying to re-register", ProviderRegistrationResult.EQUAL_ALREADY_REGISTERED, result); - assertNotNull("Providers should still be registered", DynamicSaslRegistrar.findProvider(JCAProvider.QPID_CLIENT_SASL_PROVIDER_NAME)); - } - - @SuppressWarnings("serial") - public void testRegisterDefaultProviderWhenAnotherIsAlreadyPresentWithDifferentFactories() - { - assertNull("Provider should not be registered", DynamicSaslRegistrar.findProvider(JCAProvider.QPID_CLIENT_SASL_PROVIDER_NAME)); - - //Add a test provider with the same name, version, info as the default client provider, but with different factory properties (none). - Provider testProvider = new Provider(JCAProvider.QPID_CLIENT_SASL_PROVIDER_NAME, - JCAProvider.QPID_CLIENT_SASL_PROVIDER_VERSION, - JCAProvider.QPID_CLIENT_SASL_PROVIDER_INFO){}; - Security.addProvider(testProvider); - assertSame("Test provider should be registered", testProvider, DynamicSaslRegistrar.findProvider(JCAProvider.QPID_CLIENT_SASL_PROVIDER_NAME)); - - //Try to register the default provider now that another with the same name etc (but different factories) - //is already registered, expect it not to be registered as a result. - ProviderRegistrationResult result = DynamicSaslRegistrar.registerSaslProviders(); - assertEquals("Unexpected registration result", ProviderRegistrationResult.DIFFERENT_ALREADY_REGISTERED, result); - - //Verify the test provider is still registered - assertSame("Test provider should still be registered", testProvider, DynamicSaslRegistrar.findProvider(JCAProvider.QPID_CLIENT_SASL_PROVIDER_NAME)); - } - - public void testRegisterWithNoFactories() - { - File emptyTempFile = TestFileUtils.createTempFile(this); - - assertNull("Provider should not be registered", DynamicSaslRegistrar.findProvider(JCAProvider.QPID_CLIENT_SASL_PROVIDER_NAME)); - - //Adjust the location of the properties file to point at an empty file, so no factories are found to register. - setTestSystemProperty("amq.dynamicsaslregistrar.properties", emptyTempFile.getPath()); - - //Try to register the default provider, expect it it not to be registered because there were no factories. - ProviderRegistrationResult result = DynamicSaslRegistrar.registerSaslProviders(); - assertEquals("Unexpected registration result", ProviderRegistrationResult.NO_SASL_FACTORIES, result); - - assertNull("Provider should not be registered", DynamicSaslRegistrar.findProvider(JCAProvider.QPID_CLIENT_SASL_PROVIDER_NAME)); - } - - public void testRegisterWithMissingFileGetsDefault() - { - //Create a temp file and then delete it, such that we get a path which doesn't exist - File tempFile = TestFileUtils.createTempFile(this); - assertTrue("Failed to delete file", tempFile.delete()); - - assertNull("Provider should not be registered", DynamicSaslRegistrar.findProvider(JCAProvider.QPID_CLIENT_SASL_PROVIDER_NAME)); - - //Adjust the location of the properties file to point at non-existent file. - setTestSystemProperty("amq.dynamicsaslregistrar.properties", tempFile.getPath()); - - //Try to register the default provider, expect it to fall back to the default in the jar and succeed. - ProviderRegistrationResult result = DynamicSaslRegistrar.registerSaslProviders(); - assertEquals("Unexpected registration result", ProviderRegistrationResult.SUCCEEDED, result); - - assertNotNull("Provider should be registered", DynamicSaslRegistrar.findProvider(JCAProvider.QPID_CLIENT_SASL_PROVIDER_NAME)); - } -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/security/UsernameHashedPasswordCallbackHandlerTest.java b/qpid/java/client/src/test/java/org/apache/qpid/client/security/UsernameHashedPasswordCallbackHandlerTest.java deleted file mode 100644 index 290ef7420a..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/client/security/UsernameHashedPasswordCallbackHandlerTest.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.client.security; - -import junit.framework.TestCase; - -import org.apache.qpid.client.AMQConnectionURL; - -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.NameCallback; -import javax.security.auth.callback.PasswordCallback; -import java.security.MessageDigest; -import java.util.Arrays; - -/** - * Unit tests for the UsernameHashPasswordCallbackHandler. This callback handler is - * used by the CRAM-MD5-HASHED SASL mechanism. - * - */ -public class UsernameHashedPasswordCallbackHandlerTest extends TestCase -{ - private AMQCallbackHandler _callbackHandler = new UsernameHashedPasswordCallbackHandler(); // Class under test - private static final String PROMPT_UNUSED = "unused"; - - @Override - protected void setUp() throws Exception - { - super.setUp(); - - final String url = "amqp://username:password@client/test?brokerlist='tcp://localhost:1'"; - _callbackHandler.initialise(new AMQConnectionURL(url)); - } - - /** - * Tests that the callback handler can correctly retrieve the username from the connection url. - */ - public void testNameCallback() throws Exception - { - final String expectedName = "username"; - NameCallback nameCallback = new NameCallback(PROMPT_UNUSED); - - assertNull("Unexpected name before test", nameCallback.getName()); - _callbackHandler.handle(new Callback[] {nameCallback}); - assertEquals("Unexpected name", expectedName, nameCallback.getName()); - } - - /** - * Tests that the callback handler can correctly retrieve the password from the connection url - * and calculate a MD5. - */ - public void testDigestedPasswordCallback() throws Exception - { - final char[] expectedPasswordDigested = getHashPassword("password"); - - PasswordCallback passwordCallback = new PasswordCallback(PROMPT_UNUSED, false); - assertNull("Unexpected password before test", passwordCallback.getPassword()); - _callbackHandler.handle(new Callback[] {passwordCallback}); - assertTrue("Unexpected password", Arrays.equals(expectedPasswordDigested, passwordCallback.getPassword())); - } - - private char[] getHashPassword(final String password) throws Exception - { - MessageDigest md5Digester = MessageDigest.getInstance("MD5"); - final byte[] digest = md5Digester.digest(password.getBytes("UTF-8")); - - char[] hash = new char[digest.length]; - - int index = 0; - for (byte b : digest) - { - hash[index++] = (char) b; - } - - return hash; - } -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/security/UsernamePasswordCallbackHandlerTest.java b/qpid/java/client/src/test/java/org/apache/qpid/client/security/UsernamePasswordCallbackHandlerTest.java deleted file mode 100644 index 70f279d53c..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/client/security/UsernamePasswordCallbackHandlerTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.client.security; - -import junit.framework.TestCase; - -import org.apache.qpid.client.AMQConnectionURL; - -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.NameCallback; -import javax.security.auth.callback.PasswordCallback; - -/** - * Unit tests for the UsernamePasswordCallbackHandler. - * - */ -public class UsernamePasswordCallbackHandlerTest extends TestCase -{ - private AMQCallbackHandler _callbackHandler = new UsernamePasswordCallbackHandler(); // Class under test - private static final String PROMPT_UNUSED = "unused"; - - @Override - protected void setUp() throws Exception - { - super.setUp(); - - final String url = "amqp://username:password@client/test?brokerlist='tcp://localhost:1'"; - - _callbackHandler.initialise(new AMQConnectionURL(url)); - } - - /** - * Tests that the callback handler can correctly retrieve the username from the connection url. - */ - public void testNameCallback() throws Exception - { - final String expectedName = "username"; - NameCallback nameCallback = new NameCallback(PROMPT_UNUSED); - - assertNull("Unexpected name before test", nameCallback.getName()); - _callbackHandler.handle(new Callback[] {nameCallback}); - assertEquals("Unexpected name", expectedName, nameCallback.getName()); - } - - /** - * Tests that the callback handler can correctly retrieve the password from the connection url. - */ - public void testPasswordCallback() throws Exception - { - final String expectedPassword = "password"; - PasswordCallback passwordCallback = new PasswordCallback(PROMPT_UNUSED, false); - assertNull("Unexpected password before test", passwordCallback.getPassword()); - _callbackHandler.handle(new Callback[] {passwordCallback}); - assertEquals("Unexpected password", expectedPassword, new String(passwordCallback.getPassword())); - } -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/transport/MockSender.java b/qpid/java/client/src/test/java/org/apache/qpid/client/transport/MockSender.java deleted file mode 100644 index ee6704bb39..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/client/transport/MockSender.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.client.transport; - -import java.nio.ByteBuffer; - -import org.apache.qpid.transport.ByteBufferSender; - -public class MockSender implements ByteBufferSender -{ - - public void send(ByteBuffer msg) - { - - } - - public void flush() - { - - } - - public void close() - { - - } -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/transport/TestNetworkConnection.java b/qpid/java/client/src/test/java/org/apache/qpid/client/transport/TestNetworkConnection.java deleted file mode 100644 index cdfa83571b..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/client/transport/TestNetworkConnection.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.client.transport; - -import java.net.BindException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.nio.ByteBuffer; -import java.security.Principal; - -import org.apache.qpid.protocol.ProtocolEngineFactory; -import org.apache.qpid.ssl.SSLContextFactory; -import org.apache.qpid.transport.ByteBufferSender; -import org.apache.qpid.transport.NetworkTransportConfiguration; -import org.apache.qpid.transport.network.NetworkConnection; - -/** - * 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 TestNetworkConnection implements NetworkConnection -{ - private String _remoteHost = "127.0.0.1"; - private String _localHost = "127.0.0.1"; - private int _port = 1; - private SocketAddress _localAddress = null; - private SocketAddress _remoteAddress = null; - private final MockSender _sender; - - public TestNetworkConnection() - { - _sender = new MockSender(); - } - - - - public void bind(int port, InetAddress[] addresses, ProtocolEngineFactory protocolFactory, - NetworkTransportConfiguration config, SSLContextFactory sslFactory) throws BindException - { - - } - - public SocketAddress getLocalAddress() - { - return (_localAddress != null) ? _localAddress : new InetSocketAddress(_localHost, _port); - } - - public SocketAddress getRemoteAddress() - { - return (_remoteAddress != null) ? _remoteAddress : new InetSocketAddress(_remoteHost, _port); - } - - public void setMaxReadIdle(int idleTime) - { - - } - - @Override - public Principal getPeerPrincipal() - { - return null; - } - - @Override - public int getMaxReadIdle() - { - return 0; - } - - @Override - public int getMaxWriteIdle() - { - return 0; - } - - public void setMaxWriteIdle(int idleTime) - { - - } - - public void close() - { - - } - - public void flush() - { - - } - - public void send(ByteBuffer msg) - { - - } - - public void setIdleTimeout(int i) - { - - } - - public void setPort(int port) - { - _port = port; - } - - public int getPort() - { - return _port; - } - - public void setLocalHost(String host) - { - _localHost = host; - } - - public void setRemoteHost(String host) - { - _remoteHost = host; - } - - public void setLocalAddress(SocketAddress address) - { - _localAddress = address; - } - - public void setRemoteAddress(SocketAddress address) - { - _remoteAddress = address; - } - - public ByteBufferSender getSender() - { - return _sender; - } - - public void start() - { - } -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/util/ClassLoadingAwareObjectInputStreamTest.java b/qpid/java/client/src/test/java/org/apache/qpid/client/util/ClassLoadingAwareObjectInputStreamTest.java deleted file mode 100644 index 91460ab4e7..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/client/util/ClassLoadingAwareObjectInputStreamTest.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.client.util; - -import org.apache.qpid.test.utils.QpidTestCase; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.io.ObjectOutputStream; -import java.util.Arrays; -import java.util.List; - -public class ClassLoadingAwareObjectInputStreamTest extends QpidTestCase -{ - private InputStream _in; - private ClassLoadingAwareObjectInputStream _claOIS; - - protected void setUp() throws Exception - { - //Create a viable input stream for instantiating the CLA OIS - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - ObjectOutputStream out = new ObjectOutputStream(baos); - out.writeObject("testString"); - out.flush(); - out.close(); - - - _in = new ByteArrayInputStream(baos.toByteArray()); - - _claOIS = new ClassLoadingAwareObjectInputStream(_in); - } - - /** - * Test that the resolveProxyClass method returns a proxy class implementing the desired interface - */ - public void testResolveProxyClass() throws Exception - { - //try to proxy an interface - Class<?> clazz = _claOIS.resolveProxyClass(new String[]{"java.lang.CharSequence"}); - - //verify the proxy supports the expected interface (only) - List<Class<?>> interfaces = Arrays.asList(clazz.getInterfaces()); - assertTrue("Unexpected interfaces supported by proxy", interfaces.contains(CharSequence.class)); - assertEquals("Unexpected interfaces supported by proxy", 1, interfaces.size()); - } - - /** - * Test that the resolveProxyClass method throws a ClassNotFoundException wrapping an - * IllegalArgumentException if it is provided arguments which violate the restrictions allowed - * by Proxy.getProxyClass (as required by the ObjectInputStream.resolveProxyClass javadoc). - */ - public void testResolveProxyClassThrowsCNFEWrappingIAE() throws Exception - { - try - { - //try to proxy a *class* rather than an interface, which is illegal - _claOIS.resolveProxyClass(new String[]{"java.lang.String"}); - fail("should have thrown an exception"); - } - catch(ClassNotFoundException cnfe) - { - //expected, but must verify it is wrapping an IllegalArgumentException - assertTrue(cnfe.getCause() instanceof IllegalArgumentException); - } - } -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/filter/JMSSelectorFilterTest.java b/qpid/java/client/src/test/java/org/apache/qpid/filter/JMSSelectorFilterTest.java deleted file mode 100644 index 8782b92ee9..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/filter/JMSSelectorFilterTest.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.filter; - -import junit.framework.TestCase; - -import org.apache.qpid.AMQInternalException; -import org.apache.qpid.client.filter.JMSSelectorFilter; -import org.apache.qpid.client.filter.MessageFilter; -import org.apache.qpid.client.message.JMSTextMessage; -import org.apache.qpid.client.message.TestMessageHelper; - -public class JMSSelectorFilterTest extends TestCase -{ - - public void testEmptySelectorFilter() throws Exception - { - try - { - new JMSSelectorFilter(""); - fail("Should not be able to create a JMSSelectorFilter with an empty selector"); - } - catch (IllegalArgumentException iae) - { - // pass - } - } - - public void testNullSelectorFilter() throws Exception - { - try - { - new JMSSelectorFilter(null); - fail("Should not be able to create a JMSSelectorFilter with a null selector"); - } - catch (IllegalArgumentException iae) - { - // pass - } - } - - public void testInvalidSelectorFilter() throws Exception - { - try - { - new JMSSelectorFilter("$%^"); - fail("Unparsable selector so expected AMQInternalException to be thrown"); - } - catch (AMQInternalException amqie) - { - // pass - } - } - - public void testSimpleSelectorFilter() throws Exception - { - MessageFilter simpleSelectorFilter = new JMSSelectorFilter("select=5"); - - assertNotNull("Filter object is null", simpleSelectorFilter); - assertNotNull("Selector string is null", simpleSelectorFilter.getSelector()); - assertEquals("Unexpected selector", "select=5", simpleSelectorFilter.getSelector()); - assertTrue("Filter object is invalid", simpleSelectorFilter != null); - - final JMSTextMessage message = TestMessageHelper.newJMSTextMessage(); - - message.setIntProperty("select", 4); - assertFalse("Selector did match when not expected", simpleSelectorFilter.matches(message)); - message.setIntProperty("select", 5); - assertTrue("Selector didnt match when expected", simpleSelectorFilter.matches(message)); - message.setIntProperty("select", 6); - assertFalse("Selector did match when not expected", simpleSelectorFilter.matches(message)); - } - - public void testFailedMatchingFilter() throws Exception - { - MessageFilter simpleSelectorFilter = new JMSSelectorFilter("select>4"); - - assertNotNull("Filter object is null", simpleSelectorFilter); - assertNotNull("Selector string is null", simpleSelectorFilter.getSelector()); - assertEquals("Unexpected selector", "select>4", simpleSelectorFilter.getSelector()); - assertTrue("Filter object is invalid", simpleSelectorFilter != null); - - final JMSTextMessage message = TestMessageHelper.newJMSTextMessage(); - - message.setStringProperty("select", "5"); - assertFalse("Selector matched when not expected", simpleSelectorFilter.matches(message)); - message.setStringProperty("select", "elephant"); - assertFalse("Selector matched when not expected", simpleSelectorFilter.matches(message)); - message.setBooleanProperty("select", false); - assertFalse("Selector matched when not expected", simpleSelectorFilter.matches(message)); - } -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/jms/FailoverPolicyTest.java b/qpid/java/client/src/test/java/org/apache/qpid/jms/FailoverPolicyTest.java deleted file mode 100644 index cb9623237c..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/jms/FailoverPolicyTest.java +++ /dev/null @@ -1,338 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.jms; - -import junit.framework.TestCase; - -import org.apache.qpid.client.AMQConnectionURL; -import org.apache.qpid.jms.failover.FailoverExchangeMethod; -import org.apache.qpid.jms.failover.FailoverMethod; -import org.apache.qpid.jms.failover.FailoverRoundRobinServers; -import org.apache.qpid.jms.failover.FailoverSingleServer; -import org.apache.qpid.jms.failover.NoFailover; - -import javax.jms.ConnectionConsumer; -import javax.jms.ConnectionMetaData; -import javax.jms.Destination; -import javax.jms.ExceptionListener; -import javax.jms.JMSException; -import javax.jms.ServerSessionPool; -import javax.jms.Topic; - -/** - * Tests the ability of FailoverPolicy to instantiate the correct FailoverMethod. - * - * This test presently does <i>not</i> test {@link FailoverPolicy#FailoverPolicy(FailoverMethod) or - * {@link FailoverPolicy#addMethod(FailoverMethod)} as it appears that this functionality - * is no longer in use. - * - */ -public class FailoverPolicyTest extends TestCase -{ - private FailoverPolicy _failoverPolicy = null; // class under test - private String _url; - private Connection _connection = null; - private ConnectionURL _connectionUrl = null; - - /** - * Tests single server method is selected for a brokerlist with one broker when - * the failover option is not specified. - */ - public void testBrokerListWithOneBrokerDefaultsToSingleServerPolicy() throws Exception - { - _url = "amqp://user:pass@clientid/test?brokerlist='tcp://localhost:5672'"; - _connectionUrl = new AMQConnectionURL(_url); - _connection = createStubConnection(); - - _failoverPolicy = new FailoverPolicy(_connectionUrl, _connection); - - assertTrue("Unexpected failover method", _failoverPolicy.getCurrentMethod() instanceof FailoverSingleServer); - } - - /** - * Tests round robin method is selected for a brokerlist with two brokers when - * the failover option is not specified. - */ - public void testBrokerListWithTwoBrokersDefaultsToRoundRobinPolicy() throws Exception - { - _url = "amqp://user:pass@clientid/test?brokerlist='tcp://localhost:5672;tcp://localhost:5673'"; - _connectionUrl = new AMQConnectionURL(_url); - _connection = createStubConnection(); - - _failoverPolicy = new FailoverPolicy(_connectionUrl, _connection); - - assertTrue("Unexpected failover method", _failoverPolicy.getCurrentMethod() instanceof FailoverRoundRobinServers); - } - - /** - * Tests single server method is selected for a brokerlist with one broker when - * the failover option passed as 'singlebroker'. - */ - public void testExplictFailoverOptionSingleBroker() throws Exception - { - _url = "amqp://user:pass@clientid/test?brokerlist='tcp://localhost:5672'&failover='singlebroker'"; - _connectionUrl = new AMQConnectionURL(_url); - _connection = createStubConnection(); - - _failoverPolicy = new FailoverPolicy(_connectionUrl, _connection); - - assertTrue("Unexpected failover method", _failoverPolicy.getCurrentMethod() instanceof FailoverSingleServer); - } - - /** - * Tests round robin method is selected for a brokerlist with two brokers when - * the failover option passed as 'roundrobin'. - */ - public void testExplictFailoverOptionRoundrobin() throws Exception - { - _url = "amqp://user:pass@clientid/test?brokerlist='tcp://localhost:5672;tcp://localhost:5673'&failover='roundrobin'"; - _connectionUrl = new AMQConnectionURL(_url); - _connection = createStubConnection(); - - _failoverPolicy = new FailoverPolicy(_connectionUrl, _connection); - - assertTrue("Unexpected failover method", _failoverPolicy.getCurrentMethod() instanceof FailoverRoundRobinServers); - } - - /** - * Tests no failover method is selected for a brokerlist with one broker when - * the failover option passed as 'nofailover'. - */ - public void testExplictFailoverOptionNofailover() throws Exception - { - _url = "amqp://user:pass@clientid/test?brokerlist='tcp://localhost:5672'&failover='nofailover'"; - _connectionUrl = new AMQConnectionURL(_url); - _connection = createStubConnection(); - - _failoverPolicy = new FailoverPolicy(_connectionUrl, _connection); - - assertTrue("Unexpected failover method", _failoverPolicy.getCurrentMethod() instanceof NoFailover); - } - - /** - * Tests failover exchange method is selected for a brokerlist with one broker when - * the failover option passed as 'failover_exchange'. - */ - public void testExplictFailoverOptionFailoverExchange() throws Exception - { - _url = "amqp://user:pass@clientid/test?brokerlist='tcp://localhost:5672'&failover='failover_exchange'"; - _connectionUrl = new AMQConnectionURL(_url); - _connection = createStubConnection(); - - _failoverPolicy = new FailoverPolicy(_connectionUrl, _connection); - - assertTrue("Unexpected failover method", _failoverPolicy.getCurrentMethod() instanceof FailoverExchangeMethod); - } - - /** - * Tests that a custom method can be selected for a brokerlist with one brokers when - * the failover option passed as a qualified class-name. - */ - public void testExplictFailoverOptionDynamicallyLoadedFailoverMethod() throws Exception - { - _url = "amqp://user:pass@clientid/test?brokerlist='tcp://localhost:5672'&failover='org.apache.qpid.jms.FailoverPolicyTest$MyFailoverMethod'"; - _connectionUrl = new AMQConnectionURL(_url); - _connection = createStubConnection(); - - _failoverPolicy = new FailoverPolicy(_connectionUrl, _connection); - - assertTrue("Unexpected failover method", _failoverPolicy.getCurrentMethod() instanceof MyFailoverMethod); - } - - /** - * Tests that an unknown method caused an exception. - */ - public void testUnknownFailoverMethod() throws Exception - { - _url = "amqp://user:pass@clientid/test?brokerlist='tcp://localhost:5672'&failover='unknown'"; - _connectionUrl = new AMQConnectionURL(_url); - _connection = createStubConnection(); - - try - { - new FailoverPolicy(_connectionUrl, _connection); - fail("Exception not thrown"); - } - catch(IllegalArgumentException iae) - { - // PASS - } - } - - private Connection createStubConnection() - { - return new Connection() - { - - @Override - public Session createSession(boolean transacted, - int acknowledgeMode, int prefetch) throws JMSException - { - return null; - } - - @Override - public Session createSession(boolean transacted, - int acknowledgeMode, int prefetchHigh, int prefetchLow) - throws JMSException - { - return null; - } - - @Override - public ConnectionListener getConnectionListener() - { - return null; - } - - @Override - public long getMaximumChannelCount() throws JMSException - { - return 0; - } - - @Override - public void setConnectionListener(ConnectionListener listener) - { - } - - @Override - public void close() throws JMSException - { - } - - @Override - public ConnectionConsumer createConnectionConsumer( - Destination arg0, String arg1, ServerSessionPool arg2, - int arg3) throws JMSException - { - return null; - } - - @Override - public ConnectionConsumer createDurableConnectionConsumer( - Topic arg0, String arg1, String arg2, - ServerSessionPool arg3, int arg4) throws JMSException - { - return null; - } - - @Override - public javax.jms.Session createSession(boolean arg0, int arg1) - throws JMSException - { - return null; - } - - @Override - public String getClientID() throws JMSException - { - return null; - } - - @Override - public ExceptionListener getExceptionListener() throws JMSException - { - return null; - } - - @Override - public ConnectionMetaData getMetaData() throws JMSException - { - return null; - } - - @Override - public void setClientID(String arg0) throws JMSException - { - } - - @Override - public void setExceptionListener(ExceptionListener arg0) - throws JMSException - { - } - - @Override - public void start() throws JMSException - { - } - - @Override - public void stop() throws JMSException - { - } - }; - } - - // Class used to test the ability of FailoverPolicy to load an implementation. - static class MyFailoverMethod implements FailoverMethod - { - public MyFailoverMethod(ConnectionURL connectionDetails) - { - } - - @Override - public void attainedConnection() - { - } - - @Override - public boolean failoverAllowed() - { - return false; - } - - @Override - public BrokerDetails getCurrentBrokerDetails() - { - return null; - } - - @Override - public BrokerDetails getNextBrokerDetails() - { - return null; - } - - @Override - public String methodName() - { - return null; - } - - @Override - public void reset() - { - } - - @Override - public void setBroker(BrokerDetails broker) - { - } - - @Override - public void setRetries(int maxRetries) - { - } - } - -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/jndi/JNDITest.properties b/qpid/java/client/src/test/java/org/apache/qpid/jndi/JNDITest.properties deleted file mode 100644 index 07017a05a6..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/jndi/JNDITest.properties +++ /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. -# -java.naming.factory.initial = org.apache.qpid.jndi.PropertiesFileInitialContextFactory - -# Queue name with spaces -queue.QueueNameWithSpace = QueueNameWithSpace - -# Topic name with spaces -topic.TopicNameWithSpace = TopicNameWithSpace - -# Multiple topic names with spaces -topic.MultipleTopicNamesWithSpace = Topic1WithSpace , Topic2WithSpace , Topic3WithSpace diff --git a/qpid/java/client/src/test/java/org/apache/qpid/jndi/PropertiesFileInitialContextFactoryTest.java b/qpid/java/client/src/test/java/org/apache/qpid/jndi/PropertiesFileInitialContextFactoryTest.java deleted file mode 100644 index 2914244103..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/jndi/PropertiesFileInitialContextFactoryTest.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.jndi; - - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Properties; - -import javax.jms.ConnectionFactory; -import javax.jms.Destination; -import javax.jms.Queue; -import javax.jms.Topic; -import javax.naming.ConfigurationException; -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.naming.NamingException; - -import org.apache.qpid.client.AMQConnectionFactory; -import org.apache.qpid.client.AMQDestination; -import org.apache.qpid.configuration.ClientProperties; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.test.utils.QpidTestCase; - -public class PropertiesFileInitialContextFactoryTest extends QpidTestCase -{ - private static final String CONNECTION_URL = "amqp://username:password@clientid/test?brokerlist='tcp://testContextFromProviderURL:5672'"; - - public void testQueueNamesWithTrailingSpaces() throws Exception - { - Context ctx = prepareContext(); - Queue queue = (Queue)ctx.lookup("QueueNameWithSpace"); - assertEquals("QueueNameWithSpace",queue.getQueueName()); - } - - public void testTopicNamesWithTrailingSpaces() throws Exception - { - Context ctx = prepareContext(); - Topic topic = (Topic)ctx.lookup("TopicNameWithSpace"); - assertEquals("TopicNameWithSpace",topic.getTopicName()); - } - - public void testMultipleTopicNamesWithTrailingSpaces() throws Exception - { - Context ctx = prepareContext(); - Topic topic = (Topic)ctx.lookup("MultipleTopicNamesWithSpace"); - int i = 0; - for (AMQShortString bindingKey: ((AMQDestination)topic).getBindingKeys()) - { - i++; - assertEquals("Topic" + i + "WithSpace",bindingKey.asString()); - } - } - - public void testConfigurationErrors() throws Exception - { - Properties properties = new Properties(); - properties.put("java.naming.factory.initial", "org.apache.qpid.jndi.PropertiesFileInitialContextFactory"); - properties.put("destination.my-queue","amq.topic/test;create:always}"); - - try - { - new InitialContext(properties); - fail("A configuration exception should be thrown with details about the address syntax error"); - } - catch(ConfigurationException e) - { - assertTrue("Incorrect exception", e.getMessage().contains("Failed to parse entry: amq.topic/test;create:always}")); - } - } - - private InitialContext prepareContext() throws IOException, NamingException - { - Properties properties = new Properties(); - properties.load(this.getClass().getResourceAsStream("JNDITest.properties")); - - return new InitialContext(properties); - } - - /** - * Test loading of a JNDI properties file through use of a file:// URL - * supplied via the InitialContext.PROVIDER_URL system property. - */ - public void testContextFromProviderURL() throws Exception - { - Properties properties = new Properties(); - properties.put("connectionfactory.qpidConnectionfactory", CONNECTION_URL); - properties.put("destination.topicExchange", "destName"); - - File f = File.createTempFile(getTestName(), ".properties"); - try - { - FileOutputStream fos = new FileOutputStream(f); - properties.store(fos, null); - fos.close(); - - setTestSystemProperty(ClientProperties.DEST_SYNTAX, "ADDR"); - setTestSystemProperty(InitialContext.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jndi.PropertiesFileInitialContextFactory"); - setTestSystemProperty(InitialContext.PROVIDER_URL, f.toURI().toURL().toString()); - - InitialContext context = new InitialContext(); - Destination dest = (Destination) context.lookup("topicExchange"); - assertNotNull("Lookup from URI based context should not be null", dest); - assertTrue("Unexpected value from lookup", dest.toString().contains("destName")); - - ConnectionFactory factory = (ConnectionFactory) context.lookup("qpidConnectionfactory"); - assertTrue("ConnectionFactory was not an instance of AMQConnectionFactory", factory instanceof AMQConnectionFactory); - assertEquals("Unexpected ConnectionURL value", CONNECTION_URL.replaceAll("password", "********"), - ((AMQConnectionFactory)factory).getConnectionURLString()); - - context.close(); - } - finally - { - f.delete(); - } - } -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTableKeyEnumeratorTest.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTableKeyEnumeratorTest.java deleted file mode 100644 index b5a4166b55..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTableKeyEnumeratorTest.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.test.unit.basic; - -import junit.framework.TestCase; - -import org.apache.qpid.client.message.JMSTextMessage; -import org.apache.qpid.client.message.TestMessageHelper; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.FieldTableFactory; - -import javax.jms.JMSException; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.NoSuchElementException; - -public class FieldTableKeyEnumeratorTest extends TestCase -{ - public void testTrue() - { - - } - public void testKeyEnumeration() - { - FieldTable result = FieldTableFactory.newFieldTable(); - result.setObject("one", 1L); - result.setObject("two", 2L); - result.setObject("three", 3L); - result.setObject("four", 4L); - result.setObject("five", 5L); - - Iterator iterator = result.keys().iterator(); - - try - { - assertTrue("one".equals(iterator.next())); - assertTrue("two".equals(iterator.next())); - assertTrue("three".equals(iterator.next())); - assertTrue("four".equals(iterator.next())); - assertTrue("five".equals(iterator.next())); - } - catch (NoSuchElementException e) - { - fail("All elements should be found."); - } - - } - - public void testPropertyEnum() - { - try - { - JMSTextMessage text = TestMessageHelper.newJMSTextMessage(); - - text.setBooleanProperty("Boolean1", true); - text.setBooleanProperty("Boolean2", true); - text.setIntProperty("Int", 2); - text.setLongProperty("Long", 2); - - Enumeration e = text.getPropertyNames(); - - assertTrue("Boolean1".equals(e.nextElement())); - assertTrue("Boolean2".equals(e.nextElement())); - assertTrue("Int".equals(e.nextElement())); - assertTrue("Long".equals(e.nextElement())); - } - catch (JMSException e) - { - - } - } - - public static junit.framework.Test suite() - { - return new junit.framework.TestSuite(FieldTableKeyEnumeratorTest.class); - } -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTablePropertyTest.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTablePropertyTest.java deleted file mode 100644 index e27c684adc..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTablePropertyTest.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.test.unit.basic; - -import junit.framework.TestCase; - -import org.apache.qpid.client.message.JMSTextMessage; -import org.apache.qpid.client.message.TestMessageHelper; - -import javax.jms.JMSException; -import java.util.Enumeration; - -public class FieldTablePropertyTest extends TestCase -{ - public void testPropertyNames() - { - try - { - JMSTextMessage text = TestMessageHelper.newJMSTextMessage(); - - text.setBooleanProperty("Boolean1", true); - text.setBooleanProperty("Boolean2", true); - text.setIntProperty("Int", 2); - text.setLongProperty("Long", 2); - - Enumeration e = text.getPropertyNames(); - - assertEquals("Boolean1", e.nextElement()); - assertTrue("Boolean2".equals(e.nextElement())); - assertTrue("Int".equals(e.nextElement())); - assertTrue("Long".equals(e.nextElement())); - } - catch (JMSException e) - { - - } - } - - public static junit.framework.Test suite() - { - return new junit.framework.TestSuite(FieldTablePropertyTest.class); - } -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/BrokerDetails/BrokerDetailsTest.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/BrokerDetails/BrokerDetailsTest.java deleted file mode 100644 index 2733d7bf6d..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/BrokerDetails/BrokerDetailsTest.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.test.unit.client.BrokerDetails; - -import org.apache.qpid.client.AMQBrokerDetails; -import org.apache.qpid.configuration.ClientProperties; -import org.apache.qpid.jms.BrokerDetails; -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.transport.ConnectionSettings; -import org.apache.qpid.url.URLSyntaxException; - -public class BrokerDetailsTest extends QpidTestCase -{ - public void testDefaultTCP_NODELAY() throws URLSyntaxException - { - String brokerURL = "tcp://localhost:5672"; - AMQBrokerDetails broker = new AMQBrokerDetails(brokerURL); - - assertNull("default value should be null", broker.getProperty(BrokerDetails.OPTIONS_TCP_NO_DELAY)); - } - - public void testOverridingTCP_NODELAY() throws URLSyntaxException - { - String brokerURL = "tcp://localhost:5672?tcp_nodelay='true'"; - AMQBrokerDetails broker = new AMQBrokerDetails(brokerURL); - - assertTrue("value should be true", Boolean.valueOf(broker.getProperty(BrokerDetails.OPTIONS_TCP_NO_DELAY))); - - brokerURL = "tcp://localhost:5672?tcp_nodelay='false''&maxprefetch='1'"; - broker = new AMQBrokerDetails(brokerURL); - - assertFalse("value should be false", Boolean.valueOf(broker.getProperty(BrokerDetails.OPTIONS_TCP_NO_DELAY))); - } - - public void testDefaultConnectTimeout() throws URLSyntaxException - { - String brokerURL = "tcp://localhost:5672"; - AMQBrokerDetails broker = new AMQBrokerDetails(brokerURL); - - ConnectionSettings settings = broker.buildConnectionSettings(); - - assertEquals("unexpected default connect timeout value", BrokerDetails.DEFAULT_CONNECT_TIMEOUT, settings.getConnectTimeout()); - } - - public void testOverridingConnectTimeout() throws URLSyntaxException - { - int timeout = 2 * BrokerDetails.DEFAULT_CONNECT_TIMEOUT; - assertTrue(timeout != BrokerDetails.DEFAULT_CONNECT_TIMEOUT); - - String brokerURL = "tcp://localhost:5672?" + BrokerDetails.OPTIONS_CONNECT_TIMEOUT + "='" + timeout + "'"; - AMQBrokerDetails broker = new AMQBrokerDetails(brokerURL); - - ConnectionSettings settings = broker.buildConnectionSettings(); - - assertEquals("unexpected connect timeout value", timeout, settings.getConnectTimeout()); - } - - public void testMultiParameters() throws URLSyntaxException - { - String url = "tcp://localhost:5672?timeout='200',immediatedelivery='true'"; - - AMQBrokerDetails broker = new AMQBrokerDetails(url); - - assertTrue(broker.getProperty("timeout").equals("200")); - assertTrue(broker.getProperty("immediatedelivery").equals("true")); - } - - public void testTransportsDefaultToTCP() throws URLSyntaxException - { - String url = "localhost:5672"; - - AMQBrokerDetails broker = new AMQBrokerDetails(url); - assertTrue(broker.getTransport().equals("tcp")); - } - - public void testCheckDefaultPort() throws URLSyntaxException - { - String url = "tcp://localhost"; - - AMQBrokerDetails broker = new AMQBrokerDetails(url); - assertTrue(broker.getPort() == AMQBrokerDetails.DEFAULT_PORT); - } - - public void testBothDefaults() throws URLSyntaxException - { - String url = "localhost"; - - AMQBrokerDetails broker = new AMQBrokerDetails(url); - - assertTrue(broker.getTransport().equals("tcp")); - assertTrue(broker.getPort() == AMQBrokerDetails.DEFAULT_PORT); - } - - public void testWrongOptionSeparatorInBroker() - { - String url = "tcp://localhost:5672+option='value'"; - try - { - new AMQBrokerDetails(url); - } - catch (URLSyntaxException urise) - { - assertTrue(urise.getReason().equals("Illegal character in port number")); - } - } - - public void testToStringMasksKeyStorePassword() throws Exception - { - String url = "tcp://localhost:5672?key_store_password='password'"; - BrokerDetails details = new AMQBrokerDetails(url); - - String expectedToString = "tcp://localhost:5672?key_store_password='********'"; - String actualToString = details.toString(); - - assertEquals("Unexpected toString", expectedToString, actualToString); - } - - public void testToStringMasksTrustStorePassword() throws Exception - { - String url = "tcp://localhost:5672?trust_store_password='password'"; - BrokerDetails details = new AMQBrokerDetails(url); - - String expectedToString = "tcp://localhost:5672?trust_store_password='********'"; - String actualToString = details.toString(); - - assertEquals("Unexpected toString", expectedToString, actualToString); - } - - public void testDefaultSsl() throws URLSyntaxException - { - String brokerURL = "tcp://localhost:5672"; - AMQBrokerDetails broker = new AMQBrokerDetails(brokerURL); - - assertNull("default value should be null", broker.getProperty(BrokerDetails.OPTIONS_SSL)); - } - - public void testOverridingSsl() throws URLSyntaxException - { - String brokerURL = "tcp://localhost:5672?ssl='true'"; - AMQBrokerDetails broker = new AMQBrokerDetails(brokerURL); - - assertTrue("value should be true", Boolean.valueOf(broker.getProperty(BrokerDetails.OPTIONS_SSL))); - - brokerURL = "tcp://localhost:5672?ssl='false''&maxprefetch='1'"; - broker = new AMQBrokerDetails(brokerURL); - - assertFalse("value should be false", Boolean.valueOf(broker.getProperty(BrokerDetails.OPTIONS_SSL))); - } - - public void testHeartbeatDefaultsToNull() throws Exception - { - String brokerURL = "tcp://localhost:5672"; - AMQBrokerDetails broker = new AMQBrokerDetails(brokerURL); - assertNull("unexpected default value for " + BrokerDetails.OPTIONS_HEARTBEAT, broker.getProperty(BrokerDetails.OPTIONS_HEARTBEAT)); - } - - public void testOverriddingHeartbeat() throws Exception - { - String brokerURL = "tcp://localhost:5672?heartbeat='60'"; - AMQBrokerDetails broker = new AMQBrokerDetails(brokerURL); - assertEquals(60, Integer.parseInt(broker.getProperty(BrokerDetails.OPTIONS_HEARTBEAT))); - - assertEquals(Integer.valueOf(60), broker.buildConnectionSettings().getHeartbeatInterval08()); - } - - @SuppressWarnings("deprecation") - public void testLegacyHeartbeat() throws Exception - { - String brokerURL = "tcp://localhost:5672?idle_timeout='60000'"; - AMQBrokerDetails broker = new AMQBrokerDetails(brokerURL); - assertEquals(60000, Integer.parseInt(broker.getProperty(BrokerDetails.OPTIONS_IDLE_TIMEOUT))); - - assertEquals(Integer.valueOf(60), broker.buildConnectionSettings().getHeartbeatInterval08()); - } - - public void testSslVerifyHostNameIsTurnedOnByDefault() throws Exception - { - String brokerURL = "tcp://localhost:5672?ssl='true'"; - AMQBrokerDetails broker = new AMQBrokerDetails(brokerURL); - ConnectionSettings connectionSettings = broker.buildConnectionSettings(); - assertTrue(String.format("Unexpected '%s' option value", BrokerDetails.OPTIONS_SSL_VERIFY_HOSTNAME), - connectionSettings.isVerifyHostname()); - assertNull(String.format("Unexpected '%s' property value", BrokerDetails.OPTIONS_SSL_VERIFY_HOSTNAME), - broker.getProperty(BrokerDetails.OPTIONS_SSL_VERIFY_HOSTNAME)); - } - - public void testSslVerifyHostNameIsTurnedOff() throws Exception - { - String brokerURL = "tcp://localhost:5672?ssl='true'&ssl_verify_hostname='false'"; - AMQBrokerDetails broker = new AMQBrokerDetails(brokerURL); - ConnectionSettings connectionSettings = broker.buildConnectionSettings(); - assertFalse(String.format("Unexpected '%s' option value", BrokerDetails.OPTIONS_SSL_VERIFY_HOSTNAME), - connectionSettings.isVerifyHostname()); - assertEquals(String.format("Unexpected '%s' property value", BrokerDetails.OPTIONS_SSL_VERIFY_HOSTNAME), - "false", broker.getProperty(BrokerDetails.OPTIONS_SSL_VERIFY_HOSTNAME)); - } - - public void testSslVerifyHostNameTurnedOffViaSystemProperty() throws Exception - { - setTestSystemProperty(ClientProperties.CONNECTION_OPTION_SSL_VERIFY_HOST_NAME, "false"); - String brokerURL = "tcp://localhost:5672?ssl='true'"; - AMQBrokerDetails broker = new AMQBrokerDetails(brokerURL); - ConnectionSettings connectionSettings = broker.buildConnectionSettings(); - assertFalse(String.format("Unexpected '%s' option value", BrokerDetails.OPTIONS_SSL_VERIFY_HOSTNAME), - connectionSettings.isVerifyHostname()); - assertNull(String.format("Unexpected '%s' property value", BrokerDetails.OPTIONS_SSL_VERIFY_HOSTNAME), - broker.getProperty(BrokerDetails.OPTIONS_SSL_VERIFY_HOSTNAME)); - } -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/ChannelCloseMethodHandlerNoCloseOk.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/ChannelCloseMethodHandlerNoCloseOk.java deleted file mode 100644 index 0bdd3062ea..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/ChannelCloseMethodHandlerNoCloseOk.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.test.unit.client.channelclose; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQChannelClosedException; -import org.apache.qpid.AMQException; -import org.apache.qpid.AMQInvalidArgumentException; -import org.apache.qpid.AMQInvalidRoutingKeyException; -import org.apache.qpid.client.AMQNoConsumersException; -import org.apache.qpid.client.AMQNoRouteException; -import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.apache.qpid.client.state.StateAwareMethodListener; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.ChannelCloseBody; -import org.apache.qpid.protocol.AMQConstant; - -public class ChannelCloseMethodHandlerNoCloseOk implements StateAwareMethodListener<ChannelCloseBody> -{ - private static final Logger _logger = LoggerFactory.getLogger(ChannelCloseMethodHandlerNoCloseOk.class); - - private static ChannelCloseMethodHandlerNoCloseOk _handler = new ChannelCloseMethodHandlerNoCloseOk(); - - public static ChannelCloseMethodHandlerNoCloseOk getInstance() - { - return _handler; - } - - public void methodReceived(AMQProtocolSession session, ChannelCloseBody method, int channelId) - throws AMQException - { - _logger.debug("ChannelClose method received"); - - AMQConstant errorCode = AMQConstant.getConstant(method.getReplyCode()); - AMQShortString reason = method.getReplyText(); - if (_logger.isDebugEnabled()) - { - _logger.debug("Channel close reply code: " + errorCode + ", reason: " + reason); - } - - // For this test Method Handler .. don't send Close-OK - // // TODO: Be aware of possible changes to parameter order as versions change. - // AMQFrame frame = ChannelCloseOkBody.createAMQFrame(evt.getChannelId(), method.getMajor(), method.getMinor()); - // protocolSession.writeFrame(frame); - if (errorCode != AMQConstant.REPLY_SUCCESS) - { - _logger.error("Channel close received with errorCode " + errorCode + ", and reason " + reason); - if (errorCode == AMQConstant.NO_CONSUMERS) - { - throw new AMQNoConsumersException("Error: " + reason, null, null); - } - else if (errorCode == AMQConstant.NO_ROUTE) - { - throw new AMQNoRouteException("Error: " + reason, null, null); - } - else if (errorCode == AMQConstant.ARGUMENT_INVALID) - { - _logger.debug("Broker responded with Invalid Argument."); - - throw new AMQInvalidArgumentException(String.valueOf(reason), null); - } - else if (errorCode == AMQConstant.INVALID_ROUTING_KEY) - { - _logger.debug("Broker responded with Invalid Routing Key."); - - throw new AMQInvalidRoutingKeyException(String.valueOf(reason), null); - } - else - { - throw new AMQChannelClosedException(errorCode, "Error: " + reason, null); - } - - } - - session.channelClosed(channelId, errorCode, String.valueOf(reason)); - } -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/NoCloseOKStateManager.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/NoCloseOKStateManager.java deleted file mode 100644 index 3498045601..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/NoCloseOKStateManager.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.test.unit.client.channelclose; - -import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.apache.qpid.client.state.AMQStateManager; - -public class NoCloseOKStateManager extends AMQStateManager -{ - public NoCloseOKStateManager(AMQProtocolSession protocolSession) - { - super(protocolSession); - } - - - - -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/connectionurl/ConnectionURLTest.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/connectionurl/ConnectionURLTest.java deleted file mode 100644 index c14ea3a101..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/connectionurl/ConnectionURLTest.java +++ /dev/null @@ -1,654 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.unit.client.connectionurl; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; - -import junit.framework.TestCase; - -import org.apache.qpid.client.AMQBrokerDetails; -import org.apache.qpid.client.AMQConnectionURL; -import org.apache.qpid.jms.BrokerDetails; -import org.apache.qpid.jms.ConnectionURL; -import org.apache.qpid.url.URLSyntaxException; - -public class ConnectionURLTest extends TestCase -{ - public void testFailoverURL() throws URLSyntaxException - { - String url = "amqp://ritchiem:bob@/test?brokerlist='tcp://localhost:5672;tcp://fancyserver:3000/',failover='roundrobin?cyclecount='100''"; - - ConnectionURL connectionurl = new AMQConnectionURL(url); - - assertTrue(connectionurl.getFailoverMethod().equals("roundrobin")); - assertEquals("100", connectionurl.getFailoverOption(ConnectionURL.OPTIONS_FAILOVER_CYCLE)); - assertTrue(connectionurl.getUsername().equals("ritchiem")); - assertTrue(connectionurl.getPassword().equals("bob")); - assertTrue(connectionurl.getVirtualHost().equals("/test")); - - assertTrue(connectionurl.getBrokerCount() == 2); - - BrokerDetails service = connectionurl.getBrokerDetails(0); - - assertTrue(service.getTransport().equals("tcp")); - assertTrue(service.getHost().equals("localhost")); - assertTrue(service.getPort() == 5672); - - service = connectionurl.getBrokerDetails(1); - - assertTrue(service.getTransport().equals("tcp")); - assertTrue(service.getHost().equals("fancyserver")); - assertTrue(service.getPort() == 3000); - - } - - public void testSingleTransportUsernamePasswordURL() throws URLSyntaxException - { - String url = "amqp://ritchiem:bob@/test?brokerlist='tcp://localhost:5672'"; - - ConnectionURL connectionurl = new AMQConnectionURL(url); - - assertTrue(connectionurl.getFailoverMethod() == null); - assertTrue(connectionurl.getUsername().equals("ritchiem")); - assertTrue(connectionurl.getPassword().equals("bob")); - assertTrue(connectionurl.getVirtualHost().equals("/test")); - - assertTrue(connectionurl.getBrokerCount() == 1); - - BrokerDetails service = connectionurl.getBrokerDetails(0); - - assertTrue(service.getTransport().equals("tcp")); - assertTrue(service.getHost().equals("localhost")); - assertTrue(service.getPort() == 5672); - } - - public void testSingleTransportUsernameBlankPasswordURL() throws URLSyntaxException - { - String url = "amqp://ritchiem:@/test?brokerlist='tcp://localhost:5672'"; - - ConnectionURL connectionurl = new AMQConnectionURL(url); - - assertTrue(connectionurl.getFailoverMethod() == null); - assertTrue(connectionurl.getUsername().equals("ritchiem")); - assertTrue(connectionurl.getPassword().equals("")); - assertTrue(connectionurl.getVirtualHost().equals("/test")); - - assertTrue(connectionurl.getBrokerCount() == 1); - - BrokerDetails service = connectionurl.getBrokerDetails(0); - - assertTrue(service.getTransport().equals("tcp")); - assertTrue(service.getHost().equals("localhost")); - assertTrue(service.getPort() == 5672); - } - - public void testFailedURLNullPassword() - { - String url = "amqp://ritchiem@/test?brokerlist='tcp://localhost:5672'"; - - try - { - new AMQConnectionURL(url); - fail("URL has null password"); - } - catch (URLSyntaxException e) - { - assertTrue(e.getReason().equals("Null password in user information not allowed.")); - assertTrue(e.getIndex() == 7); - } - } - - - public void testSingleTransportURL() throws URLSyntaxException - { - String url = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672'"; - - ConnectionURL connectionurl = new AMQConnectionURL(url); - - - assertTrue(connectionurl.getFailoverMethod() == null); - assertTrue(connectionurl.getUsername().equals("guest")); - assertTrue(connectionurl.getPassword().equals("guest")); - assertTrue(connectionurl.getVirtualHost().equals("/test")); - - - assertTrue(connectionurl.getBrokerCount() == 1); - - - BrokerDetails service = connectionurl.getBrokerDetails(0); - - assertTrue(service.getTransport().equals("tcp")); - assertTrue(service.getHost().equals("localhost")); - assertTrue(service.getPort() == 5672); - } - - public void testSingleTransportWithClientURLURL() throws URLSyntaxException - { - String url = "amqp://guest:guest@clientname/test?brokerlist='tcp://localhost:5672'"; - - ConnectionURL connectionurl = new AMQConnectionURL(url); - - - assertTrue(connectionurl.getFailoverMethod() == null); - assertTrue(connectionurl.getUsername().equals("guest")); - assertTrue(connectionurl.getPassword().equals("guest")); - assertTrue(connectionurl.getVirtualHost().equals("/test")); - assertTrue(connectionurl.getClientName().equals("clientname")); - - - assertTrue(connectionurl.getBrokerCount() == 1); - - - BrokerDetails service = connectionurl.getBrokerDetails(0); - - assertTrue(service.getTransport().equals("tcp")); - assertTrue(service.getHost().equals("localhost")); - assertTrue(service.getPort() == 5672); - } - - public void testSingleTransport1OptionURL() throws URLSyntaxException - { - String url = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672',routingkey='jim'"; - - ConnectionURL connectionurl = new AMQConnectionURL(url); - - assertTrue(connectionurl.getFailoverMethod() == null); - assertTrue(connectionurl.getUsername().equals("guest")); - assertTrue(connectionurl.getPassword().equals("guest")); - assertTrue(connectionurl.getVirtualHost().equals("/test")); - - - assertTrue(connectionurl.getBrokerCount() == 1); - - BrokerDetails service = connectionurl.getBrokerDetails(0); - - assertTrue(service.getTransport().equals("tcp")); - - assertTrue(service.getHost().equals("localhost")); - assertTrue(service.getPort() == 5672); - assertTrue(connectionurl.getOption("routingkey").equals("jim")); - } - - public void testSingleTransportDefaultedBroker() throws URLSyntaxException - { - String url = "amqp://guest:guest@/test?brokerlist='localhost'"; - - ConnectionURL connectionurl = new AMQConnectionURL(url); - - assertTrue(connectionurl.getFailoverMethod() == null); - assertTrue(connectionurl.getUsername().equals("guest")); - assertTrue(connectionurl.getPassword().equals("guest")); - assertTrue(connectionurl.getVirtualHost().equals("/test")); - - - assertTrue(connectionurl.getBrokerCount() == 1); - - BrokerDetails service = connectionurl.getBrokerDetails(0); - - assertTrue(service.getTransport().equals("tcp")); - - assertTrue(service.getHost().equals("localhost")); - assertTrue(service.getPort() == 5672); - } - - public void testSingleTransportDefaultedBrokerWithPort() throws URLSyntaxException - { - String url = "amqp://guest:guest@/test?brokerlist='localhost:1234'"; - - ConnectionURL connectionurl = new AMQConnectionURL(url); - - assertTrue(connectionurl.getFailoverMethod() == null); - assertTrue(connectionurl.getUsername().equals("guest")); - assertTrue(connectionurl.getPassword().equals("guest")); - assertTrue(connectionurl.getVirtualHost().equals("/test")); - - - assertTrue(connectionurl.getBrokerCount() == 1); - - BrokerDetails service = connectionurl.getBrokerDetails(0); - - assertTrue(service.getTransport().equals("tcp")); - - assertTrue(service.getHost().equals("localhost")); - assertTrue(service.getPort() == 1234); - } - - public void testSingleTransportDefaultedBrokerWithIP() throws URLSyntaxException - { - String url = "amqp://guest:guest@/test?brokerlist='127.0.0.1'"; - - ConnectionURL connectionurl = new AMQConnectionURL(url); - - assertTrue(connectionurl.getFailoverMethod() == null); - assertTrue(connectionurl.getUsername().equals("guest")); - assertTrue(connectionurl.getPassword().equals("guest")); - assertTrue(connectionurl.getVirtualHost().equals("/test")); - - - assertTrue(connectionurl.getBrokerCount() == 1); - - BrokerDetails service = connectionurl.getBrokerDetails(0); - - assertTrue(service.getTransport().equals("tcp")); - - assertTrue(service.getHost().equals("127.0.0.1")); - assertTrue(service.getPort() == 5672); - } - - public void testConnectionURLOptionToStringMasksPassword() throws URLSyntaxException - { - String url = "amqp://guest:guest@client/localhost?brokerlist='tcp://localhost:1234'"; - ConnectionURL connectionurl = new AMQConnectionURL(url); - - String expectedToString = "amqp://guest:********@client/localhost?brokerlist='tcp://localhost:1234'"; - String actualToString = connectionurl.toString(); - assertEquals("Unexpected toString form", expectedToString, actualToString); - } - - public void testConnectionURLOptionToStringMasksSslTrustStorePassword() throws URLSyntaxException - { - String url = "amqp://guest:guest@client/vhost?brokerlist='tcp://host:1234?trust_store_password='truststorepassword''"; - ConnectionURL connectionurl = new AMQConnectionURL(url); - - String expectedToString = "amqp://guest:********@client/vhost?brokerlist='tcp://host:1234?trust_store_password='********''"; - String actualToString = connectionurl.toString(); - assertEquals("Unexpected toString form", expectedToString, actualToString); - } - - public void testConnectionURLOptionToStringMasksSslKeyStorePassword() throws URLSyntaxException - { - String url = "amqp://guest:guest@client/vhost?brokerlist='tcp://host:1234?key_store_password='keystorepassword1';tcp://host:1235?key_store_password='keystorepassword2''"; - ConnectionURL connectionurl = new AMQConnectionURL(url); - - String expectedToString = "amqp://guest:********@client/vhost?brokerlist='tcp://host:1234?key_store_password='********';tcp://host:1235?key_store_password='********''"; - String actualToString = connectionurl.toString(); - assertEquals("Unexpected toString form", expectedToString, actualToString); - } - - /** - * Test for QPID-3662 to ensure the {@code toString()} representation is correct. - */ - public void testConnectionURLOptionToStringWithMaxPreftech() throws URLSyntaxException - { - String url = "amqp://guest:guest@client/localhost?maxprefetch='1'&brokerlist='tcp://localhost:1234?tcp_nodelay='true''"; - ConnectionURL connectionurl = new AMQConnectionURL(url); - - String expectedToString = "amqp://guest:********@client/localhost?maxprefetch='1'&brokerlist='tcp://localhost:1234?tcp_nodelay='true''"; - String actualToString = connectionurl.toString(); - assertEquals("Unexpected toString form", expectedToString, actualToString); - } - - public void testSingleTransportMultiOptionURL() throws URLSyntaxException - { - String url = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672?foo='jim'&bar='bob'&fred='jimmy'',routingkey='jim',timeout='200',immediatedelivery='true'"; - - ConnectionURL connectionurl = new AMQConnectionURL(url); - - assertTrue(connectionurl.getFailoverMethod() == null); - assertTrue(connectionurl.getUsername().equals("guest")); - assertTrue(connectionurl.getPassword().equals("guest")); - assertTrue(connectionurl.getVirtualHost().equals("/test")); - - assertTrue(connectionurl.getBrokerCount() == 1); - - BrokerDetails service = connectionurl.getBrokerDetails(0); - - assertTrue(service.getTransport().equals("tcp")); - - assertTrue(service.getHost().equals("localhost")); - assertTrue(service.getPort() == 5672); - - assertTrue(connectionurl.getOption("routingkey").equals("jim")); - assertTrue(connectionurl.getOption("timeout").equals("200")); - assertTrue(connectionurl.getOption("immediatedelivery").equals("true")); - } - - public void testNoVirtualHostURL() - { - String url = "amqp://user@?brokerlist='tcp://localhost:5672'"; - - try - { - new AMQConnectionURL(url); - fail("URL has no virtual host should not parse"); - } - catch (URLSyntaxException e) - { - // This should occur. - } - } - - public void testNoClientID() throws URLSyntaxException - { - String url = "amqp://user:@/test?brokerlist='tcp://localhost:5672'"; - - ConnectionURL connectionurl = new AMQConnectionURL(url); - - assertTrue(connectionurl.getUsername().equals("user")); - assertTrue(connectionurl.getPassword().equals("")); - assertTrue(connectionurl.getVirtualHost().equals("/test")); - - assertTrue(connectionurl.getBrokerCount() == 1); - } - - public void testClientIDWithUnderscore() throws URLSyntaxException - { - String url = "amqp://user:pass@client_id/test?brokerlist='tcp://localhost:5672'"; - - ConnectionURL connectionurl = new AMQConnectionURL(url); - - assertTrue(connectionurl.getUsername().equals("user")); - assertTrue(connectionurl.getPassword().equals("pass")); - assertTrue(connectionurl.getVirtualHost().equals("/test")); - assertTrue(connectionurl.getClientName().equals("client_id")); - - assertTrue(connectionurl.getBrokerCount() == 1); - } - - public void testWrongOptionSeparatorInOptions() - { - String url = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672;tcp://localhost:5673'+failover='roundrobin'"; - try - { - new AMQConnectionURL(url); - fail("URL Should not parse"); - } - catch (URLSyntaxException urise) - { - assertTrue(urise.getReason().equals("Unterminated option. Possible illegal option separator:'+'")); - } - - } - - - public void testNoUserDetailsProvidedWithClientID() - - { - String url = "amqp://clientID/test?brokerlist='tcp://localhost:5672;tcp://localhost:5673'"; - try - { - new AMQConnectionURL(url); - } - catch (URLSyntaxException urise) - { - fail("User information is optional in url"); - } - - } - - public void testNoUserDetailsProvidedNOClientID() - - { - String url = "amqp:///test?brokerlist='tcp://localhost:5672;tcp://localhost:5673'"; - try - { - new AMQConnectionURL(url); - } - catch (URLSyntaxException urise) - { - fail("User information is optional in url"); - } - - } - - public void testCheckVirtualhostFormat() throws URLSyntaxException - { - String url = "amqp://guest:guest@/t.-_+!=:?brokerlist='tcp://localhost:5672'"; - - AMQConnectionURL connection = new AMQConnectionURL(url); - assertTrue(connection.getVirtualHost().equals("/t.-_+!=:")); - } - - public void testCheckDefaultPort() throws URLSyntaxException - { - String url = "amqp://guest:guest@/test=:?brokerlist='tcp://localhost'"; - - AMQConnectionURL connection = new AMQConnectionURL(url); - - BrokerDetails broker = connection.getBrokerDetails(0); - assertTrue(broker.getPort() == AMQBrokerDetails.DEFAULT_PORT); - - } - - public void testCheckMissingFinalQuote() throws URLSyntaxException - { - String url = "amqp://guest:guest@id/test" + "?brokerlist='tcp://localhost:5672"; - - try - { - new AMQConnectionURL(url); - } - catch (URLSyntaxException e) - { - assertEquals(e.getMessage(), "Unterminated option at index 32: brokerlist='tcp://localhost:5672"); - } - } - - - public void testDefaultExchanges() throws URLSyntaxException - { - String url = "amqp://guest:guest@id/test" + "?defaultQueueExchange='test.direct'&defaultTopicExchange='test.topic'&temporaryQueueExchange='tmp.direct'&temporaryTopicExchange='tmp.topic'"; - - AMQConnectionURL conn = new AMQConnectionURL(url); - - assertEquals(conn.getDefaultQueueExchangeName().asString(),"test.direct"); - - assertEquals(conn.getDefaultTopicExchangeName().asString(),"test.topic"); - - assertEquals(conn.getTemporaryQueueExchangeName().asString(),"tmp.direct"); - - assertEquals(conn.getTemporaryTopicExchangeName().asString(),"tmp.topic"); - - } - - public void testSingleTransportMultiOptionOnBrokerURL() throws URLSyntaxException - { - String url = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672?foo='jim'&bar='bob'&fred='jimmy'',routingkey='jim',timeout='200',immediatedelivery='true'"; - - ConnectionURL connectionurl = new AMQConnectionURL(url); - - assertTrue(connectionurl.getFailoverMethod() == null); - assertTrue(connectionurl.getUsername().equals("guest")); - assertTrue(connectionurl.getPassword().equals("guest")); - assertTrue(connectionurl.getVirtualHost().equals("/test")); - - assertTrue(connectionurl.getBrokerCount() == 1); - - BrokerDetails service = connectionurl.getBrokerDetails(0); - - assertTrue(service.getTransport().equals("tcp")); - - assertTrue(service.getHost().equals("localhost")); - assertTrue(service.getPort() == 5672); - assertEquals("jim",service.getProperty("foo")); - assertEquals("bob",service.getProperty("bar")); - assertEquals("jimmy",service.getProperty("fred")); - - assertTrue(connectionurl.getOption("routingkey").equals("jim")); - assertTrue(connectionurl.getOption("timeout").equals("200")); - assertTrue(connectionurl.getOption("immediatedelivery").equals("true")); - } - - /** - * Test that options other than failover and brokerlist are returned in the string representation. - * <p> - * QPID-2697 - */ - public void testOptionToString() throws Exception - { - ConnectionURL url = new AMQConnectionURL("amqp://user:pass@temp/test?maxprefetch='12345'&brokerlist='tcp://localhost:5672'"); - - assertTrue("String representation should contain options and values", url.toString().contains("maxprefetch='12345'")); - } - - public void testHostNamesWithUnderScore() throws URLSyntaxException - { - String url = "amqp://guest:guest@clientid/test?brokerlist='tcp://under_score:6672'"; - - ConnectionURL connectionurl = new AMQConnectionURL(url); - - assertTrue(connectionurl.getUsername().equals("guest")); - assertTrue(connectionurl.getPassword().equals("guest")); - assertTrue(connectionurl.getVirtualHost().equals("/test")); - - assertTrue(connectionurl.getBrokerCount() == 1); - BrokerDetails service = connectionurl.getBrokerDetails(0); - assertTrue(service.getTransport().equals("tcp")); - assertTrue(service.getHost().equals("under_score")); - assertTrue(service.getPort() == 6672); - - url = "amqp://guest:guest@clientid/test?brokerlist='tcp://under_score'"; - - connectionurl = new AMQConnectionURL(url); - - assertTrue(connectionurl.getUsername().equals("guest")); - assertTrue(connectionurl.getPassword().equals("guest")); - assertTrue(connectionurl.getVirtualHost().equals("/test")); - - assertTrue(connectionurl.getBrokerCount() == 1); - service = connectionurl.getBrokerDetails(0); - assertTrue(service.getTransport().equals("tcp")); - assertTrue(service.getHost().equals("under_score")); - assertTrue(service.getPort() == 5672); - } - - - public void testRejectBehaviourPresent() throws Exception - { - String url = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672'&rejectbehaviour='server'"; - - ConnectionURL connectionURL = new AMQConnectionURL(url); - - assertTrue(connectionURL.getFailoverMethod() == null); - assertTrue(connectionURL.getUsername().equals("guest")); - assertTrue(connectionURL.getPassword().equals("guest")); - assertTrue(connectionURL.getVirtualHost().equals("/test")); - - //check that the reject behaviour option is returned as expected - assertEquals("Reject behaviour option was not as expected", "server", - connectionURL.getOption(ConnectionURL.OPTIONS_REJECT_BEHAVIOUR)); - } - - public void testRejectBehaviourNotPresent() throws URLSyntaxException - { - String url = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672'&foo='bar'"; - - ConnectionURL connectionurl = new AMQConnectionURL(url); - - assertTrue(connectionurl.getFailoverMethod() == null); - assertTrue(connectionurl.getUsername().equals("guest")); - assertTrue(connectionurl.getPassword().equals("guest")); - assertTrue(connectionurl.getVirtualHost().equals("/test")); - - //check that the reject behaviour option is null as expected - assertNull("Reject behaviour option was not as expected", - connectionurl.getOption(ConnectionURL.OPTIONS_REJECT_BEHAVIOUR)); - } - - /** - * Verify that when the ssl option is not specified, asking for the option returns null, - * such that this can later be used to verify it wasnt specified. - */ - public void testDefaultSsl() throws URLSyntaxException - { - String url = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672'&foo='bar'"; - ConnectionURL connectionURL = new AMQConnectionURL(url); - - assertNull("default ssl value should be null", connectionURL.getOption(ConnectionURL.OPTIONS_SSL)); - } - - /** - * Verify that when the ssl option is specified, asking for the option returns the value, - * such that this can later be used to verify what value it was specified as. - */ - public void testOverridingSsl() throws URLSyntaxException - { - String url = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672'&ssl='true'"; - ConnectionURL connectionURL = new AMQConnectionURL(url); - - assertTrue("value should be true", Boolean.valueOf(connectionURL.getOption(ConnectionURL.OPTIONS_SSL))); - - url = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672'&ssl='false'"; - connectionURL = new AMQConnectionURL(url); - - assertFalse("value should be false", Boolean.valueOf(connectionURL.getOption(ConnectionURL.OPTIONS_SSL))); - } - - /** - * Verify that when the {@value ConnectionURL#OPTIONS_VERIFY_QUEUE_ON_SEND} option is not - * specified, asking for the option returns null, such that this can later be used to - * verify it wasn't specified. - */ - public void testDefaultVerifyQueueOnSend() throws URLSyntaxException - { - String url = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672'&foo='bar'"; - ConnectionURL connectionURL = new AMQConnectionURL(url); - - assertNull("default ssl value should be null", connectionURL.getOption(ConnectionURL.OPTIONS_SSL)); - } - - /** - * Verify that when the {@value ConnectionURL#OPTIONS_VERIFY_QUEUE_ON_SEND} option is - * specified, asking for the option returns the value, such that this can later be used - * to verify what value it was specified as. - */ - public void testOverridingVerifyQueueOnSend() throws URLSyntaxException - { - String url = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672'&verifyQueueOnSend='true'"; - ConnectionURL connectionURL = new AMQConnectionURL(url); - - assertTrue("value should be true", Boolean.valueOf(connectionURL.getOption(ConnectionURL.OPTIONS_VERIFY_QUEUE_ON_SEND))); - - url = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672'&verifyQueueOnSend='false'"; - connectionURL = new AMQConnectionURL(url); - - assertFalse("value should be false", Boolean.valueOf(connectionURL.getOption(ConnectionURL.OPTIONS_VERIFY_QUEUE_ON_SEND))); - } - - public void testSerialization() throws Exception - { - String url = "amqp://ritchiem:bob@/test?brokerlist='tcp://localhost:5672'"; - ConnectionURL connectionurl = new AMQConnectionURL(url); - - - assertTrue(connectionurl instanceof Serializable); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(bos); - oos.writeObject(connectionurl); - oos.close(); - - ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - ObjectInputStream ois = new ObjectInputStream(bis); - Object deserializedObject = ois.readObject(); - ois.close(); - - ConnectionURL deserialisedConnectionUrl = (AMQConnectionURL) deserializedObject; - assertEquals(connectionurl, deserialisedConnectionUrl); - assertEquals(connectionurl.hashCode(), deserialisedConnectionUrl.hashCode()); - - } -} - diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/destinationurl/DestinationURLTest.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/destinationurl/DestinationURLTest.java deleted file mode 100644 index 9c9664931a..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/destinationurl/DestinationURLTest.java +++ /dev/null @@ -1,410 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.unit.client.destinationurl; - -import junit.framework.TestCase; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.client.AMQDestination; -import org.apache.qpid.client.RejectBehaviour; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.url.AMQBindingURL; -import org.apache.qpid.url.BindingURL; - -import java.net.URISyntaxException; - -public class DestinationURLTest extends TestCase -{ - private static final Logger _logger = LoggerFactory.getLogger(DestinationURLTest.class); - - public void testFullURL() throws URISyntaxException - { - - String url = "exchange.Class://exchangeName/Destination/Queue"; - - AMQBindingURL dest = new AMQBindingURL(url); - - assertTrue(url.equals(dest.toString())); - - assertTrue(dest.getExchangeClass().equalsCharSequence("exchange.Class")); - assertTrue(dest.getExchangeName().equalsCharSequence("exchangeName")); - assertTrue(dest.getDestinationName().equalsCharSequence("Destination")); - assertTrue(dest.getQueueName().equalsCharSequence("Queue")); - } - - public void testQueue() throws URISyntaxException - { - - String url = "exchangeClass://exchangeName//Queue"; - - AMQBindingURL dest = new AMQBindingURL(url); - - assertTrue(url.equals(dest.toString())); - - assertTrue(dest.getExchangeClass().equalsCharSequence("exchangeClass")); - assertTrue(dest.getExchangeName().equalsCharSequence("exchangeName")); - assertTrue(dest.getDestinationName().equalsCharSequence("")); - assertTrue(dest.getQueueName().equalsCharSequence("Queue")); - } - - public void testQueueWithOption() throws URISyntaxException - { - - String url = "exchangeClass://exchangeName//Queue?option='value'"; - - AMQBindingURL dest = new AMQBindingURL(url); - - assertTrue(url.equals(dest.toString())); - - assertTrue(dest.getExchangeClass().equalsCharSequence("exchangeClass")); - assertTrue(dest.getExchangeName().equalsCharSequence("exchangeName")); - assertTrue(dest.getDestinationName().equalsCharSequence("")); - assertTrue(dest.getQueueName().equalsCharSequence("Queue")); - assertTrue(dest.getOption("option").equals("value")); - } - - - public void testDestination() throws URISyntaxException - { - - String url = "exchangeClass://exchangeName/Destination/"; - - AMQBindingURL dest = new AMQBindingURL(url); - - assertTrue(url.equals(dest.toString())); - - assertTrue(dest.getExchangeClass().equalsCharSequence("exchangeClass")); - assertTrue(dest.getExchangeName().equalsCharSequence("exchangeName")); - assertTrue(dest.getDestinationName().equalsCharSequence("Destination")); - assertTrue(dest.getQueueName().equalsCharSequence("")); - } - - public void testDestinationWithOption() throws URISyntaxException - { - - String url = "exchangeClass://exchangeName/Destination/?option='value'"; - - AMQBindingURL dest = new AMQBindingURL(url); - - assertTrue(url.equals(dest.toString())); - - assertTrue(dest.getExchangeClass().equalsCharSequence("exchangeClass")); - assertTrue(dest.getExchangeName().equalsCharSequence("exchangeName")); - assertTrue(dest.getDestinationName().equalsCharSequence("Destination")); - assertTrue(dest.getQueueName().equalsCharSequence("")); - - assertTrue(dest.getOption("option").equals("value")); - } - - public void testDestinationWithMultiOption() throws URISyntaxException - { - - String url = "exchangeClass://exchangeName/Destination/?option='value',option2='value2'"; - - AMQBindingURL dest = new AMQBindingURL(url); - - assertTrue(dest.getExchangeClass().equalsCharSequence("exchangeClass")); - assertTrue(dest.getExchangeName().equalsCharSequence("exchangeName")); - assertTrue(dest.getDestinationName().equalsCharSequence("Destination")); - assertTrue(dest.getQueueName().equalsCharSequence("")); - - assertTrue(dest.getOption("option").equals("value")); - assertTrue(dest.getOption("option2").equals("value2")); - } - - public void testDestinationWithNoExchangeDefaultsToDirect() throws URISyntaxException - { - - String url = "IBMPerfQueue1?durable='true'"; - - AMQBindingURL dest = new AMQBindingURL(url); - - assertTrue(dest.getExchangeClass().equals(AMQShortString.valueOf(ExchangeDefaults.DIRECT_EXCHANGE_CLASS))); - assertTrue(dest.getExchangeName().equalsCharSequence("")); - assertTrue(dest.getDestinationName().equalsCharSequence("")); - assertTrue(dest.getQueueName().equalsCharSequence("IBMPerfQueue1")); - - assertTrue(dest.getOption("durable").equals("true")); - } - - public void testDestinationWithMultiBindingKeys() throws URISyntaxException - { - - String url = "exchangeClass://exchangeName/Destination/?bindingkey='key1',bindingkey='key2'"; - - AMQBindingURL dest = new AMQBindingURL(url); - - assertTrue(dest.getExchangeClass().equalsCharSequence("exchangeClass")); - assertTrue(dest.getExchangeName().equalsCharSequence("exchangeName")); - assertTrue(dest.getDestinationName().equalsCharSequence("Destination")); - assertTrue(dest.getQueueName().equalsCharSequence("")); - - assertTrue(dest.getBindingKeys().length == 2); - } - - // You can only specify only a routing key or binding key, but not both. - public void testDestinationIfOnlyRoutingKeyOrBindingKeyIsSpecified() throws URISyntaxException - { - - String url = "exchangeClass://exchangeName/Destination/?bindingkey='key1',routingkey='key2'"; - boolean exceptionThrown = false; - try - { - - new AMQBindingURL(url); - } - catch(URISyntaxException e) - { - exceptionThrown = true; - _logger.info("Exception thrown",e); - } - - assertTrue("Failed to throw an URISyntaxException when both the bindingkey and routingkey is specified",exceptionThrown); - } - - public void testExchangeOptionsNotPresent() throws URISyntaxException - { - String url = "exchangeClass://exchangeName/Destination/Queue"; - - AMQBindingURL burl = new AMQBindingURL(url); - - assertTrue(url.equals(burl.toString())); - - assertNull(burl.getOption(BindingURL.OPTION_EXCHANGE_DURABLE)); - assertNull(burl.getOption(BindingURL.OPTION_EXCHANGE_AUTODELETE)); - assertNull(burl.getOption(BindingURL.OPTION_EXCHANGE_INTERNAL)); - - class MyTestAMQDestination extends AMQDestination - { - public MyTestAMQDestination(BindingURL url) - { - super(url); - } - public boolean isNameRequired() - { - return false; - } - }; - - AMQDestination dest = new MyTestAMQDestination(burl); - assertFalse(dest.isExchangeAutoDelete()); - assertFalse(dest.isExchangeDurable()); - assertFalse(dest.isExchangeInternal()); - } - - public void testExchangeAutoDeleteOptionPresent() throws URISyntaxException - { - String url = "exchangeClass://exchangeName/Destination/Queue?" + BindingURL.OPTION_EXCHANGE_AUTODELETE + "='true'"; - - AMQBindingURL burl = new AMQBindingURL(url); - - assertTrue(url.equals(burl.toString())); - - assertEquals("true", burl.getOption(BindingURL.OPTION_EXCHANGE_AUTODELETE)); - assertNull(burl.getOption(BindingURL.OPTION_EXCHANGE_DURABLE)); - assertNull(burl.getOption(BindingURL.OPTION_EXCHANGE_INTERNAL)); - - class MyTestAMQDestination extends AMQDestination - { - public MyTestAMQDestination(BindingURL url) - { - super(url); - } - public boolean isNameRequired() - { - return false; - } - }; - - AMQDestination dest = new MyTestAMQDestination(burl); - assertTrue(dest.isExchangeAutoDelete()); - assertFalse(dest.isExchangeDurable()); - assertFalse(dest.isExchangeInternal()); - } - - public void testExchangeDurableOptionPresent() throws URISyntaxException - { - String url = "exchangeClass://exchangeName/Destination/Queue?" + BindingURL.OPTION_EXCHANGE_DURABLE + "='true'"; - - AMQBindingURL burl = new AMQBindingURL(url); - - assertTrue(url.equals(burl.toString())); - - assertEquals("true", burl.getOption(BindingURL.OPTION_EXCHANGE_DURABLE)); - assertNull(burl.getOption(BindingURL.OPTION_EXCHANGE_AUTODELETE)); - assertNull(burl.getOption(BindingURL.OPTION_EXCHANGE_INTERNAL)); - - class MyTestAMQDestination extends AMQDestination - { - public MyTestAMQDestination(BindingURL url) - { - super(url); - } - public boolean isNameRequired() - { - return false; - } - }; - - AMQDestination dest = new MyTestAMQDestination(burl); - assertTrue(dest.isExchangeDurable()); - assertFalse(dest.isExchangeAutoDelete()); - assertFalse(dest.isExchangeInternal()); - } - - public void testExchangeInternalOptionPresent() throws URISyntaxException - { - String url = "exchangeClass://exchangeName/Destination/Queue?" + BindingURL.OPTION_EXCHANGE_INTERNAL + "='true'"; - - AMQBindingURL burl = new AMQBindingURL(url); - - assertTrue(url.equals(burl.toString())); - - assertEquals("true", burl.getOption(BindingURL.OPTION_EXCHANGE_INTERNAL)); - assertNull(burl.getOption(BindingURL.OPTION_EXCHANGE_AUTODELETE)); - assertNull(burl.getOption(BindingURL.OPTION_EXCHANGE_DURABLE)); - - class MyTestAMQDestination extends AMQDestination - { - public MyTestAMQDestination(BindingURL url) - { - super(url); - } - public boolean isNameRequired() - { - return false; - } - }; - - AMQDestination dest = new MyTestAMQDestination(burl); - assertTrue(dest.isExchangeInternal()); - assertFalse(dest.isExchangeDurable()); - assertFalse(dest.isExchangeAutoDelete()); - } - - public void testRejectBehaviourPresent() throws URISyntaxException - { - String url = "exchangeClass://exchangeName/Destination/Queue?rejectbehaviour='server'"; - - AMQBindingURL burl = new AMQBindingURL(url); - - assertTrue(url.equals(burl.toString())); - assertTrue(burl.getExchangeClass().equalsCharSequence("exchangeClass")); - assertTrue(burl.getExchangeName().equalsCharSequence("exchangeName")); - assertTrue(burl.getDestinationName().equalsCharSequence("Destination")); - assertTrue(burl.getQueueName().equalsCharSequence("Queue")); - - //check that the MaxDeliveryCount property has the right value - assertEquals("server",burl.getOption(BindingURL.OPTION_REJECT_BEHAVIOUR)); - - //check that the MaxDeliveryCount value is correctly returned from an AMQDestination - class MyTestAMQDestination extends AMQDestination - { - public MyTestAMQDestination(BindingURL url) - { - super(url); - } - public boolean isNameRequired() - { - return false; - } - }; - - AMQDestination dest = new MyTestAMQDestination(burl); - assertEquals("Reject behaviour is unexpected", RejectBehaviour.SERVER, dest.getRejectBehaviour()); - } - - public void testRejectBehaviourNotPresent() throws URISyntaxException - { - String url = "exchangeClass://exchangeName/Destination/Queue"; - - AMQBindingURL burl = new AMQBindingURL(url); - - assertTrue(url.equals(burl.toString())); - - assertTrue(burl.getExchangeClass().equalsCharSequence("exchangeClass")); - assertTrue(burl.getExchangeName().equalsCharSequence("exchangeName")); - assertTrue(burl.getDestinationName().equalsCharSequence("Destination")); - assertTrue(burl.getQueueName().equalsCharSequence("Queue")); - - class MyTestAMQDestination extends AMQDestination - { - public MyTestAMQDestination(BindingURL url) - { - super(url); - } - public boolean isNameRequired() - { - return false; - } - }; - - AMQDestination dest = new MyTestAMQDestination(burl); - assertNull("Reject behaviour is unexpected", dest.getRejectBehaviour()); - } - - public void testBindingUrlWithoutDestinationAndQueueName() throws Exception - { - AMQBindingURL bindingURL = new AMQBindingURL("topic://amq.topic//?routingkey='testTopic'"); - assertEquals("Unexpected queue name", AMQShortString.EMPTY_STRING, bindingURL.getQueueName()); - assertEquals("Unexpected destination", AMQShortString.EMPTY_STRING, bindingURL.getDestinationName()); - assertEquals("Unexpected routing key", AMQShortString.valueOf("testTopic"), bindingURL.getRoutingKey()); - } - - public void testBindingUrlWithoutDestinationAndMissedQueueName() throws Exception - { - AMQBindingURL bindingURL = new AMQBindingURL("topic://amq.topic/?routingkey='testTopic'"); - assertEquals("Unexpected queue name", AMQShortString.EMPTY_STRING, bindingURL.getQueueName()); - assertEquals("Unexpected destination", AMQShortString.EMPTY_STRING, bindingURL.getDestinationName()); - assertEquals("Unexpected routing key", AMQShortString.valueOf("testTopic"), bindingURL.getRoutingKey()); - } - - public void testBindingUrlWithoutQueueName() throws Exception - { - AMQBindingURL bindingURL = new AMQBindingURL("topic://amq.topic/destination/?routingkey='testTopic'"); - assertEquals("Unexpected queue name", AMQShortString.EMPTY_STRING, bindingURL.getQueueName()); - assertEquals("Unexpected destination", AMQShortString.valueOf("destination"), bindingURL.getDestinationName()); - assertEquals("Unexpected routing key", AMQShortString.valueOf("testTopic"), bindingURL.getRoutingKey()); - } - - public void testBindingUrlWithQueueNameWithoutDestination() throws Exception - { - AMQBindingURL bindingURL = new AMQBindingURL("topic://amq.topic//queueName?routingkey='testTopic'"); - assertEquals("Unexpected queue name", AMQShortString.valueOf("queueName"), bindingURL.getQueueName()); - assertEquals("Unexpected destination", AMQShortString.EMPTY_STRING, bindingURL.getDestinationName()); - assertEquals("Unexpected routing key", AMQShortString.valueOf("testTopic"), bindingURL.getRoutingKey()); - } - - public void testBindingUrlWithQueueNameAndDestination() throws Exception - { - AMQBindingURL bindingURL = new AMQBindingURL("topic://amq.topic/destination/queueName?routingkey='testTopic'"); - assertEquals("Unexpected queue name", AMQShortString.valueOf("queueName"), bindingURL.getQueueName()); - assertEquals("Unexpected destination", AMQShortString.valueOf("destination"), bindingURL.getDestinationName()); - assertEquals("Unexpected routing key", AMQShortString.valueOf("testTopic"), bindingURL.getRoutingKey()); - } - - public static junit.framework.Test suite() - { - return new junit.framework.TestSuite(DestinationURLTest.class); - } -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/message/BytesMessageTest.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/message/BytesMessageTest.java deleted file mode 100644 index 1ab3ad0573..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/message/BytesMessageTest.java +++ /dev/null @@ -1,568 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.unit.client.message; - -import junit.framework.TestCase; - -import org.apache.qpid.client.message.JMSBytesMessage; -import org.apache.qpid.client.message.TestMessageHelper; - -import javax.jms.MessageEOFException; -import javax.jms.MessageFormatException; -import javax.jms.MessageNotReadableException; -import javax.jms.MessageNotWriteableException; -import java.util.HashMap; - -public class BytesMessageTest extends TestCase -{ - /** - * Tests that on creation a call to getBodyLength() throws an exception - * if null was passed in during creation - */ - public void testNotReadableOnCreationWithNull() throws Exception - { - try - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.getBodyLength(); - fail("expected exception did not occur"); - } - catch (MessageNotReadableException m) - { - // ok - } - catch (Exception e) - { - fail("expected MessageNotReadableException, got " + e); - } - } - - public void testResetMakesReadble() throws Exception - { - try - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.writeInt(10); - bm.reset(); - bm.writeInt(12); - fail("expected exception did not occur"); - } - catch (MessageNotWriteableException m) - { - // ok - } - catch (Exception e) - { - fail("expected MessageNotWriteableException, got " + e); - } - } - - public void testClearBodyMakesWritable() throws Exception - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.writeInt(10); - bm.reset(); - bm.clearBody(); - bm.writeInt(10); - } - - public void testWriteBoolean() throws Exception - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.writeBoolean(true); - bm.writeBoolean(false); - bm.reset(); - boolean val = bm.readBoolean(); - assertEquals(true, val); - val = bm.readBoolean(); - assertEquals(false, val); - } - - public void testWriteInt() throws Exception - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.writeInt(10); - bm.reset(); - long len = bm.getBodyLength(); - assertTrue(len == 4); - int val = bm.readInt(); - assertTrue(val == 10); - } - - public void testWriteString() throws Exception - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.writeUTF("Bananas"); - bm.reset(); - String res = bm.readUTF(); - assertEquals("Bananas", res); - } - - public void testWriteBytes() throws Exception - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - byte[] bytes = {1,2,3,4}; - bm.writeBytes(bytes, 1, 2); - bm.reset(); - bytes = new byte[2]; - bm.readBytes(bytes); - assertEquals(2, bytes[0]); - assertEquals(3, bytes[1]); - } - - public void testWriteObject() throws Exception - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.writeObject(new Boolean(true)); - bm.writeObject(new Boolean(false)); - bm.writeObject(new Byte((byte)2)); - bm.writeObject(new byte[]{1,2,3,4}); - bm.writeObject(new Character('g')); - bm.writeObject(new Short((short) 29)); - bm.writeObject(new Integer(101)); - bm.writeObject(new Long(50003222L)); - bm.writeObject("Foobar"); - bm.writeObject(new Float(1.7f)); - bm.writeObject(new Double(8.7d)); - bm.reset(); - assertTrue(bm.readBoolean()); - assertTrue(!bm.readBoolean()); - assertEquals((byte)2, bm.readByte()); - byte[] bytes = new byte[4]; - bm.readBytes(bytes); - assertEquals('g', bm.readChar()); - assertEquals((short) 29, bm.readShort()); - assertEquals(101, bm.readInt()); - assertEquals(50003222L, bm.readLong()); - assertEquals("Foobar", bm.readUTF()); - assertEquals(1.7f, bm.readFloat()); - assertEquals(8.7d, bm.readDouble()); - } - - public void testWriteObjectRejectsNonPrimitives() throws Exception - { - try - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.writeObject(new HashMap()); - fail("expected MessageFormatException was not thrown"); - } - catch (MessageFormatException e) - { - // pass - } - } - - public void testWriteObjectThrowsNPE() throws Exception - { - try - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.writeObject(null); - fail("expected exception did not occur"); - } - catch (NullPointerException n) - { - // ok - } - catch (Exception e) - { - fail("expected NullPointerException, got " + e); - } - } - - public void testReadBoolean() throws Exception - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.writeBoolean(true); - bm.reset(); - boolean result = bm.readBoolean(); - assertTrue(result); - } - - public void testReadUnsignedByte() throws Exception - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.writeByte((byte) 9); - bm.reset(); - int result = bm.readUnsignedByte(); - assertEquals(9, result); - } - - public void testReadUnsignedShort() throws Exception - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.writeShort((byte) 9); - bm.reset(); - int result = bm.readUnsignedShort(); - assertEquals(9, result); - } - - public void testReadBytesChecksNull() throws Exception - { - try - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.readBytes(null); - } - catch (IllegalArgumentException e) - { - // pass - } - - try - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.readBytes(null, 1); - } - catch (IllegalArgumentException e) - { - // pass - } - } - - public void testReadBytesChecksMaxSize() throws Exception - { - try - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - byte[] bytes = new byte[100]; - bm.readBytes(bytes, 120); - } - catch (IllegalArgumentException e) - { - // pass - } - } - - public void testReadBytesReturnsCorrectLengths() throws Exception - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - byte[] bytes = {2, 3}; - bm.writeBytes(bytes); - bm.reset(); - int len = bm.readBytes(bytes); - assertEquals(2, len); - len = bm.readBytes(bytes); - assertEquals(-1, len); - len = bm.readBytes(bytes, 2); - assertEquals(-1, len); - bm.reset(); - len = bm.readBytes(bytes, 2); - assertEquals(2, len); - bm.reset(); - len = bm.readBytes(bytes, 1); - assertEquals(1, len); - - } - - public void testEOFByte() throws Exception - { - try - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.writeByte((byte)1); - bm.reset(); - bm.readByte(); - // should throw - bm.readByte(); - fail("expected exception did not occur"); - } - catch (MessageEOFException m) - { - // ok - } - catch (Exception e) - { - fail("expected MessageEOFException, got " + e); - } - } - - public void testEOFUnsignedByte() throws Exception - { - try - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.writeByte((byte)1); - bm.reset(); - bm.readByte(); - // should throw - bm.readUnsignedByte(); - fail("expected exception did not occur"); - } - catch (MessageEOFException m) - { - // ok - } - catch (Exception e) - { - fail("expected MessageEOFException, got " + e); - } - } - - public void testEOFBoolean() throws Exception - { - try - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.writeBoolean(true); - bm.reset(); - bm.readBoolean(); - // should throw - bm.readBoolean(); - fail("expected exception did not occur"); - } - catch (MessageEOFException m) - { - // ok - } - catch (Exception e) - { - fail("expected MessageEOFException, got " + e); - } - } - - public void testEOFChar() throws Exception - { - try - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.writeChar('A'); - bm.reset(); - bm.readChar(); - // should throw - bm.readChar(); - fail("expected exception did not occur"); - } - catch (MessageEOFException m) - { - // ok - } - catch (Exception e) - { - fail("expected MessageEOFException, got " + e); - } - } - - public void testEOFDouble() throws Exception - { - try - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.writeDouble(1.3d); - bm.reset(); - bm.readDouble(); - // should throw - bm.readDouble(); - fail("expected exception did not occur"); - } - catch (MessageEOFException m) - { - // ok - } - catch (Exception e) - { - fail("expected MessageEOFException, got " + e); - } - } - - public void testEOFFloat() throws Exception - { - try - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.writeFloat(1.3f); - bm.reset(); - bm.readFloat(); - // should throw - bm.readFloat(); - fail("expected exception did not occur"); - } - catch (MessageEOFException m) - { - // ok - } - catch (Exception e) - { - fail("expected MessageEOFException, got " + e); - } - } - - public void testEOFInt() throws Exception - { - try - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.writeInt(99); - bm.reset(); - bm.readInt(); - // should throw - bm.readInt(); - fail("expected exception did not occur"); - } - catch (MessageEOFException m) - { - // ok - } - catch (Exception e) - { - fail("expected MessageEOFException, got " + e); - } - } - - public void testEOFLong() throws Exception - { - try - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.writeLong(4L); - bm.reset(); - bm.readLong(); - // should throw - bm.readLong(); - fail("expected exception did not occur"); - } - catch (MessageEOFException m) - { - // ok - } - catch (Exception e) - { - fail("expected MessageEOFException, got " + e); - } - } - - public void testEOFShort() throws Exception - { - try - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.writeShort((short)4); - bm.reset(); - bm.readShort(); - // should throw - bm.readShort(); - fail("expected exception did not occur"); - } - catch (MessageEOFException m) - { - // ok - } - catch (Exception e) - { - fail("expected MessageEOFException, got " + e); - } - } - - public void testEOFUnsignedShort() throws Exception - { - try - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.writeShort((short)4); - bm.reset(); - bm.readUnsignedShort(); - // should throw - bm.readUnsignedShort(); - fail("expected exception did not occur"); - } - catch (MessageEOFException m) - { - // ok - } - catch (Exception e) - { - fail("expected MessageEOFException, got " + e); - } - } - - /** - * Tests that the readBytes() method populates the passed in array - * correctly - * @throws Exception - */ - public void testReadBytes() throws Exception - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.writeByte((byte)3); - bm.writeByte((byte)4); - bm.reset(); - byte[] result = new byte[2]; - int count = bm.readBytes(result); - assertEquals((byte)3, result[0]); - assertEquals((byte)4, result[1]); - assertEquals(2, count); - } - - public void testReadBytesEOF() throws Exception - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.writeByte((byte)3); - bm.writeByte((byte)4); - bm.reset(); - byte[] result = new byte[2]; - bm.readBytes(result); - int count = bm.readBytes(result); - assertEquals(-1, count); - } - - public void testReadBytesWithLargerArray() throws Exception - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.writeByte((byte)3); - bm.writeByte((byte)4); - bm.reset(); - byte[] result = new byte[3]; - int count = bm.readBytes(result); - assertEquals(2, count); - assertEquals((byte)3, result[0]); - assertEquals((byte)4, result[1]); - assertEquals((byte)0, result[2]); - } - - public void testReadBytesWithCount() throws Exception - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.writeByte((byte)3); - bm.writeByte((byte)4); - bm.writeByte((byte)5); - bm.reset(); - byte[] result = new byte[3]; - int count = bm.readBytes(result, 2); - assertEquals(2, count); - assertEquals((byte)3, result[0]); - assertEquals((byte)4, result[1]); - assertEquals((byte)0, result[2]); - } - - public void testToBodyStringWithNull() throws Exception - { - JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); - bm.reset(); - String result = bm.toBodyString(); - assertEquals("\"\"", result); - } - - public static junit.framework.Test suite() - { - return new junit.framework.TestSuite(BytesMessageTest.class); - } -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/message/MapMessageTest.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/message/MapMessageTest.java deleted file mode 100644 index 41cf79e963..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/message/MapMessageTest.java +++ /dev/null @@ -1,383 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.unit.client.message; - -import org.junit.Assert; -import junit.framework.TestCase; - -import org.apache.qpid.client.message.JMSMapMessage; -import org.apache.qpid.client.message.TestMessageHelper; - -import javax.jms.JMSException; -import javax.jms.MessageFormatException; - - -public class MapMessageTest extends TestCase -{ - - //Test Lookups - - public void testBooleanLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - - mm.setBoolean("value", true); - Assert.assertEquals(true, mm.getBoolean("value")); - Assert.assertEquals("true", mm.getString("value")); - } - catch (JMSException e) - { - Assert.fail("JMSException received." + e); - } - } - - public void testByteLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - mm.setByte("value", Byte.MAX_VALUE); - - Assert.assertEquals(Byte.MAX_VALUE, mm.getByte("value")); - Assert.assertEquals((short) Byte.MAX_VALUE, mm.getShort("value")); - Assert.assertEquals(Byte.MAX_VALUE, mm.getInt("value")); - Assert.assertEquals((long) Byte.MAX_VALUE, mm.getLong("value")); - Assert.assertEquals("" + Byte.MAX_VALUE, mm.getString("value")); - - } - catch (JMSException e) - { - Assert.fail("JMSException received." + e); - } - } - - public void testShortLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - mm.setShort("value", Short.MAX_VALUE); - Assert.assertEquals(Short.MAX_VALUE, mm.getShort("value")); - Assert.assertEquals((int) Short.MAX_VALUE, mm.getInt("value")); - Assert.assertEquals((long) Short.MAX_VALUE, mm.getLong("value")); - Assert.assertEquals("" + Short.MAX_VALUE, mm.getString("value")); - } - catch (JMSException e) - { - Assert.fail("JMSException received." + e); - } - } - - - public void testCharLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - - mm.setChar("value", 'c'); - Assert.assertEquals('c', mm.getChar("value")); - Assert.assertEquals("c", mm.getString("value")); - } - catch (JMSException e) - { - Assert.fail("JMSException received." + e); - } - - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - - mm.setString("value", null); - mm.getChar("value"); - fail("Expected NullPointerException"); - - } - catch (NullPointerException e) - { - ; // pass - } - catch (JMSException e) - { - Assert.fail("JMSException received." + e); - } - - - - } - - public void testDoubleLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - mm.setDouble("value", Double.MAX_VALUE); - Assert.assertEquals(Double.MAX_VALUE, mm.getDouble("value"), 0d); - Assert.assertEquals("" + Double.MAX_VALUE, mm.getString("value")); - } - catch (JMSException e) - { - Assert.fail("JMSException received." + e); - } - } - - public void testFloatLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - mm.setFloat("value", Float.MAX_VALUE); - Assert.assertEquals(Float.MAX_VALUE, mm.getFloat("value"), 0f); - Assert.assertEquals(Double.valueOf(Float.MAX_VALUE), mm.getDouble("value"), 0d); - Assert.assertEquals("" + Float.MAX_VALUE, mm.getString("value")); - } - catch (JMSException e) - { - Assert.fail("JMSException received." + e); - } - } - - public void testIntLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - mm.setInt("value", Integer.MAX_VALUE); - Assert.assertEquals(Integer.MAX_VALUE, mm.getInt("value")); - Assert.assertEquals((long) Integer.MAX_VALUE, mm.getLong("value")); - Assert.assertEquals("" + Integer.MAX_VALUE, mm.getString("value")); - } - catch (JMSException e) - { - Assert.fail("JMSException received." + e); - } - } - - public void testLongLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - mm.setLong("value", Long.MAX_VALUE); - Assert.assertEquals(Long.MAX_VALUE, mm.getLong("value")); - Assert.assertEquals("" + Long.MAX_VALUE, mm.getString("value")); - } - catch (JMSException e) - { - Assert.fail("JMSException received." + e); - } - } - - public void testBytesLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - byte[] bytes = {99, 98, 97, 96, 95}; - mm.setBytes("bytes", bytes); - assertBytesEqual(bytes, mm.getBytes("bytes")); - } - catch (JMSException e) - { - Assert.fail("JMSException received." + e); - } - } - - // Failed Lookups - - public void testFailedBooleanLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - Assert.assertEquals(false, mm.getBoolean("int")); - } - catch (JMSException e) - { - Assert.fail("JMSException received." + e); - } - } - - public void testFailedByteLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - mm.getByte("random"); - Assert.fail("NumberFormatException expected"); - } - catch (NumberFormatException e) - { - //normal execution - } - catch (JMSException e) - { - Assert.fail("JMSException received:" + e); - } - - } - - public void testFailedBytesLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - mm.getBytes("random"); - Assert.fail("MessageFormatException expected"); - } - catch (MessageFormatException mfe) - { - //normal path - } - catch (JMSException e) - { - Assert.fail("JMSException received:" + e); - } - } - - public void testFailedCharLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - mm.getChar("random"); - Assert.fail("MessageFormatException expected"); - } - catch (MessageFormatException e) - { - //normal execution - } - catch (JMSException e) - { - Assert.fail("JMSException received:" + e); - } - } - - public void testFailedDoubleLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - mm.getDouble("random"); - Assert.fail("NullPointerException should be received."); - } - catch (NullPointerException e) - { - //normal execution - } - catch (JMSException e) - { - Assert.fail("JMSException received:" + e); - } - } - - public void testFailedFloatLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - mm.getFloat("random"); - Assert.fail("NullPointerException should be received."); - } - catch (NullPointerException e) - { - //normal execution - } - catch (JMSException e) - { - Assert.fail("JMSException received:" + e); - } - } - - public void testFailedIntLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - mm.getInt("random"); - Assert.fail("NumberFormatException should be received."); - } - catch (NumberFormatException e) - { - //normal execution - } - catch (JMSException e) - { - Assert.fail("JMSException received:" + e); - } - } - - public void testFailedLongLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - mm.getLong("random"); - Assert.fail("NumberFormatException should be received."); - } - catch (NumberFormatException e) - { - //normal execution - } - catch (JMSException e) - { - Assert.fail("JMSException received:" + e); - } - } - - public void testFailedShortLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - mm.getShort("random"); - Assert.fail("NumberFormatException should be received."); - } - catch (NumberFormatException e) - { - //normal execution - } - catch (JMSException e) - { - Assert.fail("JMSException received:" + e); - } - } - - - private void assertBytesEqual(byte[] expected, byte[] actual) - { - Assert.assertEquals(expected.length, actual.length); - - for (int index = 0; index < expected.length; index++) - { - Assert.assertEquals(expected[index], actual[index]); - } - } - - public static junit.framework.Test suite() - { - return new junit.framework.TestSuite(MapMessageTest.class); - } - - -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/message/ObjectMessageUnitTest.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/message/ObjectMessageUnitTest.java deleted file mode 100644 index a2c5bf624f..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/message/ObjectMessageUnitTest.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.test.unit.client.message; - -import org.apache.qpid.client.message.JMSObjectMessage; -import org.apache.qpid.client.message.TestMessageHelper; -import org.apache.qpid.test.utils.QpidTestCase; - -import java.util.ArrayList; -import java.util.Arrays; - -public class ObjectMessageUnitTest extends QpidTestCase -{ - private JMSObjectMessage _om; - - protected void setUp() throws Exception - { - super.setUp(); - _om = TestMessageHelper.newJMSObjectMessage(); - } - - /** - * Test that setObject with a primitive works - */ - public void testSetObjectWithBooleanPrimitive() throws Exception - { - _om.setObject(true); - - //make the message readable - Object object = _om.getObject(); - - assertTrue("Unexpected type returned", object instanceof Boolean); - assertEquals("Unexpected value returned", true, object); - } - - /** - * Test that setObject with a serializable Object works - */ - public void testSetObjectWithString() throws Exception - { - _om.setObject("test string"); - - //make the message readable - Object object = _om.getObject(); - - assertTrue("Unexpected type returned", object instanceof String); - assertEquals("Unexpected value returned", "test string", object); - } - - /** - * Test that setObject with a Collection of serializable's works, returning - * the items in the list when deserialized and ignoring any values - * added to the collection after setObject() is called on the message. - */ - public void testSetObjectWithArrayListOfInteger() throws Exception - { - ArrayList<Integer> list = new ArrayList<Integer>(); - list.add(1234); - list.add(Integer.MIN_VALUE); - list.add(Integer.MAX_VALUE); - - _om.setObject(list); - - //add something extra to the list now, and check it isn't in the value read back - list.add(0); - - //make the message readable - - //retrieve the Object - Object object = _om.getObject(); - - ArrayList<?> returnedList = null; - if(object instanceof ArrayList<?>) - { - returnedList = (ArrayList<?>) object; - } - else - { - fail("returned object was not an ArrayList"); - } - - //verify the extra added Integer was not present, then remove it from original list again and compare contents with the returned list - assertFalse("returned list should not have had the value added after setObject() was used", returnedList.contains(0)); - list.remove(Integer.valueOf(0)); - assertTrue("list contents were not equal", Arrays.equals(list.toArray(), returnedList.toArray())); - } -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/message/StreamMessageTest.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/message/StreamMessageTest.java deleted file mode 100644 index 648e4b0c83..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/message/StreamMessageTest.java +++ /dev/null @@ -1,622 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.unit.client.message; - -import junit.framework.TestCase; - -import org.apache.qpid.client.message.JMSStreamMessage; -import org.apache.qpid.client.message.TestMessageHelper; - -import javax.jms.JMSException; -import javax.jms.MessageEOFException; -import javax.jms.MessageFormatException; -import javax.jms.MessageNotReadableException; -import javax.jms.MessageNotWriteableException; -import javax.jms.StreamMessage; -import java.util.HashMap; - -/** - * @author Apache Software Foundation - */ -public class StreamMessageTest extends TestCase -{ - /** - * Tests that on creation a call to getBodyLength() throws an exception - * if null was passed in during creation - */ - public void testNotReadableOnCreationWithNull() throws Exception - { - try - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.readByte(); - fail("expected exception did not occur"); - } - catch (MessageNotReadableException m) - { - // ok - } - catch (Exception e) - { - fail("expected MessageNotReadableException, got " + e); - } - } - - public void testResetMakesReadble() throws Exception - { - try - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeInt(10); - bm.reset(); - bm.writeInt(12); - fail("expected exception did not occur"); - } - catch (MessageNotWriteableException m) - { - // ok - } - catch (Exception e) - { - fail("expected MessageNotWriteableException, got " + e); - } - } - - public void testClearBodyMakesWritable() throws Exception - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeInt(10); - bm.reset(); - bm.clearBody(); - bm.writeInt(10); - } - - public void testWriteBoolean() throws Exception - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeBoolean(true); - bm.writeBoolean(false); - bm.reset(); - boolean val = bm.readBoolean(); - assertEquals(true, val); - val = bm.readBoolean(); - assertEquals(false, val); - } - - public void testWriteInt() throws Exception - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeInt(10); - bm.reset(); - int val = bm.readInt(); - assertTrue(val == 10); - } - - public void testWriteString() throws Exception - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeString("Bananas"); - bm.reset(); - String res = bm.readString(); - assertEquals("Bananas", res); - } - - public void testWriteBytes() throws Exception - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - byte[] bytes = {1,2,3,4}; - bm.writeBytes(bytes, 1, 2); - bm.reset(); - bytes = new byte[2]; - bm.readBytes(bytes); - assertEquals(2, bytes[0]); - assertEquals(3, bytes[1]); - } - - public void testWriteObject() throws Exception - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeObject(new Boolean(true)); - bm.writeObject(new Boolean(false)); - bm.writeObject(new Byte((byte)2)); - bm.writeObject(new byte[]{1,2,3,4}); - bm.writeObject(new Character('g')); - bm.writeObject(new Short((short) 29)); - bm.writeObject(new Integer(101)); - bm.writeObject(new Long(50003222L)); - bm.writeObject("Foobar"); - bm.writeObject(new Float(1.7f)); - bm.writeObject(new Double(8.7d)); - bm.reset(); - assertTrue(bm.readBoolean()); - assertTrue(!bm.readBoolean()); - assertEquals((byte)2, bm.readByte()); - byte[] bytes = new byte[4]; - bm.readBytes(bytes); - assertEquals('g', bm.readChar()); - assertEquals((short) 29, bm.readShort()); - assertEquals(101, bm.readInt()); - assertEquals(50003222L, bm.readLong()); - assertEquals("Foobar", bm.readString()); - assertEquals(1.7f, bm.readFloat()); - assertEquals(8.7d, bm.readDouble()); - } - - public void testWriteObjectRejectsNonPrimitives() throws Exception - { - try - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeObject(new HashMap()); - fail("expected MessageFormatException was not thrown"); - } - catch (MessageFormatException e) - { - // pass - } - } - - public void testReadBoolean() throws Exception - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeBoolean(true); - bm.reset(); - boolean result = bm.readBoolean(); - assertTrue(result); - } - - public void testReadBytesChecksNull() throws Exception - { - try - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.readBytes(null); - } - catch (IllegalArgumentException e) - { - // pass - } - } - - public void testReadBytesReturnsCorrectLengths() throws Exception - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - byte[] bytes = {2, 3}; - bm.writeBytes(bytes); - bm.writeBytes(null); - bm.writeBytes(new byte[]{}); - bm.reset(); - int len = bm.readBytes(bytes); - assertEquals(2, len); - len = bm.readBytes(bytes); - assertEquals(-1, len); - len = bm.readBytes(bytes); - assertEquals(-1, len); - len = bm.readBytes(bytes); - assertEquals(0, len); - } - - public void testReadBytesFollowedByPrimitive() throws Exception - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeBytes(new byte[]{2, 3, 4, 5, 6, 7, 8}); - bm.writeBytes(new byte[]{2, 3, 4, 5, 6, 7}); - bm.writeString("Foo"); - bm.reset(); - int len; - do - { - len = bm.readBytes(new byte[2]); - } - while (len == 2); - - do - { - len = bm.readBytes(new byte[2]); - } - while (len == 2); - - assertEquals("Foo", bm.readString()); - } - - public void testReadMultipleByteArrays() throws Exception - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - byte[] bytes = {2, 3, 4}; - bm.writeBytes(bytes); - bm.writeBytes(bytes); - bm.reset(); - byte[] result = new byte[2]; - int len = bm.readBytes(result); - assertEquals(2, len); - len = bm.readBytes(result); - assertEquals(1, len); - len = bm.readBytes(result); - assertEquals(2, len); - } - - public void testEOFByte() throws Exception - { - try - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeByte((byte)1); - bm.reset(); - bm.readByte(); - // should throw - bm.readByte(); - fail("expected exception did not occur"); - } - catch (MessageEOFException m) - { - // ok - } - catch (Exception e) - { - fail("expected MessageEOFException, got " + e); - } - } - - public void testEOFBoolean() throws Exception - { - try - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeBoolean(true); - bm.reset(); - bm.readBoolean(); - // should throw - bm.readBoolean(); - fail("expected exception did not occur"); - } - catch (MessageEOFException m) - { - // ok - } - catch (Exception e) - { - fail("expected MessageEOFException, got " + e); - } - } - - public void testEOFChar() throws Exception - { - try - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeChar('A'); - bm.reset(); - bm.readChar(); - // should throw - bm.readChar(); - fail("expected exception did not occur"); - } - catch (MessageEOFException m) - { - // ok - } - catch (Exception e) - { - fail("expected MessageEOFException, got " + e); - } - } - - public void testEOFDouble() throws Exception - { - try - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeDouble(1.3d); - bm.reset(); - bm.readDouble(); - // should throw - bm.readDouble(); - fail("expected exception did not occur"); - } - catch (MessageEOFException m) - { - // ok - } - catch (Exception e) - { - fail("expected MessageEOFException, got " + e); - } - } - - public void testEOFFloat() throws Exception - { - try - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeFloat(1.3f); - bm.reset(); - bm.readFloat(); - // should throw - bm.readFloat(); - fail("expected exception did not occur"); - } - catch (MessageEOFException m) - { - // ok - } - catch (Exception e) - { - fail("expected MessageEOFException, got " + e); - } - } - - public void testEOFInt() throws Exception - { - try - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeInt(99); - bm.reset(); - bm.readInt(); - // should throw - bm.readInt(); - fail("expected exception did not occur"); - } - catch (MessageEOFException m) - { - // ok - } - catch (Exception e) - { - fail("expected MessageEOFException, got " + e); - } - } - - public void testEOFLong() throws Exception - { - try - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeLong(4L); - bm.reset(); - bm.readLong(); - // should throw - bm.readLong(); - fail("expected exception did not occur"); - } - catch (MessageEOFException m) - { - // ok - } - catch (Exception e) - { - fail("expected MessageEOFException, got " + e); - } - } - - public void testEOFShort() throws Exception - { - try - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeShort((short)4); - bm.reset(); - bm.readShort(); - // should throw - bm.readShort(); - fail("expected exception did not occur"); - } - catch (MessageEOFException m) - { - // ok - } - catch (Exception e) - { - fail("expected MessageEOFException, got " + e); - } - } - - public void testToBodyStringWithNull() throws Exception - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.reset(); - String result = bm.toBodyString(); - assertEquals("\"\"", result); - } - - private void checkConversionsFail(StreamMessage sm, int[] conversions) throws JMSException - { - for (int conversion : conversions) - { - try - { - switch (conversion) - { - case 0: - sm.readBoolean(); - break; - case 1: - sm.readByte(); - break; - case 2: - sm.readShort(); - break; - case 3: - sm.readChar(); - break; - case 4: - sm.readInt(); - break; - case 5: - sm.readLong(); - break; - case 6: - sm.readFloat(); - break; - case 7: - sm.readDouble(); - break; - case 8: - sm.readString(); - break; - case 9: - sm.readBytes(new byte[3]); - break; - } - fail("MessageFormatException was not thrown"); - } - catch (MessageFormatException e) - { - // PASS - } - sm.reset(); - } - } - public void testBooleanConversions() throws Exception - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeBoolean(true); - bm.reset(); - String result = bm.readString(); - assertEquals("true", result); - bm.reset(); - checkConversionsFail(bm, new int[]{1,2,3,4,5,6,7,9}); - } - - public void testByteConversions() throws Exception - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeByte((byte) 43); - bm.reset(); - assertEquals(43, bm.readShort()); - bm.reset(); - assertEquals(43, bm.readInt()); - bm.reset(); - assertEquals(43, bm.readLong()); - bm.reset(); - String result = bm.readString(); - assertEquals("43", result); - bm.reset(); - checkConversionsFail(bm, new int[]{0, 3, 6, 7, 9}); - } - - public void testShortConversions() throws Exception - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeShort((short) 87); - bm.reset(); - assertEquals(87, bm.readInt()); - bm.reset(); - assertEquals(87, bm.readLong()); - bm.reset(); - assertEquals("87", bm.readString()); - bm.reset(); - checkConversionsFail(bm, new int[]{0, 1, 3, 6, 7, }); - } - - public void testCharConversions() throws Exception - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeChar('d'); - bm.reset(); - assertEquals("d", bm.readString()); - bm.reset(); - checkConversionsFail(bm, new int[]{0, 1, 2, 4, 5, 6, 7, 9}); - } - - public void testIntConversions() throws Exception - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeInt(167); - bm.reset(); - assertEquals(167, bm.readLong()); - bm.reset(); - assertEquals("167", bm.readString()); - bm.reset(); - checkConversionsFail(bm, new int[]{0, 1, 2, 3, 6, 7, 9}); - } - - public void testLongConversions() throws Exception - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeLong(1678); - bm.reset(); - assertEquals("1678", bm.readString()); - bm.reset(); - checkConversionsFail(bm, new int[]{0, 1, 2, 3, 4, 6, 7, 9}); - } - - public void testFloatConversions() throws Exception - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeFloat(6.2f); - bm.reset(); - assertEquals(6.2d, bm.readDouble(), 0.01); - bm.reset(); - assertEquals("6.2", bm.readString()); - bm.reset(); - checkConversionsFail(bm, new int[]{0, 1, 2, 3, 4, 5, 9}); - } - - public void testDoubleConversions() throws Exception - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeDouble(88.35d); - bm.reset(); - assertEquals("88.35", bm.readString()); - bm.reset(); - checkConversionsFail(bm, new int[]{0, 1, 2, 3, 4, 5, 6, 9}); - } - - public void testStringConversions() throws Exception - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeString("true"); - bm.reset(); - assertEquals(true, bm.readBoolean()); - bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeString("2"); - bm.reset(); - assertEquals((byte)2, bm.readByte()); - bm.reset(); - assertEquals((short)2, bm.readShort()); - bm.reset(); - assertEquals(2, bm.readInt()); - bm.reset(); - assertEquals((long)2, bm.readLong()); - bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeString("5.7"); - bm.reset(); - assertEquals(5.7f, bm.readFloat()); - bm.reset(); - assertEquals(5.7d, bm.readDouble()); - } - - public void testNulls() throws Exception - { - JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); - bm.writeString(null); - bm.writeObject(null); - bm.reset(); - assertNull(bm.readObject()); - assertNull(bm.readObject()); - } - - public static junit.framework.Test suite() - { - return new junit.framework.TestSuite(StreamMessageTest.class); - } -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/message/TextMessageTest.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/message/TextMessageTest.java deleted file mode 100644 index 78c018840c..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/message/TextMessageTest.java +++ /dev/null @@ -1,300 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.unit.client.message; - -import org.junit.Assert; -import junit.framework.TestCase; - -import org.apache.qpid.client.message.JMSMapMessage; -import org.apache.qpid.client.message.JMSTextMessage; -import org.apache.qpid.client.message.TestMessageHelper; - -import javax.jms.JMSException; - -public class TextMessageTest extends TestCase -{ - public void testTextOnConstruction() throws Exception - { - JMSTextMessage tm = TestMessageHelper.newJMSTextMessage(); - tm.setText("pies"); - String val = tm.getText(); - assertEquals(val, "pies"); - } - - public void testClearBody() throws Exception - { - JMSTextMessage tm = TestMessageHelper.newJMSTextMessage(); - tm.setText("pies"); - tm.clearBody(); - String val = tm.getText(); - assertNull(val); - tm.setText("Banana"); - val = tm.getText(); - assertEquals(val, "Banana"); - } - - - public void testBooleanPropertyLookup() - { - try - { - JMSTextMessage tm = TestMessageHelper.newJMSTextMessage(); - - tm.setBooleanProperty("value", true); - Assert.assertEquals(true, tm.getBooleanProperty("value")); - Assert.assertEquals("true", tm.getStringProperty("value")); - } - catch (JMSException e) - { - Assert.fail("JMSException received." + e); - } - } - - public void testBytePropertyLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - mm.setByteProperty("value", Byte.MAX_VALUE); - - Assert.assertEquals(Byte.MAX_VALUE, mm.getByteProperty("value")); - Assert.assertEquals((short) Byte.MAX_VALUE, mm.getShortProperty("value")); - Assert.assertEquals(Byte.MAX_VALUE, mm.getIntProperty("value")); - Assert.assertEquals((long) Byte.MAX_VALUE, mm.getLongProperty("value")); - Assert.assertEquals("" + Byte.MAX_VALUE, mm.getStringProperty("value")); - - } - catch (JMSException e) - { - Assert.fail("JMSException received." + e); - } - } - - public void testShortPropertyLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - mm.setShortProperty("value", Short.MAX_VALUE); - Assert.assertEquals(Short.MAX_VALUE, mm.getShortProperty("value")); - Assert.assertEquals((int) Short.MAX_VALUE, mm.getIntProperty("value")); - Assert.assertEquals((long) Short.MAX_VALUE, mm.getLongProperty("value")); - Assert.assertEquals("" + Short.MAX_VALUE, mm.getStringProperty("value")); - } - catch (JMSException e) - { - Assert.fail("JMSException received." + e); - } - } - - public void testDoublePropertyLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - mm.setDoubleProperty("value", Double.MAX_VALUE); - Assert.assertEquals(Double.MAX_VALUE, mm.getDoubleProperty("value"), 0d); - Assert.assertEquals("" + Double.MAX_VALUE, mm.getStringProperty("value")); - } - catch (JMSException e) - { - Assert.fail("JMSException received." + e); - } - } - - public void testFloatPropertyLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - mm.setFloatProperty("value", Float.MAX_VALUE); - Assert.assertEquals(Float.MAX_VALUE, mm.getFloatProperty("value"), 0f); - Assert.assertEquals(Double.valueOf(Float.MAX_VALUE), mm.getDoubleProperty("value"), 0d); - Assert.assertEquals("" + Float.MAX_VALUE, mm.getStringProperty("value")); - } - catch (JMSException e) - { - Assert.fail("JMSException received." + e); - } - } - - public void testIntPropertyLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - mm.setIntProperty("value", Integer.MAX_VALUE); - Assert.assertEquals(Integer.MAX_VALUE, mm.getIntProperty("value")); - Assert.assertEquals((long) Integer.MAX_VALUE, mm.getLongProperty("value")); - Assert.assertEquals("" + Integer.MAX_VALUE, mm.getStringProperty("value")); - } - catch (JMSException e) - { - Assert.fail("JMSException received." + e); - } - } - - public void testLongPropertyLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - mm.setLongProperty("value", Long.MAX_VALUE); - Assert.assertEquals(Long.MAX_VALUE, mm.getLongProperty("value")); - Assert.assertEquals("" + Long.MAX_VALUE, mm.getStringProperty("value")); - } - catch (JMSException e) - { - Assert.fail("JMSException received." + e); - } - } - - - // Failed Lookups - - public void testFailedBooleanPropertyLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - Assert.assertEquals(false, mm.getBooleanProperty("int")); - } - catch (JMSException e) - { - Assert.fail("JMSException received." + e); - } - } - - public void testFailedBytePropertyLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - mm.getByteProperty("random"); - Assert.fail("NumberFormatException expected"); - } - catch (NumberFormatException e) - { - //normal execution - } - catch (JMSException e) - { - Assert.fail("JMSException received:" + e); - } - - } - - public void testFailedDoublePropertyLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - mm.getDoubleProperty("random"); - Assert.fail("NullPointerException should be received."); - } - catch (NullPointerException e) - { - //normal execution - } - catch (JMSException e) - { - Assert.fail("JMSException received:" + e); - } - } - - public void testFailedFloatPropertyLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - mm.getFloatProperty("random"); - Assert.fail("NullPointerException should be received."); - } - catch (NullPointerException e) - { - //normal execution - } - catch (JMSException e) - { - Assert.fail("JMSException received:" + e); - } - } - - public void testFailedIntPropertyLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - mm.getIntProperty("random"); - Assert.fail("NumberFormatException should be received."); - } - catch (NumberFormatException e) - { - //normal execution - } - catch (JMSException e) - { - Assert.fail("JMSException received:" + e); - } - } - - public void testFailedLongPropertyLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - mm.getLongProperty("random"); - Assert.fail("NumberFormatException should be received."); - } - catch (NumberFormatException e) - { - //normal execution - } - catch (JMSException e) - { - Assert.fail("JMSException received:" + e); - } - } - - public void testFailedShortPropertyLookup() - { - try - { - JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); - mm.getShortProperty("random"); - Assert.fail("NumberFormatException should be received."); - } - catch (NumberFormatException e) - { - //normal execution - } - catch (JMSException e) - { - Assert.fail("JMSException received:" + e); - } - } - - - public static junit.framework.Test suite() - { - return new junit.framework.TestSuite(TextMessageTest.class); - } -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/message/MessageConverterTest.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/message/MessageConverterTest.java deleted file mode 100644 index 4607755767..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/message/MessageConverterTest.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.unit.message; - -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.MapMessage; -import javax.jms.Message; -import javax.jms.TextMessage; - -import junit.framework.TestCase; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.client.AMQConnection; -import org.apache.qpid.client.AMQQueue; -import org.apache.qpid.client.AMQSession; -import org.apache.qpid.client.MockAMQConnection; -import org.apache.qpid.client.message.AMQMessageDelegateFactory; -import org.apache.qpid.client.message.AbstractJMSMessage; -import org.apache.qpid.client.message.JMSMapMessage; -import org.apache.qpid.client.message.JMSTextMessage; -import org.apache.qpid.client.message.MessageConverter; -import org.apache.qpid.exchange.ExchangeDefaults; - - -public class MessageConverterTest extends TestCase -{ - private static final Logger _logger = LoggerFactory.getLogger(MessageConverterTest.class); - public static final String JMS_CORR_ID = "QPIDID_01"; - public static final int JMS_DELIV_MODE = 1; - public static final String JMS_TYPE = "test.jms.type"; - public static final Destination JMS_REPLY_TO = new AMQQueue(ExchangeDefaults.DIRECT_EXCHANGE_NAME,"my.replyto"); - - protected JMSTextMessage testTextMessage; - - protected JMSMapMessage testMapMessage; - private AMQConnection _connection; - private AMQSession _session; - - - protected void setUp() throws Exception - { - super.setUp(); - - _connection = new MockAMQConnection("amqp://guest:guest@client/test?brokerlist='tcp://localhost:1'"); - _session = new TestAMQSession(_connection); - - testTextMessage = new JMSTextMessage(AMQMessageDelegateFactory.FACTORY_0_8); - - //Set Message Text - testTextMessage.setText("testTextMessage text"); - setMessageProperties(testTextMessage); - - testMapMessage = new JMSMapMessage(AMQMessageDelegateFactory.FACTORY_0_8); - testMapMessage.setString("testMapString", "testMapStringValue"); - testMapMessage.setDouble("testMapDouble", Double.MAX_VALUE); - } - - public void testSetProperties() throws Exception - { - AbstractJMSMessage newMessage = new MessageConverter(_session, (TextMessage) testTextMessage).getConvertedMessage(); - mesagePropertiesTest(testTextMessage, newMessage); - } - - public void testJMSTextMessageConversion() throws Exception - { - AbstractJMSMessage newMessage = new MessageConverter(_session, (TextMessage) testTextMessage).getConvertedMessage(); - assertEquals("Converted message text mismatch", ((JMSTextMessage) newMessage).getText(), testTextMessage.getText()); - } - - public void testJMSMapMessageConversion() throws Exception - { - AbstractJMSMessage newMessage = new MessageConverter(_session, (MapMessage) testMapMessage).getConvertedMessage(); - assertEquals("Converted map message String mismatch", ((JMSMapMessage) newMessage).getString("testMapString"), - testMapMessage.getString("testMapString")); - assertEquals("Converted map message Double mismatch", ((JMSMapMessage) newMessage).getDouble("testMapDouble"), - testMapMessage.getDouble("testMapDouble")); - - } - - public void testMessageConversion() throws Exception - { - Message newMessage = new NonQpidMessage(); - setMessageProperties(newMessage); - mesagePropertiesTest(testTextMessage, newMessage); - } - - private void setMessageProperties(Message message) throws JMSException - { - message.setJMSCorrelationID(JMS_CORR_ID); - message.setJMSDeliveryMode(JMS_DELIV_MODE); - message.setJMSType(JMS_TYPE); - message.setJMSReplyTo(JMS_REPLY_TO); - - //Add non-JMS properties - message.setStringProperty("testProp1", "testValue1"); - message.setDoubleProperty("testProp2", Double.MIN_VALUE); - } - - - private void mesagePropertiesTest(Message expectedMessage, Message actualMessage) - { - try - { - //check JMS prop values on newMessage match - assertEquals("JMS Correlation ID mismatch", expectedMessage.getJMSCorrelationID(), actualMessage.getJMSCorrelationID()); - assertEquals("JMS Delivery mode mismatch", expectedMessage.getJMSDeliveryMode(), actualMessage.getJMSDeliveryMode()); - assertEquals("JMS Type mismatch", expectedMessage.getJMSType(), actualMessage.getJMSType()); - assertEquals("JMS Reply To mismatch", expectedMessage.getJMSReplyTo(), actualMessage.getJMSReplyTo()); - - //check non-JMS standard props ok too - assertEquals("Test String prop value mismatch", expectedMessage.getStringProperty("testProp1"), - actualMessage.getStringProperty("testProp1")); - - assertEquals("Test Double prop value mismatch", expectedMessage.getDoubleProperty("testProp2"), - actualMessage.getDoubleProperty("testProp2")); - } - catch (JMSException e) - { - _logger.error("An error occured testing the property values", e); - fail("An error occured testing the property values" + e.getCause()); - } - } - - protected void tearDown() throws Exception - { - super.tearDown(); - testTextMessage = null; - } - - -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/message/NonQpidMessage.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/message/NonQpidMessage.java deleted file mode 100644 index d93ba23a25..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/message/NonQpidMessage.java +++ /dev/null @@ -1,419 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.unit.message; - -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageFormatException; -import java.util.Enumeration; -import java.util.Hashtable; - -public class NonQpidMessage implements Message -{ - private String _JMSMessageID; - private long _JMSTimestamp; - private byte[] _JMSCorrelationIDAsBytes; - private String _JMSCorrelationID; - private Destination _JMSReplyTo; - private Destination _JMSDestination; - private int _JMSDeliveryMode; - private boolean _JMSRedelivered; - private String _JMSType; - private long _JMSExpiration; - private int _JMSPriority; - private Hashtable _properties; - - public NonQpidMessage() - { - _properties = new Hashtable(); - _JMSPriority = javax.jms.Message.DEFAULT_PRIORITY; - _JMSDeliveryMode = javax.jms.Message.DEFAULT_DELIVERY_MODE; - } - - public String getJMSMessageID() throws JMSException - { - return _JMSMessageID; - } - - public void setJMSMessageID(String string) throws JMSException - { - _JMSMessageID = string; - } - - public long getJMSTimestamp() throws JMSException - { - return _JMSTimestamp; - } - - public void setJMSTimestamp(long l) throws JMSException - { - _JMSTimestamp = l; - } - - public byte[] getJMSCorrelationIDAsBytes() throws JMSException - { - return _JMSCorrelationIDAsBytes; - } - - public void setJMSCorrelationIDAsBytes(byte[] bytes) throws JMSException - { - _JMSCorrelationIDAsBytes = bytes; - } - - public void setJMSCorrelationID(String string) throws JMSException - { - _JMSCorrelationID = string; - } - - public String getJMSCorrelationID() throws JMSException - { - return _JMSCorrelationID; - } - - public Destination getJMSReplyTo() throws JMSException - { - return _JMSReplyTo; - } - - public void setJMSReplyTo(Destination destination) throws JMSException - { - _JMSReplyTo = destination; - } - - public Destination getJMSDestination() throws JMSException - { - return _JMSDestination; - } - - public void setJMSDestination(Destination destination) throws JMSException - { - _JMSDestination = destination; - } - - public int getJMSDeliveryMode() throws JMSException - { - return _JMSDeliveryMode; - } - - public void setJMSDeliveryMode(int i) throws JMSException - { - _JMSDeliveryMode = i; - } - - public boolean getJMSRedelivered() throws JMSException - { - return _JMSRedelivered; - } - - public void setJMSRedelivered(boolean b) throws JMSException - { - _JMSRedelivered = b; - } - - public String getJMSType() throws JMSException - { - return _JMSType; - } - - public void setJMSType(String string) throws JMSException - { - _JMSType = string; - } - - public long getJMSExpiration() throws JMSException - { - return _JMSExpiration; - } - - public void setJMSExpiration(long l) throws JMSException - { - _JMSExpiration = l; - } - - public int getJMSPriority() throws JMSException - { - return _JMSPriority; - } - - public void setJMSPriority(int i) throws JMSException - { - _JMSPriority = i; - } - - public void clearProperties() throws JMSException - { - _properties.clear(); - } - - public boolean propertyExists(String string) throws JMSException - { - return _properties.containsKey(string); - } - - public boolean getBooleanProperty(String string) throws JMSException - { - if (propertyExists(string)) - { - Object o = _properties.get(string); - if (o instanceof Boolean) - { - return (Boolean) o; - } - else - { - return Boolean.valueOf(null); - } - } - else - { - throw new JMSException("property does not exist: " + string); - } - } - - public byte getByteProperty(String string) throws JMSException - { - if (propertyExists(string)) - { - Object o = _properties.get(string); - if (o instanceof Byte) - { - return (Byte) o; - } - else - { - return Byte.valueOf(null); - } - } - else - { - throw new JMSException("property does not exist: " + string); - } - } - - public short getShortProperty(String string) throws JMSException - { - if (propertyExists(string)) - { - Object o = _properties.get(string); - if (o instanceof Short) - { - return (Short) o; - } - else - { - return Short.valueOf(null); - } - } - else - { - throw new JMSException("property does not exist: " + string); - } - } - - public int getIntProperty(String string) throws JMSException - { - if (propertyExists(string)) - { - Object o = _properties.get(string); - if (o instanceof Integer) - { - return (Integer) o; - } - else - { - return Integer.valueOf(null); - } - } - else - { - throw new JMSException("property does not exist: " + string); - } - } - - public long getLongProperty(String string) throws JMSException - { - if (propertyExists(string)) - { - Object o = _properties.get(string); - if (o instanceof Long) - { - return (Long) o; - } - else - { - return Long.valueOf(null); - } - } - else - { - throw new JMSException("property does not exist: " + string); - } - } - - public float getFloatProperty(String string) throws JMSException - { - if (propertyExists(string)) - { - Object o = _properties.get(string); - if (o instanceof Float) - { - return (Float) o; - } - else if(o instanceof String) - { - return Float.valueOf((String)o); - } - else if(o == null) - { - throw new NullPointerException("No such property: " + string); - } - else - { - throw new MessageFormatException("getFloatProperty(\""+string+"\") failed as value is not a float: " + o); - } - } - else - { - throw new JMSException("property does not exist: " + string); - } - } - - public double getDoubleProperty(String string) throws JMSException - { - if (propertyExists(string)) - { - Object o = _properties.get(string); - if (o instanceof Double) - { - return (Double) o; - } - else - { - return getFloatProperty(string); - } - } - else - { - throw new JMSException("property does not exist: " + string); - } - } - - public String getStringProperty(String string) throws JMSException - { - if (propertyExists(string)) - { - Object o = _properties.get(string); - if (o instanceof String) - { - return (String) o; - } - else - { - return null; - } - } - else - { - throw new JMSException("property does not exist: " + string); - } - } - - public Object getObjectProperty(String string) throws JMSException - { - if (propertyExists(string)) - { - Object o = _properties.get(string); - if (o instanceof Boolean) - { - return (Boolean) o; - } - else - { - return Boolean.valueOf(null); - } - } - else - { - throw new JMSException("property does not exist: " + string); - } - } - - public Enumeration getPropertyNames() throws JMSException - { - return _properties.keys(); - } - - public void setBooleanProperty(String string, boolean b) throws JMSException - { - _properties.put(string, b); - } - - public void setByteProperty(String string, byte b) throws JMSException - { - _properties.put(string, b); - } - - public void setShortProperty(String string, short i) throws JMSException - { - _properties.put(string, i); - } - - public void setIntProperty(String string, int i) throws JMSException - { - _properties.put(string, i); - } - - public void setLongProperty(String string, long l) throws JMSException - { - _properties.put(string, l); - } - - public void setFloatProperty(String string, float v) throws JMSException - { - _properties.put(string, v); - } - - public void setDoubleProperty(String string, double v) throws JMSException - { - _properties.put(string, v); - } - - public void setStringProperty(String string, String string1) throws JMSException - { - _properties.put(string, string1); - } - - public void setObjectProperty(String string, Object object) throws JMSException - { - _properties.put(string, object); - } - - public void acknowledge() throws JMSException - { - - } - - public void clearBody() throws JMSException - { - - } -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/message/TestAMQSession.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/message/TestAMQSession.java deleted file mode 100644 index 4ad9069ba0..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/message/TestAMQSession.java +++ /dev/null @@ -1,208 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.unit.message; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.AMQConnection; -import org.apache.qpid.client.AMQDestination; -import org.apache.qpid.client.AMQSession_0_8; -import org.apache.qpid.client.BasicMessageConsumer_0_8; -import org.apache.qpid.client.BasicMessageProducer_0_8; -import org.apache.qpid.client.failover.FailoverException; -import org.apache.qpid.client.message.AMQMessageDelegateFactory; -import org.apache.qpid.client.protocol.AMQProtocolHandler; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.FieldTable; - -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.TemporaryQueue; -import javax.jms.Topic; -import javax.jms.TopicSubscriber; -import java.util.Map; - -public class TestAMQSession extends AMQSession_0_8 -{ - - public TestAMQSession(AMQConnection connection) - { - super(connection, 0, false, AUTO_ACKNOWLEDGE, null, 0, 0); - } - - public void acknowledgeMessage(long deliveryTag, boolean multiple) - { - - } - - public void sendQueueBind(AMQShortString queueName, AMQShortString routingKey, FieldTable arguments, - AMQShortString exchangeName, AMQDestination destination, - boolean nowait) throws AMQException, FailoverException - { - - } - - public void sendClose(long timeout) throws AMQException, FailoverException - { - - } - - public void commitImpl() throws AMQException, FailoverException - { - - } - - public void acknowledgeImpl() - { - - } - - public TopicSubscriber createDurableSubscriber(Topic topic, String name) throws JMSException - { - return null; - } - - public void sendCreateQueue(AMQShortString name, boolean autoDelete, boolean durable, boolean exclusive, Map<String, Object> arguments) throws AMQException, FailoverException - { - - } - - public TemporaryQueue createTemporaryQueue() throws JMSException - { - return null; - } - - public void sendRecover() throws AMQException, FailoverException - { - - } - - public void rejectMessage(long deliveryTag, boolean requeue) - { - - } - - public void releaseForRollback() - { - - } - - public void sendRollback() throws AMQException, FailoverException - { - - } - - public BasicMessageConsumer_0_8 createMessageConsumer(AMQDestination destination, int prefetchHigh, int prefetchLow, boolean noLocal, boolean exclusive, String selector, FieldTable arguments, boolean noConsume, boolean autoClose) throws JMSException - { - return null; - } - - public boolean isQueueBound(AMQShortString exchangeName, AMQShortString queueName, AMQShortString routingKey) throws JMSException - { - return false; - } - - public boolean isQueueBound(AMQDestination destination) throws JMSException - { - return false; - } - - public void sendConsume(BasicMessageConsumer_0_8 consumer, AMQShortString queueName, boolean nowait, int tag) throws AMQException, FailoverException - { - - } - - public BasicMessageProducer_0_8 createMessageProducer(Destination destination, boolean mandatory, boolean immediate, long producerId) - { - return null; - } - - protected Long requestQueueDepth(AMQDestination amqd) throws AMQException, FailoverException - { - return null; - } - - public void sendExchangeDeclare(AMQShortString name, AMQShortString type, boolean nowait, boolean durable, boolean autoDelete, boolean internal) throws AMQException, FailoverException - { - - } - - public void sendQueueDeclare(AMQDestination amqd, AMQProtocolHandler protocolHandler, - boolean passive) throws AMQException, FailoverException - { - - } - - public void sendQueueDelete(AMQShortString queueName) throws AMQException, FailoverException - { - - } - - public void sendSuspendChannel(boolean suspend) throws AMQException, FailoverException - { - - } - - protected boolean tagLE(long tag1, long tag2) - { - return false; - } - - protected boolean updateRollbackMark(long current, long deliveryTag) - { - return false; - } - - public AMQMessageDelegateFactory getMessageDelegateFactory() - { - return AMQMessageDelegateFactory.FACTORY_0_8; - } - - protected Object getFailoverMutex() - { - return this; - } - - public void checkNotClosed() - { - - } - - public void sync() - { - } - - @Override - protected void flushAcknowledgments() - { - } - - public boolean isQueueBound(String exchangeName, String queueName, - String bindingKey, Map<String, Object> args) throws JMSException - { - return false; - } - - @Override - public AMQException getLastException() - { - return null; - } -} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/tests.properties b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/tests.properties deleted file mode 100644 index 2fd961a078..0000000000 --- a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/tests.properties +++ /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. - - -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://username:password@clientid/test?brokerlist='tcp://localhost:5672' -#qpid:password=guest;username=guest;client_id=clientid;virtualhost=test@tcp:127.0.0.1:5672 - - -# register some queues in JNDI using the form -# queue.[jndiName] = [physicalName] -queue.MyQueue = example.MyQueue -queue.queue = example.queue -queue.xaQueue = xaQueue - -# register some topics in JNDI using the form -# topic.[jndiName] = [physicalName] -#topic.ibmStocks = stocks.nyse.ibm -topic.xaTopic = xaTopic -topic.durableSubscriberTopic = durableSubscriberTopic - -# Register an AMQP destination in JNDI -# NOTE: Qpid currently only supports direct,topics and headers -# destination.[jniName] = [BindingURL] -#destination.direct = direct://amq.direct//directQueue |
